<commit_before>/**
 * Constructor for an analogue of the TimeRanges class
 * returned by various HTMLMediaElement properties
 *
 * Pass an array of two-element arrays, each containing a start and end time.
 */
function OgvSwfTimeRanges(ranges) {
	// note: can't use Object.defineProperty on non-DOM objects in IE 8
	this.length = ranges.length;
	this.start = function(i) {
		return ranges[i][0];
	};
	this.end = function(i) {
		return ranges[i][1];
	}
	return this;
}

function OgvSwfPlayer(options) {
	var options = options || {};
	var useGPU = !!options.useGPU;

	// Return a magical custom element!
	var self = document.createElement('ogvswf');
	self.style.display = 'inline-block';
	self.style.position = 'relative';

	var idkey = OgvSwfPlayer.nextId++,
		callbackName = 'ogvSwfFlashCallback' + idkey,
		validCallbacks = [
			'onframecallback',
			'onplay',
			'onpause',
			'onended',
			'ontrace',
			'onloadedmetadata'
		];
	self.ontrace = function(str) {
		console.log('Flash: ' + str);
	};

	// Register a global function for callbacks. :P
	window[callbackName] = function ogvSwfFlashCallback(eventName, args) {
		// Array.indexOf doesn't exist in IE until 9!
		var legit = false;
		for (var i = 0; i < validCallbacks.length; i++) {
			if (eventName === validCallbacks[i]) {
				legit = true;
				break;
			}
		}
		if (legit && self[eventName]) {
			self[eventName](args);
		}
	};

	function param(name, value) {
		var el = document.createElement('param');
		el.name = name;
		el.value = value;
		return el;
	}

	var swfUrl = 'lib/ogv.swf?buildDate=' + encodeURIComponent(OgvSwfPlayer.buildDate);

	var flash = document.createElement('object');
	flash.id = 'ogvswf-flashelement-' + idkey;
	flash.width = 320;
	flash.height = 240;
	flash.appendChild(param('allowscriptaccess', 'always'));
	if (useGPU) {
		flash.appendChild(param('flashVars', 'jsCallbackName=' + callbackName + '&useGPU=1'));
		flash.appendChild(param('wmode', 'direct'));
	} else {
		flash.appendChild(param('flashVars', 'jsCallbackName=' + callbackName));
		flash.appendChild(param('wmode', 'opaque'));
	}
	// For IE <= 9:
	if (typeof flash.classid == 'string') {
		flash.appendChild(param('movie', swfUrl));
		// Must set all the parameters before setting classid...
		flash.classid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000';
	} else {
		// And for everybody else:
		flash.type = 'application/x-shockwave-flash';
	}
	flash.data = swfUrl;

	self.appendChild(flash);

	var waitingCallbacks = [],
		waitingTimer = null,
		times = 0,
		maxTimes = 100;
	function pingFlashPlugin() {
		waitingTimer = setTimeout(function doPingFlashPlugin() {
			waitingTimer = null;
			times++;
			if (flash._isReady) {
				for (var i = 0; i < waitingCallbacks.length; i++) {
					waitingCallbacks[i]();
				}
				waitingCallbacks = [];
			} else if (times > maxTimes) {
				console.log("Failed to initialize Flash Ogv video player");
			} else {
				console.log('try again...');
				pingFlashPlugin();
			}
		}, 20);
	}
	function waitForFlash(callback) {
		if (flash._isReady) {
			callback();
		} else if (waitingTimer == null) {
			waitingCallbacks.push(callback);
			pingFlashPlugin();
		} else {
			// already waiting
			waitingCallbacks.push(callback);
		}
	}

	/**
	 * @todo can we force this to call automatically on removal?
	 */
	self.destroy = function() {
		window[callbackName] = undefined;
	};

	/**
	 * HTMLMediaElement load method
	 */
	self.load = function() {
		waitForFlash(function() {
			flash._load();
		});
	};

	/**
	 * HTMLMediaElement canPlayType method
	 */
	self.canPlayType = function(type) {
		// @todo: implement better parsing
		if (type === 'audio/ogg; codecs="vorbis"') {
			return 'probably';
		} else if (type.match(/^audio\/ogg\b/)) {
			return 'maybe';
		} else if (type === 'video/ogg; codecs="theora"') {
			return 'probably';
		} else if (type === 'video/ogg; codecs="theora,vorbis"') {
			return 'probably';
		} else if (type.match(/^video\/ogg\b/)) {
			return 'maybe';
		} else {
			return '';
		}
	};

	/**
	 * HTMLMediaElement play method
	 */
	self.play = function() {
		waitForFlash(function() {
			flash._play();
		});
	};

	/**
	 * custom getPlaybackStats method
	 */
	self.getPlaybackStats = function() {
		if (flash._isReady) {
			return flash._getPlaybackStats();
		} else {
			return {
				framesProcessed: 0,
				demuxingTime: 0,
				videoDecodingTime: 0,
				audioDecodingTime: 0,
				bufferTime: 0,
				colorTime: 0,
				drawingTime: 0,
				droppedAudio: 0,
				jitter: 0
			};
		}
	};
	self.resetPlaybackStats = function() {
		waitForFlash(function() {
			flash._resetPlaybackStats();
		});
	};

	/**
	 * HTMLMediaElement pause method
	 */
	self.pause = function() {
		waitForFlash(function() {
			flash._pause();
		});
	};

	/**
	 * HTMLMediaElement src property
	 */
	var src = "";
	Object.defineProperty(self, "src", {
		get: function getSrc() {
			return src;
		},
		set: function setSrc(val) {
			src = val;
			waitForFlash(function() {
				flash._setSrc(val);
			});
		}
	});

	/**
	 */
	Object.defineProperty(self, "buffered", {
		get: function getBuffered() {
			var bufferedTime;
			if (flash._isReady) {
				bufferedTime = flash._getBufferedTime();
			} else {
				bufferedTime = 0;
			}
			return new OgvSwfTimeRanges([[0, bufferedTime]]);
		}
	});

	/**
	 * HTMLMediaElement currentTime property
	 */
	Object.defineProperty(self, "currentTime", {
		get: function getCurrentTime() {
			if (flash._isReady) {
				return flash._getCurrentTime();
			} else {
				return 0;
			}
		}
	});

	/**
	 * custom durationHint property
	 */
	var durationHint = null;
	Object.defineProperty(self, "durationHint", {
		get: function getDurationHint() {
			return durationHint;
		},
		set: function setDurationHint(val) {
			durationHint = val;
			waitForFlash(function() {
				flash._setDurationHint(durationHint);
			});
		}
	});

	/**
	 * HTMLMediaElement duration property
	 */
	Object.defineProperty(self, "duration", {
		get: function getDuration() {
			if (flash._isReady) {
				return flash._getDuration();
			} else {
				return 0;
			}
		}
	});

	/**
	 * HTMLMediaElement paused property
	 */
	Object.defineProperty(self, "paused", {
		get: function getPaused() {
			if (flash._isReady) {
				return flash._getPaused();
			} else {
				return true;
			}
		}
	});

	/**
	 * HTMLMediaElement ended property
	 */
	Object.defineProperty(self, "ended", {
		get: function getEnded() {
			if (flash._isReady) {
				return flash._getEnded();
			} else {
				return false;
			}
		}
	});

	/**
	 * HTMLMediaElement muted property
	 */
	var muted;
	Object.defineProperty(self, "muted", {
		get: function getMuted() {
			return muted;
		},
		set: function setMuted(val) {
			muted = val;
			waitForFlash(function() {
				flash._setMuted(val);
			});
		}
	});

	/**
	 * HTMLVideoElement poster property
	 */
	var poster;
	Object.defineProperty(self, "poster", {
		get: function getPoster() {
			return poster;
		},
		set: function setPoster(val) {
			waitForFlash(function() {
				flash._setPoster(val);
			});
		}
	});

	// Video metadata properties...
	Object.defineProperty(self, "videoWidth", {
		get: function getVideoWidth() {
			if (flash._isReady) {
				return flash._getVideoWidth();
			} else {
				return 0;
			}
		}
	});
	Object.defineProperty(self, "videoHeight", {
		get: function getVideoHeight() {
			if (flash._isReady) {
				return flash._getVideoHeight();
			} else {
				return 0;
			}
		}
	});
	Object.defineProperty(self, "ogvjsVideoFrameRate", {
		get: function getOgvJsVideoFrameRate() {
			if (flash._isReady) {
				return flash._getFrameRate();
			} else {
				return 0;
			}
		}
	});

	// Audio metadata properties...
	Object.defineProperty(self, "ogvjsAudioChannels", {
		get: function getOgvJsAudioChannels() {
			if (flash._isReady) {
				return flash._getAudioChannels();
			} else {
				return 0;
			}
		}
	});
	Object.defineProperty(self, "ogvjsAudioSampleRate", {
		get: function getOgvJsAudioChannels() {
			if (flash._isReady) {
				return flash._getAudioSampleRate();
			} else {
				return 0;
			}
		}
	});

	// Display size...
	var width = 0, height = 0;
	Object.defineProperty(self, "width", {
		get: function getWidth() {
			return width;
		},
		set: function setWidth(val) {
			width = parseInt(val, 10);
			flash.width = width;
		}
	});

	Object.defineProperty(self, "height", {
		get: function getHeight() {
			return height;
		},
		set: function setHeight(val) {
			height = parseInt(val, 10);
			flash.height = height;
		}
	});

	// Events!

	/**
	 * custom onframecallback, takes frame decode time in ms
	 */
	self.onframecallback = null;

	/**
	 * Called when all metadata is available.
	 * Note in theory we must know 'duration' at this point.
	 */
	self.onloadedmetadata = null;

	/**
	 * Called when we start playback
	 */
	self.onplay = null;

	/**
	 * Called when we get paused
	 */
	self.onpause = null;

	/**
	 * Called when playback ends
	 */
	self.onended = null;

	return self;
}

OgvSwfPlayer.nextId = 1;
<commit_msg>Autosize flash player when video loads<commit_after>/**
 * Constructor for an analogue of the TimeRanges class
 * returned by various HTMLMediaElement properties
 *
 * Pass an array of two-element arrays, each containing a start and end time.
 */
function OgvSwfTimeRanges(ranges) {
	// note: can't use Object.defineProperty on non-DOM objects in IE 8
	this.length = ranges.length;
	this.start = function(i) {
		return ranges[i][0];
	};
	this.end = function(i) {
		return ranges[i][1];
	}
	return this;
}

function OgvSwfPlayer(options) {
	var options = options || {};
	var useGPU = !!options.useGPU;

	// Return a magical custom element!
	var self = document.createElement('ogvswf');
	self.style.display = 'inline-block';
	self.style.position = 'relative';

	var idkey = OgvSwfPlayer.nextId++,
		callbackName = 'ogvSwfFlashCallback' + idkey,
		validCallbacks = [
			'onframecallback',
			'onplay',
			'onpause',
			'onended',
			'ontrace',
			'onloadedmetadata'
		];
	self.ontrace = function(str) {
		console.log('Flash: ' + str);
	};

	// Register a global function for callbacks. :P
	window[callbackName] = function ogvSwfFlashCallback(eventName, args) {
		// Array.indexOf doesn't exist in IE until 9!
		var legit = false;
		for (var i = 0; i < validCallbacks.length; i++) {
			if (eventName === validCallbacks[i]) {
				legit = true;
				break;
			}
		}
		if (eventName === 'onloadedmetadata') {
			if (width == 0) {
				flash.width = self.videoWidth;
			}
			if (height == 0) {
				flash.height = self.videoHeight;
			}
		}
		if (legit && self[eventName]) {
			self[eventName](args);
		}
	};

	function param(name, value) {
		var el = document.createElement('param');
		el.name = name;
		el.value = value;
		return el;
	}

	var swfUrl = 'lib/ogv.swf?buildDate=' + encodeURIComponent(OgvSwfPlayer.buildDate);

	var flash = document.createElement('object');
	flash.id = 'ogvswf-flashelement-' + idkey;
	flash.width = 320;
	flash.height = 240;
	flash.appendChild(param('allowscriptaccess', 'always'));
	if (useGPU) {
		flash.appendChild(param('flashVars', 'jsCallbackName=' + callbackName + '&useGPU=1'));
		flash.appendChild(param('wmode', 'direct'));
	} else {
		flash.appendChild(param('flashVars', 'jsCallbackName=' + callbackName));
		flash.appendChild(param('wmode', 'opaque'));
	}
	// For IE <= 9:
	if (typeof flash.classid == 'string') {
		flash.appendChild(param('movie', swfUrl));
		// Must set all the parameters before setting classid...
		flash.classid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000';
	} else {
		// And for everybody else:
		flash.type = 'application/x-shockwave-flash';
	}
	flash.data = swfUrl;

	self.appendChild(flash);

	var waitingCallbacks = [],
		waitingTimer = null,
		times = 0,
		maxTimes = 100;
	function pingFlashPlugin() {
		waitingTimer = setTimeout(function doPingFlashPlugin() {
			waitingTimer = null;
			times++;
			if (flash._isReady) {
				for (var i = 0; i < waitingCallbacks.length; i++) {
					waitingCallbacks[i]();
				}
				waitingCallbacks = [];
			} else if (times > maxTimes) {
				console.log("Failed to initialize Flash Ogv video player");
			} else {
				console.log('try again...');
				pingFlashPlugin();
			}
		}, 20);
	}
	function waitForFlash(callback) {
		if (flash._isReady) {
			callback();
		} else if (waitingTimer == null) {
			waitingCallbacks.push(callback);
			pingFlashPlugin();
		} else {
			// already waiting
			waitingCallbacks.push(callback);
		}
	}

	/**
	 * @todo can we force this to call automatically on removal?
	 */
	self.destroy = function() {
		window[callbackName] = undefined;
	};

	/**
	 * HTMLMediaElement load method
	 */
	self.load = function() {
		waitForFlash(function() {
			flash._load();
		});
	};

	/**
	 * HTMLMediaElement canPlayType method
	 */
	self.canPlayType = function(type) {
		// @todo: implement better parsing
		if (type === 'audio/ogg; codecs="vorbis"') {
			return 'probably';
		} else if (type.match(/^audio\/ogg\b/)) {
			return 'maybe';
		} else if (type === 'video/ogg; codecs="theora"') {
			return 'probably';
		} else if (type === 'video/ogg; codecs="theora,vorbis"') {
			return 'probably';
		} else if (type.match(/^video\/ogg\b/)) {
			return 'maybe';
		} else {
			return '';
		}
	};

	/**
	 * HTMLMediaElement play method
	 */
	self.play = function() {
		waitForFlash(function() {
			flash._play();
		});
	};

	/**
	 * custom getPlaybackStats method
	 */
	self.getPlaybackStats = function() {
		if (flash._isReady) {
			return flash._getPlaybackStats();
		} else {
			return {
				framesProcessed: 0,
				demuxingTime: 0,
				videoDecodingTime: 0,
				audioDecodingTime: 0,
				bufferTime: 0,
				colorTime: 0,
				drawingTime: 0,
				droppedAudio: 0,
				jitter: 0
			};
		}
	};
	self.resetPlaybackStats = function() {
		waitForFlash(function() {
			flash._resetPlaybackStats();
		});
	};

	/**
	 * HTMLMediaElement pause method
	 */
	self.pause = function() {
		waitForFlash(function() {
			flash._pause();
		});
	};

	/**
	 * HTMLMediaElement src property
	 */
	var src = "";
	Object.defineProperty(self, "src", {
		get: function getSrc() {
			return src;
		},
		set: function setSrc(val) {
			src = val;
			waitForFlash(function() {
				flash._setSrc(val);
			});
		}
	});

	/**
	 */
	Object.defineProperty(self, "buffered", {
		get: function getBuffered() {
			var bufferedTime;
			if (flash._isReady) {
				bufferedTime = flash._getBufferedTime();
			} else {
				bufferedTime = 0;
			}
			return new OgvSwfTimeRanges([[0, bufferedTime]]);
		}
	});

	/**
	 * HTMLMediaElement currentTime property
	 */
	Object.defineProperty(self, "currentTime", {
		get: function getCurrentTime() {
			if (flash._isReady) {
				return flash._getCurrentTime();
			} else {
				return 0;
			}
		}
	});

	/**
	 * custom durationHint property
	 */
	var durationHint = null;
	Object.defineProperty(self, "durationHint", {
		get: function getDurationHint() {
			return durationHint;
		},
		set: function setDurationHint(val) {
			durationHint = val;
			waitForFlash(function() {
				flash._setDurationHint(durationHint);
			});
		}
	});

	/**
	 * HTMLMediaElement duration property
	 */
	Object.defineProperty(self, "duration", {
		get: function getDuration() {
			if (flash._isReady) {
				return flash._getDuration();
			} else {
				return 0;
			}
		}
	});

	/**
	 * HTMLMediaElement paused property
	 */
	Object.defineProperty(self, "paused", {
		get: function getPaused() {
			if (flash._isReady) {
				return flash._getPaused();
			} else {
				return true;
			}
		}
	});

	/**
	 * HTMLMediaElement ended property
	 */
	Object.defineProperty(self, "ended", {
		get: function getEnded() {
			if (flash._isReady) {
				return flash._getEnded();
			} else {
				return false;
			}
		}
	});

	/**
	 * HTMLMediaElement muted property
	 */
	var muted;
	Object.defineProperty(self, "muted", {
		get: function getMuted() {
			return muted;
		},
		set: function setMuted(val) {
			muted = val;
			waitForFlash(function() {
				flash._setMuted(val);
			});
		}
	});

	/**
	 * HTMLVideoElement poster property
	 */
	var poster;
	Object.defineProperty(self, "poster", {
		get: function getPoster() {
			return poster;
		},
		set: function setPoster(val) {
			waitForFlash(function() {
				flash._setPoster(val);
			});
		}
	});

	// Video metadata properties...
	Object.defineProperty(self, "videoWidth", {
		get: function getVideoWidth() {
			if (flash._isReady) {
				return flash._getVideoWidth();
			} else {
				return 0;
			}
		}
	});
	Object.defineProperty(self, "videoHeight", {
		get: function getVideoHeight() {
			if (flash._isReady) {
				return flash._getVideoHeight();
			} else {
				return 0;
			}
		}
	});
	Object.defineProperty(self, "ogvjsVideoFrameRate", {
		get: function getOgvJsVideoFrameRate() {
			if (flash._isReady) {
				return flash._getFrameRate();
			} else {
				return 0;
			}
		}
	});

	// Audio metadata properties...
	Object.defineProperty(self, "ogvjsAudioChannels", {
		get: function getOgvJsAudioChannels() {
			if (flash._isReady) {
				return flash._getAudioChannels();
			} else {
				return 0;
			}
		}
	});
	Object.defineProperty(self, "ogvjsAudioSampleRate", {
		get: function getOgvJsAudioChannels() {
			if (flash._isReady) {
				return flash._getAudioSampleRate();
			} else {
				return 0;
			}
		}
	});

	// Display size...
	var width = 0, height = 0;
	Object.defineProperty(self, "width", {
		get: function getWidth() {
			return width;
		},
		set: function setWidth(val) {
			width = parseInt(val, 10);
			flash.width = width;
		}
	});

	Object.defineProperty(self, "height", {
		get: function getHeight() {
			return height;
		},
		set: function setHeight(val) {
			height = parseInt(val, 10);
			flash.height = height;
		}
	});

	// Events!

	/**
	 * custom onframecallback, takes frame decode time in ms
	 */
	self.onframecallback = null;

	/**
	 * Called when all metadata is available.
	 * Note in theory we must know 'duration' at this point.
	 */
	self.onloadedmetadata = null;

	/**
	 * Called when we start playback
	 */
	self.onplay = null;

	/**
	 * Called when we get paused
	 */
	self.onpause = null;

	/**
	 * Called when playback ends
	 */
	self.onended = null;

	return self;
}

OgvSwfPlayer.nextId = 1;
<|endoftext|>


<commit_before>import edaStepWayEasyFormGenController, {
  STEP_WAY_MAIN_CONTROLLER_NAME
}                                         from './stepway.main.controller';
import edaStepWayEasyFormGenDirective, {
  STEP_WAY_DIRECTIVE_NAME
}                                         from './stepway.main.directive';
import easyFormSteWayConfig, {
  EASY_FORM_STEP_WAY_CONFIG_NAME
}                                         from './stepway.main.provider';

const  STEP_WAY_MAIN_MODULE = 'easyFormStepwayMainModule';

export default angular
                .module(STEP_WAY_MAIN_MODULE, [])
                .controller(STEP_WAY_MAIN_CONTROLLER_NAME,  edaStepWayEasyFormGenController)
                .directive(STEP_WAY_DIRECTIVE_NAME,         edaStepWayEasyFormGenDirective)
                .provider(EASY_FORM_STEP_WAY_CONFIG_NAME,   easyFormSteWayConfig);
<commit_msg>chore : refactor<commit_after>import edaStepWayEasyFormGenController, {
  STEP_WAY_MAIN_CONTROLLER_NAME
}                                         from './stepway.main.controller';
import edaStepWayEasyFormGenDirective, {
  STEP_WAY_DIRECTIVE_NAME
}                                         from './stepway.main.directive';
import easyFormSteWayConfig, {
  EASY_FORM_STEP_WAY_CONFIG_NAME
}                                         from './stepway.main.provider';
import pagerModule                        from './pager/stepway.main.pager.module';
import pageIndicatorModule                from './pageIndicator/stepway.main.pageIndicator.module';
import stepZeroContentModule              from './stepZeroContent/stepway.main.stepZeroContent.module';
import stepOneContentModule               from './stepOneContent/stepway.main.stepOneContent.module';
import stepTwoContentModule               from './stepTwoContent/stepway.main.stepTwoContent.module';
import stepThreeContentModule             from './stepThreeContent/stepway.main.stepThreeContent.module';

const  STEP_WAY_MAIN_MODULE = 'easyFormStepwayMainModule';

const TO_INJECT = [
  pagerModule.name,
  pageIndicatorModule.name,
  stepZeroContentModule.name,
  stepOneContentModule.name,
  stepTwoContentModule.name,
  stepThreeContentModule.name
];

export default angular
                .module(STEP_WAY_MAIN_MODULE, TO_INJECT)
                .controller(STEP_WAY_MAIN_CONTROLLER_NAME,  edaStepWayEasyFormGenController)
                .directive(STEP_WAY_DIRECTIVE_NAME,         edaStepWayEasyFormGenDirective)
                .provider(EASY_FORM_STEP_WAY_CONFIG_NAME,   easyFormSteWayConfig);
<|endoftext|>


<commit_before>var chai = require('chai'),
  should = chai.should(),
  proxyquire = require('proxyquire'),
  sinon = require('sinon'),
  gitLabTranslator = require('../../../api/translators/gitLabTranslator'),
  GitLabCommitMalformedError = require('../../../middleware/gitLabCommitMalformedError');

describe('gitLabTranslator', function() {

  describe('with appropriate headers', function() {

    var originalHasCorrectHeaders;

    before(function() {
      // Set hasCorrectHeaders to be a stub to ensure it's been called.
      originalHasCorrectHeaders = gitLabTranslator.hasCorrectHeaders;
      gitLabTranslator.hasCorrectHeaders = sinon.stub();
      gitLabTranslator.hasCorrectHeaders.returns(true);
    });

    it('canTranslate should check for appropriate headers', function() {
      var request = {};

      // Act, which should cause the call to hasCorrectHeaders
      gitLabTranslator.canTranslate(request);

      // Check that hasCorrectHeaders was called
      gitLabTranslator.hasCorrectHeaders.should.have.been.calledOnce;
    });

    it('canTranslate should return true when valid headers are available', function() {
      var request = {};

      gitLabTranslator.canTranslate(request).should.equal(true);
    });

    it('should report correct headers if x-gitlab-event header is "Push Hook"', function() {
      var request = {
        'headers': {
          'x-gitlab-event': 'Push Hook'
        }
      }

      gitLabTranslator.hasCorrectHeaders(request.headers).should.equal(true);
    });

    after(function() {
      // reset hasCorrectHeaders back to the real implementation, not our stub.
      gitLabTranslator.hasCorrectHeaders = originalHasCorrectHeaders;
    });
  });

  describe('with incorrect headers', function() {

    var originalHasCorrectHeaders;

    before(function() {

      // Set hasCorrectHeaders to be a stub to ensure it's been called.
      originalHasCorrectHeaders = gitLabTranslator.hasCorrectHeaders;
      gitLabTranslator.hasCorrectHeaders = sinon.stub();
      gitLabTranslator.hasCorrectHeaders.returns(false);
    });

    it('canTranslate should return false when invalid headers are present', function() {
      // What is in the request does not matter for this one, because the component that
      // actually uses the request (gitLabTranslator.hasCorrectHeaders) is being set
      // as a stub for this tests.

      var request = {};
      gitLabTranslator.canTranslate(request).should.equal(false);
    });

    it('should report incorrect headers if x-gitlab-event header is missing', function() {
      var request = {
        'headers': {}
      }

      gitLabTranslator.hasCorrectHeaders(request.headers).should.equal(false);
    });

    it('should report incorrect headers if  x-gitlab-event header is "Tag Push Hook"', function() {
      var request = {
        'headers': {
          'x-gitlab-event': 'Tag Push Hook'
        }
      }

      gitLabTranslator.hasCorrectHeaders(request.headers).should.equal(false);
    });

    it('should report incorrect headers if  x-gitlab-event header is "Issue Hook"', function() {
      var request = {
        'headers': {
          'x-gitlab-event': 'Issue Hook'
        }
      }

      gitLabTranslator.hasCorrectHeaders(request.headers).should.equal(false);
    });

    it('should report incorrect headers if  x-gitlab-event header is "Note Hook"', function() {
      var request = {
        'headers': {
          'x-gitlab-event': 'Note Hook'
        }
      }

      gitLabTranslator.hasCorrectHeaders(request.headers).should.equal(false);
    });

    it('should report incorrect headers if  x-gitlab-event header is "Merge Request Hook"', function() {
      var request = {
        'headers': {
          'x-gitlab-event': 'Merge Request Hook'
        }
      }

      gitLabTranslator.hasCorrectHeaders(request.headers).should.equal(false);
    });

    after(function() {
      // reset hasCorrectHeaders back to the real implementation, not our stub.
      gitLabTranslator.hasCorrectHeaders = originalHasCorrectHeaders;
    });
  });

  describe('with malformed push events', function() {
    it('it should throw a GitLabCommitMalformedError.', function() {
      var invokeTranslatePush = function() {
        var malformedPushEvent = {};
        var instanceId = '73b40eab-bbb9-4478-9031-601b9e701d17',
          digestId = '9c369aef-b041-4a38-a76c-d3cf59dec0d2',
          inboxId = '9c369aef-b041-4a38-a76c-d3cf59dec0d2';

        gitLabTranslator.translatePush(malformedPushEvent, instanceId, digestId, inboxId);
      }

      invokeTranslatePush.should.throw(GitLabCommitMalformedError);
    })
  });
});<commit_msg>S-53159: unit test of what we would expect for the output of the gitLab translator given an input.<commit_after>var chai = require('chai'),
  should = chai.should(),
  proxyquire = require('proxyquire'),
  sinon = require('sinon'),
  GitLabCommitMalformedError = require('../../../middleware/gitLabCommitMalformedError'),
  uuidStub = sinon.stub(),
  gitLabTranslator = proxyquire('../../../api/translators/gitLabTranslator', {
    'uuid-v4': uuidStub
  });

var pushEventWithOneCommit = {
  "object_kind": "push",
  "before": "95790bf891e76fee5e1747ab589903a6a1f80f22",
  "after": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
  "ref": "refs/heads/master",
  "user_id": 4,
  "user_name": "John Smith",
  "user_email": "john@example.com",
  "project_id": 15,
  "repository": {
    "name": "Diaspora",
    "url": "git@example.com:mike/diasporadiaspora.git",
    "description": "",
    "homepage": "http://example.com/mike/diaspora",
    "git_http_url": "http://example.com/mike/diaspora.git",
    "git_ssh_url": "git@example.com:mike/diaspora.git",
    "visibility_level": 0
  },
  "commits": [{
    "id": "b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327",
    "message": "Update Catalan translation to e38cb41.",
    "timestamp": "2011-12-12T14:27:31+02:00",
    "url": "http://example.com/mike/diaspora/commit/b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327",
    "author": {
      "name": "Jordi Mallach",
      "email": "jordi@softcatala.org"
    }
  }],
  "total_commits_count": 4
};

describe('gitLabTranslator', function() {

  describe('with appropriate headers', function() {

    var originalHasCorrectHeaders;

    before(function() {
      // Set hasCorrectHeaders to be a stub to ensure it's been called.
      originalHasCorrectHeaders = gitLabTranslator.hasCorrectHeaders;
      gitLabTranslator.hasCorrectHeaders = sinon.stub();
      gitLabTranslator.hasCorrectHeaders.returns(true);
    });

    it('canTranslate should check for appropriate headers', function() {
      var request = {};
      // Act, which should cause the call to hasCorrectHeaders
      gitLabTranslator.canTranslate(request);

      // Check that hasCorrectHeaders was called
      gitLabTranslator.hasCorrectHeaders.should.have.been.calledOnce;
    });

    it('canTranslate should return true when valid headers are available', function() {
      var request = {};

      gitLabTranslator.canTranslate(request).should.equal(true);
    });

    it('should report correct headers if x-gitlab-event header is "Push Hook"', function() {
      var request = {
        'headers': {
          'x-gitlab-event': 'Push Hook'
        }
      }

      gitLabTranslator.hasCorrectHeaders(request.headers).should.equal(true);
    });

    after(function() {
      // reset hasCorrectHeaders back to the real implementation, not our stub.
      gitLabTranslator.hasCorrectHeaders = originalHasCorrectHeaders;
    });
  });

  describe('with incorrect headers', function() {

    var originalHasCorrectHeaders;

    before(function() {

      // Set hasCorrectHeaders to be a stub to ensure it's been called.
      originalHasCorrectHeaders = gitLabTranslator.hasCorrectHeaders;
      gitLabTranslator.hasCorrectHeaders = sinon.stub();
      gitLabTranslator.hasCorrectHeaders.returns(false);
    });

    it('canTranslate should return false when invalid headers are present', function() {
      // What is in the request does not matter for this one, because the component that
      // actually uses the request (gitLabTranslator.hasCorrectHeaders) is being set
      // as a stub for this tests.

      var request = {};
      gitLabTranslator.canTranslate(request).should.equal(false);
    });

    it('should report incorrect headers if x-gitlab-event header is missing', function() {
      var request = {
        'headers': {}
      }

      gitLabTranslator.hasCorrectHeaders(request.headers).should.equal(false);
    });

    it('should report incorrect headers if  x-gitlab-event header is "Tag Push Hook"', function() {
      var request = {
        'headers': {
          'x-gitlab-event': 'Tag Push Hook'
        }
      }

      gitLabTranslator.hasCorrectHeaders(request.headers).should.equal(false);
    });

    it('should report incorrect headers if  x-gitlab-event header is "Issue Hook"', function() {
      var request = {
        'headers': {
          'x-gitlab-event': 'Issue Hook'
        }
      }

      gitLabTranslator.hasCorrectHeaders(request.headers).should.equal(false);
    });

    it('should report incorrect headers if  x-gitlab-event header is "Note Hook"', function() {
      var request = {
        'headers': {
          'x-gitlab-event': 'Note Hook'
        }
      }

      gitLabTranslator.hasCorrectHeaders(request.headers).should.equal(false);
    });

    it('should report incorrect headers if  x-gitlab-event header is "Merge Request Hook"', function() {
      var request = {
        'headers': {
          'x-gitlab-event': 'Merge Request Hook'
        }
      }

      gitLabTranslator.hasCorrectHeaders(request.headers).should.equal(false);
    });

    after(function() {
      // reset hasCorrectHeaders back to the real implementation, not our stub.
      gitLabTranslator.hasCorrectHeaders = originalHasCorrectHeaders;
    });
  });

  describe('with malformed push events', function() {
    it('it should throw a GitLabCommitMalformedError.', function() {
      var invokeTranslatePush = function() {
        var malformedPushEvent = {};
        var instanceId = '73b40eab-bbb9-4478-9031-601b9e701d17',
          digestId = '9c369aef-b041-4a38-a76c-d3cf59dec0d2',
          inboxId = '9c369aef-b041-4a38-a76c-d3cf59dec0d2';

        gitLabTranslator.translatePush(malformedPushEvent, instanceId, digestId, inboxId);
      }

      invokeTranslatePush.should.throw(GitLabCommitMalformedError);
    })
  });

  describe('when translating a push event that contains one commit', function() {
    it('should match the expected translation', function() {
      var instanceId = '73b40eab-bbb9-4478-9031-601b9e701d17',
        digestId = '9c369aef-b041-4a38-a76c-d3cf59dec0d2',
        inboxId = '9c369aef-b041-4a38-a76c-d3cf59dec0d2';
      eventId = '87b66de8-8307-4e03-b2d3-da447c66501a';
      uuidStub.returns(eventId);

      var expected = [{
        eventId: eventId,
        eventType: 'GitLabCommitReceived',
        data: {
          sha: 'b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327',
          commit: {
            author: {
              email: "jordi@softcatala.org",
              name: "Jordi Mallach"
            },
            committer: {
              date: "2011-12-12T14:27:31+02:00",
              email: "jordi@softcatala.org",
              name: "Jordi Mallach"
            },
            message: "Update Catalan translation to e38cb41."
          },
          html_url: 'http://example.com/mike/diaspora/commit/b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327',
          repository: {
            name: "Diaspora"
          },
          branch: 'master',
          originalMessage: {
            author: {
              email: "jordi@softcatala.org",
              name: "Jordi Mallach"
            },
            id: "b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327",
            message: "Update Catalan translation to e38cb41.",
            timestamp: "2011-12-12T14:27:31+02:00",
            url: "http://example.com/mike/diaspora/commit/b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327"
          }
        },
        metadata: {
          instanceId: '73b40eab-bbb9-4478-9031-601b9e701d17',
          digestId: '9c369aef-b041-4a38-a76c-d3cf59dec0d2',
          inboxId: '9c369aef-b041-4a38-a76c-d3cf59dec0d2'
        }
      }];

      var actual = gitLabTranslator.translatePush(pushEventWithOneCommit, instanceId, digestId, inboxId);

      actual.should.deep.equal(expected);
    });

  });
});<|endoftext|>


<commit_before>import { createStore, applyMiddleware } from 'redux';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-15';
import thunk from 'redux-thunk';
import reducer from '../app/assets/javascripts/reducers';

const jsdom = require('jsdom');
const { JSDOM } = jsdom;

global.document = new JSDOM(`<!doctype html><html><body><div data-current_user='{ "admin": false, "id": null }' id='react_root'></div></body></html>`, {
  url: 'http://localhost',
  skipWindowCheck: true
});
global.window = document.defaultView;
global.navigator = global.window.navigator;

configure({ adapter: new Adapter() });

const sinon = require('sinon');
const React = require('react');
const ReactDOM = require('react-dom');
const ReactTestUtils = require('react-dom/test-utils');
const $ = require('jquery');
const moment = require('moment');
const momentRecur = require('moment-recur');
const I18n = require('../public/assets/javascripts/i18n.js'); // eslint-disable-line import/no-unresolved
const chai = require('chai');
const sinonChai = require('sinon-chai');

const reduxStore = createStore(reducer, applyMiddleware(thunk));

global.reduxStore = reduxStore;
global.$ = $;
global.sinon = sinon;
global.React = React;
global.ReactDOM = ReactDOM;
global.ReactTestUtils = ReactTestUtils;
global.Simulate = ReactTestUtils.Simulate;
global.moment = moment;
global['moment-recur'] = momentRecur;
global.I18n = I18n;
global.chai = chai;
global.expect = chai.expect;
global.assert = chai.assert;
global.Features = {};
global.currentUser = {};

require('../public/assets/javascripts/i18n/en'); // eslint-disable-line import/no-unresolved

chai.use(sinonChai);
<commit_msg>Fix a warning in the jest test suite<commit_after>import { createStore, applyMiddleware } from 'redux';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-15';
import thunk from 'redux-thunk';
import reducer from '../app/assets/javascripts/reducers';

const jsdom = require('jsdom');
const { JSDOM } = jsdom;

global.document = new JSDOM(`<!doctype html><html><body><div data-current_user='{ "admin": false, "id": null }' id='react_root'></div></body></html>`, {
  url: 'http://localhost',
  skipWindowCheck: true
});
global.window = document.defaultView;
global.window.scrollTo = jest.fn(); // scrollTo is not implemented by JSDOM, so we mock it.
global.navigator = global.window.navigator;

configure({ adapter: new Adapter() });

const sinon = require('sinon');
const React = require('react');
const ReactDOM = require('react-dom');
const ReactTestUtils = require('react-dom/test-utils');
const $ = require('jquery');
const moment = require('moment');
const momentRecur = require('moment-recur');
const I18n = require('../public/assets/javascripts/i18n.js'); // eslint-disable-line import/no-unresolved
const chai = require('chai');
const sinonChai = require('sinon-chai');

const reduxStore = createStore(reducer, applyMiddleware(thunk));

global.reduxStore = reduxStore;
global.$ = $;
global.sinon = sinon;
global.React = React;
global.ReactDOM = ReactDOM;
global.ReactTestUtils = ReactTestUtils;
global.Simulate = ReactTestUtils.Simulate;
global.moment = moment;
global['moment-recur'] = momentRecur;
global.I18n = I18n;
global.chai = chai;
global.expect = chai.expect;
global.assert = chai.assert;
global.Features = {};
global.currentUser = {};

require('../public/assets/javascripts/i18n/en'); // eslint-disable-line import/no-unresolved

chai.use(sinonChai);
<|endoftext|>


<commit_before>'use babel';

import {CompositeDisposable} from 'atom';

const osascript = require('node-osascript');
const fileExists = require('file-exists');

const configFileNames = [
    'config.codekit3',
    '.config.codekit3',
    'config.codekit'
]

const messages = {
    paused: "CodeKit Atom Sync Paused",
    resumed: "CodeKit Atom Sync Resumed"
};

export default {

    subscriptions: null,
    workspaceSubscriptions: null,

    activate(state) {

        // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
        this.subscriptions = new CompositeDisposable();

        // Register command that toggles this view
        this.subscriptions.add(atom.commands.add('atom-workspace', {
            'codekit-atom-sync:open-codekit': () => this.codekit_open(),
            'codekit-atom-sync:add-project-to-codekit': () => this.codekit_addProject(),
            'codekit-atom-sync:toggle-codekit-atom-sync': () => this.toggleWorkspaceSubscriptions()
        }));

        this.registerWorkspaceSubscriptions();

    },

    deactivate() {
        this.subscriptions.dispose();
        this.workspaceSubscriptions.dispose();
    },

    serialize() {
        return {};
    },

    /*
    |--------------------------------------------------------------------------
    | Atom Commands
    |--------------------------------------------------------------------------
    */

    // Toggles the core project switching subscriptions.
    // Used when 'pausing' and 'resuming' the plugin.
    toggleWorkspaceSubscriptions() {

        if (this.workspaceSubscriptions.disposed) {

            // Dismiss the paused notification
            atom.notifications.getNotifications().forEach(notification => {
                if (notification.getMessage() == messages.paused) {
                    notification.dismiss();
                }
            });

            // Add a resumed notification
            atom.notifications.addInfo(messages.resumed);

            // Resume plugin
            this.registerWorkspaceSubscriptions();

        } else {

            // Add paused notification
            atom.notifications.addInfo(messages.paused, {dismissable: true});

            // Pause plugin
            this.deregisterWorkspaceSubscriptions();
        }
    },

    // Registers the core project switching subscriptions
    registerWorkspaceSubscriptions() {
        // Add event listener for workspace opening something
        this.workspaceSubscriptions = new CompositeDisposable();
        this.workspaceSubscriptions.add(atom.workspace.onDidOpen( this.atom_environmentChanged.bind(this) ));
    },

    // Deregisters the core project switching subscriptions
    deregisterWorkspaceSubscriptions() {
        this.workspaceSubscriptions.dispose();
    },

    // Determines if this folder is a codekit project.
    // If it is - it adds and switches to it in CodeKit
    atom_environmentChanged(event) {

        let path = atom.project.getPaths()[0];

        let configFileExists = false;
        configFileNames.forEach( filename => {
            if (fileExists.sync(`${path}/${filename}`)) {
                configFileExists = true;
            }
        });

        // If config file exists
        if (configFileExists) {
            // Switch/Add project
            this.codekit_addProject(path);
            this.codekit_switchProject(path);
        } else {
            // Then this isn't a Codekit Project. Do nothing.
        }

    },

    /*
    |--------------------------------------------------------------------------
    | Codekit Commands
    |--------------------------------------------------------------------------
    */

    // If Codekit is not running, open it. Do nothing if it's already running.
    codekit_open() {
        osascript.execute(`tell application "CodeKit" to launch`, function(err, result, raw) {});
    },

    // Adds a project to Codekit then switches it to the active project
    codekit_addProject(projectPath = false) {
        projectPath = projectPath || atom.project.getPaths()[0];
        osascript.execute(`tell application "CodeKit" to add project at path "${projectPath}"`, function(err, result, raw) {});
    },

    // Tells CodeKit to swtich to the specified project
    codekit_switchProject(projectPath = false) {
        projectPath = projectPath || atom.project.getPaths()[0];
        osascript.execute(`tell application "CodeKit" to select project containing path "${projectPath}"`, function(err, result, raw) {});
    }

};<commit_msg>Create helper for dismissing notifications by name<commit_after>'use babel';

import {CompositeDisposable} from 'atom';

const osascript = require('node-osascript');
const fileExists = require('file-exists');

const configFileNames = [
    'config.codekit3',
    '.config.codekit3',
    'config.codekit'
]

const messages = {
    paused: "CodeKit Atom Sync Paused",
    resumed: "CodeKit Atom Sync Resumed"
};

export default {

    subscriptions: null,
    workspaceSubscriptions: null,

    activate(state) {

        // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
        this.subscriptions = new CompositeDisposable();

        // Register command that toggles this view
        this.subscriptions.add(atom.commands.add('atom-workspace', {
            'codekit-atom-sync:open-codekit': () => this.codekit_open(),
            'codekit-atom-sync:add-project-to-codekit': () => this.codekit_addProject(),
            'codekit-atom-sync:toggle-codekit-atom-sync': () => this.toggleWorkspaceSubscriptions()
        }));

        this.registerWorkspaceSubscriptions();

    },

    deactivate() {
        this.subscriptions.dispose();
        this.workspaceSubscriptions.dispose();
    },

    serialize() {
        return {};
    },

    /*
    |--------------------------------------------------------------------------
    | Atom Commands
    |--------------------------------------------------------------------------
    */

    removeNotificationWithMessage(message) {
        atom.notifications.getNotifications().forEach(notification => {
            if (notification.getMessage() == message) {
                notification.dismiss();
            }
        });
    },

    // Toggles the core project switching subscriptions.
    // Used when 'pausing' and 'resuming' the plugin.
    toggleWorkspaceSubscriptions() {

        if (this.workspaceSubscriptions.disposed) {

            // Dismiss the paused notification
            this.removeNotificationWithMessage(messages.paused);

            // Add a resumed notification
            atom.notifications.addInfo(messages.resumed);

            // Resume plugin
            this.registerWorkspaceSubscriptions();

        } else {

            // Add paused notification
            atom.notifications.addInfo(messages.paused, {dismissable: true});

            // Pause plugin
            this.deregisterWorkspaceSubscriptions();
        }
    },

    // Registers the core project switching subscriptions
    registerWorkspaceSubscriptions() {
        // Add event listener for workspace opening something
        this.workspaceSubscriptions = new CompositeDisposable();
        this.workspaceSubscriptions.add(atom.workspace.onDidOpen( this.atom_environmentChanged.bind(this) ));
    },

    // Deregisters the core project switching subscriptions
    deregisterWorkspaceSubscriptions() {
        this.workspaceSubscriptions.dispose();
    },

    // Determines if this folder is a codekit project.
    // If it is - it adds and switches to it in CodeKit
    atom_environmentChanged(event) {

        let path = atom.project.getPaths()[0];

        let configFileExists = false;
        configFileNames.forEach( filename => {
            if (fileExists.sync(`${path}/${filename}`)) {
                configFileExists = true;
            }
        });

        // If config file exists
        if (configFileExists) {
            // Switch/Add project
            this.codekit_addProject(path);
            this.codekit_switchProject(path);
        } else {
            // Then this isn't a Codekit Project. Do nothing.
        }

    },

    /*
    |--------------------------------------------------------------------------
    | Codekit Commands
    |--------------------------------------------------------------------------
    */

    // If Codekit is not running, open it. Do nothing if it's already running.
    codekit_open() {
        osascript.execute(`tell application "CodeKit" to launch`, function(err, result, raw) {});
    },

    // Adds a project to Codekit then switches it to the active project
    codekit_addProject(projectPath = false) {
        projectPath = projectPath || atom.project.getPaths()[0];
        osascript.execute(`tell application "CodeKit" to add project at path "${projectPath}"`, function(err, result, raw) {});
    },

    // Tells CodeKit to swtich to the specified project
    codekit_switchProject(projectPath = false) {
        projectPath = projectPath || atom.project.getPaths()[0];
        osascript.execute(`tell application "CodeKit" to select project containing path "${projectPath}"`, function(err, result, raw) {});
    }

};<|endoftext|>


<commit_before>(function() {
  'use strict';
  angular.module('civic.events.variants')
    .directive('variantEditBasic', variantEditBasicDirective)
    .controller('VariantEditBasicController', VariantEditBasicController);

  // @ngInject
  function variantEditBasicDirective() {
    return {
      restrict: 'E',
      scope: {},
      controller: 'VariantEditBasicController',
      templateUrl: 'app/views/events/variants/edit/variantEditBasic.tpl.html'
    }
  }

  // @ngInject
  function VariantEditBasicController($scope,
                                      $stateParams,
                                      Security,
                                      VariantRevisions,
                                      Variants,
                                      VariantHistory,
                                      VariantsViewOptions,
                                      formConfig) {
    var variantModel, vm;

    vm = $scope.vm = {};
    variantModel = vm.variantModel = Variants;

    vm.isAdmin = Security.isAdmin();
    vm.isAuthenticated = Security.isAuthenticated();

    vm.variant = Variants.data.item;
    vm.variantRevisions = VariantRevisions;
    vm.variantHistory = VariantHistory;
    vm.variantEdit = angular.copy(vm.variant);
    vm.variantEdit.comment = { title: 'VARIANT ' + vm.variant.name + ' Suggested Revision', text:'' };
    vm.myVariantInfo = variantModel.data.myVariantInfo;
    vm.variants = variantModel.data.variants;
    vm.variantGroups = variantModel.data.variantGroups;

    vm.styles = VariantsViewOptions.styles;

    vm.user = {};

    vm.formErrors = {};
    vm.formMessages = {};
    vm.errorMessages = formConfig.errorMessages;
    vm.errorPrompts = formConfig.errorPrompts;
    vm.newRevisionId = Number();
    vm.stateParams = $stateParams;

    vm.showForm = true;
    vm.showSuccessMessage = false;
    vm.showInstructions = true;

    vm.variantFields = [
      {
        key: 'name',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Name',
          value: vm.variant.name,
          helpText: ''
        }
      },
      {
        key: 'description',
        type: 'horizontalTextareaHelp',
        templateOptions: {
          rows: 8,
          label: 'Description',
          value: 'vm.variant.description',
          minLength: 32,
          helpText: 'User-defined summary of the clinical relevance of this Variant.'
        }
      },
      {
        template: '
Coordinates

'
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'chromosome',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Chromosome',
          value: vm.variantEdit.coordinates.chromosome,
          helpText: 'Chromosome in which this variant occurs'
        }
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'start',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Start',
          value: vm.variantEdit.coordinates.start,
          helpText: ''
        }
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'stop',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Stop',
          value: vm.variantEdit.coordinates.stop,
          helpText: ''
        }
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'reference_bases',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Reference Bases',
          value: vm.variantEdit.coordinates.reference_bases,
          helpText: ''
        }
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'variant_bases',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Variant Bases',
          value: vm.variantEdit.coordinates.variant_bases,
          helpText: ''
        }
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'representative_transcript',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Representative Transcript',
          value: vm.variantEdit.coordinates.representative_transcript,
          helpText: ''
        }
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'reference_bases',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Reference Bases',
          value: vm.variantEdit.coordinates.reference_bases,
          helpText: ''
        }
      },
      {
        template: '
Fusion Coordinates

'
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'chromosome2',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Chromosome 2',
          value: vm.variantEdit.coordinates.chromosome2,
          helpText: 'If variant is a fusion, specify its coordinates'
        }
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'start2',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Start 2',
          value: vm.variantEdit.coordinates.start2,
          helpText: ''
        }
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'stop2',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Stop 2',
          value: vm.variantEdit.coordinates.stop2,
          helpText: ''
        }
      },
      {
        template: '
'
      },
      {
        model: vm.variantEdit.comment,
        key: 'text',
        type: 'horizontalTextareaHelp',
        templateOptions: {
          rows: 5,
          label: 'Revision Description',
          value: 'text',
          helpText: 'Please provide a brief description and support, if necessary, for your suggested revision. It will appear as the first comment in this revision\'s comment thread.'
        }
      }
    ];

    vm.submit = function(variantEdit, options) {
      variantEdit.variantId = variantEdit.id;
      vm.formErrors = {};
      vm.formMessages = {};
      VariantRevisions.submitRevision(variantEdit)
        .then(function(response) {
          console.log('revision submit success!');
          vm.newRevisionId = response.id;
          vm.formMessages['submitSuccess'] = true;
          vm.showInstructions = false;
          vm.showForm = false;
          vm.showSuccessMessage = true;
          // options.resetModel();
        })
        .catch(function(error) {
          console.error('revision submit error!');
          vm.formErrors[error.status] = true;
        })
        .finally(function(){
          console.log('revision submit done!');
        });
    };

    vm.apply = function(variantEdit, options) {
      variantEdit.variantId = variantEdit.id;
      vm.formErrors = {};
      vm.formMessages = {};
      Variants.apply(variantEdit)
        .then(function(response) {
          console.log('revision appy success!');
          vm.formMessages['applySuccess'] = true;
          // options.resetModel();
        })
        .catch(function(response) {
          console.error('revision application error!');
          vm.formErrors[response.status] = true;
        })
        .finally(function(){
          console.log('revision apply done!');
        });
    };
  }
})();
<commit_msg>submitting/accepting suggested revisions for variant coordinate updates now works as expected<commit_after>(function() {
  'use strict';
  angular.module('civic.events.variants')
    .directive('variantEditBasic', variantEditBasicDirective)
    .controller('VariantEditBasicController', VariantEditBasicController);

  // @ngInject
  function variantEditBasicDirective() {
    return {
      restrict: 'E',
      scope: {},
      controller: 'VariantEditBasicController',
      templateUrl: 'app/views/events/variants/edit/variantEditBasic.tpl.html'
    }
  }

  // @ngInject
  function VariantEditBasicController($scope,
                                      $stateParams,
                                      Security,
                                      VariantRevisions,
                                      Variants,
                                      VariantHistory,
                                      VariantsViewOptions,
                                      formConfig) {
    var variantModel, vm;

    vm = $scope.vm = {};
    variantModel = vm.variantModel = Variants;

    vm.isAdmin = Security.isAdmin();
    vm.isAuthenticated = Security.isAuthenticated();

    vm.variant = Variants.data.item;
    vm.variantRevisions = VariantRevisions;
    vm.variantHistory = VariantHistory;
    vm.variantEdit = angular.copy(vm.variant);
    vm.variantEdit.comment = { title: 'VARIANT ' + vm.variant.name + ' Suggested Revision', text:'' };
    vm.myVariantInfo = variantModel.data.myVariantInfo;
    vm.variants = variantModel.data.variants;
    vm.variantGroups = variantModel.data.variantGroups;

    vm.styles = VariantsViewOptions.styles;

    vm.user = {};

    vm.formErrors = {};
    vm.formMessages = {};
    vm.errorMessages = formConfig.errorMessages;
    vm.errorPrompts = formConfig.errorPrompts;
    vm.newRevisionId = Number();
    vm.stateParams = $stateParams;

    vm.showForm = true;
    vm.showSuccessMessage = false;
    vm.showInstructions = true;

    vm.variantFields = [
      {
        key: 'name',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Name',
          value: vm.variant.name,
          helpText: ''
        }
      },
      {
        key: 'description',
        type: 'horizontalTextareaHelp',
        templateOptions: {
          rows: 8,
          label: 'Description',
          value: 'vm.variant.description',
          minLength: 32,
          helpText: 'User-defined summary of the clinical relevance of this Variant.'
        }
      },
      {
        template: '
Coordinates

'
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'chromosome',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Chromosome',
          value: vm.variantEdit.coordinates.chromosome,
          helpText: 'Chromosome in which this variant occurs'
        }
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'start',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Start',
          value: vm.variantEdit.coordinates.start,
          helpText: ''
        }
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'stop',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Stop',
          value: vm.variantEdit.coordinates.stop,
          helpText: ''
        }
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'reference_bases',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Reference Bases',
          value: vm.variantEdit.coordinates.reference_bases,
          helpText: ''
        }
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'variant_bases',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Variant Bases',
          value: vm.variantEdit.coordinates.variant_bases,
          helpText: ''
        }
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'representative_transcript',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Representative Transcript',
          value: vm.variantEdit.coordinates.representative_transcript,
          helpText: ''
        }
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'reference_bases',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Reference Bases',
          value: vm.variantEdit.coordinates.reference_bases,
          helpText: ''
        }
      },
      {
        template: '
Fusion Coordinates

'
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'chromosome2',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Chromosome 2',
          value: vm.variantEdit.coordinates.chromosome2,
          helpText: 'If variant is a fusion, specify its coordinates'
        }
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'start2',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Start 2',
          value: vm.variantEdit.coordinates.start2,
          helpText: ''
        }
      },
      {
        model: vm.variantEdit.coordinates,
        key: 'stop2',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Stop 2',
          value: vm.variantEdit.coordinates.stop2,
          helpText: ''
        }
      },
      {
        template: '
'
      },
      {
        model: vm.variantEdit.comment,
        key: 'text',
        type: 'horizontalTextareaHelp',
        templateOptions: {
          rows: 5,
          label: 'Revision Description',
          value: 'text',
          helpText: 'Please provide a brief description and support, if necessary, for your suggested revision. It will appear as the first comment in this revision\'s comment thread.'
        }
      }
    ];

    vm.submit = function(variantEdit, options) {
      variantEdit.variantId = variantEdit.id;
      vm.formErrors = {};
      vm.formMessages = {};
      variantEdit = _.merge(variantEdit, variantEdit.coordinates); // civic-server needs coords on base variant obj
      delete variantEdit.coordinates;

      VariantRevisions.submitRevision(variantEdit)
        .then(function(response) {
          console.log('revision submit success!');
          vm.newRevisionId = response.id;
          vm.formMessages['submitSuccess'] = true;
          vm.showInstructions = false;
          vm.showForm = false;
          vm.showSuccessMessage = true;
          // options.resetModel();
        })
        .catch(function(error) {
          console.error('revision submit error!');
          vm.formErrors[error.status] = true;
        })
        .finally(function(){
          console.log('revision submit done!');
        });
    };

    vm.apply = function(variantEdit, options) {
      variantEdit.variantId = variantEdit.id;
      vm.formErrors = {};
      vm.formMessages = {};
      Variants.apply(variantEdit)
        .then(function(response) {
          console.log('revision appy success!');
          vm.formMessages['applySuccess'] = true;
          // options.resetModel();
        })
        .catch(function(response) {
          console.error('revision application error!');
          vm.formErrors[response.status] = true;
        })
        .finally(function(){
          console.log('revision apply done!');
        });
    };
  }
})();
<|endoftext|>


<commit_before>Games = new Mongo.Collection('games');

var Schemas = {};

TeamShootsSchema = new SimpleSchema({
	onePointIn: {
		type: Number,
		label: 'Team FT scored',
		min: 0
	},
	onePointOut: {
		type: Number,
		label: 'Team FT missed',
		min: 0
	},
	twoPointsIn: {
		type: Number,
		label: 'Team 2pt scored',
		min: 0
	},
	twoPointsOut: {
		type: Number,
		label: 'Team 2pt missed',
		min: 0
	},
	threePointsIn: {
		type: Number,
		label: 'Team 3pt scored',
		min: 0
	},
	threePointsOut: {
		type: Number,
		label: 'Team 3pt missed',
		min: 0
	}
});

TeamReboundsSchema = new SimpleSchema({
	offReb: {
		type: Number,
		label: 'Team offensive rebounds',
		min: 0
	},
	defReb: {
		type: Number,
		label: 'Team defensive rebounds',
		min: 0
	}
});

TeamProvFoulsSchema = new SimpleSchema({
	offFouls: {
		type: Number,
		label: 'Team offensive provoqued fouls',
		min: 0
	},
	defFouls: {
		type: Number,
		label: 'Team defensive provoqued fouls',
		min: 0
	}
});

TeamFoulsSchema = new SimpleSchema({
	provFouls: {
		type: TeamProvFoulsSchema
	},
	offFouls: {
		type: Number,
		label: 'Team offensive fouls',
		min: 0
	},
	defFouls: {
		type: Number,
		label: 'Team defensive fouls',
		min: 0
	},
	totalFouls: {
		type: Number,
		label: 'Team total fouls',
		min: 0
	},
	foul1FT: {
		type: Number,
		label: 'Team 1 FT fouls',
		min: 0
	},
	foul2FT: {
		type: Number,
		label: 'Team 2 FT fouls',
		min: 0
	},
	foul3FT: {
		type: Number,
		label: 'Team 3 FT fouls',
		min: 0
	},
	techFouls: {
		type: Number,
		label: 'Team technical fouls',
		min: 0
	},
	antiSportFouls: {
		type: Number,
		label: 'Team anti sportive fouls',
		min: 0
	},
	disqualifyingFouls: {
		type: Number,
		label: 'Team disqualifying fouls',
		min: 0
	}
});

TeamStatsSchema = new SimpleSchema({
	score: {
		type: Number,
		label: 'Team Score',
		min: 0
	},
	evaluation: {
		type: Number,
		label: 'Global team evaluation'
	},
	shoots: {
		type: TeamShootsSchema
	},
	assists: {
		type: Number,
		label: 'Team assists',
		min: 0
	},
	rebounds: {
		type: TeamReboundsSchema
	},
	fouls: {
		type: TeamFoulsSchema
	},
	steals: {
		type: Number,
		label: 'Team steals',
		min: 0
	},
	blocks: {
		type: Number,
		label: 'Team blocks',
		min: 0
	},
	turnovers: {
		type: Number,
		label: 'Team turnovers',
		min: 0
	}
});

GameStatsSchema = new SimpleSchema({
	homeTeam: {
		type: TeamStatsSchema
	},
	awayTeam: {
		type: TeamStatsSchema
	},
	evolution: {
		type: [Object],
		label: 'Game score evolution'
	},
});

GameInfosSchema = new SimpleSchema({
	homeTeamId: {
		type: String,
		label: 'Home team id'
	},
	awayTeamId: {
		type: String,
		label: 'Away team id'
	},
	level: {
		type: String,
		label: 'Game level',
		optional: true
	},
	group: {
		type: String,
		label: 'Group of the both teams',
		optional: true
	}
});

Schemas.Games = new SimpleSchema({
	userId: {
		type: String,
		label: 'User id'
	},
	createdAt: {
		type: String,
		label: 'State of the game'
	},
	gameState: {
		type: String,
		label: 'Mangas name',
		allowedValues: ['notStarted', 'q1Running', 'q1Ended', 'q2Running', 'halfTime', 'q3Running', 'q3Ended', 'q4Running', 'gameEnded', 'oT1', 'oT2', 'oT3', 'oT4', 'oT5']
	},
	privateGame: {
		type: Boolean,
		label: 'Game privacy',
		defaultValue: false
	},
	gameInfos: {
		type: GameInfosSchema
	},
	stats: {
		type: GameStatsSchema,
	}
});

Games.attachSchema(Schemas.Games);

Games.allow({
	insert: function(userId, doc) {
		// the user must be logged in, and the document must be owned by the user
		return (userId && doc.userId === userId);
	},
	update: function(userId, doc, fields, modifier) {
		// can only change your own documents
		return doc.userId === userId;
	},
	remove: function(userId, doc) {
		// can only remove your own documents
		return doc.userId === userId;
	},
	fetch: ['userId']
});

Games.deny({
	update: function(userId, docs, fields, modifier) {
		// can't change userId
		return _.contains(fields, 'userId');
	},
	fetch: ['userId']
});
<commit_msg>Fix label<commit_after>Games = new Mongo.Collection('games');

var Schemas = {};

TeamShootsSchema = new SimpleSchema({
	onePointIn: {
		type: Number,
		label: 'Team FT scored',
		min: 0
	},
	onePointOut: {
		type: Number,
		label: 'Team FT missed',
		min: 0
	},
	twoPointsIn: {
		type: Number,
		label: 'Team 2pt scored',
		min: 0
	},
	twoPointsOut: {
		type: Number,
		label: 'Team 2pt missed',
		min: 0
	},
	threePointsIn: {
		type: Number,
		label: 'Team 3pt scored',
		min: 0
	},
	threePointsOut: {
		type: Number,
		label: 'Team 3pt missed',
		min: 0
	}
});

TeamReboundsSchema = new SimpleSchema({
	offReb: {
		type: Number,
		label: 'Team offensive rebounds',
		min: 0
	},
	defReb: {
		type: Number,
		label: 'Team defensive rebounds',
		min: 0
	}
});

TeamProvFoulsSchema = new SimpleSchema({
	offFouls: {
		type: Number,
		label: 'Team offensive provoqued fouls',
		min: 0
	},
	defFouls: {
		type: Number,
		label: 'Team defensive provoqued fouls',
		min: 0
	}
});

TeamFoulsSchema = new SimpleSchema({
	provFouls: {
		type: TeamProvFoulsSchema
	},
	offFouls: {
		type: Number,
		label: 'Team offensive fouls',
		min: 0
	},
	defFouls: {
		type: Number,
		label: 'Team defensive fouls',
		min: 0
	},
	totalFouls: {
		type: Number,
		label: 'Team total fouls',
		min: 0
	},
	foul1FT: {
		type: Number,
		label: 'Team 1 FT fouls',
		min: 0
	},
	foul2FT: {
		type: Number,
		label: 'Team 2 FT fouls',
		min: 0
	},
	foul3FT: {
		type: Number,
		label: 'Team 3 FT fouls',
		min: 0
	},
	techFouls: {
		type: Number,
		label: 'Team technical fouls',
		min: 0
	},
	antiSportFouls: {
		type: Number,
		label: 'Team anti sportive fouls',
		min: 0
	},
	disqualifyingFouls: {
		type: Number,
		label: 'Team disqualifying fouls',
		min: 0
	}
});

TeamStatsSchema = new SimpleSchema({
	score: {
		type: Number,
		label: 'Team Score',
		min: 0
	},
	evaluation: {
		type: Number,
		label: 'Global team evaluation'
	},
	shoots: {
		type: TeamShootsSchema
	},
	assists: {
		type: Number,
		label: 'Team assists',
		min: 0
	},
	rebounds: {
		type: TeamReboundsSchema
	},
	fouls: {
		type: TeamFoulsSchema
	},
	steals: {
		type: Number,
		label: 'Team steals',
		min: 0
	},
	blocks: {
		type: Number,
		label: 'Team blocks',
		min: 0
	},
	turnovers: {
		type: Number,
		label: 'Team turnovers',
		min: 0
	}
});

GameStatsSchema = new SimpleSchema({
	homeTeam: {
		type: TeamStatsSchema
	},
	awayTeam: {
		type: TeamStatsSchema
	},
	evolution: {
		type: [Object],
		label: 'Game score evolution'
	},
});

GameInfosSchema = new SimpleSchema({
	homeTeamId: {
		type: String,
		label: 'Home team id'
	},
	awayTeamId: {
		type: String,
		label: 'Away team id'
	},
	level: {
		type: String,
		label: 'Game level',
		optional: true
	},
	group: {
		type: String,
		label: 'Group of the both teams',
		optional: true
	}
});

Schemas.Games = new SimpleSchema({
	userId: {
		type: String,
		label: 'User id'
	},
	createdAt: {
		type: String,
		label: 'State of the game'
	},
	gameState: {
		type: String,
		label: 'State of the game',
		allowedValues: ['notStarted', 'q1Running', 'q1Ended', 'q2Running', 'halfTime', 'q3Running', 'q3Ended', 'q4Running', 'gameEnded', 'oT1', 'oT2', 'oT3', 'oT4', 'oT5']
	},
	privateGame: {
		type: Boolean,
		label: 'Game privacy',
		defaultValue: false
	},
	gameInfos: {
		type: GameInfosSchema
	},
	stats: {
		type: GameStatsSchema,
	}
});

Games.attachSchema(Schemas.Games);

Games.allow({
	insert: function(userId, doc) {
		// the user must be logged in, and the document must be owned by the user
		return (userId && doc.userId === userId);
	},
	update: function(userId, doc, fields, modifier) {
		// can only change your own documents
		return doc.userId === userId;
	},
	remove: function(userId, doc) {
		// can only remove your own documents
		return doc.userId === userId;
	},
	fetch: ['userId']
});

Games.deny({
	update: function(userId, docs, fields, modifier) {
		// can't change userId
		return _.contains(fields, 'userId');
	},
	fetch: ['userId']
});
<|endoftext|>


<commit_before>
Nodes = new Mongo.Collection('nodes');

// Externalized properties
Nodes.TYPE = {
  list: ['C', 'T', 'O', 'S'],
  'C': {
    color: '#E98F96',
    code: 'C',
    name: 'Competency'
  },
  'T': {
    color: '#6382D9',
    code: 'T',
    name: 'Topic'
  },
  'O': {
    color: '#1CC0A4',
    code: 'O',
    name: 'Learning Objective'
  },
  'S': {
    color: '#DC85DA',
    code: 'S',
    name: 'Skill'
  }
};

/**
 * @summary For provided Cytoscape instance and node id return child nodes (id)
 * @method getChildren
 * @param {Object} [cy] Instance of Cytoscape.js
 * @param {String} [id] Node id
 * @returns {Array}
 */
Nodes.getChildren = function(cy, id) {
  var node = cy.$('#' + id);
  var result = [];
  var type;
  var selector;

  if (node.length !== 0) {
    type = node.data('type');

    if (type !== 'S') {
      if ((type === 'C') || (type === 'T')) {
        selector = '[type = "T"], [type = "O"]';
      } else if (type === 'O') {
        selector = '[type = "S"]';
      } else {
        throw 'Unknown node type';
      }

      node.outgoers(selector).forEach(function(el) {
        result.push(el.id());
      });
    }
  }

  return result;
};

/**
 * @summary For provided Cytoscape instance and node id return parent nodes (id)
 * @method getParents
 * @param {Object} [cy] Instance of Cytoscape.js
 * @param {String} [id] Node id
 * @returns {Array}
 */
Nodes.getParents = function(cy, id) {
  var node = cy.$('#' + id);
  var result = [];

  if (node.length !== 0) {
    node.incomers().forEach(function(el) {
      result.push(el.id());
    });
  }

  return result;
};

/**
 * @summary For provided Cytoscape instance and node id return skill nodes (id)
 * @method getSkills
 * @param {Object} [cy] Instance of Cytoscape.js
 * @param {String} [id] Node id
 * @returns {Array}
 */
Nodes.getSkills = function(cy, id) {
  var node = cy.$('#' + id);
  var result = [];

  if (node.length !== 0) {
    node.successors('[type = "S"]').forEach(function(el) {
      result.push(el.id());
    });
  }

  return result;
};

Nodes.graph = {};

/**
 * @summary For provided Cytoscape instance return node ids
 * @method graph.ids
 * @param {Object} [graph] Instance of Cytoscape.js
 * @returns {Array}
 */
Nodes.graph.ids = function(graph) {
  var result = [];
  graph.nodes().forEach(function(it) {
    result.push(it.id());
  });

  return result;
};

/**
 * @summary Create node for Cytoscape.js
 * @method createNode
 * @param {Object} [node] Nodes collection instance
 * @returns {Object}
 */
Nodes.graph.createNode = function(node) {
  return {
    data: {
      id: node._id,
      type: node.type
    }
  };
};

/**
 * @summary Create edge from parent to child node (for Cytoscape.js)
 * @method createEdge
 * @param {String} [parent] Parent node id
 * @param {String} [child] Child node id
 * @returns {Object}
 */
Nodes.graph.createEdge = function(parent, child) {
  return {
    data: {
      source: parent,
      target: child
    }
  };
};

/**
 * @summary Create edges from multiple parent nodes to child node (Cytoscape.js)
 * @method createEdges
 * @param {Array} [parents] Parent node ids
 * @param {String} [child] Child node id
 * @returns {Array}
 */
Nodes.graph.createEdges = function(parents, child) {
  var result = [];

  Lazy(parents).each(function(it) {
    result.push(Nodes.graph.createEdge(it, child));
  });

  return result;
};
<commit_msg>Nodes collection update<commit_after>
Nodes = new Mongo.Collection('nodes');

// Reference settings
Nodes.TYPE = Meteor.settings.public.node;

/**
 * @summary For provided Cytoscape instance and node id return child nodes (id)
 * @method getChildren
 * @param {Object} [cy] Instance of Cytoscape.js
 * @param {String} [id] Node id
 * @returns {Array}
 */
Nodes.getChildren = function(cy, id) {
  var node = cy.$('#' + id);
  var result = [];
  var type;
  var selector;

  if (node.length !== 0) {
    type = node.data('type');

    if (type !== 'S') {
      if ((type === 'R') || (type === 'T')) {
        selector = '[type = "T"], [type = "O"]';
      } else if (type === 'O') {
        selector = '[type = "S"]';
      } else {
        throw new Error('Unknown node type');
      }

      node.outgoers(selector).forEach(function(el) {
        result.push(el.id());
      });
    }
  }

  return result;
};

/**
 * @summary For provided Cytoscape instance and node id return parent nodes (id)
 * @method getParents
 * @param {Object} [cy] Instance of Cytoscape.js
 * @param {String} [id] Node id
 * @returns {Array}
 */
Nodes.getParents = function(cy, id) {
  var node = cy.$('#' + id);
  var result = [];

  if (node.length !== 0) {
    node.incomers().forEach(function(el) {
      result.push(el.id());
    });
  }

  return result;
};

/**
 * @summary For provided Cytoscape instance and node id return skill nodes (id)
 * @method getSkills
 * @param {Object} [cy] Instance of Cytoscape.js
 * @param {String} [id] Node id
 * @returns {Array}
 */
Nodes.getSkills = function(cy, id) {
  var node = cy.$('#' + id);
  var result = [];

  if (node.length !== 0) {
    node.successors('[type = "S"]').forEach(function(el) {
      result.push(el.id());
    });
  }

  return result;
};

Nodes.graph = {};

/**
 * @summary For provided Cytoscape instance return node ids
 * @method graph.ids
 * @param {Object} [graph] Instance of Cytoscape.js
 * @returns {Array}
 */
Nodes.graph.ids = function(graph) {
  var result = [];
  graph.nodes().forEach(function(it) {
    result.push(it.id());
  });

  return result;
};

/**
 * @summary Create node for Cytoscape.js
 * @method createNode
 * @param {Object} [node] Nodes collection instance
 * @returns {Object}
 */
Nodes.graph.createNode = function(node) {
  return {
    data: {
      id: node._id,
      type: node.type
    }
  };
};

/**
 * @summary Create edge from parent to child node (for Cytoscape.js)
 * @method createEdge
 * @param {String} [parent] Parent node id
 * @param {String} [child] Child node id
 * @returns {Object}
 */
Nodes.graph.createEdge = function(parent, child) {
  return {
    data: {
      source: parent,
      target: child
    }
  };
};

/**
 * @summary Create edges from multiple parent nodes to child node (Cytoscape.js)
 * @method createEdges
 * @param {Array} [parents] Parent node ids
 * @param {String} [child] Child node id
 * @returns {Array}
 */
Nodes.graph.createEdges = function(parents, child) {
  var result = [];

  Lazy(parents).each(function(it) {
    result.push(Nodes.graph.createEdge(it, child));
  });

  return result;
};
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { Creatable } from 'react-select';
import { createTextFilter } from './common';

const propTypes = {
  value: PropTypes.array,
  filterText: PropTypes.string,
  onChange: PropTypes.func.isRequired,
  onTextChange: PropTypes.func.isRequired,
  options: PropTypes.array.isRequired,
  className: PropTypes.string,
  hasFilterable: PropTypes.bool,
  placeholder: PropTypes.node,
  style: PropTypes.object,
};

class Filter extends Component {
  constructor(props) {
    super(props);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleCreateOption = this.handleCreateOption.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
  }

  shouldComponentUpdate(nextProps) {
    const { value, filterText, options } = this.props;
    if (nextProps.value !== value ||
        nextProps.options !== options ||
        nextProps.filterText !== filterText) {
      return true;
    }
    return false;
  }

  handleInputChange(text, { action }) {
    const { onTextChange } = this.props;
    // prevent blur from clearing text that wasn't confirmed with tab or enter
    if (action !== 'input-blur' && action !== 'menu-close') {
      onTextChange(text);
    }
  }

  handleBlur(e) {
    // preserve text on blur
    const { onTextChange } = this.props;
    const val = e.target.value;
    if (val !== '') {
      onTextChange(val);
    }
  }

  handleCreateOption(val) {
    const { onChange, value } = this.props;
    const opt = createTextFilter(val);
    onChange([...value, opt]);
  }

  render() {
    const {
      value,
      filterText,
      onChange,
      options,
      className,
      hasFilterable,
      placeholder,
      style,
    } = this.props;
    const defaultPlaceholder = hasFilterable ? 'Search or filter using tags...' : 'Search...';
    return (
      <Creatable
        className={className}
        options={options}
        noOptionsMessage={() => 'Type text to search, press Enter to save as filter'}
        placeholder={placeholder || defaultPlaceholder}
        formatCreateLabel={txt => `Create '${txt}' filter`}
        isValidNewOption={input => !!input}
        onChange={selected => onChange(selected)}
        onInputChange={this.handleInputChange}
        onCreateOption={this.handleCreateOption}
        onBlur={this.handleBlur}
        value={value}
        inputValue={filterText || ''}
        isMulti
        style={style}
      />
    );
  }
}

Filter.propTypes = propTypes;
export default Filter;
<commit_msg>Make sure that 'Create filter' is always on top of options<commit_after>import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { Creatable } from 'react-select';
import { createTextFilter } from './common';

const propTypes = {
  value: PropTypes.array,
  filterText: PropTypes.string,
  onChange: PropTypes.func.isRequired,
  onTextChange: PropTypes.func.isRequired,
  options: PropTypes.array.isRequired,
  className: PropTypes.string,
  hasFilterable: PropTypes.bool,
  placeholder: PropTypes.node,
  style: PropTypes.object,
};

class Filter extends Component {
  constructor(props) {
    super(props);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleCreateOption = this.handleCreateOption.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
  }

  shouldComponentUpdate(nextProps) {
    const { value, filterText, options } = this.props;
    if (nextProps.value !== value ||
        nextProps.options !== options ||
        nextProps.filterText !== filterText) {
      return true;
    }
    return false;
  }

  handleInputChange(text, { action }) {
    const { onTextChange } = this.props;
    // prevent blur from clearing text that wasn't confirmed with tab or enter
    if (action !== 'input-blur' && action !== 'menu-close') {
      onTextChange(text);
    }
  }

  handleBlur(e) {
    // preserve text on blur
    const { onTextChange } = this.props;
    const val = e.target.value;
    if (val !== '') {
      onTextChange(val);
    }
  }

  handleCreateOption(val) {
    const { onChange, value } = this.props;
    const opt = createTextFilter(val);
    onChange([...value, opt]);
  }

  render() {
    const {
      value,
      filterText,
      onChange,
      options,
      className,
      hasFilterable,
      placeholder,
      style,
    } = this.props;
    const defaultPlaceholder = hasFilterable ? 'Search or filter using tags...' : 'Search...';
    return (
      <Creatable
        className={className}
        options={options}
        noOptionsMessage={() => 'Type text to search, press Enter to save as filter'}
        placeholder={placeholder || defaultPlaceholder}
        formatCreateLabel={txt => `Create '${txt}' filter`}
        createOptionPosition="first"
        isValidNewOption={input => !!input}
        onChange={selected => onChange(selected)}
        onInputChange={this.handleInputChange}
        onCreateOption={this.handleCreateOption}
        onBlur={this.handleBlur}
        value={value}
        inputValue={filterText || ''}
        isMulti
        style={style}
      />
    );
  }
}

Filter.propTypes = propTypes;
export default Filter;
<|endoftext|>


<commit_before>Posts = new Mongo.Collection('posts');

Posts.allow({
  update: function(userId, post) { return ownsDocument(userId, post); },
  remove: function(userId, post) { return ownsDocument(userId, post); },
});

Meteor.methods({
  postInsert: function(postAttributes) {
    check(Meteor.userId(), String);
    check(postAttributes, {
      title: String,
      url: String
    });

    var postWithSameLink = Posts.findOne({url: postAttributes.url});
    if (postWithSameLink) {
      return {
        postExists: true,
        _id: postWithSameLink._id
      }
    }

    var user = Meteor.user();
    var post = _.extend(postAttributes, {
      userId: user._id,
      author: user.username,
      submitted: new Date()
    });
    var postId = Posts.insert(post);
    return {
      _id: postId
    };
  }
});
<commit_msg>Only allow changing certain fields of posts<commit_after>Posts = new Mongo.Collection('posts');

Posts.allow({
  update: function(userId, post) { return ownsDocument(userId, post); },
  remove: function(userId, post) { return ownsDocument(userId, post); },
});

Posts.deny({
  update: function(userId, post, fieldNames) {
    return (_.without(fieldNames, 'url', 'title').length > 0);
  }
});

Meteor.methods({
  postInsert: function(postAttributes) {
    check(Meteor.userId(), String);
    check(postAttributes, {
      title: String,
      url: String
    });

    var postWithSameLink = Posts.findOne({url: postAttributes.url});
    if (postWithSameLink) {
      return {
        postExists: true,
        _id: postWithSameLink._id
      }
    }

    var user = Meteor.user();
    var post = _.extend(postAttributes, {
      userId: user._id,
      author: user.username,
      submitted: new Date()
    });
    var postId = Posts.insert(post);
    return {
      _id: postId
    };
  }
});
<|endoftext|>


<commit_before>Tiers = new Mongo.Collection('tiers');

Meteor.methods({
  prizeChange: function (prize, tierId, pos) {
    check(Meteor.userId(), String);
    check(prize, String);
    check(tierId, String);
    check(pos, Number);
    var newPrize = {_id: Random.id(), pos: pos, prize: prize};
    //console.log(newPrize);
    //var lotto = Tiers.findOne(tierId);
    //var p = _.find(lotto.prizes, function (x) { return x.pos === pos; });
    //console.log(p);

    // TODO: still doesn't work
    Tiers.update({_id: tierId}, {
      $pull: {prizes: {pos: pos}},
      $push: {prizes: newPrize}
    });

    return {
      _id: newPrize._id
    };
  }
});<commit_msg>Fixed changing prizes<commit_after>Tiers = new Mongo.Collection('tiers');

Meteor.methods({
  prizeChange: function (prize, tierId, pos) {
    check(Meteor.userId(), String);
    check(prize, String);
    check(tierId, String);
    check(pos, Number);
    var newPrize = {_id: Random.id(), pos: pos, prize: prize};

    //TODO: make this atomic
    var tier = Tiers.findOne({ _id: tierId, 'prizes.pos': pos });
    if (!!tier) {
      Tiers.update(
        { _id: tierId, 'prizes.pos': pos },
        { $set: {'prizes.$': newPrize } }
      );
    } else {
      Tiers.update(
        { _id: tierId },
        { $addToSet: {prizes: newPrize } }
      );
    }
    return {
      _id: newPrize._id
    };
  }
});<|endoftext|>


<commit_before>/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
/** @module */

var Stream = require('../Stream');
var identity = require('../base').identity;

var Yield = Stream.Yield;

exports.unfold = unfold;
exports.iterate = iterate;
exports.repeat = repeat;

/**
 * Build a stream by unfolding steps from a seed value
 * @param {function(x:*):Step} f
 * @param {*} x seed value
 * @returns {Stream} stream containing all items
 */
function unfold(f, x) {
	return new Stream(f, x);
}

/**
 * Build a stream by iteratively calling f
 * @param {function(x:*):*} f
 * @param {*} x initial value
 * @returns {Stream}
 */
function iterate(f, x) {
	var scheduler = Stream.getDefaultScheduler();
	return new Stream(function(x) {
		return new Yield(scheduler.now(), x, f(x));
	}, x);
}

/**
 * Create an infinite stream of xs
 * @param {*} x
 * @returns {Stream} infinite stream where all items are x
 */
function repeat(x) {
	return iterate(identity, x);
}
<commit_msg>Don't automatically await promises in repeat()<commit_after>/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
/** @module */

var Stream = require('../Stream');
var identity = require('../base').identity;
var Pair = require('../step').Pair;

var Yield = Stream.Yield;

exports.unfold = unfold;
exports.iterate = iterate;
exports.repeat = repeat;

/**
 * Build a stream by unfolding steps from a seed value
 * @param {function(x:*):Step} f
 * @param {*} x seed value
 * @returns {Stream} stream containing all items
 */
function unfold(f, x) {
	return new Stream(f, x);
}

/**
 * Build a stream by iteratively calling f
 * @param {function(x:*):*} f
 * @param {*} x initial value
 * @returns {Stream}
 */
function iterate(f, x) {
	return new Stream(function(s) {
		var scheduler = s.state;
		return new Yield(scheduler.now(), s.value, new Pair(f(s.value), scheduler));
	}, new Pair(x, Stream.getDefaultScheduler()));
}

/**
 * Create an infinite stream of xs
 * @param {*} x
 * @returns {Stream} infinite stream where all items are x
 */
function repeat(x) {
	return iterate(identity, x);
}
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var defineProperty = require( '@stdlib/utils/define-property' );
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var randu = require( '@stdlib/random/base/mt19937' ).factory;
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var validate = require( './validate.js' );
var arcsine0 = require( './arcsine.js' );

// MAIN //

/**
* Returns a pseudorandom number generator for generating arcsine distributed random numbers.
*
* @param {number} [a] - minimum support
* @param {number} [b] - maximum support
* @param {Options} [options] - function options
* @param {*} [options.seed] - pseudorandom number generator seed
* @throws {TypeError} `a` must be a number
* @throws {TypeError} `b` must be a number
* @throws {RangeError} `a` must be less than `b`
* @throws {TypeError} options must be an object
* @throws {TypeError} must provide valid options
* @returns {Function} pseudorandom number generator
*
* @example
* var arcsine = factory( 0.0, 1.0 );
* var v = arcsine();
* // returns <number>
*
* @example
* var arcsine = factory( -3.0, -1.0, {
*     'seed': 297
* });
* var v = arcsine();
* // returns <number>
*/
function factory() {
	var opts;
	var rand;
	var prng;
	var err;
	var a;
	var b;

	if ( arguments.length === 0 ) {
		rand = randu();
	} else if ( arguments.length === 1 ) {
		opts = arguments[ 0 ];
		if ( !isObject( opts ) ) {
			throw new TypeError( 'invalid argument. Options argument must be an object. Value: `'+opts+'`.' );
		}
		rand = randu( opts );
	} else {
		a = arguments[ 0 ];
		b = arguments[ 1 ];
		err = validate( a, b );
		if ( err ) {
			throw err;
		}
		if ( arguments.length > 2 ) {
			opts = arguments[ 2 ];
			if ( !isObject( opts ) ) {
				throw new TypeError( 'invalid argument. Options argument must be an object. Value: `'+opts+'`.' );
			}
			rand = randu( opts );
		} else {
			rand = randu();
		}
	}
	rand = rand.normalized;

	if ( a === void 0 ) {
		prng = arcsine2;
	} else {
		prng = arcsine1;
	}
	setReadOnly( prng, 'NAME', 'arcsine' );
	setReadOnly( prng, 'seed', rand.seed );
	defineProperty( prng, 'state', {
		'configurable': false,
		'enumerable': true,
		'get': getState,
		'set': setState
	});
	setReadOnly( prng, 'stateLength', rand.stateLength );
	setReadOnly( prng, 'byteLength', rand.byteLength );
	setReadOnly( prng, 'PRNG', rand );

	return prng;

	/**
	* Returns the current pseudorandom number generator state.
	*
	* @private
	* @returns {Uint32Array} current state
	*/
	function getState() {
		return rand.state;
	}

	/**
	* Sets the pseudorandom number generator state.
	*
	* @private
	* @param {Uint32Array} s - generator state
	*/
	function setState( s ) {
		rand.state = s;
	}

	/**
	* Returns a arcsine distributed pseudorandom number with minimum support `a` and maximum support `b`.
	*
	* @private
	* @returns {number} pseudorandom number
	*
	* @example
	* var v = arcsine1();
	* // returns <number>
	*/
	function arcsine1() {
		return arcsine0( rand, a, b );
	}

	/**
	* Returns an arcsine distributed pseudorandom number with minimum support `a` and maximum support `b`.
	*
	* @private
	* @param {number} a - minimum support
	* @param {number} b - maximum support
	* @returns {number} pseudorandom number
	*
	* @example
	* var v = arcsine2( 0.0, 1.0 );
	* // returns <number>
	*
	* @example
	* var v = arcsine2( 1.0, 0.0 );
	* // returns NaN
	*/
	function arcsine2( a, b ) {
		if (
			isnan( a ) ||
			isnan( b ) ||
			a >= b
		) {
			return NaN;
		}
		return arcsine0( rand, a, b );
	}
}

// EXPORTS //

module.exports = factory;
<commit_msg>Refactor to support shared state<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-read-write-accessor' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var randu = require( '@stdlib/random/base/mt19937' ).factory;
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var validate = require( './validate.js' );
var arcsine0 = require( './arcsine.js' );

// MAIN //

/**
* Returns a pseudorandom number generator for generating arcsine distributed random numbers.
*
* @param {number} [a] - minimum support
* @param {number} [b] - maximum support
* @param {Options} [options] - function options
* @param {(uinteger32|Collection<uinteger32>)} [options.seed] - pseudorandom number generator seed
* @param {Uint32Array} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @throws {TypeError} `a` must be a number
* @throws {TypeError} `b` must be a number
* @throws {RangeError} `a` must be less than `b`
* @throws {TypeError} options must be an object
* @throws {TypeError} must provide valid options
* @throws {Error} must provide a valid state
* @returns {Function} pseudorandom number generator
*
* @example
* var arcsine = factory( 0.0, 1.0 );
* var v = arcsine();
* // returns <number>
*
* @example
* var arcsine = factory( -3.0, -1.0, {
*     'seed': 297
* });
* var v = arcsine();
* // returns <number>
*/
function factory() {
	var opts;
	var rand;
	var prng;
	var err;
	var a;
	var b;

	if ( arguments.length === 0 ) {
		rand = randu();
	} else if ( arguments.length === 1 ) {
		opts = arguments[ 0 ];
		if ( !isObject( opts ) ) {
			throw new TypeError( 'invalid argument. Options argument must be an object. Value: `'+opts+'`.' );
		}
		rand = randu( opts );
	} else {
		a = arguments[ 0 ];
		b = arguments[ 1 ];
		err = validate( a, b );
		if ( err ) {
			throw err;
		}
		if ( arguments.length > 2 ) {
			opts = arguments[ 2 ];
			if ( !isObject( opts ) ) {
				throw new TypeError( 'invalid argument. Options argument must be an object. Value: `'+opts+'`.' );
			}
			rand = randu( opts );
		} else {
			rand = randu();
		}
	}
	rand = rand.normalized;

	if ( a === void 0 ) {
		prng = arcsine2;
	} else {
		prng = arcsine1;
	}
	setReadOnly( prng, 'NAME', 'arcsine' );
	setReadOnlyAccessor( prng, 'seed', getSeed );
	setReadOnlyAccessor( prng, 'seedLength', getSeedLength );
	setReadWriteAccessor( prng, 'state', getState, setState );
	setReadOnlyAccessor( prng, 'stateLength', getStateLength );
	setReadOnlyAccessor( prng, 'byteLength', getStateSize );
	setReadOnly( prng, 'PRNG', rand );

	return prng;

	/**
	* Returns the PRNG seed.
	*
	* @private
	* @returns {Uint32Array} seed
	*/
	function getSeed() {
		return rand.seed;
	}

	/**
	* Returns the PRNG seed length.
	*
	* @private
	* @returns {PositiveInteger} seed length
	*/
	function getSeedLength() {
		return rand.seedLength;
	}

	/**
	* Returns the PRNG state length.
	*
	* @private
	* @returns {PositiveInteger} state length
	*/
	function getStateLength() {
		return rand.stateLength;
	}

	/**
	* Returns the PRNG state size (in bytes).
	*
	* @private
	* @returns {PositiveInteger} state size (in bytes)
	*/
	function getStateSize() {
		return rand.byteLength;
	}

	/**
	* Returns the current pseudorandom number generator state.
	*
	* @private
	* @returns {Uint32Array} current state
	*/
	function getState() {
		return rand.state;
	}

	/**
	* Sets the pseudorandom number generator state.
	*
	* @private
	* @param {Uint32Array} s - generator state
	* @throws {TypeError} must provide a `Uint32Array`
	* @throws {Error} must provide a valid state
	*/
	function setState( s ) {
		rand.state = s;
	}

	/**
	* Returns a arcsine distributed pseudorandom number with minimum support `a` and maximum support `b`.
	*
	* @private
	* @returns {number} pseudorandom number
	*
	* @example
	* var v = arcsine1();
	* // returns <number>
	*/
	function arcsine1() {
		return arcsine0( rand, a, b );
	}

	/**
	* Returns an arcsine distributed pseudorandom number with minimum support `a` and maximum support `b`.
	*
	* @private
	* @param {number} a - minimum support
	* @param {number} b - maximum support
	* @returns {number} pseudorandom number
	*
	* @example
	* var v = arcsine2( 0.0, 1.0 );
	* // returns <number>
	*
	* @example
	* var v = arcsine2( 1.0, 0.0 );
	* // returns NaN
	*/
	function arcsine2( a, b ) {
		if (
			isnan( a ) ||
			isnan( b ) ||
			a >= b
		) {
			return NaN;
		}
		return arcsine0( rand, a, b );
	}
}

// EXPORTS //

module.exports = factory;
<|endoftext|>