<commit_before>'use strict';

describe("CommitDetailsController", function () {

    var $httpBackend;
    var selectedCommitId = 123;
    var noopPromise = {then: function(){}};
    var selectedCommit, scope;
    var commentsEndpointAddress = 'rest/commits/123/comments';
    beforeEach(module('codebrag.commits'));
    var singleStoredComment = {id: '123', authorName: "mostr", message: "this is comment", time: "2013-03-29T15:14:10Z"};

    beforeEach(inject(function (_$httpBackend_, $rootScope) {
        $httpBackend = _$httpBackend_;
        scope = $rootScope.$new();
        selectedCommit = {id: 1};
    }));

    afterEach(inject(function (_$httpBackend_) {
        _$httpBackend_.verifyNoOutstandingExpectation();
        _$httpBackend_.verifyNoOutstandingRequest();
    }));

    function promiseResolvedWith(value) {
        return {
            then: function(successHandler) {
                successHandler(value);
            }
        }
    }

    it('should use commit ID provided in $stateParams to load commit data', inject(
        function ($controller, $stateParams, commitsListService) {

        // Given
        $stateParams.id = selectedCommitId;

        spyOn(commitsListService, "loadCommitById").andReturn(noopPromise);

        // When
        $controller('CommitDetailsCtrl', {$scope:scope});

        // Then
        expect(commitsListService.loadCommitById).toHaveBeenCalledWith(selectedCommitId);
    }));

    it('should load diff for selected commit', inject(function ($controller, $stateParams, commitsListService, $q) {
        // Given
        $stateParams.id = selectedCommitId;
        var expectedCommitDetails = {commit: {sha: '123'}, comments: [], files: []};
        spyOn(commitsListService, 'loadCommitById').andReturn(promiseResolvedWith(expectedCommitDetails));

        // When
        $controller('CommitDetailsCtrl', {$scope:scope});

        //then
        expect(scope.currentCommit.commit).toBe(expectedCommitDetails.commit);
        expect(scope.currentCommit.comments).toBe(expectedCommitDetails.comments);
        expect(scope.currentCommit.files).toBe(expectedCommitDetails.files);
    }));
//
    it('should call service to mark current commit as reviewed', inject( function
        ($controller, $stateParams, commitsListService) {
        // Given
        $stateParams.id = selectedCommitId;
        spyOn(commitsListService, 'loadCommitById').andReturn(noopPromise);
        spyOn(commitsListService, 'removeCommitAndGetNext').andReturn(noopPromise);

        // When
        $controller('CommitDetailsCtrl', {$scope:scope});
        scope.markCurrentCommitAsReviewed();

        // Then
        expect(commitsListService.removeCommitAndGetNext).toHaveBeenCalledWith(selectedCommitId);
    }));

});
<commit_msg>Fix broken test - update assertions on data format returned<commit_after>'use strict';

describe("CommitDetailsController", function () {

    var $httpBackend;
    var selectedCommitId = 123;
    var noopPromise = {then: function(){}};
    var selectedCommit, scope;
    var commentsEndpointAddress = 'rest/commits/123/comments';
    beforeEach(module('codebrag.commits'));
    var singleStoredComment = {id: '123', authorName: "mostr", message: "this is comment", time: "2013-03-29T15:14:10Z"};

    beforeEach(inject(function (_$httpBackend_, $rootScope) {
        $httpBackend = _$httpBackend_;
        scope = $rootScope.$new();
        selectedCommit = {id: 1};
    }));

    afterEach(inject(function (_$httpBackend_) {
        _$httpBackend_.verifyNoOutstandingExpectation();
        _$httpBackend_.verifyNoOutstandingRequest();
    }));

    function promiseResolvedWith(value) {
        return {
            then: function(successHandler) {
                successHandler(value);
            }
        }
    }

    it('should use commit ID provided in $stateParams to load commit data', inject(
        function ($controller, $stateParams, commitsListService) {

        // Given
        $stateParams.id = selectedCommitId;

        spyOn(commitsListService, "loadCommitById").andReturn(noopPromise);

        // When
        $controller('CommitDetailsCtrl', {$scope:scope});

        // Then
        expect(commitsListService.loadCommitById).toHaveBeenCalledWith(selectedCommitId);
    }));

    it('should load diff for selected commit', inject(function ($controller, $stateParams, commitsListService, $q) {
        // Given
        $stateParams.id = selectedCommitId;
        var expectedCommitDetails = {commit: {sha: '123'}, diff: [], supressedFiles: []};
        spyOn(commitsListService, 'loadCommitById').andReturn(promiseResolvedWith(expectedCommitDetails));

        // When
        $controller('CommitDetailsCtrl', {$scope:scope});

        //then
        expect(scope.currentCommit.info).toBe(expectedCommitDetails.commit);
    }));
//
    it('should call service to mark current commit as reviewed', inject( function
        ($controller, $stateParams, commitsListService) {
        // Given
        $stateParams.id = selectedCommitId;
        spyOn(commitsListService, 'loadCommitById').andReturn(noopPromise);
        spyOn(commitsListService, 'removeCommitAndGetNext').andReturn(noopPromise);

        // When
        $controller('CommitDetailsCtrl', {$scope:scope});
        scope.markCurrentCommitAsReviewed();

        // Then
        expect(commitsListService.removeCommitAndGetNext).toHaveBeenCalledWith(selectedCommitId);
    }));

});
<|endoftext|>


<commit_before>'use strict';

var aFrom           = require('es5-ext/array/from')
  , toArray         = require('es5-ext/array/to-array')
  , flatten         = require('es5-ext/array/#/flatten')
  , ensureIterable  = require('es5-ext/iterable/validate-object')
  , forEach         = require('es5-ext/object/for-each')
  , ensureCallable  = require('es5-ext/object/valid-callable')
  , ensureObject    = require('es5-ext/object/valid-object')
  , ensureString    = require('es5-ext/object/validate-stringifiable-value')
  , Map             = require('es6-map')
  , Set             = require('es6-set')
  , memoize         = require('memoizee/plain')
  , deferred        = require('deferred')
  , genStamp        = require('time-uuid/time')
  , fork            = require('child_process').fork
  , cpus            = require('os').cpus
  , ensureDriver    = require('../ensure-driver')
  , registerEmitter = require('../lib/emitter')

  , ceil = Math.ceil, min = Math.min
  , create = Object.create, keys = Object.keys
  , byStamp = function (a, b) { return a.data.stamp - b.data.stamp; };

var storeEvents = function (storage, events) {
	var current = events.slice(0, 10000);
	events = events.slice(10000);
	return deferred.map(current, function (event, index) {
		if (event.type === 'computed') {
			return storage
				._handleStoreComputed(event.ns, event.path, event.value, event.stamp, event.isOwnEvent);
		}
		if (event.type === 'direct') {
			return storage._handleStoreDirect(event.ns, event.path, event.value, event.stamp);
		}
		throw new Error("Unrecognized event configuration");
	})(function () {
		if (events.length) return storeEvents(storage, events);
	});
};

module.exports = function (driver, data) {
	var promise, slaveScriptPath, ids, getData, initialData;
	ensureDriver(driver);
	ensureObject(data);
	ids = ensureObject(data.ids);
	getData = ensureCallable(data.getData);
	slaveScriptPath = ensureString(data.slaveScriptPath);
	if (data.initialData != null) initialData = ensureObject(data.initialData);
	promise = deferred(ids)(function (ids) {
		var count = 0, indexes, processesCount, promises;
		ids = toArray(ensureIterable(ids));
		if (!ids.length) return;
		var resolveOwners = memoize(function () {
			var owners = new Map();
			return deferred.map(keys(indexes), function (storageName) {
				var storageOwners = new Map()
				  , storage = driver.getStorage(storageName);
				owners.set(storageName, storageOwners);
				return deferred.map(indexes[storageName], function (name) {
					var ownerIds = new Set();
					storageOwners.set(name, ownerIds);
					// Get all owner ids for saved records
					return storage.searchComputed({ keyPath: name }, function (id) {
						ownerIds.add(id.split('/', 1)[0]);
					});
				});
			})(owners);
		});
		var cleanup = function () {
			var events = [];
			return resolveOwners()(function (owners) {
				forEach(indexes, function (index, storageName) {
					index.forEach(function (name) {
						// Delete not used ownerids
						aFrom(owners.get(storageName).get(name)).forEach(function (ownerId) {
							events.push({ storage: storageName, type: 'computed', ns: name, path: ownerId,
								value: '', stamp: genStamp() });
						});
					});
				});
				var eventsMap = events.reduce(function (map, event) {
					if (!map[event.storage]) map[event.storage] = [];
					map[event.storage].push(event);
					return map;
				}, {});
				return deferred.reduce(keys(eventsMap), function (ignore, storageName) {
					return storeEvents(driver.getStorage(storageName), eventsMap[storageName]);
				}, null);
			});
		};

		var stats = {
			mastersCount: 0,
			recordsCount: 0,
			maxRecordsPerMasterCount: 0,
			minRecordsPerMasterCount: Infinity
		};

		var initializePool = function (id) {
			var pool, reinitializePool, indexesData, directData, emitData, getStamp, closeDef
			  , poolError, events = [];
			var clearPool = function () {
				return resolveOwners()(function (owners) {
					forEach(indexes, function (index, storageName) {
						index.forEach(function (name) {
							var ownerIds = owners.get(storageName).get(name);
							// Apply calculations
							forEach(indexesData[storageName][name], function (data, ownerId) {
								var stamp;
								ownerIds.delete(ownerId);
								delete this[ownerId];
								if (data.stamp === 'async') {
									stamp = function () { return getStamp(ownerId + '/' + name); };
								} else {
									stamp = data.stamp;
								}
								events.push({ storage: storageName, type: 'computed', ns: name, path: ownerId,
									value: data.value, stamp: stamp, isOwnEvent: data.isOwnEvent });
							}, indexesData[storageName][name]);
							directData.forEach(function (data) {
								events.push({ storage: data.name, type: 'direct', ns: data.ns,
									path: data.path, value: data.value, stamp: data.stamp });
							});
						});
					});
				})(function () {
					if (poolError) throw poolError;
					var eventsMap = events.reduce(function (map, event) {
						if (!map[event.storage]) map[event.storage] = [];
						map[event.storage].push(event);
						return map;
					}, {});
					return deferred.reduce(keys(eventsMap), function (ignore, storageName) {
						return storeEvents(driver.getStorage(storageName), eventsMap[storageName]);
					}, null);
				})(function () {
					if (poolError) throw poolError;
					events = [];
					closeDef = deferred();
					emitData.destroy();
					getStamp.destroy();
					pool.send({ type: 'close' });
					return closeDef.promise;
				});
			};
			var sendData = function (poolHealth) {
				var events = [];
				if (poolError) throw poolError;
				if (!ids.length) return clearPool();
				if (!poolHealth || (poolHealth < 1500)) {
					if (!(++count % 10)) promise.emit('progress', { type: 'nextObject' });
					++stats.mastersCount;
					return getData(ids.shift())(function self(data) {
						var masterEvents = flatten.call(data);
						if (stats.maxRecordsPerMasterCount < masterEvents.length) {
							stats.maxRecordsPerMasterCount = masterEvents.length;
						}
						if (stats.minRecordsPerMasterCount > masterEvents.length) {
							stats.minRecordsPerMasterCount = masterEvents.length;
						}
						events = events.concat(masterEvents);
						if (events.length > 10000) return;
						if (!ids.length) return;
						++stats.mastersCount;
						return getData(ids.shift())(self);
					})(function () {
						return events.sort(byStamp);
					})(emitData)(function (data) {
						data.events.forEach(function (data) {
							if (data.type === 'direct') directData.push(data);
							else indexesData[data.name][data.ns][data.path] = data;
						});
						return sendData(data.health);
					});
				}
				promise.emit('progress', { type: 'nextPool' });
				return clearPool()(reinitializePool);
			};
			reinitializePool = function () {
				var def = deferred();
				pool = fork(slaveScriptPath);
				emitData = registerEmitter('data', pool);
				getStamp = registerEmitter('stamp', pool);
				pool.once('message', function (message) {
					if (poolError) {
						def.reject(poolError);
						return;
					}
					if (message.type !== 'init') {
						def.reject(new Error("Unexpected message"));
						return;
					}
					if (!indexes) indexes = message.indexes;
					directData = [];
					if (!indexesData) {
						indexesData = create(null);
						forEach(indexes, function (storageIndexes, name) {
							var storageIndexesData = indexesData[name] = create(null);
							storageIndexes.forEach(function (name) { storageIndexesData[name] = create(null); });
						});
					}
					if (initialData) {
						def.resolve(deferred(initialData)(emitData)(function (data) {
							if (data.events.length) {
								throw new Error("Unexpected events triggered by initial data");
							}
							return sendData();
						}));
					} else {
						def.resolve(sendData());
					}
				});
				pool.on('error', function (err) { poolError = err; });
				pool.on('exit', function () {
					if (this !== pool) return;
					if (!closeDef) {
						if (!poolError) poolError = new Error("Slave process stopped working");
					} else if (poolError) {
						closeDef.reject(poolError);
					} else {
						closeDef.resolve();
					}
				});
				return def.promise;
			};
			return reinitializePool();
		};

		processesCount = min(cpus().length, ceil(ids.length / 10));
		promises = [];
		while (processesCount--) promises.push(initializePool());
		return deferred.map(promises)(cleanup)(stats);
	});
	return promise;
};
<commit_msg>Improve pass of stats<commit_after>'use strict';

var aFrom           = require('es5-ext/array/from')
  , toArray         = require('es5-ext/array/to-array')
  , flatten         = require('es5-ext/array/#/flatten')
  , ensureIterable  = require('es5-ext/iterable/validate-object')
  , forEach         = require('es5-ext/object/for-each')
  , ensureCallable  = require('es5-ext/object/valid-callable')
  , ensureObject    = require('es5-ext/object/valid-object')
  , ensureString    = require('es5-ext/object/validate-stringifiable-value')
  , Map             = require('es6-map')
  , Set             = require('es6-set')
  , memoize         = require('memoizee/plain')
  , deferred        = require('deferred')
  , genStamp        = require('time-uuid/time')
  , fork            = require('child_process').fork
  , cpus            = require('os').cpus
  , ensureDriver    = require('../ensure-driver')
  , registerEmitter = require('../lib/emitter')

  , ceil = Math.ceil, min = Math.min
  , create = Object.create, keys = Object.keys
  , byStamp = function (a, b) { return a.data.stamp - b.data.stamp; };

var storeEvents = function (storage, events) {
	var current = events.slice(0, 10000);
	events = events.slice(10000);
	return deferred.map(current, function (event, index) {
		if (event.type === 'computed') {
			return storage
				._handleStoreComputed(event.ns, event.path, event.value, event.stamp, event.isOwnEvent);
		}
		if (event.type === 'direct') {
			return storage._handleStoreDirect(event.ns, event.path, event.value, event.stamp);
		}
		throw new Error("Unrecognized event configuration");
	})(function () {
		if (events.length) return storeEvents(storage, events);
	});
};

module.exports = function (driver, data) {
	var promise, slaveScriptPath, ids, getData, initialData;
	ensureDriver(driver);
	ensureObject(data);
	ids = ensureObject(data.ids);
	getData = ensureCallable(data.getData);
	slaveScriptPath = ensureString(data.slaveScriptPath);
	if (data.initialData != null) initialData = ensureObject(data.initialData);

	var stats = {
		mastersCount: 0,
		recordsCount: 0,
		maxRecordsPerMasterCount: 0,
		minRecordsPerMasterCount: Infinity
	};

	promise = deferred(ids)(function (ids) {
		var count = 0, indexes, processesCount, promises;
		ids = toArray(ensureIterable(ids));
		if (!ids.length) return;
		var resolveOwners = memoize(function () {
			var owners = new Map();
			return deferred.map(keys(indexes), function (storageName) {
				var storageOwners = new Map()
				  , storage = driver.getStorage(storageName);
				owners.set(storageName, storageOwners);
				return deferred.map(indexes[storageName], function (name) {
					var ownerIds = new Set();
					storageOwners.set(name, ownerIds);
					// Get all owner ids for saved records
					return storage.searchComputed({ keyPath: name }, function (id) {
						ownerIds.add(id.split('/', 1)[0]);
					});
				});
			})(owners);
		});
		var cleanup = function () {
			var events = [];
			return resolveOwners()(function (owners) {
				forEach(indexes, function (index, storageName) {
					index.forEach(function (name) {
						// Delete not used ownerids
						aFrom(owners.get(storageName).get(name)).forEach(function (ownerId) {
							events.push({ storage: storageName, type: 'computed', ns: name, path: ownerId,
								value: '', stamp: genStamp() });
						});
					});
				});
				var eventsMap = events.reduce(function (map, event) {
					if (!map[event.storage]) map[event.storage] = [];
					map[event.storage].push(event);
					return map;
				}, {});
				return deferred.reduce(keys(eventsMap), function (ignore, storageName) {
					return storeEvents(driver.getStorage(storageName), eventsMap[storageName]);
				}, null);
			});
		};

		var initializePool = function (id) {
			var pool, reinitializePool, indexesData, directData, emitData, getStamp, closeDef
			  , poolError, events = [];
			var clearPool = function () {
				return resolveOwners()(function (owners) {
					forEach(indexes, function (index, storageName) {
						index.forEach(function (name) {
							var ownerIds = owners.get(storageName).get(name);
							// Apply calculations
							forEach(indexesData[storageName][name], function (data, ownerId) {
								var stamp;
								ownerIds.delete(ownerId);
								delete this[ownerId];
								if (data.stamp === 'async') {
									stamp = function () { return getStamp(ownerId + '/' + name); };
								} else {
									stamp = data.stamp;
								}
								events.push({ storage: storageName, type: 'computed', ns: name, path: ownerId,
									value: data.value, stamp: stamp, isOwnEvent: data.isOwnEvent });
							}, indexesData[storageName][name]);
							directData.forEach(function (data) {
								events.push({ storage: data.name, type: 'direct', ns: data.ns,
									path: data.path, value: data.value, stamp: data.stamp });
							});
						});
					});
				})(function () {
					if (poolError) throw poolError;
					var eventsMap = events.reduce(function (map, event) {
						if (!map[event.storage]) map[event.storage] = [];
						map[event.storage].push(event);
						return map;
					}, {});
					return deferred.reduce(keys(eventsMap), function (ignore, storageName) {
						return storeEvents(driver.getStorage(storageName), eventsMap[storageName]);
					}, null);
				})(function () {
					if (poolError) throw poolError;
					events = [];
					closeDef = deferred();
					emitData.destroy();
					getStamp.destroy();
					pool.send({ type: 'close' });
					return closeDef.promise;
				});
			};
			var sendData = function (poolHealth) {
				var events = [];
				if (poolError) throw poolError;
				if (!ids.length) return clearPool();
				if (!poolHealth || (poolHealth < 1500)) {
					if (!(++count % 10)) promise.emit('progress', { type: 'nextObject' });
					++stats.mastersCount;
					return getData(ids.shift())(function self(data) {
						var masterEvents = flatten.call(data);
						stats.recordsCount += masterEvents.length;
						if (stats.maxRecordsPerMasterCount < masterEvents.length) {
							stats.maxRecordsPerMasterCount = masterEvents.length;
						}
						if (stats.minRecordsPerMasterCount > masterEvents.length) {
							stats.minRecordsPerMasterCount = masterEvents.length;
						}
						events = events.concat(masterEvents);
						if (events.length > 10000) return;
						if (!ids.length) return;
						++stats.mastersCount;
						return getData(ids.shift())(self);
					})(function () {
						return events.sort(byStamp);
					})(emitData)(function (data) {
						data.events.forEach(function (data) {
							if (data.type === 'direct') directData.push(data);
							else indexesData[data.name][data.ns][data.path] = data;
						});
						return sendData(data.health);
					});
				}
				promise.emit('progress', { type: 'nextPool' });
				return clearPool()(reinitializePool);
			};
			reinitializePool = function () {
				var def = deferred();
				pool = fork(slaveScriptPath);
				emitData = registerEmitter('data', pool);
				getStamp = registerEmitter('stamp', pool);
				pool.once('message', function (message) {
					if (poolError) {
						def.reject(poolError);
						return;
					}
					if (message.type !== 'init') {
						def.reject(new Error("Unexpected message"));
						return;
					}
					if (!indexes) indexes = message.indexes;
					directData = [];
					if (!indexesData) {
						indexesData = create(null);
						forEach(indexes, function (storageIndexes, name) {
							var storageIndexesData = indexesData[name] = create(null);
							storageIndexes.forEach(function (name) { storageIndexesData[name] = create(null); });
						});
					}
					if (initialData) {
						def.resolve(deferred(initialData)(emitData)(function (data) {
							if (data.events.length) {
								throw new Error("Unexpected events triggered by initial data");
							}
							return sendData();
						}));
					} else {
						def.resolve(sendData());
					}
				});
				pool.on('error', function (err) { poolError = err; });
				pool.on('exit', function () {
					if (this !== pool) return;
					if (!closeDef) {
						if (!poolError) poolError = new Error("Slave process stopped working");
					} else if (poolError) {
						closeDef.reject(poolError);
					} else {
						closeDef.resolve();
					}
				});
				return def.promise;
			};
			return reinitializePool();
		};

		processesCount = min(cpus().length, ceil(ids.length / 10));
		promises = [];
		while (processesCount--) promises.push(initializePool());
		return deferred.map(promises)(cleanup);
	})(stats);
	return promise;
};
<|endoftext|>


<commit_before>DroolsPlatformControllers.controller('assetStatusController', function ($rootScope, $scope, $http) {
    /* Select package */
    $scope.selectPackage = {
        allowClear: true
    };

    $http.get('./server/rules_package/list')
        .success(function (data) {
            $scope.packagesList = data;
        })
        .error(function (error) {
            console.log(error);
        });

    /* Input select */
    $scope.filters = {};
    $scope.assets = undefined;
    $http.get('./server/rule_status/all')
        .success(function (data) {
            $scope.statuses = data;
        })
        .error(function (error) {
            console.log(error);
        });

    $scope.filtersOptions = {
        selectOnBlur: true
    };

    $scope.search = function () {
        var filters = $scope.filters;
        var packageSelected=$scope.package;
        console.log("Package selected : "+packageSelected);
        console.log("Filter()s selected : "+packageSelected);
        if(packageSelected == "" && filters.length == 0 ) {
            $scope.namePackageSelectClass="form-group has-error has-feedback";
            $scope.assetStatusSelectClass="form-group has-error has-feedback";
        }else if (filters.length == 0) {
            /* When mistake happens display the tooltip */
            $scope.assetStatusSelectClass="form-group has-error has-feedback";
            return;
        }else if (packageSelected == "") {
            /* When mistake happens display the tooltip */
            $scope.namePackageSelectClass="form-group has-error has-feedback";
            $scope.assetStatusSelectClass="form-group";
            return;
        }else{
            $scope.namePackageSelectClass="form-group";
            $scope.assetStatusSelectClass="form-group";
            //$("#popoverBtn").popover('destroy');
            $http.post('./server/rule_status/'+packageSelected, JSON.stringify(filters))
                .success(function (data) {
                    $scope.showCancelButton=true;
                    $scope.assets = data;
                })
                .error(function (error) {
                    console.log(error);
                    $scope.showCancelButton=true;
                    $scope.noAssetSent = true;
                });
        }
    };
    $scope.reset = function () {
        $scope.showCancelButton=false;
        $scope.package=undefined;
        $scope.filters = undefined;
        $scope.assets = undefined;
    }

    $scope.promoteAssetsStatus = function () {
        var packageSelected=$scope.package;
        var assetsToPromote = _.where($scope.assets, {selected: true});
        var data = {assetsToPromote: assetsToPromote, assetStatuses: $scope.filters};
        $http.post('./server/rule_status/'+packageSelected+'/promote', data)
            .success(function (data) {
                $scope.assets = data;
            })
            .error(function (error) {
                console.log(error);
            });
    };

    $scope.demoteAssetsStatus = function () {
        var assetsToDemote = _.where($scope.assets, {selected: true});
        var data = {assetsToDemote: assetsToDemote, assetStatuses: $scope.filters};
        $http.post('./server/rule_status/'+packageSelected+'/demote', data)
            .success(function (data) {
                $scope.assets = data;
            })
            .error(function (error) {
                console.log(error);
            });
    };

});
<commit_msg>Modification for "Demote" option<commit_after>DroolsPlatformControllers.controller('assetStatusController', function ($rootScope, $scope, $http) {
    /* Select package */
    $scope.selectPackage = {
        allowClear: true
    };

    $http.get('./server/rules_package/list')
        .success(function (data) {
            $scope.packagesList = data;
        })
        .error(function (error) {
            console.log(error);
        });

    /* Input select */
    $scope.filters = {};
    $scope.assets = undefined;
    $http.get('./server/rule_status/all')
        .success(function (data) {
            $scope.statuses = data;
        })
        .error(function (error) {
            console.log(error);
        });

    $scope.filtersOptions = {
        selectOnBlur: true
    };

    $scope.search = function () {
        var filters = $scope.filters;
        var packageSelected=$scope.package;
        console.log("Package selected : "+packageSelected);
        console.log("Filter()s selected : "+packageSelected);
        if(packageSelected == "" && filters.length == 0 ) {
            $scope.namePackageSelectClass="form-group has-error has-feedback";
            $scope.assetStatusSelectClass="form-group has-error has-feedback";
        }else if (filters.length == 0) {
            /* When mistake happens display the tooltip */
            $scope.assetStatusSelectClass="form-group has-error has-feedback";
            return;
        }else if (packageSelected == "") {
            /* When mistake happens display the tooltip */
            $scope.namePackageSelectClass="form-group has-error has-feedback";
            $scope.assetStatusSelectClass="form-group";
            return;
        }else{
            $scope.namePackageSelectClass="form-group";
            $scope.assetStatusSelectClass="form-group";
            //$("#popoverBtn").popover('destroy');
            $http.post('./server/rule_status/'+packageSelected, JSON.stringify(filters))
                .success(function (data) {
                    $scope.showCancelButton=true;
                    $scope.assets = data;
                })
                .error(function (error) {
                    console.log(error);
                    $scope.showCancelButton=true;
                    $scope.noAssetSent = true;
                });
        }
    };
    $scope.reset = function () {
        $scope.showCancelButton=false;
        $scope.package=undefined;
        $scope.filters = undefined;
        $scope.assets = undefined;
    }

    $scope.promoteAssetsStatus = function () {
        var packageSelected=$scope.package;
        var assetsToPromote = _.where($scope.assets, {selected: true});
        var data = {assetsToPromote: assetsToPromote, assetStatuses: $scope.filters};
        $http.post('./server/rule_status/'+packageSelected+'/promote', data)
            .success(function (data) {
                $scope.assets = data;
            })
            .error(function (error) {
                console.log(error);
            });
    };

    $scope.demoteAssetsStatus = function () {
        var packageSelected=$scope.package;
        var assetsToDemote = _.where($scope.assets, {selected: true});
        var data = {assetsToDemote: assetsToDemote, assetStatuses: $scope.filters};
        $http.post('./server/rule_status/'+packageSelected+'/demote', data)
            .success(function (data) {
                $scope.assets = data;
            })
            .error(function (error) {
                console.log(error);
            });
    };

});
<|endoftext|>


<commit_before><commit_msg>js: Removed obsolete colorzone.<commit_after><|endoftext|>


<commit_before>$(document).ready(function() {

    /**
     * Replaces tokens in a string with values in a supplied key-value map.
     */
    if (!String.prototype.supplant) {
        String.prototype.supplant = function(o) {
            return this.replace(/\{([^{}]*)\}/g, function (a, b) {
                var r = o[b];
                return typeof r === 'string' || typeof r === 'number' ? r : a;
            });
        };
    }

    /**
     * Parses the GET query and returns a key-value map of the data.
     */
    if (!HTMLDocument.prototype.parseQuery) {
        HTMLDocument.prototype.parseQuery = function() {
            if (!document.location.search)
                return {};
            var params = {};
            $.each(document.location.search.substring(1).split(/&/g), function(i, token) {
                var parts = token.split(/=/, 2);
                params[parts[0]] = parts[1];
            });
            return params;
        }
    }

    // Convenience constants
    var WIN = $(window);

    // Cause <a> elems with the a-newtab class to open in a new tab.
    $('a.a-newtab').attr('target', '_BLANK');

    // Cause the navbar to expand when clicking the navbar-expand button.
    $('a.navbar-expand').click(function(e) {
        $('.navbar-links').toggleClass('navbar-expanded');
    });

    // Card grid interaction functions
    var cardsInterpolated = false;

    var cardInterpolate = () => {
        cardsInterpolated = true;
        $('.card-parent').each((ind, elem) => {
            var cols = $(elem).children('.card-col'), cards = [], i = 0, card;
            while (card = $(cols[i]).children('.card:eq(0)'), card.size() > 0) {
                cards.push(card.detach());
                if (++i >= cols.size())
                    i = 0;
            }
            cols.each((i, elem) => $(elem).children().detach());
            var col0 = cols.filter('.card-col:eq(0)');
            $.each(cards, (ind, card) => col0.append(card));
        });
    };

    var cardDeinterpolate = () => {
        cardsInterpolated = false;
        $('.card-parent').each((ind, elem) => {
            var cols = $(elem).children('.card-col'), col0 = cols.filter('.card-col:eq(0)'), cards = [];
            col0.children().each((ind, card) => cards.push($(card).detach()));
            $.each(cards, (ind, card) => $(cols[ind % cols.size()]).append(card));
        });
    };

    // Listens for when the browser window is resized.
    var onWindowResize = e => {
        if (WIN.width() > 768) {
            if (cardsInterpolated)
                cardDeinterpolate();
        } else {
            if (!cardsInterpolated)
                cardInterpolate();
        }
    };
    WIN.resize(onWindowResize);
    onWindowResize();

});

/**
 * Adds a card to a card grid.
 */
var addCard = (parent, card) => {
    if (parent.hasClass('card-parent') && card.hasClass('card')) {
        var cols = $(parent).children('.card-col'), size = 0, col;
        for (var i = 0;; i++) {
            if (i >= cols.size()) {
                col = cols.filter('.card-col:eq(0)');
                break;
            }
            col = $(cols[i]);
            var children = col.children().size();
            if (children < size)
                break;
            size = children;
        }
        col.append(card);
    }
    else
        throw 'Invalid call to addCard!';
};<commit_msg>Make addCard work on mobile environments<commit_after>/**
 * Whether the cards have been interpolated yet.
 */
var cardsInterpolated = false;

/**
 * Adds a card to a card grid.
 */
var addCard = (parent, card) => {
    if (parent.hasClass('card-parent') && card.hasClass('card')) {
        if (cardsInterpolated)
            $(parent).children('.card-col:eq(0)').append(card);
        else {
            var cols = $(parent).children('.card-col'), size = 0, col;
            for (var i = 0;; i++) {
                if (i >= cols.size()) {
                    col = cols.filter('.card-col:eq(0)');
                    break;
                }
                col = $(cols[i]);
                var children = col.children().size();
                if (children < size)
                    break;
                size = children;
            }
            col.append(card);
        }
    }
    else
        throw 'Invalid call to addCard!';
};

$(document).ready(function() {

    /**
     * Replaces tokens in a string with values in a supplied key-value map.
     */
    if (!String.prototype.supplant) {
        String.prototype.supplant = function(o) {
            return this.replace(/\{([^{}]*)\}/g, function (a, b) {
                var r = o[b];
                return typeof r === 'string' || typeof r === 'number' ? r : a;
            });
        };
    }

    /**
     * Parses the GET query and returns a key-value map of the data.
     */
    if (!HTMLDocument.prototype.parseQuery) {
        HTMLDocument.prototype.parseQuery = function() {
            if (!document.location.search)
                return {};
            var params = {};
            $.each(document.location.search.substring(1).split(/&/g), function(i, token) {
                var parts = token.split(/=/, 2);
                params[parts[0]] = parts[1];
            });
            return params;
        }
    }

    // Convenience constants
    var WIN = $(window);

    // Cause <a> elems with the a-newtab class to open in a new tab.
    $('a.a-newtab').attr('target', '_BLANK');

    // Cause the navbar to expand when clicking the navbar-expand button.
    $('a.navbar-expand').click(function(e) {
        $('.navbar-links').toggleClass('navbar-expanded');
    });

    // Card grid interaction functions
    var cardInterpolate = () => {
        cardsInterpolated = true;
        $('.card-parent').each((ind, elem) => {
            var cols = $(elem).children('.card-col'), cards = [], i = 0, card;
            while (card = $(cols[i]).children('.card:eq(0)'), card.size() > 0) {
                cards.push(card.detach());
                if (++i >= cols.size())
                    i = 0;
            }
            cols.each((i, elem) => $(elem).children().detach());
            var col0 = cols.filter('.card-col:eq(0)');
            $.each(cards, (ind, card) => col0.append(card));
        });
    };

    var cardDeinterpolate = () => {
        cardsInterpolated = false;
        $('.card-parent').each((ind, elem) => {
            var cols = $(elem).children('.card-col'), col0 = cols.filter('.card-col:eq(0)'), cards = [];
            col0.children().each((ind, card) => cards.push($(card).detach()));
            $.each(cards, (ind, card) => $(cols[ind % cols.size()]).append(card));
        });
    };

    // Listens for when the browser window is resized.
    var onWindowResize = e => {
        if (WIN.width() > 768) {
            if (cardsInterpolated)
                cardDeinterpolate();
        } else {
            if (!cardsInterpolated)
                cardInterpolate();
        }
    };
    WIN.resize(onWindowResize);
    onWindowResize();

});<|endoftext|>


<commit_before>/* If it doesn't look like there's a contest ID in the URL, show an alert, and go back one page. */
if (window.location.search.indexOf("?contest") === -1) {
	alert("Contest ID not found!");

	window.history.back();
}

/* If it doesn't look like there's an entry ID in the URL, show an alert, and go back one page. */
if (window.location.search.indexOf("&entry=") === -1) {
	alert("Entry ID not found!");

	window.history.back();
}
var selectedLvlBtn = "n/a";
var selectedCleanCodeBtn = "n/a";
var selectedCreativityBtn = "n/a";
var selectedOverallBtn = "n/a";
/* Locate the contest ID in the URL, and store it for later use. */
var contestId = window.location.href.split("?contest=")[1].split("&")[0];

/* Locate the entry ID in the URL, and store it for later use. */
var entryId = window.location.href.split("&entry=")[1];

/* The base URL for the program preview Iframe. */
var baseURL = "https://www.khanacademy.org/computer-programming/entry/{ENTRYID}/embedded?buttons=no&editor=no&author=no&embed=yes";

/* A couple elements that we'll be using later on */
var programPreview = document.querySelector(".program-preview");
var judgingPane = document.querySelector(".judging-pane");
var currentScore = document.querySelector(".current-score");
var rubricsDiv = document.querySelector(".rubrics");
currentScore.addEventListener("click", function() {
	if (currentScore.className.indexOf("hidden-data") !== -1) {
		currentScore.className = currentScore.className.replace("hidden-data", "");
	} else {
		currentScore.className += " hidden-data";
	}
	console.log(currentScore.className);
});

/* Print the contest ID that we found, to the console. */
console.log("Contest ID: " + contestId);

/* Print the entry ID that we found, to the console. */
console.log("Entry ID: " + entryId);

/* Fetch the data for this contest entry, and then use the data to build up the current page. */
Contest_Judging_System.loadEntry(contestId, entryId, function(entryData) {
	console.log("Entered loadEntry callback!");

	/* Set the text of our "program-name" heading to the name of the current entry */
	document.querySelector("#program-name").textContent = entryData.name;

	/* The following stuff is broken in Firefox. Issue reported on Khan Academy live-editor repo. */
	var programIframe = document.createElement("iframe");
	programIframe.src = baseURL.replace("{ENTRYID}", entryData.id);
	programIframe.width = 940;
	programIframe.height = 400;
	programIframe.scrolling = "no";
	programIframe.frameborder = 0;

	/* Create a div that will hold all of the elements required to show the current score for this entry */
	var currentScoreDiv = document.createElement("div");
	currentScoreDiv.className = "current-score";

	/* Create a paragraph element to display the level rubric */
	var levelRubric = document.createElement("p");
	levelRubric.textContent = "Level: " + entryData.scores.rubric.Level.avg;

	/* Create a paragraph element to display the clean code rubric */
	var cleanCodeRubric = document.createElement("p");
	cleanCodeRubric.textContent = "Clean Code: " + Math.round(entryData.scores.rubric.Clean_Code.avg);

	/* Create a paragraph element to display the creativity rubric */
	var creativityRubric = document.createElement("p");
	creativityRubric.textContent = "Creativity: " + Math.round(entryData.scores.rubric.Creativity.avg);

	/* Create a paragraph element to display the overall rubric */
	var overallRubric = document.createElement("p");
	overallRubric.textContent = "Overall: " + Math.round(entryData.scores.rubric.Overall.avg);

	/* Create all the elements we'll need for the "Level" rubric */
	var levelGroup = document.createElement("div");
	levelGroup.id = "level_group";

	var levelLabel = document.createElement("label");
	levelLabel.htmlFor = "level";
	levelLabel.textContent = "Level: ";

	var levelSelect = document.createElement("div");
	levelSelect.id = "level-btn-toolbar";
	levelSelect.className = "btn-toolbar";

	var levelSelectBtnGroup = document.createElement("div");
	levelSelectBtnGroup.className = "btn-group";
	levelSelectBtnGroup.role = "group";

	var levelSelectBtns = [ ];
	var levels = ["Beginner", "Intermediate", "Advanced"];
	for (var i = 0; i < 3; i++){
		var levelSelectButton = document.createElement("button");
		levelSelectButton.type = "button";
		levelSelectButton.id = ("lvlSelectButton" + (i + 1)).toString();
		levelSelectButton.className = "btn btn-sm btn-default";
		levelSelectButton.textContent = levels[i];
		levelSelectBtns.push(levelSelectButton);
	}

	/* Create all the elements we'll need for the "Clean_Code" rubric */
	var cleanCodeGroup = document.createElement("div");
	cleanCodeGroup.id = "clean_code_group";

	var cleanCodeLabel = document.createElement("label");
	cleanCodeLabel.htmlFor = "clean_code";
	cleanCodeLabel.textContent = "Clean Code: ";

	var cleanCodeSelect = document.createElement("div");
	cleanCodeSelect.id = "level-btn-toolbar";
	cleanCodeSelect.className = "btn-toolbar";

	var cleanCodeSelectBtnGroup = document.createElement("div");
	cleanCodeSelectBtnGroup.className = "btn-group";
	cleanCodeSelectBtnGroup.role = "group";

	var cleanCodeSelectBtns = [ ];
	for (var i = 0; i < 5; i++) {
		var cleanCodeSelectButton = document.createElement("button");
		cleanCodeSelectButton.type = "button";
		cleanCodeSelectButton.id = ("cleanCodeSelectButton" + (i + 1)).toString();
		cleanCodeSelectButton.className = "btn btn-sm btn-default";
		cleanCodeSelectButton.textContent = (i + 1).toString();
		cleanCodeSelectBtns.push(cleanCodeSelectButton);
	}

	/* Create all the elements we'll need for the "Creativity" rubric */
	var creativityGroup = document.createElement("div");
	creativityGroup.id = "creativity_group";

	var creativityLabel = document.createElement("label");
	creativityLabel.htmlFor = "creativity";
	creativityLabel.textContent = "Creativity: ";

	var creativitySelect = document.createElement("div");
	creativitySelect.id = "level-btn-toolbar";
	creativitySelect.className = "btn-toolbar";

	var creativitySelectBtnGroup = document.createElement("div");
	creativitySelectBtnGroup.className = "btn-group";
	creativitySelectBtnGroup.role = "group";

	var creativitySelectBtns = [ ];
	for (var i = 0; i < 5; i++) {
		var creativitySelectButton = document.createElement("button");
		creativitySelectButton.type = "button";
		creativitySelectButton.id = ("creativitySelectButton" + (i + 1)).toString();
		creativitySelectButton.className = "btn btn-sm btn-default";
		creativitySelectButton.textContent = (i + 1).toString();
		creativitySelectBtns.push(creativitySelectButton);
	}

	var overallGroup = document.createElement("div");
	overallGroup.id = "overall_group";

	var overallLabel = document.createElement("label");
	overallLabel.htmlFor = "overall";
	overallLabel.textContent = "Overall: ";

	var overallSelect = document.createElement("div");
	overallSelect.id = "level-btn-toolbar";
	overallSelect.className = "btn-toolbar";

	var overallSelectBtnGroup = document.createElement("div");
	overallSelectBtnGroup.className = "btn-group";
	overallSelectBtnGroup.role = "group";

	var overallSelectBtns = [ ];
	for (var i = 0; i < 5; i++) {
		var overallSelectButton = document.createElement("button");
		overallSelectButton.type = "button";
		overallSelectButton.id = ("overallSelectButton" + (i + 1)).toString();
		overallSelectButton.className = "btn btn-sm btn-default";
		overallSelectButton.textContent = (i + 1).toString();
		overallSelectBtns.push(overallSelectButton);
	}

	/* Append everything to whatever it needs to be appended to */
	for (var i = 0; i < levelSelectBtns.length; i++){
		levelSelectBtnGroup.appendChild(levelSelectBtns[i]);
	}
	levelSelect.appendChild(levelSelectBtnGroup);
	levelGroup.appendChild(levelLabel);
	levelGroup.appendChild(levelSelect);

	cleanCodeGroup.appendChild(cleanCodeLabel);
	for (var i = 0; i < cleanCodeSelectBtns.length; i++){
		cleanCodeSelectBtnGroup.appendChild(cleanCodeSelectBtns[i]);
	}
	cleanCodeSelect.appendChild(cleanCodeSelectBtnGroup);
	cleanCodeGroup.appendChild(cleanCodeSelect);

	creativityGroup.appendChild(creativityLabel);
	for (var i = 0; i < creativitySelectBtns.length; i++){
		creativitySelectBtnGroup.appendChild(creativitySelectBtns[i]);
	}
	creativitySelect.appendChild(creativitySelectBtnGroup);
	creativityGroup.appendChild(creativitySelect);

	overallGroup.appendChild(overallLabel);
	for (var i = 0; i < overallSelectBtns.length; i++){
		overallSelectBtnGroup.appendChild(overallSelectBtns[i]);
	}
	overallSelect.appendChild(overallSelectBtnGroup);
	overallGroup.appendChild(overallSelect);

	/* Append all of our judging tools to the rubrics div */
	rubricsDiv.appendChild(levelGroup);
	rubricsDiv.appendChild(cleanCodeGroup);
	rubricsDiv.appendChild(creativityGroup);
	rubricsDiv.appendChild(overallGroup);

	/* Append our program iframe to the "program-preview" div. */
	programPreview.appendChild(programIframe);

	/* Append all of the score information to the page. */
	currentScoreDiv.appendChild(levelRubric);
	currentScoreDiv.appendChild(cleanCodeRubric);
	currentScoreDiv.appendChild(creativityRubric);
	currentScoreDiv.appendChild(overallRubric);
	currentScore.appendChild(currentScoreDiv);

	/* Bind to click for Level Select */
	for (var i = 0; i < 3; i++) {
		$("#lvlSelectButton" + (i+1).toString()).click(function(event) {
			var id = event.target.id;
			if (selectedLvlBtn != "n/a" && selectedLvlBtn != id) {
				$("#" + selectedLvlBtn).removeClass("btn-success").addClass("btn-default");
			}
			selectedLvlBtn = id;
			$("#" + id).removeClass("btn-default").addClass("btn-success");
		});
	}
	for (var i = 0; i < 5; i++) {
		$("#cleanCodeSelectButton" + (i+1).toString()).click(function(event) {
			var id = event.target.id;
			if (selectedCleanCodeBtn != "n/a" && selectedCleanCodeBtn != id) {
				$("#" + selectedCleanCodeBtn).removeClass("btn-success").addClass("btn-default");
			}
			selectedCleanCodeBtn = id;
			$("#" + id).removeClass("btn-default").addClass("btn-success");
		});
	}
	for (var i = 0; i < 5; i++) {
		$("#creativitySelectButton" + (i+1).toString()).click(function(event){
			var id = event.target.id;
			if (selectedCreativityBtn != "n/a" && selectedCreativityBtn != id) {
				$("#" + selectedCreativityBtn).removeClass("btn-success").addClass("btn-default");
			}
			selectedCreativityBtn = id;
			$("#" + id).removeClass("btn-default").addClass("btn-success");
		});
	}
	for (var i = 0; i < 5; i++) {
		$("#overallSelectButton" + (i+1).toString()).click(function(event){
			var id = event.target.id;
			if (selectedOverallBtn != "n/a" && selectedOverallBtn != id){
				$("#" + selectedOverallBtn).removeClass("btn-success").addClass("btn-default");
			}
			selectedOverallBtn = id;
			$("#" + id).removeClass("btn-default").addClass("btn-success");
		});
	}
	console.log("Exiting loadEntry callback!");

});

/* Whenever we click the toggleCode button; toggle the code. */
$(".toggleCode").on("click", function() {
	var currentSrc = $("iframe").attr("src");

	if (currentSrc.indexOf("editor=yes") !== -1) {
		$("iframe").attr("src", currentSrc.replace("editor=yes", "editor=no"));
	} else {
		$("iframe").attr("src", currentSrc.replace("editor=no", "editor=yes"));
	}
});

function judgeEntry(scoreData) {
    /* This function simply judges the entry using scoreData. */
    Contest_Judging_System.judgeEntry(contestId, entryId, scoreData, function(data) {
		console.log("Submitted scores!");
	});
}

/* This bool is true iff the user has been authenticated. */
var authenticated = false;
$("#submitBtn").on("click", function() {
	console.log("Button clicked!");
	var scoreData = {};
	if(selectedLvlBtn != "n/a"&&selectedOverallBtn != "n/a"&&selectedCreativityBtn != "n/a"&&selectedCleanCodeBtn != "n/a"){
		scoreData.Level = parseInt(selectedLvlBtn.replace("lvlSelectButton",""), 10);
		scoreData.Clean_Code = parseInt(selectedCleanCodeBtn.replace("cleanCodeSelectButton",""), 10);
		scoreData.Creativity = parseInt(selectedCreativityBtn.replace("creativitySelectButton",""), 10);
		scoreData.Overall = parseInt(selectedOverallBtn.replace("overallSelectButton",""), 10);
	}else{
		alert("Please fill out all criteria.");
		return;
	}

    /* If the user hasn't been authenticated, try to authenticate them and judge the entry if they are a valid judge. */
    /* Notice that this gives them a way to be authenticated multiple times in case a valid judge messes up in logging in the first time. */
	if (!authenticated) Contest_Judging_System.tryAuthentication(function(valid) {
        authenticated = valid;
        if (valid) judgeEntry(scoreData);
        else alert("You aren't in the allowed judges list!");
    });
    /* Otherwise, if they've already been authenticated, just judge the entry. */
    else judgeEntry(scoreData);
});
<commit_msg>Cleaned more of Lokis code<commit_after>/* If it doesn't look like there's a contest ID in the URL, show an alert, and go back one page. */
if (window.location.search.indexOf("?contest") === -1) {
	alert("Contest ID not found!");

	window.history.back();
}

/* If it doesn't look like there's an entry ID in the URL, show an alert, and go back one page. */
if (window.location.search.indexOf("&entry=") === -1) {
	alert("Entry ID not found!");

	window.history.back();
}
var selectedLvlBtn = "n/a";
var selectedCleanCodeBtn = "n/a";
var selectedCreativityBtn = "n/a";
var selectedOverallBtn = "n/a";
/* Locate the contest ID in the URL, and store it for later use. */
var contestId = window.location.href.split("?contest=")[1].split("&")[0];

/* Locate the entry ID in the URL, and store it for later use. */
var entryId = window.location.href.split("&entry=")[1];

/* The base URL for the program preview Iframe. */
var baseURL = "https://www.khanacademy.org/computer-programming/entry/{ENTRYID}/embedded?buttons=no&editor=no&author=no&embed=yes";

/* A couple elements that we'll be using later on */
var programPreview = document.querySelector(".program-preview");
var judgingPane = document.querySelector(".judging-pane");
var currentScore = document.querySelector(".current-score");
var rubricsDiv = document.querySelector(".rubrics");
currentScore.addEventListener("click", function() {
	if (currentScore.className.indexOf("hidden-data") !== -1) {
		currentScore.className = currentScore.className.replace("hidden-data", "");
	} else {
		currentScore.className += " hidden-data";
	}
	console.log(currentScore.className);
});

/* Print the contest ID that we found, to the console. */
console.log("Contest ID: " + contestId);

/* Print the entry ID that we found, to the console. */
console.log("Entry ID: " + entryId);

/* Fetch the data for this contest entry, and then use the data to build up the current page. */
Contest_Judging_System.loadEntry(contestId, entryId, function(entryData) {
	console.log("Entered loadEntry callback!");

	/* Set the text of our "program-name" heading to the name of the current entry */
	document.querySelector("#program-name").textContent = entryData.name;

	/* The following stuff is broken in Firefox. Issue reported on Khan Academy live-editor repo. */
	var programIframe = document.createElement("iframe");
	programIframe.src = baseURL.replace("{ENTRYID}", entryData.id);
	programIframe.width = 940;
	programIframe.height = 400;
	programIframe.scrolling = "no";
	programIframe.frameborder = 0;

	/* Create a div that will hold all of the elements required to show the current score for this entry */
	var currentScoreDiv = document.createElement("div");
	currentScoreDiv.className = "current-score";

	/* Create a paragraph element to display the level rubric */
	var levelRubric = document.createElement("p");
	levelRubric.textContent = "Level: " + entryData.scores.rubric.Level.avg;

	/* Create a paragraph element to display the clean code rubric */
	var cleanCodeRubric = document.createElement("p");
	cleanCodeRubric.textContent = "Clean Code: " + Math.round(entryData.scores.rubric.Clean_Code.avg);

	/* Create a paragraph element to display the creativity rubric */
	var creativityRubric = document.createElement("p");
	creativityRubric.textContent = "Creativity: " + Math.round(entryData.scores.rubric.Creativity.avg);

	/* Create a paragraph element to display the overall rubric */
	var overallRubric = document.createElement("p");
	overallRubric.textContent = "Overall: " + Math.round(entryData.scores.rubric.Overall.avg);

	/* Create all the elements we'll need for the "Level" rubric */
	var levelGroup = document.createElement("div");
	levelGroup.id = "level_group";

	var levelLabel = document.createElement("label");
	levelLabel.htmlFor = "level";
	levelLabel.textContent = "Level: ";

	var levelSelect = document.createElement("div");
	levelSelect.id = "level-btn-toolbar";
	levelSelect.className = "btn-toolbar";

	var levelSelectBtnGroup = document.createElement("div");
	levelSelectBtnGroup.className = "btn-group";
	levelSelectBtnGroup.role = "group";

	var levelSelectBtns = [ ];
	var levels = ["Beginner", "Intermediate", "Advanced"];
	for (var i = 0; i < 3; i++){
		var levelSelectButton = document.createElement("button");
		levelSelectButton.type = "button";
		levelSelectButton.id = ("lvlSelectButton" + (i + 1)).toString();
		levelSelectButton.className = "btn btn-sm btn-default";
		levelSelectButton.textContent = levels[i];
		levelSelectBtns.push(levelSelectButton);
	}

	/* Create all the elements we'll need for the "Clean_Code" rubric */
	var cleanCodeGroup = document.createElement("div");
	cleanCodeGroup.id = "clean_code_group";

	var cleanCodeLabel = document.createElement("label");
	cleanCodeLabel.htmlFor = "clean_code";
	cleanCodeLabel.textContent = "Clean Code: ";

	var cleanCodeSelect = document.createElement("div");
	cleanCodeSelect.id = "level-btn-toolbar";
	cleanCodeSelect.className = "btn-toolbar";

	var cleanCodeSelectBtnGroup = document.createElement("div");
	cleanCodeSelectBtnGroup.className = "btn-group";
	cleanCodeSelectBtnGroup.role = "group";

	var cleanCodeSelectBtns = [ ];
	for (var i = 0; i < 5; i++) {
		var cleanCodeSelectButton = document.createElement("button");
		cleanCodeSelectButton.type = "button";
		cleanCodeSelectButton.id = ("cleanCodeSelectButton" + (i + 1)).toString();
		cleanCodeSelectButton.className = "btn btn-sm btn-default";
		cleanCodeSelectButton.textContent = (i + 1).toString();
		cleanCodeSelectBtns.push(cleanCodeSelectButton);
	}

	/* Create all the elements we'll need for the "Creativity" rubric */
	var creativityGroup = document.createElement("div");
	creativityGroup.id = "creativity_group";

	var creativityLabel = document.createElement("label");
	creativityLabel.htmlFor = "creativity";
	creativityLabel.textContent = "Creativity: ";

	var creativitySelect = document.createElement("div");
	creativitySelect.id = "level-btn-toolbar";
	creativitySelect.className = "btn-toolbar";

	var creativitySelectBtnGroup = document.createElement("div");
	creativitySelectBtnGroup.className = "btn-group";
	creativitySelectBtnGroup.role = "group";

	var creativitySelectBtns = [ ];
	for (var i = 0; i < 5; i++) {
		var creativitySelectButton = document.createElement("button");
		creativitySelectButton.type = "button";
		creativitySelectButton.id = ("creativitySelectButton" + (i + 1)).toString();
		creativitySelectButton.className = "btn btn-sm btn-default";
		creativitySelectButton.textContent = (i + 1).toString();
		creativitySelectBtns.push(creativitySelectButton);
	}

	var overallGroup = document.createElement("div");
	overallGroup.id = "overall_group";

	var overallLabel = document.createElement("label");
	overallLabel.htmlFor = "overall";
	overallLabel.textContent = "Overall: ";

	var overallSelect = document.createElement("div");
	overallSelect.id = "level-btn-toolbar";
	overallSelect.className = "btn-toolbar";

	var overallSelectBtnGroup = document.createElement("div");
	overallSelectBtnGroup.className = "btn-group";
	overallSelectBtnGroup.role = "group";

	var overallSelectBtns = [ ];
	for (var i = 0; i < 5; i++) {
		var overallSelectButton = document.createElement("button");
		overallSelectButton.type = "button";
		overallSelectButton.id = ("overallSelectButton" + (i + 1)).toString();
		overallSelectButton.className = "btn btn-sm btn-default";
		overallSelectButton.textContent = (i + 1).toString();
		overallSelectBtns.push(overallSelectButton);
	}

	/* Append everything to whatever it needs to be appended to */
	for (var i = 0; i < levelSelectBtns.length; i++){
		levelSelectBtnGroup.appendChild(levelSelectBtns[i]);
	}
	levelSelect.appendChild(levelSelectBtnGroup);
	levelGroup.appendChild(levelLabel);
	levelGroup.appendChild(levelSelect);

	cleanCodeGroup.appendChild(cleanCodeLabel);
	for (var i = 0; i < cleanCodeSelectBtns.length; i++){
		cleanCodeSelectBtnGroup.appendChild(cleanCodeSelectBtns[i]);
	}
	cleanCodeSelect.appendChild(cleanCodeSelectBtnGroup);
	cleanCodeGroup.appendChild(cleanCodeSelect);

	creativityGroup.appendChild(creativityLabel);
	for (var i = 0; i < creativitySelectBtns.length; i++){
		creativitySelectBtnGroup.appendChild(creativitySelectBtns[i]);
	}
	creativitySelect.appendChild(creativitySelectBtnGroup);
	creativityGroup.appendChild(creativitySelect);

	overallGroup.appendChild(overallLabel);
	for (var i = 0; i < overallSelectBtns.length; i++){
		overallSelectBtnGroup.appendChild(overallSelectBtns[i]);
	}
	overallSelect.appendChild(overallSelectBtnGroup);
	overallGroup.appendChild(overallSelect);

	/* Append all of our judging tools to the rubrics div */
	rubricsDiv.appendChild(levelGroup);
	rubricsDiv.appendChild(cleanCodeGroup);
	rubricsDiv.appendChild(creativityGroup);
	rubricsDiv.appendChild(overallGroup);

	/* Append our program iframe to the "program-preview" div. */
	programPreview.appendChild(programIframe);

	/* Append all of the score information to the page. */
	currentScoreDiv.appendChild(levelRubric);
	currentScoreDiv.appendChild(cleanCodeRubric);
	currentScoreDiv.appendChild(creativityRubric);
	currentScoreDiv.appendChild(overallRubric);
	currentScore.appendChild(currentScoreDiv);

	/* Bind to click for Level Select */
	for (var i = 0; i < 3; i++) {
		$("#lvlSelectButton" + (i+1).toString()).click(function(event) {
			var id = event.target.id;
			if (selectedLvlBtn != "n/a" && selectedLvlBtn != id) {
				$("#" + selectedLvlBtn).removeClass("btn-success").addClass("btn-default");
			}
			selectedLvlBtn = id;
			$("#" + id).removeClass("btn-default").addClass("btn-success");
		});
	}
	for (var i = 0; i < 5; i++) {
		$("#cleanCodeSelectButton" + (i+1).toString()).click(function(event) {
			var id = event.target.id;
			if (selectedCleanCodeBtn != "n/a" && selectedCleanCodeBtn != id) {
				$("#" + selectedCleanCodeBtn).removeClass("btn-success").addClass("btn-default");
			}
			selectedCleanCodeBtn = id;
			$("#" + id).removeClass("btn-default").addClass("btn-success");
		});
	}
	for (var i = 0; i < 5; i++) {
		$("#creativitySelectButton" + (i+1).toString()).click(function(event){
			var id = event.target.id;
			if (selectedCreativityBtn != "n/a" && selectedCreativityBtn != id) {
				$("#" + selectedCreativityBtn).removeClass("btn-success").addClass("btn-default");
			}
			selectedCreativityBtn = id;
			$("#" + id).removeClass("btn-default").addClass("btn-success");
		});
	}
	for (var i = 0; i < 5; i++) {
		$("#overallSelectButton" + (i+1).toString()).click(function(event){
			var id = event.target.id;
			if (selectedOverallBtn != "n/a" && selectedOverallBtn != id){
				$("#" + selectedOverallBtn).removeClass("btn-success").addClass("btn-default");
			}
			selectedOverallBtn = id;
			$("#" + id).removeClass("btn-default").addClass("btn-success");
		});
	}
	console.log("Exiting loadEntry callback!");

});

/* Whenever we click the toggleCode button; toggle the code. */
$(".toggleCode").on("click", function() {
	var currentSrc = $("iframe").attr("src");

	if (currentSrc.indexOf("editor=yes") !== -1) {
		$("iframe").attr("src", currentSrc.replace("editor=yes", "editor=no"));
	} else {
		$("iframe").attr("src", currentSrc.replace("editor=no", "editor=yes"));
	}
});

function judgeEntry(scoreData) {
    /* This function simply judges the entry using scoreData. */
    Contest_Judging_System.judgeEntry(contestId, entryId, scoreData, function(data) {
		console.log("Submitted scores!");
	});
}

/* This bool is true iff the user has been authenticated. */
var authenticated = false;
$("#submitBtn").on("click", function() {
	console.log("Button clicked!");
	var scoreData = { };
	if(selectedLvlBtn != "n/a" && selectedOverallBtn != "n/a" && selectedCreativityBtn != "n/a" && selectedCleanCodeBtn != "n/a"){
		scoreData.Level = parseInt(selectedLvlBtn.replace("lvlSelectButton", ""), 10);
		scoreData.Clean_Code = parseInt(selectedCleanCodeBtn.replace("cleanCodeSelectButton", ""), 10);
		scoreData.Creativity = parseInt(selectedCreativityBtn.replace("creativitySelectButton", ""), 10);
		scoreData.Overall = parseInt(selectedOverallBtn.replace("overallSelectButton", ""), 10);
	}else{
		alert("Please fill out all criteria.");
		return;
	}

    /* If the user hasn't been authenticated, try to authenticate them and judge the entry if they are a valid judge. */
    /* Notice that this gives them a way to be authenticated multiple times in case a valid judge messes up in logging in the first time. */
	if (!authenticated) Contest_Judging_System.tryAuthentication(function(valid) {
        authenticated = valid;
        if (valid) judgeEntry(scoreData);
        else alert("You aren't in the allowed judges list!");
    });
    /* Otherwise, if they've already been authenticated, just judge the entry. */
    else judgeEntry(scoreData);
});
<|endoftext|>


<commit_before>/* If it doesn't look like there's a contest ID in the URL, show an alert, and go back one page. */
if (window.location.search.indexOf("?contest") === -1) {
	alert("Contest ID not found!");

	window.history.back();
}

/* If it doesn't look like there's an entry ID in the URL, show an alert, and go back one page. */
if (window.location.search.indexOf("&entry=") === -1) {
	alert("Entry ID not found!");

	window.history.back();
}

/* The id of the button selected for "Level" */
var selectedLvlBtn = "n/a";
/* The score for this entry */
var scoreData = {
    Level: null,
    Clean_Code: 1,
    Creativity: 1,
    Overall: 1
};

/* Locate the contest ID in the URL, and store it for later use. */
var contestId = window.location.href.split("?contest=")[1].split("&")[0];

/* Locate the entry ID in the URL, and store it for later use. */
var entryId = window.location.href.split("&entry=")[1];

/* The base URL for the program preview Iframe. */
var baseURL = "https://www.khanacademy.org/computer-programming/entry/{ENTRYID}/embedded?buttons=no&editor=yes&author=no&embed=yes";

/* A couple elements that we'll be using later on */
var programPreview = document.querySelector(".program-preview");
var judgingPane = document.querySelector(".judging-pane");
var currentScore = document.querySelector(".current-score");
var rubricsDiv = document.querySelector(".rubrics");

/* Print the contest ID that we found, to the console. */
console.log("Contest ID: " + contestId);

/* Print the entry ID that we found, to the console. */
console.log("Entry ID: " + entryId);

/* The number of lines of code of this project */
var linesOfCode;
/* Send an AJAX request to the KA API for this program. */
$.ajax({
    type: "GET",
    url: "https://www.khanacademy.org/api/internal/scratchpads/"+entryId,
    async: true,
    complete: function(response) {
        /* Calculate the number of lines of code in this entry. */
        linesOfCode = response.responseJSON.revision.code.split("\n").length;
        /* Insert it into where it should be in the document. */
        document.querySelector("#program-info").textContent = linesOfCode+" lines of code";
        /* Call loadEntry() */
        loadEntry();
    }
});

function loadEntry() {
    /* Fetch the data for this contest entry, and then use the data to build up the current page. */
    /* TODO: Fetch all rubrics to automate the min/max/key fetching. */
    Contest_Judging_System.loadEntry(contestId, entryId, function(entryData) {
        console.log("Entered loadEntry callback!");

        /* Set the text of our "program-name" heading to the name of the current entry */
        document.querySelector("#program-name").textContent = entryData.name;

        /* The following stuff is broken in Firefox. Issue reported on Khan Academy live-editor repo. */
        var programIframe = document.createElement("iframe");
        programIframe.src = baseURL.replace("{ENTRYID}", entryData.id);
        programIframe.width = 940;
        programIframe.height = 400;
        programIframe.scrolling = "no";
        programIframe.frameborder = 0;

        /* Wrap all this code in a callback to our getRubrics function, that way we can get more data from the rubrics */
        Contest_Judging_System.getRubrics(function(rubrics) {
            /* Create a div that will hold all of the elements required to show the current score for this entry */
            var currentScoreDiv = document.querySelector(".current-score");

            /* Create a paragraph element to display the level rubric */
            var levelRubric = document.createElement("p");
            levelRubric.textContent = "Level: " + rubrics["Level"].keys[entryData.scores.rubric.Level.avg];

            /* Create a paragraph element to display the clean code rubric */
            var cleanCodeRubric = document.createElement("p");
            cleanCodeRubric.textContent = "Clean Code: " + Math.round(entryData.scores.rubric.Clean_Code.avg) + " out of " + rubrics["Clean_Code"].max;

            /* Create a paragraph element to display the creativity rubric */
            var creativityRubric = document.createElement("p");
            creativityRubric.textContent = "Creativity: " + Math.round(entryData.scores.rubric.Creativity.avg) + " out of " + rubrics["Creativity"].max;

            /* Create a paragraph element to display the overall rubric */
            var overallRubric = document.createElement("p");
            overallRubric.textContent = "Overall: " + Math.round(entryData.scores.rubric.Overall.avg) + " out of " + rubrics["Overall"].max;

            /* Create all the elements we'll need for the "Level" rubric */
            var levelGroup = document.createElement("div");
            levelGroup.id = "level_group";

            /* Label for "Level" */
            var levelLabel = document.createElement("label");
            levelLabel.htmlFor = "level";
            levelLabel.textContent = "Level: ";

            /* Container for levelSelectBtnGroup */
            var levelSelect = document.createElement("div");
            levelSelect.id = "level-btn-toolbar";
            levelSelect.className = "btn-toolbar";

            /* Container for levelSelectBtns */
            var levelSelectBtnGroup = document.createElement("div");
            levelSelectBtnGroup.className = "btn-group";
            levelSelectBtnGroup.role = "group";

            /* All buttons for "Level" */
            var levelSelectBtns = [ ];
            /* All levels */
            var levels = ["Beginner", "Intermediate", "Advanced"];
            /* Create all buttons and push into levelSelectBtns */
            for (var i = 0; i < levels.length; i++){
                var levelSelectButton = document.createElement("button");
                levelSelectButton.type = "button";
                levelSelectButton.id = ("lvlSelectButton" + (i + 1)).toString();
                levelSelectButton.className = "btn btn-sm btn-default";
                levelSelectButton.textContent = levels[i];
                levelSelectBtns.push(levelSelectButton);
            }

            /* Create all the elements we'll need for the "Clean_Code" rubric */
            var cleanCodeGroup = document.createElement("div");
            cleanCodeGroup.id = "clean_code_group";

            /* Label for "Clean_Code" */
            var cleanCodeLabel = document.createElement("label");
            cleanCodeLabel.htmlFor = "clean_code";
            cleanCodeLabel.textContent = "Clean Code: 1";

            /* Slider */
            var cleanCodeSlider = document.createElement("div");
            cleanCodeSlider.className = "slider1to5";
            cleanCodeSlider.role = "slider";
            /* Use jQuery UI to create slider */
            $(cleanCodeSlider).slider({
                range: "max",
                min: 1,
                max: 5,
                value: 1,
                slide: function(event, ui) {
                    /* Tell the score in cleanCodeLabel when the slider changes. */
                    cleanCodeLabel.textContent = "Clean Code: "+ui.value;
                    /* Set scoreData */
                    scoreData.Clean_Code = ui.value;
                }
            });

            /* Create all the elements we'll need for the "Creativity" rubric */
            var creativityGroup = document.createElement("div");
            creativityGroup.id = "creativity_group";

            /* Label for "Creativity" */
            var creativityLabel = document.createElement("label");
            creativityLabel.htmlFor = "creativity";
            creativityLabel.textContent = "Creativity: 1";

            /* Slider */
            var creativitySlider = document.createElement("div");
            creativitySlider.className = "slider1to5";
            creativitySlider.role = "slider";
            /* Use jQuery UI to create slider */
            $(creativitySlider).slider({
                range: "max",
                min: 1,
                max: 5,
                value: 1,
                slide: function(event, ui) {
                    /* Tell the score in creativityLabel when the slider changes. */
                    creativityLabel.textContent = "Creativity: "+ui.value;
                    /* Set scoreData */
                    scoreData.Creativity = ui.value;
                }
            });

            /* Create all the elements we'll need for the "Overall" rubric */
            var overallGroup = document.createElement("div");
            overallGroup.id = "overall_group";

            /* Label for "Overall" */
            var overallLabel = document.createElement("label");
            overallLabel.htmlFor = "overall";
            overallLabel.textContent = "Overall: 1";

            /* Slider */
            var overallSlider = document.createElement("div");
            overallSlider.className = "slider1to5";
            overallSlider.role = "slider";
            $(overallSlider).slider({
                range: "max",
                min: 1,
                max: 5,
                value: 1,
                slide: function(event, ui) {
                    /* Tell the score in overallLabel when the slider changes. */
                    overallLabel.textContent = "Overall: "+ui.value;
                    /* Set scoreData */
                    scoreData.Overall = ui.value;
                }
            });

            /* Append everything to whatever it needs to be appended to */
            for (var i = 0; i < levelSelectBtns.length; i++){
                levelSelectBtnGroup.appendChild(levelSelectBtns[i]);
            }
            levelSelect.appendChild(levelSelectBtnGroup);
            levelGroup.appendChild(levelLabel);
            levelGroup.appendChild(levelSelect);

            cleanCodeGroup.appendChild(cleanCodeLabel);
            cleanCodeGroup.appendChild(cleanCodeSlider);

            creativityGroup.appendChild(creativityLabel);
            creativityGroup.appendChild(creativitySlider);

            overallGroup.appendChild(overallLabel);
            overallGroup.appendChild(overallSlider);

            /* Append all of our judging tools to the rubrics div */
            rubricsDiv.appendChild(levelGroup);
            rubricsDiv.appendChild(cleanCodeGroup);
            rubricsDiv.appendChild(creativityGroup);
            rubricsDiv.appendChild(overallGroup);

            /* Append our program iframe to the "program-preview" div. */
            programPreview.appendChild(programIframe);

            /* Append all of the score information to the page. */
            currentScoreDiv.appendChild(levelRubric);
            currentScoreDiv.appendChild(cleanCodeRubric);
            currentScoreDiv.appendChild(creativityRubric);
            currentScoreDiv.appendChild(overallRubric);

            /* Set the widths of our sliders to 30% */
            $(".slider1to5").width("30%");

            /* Bind to click for Level Select */
            for (var i = 0; i < 3; i++) {
                $("#lvlSelectButton" + (i + 1).toString()).click(function(event) {
                    var id = event.target.id;
                    /* Unselect previously selected button */
                    if (selectedLvlBtn != "n/a" && selectedLvlBtn != id) {
                        $("#" + selectedLvlBtn).removeClass("btn-success").addClass("btn-default");
                    }
                    /* Set selectedLvlBtn and scoreData.Level */
                    selectedLvlBtn = id;
                    scoreData.Level = parseInt(selectedLvlBtn.replace("lvlSelectButton", ""), 10);
                    /* Select the selected button */
                    $("#" + id).removeClass("btn-default").addClass("btn-success");
                });
            }
        });

        console.log("Exiting loadEntry callback!");
    });
}

/* Whenever we click the toggleCode button; toggle the code. */
$(".toggleCode").on("click", function() {
	var currentSrc = $("iframe").attr("src");

	if (currentSrc.indexOf("editor=yes") !== -1) {
		$("iframe").attr("src", currentSrc.replace("editor=yes", "editor=no"));
	} else {
		$("iframe").attr("src", currentSrc.replace("editor=no", "editor=yes"));
	}
});

function judgeEntry(scoreData) {
    /* This function simply judges the entry using scoreData. */
    Contest_Judging_System.judgeEntry(contestId, entryId, scoreData, function(data) {
		console.log("Submitted scores!");
	});
}

$(".viewOnKA").on("click", function() {
	var promptMsg = prompt("By visiting the following page, you're exposing yourself to information that could bias your judging. If you agree to not let information you see on Khan Academy bias your judging, please type \"I agree\", otherwise, close this prompt.");
	if (promptMsg == "I agree") {
		window.open("https://www.khanacademy.org/computer-programming/entry/" + entryId);
	}
});

/* This bool is true if the user has been authenticated. */
var authenticated = false;
$("#submitBtn").on("click", function() {
    /* Tell the user to fill out all criteria if they haven't filled out the Level. */
    if (!scoreData.Level) {
		alert("Please fill out all criteria.");
		return;
	}
    console.log(scoreData);

    /* If the user hasn't been authenticated, try to authenticate them and judge the entry if they are a valid judge. */
    /* Notice that this gives them a way to be authenticated multiple times in case a valid judge messes up in logging in the first time. */
	if (!authenticated) Contest_Judging_System.tryAuthentication(function(valid) {
        authenticated = valid;
        if (valid) judgeEntry(scoreData);
        else alert("You aren't in the allowed judges list!");
    });
    /* Otherwise, if they've already been authenticated, just judge the entry. */
    else judgeEntry(scoreData);
});<commit_msg>Fixed a minor bug<commit_after>/* If it doesn't look like there's a contest ID in the URL, show an alert, and go back one page. */
if (window.location.search.indexOf("?contest") === -1) {
	alert("Contest ID not found!");

	window.history.back();
}

/* If it doesn't look like there's an entry ID in the URL, show an alert, and go back one page. */
if (window.location.search.indexOf("&entry=") === -1) {
	alert("Entry ID not found!");

	window.history.back();
}

/* The id of the button selected for "Level" */
var selectedLvlBtn = "n/a";
/* The score for this entry */
var scoreData = {
    Level: null,
    Clean_Code: 1,
    Creativity: 1,
    Overall: 1
};

/* Locate the contest ID in the URL, and store it for later use. */
var contestId = window.location.href.split("?contest=")[1].split("&")[0];

/* Locate the entry ID in the URL, and store it for later use. */
var entryId = window.location.href.split("&entry=")[1];

/* The base URL for the program preview Iframe. */
var baseURL = "https://www.khanacademy.org/computer-programming/entry/{ENTRYID}/embedded?buttons=no&editor=yes&author=no&embed=yes";

/* A couple elements that we'll be using later on */
var programPreview = document.querySelector(".program-preview");
var judgingPane = document.querySelector(".judging-pane");
var currentScore = document.querySelector(".current-score");
var rubricsDiv = document.querySelector(".rubrics");

/* Print the contest ID that we found, to the console. */
console.log("Contest ID: " + contestId);

/* Print the entry ID that we found, to the console. */
console.log("Entry ID: " + entryId);

/* The number of lines of code of this project */
var linesOfCode;
/* Send an AJAX request to the KA API for this program. */
$.ajax({
    type: "GET",
    url: "https://www.khanacademy.org/api/internal/scratchpads/"+entryId,
    async: true,
    complete: function(response) {
        /* Calculate the number of lines of code in this entry. */
        linesOfCode = response.responseJSON.revision.code.split("\n").length;
        /* Insert it into where it should be in the document. */
        document.querySelector("#program-info").textContent = linesOfCode+" lines of code";
        /* Call loadEntry() */
        loadEntry();
    }
});

function loadEntry() {
    /* Fetch the data for this contest entry, and then use the data to build up the current page. */
    /* TODO: Fetch all rubrics to automate the min/max/key fetching. */
    Contest_Judging_System.loadEntry(contestId, entryId, function(entryData) {
        console.log("Entered loadEntry callback!");

        /* Set the text of our "program-name" heading to the name of the current entry */
        document.querySelector("#program-name").textContent = entryData.name;

        /* The following stuff is broken in Firefox. Issue reported on Khan Academy live-editor repo. */
        var programIframe = document.createElement("iframe");
        programIframe.src = baseURL.replace("{ENTRYID}", entryData.id);
        programIframe.width = 940;
        programIframe.height = 400;
        programIframe.scrolling = "no";
        programIframe.frameborder = 0;

        /* Wrap all this code in a callback to our getRubrics function, that way we can get more data from the rubrics */
        Contest_Judging_System.getRubrics(function(rubrics) {
            /* Create a div that will hold all of the elements required to show the current score for this entry */
            var currentScoreDiv = document.querySelector(".current-score");

            /* Create a paragraph element to display the level rubric */
            var levelRubric = document.createElement("p");
            levelRubric.textContent = "Level: " + rubrics["Level"].keys[entryData.scores.rubric.Level.avg];

            /* Create a paragraph element to display the clean code rubric */
            var cleanCodeRubric = document.createElement("p");
            cleanCodeRubric.textContent = "Clean Code: " + Math.round(entryData.scores.rubric.Clean_Code.avg) + " out of " + rubrics["Clean_Code"].max;

            /* Create a paragraph element to display the creativity rubric */
            var creativityRubric = document.createElement("p");
            creativityRubric.textContent = "Creativity: " + Math.round(entryData.scores.rubric.Creativity.avg) + " out of " + rubrics["Creativity"].max;

            /* Create a paragraph element to display the overall rubric */
            var overallRubric = document.createElement("p");
            overallRubric.textContent = "Overall: " + Math.round(entryData.scores.rubric.Overall.avg) + " out of " + rubrics["Overall"].max;

            /* Create all the elements we'll need for the "Level" rubric */
            var levelGroup = document.createElement("div");
            levelGroup.id = "level_group";

            /* Label for "Level" */
            var levelLabel = document.createElement("label");
            levelLabel.htmlFor = "level";
            levelLabel.textContent = "Level: ";

            /* Container for levelSelectBtnGroup */
            var levelSelect = document.createElement("div");
            levelSelect.id = "level-btn-toolbar";
            levelSelect.className = "btn-toolbar";

            /* Container for levelSelectBtns */
            var levelSelectBtnGroup = document.createElement("div");
            levelSelectBtnGroup.className = "btn-group";
            levelSelectBtnGroup.role = "group";

            /* All buttons for "Level" */
            var levelSelectBtns = [ ];
            /* All levels */
            var levels = ["Unknown", "Beginner", "Intermediate", "Advanced"];
            /* Create all buttons and push into levelSelectBtns */
            for (var i = 0; i < levels.length; i++){
                var levelSelectButton = document.createElement("button");
                levelSelectButton.type = "button";
                levelSelectButton.id = ("lvlSelectButton" + (i + 1)).toString();
                levelSelectButton.className = "btn btn-sm btn-default";
                levelSelectButton.textContent = levels[i];
                levelSelectBtns.push(levelSelectButton);
            }

            /* Create all the elements we'll need for the "Clean_Code" rubric */
            var cleanCodeGroup = document.createElement("div");
            cleanCodeGroup.id = "clean_code_group";

            /* Label for "Clean_Code" */
            var cleanCodeLabel = document.createElement("label");
            cleanCodeLabel.htmlFor = "clean_code";
            cleanCodeLabel.textContent = "Clean Code: 1";

            /* Slider */
            var cleanCodeSlider = document.createElement("div");
            cleanCodeSlider.className = "slider1to5";
            cleanCodeSlider.role = "slider";
            /* Use jQuery UI to create slider */
            $(cleanCodeSlider).slider({
                range: "max",
                min: 1,
                max: 5,
                value: 1,
                slide: function(event, ui) {
                    /* Tell the score in cleanCodeLabel when the slider changes. */
                    cleanCodeLabel.textContent = "Clean Code: "+ui.value;
                    /* Set scoreData */
                    scoreData.Clean_Code = ui.value;
                }
            });

            /* Create all the elements we'll need for the "Creativity" rubric */
            var creativityGroup = document.createElement("div");
            creativityGroup.id = "creativity_group";

            /* Label for "Creativity" */
            var creativityLabel = document.createElement("label");
            creativityLabel.htmlFor = "creativity";
            creativityLabel.textContent = "Creativity: 1";

            /* Slider */
            var creativitySlider = document.createElement("div");
            creativitySlider.className = "slider1to5";
            creativitySlider.role = "slider";
            /* Use jQuery UI to create slider */
            $(creativitySlider).slider({
                range: "max",
                min: 1,
                max: 5,
                value: 1,
                slide: function(event, ui) {
                    /* Tell the score in creativityLabel when the slider changes. */
                    creativityLabel.textContent = "Creativity: "+ui.value;
                    /* Set scoreData */
                    scoreData.Creativity = ui.value;
                }
            });

            /* Create all the elements we'll need for the "Overall" rubric */
            var overallGroup = document.createElement("div");
            overallGroup.id = "overall_group";

            /* Label for "Overall" */
            var overallLabel = document.createElement("label");
            overallLabel.htmlFor = "overall";
            overallLabel.textContent = "Overall: 1";

            /* Slider */
            var overallSlider = document.createElement("div");
            overallSlider.className = "slider1to5";
            overallSlider.role = "slider";
            $(overallSlider).slider({
                range: "max",
                min: 1,
                max: 5,
                value: 1,
                slide: function(event, ui) {
                    /* Tell the score in overallLabel when the slider changes. */
                    overallLabel.textContent = "Overall: "+ui.value;
                    /* Set scoreData */
                    scoreData.Overall = ui.value;
                }
            });

            /* Append everything to whatever it needs to be appended to */
            for (var i = 0; i < levelSelectBtns.length; i++){
                levelSelectBtnGroup.appendChild(levelSelectBtns[i]);
            }
            levelSelect.appendChild(levelSelectBtnGroup);
            levelGroup.appendChild(levelLabel);
            levelGroup.appendChild(levelSelect);

            cleanCodeGroup.appendChild(cleanCodeLabel);
            cleanCodeGroup.appendChild(cleanCodeSlider);

            creativityGroup.appendChild(creativityLabel);
            creativityGroup.appendChild(creativitySlider);

            overallGroup.appendChild(overallLabel);
            overallGroup.appendChild(overallSlider);

            /* Append all of our judging tools to the rubrics div */
            rubricsDiv.appendChild(levelGroup);
            rubricsDiv.appendChild(cleanCodeGroup);
            rubricsDiv.appendChild(creativityGroup);
            rubricsDiv.appendChild(overallGroup);

            /* Append our program iframe to the "program-preview" div. */
            programPreview.appendChild(programIframe);

            /* Append all of the score information to the page. */
            currentScoreDiv.appendChild(levelRubric);
            currentScoreDiv.appendChild(cleanCodeRubric);
            currentScoreDiv.appendChild(creativityRubric);
            currentScoreDiv.appendChild(overallRubric);

            /* Set the widths of our sliders to 30% */
            $(".slider1to5").width("30%");

            /* Bind to click for Level Select */
            for (var i = 0; i < levels.length; i++) {
                $("#lvlSelectButton" + (i + 1).toString()).click(function(event) {
                    var id = event.target.id;
                    /* Unselect previously selected button */
                    if (selectedLvlBtn != "n/a" && selectedLvlBtn != id) {
                        $("#" + selectedLvlBtn).removeClass("btn-success").addClass("btn-default");
                    }
                    /* Set selectedLvlBtn and scoreData.Level */
                    selectedLvlBtn = id;
                    scoreData.Level = parseInt(selectedLvlBtn.replace("lvlSelectButton", ""), 10);
                    /* Select the selected button */
                    $("#" + id).removeClass("btn-default").addClass("btn-success");
                });
            }
        });

        console.log("Exiting loadEntry callback!");
    });
}

/* Whenever we click the toggleCode button; toggle the code. */
$(".toggleCode").on("click", function() {
	var currentSrc = $("iframe").attr("src");

	if (currentSrc.indexOf("editor=yes") !== -1) {
		$("iframe").attr("src", currentSrc.replace("editor=yes", "editor=no"));
	} else {
		$("iframe").attr("src", currentSrc.replace("editor=no", "editor=yes"));
	}
});

function judgeEntry(scoreData) {
    /* This function simply judges the entry using scoreData. */
    Contest_Judging_System.judgeEntry(contestId, entryId, scoreData, function(data) {
		console.log("Submitted scores!");
	});
}

$(".viewOnKA").on("click", function() {
	var promptMsg = prompt("By visiting the following page, you're exposing yourself to information that could bias your judging. If you agree to not let information you see on Khan Academy bias your judging, please type \"I agree\", otherwise, close this prompt.");
	if (promptMsg == "I agree") {
		window.open("https://www.khanacademy.org/computer-programming/entry/" + entryId);
	}
});

/* This bool is true if the user has been authenticated. */
var authenticated = false;
$("#submitBtn").on("click", function() {
    /* Tell the user to fill out all criteria if they haven't filled out the Level. */
    if (!scoreData.Level) {
		alert("Please fill out all criteria.");
		return;
	}
    console.log(scoreData);

    /* If the user hasn't been authenticated, try to authenticate them and judge the entry if they are a valid judge. */
    /* Notice that this gives them a way to be authenticated multiple times in case a valid judge messes up in logging in the first time. */
	if (!authenticated) Contest_Judging_System.tryAuthentication(function(valid) {
        authenticated = valid;
        if (valid) judgeEntry(scoreData);
        else alert("You aren't in the allowed judges list!");
    });
    /* Otherwise, if they've already been authenticated, just judge the entry. */
    else judgeEntry(scoreData);
});<|endoftext|>


<commit_before>"use strict";

const prerender = require("prerender");

const server = prerender({
    chromeFlags: ["--no-sandbox", "--headless", "--disable-gpu", "--remote-debugging-port=9222", "--hide-scrollbars"],
});

server.start();
<commit_msg>Improved renderer configuration<commit_after>"use strict";

const prerender = require("prerender");

const server = prerender({
    chromeFlags: ["--no-sandbox", "--headless", "--disable-gpu", "--remote-debugging-port=9222", "--hide-scrollbars"],
});

server.use(prerender.sendPrerenderHeader());
server.use(prerender.removeScriptTags());
server.use(prerender.httpHeaders());

server.start();
<|endoftext|>


<commit_before><commit_msg>lab - jeager link on Video<commit_after><|endoftext|>


<commit_before><commit_msg>add save/edit button switch for eval forms<commit_after><|endoftext|>


<commit_before>gpf.require.define({
    Tile: "tile.js",
    dom: "../dom.js",
    config: "../../tmp/config.json"

}, function (require) {
    "use strict";

    var HTTP_NOTFOUND = 404,
        dom = require.dom,
        config = require.config;

    return gpf.define({
        $class: "Hosts",
        $extend: require.Tile,

        constructor: function () {
            this.$super("hosts", "Hosts");
            this._setGruntCommand("detectSelenium", "Detect selenium");
        },

        getDynamicContent: function () {
            return gpf.http.get("/fs/test/legacy")
                .then(function (response) {
                    if (response.status === HTTP_NOTFOUND) {
                        return [];
                    }
                    return JSON.parse(response.responseText);
                })
                .then(function (legacyFolderContent) {
                    return [
                        dom.label({"for": "hostsVersion"}, "Version: "),
                        dom.select({id: "hostsVersion"}, [
                            dom.optgroup({label: "Current"}, [
                                dom.option({value: "Verbose"}, "source"),
                                dom.option({value: "Debug"}, "debug"),
                                dom.option({value: "Release"}, "release")
                            ]),
                            dom.optgroup({label: "Legacy"}, legacyFolderContent
                                .filter(function (name) {
                                    return name !== "legacy.json";
                                })
                                .map(function (name) {
                                    var version = (/\d+\.\d+\.\d+/).exec(name).toString();
                                    return dom.option({value: "Legacy:" + version}, version);
                                })
                            )
                        ]),
                        dom.ul({id: "hostsNames"}, Object.keys(config.browsers)
                            .concat(["node", "phantom", "nodewscript"])
                            .concat(["rhino"].filter(function () {
                                return config.host.java;
                            }))
                            .concat(["nashorn"].filter(function () {
                                return config.host.nashorn;
                            }))
                            .concat(["wscript"].filter(function () {
                                return config.host.wscript;
                            }))
                            .sort()
                            .map(function (name) {
                                return dom.li({id: "host-" + name, link: "host"}, name);
                            })
                        )
                    ];
                });
        }

    });

});
<commit_msg>adds chakra (#305)<commit_after>gpf.require.define({
    Tile: "tile.js",
    dom: "../dom.js",
    config: "../../tmp/config.json"

}, function (require) {
    "use strict";

    var HTTP_NOTFOUND = 404,
        dom = require.dom,
        config = require.config;

    return gpf.define({
        $class: "Hosts",
        $extend: require.Tile,

        constructor: function () {
            this.$super("hosts", "Hosts");
            this._setGruntCommand("detectSelenium", "Detect selenium");
        },

        getDynamicContent: function () {
            return gpf.http.get("/fs/test/legacy")
                .then(function (response) {
                    if (response.status === HTTP_NOTFOUND) {
                        return [];
                    }
                    return JSON.parse(response.responseText);
                })
                .then(function (legacyFolderContent) {
                    return [
                        dom.label({"for": "hostsVersion"}, "Version: "),
                        dom.select({id: "hostsVersion"}, [
                            dom.optgroup({label: "Current"}, [
                                dom.option({value: "Verbose"}, "source"),
                                dom.option({value: "Debug"}, "debug"),
                                dom.option({value: "Release"}, "release")
                            ]),
                            dom.optgroup({label: "Legacy"}, legacyFolderContent
                                .filter(function (name) {
                                    return name !== "legacy.json";
                                })
                                .map(function (name) {
                                    var version = (/\d+\.\d+\.\d+/).exec(name).toString();
                                    return dom.option({value: "Legacy:" + version}, version);
                                })
                            )
                        ]),
                        dom.ul({id: "hostsNames"}, Object.keys(config.browsers)
                            .concat(["node", "phantom", "nodewscript"])
                            .concat(["rhino"].filter(function () {
                                return config.host.java;
                            }))
                            .concat(["nashorn"].filter(function () {
                                return config.host.nashorn;
                            }))
                            .concat(["wscript", "iescript"].filter(function () {
                                return config.host.wscript;
                            }))
                            .sort()
                            .map(function (name) {
                                return dom.li({id: "host-" + name, link: "host"}, name);
                            })
                        )
                    ];
                });
        }

    });

});
<|endoftext|>