<commit_before>/**
 * Copyright 2013 GetHuman LLC
 * Author: Jeff Whelpley
 * Date: 4/25/14
 *
 * The purpose of this singleton is to allow any client side code to easily inject
 * the information about the active user
 */
module.exports = {

    // on the server side, we attempt to get the user from the CLS session
    // NOTE: this is not 100% fullproof, so only use for non-critical situations
    server: function (Q, cls) {
        return {
            init: function () {
                var session = cls.getNamespace('appSession');
                if (session) {
                    var caller = session.get('caller');
                    if (caller) {
                        return new Q(caller.user);
                    }
                }

                return new Q({});
            }
        };
    },

    // the client maintains the active user in memory
    client: function ($timeout, _, Q, userService, log, eventBus, storage) {

        var user = {
            initComplete:   false,
            visitorId:      storage.get('visitorId')
        };

        /**
         * If user already loaded, use that, otherwise get it from the API
         * @returns {*}
         */
        function init() {
            return user.initComplete ?
                Q.when(user) :
                userService.findMe()
                    .then(function setUserLocal(me) {
                        me = me || {};

                        // if nothing returned log an error and return
                        //if (!me) { log.error('No user info found', null); return null; }

                        // save the visitor Id in storage for use by ajax
                        var visitorId = user.visitorId || me.visitorId;
                        storage.set('visitorId', visitorId);

                        // otherwise, pull out the user
                        _.extend(user, me.user, { visitorId: visitorId });

                        // return the user and notify init complete
                        user.initComplete = true;
                        eventBus.emit('user.init');

                        return user;
                    });
        }

        /**
         * Remove user vals from the user object (for logout or before changing user)
         * All values are removed from user except functions, visitorId and initComplete
         */
        function removeUserVals() {
            _.each(user, function reset(val, key) {
                if (!_.isFunction(val) && key !== 'visitorId' && key !== 'initComplete') {
                    user[key] = null;
                }
            });
        }

        /**
         * Update the active user (i.e. during login/logout/etc.)
         * @param updatedUser
         * @param jwt
         */
        function login(updatedUser, jwt) {
            storage.set('jwt', jwt);        // set the token in local storage
            removeUserVals();               // remove old user values
            _.extend(user, updatedUser);    // add new user values
            eventBus.emit('user.init');     // let everyone else know there is a new user in town
        }

        /**
         * Log the active user out
         */
        function logout() {
            removeUserVals();               // remove user vals to log out
            storage.remove('jwt');          // then remove the JSON web token from local storage
            eventBus.emit('user.init');     // let everyone else know user logged out
        }

        // add functions to user
        _.extend(user, {
            init: init,
            login: login,
            logout: logout
        });

        // return the user as a singleton from this module
        return user;
    }
};<commit_msg>Changes to ensure visitorId set correctly<commit_after>/**
 * Copyright 2013 GetHuman LLC
 * Author: Jeff Whelpley
 * Date: 4/25/14
 *
 * The purpose of this singleton is to allow any client side code to easily inject
 * the information about the active user
 */
module.exports = {

    // on the server side, we attempt to get the user from the CLS session
    // NOTE: this is not 100% fullproof, so only use for non-critical situations
    server: function (Q, cls) {
        return {
            init: function () {
                var session = cls.getNamespace('appSession');
                if (session) {
                    var caller = session.get('caller');
                    if (caller) {
                        return new Q(caller.user);
                    }
                }

                return new Q({});
            }
        };
    },

    // the client maintains the active user in memory
    client: function ($timeout, _, Q, userService, log, eventBus, storage) {
        var id = storage.get('visitorId');
        var user = {
            initComplete:   false,
            visitorId:      (id && id !== 'null') ? id : null
        };

        /**
         * If user already loaded, use that, otherwise get it from the API
         * @returns {*}
         */
        function init() {
            return user.initComplete ?
                Q.when(user) :
                userService.findMe()
                    .then(function setUserLocal(me) {
                        me = me || {};

                        // if nothing returned log an error and return
                        //if (!me) { log.error('No user info found', null); return null; }

                        // save the visitor Id in storage for use by ajax
                        var visitorId = (user.visitorId && user.visitorId !== 'null') ?
                            user.visitorId : me.visitorId;
                        if (visitorId) {
                            storage.set('visitorId', visitorId);
                        }

                        // otherwise, pull out the user
                        _.extend(user, me.user, { visitorId: visitorId });

                        // return the user and notify init complete
                        user.initComplete = true;
                        eventBus.emit('user.init');

                        return user;
                    });
        }

        /**
         * Remove user vals from the user object (for logout or before changing user)
         * All values are removed from user except functions, visitorId and initComplete
         */
        function removeUserVals() {
            _.each(user, function reset(val, key) {
                if (!_.isFunction(val) && key !== 'visitorId' && key !== 'initComplete') {
                    user[key] = null;
                }
            });
        }

        /**
         * Update the active user (i.e. during login/logout/etc.)
         * @param updatedUser
         * @param jwt
         */
        function login(updatedUser, jwt) {
            storage.set('jwt', jwt);        // set the token in local storage
            removeUserVals();               // remove old user values
            _.extend(user, updatedUser);    // add new user values
            eventBus.emit('user.init');     // let everyone else know there is a new user in town
        }

        /**
         * Log the active user out
         */
        function logout() {
            removeUserVals();               // remove user vals to log out
            storage.remove('jwt');          // then remove the JSON web token from local storage
            eventBus.emit('user.init');     // let everyone else know user logged out
        }

        // add functions to user
        _.extend(user, {
            init: init,
            login: login,
            logout: logout
        });

        // return the user as a singleton from this module
        return user;
    }
};<|endoftext|>


<commit_before>var colorStudent = "#31708F";
var colorSupervisor = "#A94442";
var colorFirstInspector = "#8A6D3B";
var colorSecondInspector = "#3C763D";
var colorInspection = "#337AB7";

function Inspector(json) {
	var self = this;

	self.id = json.id;
	self.username= json.username;
	self.name = json.name;
	self.keywords = json.keywords;
	self.load = json.load;
	self.capacity = json.capacity;

	self.formattedCapacity = function() {
		return self.load + "/" + self.capacity;
	};

	self.slots = [];
}

function InspectionViewModel() {
	var self = this;

	self.defaultDate = "2014-11-12";

	self.studentID = null;
	self.studentSlots = [];

	self.supervisorID = null;
	self.supervisorSlots = [];

	self.inspectionSlot = ko.observable({
            title  : 'Inspection',
            start  : '2014-11-14T12:30:00',
            end  : '2014-11-14T13:00:00',
            constraint: "businessHours",
            color: colorInspection
    });

	self.suggestedInspectors = ko.observableArray([]);
	self.otherInspectors = ko.observableArray([]);
	self.allInspectors = ko.observableArray([]);

	self.firstInspector = ko.observable();
	self.secondInspector = ko.observable();

	self.firstOtherInspector = ko.observable();
	self.secondOtherInspector = ko.observable();

	// Inputs
	self.readSuggestedInspectors = function(json) {
    	var inspectors = [];
    	json.suggestedInspectors.forEach(function(inspectorJson) {
    		var inspector = new Inspector(inspectorJson);
    		inspectors.push(inspector);
    	});
    	self.suggestedInspectors(inspectors);
    	ko.utils.arrayPushAll(self.allInspectors, inspectors);
    	self.firstInspector(null);
	};

	self.readOtherInspectors = function(json) {
    	var inspectors = [];
    	json.otherInspectors.forEach(function(inspectorJson) {
    		var inspector = new Inspector(inspectorJson);
    		inspectors.push(inspector);
    	});
    	self.otherInspectors(inspectors);
    	ko.utils.arrayPushAll(self.allInspectors, inspectors);
    	self.secondInspector(null);
	};

	self.readFirstInspector = function(json) {
    	var firstInspector = self.inspectorWithID(json.firstInspectorID);
    	self.firstInspector(firstInspector);
    	if (self.otherInspectors().indexOf(firstInspector) >= 0) {
        	self.firstOtherInspector(firstInspector);
    	}
	};

	self.readSecondInspector = function(json) {
    	var secondInspector = self.inspectorWithID(json.secondInspectorID);
    	self.secondInspector(secondInspector);
    	if (self.otherInspectors().indexOf(secondInspector) >= 0) {
        	self.secondOtherInspector(secondInspector);
    	}
	};

	self.readInspection = function() {
    	var jsonDiv = $('#json-variables');
    	var json = JSON.parse(jsonDiv.text());

		self.allInspectors([]);
		self.readStudent(json);
		self.readSuggestedInspectors(json);
		self.readOtherInspectors(json);
		self.readFirstInspector(json);
		self.readSecondInspector(json);

		self.readInspectionDate(json);
	};

	self.readStudent = function(json) {
		self.supervisorID = json.supervisorID;
		self.studentID = json.studentID;
	};

	self.readInspectionDate = function(json) {
		self.inspectionSlot().start = json.inspectionStart;
		self.inspectionSlot().end = json.inspectionEnd;
	};

	// Getters
	self.inspectorWithID = function(inspectorID) {
		var inspector = null;
		self.allInspectors().forEach(function(i) {
			if (i.id == inspectorID) {
				inspector = i;
			}
		});
		return inspector;
	};

	self.getSlots = function(start, end, timezone, callback) {
		var slots = [];
		if (self.firstInspector() != null) {
			slots = slots.concat(self.firstInspector().slots);
		}
		if (self.secondInspector() != null) {
			slots = slots.concat(self.secondInspector().slots);
		}
		slots = slots.concat(self.studentSlots);
		slots = slots.concat(self.supervisorSlots);
		slots.push(self.inspectionSlot());
		callback(slots);
	};

	// Get availability
	self.studentIsAvailable = ko.computed(function() {
		return !slotsOverlap(self.studentSlots, self.inspectionSlot());
	});
	self.supervisorIsAvailable = ko.computed(function() {
		return !slotsOverlap(self.supervisorSlots, self.inspectionSlot());
	});
	self.firstInspectorIsAvailable = ko.computed(function() {
		var user = self.firstInspector();
		if (user) {
			return !slotsOverlap(user.slots, self.inspectionSlot());
		} else {
			return true;
		}
	});
	self.secondInspectorIsAvailable = ko.computed(function() {
		var user = self.secondInspector();
		if (user) {
			return !slotsOverlap(user.slots, self.inspectionSlot());
		} else {
			return true;
		}
	});

	// Setters
	self.slotChanged = function(event, delta, revertFunc) {
		self.inspectionSlot(event);
	};

    self.setCalendarNeedUpdate = function() {
    	$('#calendar').fullCalendar( 'refetchEvents' );
    };

    // Fetchers
    self.fetchFirstInspectorSlots = function() {
    	if (self.firstInspector() != null) {
        	var userType = 'inspector';
        	var userID = self.firstInspector().id;

        	self.fetchAvailability(userType, userID, function(result) {
        		// if success
            	var json = JSON.parse(result);

            	json.slots.forEach(function(slot) {
            		slot.color = colorFirstInspector;
            		slot.rendering = "background";
            		slot.user = "first inspector";
            	});
            	self.firstInspector().slots = json.slots;
            	self.setCalendarNeedUpdate();
        	});
    	}
    };
    self.fetchSecondInspectorSlots = function() {
    	if (self.secondInspector() != null) {
        	var userType = 'inspector';
        	var userID = self.secondInspector().id;

        	self.fetchAvailability(userType, userID, function(result) {
        		// if success
            	var json = JSON.parse(result);

            	json.slots.forEach(function(slot) {
            		slot.color = colorSecondInspector;
            		slot.rendering = "background";
            		slot.user = "second inspector";
            	});
            	self.secondInspector().slots = json.slots;
            	self.setCalendarNeedUpdate();
        	});
    	}
    };
    self.fetchSupervisorSlots = function() {
    	if (self.secondInspector() != null) {
        	var userType = 'inspector';
        	var userID = self.supervisorID;

        	self.fetchAvailability(userType, userID, function(result) {
        		// if success
            	var json = JSON.parse(result);

            	json.slots.forEach(function(slot) {
            		slot.color = colorSupervisor;
            		slot.rendering = "background";
            		slot.user = "supervisor";
            	});
            	self.supervisorSlots = json.slots;
            	self.setCalendarNeedUpdate();
        	});
    	}
    };
    self.fetchStudentSlots = function() {
    	if (self.secondInspector() != null) {
        	var userType = 'student';
        	var userID = self.studentID;

        	self.fetchAvailability(userType, userID, function(result) {
        		// if success
            	var json = JSON.parse(result);

            	json.slots.forEach(function(slot) {
            		slot.color = colorStudent;
            		slot.rendering = "background";
            		slot.user = "student";
            	});
            	self.studentSlots = json.slots;
            	self.setCalendarNeedUpdate();
        	});
    	}
    };

    self.fetchAvailability = function(userType, userID, success) {
    	var contentType = 'json';
		$.ajax({
			url: '/PIMS/availability/?type=' + userType + '&id=' + userID +'&content='+ contentType,
			success: success,
			error: null
		});
    };

	// Bind other inspectors changes
	self.firstInspectorHandler = ko.computed(function() {
		self.fetchFirstInspectorSlots();
	});
	self.secondInspectorHandler = ko.computed(function() {
		self.fetchSecondInspectorSlots();
	});
	self.firstOtherInspectorHandler = ko.computed(function() {
		//console.log(self.firstOtherInspector());
	});
	self.secondOtherInspectorHandler = ko.computed(function() {
		//console.log(self.secondOtherInspector());
	});

	// Submit
    self.submitInspection = function() {
    	var usersAvailable = self.studentIsAvailable();
    	usersAvailable = usersAvailable && self.supervisorIsAvailable();
    	usersAvailable = usersAvailable && self.firstInspectorIsAvailable();
    	usersAvailable = usersAvailable && self.secondInspectorIsAvailable();
    	var forceSave = false;

    	if (!usersAvailable) {
    		forceSave = confirm("Some person may not be available at this time. Do you wish to confirm this time for the inspection ?");
    	}

    	if (usersAvailable || forceSave) {
        	var url = document.url;
        	var data = {
        		firstInspector: self.firstInspector().id,
        		secondInspector: self.secondInspector().id,
        		slot: JSON.stringify(self.inspectionSlot())
        	};
        	$.post(url, data, self.submitHandler);
    	}
    };

    self.submitHandler = function(data, status) {
    	if (status == "success") {
        	popSuccess('Inspection saved');
    	} else {
    		popError('Error');
    	}
    };

	// Start
	self.readInspection();
	self.fetchStudentSlots();
	self.fetchSupervisorSlots();
	createCalendar(self);
}

var inspectionViewModel = new InspectionViewModel();
ko.applyBindings(inspectionViewModel);<commit_msg>update load in live<commit_after>var colorStudent = "#31708F";
var colorSupervisor = "#A94442";
var colorFirstInspector = "#8A6D3B";
var colorSecondInspector = "#3C763D";
var colorInspection = "#337AB7";

function Inspector(json) {
	var self = this;

	self.id = json.id;
	self.username= json.username;
	self.name = json.name;
	self.keywords = json.keywords;
	self.load = ko.observable(json.load);
	self.capacity = json.capacity;
	self.isFirstInspector = false;

	self.setFirstInspector = function(isFirstInspector) {
		if (self.isFirstInspector != isFirstInspector) {
			self.isFirstInspector = isFirstInspector;
			if (self.isFirstInspector) {
				self.load(self.load() + 1);
			} else {
				self.load(self.load() - 1);
			}
		}
	};

	self.formattedCapacity = function() {
		return self.load() + "/" + self.capacity;
	};

	self.slots = [];
}

function InspectionViewModel() {
	var self = this;

	self.defaultDate = "2014-11-12";

	self.studentID = null;
	self.studentSlots = [];

	self.supervisorID = null;
	self.supervisorSlots = [];

	self.inspectionSlot = ko.observable({
            title  : 'Inspection',
            start  : '2014-11-14T12:30:00',
            end  : '2014-11-14T13:00:00',
            constraint: "businessHours",
            color: colorInspection
    });

	self.suggestedInspectors = ko.observableArray([]);
	self.otherInspectors = ko.observableArray([]);
	self.allInspectors = ko.observableArray([]);

	self.firstInspector = ko.observable();
	self.secondInspector = ko.observable();

	self.firstOtherInspector = ko.observable();
	self.secondOtherInspector = ko.observable();

	// Inputs
	self.readSuggestedInspectors = function(json) {
    	var inspectors = [];
    	json.suggestedInspectors.forEach(function(inspectorJson) {
    		var inspector = new Inspector(inspectorJson);
    		inspectors.push(inspector);
    	});
    	self.suggestedInspectors(inspectors);
    	ko.utils.arrayPushAll(self.allInspectors, inspectors);
    	self.firstInspector(null);
	};

	self.readOtherInspectors = function(json) {
    	var inspectors = [];
    	json.otherInspectors.forEach(function(inspectorJson) {
    		var inspector = new Inspector(inspectorJson);
    		inspectors.push(inspector);
    	});
    	self.otherInspectors(inspectors);
    	ko.utils.arrayPushAll(self.allInspectors, inspectors);
    	self.secondInspector(null);
	};

	self.readFirstInspector = function(json) {
    	var firstInspector = self.inspectorWithID(json.firstInspectorID);
    	firstInspector.isFirstInspector = true; // set selection with out changing his load
    	self.firstInspector(firstInspector);
    	if (self.otherInspectors().indexOf(firstInspector) >= 0) {
        	self.firstOtherInspector(firstInspector);
    	}
	};

	self.readSecondInspector = function(json) {
    	var secondInspector = self.inspectorWithID(json.secondInspectorID);
    	self.secondInspector(secondInspector);
    	if (self.otherInspectors().indexOf(secondInspector) >= 0) {
        	self.secondOtherInspector(secondInspector);
    	}
	};

	self.readInspection = function() {
    	var jsonDiv = $('#json-variables');
    	var json = JSON.parse(jsonDiv.text());

		self.allInspectors([]);
		self.readStudent(json);
		self.readSuggestedInspectors(json);
		self.readOtherInspectors(json);
		self.readFirstInspector(json);
		self.readSecondInspector(json);

		self.readInspectionDate(json);
	};

	self.readStudent = function(json) {
		self.supervisorID = json.supervisorID;
		self.studentID = json.studentID;
	};

	self.readInspectionDate = function(json) {
		self.inspectionSlot().start = json.inspectionStart;
		self.inspectionSlot().end = json.inspectionEnd;
	};

	// Getters
	self.inspectorWithID = function(inspectorID) {
		var inspector = null;
		self.allInspectors().forEach(function(i) {
			if (i.id == inspectorID) {
				inspector = i;
			}
		});
		return inspector;
	};
	self.inspectorMarkedFirstInspector = function() {
		var inspector = null;
		self.allInspectors().forEach(function(i) {
			if (i.isFirstInspector) {
				inspector = i;
			}
		});
		return inspector;
	};

	self.getSlots = function(start, end, timezone, callback) {
		var slots = [];
		if (self.firstInspector() != null) {
			slots = slots.concat(self.firstInspector().slots);
		}
		if (self.secondInspector() != null) {
			slots = slots.concat(self.secondInspector().slots);
		}
		slots = slots.concat(self.studentSlots);
		slots = slots.concat(self.supervisorSlots);
		slots.push(self.inspectionSlot());
		callback(slots);
	};

	// Get availability
	self.studentIsAvailable = ko.computed(function() {
		return !slotsOverlap(self.studentSlots, self.inspectionSlot());
	});
	self.supervisorIsAvailable = ko.computed(function() {
		return !slotsOverlap(self.supervisorSlots, self.inspectionSlot());
	});
	self.firstInspectorIsAvailable = ko.computed(function() {
		var user = self.firstInspector();
		if (user) {
			return !slotsOverlap(user.slots, self.inspectionSlot());
		} else {
			return true;
		}
	});
	self.secondInspectorIsAvailable = ko.computed(function() {
		var user = self.secondInspector();
		if (user) {
			return !slotsOverlap(user.slots, self.inspectionSlot());
		} else {
			return true;
		}
	});

	// Setters
	self.slotChanged = function(event, delta, revertFunc) {
		self.inspectionSlot(event);
	};

    self.setCalendarNeedUpdate = function() {
    	$('#calendar').fullCalendar( 'refetchEvents' );
    };

    // Fetchers
    self.fetchFirstInspectorSlots = function() {
    	if (self.firstInspector() != null) {
        	var userType = 'inspector';
        	var userID = self.firstInspector().id;

        	self.fetchAvailability(userType, userID, function(result) {
        		// if success
            	var json = JSON.parse(result);

            	json.slots.forEach(function(slot) {
            		slot.color = colorFirstInspector;
            		slot.rendering = "background";
            		slot.user = "first inspector";
            	});
            	self.firstInspector().slots = json.slots;
            	self.setCalendarNeedUpdate();
        	});
    	}
    };
    self.fetchSecondInspectorSlots = function() {
    	if (self.secondInspector() != null) {
        	var userType = 'inspector';
        	var userID = self.secondInspector().id;

        	self.fetchAvailability(userType, userID, function(result) {
        		// if success
            	var json = JSON.parse(result);

            	json.slots.forEach(function(slot) {
            		slot.color = colorSecondInspector;
            		slot.rendering = "background";
            		slot.user = "second inspector";
            	});
            	self.secondInspector().slots = json.slots;
            	self.setCalendarNeedUpdate();
        	});
    	}
    };
    self.fetchSupervisorSlots = function() {
    	if (self.secondInspector() != null) {
        	var userType = 'inspector';
        	var userID = self.supervisorID;

        	self.fetchAvailability(userType, userID, function(result) {
        		// if success
            	var json = JSON.parse(result);

            	json.slots.forEach(function(slot) {
            		slot.color = colorSupervisor;
            		slot.rendering = "background";
            		slot.user = "supervisor";
            	});
            	self.supervisorSlots = json.slots;
            	self.setCalendarNeedUpdate();
        	});
    	}
    };
    self.fetchStudentSlots = function() {
    	if (self.secondInspector() != null) {
        	var userType = 'student';
        	var userID = self.studentID;

        	self.fetchAvailability(userType, userID, function(result) {
        		// if success
            	var json = JSON.parse(result);

            	json.slots.forEach(function(slot) {
            		slot.color = colorStudent;
            		slot.rendering = "background";
            		slot.user = "student";
            	});
            	self.studentSlots = json.slots;
            	self.setCalendarNeedUpdate();
        	});
    	}
    };

    self.fetchAvailability = function(userType, userID, success) {
    	var contentType = 'json';
		$.ajax({
			url: '/PIMS/availability/?type=' + userType + '&id=' + userID +'&content='+ contentType,
			success: success,
			error: null
		});
    };

	// Bind other inspectors changes
	self.firstInspectorHandler = ko.computed(function() {
		self.fetchFirstInspectorSlots();

		var firstInspector = self.inspectorMarkedFirstInspector();
		if (firstInspector) {
			console.log(firstInspector);
			firstInspector.setFirstInspector(false); // unmark old first inspector
		}
		firstInspector = self.firstInspector();
		if (firstInspector) {
			console.log(firstInspector);
			firstInspector.setFirstInspector(true); // mark new first inspector
		}
	});
	self.secondInspectorHandler = ko.computed(function() {
		self.fetchSecondInspectorSlots();
	});
	self.firstOtherInspectorHandler = ko.computed(function() {
		//console.log(self.firstOtherInspector());
	});
	self.secondOtherInspectorHandler = ko.computed(function() {
		//console.log(self.secondOtherInspector());
	});

	// Submit
    self.submitInspection = function() {
    	var usersAvailable = self.studentIsAvailable();
    	usersAvailable = usersAvailable && self.supervisorIsAvailable();
    	usersAvailable = usersAvailable && self.firstInspectorIsAvailable();
    	usersAvailable = usersAvailable && self.secondInspectorIsAvailable();
    	var forceSave = false;

    	if (!usersAvailable) {
    		forceSave = confirm("Some person may not be available at this time. Do you wish to confirm this time for the inspection ?");
    	}

    	if (usersAvailable || forceSave) {
        	var url = document.url;
        	var data = {
        		firstInspector: self.firstInspector().id,
        		secondInspector: self.secondInspector().id,
        		slot: JSON.stringify(self.inspectionSlot())
        	};
        	$.post(url, data, self.submitHandler);
    	}
    };

    self.submitHandler = function(data, status) {
    	if (status == "success") {
        	popSuccess('Inspection saved');
    	} else {
    		popError('Error');
    	}
    };

	// Start
	self.readInspection();
	self.fetchStudentSlots();
	self.fetchSupervisorSlots();
	createCalendar(self);
}

var inspectionViewModel = new InspectionViewModel();
ko.applyBindings(inspectionViewModel);<|endoftext|>


<commit_before>(function() {

  'use strict';
  const popupsButtons = [...document.querySelectorAll('.popup-trigger')],
        popupSelector = '.popup',
        popupContentSelector = '.popup__content';

  class Popup {
    constructor(button, popup = popupSelector) {
      this.button = button;
      this.buttonId = button.dataset.popuptrigger;
      this.popup = document.querySelector(`${popupSelector}[data-popup=${this.buttonId}]`);
      this.popupContent = this.popup.querySelector(popupContentSelector);
      this.active = 'popup--active';
      this.body = document.querySelector('body');
      this.closeButton = this.popup.querySelector('.popup__close-btn');

      this.button.addEventListener('click', (e) => {
        e.preventDefault();
        this.toggle();
      });

      this.closeButton.addEventListener('click', (e) => {
        this.hide();
      });

      window.addEventListener('resize', () => {
        this.position();
      });
    }

    toggle() {
      if (this.isActive()) {
        this.hide();
      }
      else {
        this.show();
      }
    }

    show() {
      this.popup.classList.add(this.active);
      this.popup.open = true;
      this.popupContent.focus();
      this.position();
    }

    hide() {
      this.popup.classList.remove(this.active);
      this.button.focus();
      this.popup.open = false;
    }

    position() {
      const buttonCoords = this.button.getBoundingClientRect();

      this.popup.style.setProperty('top', `${buttonCoords.height}px`, '');
      this.popup.style.setProperty('left', `${buttonCoords.left}px`, '');
      this.isOutOfscreen(buttonCoords);
    }

    isOutOfscreen(buttonCoords) {
      const popupContentCoords = this.popup.getBoundingClientRect();

      if (window.matchMedia('(max-width: 480px)').matches) {
        const calcLeft = this.button.getBoundingClientRect().left * -1;

        this.popup.classList.add('popup--full-width');
        this.popup.style.setProperty('left', `${calcLeft}px`, '');
      }
      else if (popupContentCoords.right >= this.body.clientWidth) {
        this.popup.classList.remove('popup--full-width');
        this.popup.style.setProperty('right', '0', '');
        this.popup.style.setProperty('left', 'auto', '');
      }
    }

    isActive() {
      return this.popup.classList.contains(this.active);
    }
  }

  popupsButtons.forEach(popupButton => {
    new Popup(popupButton);
  });
}());
<commit_msg>#35299 update script - closing popup functions<commit_after>(function() {

  'use strict';
  const popupsButtons = [...document.querySelectorAll('.popup-trigger')],
        popupSelector = '.popup',
        popupContentSelector = '.popup__content';

  class Popup {
    constructor(button, popup = popupSelector) {
      this.button = button;
      this.buttonId = button.dataset.popuptrigger;
      this.popup = document.querySelector(`${popup}[data-popup=${this.buttonId}]`);
      this.popupContent = this.popup.querySelector(popupContentSelector);
      this.active = 'popup--active';
      this.body = document.querySelector('body');
      this.closeButton = this.popup.querySelector('.popup__close-btn');

      this.button.addEventListener('click', (e) => {
        e.preventDefault();
        this.toggle();
      });

      this.closeButton.addEventListener('click', () => {
        this.hide();
      });

      window.addEventListener('resize', () => {
        this.position();
      });

      window.addEventListener('click', (e) => {
        if ((e.target !== this.button) && (!this.popup.contains(e.target))) {
          if (this.isActive()) {
            this.hide();
          }
        }
      });
    }

    toggle() {
      if (this.isActive()) {
        this.hide();
      }
      else {
        this.show();
      }
    }

    show() {
      this.popup.classList.add(this.active);
      this.popup.open = true;
      this.popupContent.focus();
      this.position();
      window.addEventListener('keydown', this.keyboardClosePopup.bind(this));
    }

    hide() {
      this.popup.classList.remove(this.active);
      this.button.focus();
      this.popup.open = false;
    }

    position() {
      const buttonCoords = this.button.getBoundingClientRect();
      this.popup.style.setProperty('top', `${buttonCoords.height}px`, '');
      this.popup.style.setProperty('left', `${buttonCoords.left}px`, '');
      this.isOutOfscreen();
    }

    isOutOfscreen() {
      const popupContentCoords = this.popup.getBoundingClientRect();

      if (window.matchMedia('(max-width: 480px)').matches) {
        const calcLeft = this.button.getBoundingClientRect().left * -1;

        this.popup.classList.add('popup--full-width');
        this.popup.style.setProperty('left', `${calcLeft}px`, '');
      }
      else if (popupContentCoords.right >= this.body.clientWidth) {
        this.popup.classList.remove('popup--full-width');
        this.popup.style.setProperty('right', '0', '');
        this.popup.style.setProperty('left', 'auto', '');
      }
    }

    isActive() {
      return this.popup.classList.contains(this.active);
    }

    keyboardClosePopup(event) {
      if (event.which === 27) {
        if (this.isActive()) {
          event.preventDefault();
          this.hide();
        }
      }
    }
  }

  popupsButtons.forEach(popupButton => {
    new Popup(popupButton);
  });
}());
<|endoftext|>


<commit_before>// adding js extension in the import statement.

// Reference:
// https://regexr.com/47jlq
// https://gist.github.com/manekinekko/7e58a17bc62a9be47172
const regexp = /((?:(?:import)|(?:export))\s+?(?:(?:(?:[\w*\s{},\/\/\*]*)\s+from\s+?)|))(?:(?:"(.*?)")|(?:'(.*?)'))([\s]*?(?:;|$|))/g;

module.exports.transformImport = function (code, processModuleName) {
    return code.replace(regexp, (str, prefix, moduleNameA, moduleNameB, postfix) => {
        let moduleName = (moduleNameA === undefined ? moduleNameB : moduleNameA).trim();
        const quote = moduleNameA === undefined ? "'" : '"';
        return prefix + quote + processModuleName(moduleName) + quote + postfix;
        // Not support other extensions.
    });
}

const testCases = `import videos from './videos/index.js'

export default (socket, context) => {
    // dynamically importing all the socket.io handler (it's dynamic import that happen at run time)
  import {
	something
} from "./test/okbb"

const f = 2;

import test from 'obb'

import {
  Component
} from '@angular2/core';

import defaultMember from "module-0";

import   *    as name from "module-1  ";

import   {  member }   from "  module-2";

import { member as alias } from "module-3";

import { member1 , member2 } from "module-4";

import { member1 , member2 as alias2 , member3 as alias3 } from "module-5";

import defaultMember, { member, member } from "module-6";

import defaultMember, * as name from "module-7";

import "module-8";

import "module-9"    // comment no problem

import {
    AAAA,
    // BBB
} from 'module-10';

import "module-b' // doesn't match -> the opening and closing quation mark are different

importing hya from 'ttt'

import fbsfrom ''

// Export expressions.
export { aaa };

export * from "module-11";

export { aaa } from "module-12";

// Should not be parsed
export default aaa;

export function bbb () {
};
`

module.exports.runTest = function () {
    const expected = [
        './videos/index.js',
        './test/okbb',
        'obb',
        '@angular2/core',
        'module-0',
        'module-1',
        'module-2',
        'module-3',
        'module-4',
        'module-5',
        'module-6',
        'module-7',
        'module-8',
        'module-9',
        'module-10',
        'module-11',
        'module-12'
    ]
    let cursor = 0;
    module.exports.transformImport(testCases, (moduleName) => {
        if (expected[cursor] !== moduleName) {
            throw new Error(`Expected ${expected[cursor]}. Actual ${moduleName}`);
        }
        cursor++;
        return moduleName;
    })
    if (cursor !== expected.length) {
        throw new Error('Test failed');
    }
    console.log('All test passed!')
}

// module.exports.runTest();<commit_msg>fix issue from deepscan<commit_after>// adding js extension in the import statement.

// Reference:
// https://regexr.com/47jlq
// https://gist.github.com/manekinekko/7e58a17bc62a9be47172
const regexp = /((?:(?:import)|(?:export))\s+?(?:(?:(?:[\w*\s{},\/]*)\s+from\s+?)|))(?:(?:"(.*?)")|(?:'(.*?)'))([\s]*?(?:;|$|))/g;

module.exports.transformImport = function (code, processModuleName) {
    return code.replace(regexp, (str, prefix, moduleNameA, moduleNameB, postfix) => {
        let moduleName = (moduleNameA === undefined ? moduleNameB : moduleNameA).trim();
        const quote = moduleNameA === undefined ? "'" : '"';
        return prefix + quote + processModuleName(moduleName) + quote + postfix;
        // Not support other extensions.
    });
}

const testCases = `import videos from './videos/index.js'

export default (socket, context) => {
    // dynamically importing all the socket.io handler (it's dynamic import that happen at run time)
  import {
	something
} from "./test/okbb"

const f = 2;

import test from 'obb'

import {
  Component
} from '@angular2/core';

import defaultMember from "module-0";

import   *    as name from "module-1  ";

import   {  member }   from "  module-2";

import { member as alias } from "module-3";

import { member1 , member2 } from "module-4";

import { member1 , member2 as alias2 , member3 as alias3 } from "module-5";

import defaultMember, { member, member } from "module-6";

import defaultMember, * as name from "module-7";

import "module-8";

import "module-9"    // comment no problem

import {
    AAAA,
    // BBB
} from 'module-10';

import "module-b' // doesn't match -> the opening and closing quation mark are different

importing hya from 'ttt'

import fbsfrom ''

// Export expressions.
export { aaa };

export * from "module-11";

export { aaa } from "module-12";

// Should not be parsed
export default aaa;

export function bbb () {
};
`

module.exports.runTest = function () {
    const expected = [
        './videos/index.js',
        './test/okbb',
        'obb',
        '@angular2/core',
        'module-0',
        'module-1',
        'module-2',
        'module-3',
        'module-4',
        'module-5',
        'module-6',
        'module-7',
        'module-8',
        'module-9',
        'module-10',
        'module-11',
        'module-12'
    ]
    let cursor = 0;
    module.exports.transformImport(testCases, (moduleName) => {
        if (expected[cursor] !== moduleName) {
            throw new Error(`Expected ${expected[cursor]}. Actual ${moduleName}`);
        }
        cursor++;
        return moduleName;
    })
    if (cursor !== expected.length) {
        throw new Error('Test failed');
    }
    console.log('All test passed!')
}

// module.exports.runTest();<|endoftext|>


<commit_before><commit_msg>updated from js<commit_after><|endoftext|>


<commit_before>import {spring, Motion, TransitionMotion} from 'react-motion';
import React, {Component} from 'react';

class SceneNavigator extends Component{
    constructor(props) {
        super(props);
        var {state, data, url} = props.stateNavigator.stateContext;
        this.state = {scenes: {[url]: state.renderScene(data)}};
    }
    componentDidMount() {
        var {stateNavigator} = this.props;
        stateNavigator.onNavigate((oldState, state, data, asyncData) => {
            this.setState((prevState) => {
                var {url, crumbs} = stateNavigator.stateContext;
                var scenes = {[url]: state.renderScene(data, asyncData)};
                for(var i = 0; i < crumbs.length; i++) {
                    scenes[crumbs[i].url] = prevState.scenes[crumbs[i].url];
                }
                return {scenes};
            });
        });
    }
    renderScene({key, data: {scene, state, data, mount}, style: {parent,...parentStyle}}) {
        var {getMountStyle, getMountedStyle, animateStyle, children} = this.props;
        var style = (mount ? getMountStyle : getMountedStyle)(state, data);
        return (
            <Motion key={key} style={parent ? parentStyle : style}>
                {(tweenStyle) => children(tweenStyle, scene, state, data)}
            </Motion>
        );
    }
    render() {
        var {oldState, state, data, url, crumbs} = this.props.stateNavigator.stateContext;
        var {getUnmountedStyle, getMountStyle, getUnmountStyle} = this.props;
        var sceneContexts = crumbs.concat({state, data, url, mount: true});
        return (
            <TransitionMotion
                willEnter={() => ({...getUnmountedStyle(state, data), parent: 1})}
                willLeave={() => ({...getUnmountStyle(state, data), parent: 1})}
                styles={sceneContexts.map(({state, data, url, mount}) => ({
                    key: url,
                    data: {scene: this.state.scenes[url], state, data, mount},
                    style: {...getMountStyle(state, data), parent: spring(0)}
                }))}>
                {tweenStyles =>
{tweenStyles.map((config) => this.renderScene(config))}
}
            </TransitionMotion>
        );
    }
}

export default SceneNavigator;
<commit_msg>Removed redundant prop<commit_after>import {spring, Motion, TransitionMotion} from 'react-motion';
import React, {Component} from 'react';

class SceneNavigator extends Component{
    constructor(props) {
        super(props);
        var {state, data, url} = props.stateNavigator.stateContext;
        this.state = {scenes: {[url]: state.renderScene(data)}};
    }
    componentDidMount() {
        var {stateNavigator} = this.props;
        stateNavigator.onNavigate((oldState, state, data, asyncData) => {
            this.setState((prevState) => {
                var {url, crumbs} = stateNavigator.stateContext;
                var scenes = {[url]: state.renderScene(data, asyncData)};
                for(var i = 0; i < crumbs.length; i++) {
                    scenes[crumbs[i].url] = prevState.scenes[crumbs[i].url];
                }
                return {scenes};
            });
        });
    }
    renderScene({key, data: {scene, state, data, mount}, style: {parent,...parentStyle}}) {
        var {getMountStyle, getMountedStyle, children} = this.props;
        var style = (mount ? getMountStyle : getMountedStyle)(state, data);
        return (
            <Motion key={key} style={parent ? parentStyle : style}>
                {(tweenStyle) => children(tweenStyle, scene, state, data)}
            </Motion>
        );
    }
    render() {
        var {oldState, state, data, url, crumbs} = this.props.stateNavigator.stateContext;
        var {getUnmountedStyle, getMountStyle, getUnmountStyle} = this.props;
        var sceneContexts = crumbs.concat({state, data, url, mount: true});
        return (
            <TransitionMotion
                willEnter={() => ({...getUnmountedStyle(state, data), parent: 1})}
                willLeave={() => ({...getUnmountStyle(state, data), parent: 1})}
                styles={sceneContexts.map(({state, data, url, mount}) => ({
                    key: url,
                    data: {scene: this.state.scenes[url], state, data, mount},
                    style: {...getMountStyle(state, data), parent: spring(0)}
                }))}>
                {tweenStyles =>
{tweenStyles.map((config) => this.renderScene(config))}
}
            </TransitionMotion>
        );
    }
}

export default SceneNavigator;
<|endoftext|>


<commit_before>var React = require("react");
var openCPQ = require("opencpq");
var {Table, Button} = require("react-bootstrap");
var $ = require("jquery");
var Baby = require("babyparse");
var saveAs = require("browser-filesaver");

class BOMView {
	constructor(name, bom) {
		this.name = name;
		this.__bom = bom;
	}
	render() {
		return <ReactBom bom={this.__bom}/>
	}
}

var ReactBom = React.createClass({
	getInitialState() {
		return {itemMap: {}};
	},
	componentDidMount() {
		$.ajax({
			url: "resources/materials.tsv",
			success: string => {
				Baby.parse(string, {
					complete: ({data}) => {
						var itemMap = {};
						data.forEach(line => {
							var length = line.length;
							if (length > 0)
								itemMap[line[0]] = {label: length > 1 ? line[1] : undefined, price: length > 2 ? line[2] : undefined};
						});
						this.setState({itemMap});
					},
					fastMode: true,
					skipEmptyLines: true,
					comments: "#"
				});
			}
		});
	},
    exportCSV() {
        var csv = [];
        this.props.bom.mapItems(
            (item, quantity) => {
                var entry = this.state.itemMap[item];
                var label = entry == undefined ? "" : entry.label;
                var price = entry == undefined ? "" : entry.price;
			    var parsedPrice = parseFloat(price);
			    if (!isNaN(parsedPrice))
			    	price = parsedPrice.toLocaleString([], {localeMatcher: "lookup", minimumFractionDigits: 2, maximumFractionDigits: 2});
                csv.push(openCPQ.csvLine([quantity, item, label, price])); // TODO use Baby.unparse
            });
        var blob = new Blob(csv, {type: "text/csv;charset=utf-8"});
        saveAs(blob, "openCPQ.csv");
    },
	render() {
		var accumulatedPrice = 0;
		return

			<Button onClick={() => this.exportCSV()}>export as CSV</Button>

				<colgroup>
					<col className="bom-col-quantity"/>
					<col className="bom-col-item"/>
					<col className="bom-col-description"/>
					<col className="bom-col-price"/>
				</colgroup>

					#
					Material No.
					Description
					Price (€)

				{this.props.bom.empty() ?

(no entries)

 :
				 this.props.bom.mapItems(
					 (item, quantity) => {
						 var entry = this.state.itemMap[item];
						 var label = entry == undefined ? "(missing)" : entry.label;
						 var price = entry == undefined ? "(missing)" : entry.price;
						 var parsedPrice = parseFloat(price);
						 if (!isNaN(parsedPrice)) {
							 price = parsedPrice.toLocaleString([], {localeMatcher: "lookup", minimumFractionDigits: 2, maximumFractionDigits: 2});
							 accumulatedPrice = accumulatedPrice + parsedPrice; // TODO display accumulated price
						 }
						 return

							 {quantity}
							 {item}
							 {label}
							 {price}

;
					 }
				 )}

;
	}
});

function VBOM({bom}) {
	return new BOMView("bom", bom);
}

module.exports = {VBOM, BOMView};
<commit_msg>added Glyphicon to "CSV export button"<commit_after>var React = require("react");
var openCPQ = require("opencpq");
var {ButtonGroup, Button, Glyphicon, Table} = require("react-bootstrap");
var $ = require("jquery");
var Baby = require("babyparse");
var saveAs = require("browser-filesaver");

class BOMView {
	constructor(name, bom) {
		this.name = name;
		this.__bom = bom;
	}
	render() {
		return <ReactBom bom={this.__bom}/>
	}
}

var ReactBom = React.createClass({
	getInitialState() {
		return {itemMap: {}};
	},
	componentDidMount() {
		$.ajax({
			url: "resources/materials.tsv",
			success: string => {
				Baby.parse(string, {
					complete: ({data}) => {
						var itemMap = {};
						data.forEach(line => {
							var length = line.length;
							if (length > 0)
								itemMap[line[0]] = {label: length > 1 ? line[1] : undefined, price: length > 2 ? line[2] : undefined};
						});
						this.setState({itemMap});
					},
					fastMode: true,
					skipEmptyLines: true,
					comments: "#"
				});
			}
		});
	},
    exportCSV() {
        var csv = [];
        this.props.bom.mapItems(
            (item, quantity) => {
                var entry = this.state.itemMap[item];
                var label = entry == undefined ? "" : entry.label;
                var price = entry == undefined ? "" : entry.price;
			    var parsedPrice = parseFloat(price);
			    if (!isNaN(parsedPrice))
			    	price = parsedPrice.toLocaleString([], {localeMatcher: "lookup", minimumFractionDigits: 2, maximumFractionDigits: 2});
                csv.push(openCPQ.csvLine([quantity, item, label, price])); // TODO use Baby.unparse
            });
        var blob = new Blob(csv, {type: "text/csv;charset=utf-8"});
        saveAs(blob, "openCPQ.csv");
    },
	render() {
		var accumulatedPrice = 0;
		return

			<ButtonGroup>
				<Button onClick={() => this.exportCSV()}><Glyphicon glyph="th"/> export as CSV</Button>
			</ButtonGroup>

				<colgroup>
					<col className="bom-col-quantity"/>
					<col className="bom-col-item"/>
					<col className="bom-col-description"/>
					<col className="bom-col-price"/>
				</colgroup>

					#
					Material No.
					Description
					Price (€)

				{this.props.bom.empty() ?

(no entries)

 :
				 this.props.bom.mapItems(
					 (item, quantity) => {
						 var entry = this.state.itemMap[item];
						 var label = entry == undefined ? "(missing)" : entry.label;
						 var price = entry == undefined ? "(missing)" : entry.price;
						 var parsedPrice = parseFloat(price);
						 if (!isNaN(parsedPrice)) {
							 price = parsedPrice.toLocaleString([], {localeMatcher: "lookup", minimumFractionDigits: 2, maximumFractionDigits: 2});
							 accumulatedPrice = accumulatedPrice + parsedPrice; // TODO display accumulated price
						 }
						 return

							 {quantity}
							 {item}
							 {label}
							 {price}

;
					 }
				 )}

;
	}
});

function VBOM({bom}) {
	return new BOMView("bom", bom);
}

module.exports = {VBOM, BOMView};
<|endoftext|>


<commit_before>function dashboardView(){
    $(".info-box-content").block(blockUI_opt_el);

    //이벤트 현황
    dashboardEventStatus();

    //호스트별 장애현황
    var hostEvent = '';
    zbxApi.allServerViewHost.get().done(function(data, status, jqxHR){
        hostEvent = zbxApi.allServerViewHost.success(data);
        dashboardHostEvent(hostEvent);
    });

    //이벤트 목록
    dashboardEventList();

    //요일별이벤트발생빈도
    dashboardDayEvent();
}

function dashboardEventStatus(){
    var DAYTOMILLS = 1000*60*60*24;

    var today_select = new Date();
    today_select = today_select-(today_select % DAYTOMILLS);

    $.when(zbxApi.alertTrigger.get(), zbxApi.unAckknowledgeEvent.get(), zbxApi.todayEvent.get(today_select)).done(function(data_a, data_b, data_c) {
        zbxApi.alertTrigger.success(data_a[0]);
        zbxApi.unAckknowledgeEvent.success(data_b[0]);
        zbxApi.todayEvent.success(data_c[0]);
        console.log("today_select : " + today_select);
    }).fail(function() {
        console.log("dashboardView : Network Error");
        alertDiag("Network Error");
    });
}

function dashboardHostEvent(hostEvent){
    var hostNum = 0;
    var hostName = '';
    var hostEventCnt = 0;

    var tableDataArr = [];

    var dashboardHostEventHTML = '';

    dashboardHostEventHTML += "
";

    $.each(hostEvent.result, function(k, v){
        hostNum += 1;
        hostName = v.name;
        hostEventCnt = zbxSyncApi.alerthostTrigger(v.hostid);

        var tableDataObj = {};
        tableDataObj.hostNum = hostNum;
        tableDataObj.hostName = hostName;
        tableDataObj.hostEventCnt = hostEventCnt;
        tableDataArr.push(tableDataObj);

        dashboardHostEventHTML += "
";
        dashboardHostEventHTML += "" + hostNum + "	";
        dashboardHostEventHTML += "" + hostName + "	";
        dashboardHostEventHTML += "" + hostEventCnt + "	";
        dashboardHostEventHTML += "" + hostNum + "	";
        dashboardHostEventHTML += "
";
    });
    dashboardHostEventHTML += "
";
    $("#hostEventList").empty();
    $("#hostEventList").append(dashboardHostEventHTML);
}

function dashboardEventList() {
    var dashboard_Event = zbxSyncApi.dashboardTrigger();
    //console.log(dashboard_Event);
    //console.log(JSON.stringify(dashboard_Event));

    var eventTable = '';

    eventTable += '
';

    $.each(dashboard_Event, function (k, v) {
        var severity = convPriority(v.priority);
        var status = convStatus(v.value);
        var lastchange = convTime(v.lastchange);
        var age = convDeltaTime(v.lastchange);
        var ack = convAck(v.lastEvent.acknowledged);
        var eventId = v.lastEvent.eventid;
        var ackTime = zbxSyncApi.dashboardEvent(eventId);
            //console.log("ackTime : " + ackTime);
        ackTime = convTime(ackTime);
        var host = v.hosts[0].host;
        var description = v.description;

        eventTable += "
";
        eventTable += "" + severity + "	";
        eventTable += "" + status + "	";
        eventTable += "" + lastchange + "	";
        eventTable += "" + age + "	";
        eventTable += "" + ack + "	";
        eventTable += "" + ackTime + "	";
        eventTable += "" + host + "	";
        eventTable += "" +
            "" +
            "" + description + "	";
        eventTable += "
";
    });
    eventTable += "
";
    $("#dashboardEventList").empty();
    $("#dashboardEventList").append(eventTable);
}

function dashboardDayEvent(){ //selectRelatedObject
    //요일 구하기
    var WEEKTOMILLS = 1000*60*60*24*7;
    var today_select = new Date();
        today_select = Math.round((today_select-WEEKTOMILLS)/1000);

    var event_data = zbxSyncApi.dashboardDayEvent(today_select);
    var event_id = '';
    var event_clock = '';
    var event_triggerId = '';
    var event_priority = 0;

    $.each(event_data, function(k, v){
        event_id = v.eventid;
        event_clock = v.clock;
        event_triggerId = v.relatedObject.triggerid;
        event_priority = v.relatedObject.priority;
        //console.log(" EVENT ID : " + v.eventid + " / CLOCK : " + v.clock + " / TRIGGER ID : " + v.relatedObject.triggerid + " / PRIORITY : " + v.relatedObject.priority);

        if(event_priority == 1){ //information
            console.log(" information  EVENT ID : " + event_id + " / CLOCK : " + event_clock + " / TRIGGER ID : " + event_triggerId + " / PRIORITY : " + event_priority);
            console.log(" information  today_select : " + today_select);
        } else if(event_priority == 2){ //warning
            console.log(" warning      EVENT ID : " + event_id + " / CLOCK : " + event_clock + " / TRIGGER ID : " + event_triggerId + " / PRIORITY : " + event_priority);
            console.log(" warning      today_select : " + today_select);
        } else if(event_priority == 3){ //average
            console.log(" average      EVENT ID : " + event_id + " / CLOCK : " + event_clock + " / TRIGGER ID : " + event_triggerId + " / PRIORITY : " + event_priority);
            console.log(" average      today_select : " + today_select);
        } else if(event_priority == 4){ //high
            console.log(" high         EVENT ID : " + event_id + " / CLOCK : " + event_clock + " / TRIGGER ID : " + event_triggerId + " / PRIORITY : " + event_priority);
            console.log(" high         today_select : " + today_select);
        } else {
            console.log(" else         EVENT ID : " + event_id + " / CLOCK : " + event_clock + " / TRIGGER ID : " + event_triggerId + " / PRIORITY : " + event_priority);
            console.log(" else         today_select : " + today_select);
        }
    });

    /*$(function() {
        Highcharts.chart('chart_dayEvent', {
            chart: {
                type: 'column',
                height: 300,
                backgroundColor: '#424973',
                spacingTop: 10,
                spacingBottom: 0,
                spacingLeft: 0,
                spacingRight: 0
            },
            title: {
                text: ''
            },
            subtitle: {
                text: ''
            },
            xAxis: {
                gridLineColor: '#FBFBFB',
                lineColor: '#FBFBFB',
                minorGridLineColor: '#505053',
                tickColor: '#FBFBFB',
                categories: [
                    '월요일',
                    '화요일',
                    '수요일',
                    '목요일',
                    '금요일',
                    '토요일',
                    '일요일'
                ],
                title: {
                    text: ''
                },
                style: {
                    color: '#FBFBFB'
                }
            },
            yAxis: {
                gridLineColor: '#FBFBFB',
                lineColor: '#FBFBFB',
                minorGridLineColor: '#505053',
                tickColor: '#FBFBFB',
                min: 0,
                title: {
                    text: ''
                },
                style: {
                    color: '#FBFBFB'
                }
            },
            tooltip: {
                backgroundColor: 'rgba(0, 0, 0, 0.85)',
                style: {
                    color: '#FBFBFB'
                }
            },
            plotOptions: {
                column: {
                    pointPadding: 0.2,
                    borderWidth: 0
                },
                style: {
                    color: '#FBFBFB'
                }
            },
            series: [{
                name: 'level',
                data: level_Event,
                color: '#FC4747'
            }, {
                name: 'High',
                data: high_Event,
                color: '#F2F234'
            }, {
                name: 'average',
                data: average_Event,
                color: '#FA60CE'
            }, {
                name: 'warring',
                data: warring_Event,
                color: '#F2F234'
            }],
            legend: {
                enabled: false
            },
            exporting: {
                buttons: {
                    contextButton: {
                        enabled: false,
                        symbolStroke: 'transparent',
                        theme: {
                            fill:'#626992'
                        }
                    }
                }
            }
        });
    });*/
}<commit_msg>2017.03.14 대시보드 요일별 이벤트 발생 빈도<commit_after>function dashboardView(){
    $(".info-box-content").block(blockUI_opt_el);

    //이벤트 현황
    dashboardEventStatus();

    //호스트별 장애현황
    var hostEvent = '';
    zbxApi.allServerViewHost.get().done(function(data, status, jqxHR){
        hostEvent = zbxApi.allServerViewHost.success(data);
        dashboardHostEvent(hostEvent);
    });

    //이벤트 목록
    dashboardEventList();

    //요일별이벤트발생빈도
    dashboardDayEvent();
}

function dashboardEventStatus(){
    var DAYTOMILLS = 1000*60*60*24;

    var today_select = new Date();
    today_select = today_select-(today_select % DAYTOMILLS);

    $.when(zbxApi.alertTrigger.get(), zbxApi.unAckknowledgeEvent.get(), zbxApi.todayEvent.get(today_select)).done(function(data_a, data_b, data_c) {
        zbxApi.alertTrigger.success(data_a[0]);
        zbxApi.unAckknowledgeEvent.success(data_b[0]);
        zbxApi.todayEvent.success(data_c[0]);
        console.log("today_select : " + today_select);
    }).fail(function() {
        console.log("dashboardView : Network Error");
        alertDiag("Network Error");
    });
}

function dashboardHostEvent(hostEvent){
    var hostNum = 0;
    var hostName = '';
    var hostEventCnt = 0;

    var tableDataArr = [];

    var dashboardHostEventHTML = '';

    dashboardHostEventHTML += "
";

    $.each(hostEvent.result, function(k, v){
        hostNum += 1;
        hostName = v.name;
        hostEventCnt = zbxSyncApi.alerthostTrigger(v.hostid);

        var tableDataObj = {};
        tableDataObj.hostNum = hostNum;
        tableDataObj.hostName = hostName;
        tableDataObj.hostEventCnt = hostEventCnt;
        tableDataArr.push(tableDataObj);

        dashboardHostEventHTML += "
";
        dashboardHostEventHTML += "" + hostNum + "	";
        dashboardHostEventHTML += "" + hostName + "	";
        dashboardHostEventHTML += "" + hostEventCnt + "	";
        dashboardHostEventHTML += "" + hostNum + "	";
        dashboardHostEventHTML += "
";
    });
    dashboardHostEventHTML += "
";
    $("#hostEventList").empty();
    $("#hostEventList").append(dashboardHostEventHTML);
}

function dashboardEventList() {
    var dashboard_Event = zbxSyncApi.dashboardTrigger();
    //console.log(dashboard_Event);
    //console.log(JSON.stringify(dashboard_Event));

    var eventTable = '';

    eventTable += '
';

    $.each(dashboard_Event, function (k, v) {
        var severity = convPriority(v.priority);
        var status = convStatus(v.value);
        var lastchange = convTime(v.lastchange);
        var age = convDeltaTime(v.lastchange);
        var ack = convAck(v.lastEvent.acknowledged);
        var eventId = v.lastEvent.eventid;
        var ackTime = zbxSyncApi.dashboardEvent(eventId);
        //console.log("ackTime : " + ackTime);
        ackTime = convTime(ackTime);
        var host = v.hosts[0].host;
        var description = v.description;

        eventTable += "
";
        eventTable += "" + severity + "	";
        eventTable += "" + status + "	";
        eventTable += "" + lastchange + "	";
        eventTable += "" + age + "	";
        eventTable += "" + ack + "	";
        eventTable += "" + ackTime + "	";
        eventTable += "" + host + "	";
        eventTable += "" +
            "" +
            "" + description + "	";
        eventTable += "
";
    });
    eventTable += "
";
    $("#dashboardEventList").empty();
    $("#dashboardEventList").append(eventTable);
}

function dashboardDayEvent(){ //selectRelatedObject
    //요일 구하기
    //var WEEKTOMILLS = 1000*60*60*24*7;
    //var today_select = new Date();
    //today_select = Math.round((today_select-WEEKTOMILLS)/1000);

    var DAYTOMILLS = 60*60*24;
    var date = new Date();
        date = date.setDate(date.getDate() - 7);
    var today_select = date - (date % DAYTOMILLS);
        today_select = Math.round(today_select / 1000);
    console.log(" 일주일 전 시간 : " + today_select);

    var event_data = zbxSyncApi.dashboardDayEvent(today_select);
    var event_id = '';
    var event_clock = '';
    var event_triggerId = '';
    var event_priority = 0;

    $.each(event_data, function(k, v){
        event_id = v.eventid;
        event_clock = v.clock;
        event_triggerId = v.relatedObject.triggerid;
        event_priority = v.relatedObject.priority;
        //console.log(" EVENT ID : " + v.eventid + " / CLOCK : " + v.clock + " / TRIGGER ID : " + v.relatedObject.triggerid + " / PRIORITY : " + v.relatedObject.priority);

        if(event_priority == 1){ //information
            console.log(" information  EVENT ID : " + event_id + " / CLOCK : " + event_clock + " / TRIGGER ID : " + event_triggerId + " / PRIORITY : " + event_priority);
            console.log(" information  today_select : " + today_select);
        } else if(event_priority == 2){ //warning
            console.log(" warning      EVENT ID : " + event_id + " / CLOCK : " + event_clock + " / TRIGGER ID : " + event_triggerId + " / PRIORITY : " + event_priority);
            console.log(" warning      today_select : " + today_select);
        } else if(event_priority == 3){ //average
            console.log(" average      EVENT ID : " + event_id + " / CLOCK : " + event_clock + " / TRIGGER ID : " + event_triggerId + " / PRIORITY : " + event_priority);
            console.log(" average      today_select : " + today_select);
        } else if(event_priority == 4){ //high
            console.log(" high         EVENT ID : " + event_id + " / CLOCK : " + event_clock + " / TRIGGER ID : " + event_triggerId + " / PRIORITY : " + event_priority);
            console.log(" high         today_select : " + today_select);
        } else {
            console.log(" else         EVENT ID : " + event_id + " / CLOCK : " + event_clock + " / TRIGGER ID : " + event_triggerId + " / PRIORITY : " + event_priority);
            console.log(" else         today_select : " + today_select);
        }
    });

    /*$(function() {
     Highcharts.chart('chart_dayEvent', {
     chart: {
     type: 'column',
     height: 300,
     backgroundColor: '#424973',
     spacingTop: 10,
     spacingBottom: 0,
     spacingLeft: 0,
     spacingRight: 0
     },
     title: {
     text: ''
     },
     subtitle: {
     text: ''
     },
     xAxis: {
     gridLineColor: '#FBFBFB',
     lineColor: '#FBFBFB',
     minorGridLineColor: '#505053',
     tickColor: '#FBFBFB',
     categories: [
     '월요일',
     '화요일',
     '수요일',
     '목요일',
     '금요일',
     '토요일',
     '일요일'
     ],
     title: {
     text: ''
     },
     style: {
     color: '#FBFBFB'
     }
     },
     yAxis: {
     gridLineColor: '#FBFBFB',
     lineColor: '#FBFBFB',
     minorGridLineColor: '#505053',
     tickColor: '#FBFBFB',
     min: 0,
     title: {
     text: ''
     },
     style: {
     color: '#FBFBFB'
     }
     },
     tooltip: {
     backgroundColor: 'rgba(0, 0, 0, 0.85)',
     style: {
     color: '#FBFBFB'
     }
     },
     plotOptions: {
     column: {
     pointPadding: 0.2,
     borderWidth: 0
     },
     style: {
     color: '#FBFBFB'
     }
     },
     series: [{
     name: 'level',
     data: level_Event,
     color: '#FC4747'
     }, {
     name: 'High',
     data: high_Event,
     color: '#F2F234'
     }, {
     name: 'average',
     data: average_Event,
     color: '#FA60CE'
     }, {
     name: 'warring',
     data: warring_Event,
     color: '#F2F234'
     }],
     legend: {
     enabled: false
     },
     exporting: {
     buttons: {
     contextButton: {
     enabled: false,
     symbolStroke: 'transparent',
     theme: {
     fill:'#626992'
     }
     }
     }
     }
     });
     });*/
}<|endoftext|>


<commit_before>$(document).ready( function () {
    $('#inspector-table').DataTable( {
        "ajax": '/PIMS/inspectors.json'
    });
} );<commit_msg>copy to inspectors<commit_after>var showRender = function ( data, type, full, meta ) {
    return 'Show';
};

$(document).ready( function () {
    $('#inspector-table').DataTable( {
        "ajax": '/PIMS/inspectors.json',
        "columnDefs": [{
            "targets": 3,
            "render": showRender
          }]
    });

    $('#inspector-table').on( 'click', 'tbody tr', function () {
    	window.location.href = $(this).attr('href');
    } );
} );<|endoftext|>


<commit_before>const { AppSetting } = require('../core/app_setting');
const { BagItProfile } = require('../bagit/bagit_profile');
const { Constants } = require('../core/constants');
const { fork, spawn } = require('child_process');
const fs = require('fs');
const { Job } = require('../core/job');
const { JobParams } = require('../core/job_params');
const os = require('os');
const { PackageOperation } = require('../core/package_operation');
const path = require('path');
const { TestUtil } = require('../core/test_util');
const { Workflow } = require('../core/workflow');

// Values for these three will be set below.
let jobId = null;
let workflow = null;
let outputPath = null;

const bagItProfileId = '28f48fcc-064d-4acf-bb5b-ea6ad5c6264d';
const tarPluginId = '90110710-1ff9-4650-a086-d7b23772238f';

beforeAll(() => {
    setBaggingDir();
    saveBagItProfile();
    jobId = saveRunnableJob();
    workflow = saveRunnableWorkflow();
});

afterAll(() => {
    TestUtil.deleteJsonFile('AppSetting');
    TestUtil.deleteJsonFile('BagItProfile');
    TestUtil.deleteJsonFile('Job');
    TestUtil.deleteJsonFile('Workflow');
});

function setBaggingDir() {
    new AppSetting({
        name: 'Bagging Directory',
        value: os.tmpdir()
    }).save();
}

function saveBagItProfile() {
    let profile = BagItProfile.load(path.join(__dirname, '..', 'test', 'profiles', 'multi_manifest.json'));
    profile.save();
}

function saveRunnableJob() {
    let outputDir = AppSetting.list()[0].value;
    outputPath = path.join(outputDir, 'CLI_Test_Bag.tar');
    let bagItProfile = BagItProfile.find(bagItProfileId);
    setTag(bagItProfile, 'Source-Organization', 'Test University');
    setTag(bagItProfile, 'Title', 'CLI Test Bag');
    setTag(bagItProfile, 'Access', 'Institution');
    setTag(bagItProfile, 'Storage-Option', 'Standard');
    let packageOp = new PackageOperation('CLI_Test_Bag', outputPath);
    packageOp.packageFormat = 'BagIt';
    packageOp.pluginId = 'BagIt';
    packageOp.sourceFiles = [ __dirname ];
    let job = new Job({
        bagItProfile: bagItProfile,
        packageOp: packageOp
    });
    job.save();
    return job.id;
}

function setTag(profile, name, value) {
    profile.firstMatchingTag('tagName', name).userValue = value;
}

function saveRunnableWorkflow() {
    let workflow = new Workflow({
	    name: "CLI Test Workflow",
	    description: "Includes BagIt packaging but no uploads",
	    packageFormat: "BagIt",
	    packagePluginId: tarPluginId,
	    bagItProfileId: bagItProfileId,
	    storageServiceIds: []
    });
    workflow.save();
    return workflow;
}

function createJobParams() {
    return new JobParams({
        workflowName: 'CLI Test Workflow',
        packageName: path.basename(outputPath),
        files: [ __dirname ],
        tags: [
  		    {
  			    "tagFile": "bag-info.txt",
  			    "tagName": "Bag-Group-Identifier",
  			    "userValue": "Photos_2019"
  		    },
  		    {
  			    "tagFile": "bag-info.txt",
  			    "tagName": "Source-Organization",
  			    "userValue": "Test University"
  		    },
  		    {
  			    "tagFile": "aptrust-info.txt",
  			    "tagName": "Title",
  			    "userValue": "Photos from 2019"
  		    },
  		    {
  			    "tagFile": "aptrust-info.txt",
  			    "tagName": "Storage-Option",
  			    "userValue": "Standard"
  		    },
  		    {
  			    "tagFile": "aptrust-info.txt",
  			    "tagName": "Access",
  			    "userValue": "Institution"
  		    }
        ]
    });
}

function forkProcess(param, stdinData) {
    let modulePath = path.join(__dirname, '..', 'main.js');
    let params = ['--job', param];
    if (stdinData) {
        params = ['--stdin'];
    }
    let proc = fork(
        modulePath,
        params,
        { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] }
    );
    proc.on('message', (data) => {
        // console.log(data.toString());
    });
    proc.stdout.on('data', function(data) {
        // console.log(data.toString());
    });
    proc.stderr.on('data', function(data) {
        // console.error(data.toString());
    });
    // When sending job json to the child process' stdin,
    // we have to wait till it's ready, or it reads only
    // the last N bytes of the input. Node processes do not
    // emit a 'started' or 'ready' event, so we have to
    // give it some time to load before sending data to stdin.
    // The load time below is a guess, and varies from system
    // to system. Not sure why fork returns a process that isn't
    // fully initialized. :(
    //
    // Longer timeout for AppVeyor tests
    let timeout = os.platform() == 'win32' ? 1500 : 800;
    console.log(timeout)
    if (stdinData) {
        setTimeout(function() {
            proc.stdin.write(stdinData + "\n");
            proc.stdin.end();
        }, timeout)
    }
    expect(proc).toBeTruthy();
    return proc;
}

// Be safe about this. Don't delete anything outside the
// tmp dir.
function removeFile(filepath) {
    if (filepath.startsWith(os.tmpdir())&& fs.existsSync(filepath)) {
        fs.unlinkSync(filepath);
    }
}

test('Run job by UUID', done => {
    // Pass in the job UUID as the command line arg.
    // The JobLoader should load the job from the DART Jobs DB.
    forkProcess(jobId).on('exit', function(exitCode){
        expect(exitCode).toEqual(Constants.EXIT_SUCCESS);
        expect(outputPath).toBeTruthy();
        expect(fs.existsSync(outputPath)).toBe(true);
        removeFile(outputPath);
        done();
    });
});

test('Run job from Job JSON file', done => {
    let job = Job.find(jobId);
    let jsonPath = path.join(os.tmpdir(), 'DART_CLI_Test_Job.json');
    fs.writeFileSync(jsonPath, JSON.stringify(job));

    // Pass in the path of the Job JSON file as arg.
    // The JobLoader should load the job from that file.
    forkProcess(jsonPath).on('exit', function(exitCode){
        expect(exitCode).toEqual(Constants.EXIT_SUCCESS);
        expect(outputPath).toBeTruthy();
        expect(fs.existsSync(outputPath)).toBe(true);
        removeFile(outputPath);
        removeFile(jsonPath);
        done();
    });
});

test('Run job from JobParams JSON file', done => {
    let jobParams = createJobParams();
    let jsonPath = path.join(os.tmpdir(), 'DART_CLI_Test_JobParams.json');
    fs.writeFileSync(jsonPath, JSON.stringify(jobParams));

    // Pass in the path of the JobParams JSON file as arg.
    // The JobLoader should parse that file, assemble a Job
    // from it, and run the job.
    forkProcess(jsonPath).on('exit', function(exitCode){
        expect(exitCode).toEqual(Constants.EXIT_SUCCESS);
        expect(outputPath).toBeTruthy();
        expect(fs.existsSync(outputPath)).toBe(true);
        removeFile(outputPath);
        removeFile(jsonPath);
        done();
    });
});

test('Run job from Job JSON passed through STDIN', done => {
    let job = Job.find(jobId);
    let jobJson = JSON.stringify(job);
    forkProcess('', jobJson).on('exit', function(exitCode){
        expect(exitCode).toEqual(Constants.EXIT_SUCCESS);
        expect(outputPath).toBeTruthy();
        expect(fs.existsSync(outputPath)).toBe(true);
        removeFile(outputPath);
        done();
    });
});

test('Run job from JobParams JSON passed through STDIN', done => {
    let jobParams = createJobParams();
    let jsonData = JSON.stringify(jobParams);

    forkProcess(null, jsonData).on('exit', function(exitCode){
        expect(exitCode).toEqual(Constants.EXIT_SUCCESS);
        expect(outputPath).toBeTruthy();
        expect(fs.existsSync(outputPath)).toBe(true);
        removeFile(outputPath);
        done();
    });
});
<commit_msg>Another attempt at AppVeyor fix<commit_after>const { AppSetting } = require('../core/app_setting');
const { BagItProfile } = require('../bagit/bagit_profile');
const { Constants } = require('../core/constants');
const { fork, spawn } = require('child_process');
const fs = require('fs');
const { Job } = require('../core/job');
const { JobParams } = require('../core/job_params');
const os = require('os');
const { PackageOperation } = require('../core/package_operation');
const path = require('path');
const { TestUtil } = require('../core/test_util');
const { Workflow } = require('../core/workflow');

// Values for these three will be set below.
let jobId = null;
let workflow = null;
let outputPath = null;

const bagItProfileId = '28f48fcc-064d-4acf-bb5b-ea6ad5c6264d';
const tarPluginId = '90110710-1ff9-4650-a086-d7b23772238f';

beforeAll(() => {
    setBaggingDir();
    saveBagItProfile();
    jobId = saveRunnableJob();
    workflow = saveRunnableWorkflow();
});

afterAll(() => {
    TestUtil.deleteJsonFile('AppSetting');
    TestUtil.deleteJsonFile('BagItProfile');
    TestUtil.deleteJsonFile('Job');
    TestUtil.deleteJsonFile('Workflow');
});

function setBaggingDir() {
    new AppSetting({
        name: 'Bagging Directory',
        value: os.tmpdir()
    }).save();
}

function saveBagItProfile() {
    let profile = BagItProfile.load(path.join(__dirname, '..', 'test', 'profiles', 'multi_manifest.json'));
    profile.save();
}

function saveRunnableJob() {
    let outputDir = AppSetting.list()[0].value;
    outputPath = path.join(outputDir, 'CLI_Test_Bag.tar');
    let bagItProfile = BagItProfile.find(bagItProfileId);
    setTag(bagItProfile, 'Source-Organization', 'Test University');
    setTag(bagItProfile, 'Title', 'CLI Test Bag');
    setTag(bagItProfile, 'Access', 'Institution');
    setTag(bagItProfile, 'Storage-Option', 'Standard');
    let packageOp = new PackageOperation('CLI_Test_Bag', outputPath);
    packageOp.packageFormat = 'BagIt';
    packageOp.pluginId = 'BagIt';
    packageOp.sourceFiles = [ __dirname ];
    let job = new Job({
        bagItProfile: bagItProfile,
        packageOp: packageOp
    });
    job.save();
    return job.id;
}

function setTag(profile, name, value) {
    profile.firstMatchingTag('tagName', name).userValue = value;
}

function saveRunnableWorkflow() {
    let workflow = new Workflow({
	    name: "CLI Test Workflow",
	    description: "Includes BagIt packaging but no uploads",
	    packageFormat: "BagIt",
	    packagePluginId: tarPluginId,
	    bagItProfileId: bagItProfileId,
	    storageServiceIds: []
    });
    workflow.save();
    return workflow;
}

function createJobParams() {
    return new JobParams({
        workflowName: 'CLI Test Workflow',
        packageName: path.basename(outputPath),
        files: [ __dirname ],
        tags: [
  		    {
  			    "tagFile": "bag-info.txt",
  			    "tagName": "Bag-Group-Identifier",
  			    "userValue": "Photos_2019"
  		    },
  		    {
  			    "tagFile": "bag-info.txt",
  			    "tagName": "Source-Organization",
  			    "userValue": "Test University"
  		    },
  		    {
  			    "tagFile": "aptrust-info.txt",
  			    "tagName": "Title",
  			    "userValue": "Photos from 2019"
  		    },
  		    {
  			    "tagFile": "aptrust-info.txt",
  			    "tagName": "Storage-Option",
  			    "userValue": "Standard"
  		    },
  		    {
  			    "tagFile": "aptrust-info.txt",
  			    "tagName": "Access",
  			    "userValue": "Institution"
  		    }
        ]
    });
}

function forkProcess(param, stdinData) {
    let modulePath = path.join(__dirname, '..', 'main.js');
    let params = ['--job', param];
    if (stdinData) {
        params = ['--stdin'];
    }
    let proc = fork(
        modulePath,
        params,
        { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] }
    );
    proc.on('message', (data) => {
        // console.log(data.toString());
    });
    proc.stdout.on('data', function(data) {
        // console.log(data.toString());
    });
    proc.stderr.on('data', function(data) {
        // console.error(data.toString());
    });
    // When sending job json to the child process' stdin,
    // we have to wait till it's ready, or it reads only
    // the last N bytes of the input. Node processes do not
    // emit a 'started' or 'ready' event, so we have to
    // give it some time to load before sending data to stdin.
    // The load time below is a guess, and varies from system
    // to system. Not sure why fork returns a process that isn't
    // fully initialized. :(
    //
    // Adjust timeout for AppVeyor tests
    let timeout = os.platform() == 'win32' ? 200 : 800;
    if (stdinData) {
        setTimeout(function() {
            proc.stdin.write(stdinData + "\n");
            proc.stdin.end();
        }, timeout)
    }
    expect(proc).toBeTruthy();
    return proc;
}

// Be safe about this. Don't delete anything outside the
// tmp dir.
function removeFile(filepath) {
    if (filepath.startsWith(os.tmpdir())&& fs.existsSync(filepath)) {
        fs.unlinkSync(filepath);
    }
}

test('Run job by UUID', done => {
    // Pass in the job UUID as the command line arg.
    // The JobLoader should load the job from the DART Jobs DB.
    forkProcess(jobId).on('exit', function(exitCode){
        expect(exitCode).toEqual(Constants.EXIT_SUCCESS);
        expect(outputPath).toBeTruthy();
        expect(fs.existsSync(outputPath)).toBe(true);
        removeFile(outputPath);
        done();
    });
});

test('Run job from Job JSON file', done => {
    let job = Job.find(jobId);
    let jsonPath = path.join(os.tmpdir(), 'DART_CLI_Test_Job.json');
    fs.writeFileSync(jsonPath, JSON.stringify(job));

    // Pass in the path of the Job JSON file as arg.
    // The JobLoader should load the job from that file.
    forkProcess(jsonPath).on('exit', function(exitCode){
        expect(exitCode).toEqual(Constants.EXIT_SUCCESS);
        expect(outputPath).toBeTruthy();
        expect(fs.existsSync(outputPath)).toBe(true);
        removeFile(outputPath);
        removeFile(jsonPath);
        done();
    });
});

test('Run job from JobParams JSON file', done => {
    let jobParams = createJobParams();
    let jsonPath = path.join(os.tmpdir(), 'DART_CLI_Test_JobParams.json');
    fs.writeFileSync(jsonPath, JSON.stringify(jobParams));

    // Pass in the path of the JobParams JSON file as arg.
    // The JobLoader should parse that file, assemble a Job
    // from it, and run the job.
    forkProcess(jsonPath).on('exit', function(exitCode){
        expect(exitCode).toEqual(Constants.EXIT_SUCCESS);
        expect(outputPath).toBeTruthy();
        expect(fs.existsSync(outputPath)).toBe(true);
        removeFile(outputPath);
        removeFile(jsonPath);
        done();
    });
});

test('Run job from Job JSON passed through STDIN', done => {
    let job = Job.find(jobId);
    let jobJson = JSON.stringify(job);
    forkProcess('', jobJson).on('exit', function(exitCode){
        expect(exitCode).toEqual(Constants.EXIT_SUCCESS);
        expect(outputPath).toBeTruthy();
        expect(fs.existsSync(outputPath)).toBe(true);
        removeFile(outputPath);
        done();
    });
});

test('Run job from JobParams JSON passed through STDIN', done => {
    let jobParams = createJobParams();
    let jsonData = JSON.stringify(jobParams);

    forkProcess(null, jsonData).on('exit', function(exitCode){
        expect(exitCode).toEqual(Constants.EXIT_SUCCESS);
        expect(outputPath).toBeTruthy();
        expect(fs.existsSync(outputPath)).toBe(true);
        removeFile(outputPath);
        done();
    });
});
<|endoftext|>


<commit_before>let Promise       = require('bluebird')
let path          = require('path')
let fs            = Promise.promisifyAll(require('fs'))
let mkdirp        = Promise.promisifyAll(require('mkdirp'))
let rimraf        = Promise.promisify(require('rimraf'))
let formidable    = require('formidable')
let child_process = require('child-process-promise')

let appRoot = path.join(path.dirname(require.main.filename), '../')

// create a new file and write content in it
let createFile = function (name, context) {
  return new Promise((resolve, reject) => {

    fs.writeFileAsync(path.join(appRoot, name), context).then(() => {
      resolve()
    }).catch(error => {
      console.log(error)
      reject('file error')
    })
  })
}

// delete a file
let deleteFile = function (name) {
  return new Promise((resolve, reject) => {
    fs.unlinkAsync(path.join(appRoot, name)).then(() => {
      resolve()
    }).catch(error => {
      console.log(error)
      reject('file error')
    })
  })
}

// read a file
let readFile = function (name, type = undefined) {
  return new Promise((resolve, reject) => {
    let promise
    if (type !== undefined) {
      promise = fs.readFileAsync(path.join(appRoot, name), type)
    } else {
      promise = fs.readFileAsync(path.join(appRoot, name))
    }
    promise.then(context => {
      resolve(context)
    }).catch(error => {
      console.log(error)
      reject('file error')
    })
  })
}

// create a new folder (can be nested)
let createFolder = function (name) {
  return new Promise((resolve, reject) => {
    mkdirp.mkdirpAsync(name).then(() => {
      resolve()
    }).catch(error => {
      console.log(error)
      reject('file error')
    })
  })
}

// delete a folder (can be nested)
let deleteFolder = function (path) {
  return new Promise((resolve, reject) => {
    rimraf(path).then(() => {
      resolve()
    }).catch(error => {
      console.log(error)
      reject('file error')
    })
  })
}

let processFormData = function (data) {
  return new Promise((resolve, reject) => {
    let form = new formidable.IncomingForm()
    form.encoding       = 'utf-8'
    form.keepExtensions = true
    form.multiples      = true

    form.parse(data, (err, fields, files) => {
      if (err) {
        console.log('error')
        reject('file error')
        return
      }

      let promise = []
      for (let i in files) {
        if (Array.isArray(files[i])) {
          for (let j in files[i]) {
            promise.push(child_process.exec('tr -d \\r < ' + files[i][j].path + ' > ' + files[i][j].path))
          }
        } else {
          promise.push(child_process.exec('tr -d \\r < ' + files[i].path + ' > ' + files[i].path))
        }
      }
      Promise.all(promise).then(() => {
        resolve({fields: fields, files: files})
      }).catch(error => {
        console.log(error)
        reject()
      })
    })
  })
}

let moveFile = function (from, to) {
  return new Promise((resolve, reject) => {
    fs.rename(from, path.join(appRoot, to), err => {
      if (err) {
        reject('file error')
        return
      }
      resolve()
    })
  })
}

let copyFile = function (from, to) {
  return new Promise((resovle, reject) => {
    fs.copyFile(from, to, err => {
      if (err) {
        reject('file error')
        return
      }
      resovle()
    })
  })
}

module.exports = {
  createFile:      createFile,
  deleteFile:      deleteFile,
  readFile:        readFile,
  createFolder:    createFolder,
  deleteFolder:    deleteFolder,
  processFormData: processFormData,
  moveFile:        moveFile,
  copyFile:        copyFile
}

<commit_msg>test tr<commit_after>let Promise       = require('bluebird')
let path          = require('path')
let fs            = Promise.promisifyAll(require('fs'))
let mkdirp        = Promise.promisifyAll(require('mkdirp'))
let rimraf        = Promise.promisify(require('rimraf'))
let formidable    = require('formidable')
let child_process = require('child-process-promise')

let appRoot = path.join(path.dirname(require.main.filename), '../')

// create a new file and write content in it
let createFile = function (name, context) {
  return new Promise((resolve, reject) => {

    fs.writeFileAsync(path.join(appRoot, name), context).then(() => {
      resolve()
    }).catch(error => {
      console.log(error)
      reject('file error')
    })
  })
}

// delete a file
let deleteFile = function (name) {
  return new Promise((resolve, reject) => {
    fs.unlinkAsync(path.join(appRoot, name)).then(() => {
      resolve()
    }).catch(error => {
      console.log(error)
      reject('file error')
    })
  })
}

// read a file
let readFile = function (name, type = undefined) {
  return new Promise((resolve, reject) => {
    let promise
    if (type !== undefined) {
      promise = fs.readFileAsync(path.join(appRoot, name), type)
    } else {
      promise = fs.readFileAsync(path.join(appRoot, name))
    }
    promise.then(context => {
      resolve(context)
    }).catch(error => {
      console.log(error)
      reject('file error')
    })
  })
}

// create a new folder (can be nested)
let createFolder = function (name) {
  return new Promise((resolve, reject) => {
    mkdirp.mkdirpAsync(name).then(() => {
      resolve()
    }).catch(error => {
      console.log(error)
      reject('file error')
    })
  })
}

// delete a folder (can be nested)
let deleteFolder = function (path) {
  return new Promise((resolve, reject) => {
    rimraf(path).then(() => {
      resolve()
    }).catch(error => {
      console.log(error)
      reject('file error')
    })
  })
}

let processFormData = function (data) {
  return new Promise((resolve, reject) => {
    let form = new formidable.IncomingForm()
    form.encoding       = 'utf-8'
    form.keepExtensions = true
    form.multiples      = true

    form.parse(data, (err, fields, files) => {
      if (err) {
        console.log('error')
        reject('file error')
        return
      }

      let promise = []
      for (let i in files) {
        if (Array.isArray(files[i])) {
          for (let j in files[i]) {
            promise.push(child_process.exec('tr -d \r < ' + files[i][j].path + ' > ' + files[i][j].path))
          }
        } else {
          promise.push(child_process.exec('tr -d \r < ' + files[i].path + ' > ' + files[i].path))
        }
      }
      Promise.all(promise).then(() => {
        resolve({fields: fields, files: files})
      }).catch(error => {
        console.log(error)
        reject()
      })
    })
  })
}

let moveFile = function (from, to) {
  return new Promise((resolve, reject) => {
    fs.rename(from, path.join(appRoot, to), err => {
      if (err) {
        reject('file error')
        return
      }
      resolve()
    })
  })
}

let copyFile = function (from, to) {
  return new Promise((resovle, reject) => {
    fs.copyFile(from, to, err => {
      if (err) {
        reject('file error')
        return
      }
      resovle()
    })
  })
}

module.exports = {
  createFile:      createFile,
  deleteFile:      deleteFile,
  readFile:        readFile,
  createFolder:    createFolder,
  deleteFolder:    deleteFolder,
  processFormData: processFormData,
  moveFile:        moveFile,
  copyFile:        copyFile
}

<|endoftext|>


<commit_before><commit_msg>Changed a variable that wasn't displaying correctly<commit_after><|endoftext|>


<commit_before>// const app = require('../../main');
// const { expect } = require('chai');
// const supertest = require('supertest');
// const server = supertest.agent('http://localhost:3006');

// describe('Integration tests', () => {
//     describe('Home route', () => {
//             it('Should return status 200', (done) => {
//                 server
//                     .get('/')
//                     .end((err, res) => {
//                         // console.log(res);
//                         expect(res.statusCode).to.equal(200);
//                         done();
//                 });
//         });

//     describe('Nonexisting route', () => {
//             it('Should return status 404', () => {
//                 server
//                     .get('/random')
//                     .expect(404);
//                 });
//         });

//     describe('Feed routes', () => {
//             it('Category page should return status 200', (done) => {
//                 server
//                     .get('/category/sport')
//                     .expect(200)
//                     .end((err, res) => {
//                         expect(res.statusCode).to.equal(200);
//                         done();
//                 });
//             });
//             it('Feed page should return status 200', (done) => {
//                 server
//                     .get('/category/news/BBC news/http%3A%2F%2Ffeeds.bbci.co.uk%2Fnews%2Fworld%2Frss.xml')
//                     .expect(200)
//                     .end((err, res) => {
//                         expect(res.statusCode).to.equal(200);
//                         done();
//                 });
//             });
//             it('Article page should return status 200', (done) => {
//                 server
//                     .get('/category/news/BBC news/http%3A%2F%2Ffeeds.bbci.co.uk%2Fnews%2Fworld%2Frss.xml/li5flourv')
//                     .expect(200)
//                     .end((err, res) => {
//                         expect(res.statusCode).to.equal(200);
//                         done();
//                 });
//             });
//         });
//     });
// });
<commit_msg>integration test uncommented<commit_after>const app = require('../../main');
const { expect } = require('chai');
const supertest = require('supertest');
const server = supertest.agent('http://localhost:3006');

describe('Integration tests', () => {
    describe('Home route', () => {
            it('Should return status 200', (done) => {
                server
                    .get('/')
                    .end((err, res) => {
                        // console.log(res);
                        expect(res.statusCode).to.equal(200);
                        done();
                });
        });

    describe('Nonexisting route', () => {
            it('Should return status 404', () => {
                server
                    .get('/random')
                    .expect(404);
                });
        });

    describe('Feed routes', () => {
            it('Category page should return status 200', (done) => {
                server
                    .get('/category/sport')
                    .expect(200)
                    .end((err, res) => {
                        expect(res.statusCode).to.equal(200);
                        done();
                });
            });
            it('Feed page should return status 200', (done) => {
                server
                    .get('/category/news/BBC news/http%3A%2F%2Ffeeds.bbci.co.uk%2Fnews%2Fworld%2Frss.xml')
                    .expect(200)
                    .end((err, res) => {
                        expect(res.statusCode).to.equal(200);
                        done();
                });
            });
            it('Article page should return status 200', (done) => {
                server
                    .get('/category/news/BBC news/http%3A%2F%2Ffeeds.bbci.co.uk%2Fnews%2Fworld%2Frss.xml/li5flourv')
                    .expect(200)
                    .end((err, res) => {
                        expect(res.statusCode).to.equal(200);
                        done();
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>db.triangles.createIndex( { valid_date : 1, valid_time : 1, parameter_name : 1, triangle : "2dsphere" } );
db.triangles.createIndex( { valid_date : 1, valid_time : 1, parameter_name : 1  } );
db.hourlydata.createIndex( { measurement_key: 1, valid_date : 1, valid_time : 1 } );
db.hourlydata.createIndex( { valid_date : 1, valid_time : 1, parameter_name : 1 } );
db.hourlydata.createIndex( { measurement_key : 1, bounded : 1, hour_code : 1 } );
db.locations.createIndex( { measurement_key : 1, hour_code : 1 } );
db.loadedfiles.createIndex( { hour_code : 1 } );
db.delaunayjobs.createIndex( { hour_code : 1, parameter_name : 1 } );
db.delaunayjobs.createIndex( { dirty : 1 } );
<commit_msg>index for bounded update in hourlydata<commit_after>db.triangles.createIndex( { valid_date : 1, valid_time : 1, parameter_name : 1, triangle : "2dsphere" } );
db.triangles.createIndex( { valid_date : 1, valid_time : 1, parameter_name : 1  } );
db.hourlydata.createIndex( { measurement_key: 1, valid_date : 1, valid_time : 1 } );
db.hourlydata.createIndex( { valid_date : 1, valid_time : 1, parameter_name : 1 } );
db.hourlydata.createIndex( { measurement_key : 1, bounded : 1, hour_code : 1 } );
db.hourlydata.createIndex( { measurement_key : 1, hour_code : 1 } );
db.locations.createIndex( { measurement_key : 1, hour_code : 1 } );
db.loadedfiles.createIndex( { hour_code : 1 } );
db.delaunayjobs.createIndex( { hour_code : 1, parameter_name : 1 } );
db.delaunayjobs.createIndex( { dirty : 1 } );
<|endoftext|>