Best JavaScript code snippet using wpt
assessmentsCtrl.js
Source:assessmentsCtrl.js
1(function() {2 angular.module('occIDEASApp.Assessments')3 .controller('AssessmentsCtrl', AssessmentsCtrl);4 AssessmentsCtrl.$inject = ['AssessmentsService', 'InterviewsService', 'RulesService', 'ngTableParams', '$scope', '$filter',5 'data', '$log', '$compile', '$http', '$q', '$mdDialog', '$timeout', 'ParticipantsService', 'QuestionsService'6 , '$sessionStorage', 'ReportsService', 'SystemPropertyService',7 'ngToast', 'AgentsService', 'FiredRulesService'];8 function AssessmentsCtrl(AssessmentsService, InterviewsService, RulesService, NgTableParams, $scope, $filter,9 data, $log, $compile, $http, $q, $mdDialog, $timeout, ParticipantsService, QuestionsService,10 $sessionStorage, ReportsService, SystemPropertyService, $ngToast, AgentsService, FiredRulesService) {11 var self = this;12 $scope.data = data;13 $scope.$root.tabsLoading = false;14 $scope.updateButtonDisabled = false;15 $scope.statuses = ['Not Assessed', 'Manually assessed', 'Incomplete', 'Needs Review', 'Finished', 'Auto Assessed'];16 $scope.onChangeSaveStatus = function(idinterview, assessmentStatus) {17 InterviewsService.getInterviewWithRules(idinterview).then(function(response) {18 if(response.status == 200) {19 var interview = response.data[0];20 if(interview) {21 interview.assessedStatus = assessmentStatus;22 if(!(interview.notes)) {23 interview.notes = [];24 }25 interview.notes.push({26 interviewId: idinterview,27 text: "Updated Status",28 type: 'System'29 });30 saveInterview(interview);31 }32 } else {33 $ngToast.create({34 className: 'danger',35 content: 'Error calling webservice getInterview',36 dismissButton: true,37 dismissOnClick: false,38 animation: 'slide'39 });40 }41 });42 };43 $scope.getStatusList = function(column) {44 var statusArr = [];45 var index = 0;46 _.each($scope.statuses, function(value) {47 statusArr.push({48 'id': value,49 'title': value50 });51 index++;52 });53 return statusArr;54 };55 $scope.interviewStatusList = [{56 'id': 0,57 'title': 'Running'58 },59 {60 'id': 1,61 'title': 'Partial'62 },63 {64 'id': 2,65 'title': 'Completed'66 },67 {68 'id': 3,69 'title': 'To be excluded'70 }71 ];72 $scope.getInterviewStatusList = function(column) {73 return $scope.interviewStatusList;74 };75 function saveInterview(interview) {76 InterviewsService.save(interview).then(function(response) {77 if(response.status === 200) {78 $log.info("Saving interview at assessment note with id:" + interview.interviewId + " successful");79 $ngToast.create({80 className: 'success',81 content: "Save successful",82 timeout: 4000,83 dismissButton: true84 });85 } else {86 $ngToast.create({87 className: 'danger',88 content: "Save failed",89 timeout: 4000,90 dismissButton: true91 });92 }93 });94 }95 $scope.updateRules = function() {96 $scope.currentParticipants.reduce(function(p, data) {97 return p.then(function() {98 $scope.interviewIdInProgress = data.idinterview;99 $scope.counter++;100 $scope.interviewCount = $scope.counter;101 AgentsService.getStudyAgentsWithRules(data.idinterview).then(function(response) {102 data.agents = [];103 _.each(response, function(agent) {104 data.agents.push(agent);105 });106 FiredRulesService.getByInterviewId(data.idinterview).then(function(response) {107 if(response.status == '200') {108 var interviewFiredRules = response.data;109 data.interviewFiredRules = interviewFiredRules;110 data.firedRules = [];111 data.agentCount = [];112 for(var i = 0; i < interviewFiredRules.length; i++) {113 var rules = interviewFiredRules[i].rules;114 var key = data.idinterview;115 for(var j = 0; j < rules.length; j++) {116 for(var x = 0; x < rules[j].conditions.length; x++) {117 var node = rules[j].conditions[x];118 }119 data.firedRules.push(rules[j]);120 var agentCount = _.find(data.agentCount,121 function(o) {122 return o.idAgent == rules[j].agentId;123 });124 if(agentCount) {125 agentCount.count = agentCount.count + 1;126 } else {127 data.agentCount.push({128 idAgent: rules[j].agentId,129 count: 1130 });131 }132 }133 if(data.agentCount && data.agentCount.length > 0) {134 var arr = _.map(data.agentCount, function(element, idx) {135 return element.count;136 });137 var num = _.max(arr);138// if(num > 12){139 if(num < 3) {140 num = 3;141 }142 var borderTopPx = 7;143 var borderLowPx = 7;144 var result = num;145 var height = (result / 3) * 5.5;146 data[key] = height + borderTopPx + borderLowPx;147// }148 }149 }150 }151 });152 });153 });154 }, $q.when(true)).then(function(finalResult) {155 console.log('finish loading rules');156// $timeout(function() {157// $scope.cancel();158// ModulesService.save(row).then(function(response){159// if(response.status === 200){160// console.log('Module Save was Successful!');161// self.tableParams.shouldGetData = true;162// self.tableParams.reload().then(function (data) {163// if (data.length === 0 && self.tableParams.total() > 0) {164// self.tableParams.page(self.tableParams.page() - 1);165// self.tableParams.reload();166// $location.hash("");167// $anchorScroll();168// }169// });170// }171// });172// }, 1000); 173// self.tableParams.reload();174 }, function(err) {175 console.log('error');176 });177 };178 $scope.modules = function(column) {179 var def = $q.defer();180 /* http service is based on $q service */181 InterviewsService.getDistinctModules().then(function(response) {182 var arr = [],183 module = [];184 angular.forEach(response.data, function(item) {185 if(!_.find(module, _.matchesProperty('title', item.interviewModuleName))) {186 if(item.idModule != $sessionStorage.activeIntro.value) {187 arr.push(item.interviewModuleName);188 module.push({189 'id': item.interviewModuleName,190 'title': item.interviewModuleName191 });192 module = _.sortBy(module, 'title');193 arr = arr.sort();194 }195 }196 });197 /* whenever the data is available it resolves the object */198 def.resolve(module);199 });200 return def;201 };202 // QuestionsService.getAllMultipleQuestion().then(function(response){203 // if(response.status == '200'){204 // $scope.multipleQuestions = response.data;205 // }206 // });207 $scope.openInterviewBtn = function() {208 };209 self.cols = [210 {field: "idParticipant", title: "idParticipant"}211 ];212 self.openFiredRules = function(interviewId, reference, interviewModuleName) {213 InterviewsService.findModulesByInterviewId(interviewId).then(function(response) {214 if(response.status == '200') {215 if(response.data.length > 0) {216 var modules = response.data;217 var isSameIntroModule = true;218 var introModule = _.find(modules, function(module) {219 return module.idModule == $sessionStorage.activeIntro.value;220 });221 if(!introModule) {222 isSameIntroModule = false;223 }224 var interview = {225 interviewId: interviewId,226 referenceNumber: reference,227 moduleName: interviewModuleName,228 isSameIntroModule: isSameIntroModule229 };230 $scope.addFiredRulesTab(interview);231 console.log('FiredRulesTab Opened');232 }233 }234 });235 };236 $scope.getInterviewForCSVButton = function() {237 $scope.showExportCSV();238 };239 $scope.getCSVButton = function() {240 return $scope.csv;241 };242// AssessmentsService.getAssessmentSize('All').then(function(response){ 243// $scope.totalAssessmentSize = 0;244// if(response.status == '200'){245// $scope.totalAssessmentSize = response.data;246// }247// });248 $scope.updateAutoAssessmentsButton = function(ev) {249 var status = 'All';250 $scope.status = status;251 $scope.estimatedDuration = getEstimatedDuration(status);252 $scope.showButtons = true;253 $mdDialog.show({254 scope: $scope,255 preserveScope: true,256 templateUrl: 'scripts/assessments/partials/autoAssessmentDialog.html',257 clickOutsideToClose: false258 });259 };260 $scope.updateButton = function(status) {261 $scope.updateButtonDisabled = true;262 $scope.processAutoAssessment = true;263 $scope.showButtons = false;264 AssessmentsService.updateAutoAssessments(status).then(function(response) {265 if(response) {266 $scope.updateButtonDisabled = false;267 $scope.processAutoAssessment = false;268 $scope.cancel();269 $ngToast.create({270 className: 'success',271 content: 'Auto assessment is completed.',272 animation: 'slide'273 });274 console.log('Assessments Updated: ' + status);275 self.tableParams.reload();276 }277 });278 };279 // Make a guesstimate, 3 seconds per assessment280 function getEstimatedDuration(status) {281 var estimateInMin = 0;282 var defaultDurationInSec = 3; // Slow283 if(status === 'All') {284 estimateInMin = defaultDurationInSec * self.tableParams.total();285 } else if(status === 'Auto Assessed') {286 estimateInMin = defaultDurationInSec * $scope.assessedSize;287 } else {288 estimateInMin = defaultDurationInSec * $scope.notAssessedSize;289 }290 return estimateInMin / 60;291 }292 $scope.showExportCSVButton = function() {293 // get list of interview id294 InterviewsService.getInterviewIdList().then(function(response) {295 if(response.status == '200') {296 // display modal with list of id + progress bar297 $scope.interviewIdList = response.data;298 $scope.interviewIdCount = $scope.interviewIdList.length;299 $scope.counter = 0;300 $scope.interviewCount = $scope.counter;301 $mdDialog.show({302 scope: $scope,303 preserveScope: true,304 templateUrl: 'scripts/assessments/partials/exportCSVDialog.html',305 clickOutsideToClose: false306 });307 $scope.csv = [];308 $scope.csvTemp = [{309 Q: []310 }];311 var listOfQuestion = [];312 InterviewsService.getInterviewsWithoutAnswers().then(function(response) {313 if(response.status == '200') {314 var questionIdList = listAllInterviewQuestions(response.data, $scope.csvTemp, listOfQuestion);315 $scope.interviewIdList.reduce(function(p, interviewId) {316 return p.then(function() {317 $scope.interviewIdInProgress = interviewId;318 $scope.counter++;319 $scope.interviewCount = $scope.counter;320 return populateInterviewAnswerList(interviewId, questionIdList);321 });322 }, $q.when(true)).then(function(finalResult) {323 console.log('finish extracting data for CSV');324 $timeout(function() {325 angular.element(document.querySelector('#exportCSV')).triggerHandler('click');326 $scope.cancel();327 addToReports("Export Report CSV", $scope.csv, "completed");328 }, 1000);329 }, function(err) {330 addToReports("Export Report CSV", $scope.csv, "error");331 console.log('error');332 });333 }334 });335 }336 });337 function addToReports(name, data, status) {338 var jsonData = JSON.stringify(data);339 var report = {340 type: "Module JSON (Export)",341 name: name,342 path: "",343 status: status,344 progress: "100",345 requestor: $sessionStorage.userId,346 updatedBy: $sessionStorage.userId,347 jsonData: jsonData348 };349 ReportsService.save(report).then(function(response) {350 if(response.status == '200') {351 console.log("reports was successfully saved.");352 }353 });354 }355 function populateInterviewAnswerList(interviewId, questionIdList) {356 return InterviewsService.getInterviewQuestionAnswer(interviewId).then(function(response) {357 if(response.status == '200') {358 listAllInterviewAnswers(response.data, $scope.csvTemp, questionIdList);359 }360 });361 }362 // loop through and trigger363 // InterviewService.getInterview(interviewId)364 // with deffered365 };366 function generateUniqueAgentsList(interviews) {367 _.each(interviews, function(interview) {368 appendToUniqueListOfAgents(interview);369 });370 }371 function prepareHeaderRow() {372 var obj = {A: []};373 obj.A.push("InterviewId");374 obj.A.push("ReferenceNumber");375 _.each($scope.uniqueListOfAgents, function(agent) {376 obj.A.push(agent.name + "_Auto");377 obj.A.push(agent.name + "_Manual");378 });379 $scope.csv.push(obj.A);380 }381 function prepareNoiseHeaderRow() {382 var obj = {A: []};383 obj.A.push("InterviewId");384 obj.A.push("ReferenceNumber");385 obj.A.push("totalPartialExposure");386 obj.A.push("autoExposureLevel");387 obj.A.push("peakNoise");388 obj.A.push("ShiftLength");389 $scope.csv.push(obj.A);390 }391 $scope.showExportAssessmentCSVButton = function() {392 // get list of interview id393 InterviewsService.getInterviewsListWithRules().then(function(response) {394 if(response.status == '200') {395 // display modal with list of id + progress bar396 $scope.interviewIdList = response.data;397 $scope.interviewIdCount = $scope.interviewIdList.length;398 $scope.counter = 0;399 $scope.interviewCount = $scope.counter;400 $mdDialog.show({401 scope: $scope,402 preserveScope: true,403 templateUrl: 'scripts/assessments/partials/exportCSVDialog.html',404 clickOutsideToClose: false405 });406 $scope.csv = [];407 $scope.csvTemp = [{408 Q: []409 }];410 generateUniqueAgentsList(response.data);411 prepareHeaderRow();412 $scope.interviewIdList.reduce(function(p, interview) {413 return p.then(function() {414 $scope.interviewIdInProgress = interview.interviewId;415 $scope.counter++;416 $scope.interviewCount = $scope.counter;417 return convertInterviewToAssessmentRow(interview.interviewId);418 });419 }, $q.when(true)).then(function(finalResult) {420 console.log('finish extracting data for CSV');421 $timeout(function() {422 angular.element(document.querySelector('#exportAssessmentCSV')).triggerHandler('click');423 $scope.cancel();424 }, 1000);425 }, function(err) {426 console.log('error');427 });428 }429 });430 function convertInterviewToAssessmentRow(interviewId) {431 return InterviewsService.getInterviewWithRules(interviewId).then(function(response) {432 if(response.status == '200') {433 addAssessmentRowToCsv(response.data[0]);434 }435 });436 }437 };438 $scope.showExportAssessmentNoiseCSVButton = function() {439 SystemPropertyService.getAll().then(function(response) {440 var sysprops = response.data;441 var ssagents = _.filter(sysprops, function(sysprop) {442 return sysprop.type == 'studyagent';443 });444 $scope.agents = [];445 _.each(ssagents, function(ssagent) {446 var agent = {name: ssagent.name, idAgent: ssagent.value};447 $scope.agents.push(agent);448 });449 // get list of interview id450 InterviewsService.getInterviewsListWithRules().then(function(response) {451 if(response.status == '200') {452 // display modal with list of id + progress bar453 $scope.interviewIdList = response.data;454 $scope.interviewIdCount = $scope.interviewIdList.length;455 $scope.counter = 0;456 $scope.interviewCount = $scope.counter;457 $mdDialog.show({458 scope: $scope,459 preserveScope: true,460 templateUrl: 'scripts/assessments/partials/exportCSVDialog.html',461 clickOutsideToClose: false462 });463 $scope.csv = [];464 $scope.csvTemp = [{465 Q: []466 }];467 if($scope.agents.length == 0) {468 generateUniqueAgentsList(response.data);469 } else {470 $scope.uniqueListOfAgents = $scope.agents;471 }472 prepareNoiseHeaderRow();473 $scope.interviewIdList.reduce(function(p, interview) {474 return p.then(function() {475 $scope.interviewIdInProgress = interview.interviewId;476 $scope.counter++;477 $scope.interviewCount = $scope.counter;478 return convertInterviewToAssessmentNoiseRow(interview.interviewId);479 });480 }, $q.when(true)).then(function(finalResult) {481 console.log('finish extracting data for CSV');482 $timeout(function() {483 angular.element(document.querySelector('#exportAssessmentCSV')).triggerHandler('click');484 $scope.cancel();485 }, 1000);486 }, function(err) {487 console.log('error');488 });489 }490 });491 function convertInterviewToAssessmentNoiseRow(interviewId) {492 return AssessmentsService.updateFiredRules(interviewId).then(function(response) {493 if(response.status == '200') {494 addAssessmentNoiseRowToCsv(response.data[0]);495 }496 });497 }498 });499 };500 $scope.cancel = function() {501 $mdDialog.cancel();502 };503 $scope.uniqueListOfAgents = [];504 function appendToUniqueListOfAgents(interview) {505 _.each(interview.agents, function(agent) {506 var agentInList = false;507 _.each($scope.uniqueListOfAgents, function(agnt) {508 if(agnt.idAgent == agent.idAgent) {509 agentInList = true;510 }511 });512 if(!agentInList) {513 $scope.uniqueListOfAgents.push(agent);514 }515 });516 }517 function addAssessmentRowToCsv(interview) {518 var obj = {A: []};519 obj.A.push(interview.interviewId);520 obj.A.push(interview.referenceNumber);521 _.each($scope.uniqueListOfAgents, function(agent) {522 var level = "Not Set";523 _.each(interview.autoAssessedRules, function(rule) {524 if(agent.idAgent == rule.agent.idAgent) {525 level = rule.level;526 }527 });528 obj.A.push(level);529 level = "Not Set";530 _.each(interview.manualAssessedRules, function(rule) {531 if(agent.idAgent == rule.agent.idAgent) {532 level = rule.level;533 }534 });535 obj.A.push(level);536 });537 $scope.csv.push(obj.A);538 }539 function addAssessmentNoiseRowToCsv(interview) {540 var model = interview;541 var obj = {A: []};542 obj.A.push(interview.interviewId);543 obj.A.push(interview.referenceNumber);544 var bFoundNoiseRules = false;545 var noiseRules = [];546 for(var i = 0; i < model.agents.length; i++) {547 var agentAssessing = model.agents[i];548 var rule = {levelValue: 99};549 for(var j = 0; j < model.firedRules.length; j++) {550 var firedRule = model.firedRules[j];551 if(agentAssessing.idAgent == firedRule.agent.idAgent) {552 if(firedRule.agent.idAgent == 116) {553 bFoundNoiseRules = true;554 noiseRules.push(firedRule);555 }556 }557 }558 }559 if(bFoundNoiseRules) {560 var totalPartialExposure = 0;561 var totalPartialExposurePerAdj = 0;562 var peakNoise = 0;563 var maxBackgroundPartialExposure = 0;564 var maxBackgroundHours = 0;565 $scope.noiseRows = [];566 var totalFrequency = 0;567 var backgroundHours = 0;568 var shiftHours = 0;569 for(var m = 0; m < model.answerHistory.length; m++) {570 var iqa = model.answerHistory[m];571 if(iqa.type == 'P_frequencyshifthours') {572 shiftHours = iqa.answerFreetext;573 break;574 }575 }576 for(var k = 0; k < noiseRules.length; k++) {577 var noiseRule = noiseRules[k];578 if(noiseRule.type != 'BACKGROUND') {579 var parentNode = noiseRule.conditions[0];580 // if(model.module){581 // cascadeFindNode(model.module.nodes,parentNode);582 // }else{583 cascadeFindNode(model.answerHistory, parentNode);584 // }585 var answeredValue = 0;586 if($scope.foundNode) {587 var frequencyHoursNode = findFrequencyIdNode($scope.foundNode);588 if(frequencyHoursNode) {589 answeredValue = frequencyHoursNode.answerFreetext;590 }591 $scope.foundNode = null;592 }593 totalFrequency += Number(answeredValue);594 }595 }596 var useRatio = false;597 var ratio = 1.0;598 if(totalFrequency > shiftHours) {599 useRatio = true;600 ratio = parseFloat(totalFrequency) / parseFloat(shiftHours);601 ratio = ratio.toFixed(4);602 }603 var level = 0;604 var peakNoise = 0;605 for(var k = 0; k < noiseRules.length; k++) {606 var noiseRule = noiseRules[k];607 if(noiseRule.ruleAdditionalfields == undefined) {608 var msg = "Error on Noise rule:" + noiseRule.idRule;609 $ngToast.create({610 className: 'danger',611 content: msg,612 animation: 'slide'613 });614 break;615 }616 if(noiseRule.type == 'BACKGROUND') {617 var hoursbg = shiftHours - totalFrequency;618 if(hoursbg < 0) {619 hoursbg = 0;620 }621 var partialExposure = 4 * hoursbg * (Math.pow(10, (level - 100) / 10));622 partialExposure = partialExposure.toFixed(4);623 hoursbg = hoursbg.toFixed(4);624 level = noiseRule.ruleAdditionalfields[0].value;625 var noiseRow = {626 nodeNumber: noiseRule.conditions[0].number,627 dB: level + 'B',628 backgroundhours: hoursbg,629 partialExposure: partialExposure,630 type: 'backgroundNoise'631 };632 $scope.noiseRows.push(noiseRow);633 if(partialExposure > maxBackgroundPartialExposure) {634 maxBackgroundPartialExposure = partialExposure;635 maxBackgroundHours = hoursbg;636 }637 } else {638 var hours = 0.0;639 var frequencyhours = 0;640 var parentNode = noiseRule.conditions[0];641 // if(model.module){642 cascadeFindNode(model.answerHistory, parentNode);643 // }else{644 // cascadeFindNode(model.fragment.nodes,parentNode);645 // }646 if($scope.foundNode) {647 var frequencyHoursNode = findFrequencyIdNode($scope.foundNode);648 if(frequencyHoursNode) {649 frequencyhours = frequencyHoursNode.answerFreetext;650 }651 $scope.foundNode = null;652 }653 if(useRatio) {654 hours = parseFloat(frequencyhours) / ratio;655 } else {656 hours = parseFloat(frequencyhours);657 }658 level = noiseRule.ruleAdditionalfields[0].value;659 var percentage = 100;660 var partialExposure = 4 * hours * (Math.pow(10, (level - 100) / 10));661 partialExposure = partialExposure.toFixed(4);662 hours = hours.toFixed(4);663 var modHours = "";664 if(useRatio) {665 modHours = "*" + hours + "*";666 } else {667 modHours = hours;668 }669 var noiseRow = {670 nodeNumber: noiseRule.conditions[0].number,671 dB: level,672 backgroundhours: modHours,673 partialExposure: partialExposure674 };675 $scope.noiseRows.push(noiseRow);676 totalPartialExposure = (parseFloat(totalPartialExposure) + parseFloat(partialExposure));677 }678 if(peakNoise < Number(level)) {679 peakNoise = Number(level);680 }681 }682 totalPartialExposure = (parseFloat(totalPartialExposure) + parseFloat(maxBackgroundPartialExposure));683 totalPartialExposure = totalPartialExposure.toFixed(4);684 totalFrequency += maxBackgroundHours;685 var autoExposureLevel = 10 * (Math.log10(totalPartialExposure / (3.2 * (Math.pow(10, -9)))));686 autoExposureLevel = autoExposureLevel.toFixed(4);687 obj.A.push(totalPartialExposure);688 obj.A.push(autoExposureLevel);689 obj.A.push(peakNoise);690 obj.A.push(shiftHours);691 }692 $scope.csv.push(obj.A);693 }694 function listAllInterviewAnswers(response, csvTemp, questionIdList) {695 _.each(response, function(data) {696 var obj = {A: []};697 obj.A.push(data.interviewId);698 obj.A.push(data.referenceNumber);699 // put notes and status700// obj.A.push(data.module.idNode);701 _.each(questionIdList, function(qId) {702 // check if qId has delimeter "_" which means is multiple703 if(typeof qId == 'string' && qId.indexOf('_') > -1) {704 var temp = qId.split('_');705 var questionId = temp[0];706 var number = temp[1];707 var question = _.find(data.questionHistory, function(qHistory) {708 return qHistory.questionId == questionId709 && qHistory.deleted == 0;710 });711 if(question) {712 if(question.answers.length > 0) {713 var numberExist = false;714 _.each(question.answers, function(ans) {715 if(ans.number == number && !numberExist) {716 if(ans.answerFreetext) {717 obj.A.push(ans.answerFreetext);718 numberExist = true;719 } else {720 obj.A.push(ans.name);721 numberExist = true;722 // console.error("could not find723 // freetext");724 // invalid = true;725 // notes = ""726 }727 }728 });729 if(!numberExist) {730 obj.A.push("-- No Answer --");731 }732 }733 } else {734 obj.A.push("-- Question Not Asked --");735 }736 } else {737 var question = _.find(data.questionHistory, function(qHistory) {738 return qHistory.questionId == qId739 && qHistory.deleted == 0;740 });741 if(question) {742 // check for deleted743 if(question.answers.length > 0) {744 var ans = question.answers[0];745 if(ans.answerFreetext) {746 obj.A.push(ans.answerFreetext);747 } else {748 obj.A.push(ans.name);749 }750 } else {751 obj.A.push("-- No Answer --");752 }753 } else {754 obj.A.push("-- Question Not Asked --");755 }756 }757 });758 $scope.csv.push(obj.A);759 });760 }761 function listAllInterviewQuestions(response, csvTemp, listOfQuestion) {762 var questionIdList = [];763 _.each(response, function(data) {764 data.questionHistory = _.filter(data.questionHistory, function(qh) {765 // $log.info("Interviewid: "+data.interviewId+" Questionid:766 // "+qh.questionId);767 return qh.deleted == 0 && qh.topNodeId == 15001;768 });769 // $log.info("Interviewid: "+data.interviewId+" Questionid: ");770 // join all questions to listOfQuestion771 listOfQuestion = listOfQuestion.concat(data.questionHistory);772 });773 var sortHeaderList = {};774 var header = "";775 _.each(listOfQuestion, function(data) {776 // check if the unique question is a module/ajsm or fragment, if777 // yes add it to the header778 // to be display along with the question number in the CSV779 if(data.nodeClass == 'M' || data.type == 'M_IntroModule' || data.type == 'Q_linkedajsm' || data.type == 'F_ajsm') {780 if(header != "") {781 sortHeaderList[header] = _.sortBy(sortHeaderList[header], 'header');782 }783 header = data.name.substring(0, 4);784 if(!sortHeaderList[topHeader]) {785 sortHeaderList[topHeader] = [];786 }787 // if the unique question is an actual question get the number788 // and append to its789 // respective header which can be a module/ajsm or fragment790 } else if(data.questionId) {791 // check if the question is of type Multiple, if yes will792 // need to793 // add header for each possible answer794 if(data.type == 'Q_multiple') {795 // check if question is in the multiple question bucket796 var nodeQuestion = _.find($scope.multipleQuestions, function(question) {797 return question.idNode == data.questionId;798 });799 // look for the top node id in listquestion800 // build the header and check it in sortHeaderList801 var topModule = _.find(listOfQuestion, function(lq) {802 return lq.link == data.topNodeId;803 });804 var topHeader = topModule.name.substring(0, 4);805 if(!sortHeaderList[topHeader]) {806 sortHeaderList[topHeader] = [];807 }808 _.each(nodeQuestion.nodes, function(posAns) {809 // loop through all possible answer810 sortHeaderList[topHeader].push({811 header: topHeader + "_" + data.number + "_" + posAns.number,812 questionId: data.questionId + "_" + posAns.number813 });814 });815 }816 // for standard questions add the header + question number817 else {818 // look for the top node id in listquestion819 // build the header and check it in sortHeaderList820 if(data.questionId == 43552) {821 console.log(data);822 }823 var topModule = _.find(listOfQuestion, function(lq) {824 return lq.link == data.topNodeId;825 });826 var topHeader = topModule.name.substring(0, 4);827 if(!sortHeaderList[topHeader]) {828 sortHeaderList[topHeader] = [];829 }830 sortHeaderList[topHeader].push({831 header: topHeader + "_" + data.number,832 questionId: data.questionId833 });834 }835 }836 });837 _.each(sortHeaderList, function(headerGroup) {838 // var uniqueHeaders =839 // _.unionBy(headers,headers,function(o){return o.header;});840 _.each(headerGroup, function(data) {841 csvTemp[0].Q.push(data.header);842 questionIdList.push(data.questionId);843 })844 });845 csvTemp[0].Q.unshift('AWES ID');846 csvTemp[0].Q.unshift('Interview Id');847 $scope.csv.push(csvTemp[0].Q);848 return questionIdList;849 }850 var getData = function() {851 $log.info("Data getting from interviews ajax");852 AssessmentsService.getInterviews().then(function(data) {853 $log.info("Data received from interviews ajax");854 return data;855 });856 };857 self.showRulesMenu = function(scope) {858 var menu = angular.copy(self.rulesMenuOptions);859 if(scope.agent.idAgent != 116) {860 _.remove(menu, {861 0: 'Run Noise Assessment'862 });863 } else {864 }865 return menu;866 };867 self.showAssessmentsMenu = function(scope) {868 return self.assessmentsMenuOptions;869 };870 self.showEditAssessmentMenu = function(scope) {871 return self.editAssessmentsMenuOptions;872 };873 $scope.assessmentFilter = {874 idParticipant: null,875 interviewId: null,876 reference: null,877 status: null,878 interviewModuleName: null,879 pageNumber: null,880 size: null881 };882 self.tableParams = new NgTableParams(883 {884 page: 1,885 count: 10886 },887 {888 getData: function(params) {889 var currentPage = $scope.assessmentFilter.pageNumber;890 $scope.assessmentFilter.idParticipant = lengthGreaterThan2(params.filter().idParticipant);891 $scope.assessmentFilter.interviewId = lengthGreaterThan2(params.filter().idinterview);892 $scope.assessmentFilter.reference = lengthGreaterThan2(params.filter().reference);893 /*if(lengthGreaterThan2(params.filter().status)){894 if(params.filter().status.startsWith('run') ){895 $scope.assessmentFilter.status = 0896 }else if(params.filter().status.startsWith('par') ){897 $scope.assessmentFilter.status = 1898 }else if(params.filter().status.startsWith('com') ){899 $scope.assessmentFilter.status = 2900 }else if(params.filter().status.startsWith('tob') ){901 $scope.assessmentFilter.status = 3902 }903 }*/904 $scope.assessmentFilter.status = params.filter().status;905 $scope.assessmentFilter.assessedStatus = lengthGreaterThan2(params.filter().assessedStatus);906 $scope.assessmentFilter.interviewModuleName = lengthGreaterThan2(params.filter().interviewModuleName);907 $scope.assessmentFilter.pageNumber = params.page();908 $scope.assessmentFilter.size = params.count();909 params.goToPageNumber = null;910 var assessmentFilter = $scope.assessmentFilter;911 if(!self.tableParams.settings().dataset || (assessmentFilter.pageNumber != currentPage)912 || assessmentFilter.idParticipant913 || assessmentFilter.interviewId || assessmentFilter.reference914 || assessmentFilter.status || (assessmentFilter.status === 0) || assessmentFilter.interviewModuleName ||915 ifEmptyFilter(params.filter())) {916 $log.info("Data getting from interviews ajax ...");917 return ParticipantsService.getPaginatedAssessmentWithModList(assessmentFilter).then(function(response) {918 if(response.status == '200') {919 var data = response.data.content;920 $scope.currentParticipants = data;921// _.each(data,function(participant){922// participant.interviewId = participant.interviews[0].interviewId;923// });924 console.log("Data get list from getParticipants ajax ...");925 self.originalData = angular.copy(data);926 self.tableParams.settings().dataset = data;927 self.tableParams.shouldGetData = false;928 self.tableParams.total(response.data.totalSize);929 return data;930 }931 });932 }933 },934 });935 self.tableParams.shouldGetData = true;936 $scope.isModulesSet = false;937 $scope.refreshModules = function() {938 $scope.isModulesSet = true;939 SystemPropertyService.getByName("activeintro").then(function(response) {940 if(response.status == '200') {941 var introModuleId = response.data.value;942 _.each(self.tableParams.settings().dataset, function(participant) {943 participant.inProgress = true;944 InterviewsService.findModulesByInterviewId(participant.interviewId).then(function(response) {945 if(response.status == '200') {946 var introModule = "";947 var idModule = "";948 if(!response.data || response.data.length == 0) {949 participant.module = 'Error no module.';950 } else {951 participant.module = "";952 for(var i = 0; i < response.data.length; i++) {953 var module = response.data[i];954 if(module.idModule != introModuleId) {955 participant.module += module.interviewModuleName;956 participant.idModule += module.idModule;957 if(i < response.data.length - 1) {958 participant.module += ":";959 }960 } else {961 introModule = module.interviewModuleName;962 idModule = module.idModule;963 }964 }965 }966 if(participant.module == "") {967 participant.module = introModule;968 participant.idModule += idModule;969 }970 participant.inProgress = false;971 }972 });973 })974 }975 });976 };977 function ifEmptyFilter(filter) {978 if((!filter.idParticipant || filter.idParticipant.length == 0) &&979 (!filter.idinterview || filter.idinterview.length == 0) &&980 (!filter.reference || filter.reference.length == 0) &&981 (!filter.status || filter.status.length == 0) &&982 (!filter.interviewModuleName || filter.interviewModuleName.length == 0)) {983 return true;984 }985 }986 function lengthGreaterThan2(variable) {987 if(variable && variable.length > 2) {988 return variable;989 } else {990 return null;991 }992 }993 $scope.nodePopover = {994 templateUrl: 'scripts/questions/partials/nodePopover.html',995 open: function(x, nodeclass) {996 if(!nodeclass) {997 nodeclass = 'P';998 }999 if(!x.idNode) {1000 var convertX = {};1001 convertX.idNode = x;1002 x = convertX;1003 }1004 if(angular.isUndefined(x.info)) {1005 x.info = [];1006 }1007 x.info["Node" + x.idNode] = {1008 idNode: x.idNode,1009 nodeclass: nodeclass,1010 nodePopover: {1011 isOpen: false1012 },1013 nodePopoverInProgress: false1014 };1015 var nodeInPopup = x.info["Node" + x.idNode];1016 nodeInPopup.nodePopover.isOpen = true;1017 nodeInPopup.nodePopoverInProgress = true;1018 if(nodeclass == 'P') {1019 QuestionsService.findPossibleAnswer(nodeInPopup.idNode).then(function(data) {1020 nodeInPopup.data = data.data[0];1021 nodeInPopup.nodePopoverInProgress = false;1022 });1023 } else {1024 QuestionsService.findQuestion(nodeInPopup.idNode).then(function(data) {1025 nodeInPopup.data = data.data[0];1026 nodeInPopup.nodePopoverInProgress = false;1027 });1028 }1029 },1030 close: function close(x) {1031 x.info["Node" + x.idNode].nodePopover.isOpen = false;1032 }1033 };1034 self.rulesMenuOptions =1035 [1036 ['Show Rules', function($itemScope, $event, model) {1037 var ruleArray = _.filter(model.firedRules, function(r) {1038 return $itemScope.agent.idAgent === r.agentId;1039 });1040 for(var i = 0; i < ruleArray.length; i++) {1041 var scope = $itemScope.$new();1042 scope.model = model;1043 scope.rule = ruleArray[i];1044 scope.agentName = $itemScope.agent.name;1045 newInterviewNote($event.currentTarget.parentElement, scope, $compile);1046 }1047 }1048 ],1049 ['Run Noise Assessment', function($itemScope, $event, model) {1050 var bFoundNoiseRules = false;1051 var noiseRules = [];1052 for(var i = 0; i < model.agents.length; i++) {1053 var agentAssessing = model.agents[i];1054 var rule = {levelValue: 99};1055 for(var j = 0; j < model.firedRules.length; j++) {1056 var firedRule = model.firedRules[j];1057 if(agentAssessing.idAgent == firedRule.agent.idAgent) {1058 if(firedRule.agent.idAgent == 116) {1059 bFoundNoiseRules = true;1060 noiseRules.push(firedRule);1061 }1062 }1063 }1064 }1065 if(bFoundNoiseRules) {1066 var totalPartialExposure = 0;1067 var totalPartialExposurePerAdj = 0;1068 var peakNoise = 0;1069 var maxBackgroundPartialExposure = 0;1070 var maxBackgroundHours = 0;1071 $scope.noiseRows = [];1072 var totalFrequency = 0;1073 var backgroundHours = 0;1074 var shiftHours = 0;1075 for(var m = 0; m < model.questionsAsked.length; m++) {1076 var iqa = model.questionsAsked[m];1077 if(iqa.possibleAnswer.type == 'P_frequencyshifthours') {1078 shiftHours = iqa.interviewQuestionAnswerFreetext;1079 break;1080 }1081 }1082 for(var k = 0; k < noiseRules.length; k++) {1083 var noiseRule = noiseRules[k];1084 if(noiseRule.type != 'BACKGROUND') {1085 var parentNode = noiseRule.conditions[0];1086 if(model.module) {1087 cascadeFindNode(model.module.nodes, parentNode);1088 } else {1089 cascadeFindNode(model.fragment.nodes, parentNode);1090 }1091 var answeredValue = 0;1092 if($scope.foundNode) {1093 if($scope.foundNode.nodes[0]) {1094 if($scope.foundNode.nodes[0].nodes[0]) {1095 var frequencyHoursIdNode = $scope.foundNode.nodes[0].nodes[0].idNode;1096 for(var l = 0; l < model.questionsAsked.length; l++) {1097 var iqa = model.questionsAsked[l];1098 if(iqa.possibleAnswer.idNode == frequencyHoursIdNode) {1099 answeredValue = iqa.interviewQuestionAnswerFreetext;1100 break;1101 }1102 }1103 }1104 }1105 $scope.foundNode = null;1106 }1107 totalFrequency += Number(answeredValue);1108 }1109 }1110 var useRatio = false;1111 var ratio = 1.0;1112 if(totalFrequency > shiftHours) {1113 useRatio = true;1114 ratio = parseFloat(totalFrequency) / parseFloat(shiftHours);1115 ratio = ratio.toFixed(4);1116 }1117 var level = 0;1118 var peakNoise = 0;1119 for(var k = 0; k < noiseRules.length; k++) {1120 var noiseRule = noiseRules[k];1121 if(noiseRule.type == 'BACKGROUND') {1122 var hoursbg = shiftHours - totalFrequency;1123 if(hoursbg < 0) {1124 hoursbg = 0;1125 }1126 var partialExposure = 4 * hoursbg * (Math.pow(10, (level - 100) / 10));1127 partialExposure = partialExposure.toFixed(4);1128 hoursbg = hoursbg.toFixed(4);1129 level = noiseRule.ruleAdditionalfields[0].value;1130 var noiseRow = {1131 nodeNumber: noiseRule.conditions[0].number,1132 dB: level + 'B',1133 backgroundhours: hoursbg,1134 partialExposure: partialExposure,1135 type: 'backgroundNoise'1136 };1137 $scope.noiseRows.push(noiseRow);1138 if(partialExposure > maxBackgroundPartialExposure) {1139 maxBackgroundPartialExposure = partialExposure;1140 maxBackgroundHours = hoursbg;1141 }1142 } else {1143 var hours = 0.0;1144 var frequencyhours = 0;1145 var parentNode = noiseRule.conditions[0];1146 if(model.module) {1147 cascadeFindNode(model.module.nodes, parentNode);1148 } else {1149 cascadeFindNode(model.fragment.nodes, parentNode);1150 }1151 if($scope.foundNode) {1152 if($scope.foundNode.nodes[0]) {1153 if($scope.foundNode.nodes[0].nodes[0]) {1154 var frequencyHoursIdNode = $scope.foundNode.nodes[0].nodes[0].idNode;1155 for(var l = 0; l < model.questionsAsked.length; l++) {1156 var iqa = model.questionsAsked[l];1157 if(iqa.possibleAnswer.idNode == frequencyHoursIdNode) {1158 frequencyhours = iqa.interviewQuestionAnswerFreetext;1159 }1160 }1161 }1162 }1163 $scope.foundNode = null;1164 }1165 if(useRatio) {1166 hours = parseFloat(frequencyhours) / ratio;1167 } else {1168 hours = parseFloat(frequencyhours);1169 }1170 level = noiseRule.ruleAdditionalfields[0].value;1171 var percentage = 100;1172 var partialExposure = 4 * hours * (Math.pow(10, (level - 100) / 10));1173 partialExposure = partialExposure.toFixed(4);1174 hours = hours.toFixed(4);1175 var modHours = "";1176 if(useRatio) {1177 modHours = "*" + hours + "*";1178 } else {1179 modHours = hours;1180 }1181 var noiseRow = {1182 nodeNumber: noiseRule.conditions[0].number,1183 dB: level,1184 backgroundhours: modHours,1185 partialExposure: partialExposure1186 };1187 $scope.noiseRows.push(noiseRow);1188 totalPartialExposure = (parseFloat(totalPartialExposure) + parseFloat(partialExposure));1189 }1190 if(peakNoise < Number(level)) {1191 peakNoise = Number(level);1192 }1193 }1194 totalPartialExposure = (parseFloat(totalPartialExposure) + parseFloat(maxBackgroundPartialExposure));1195 totalPartialExposure = totalPartialExposure.toFixed(4);1196 totalFrequency += maxBackgroundHours;1197 var autoExposureLevel = 10 * (Math.log10(totalPartialExposure / (3.2 * (Math.pow(10, -9)))));1198 autoExposureLevel = autoExposureLevel.toFixed(4);1199 $scope.totalPartialExposure = totalPartialExposure;1200 $scope.autoExposureLevel = autoExposureLevel;1201 $scope.peakNoise = peakNoise;1202 }1203 }1204 ]1205 ];1206 self.assessmentsMenuOptions =1207 [1208 ['Update Fired Rules', function($itemScope, $event, model) {1209 AssessmentsService.updateFiredRules(model.interviewId).then(function(response) {1210 if(response.status === 200) {1211 $log.info("Updated Fired Rules");1212 $scope.data = response.data[0];1213 }1214 });1215 }1216 ],1217 ['Run Auto Assessment', function($itemScope, $event, model) {1218 model.autoAssessedRules = [];1219 for(var i = 0; i < model.agents.length; i++) {1220 var agentAssessing = model.agents[i];1221 var rule = {levelValue: 99};1222 for(var j = 0; j < model.firedRules.length; j++) {1223 var firedRule = model.firedRules[j];1224 if(agentAssessing.idAgent == firedRule.agent.idAgent) {1225 if(firedRule.levelValue < rule.levelValue) {1226 rule = firedRule;1227 }1228 }1229 }1230 model.autoAssessedRules.push(rule);1231 }1232 $scope.data = model;1233 InterviewsService.save(model).then(function(response) {1234 if(response.status === 200) {1235 $log.info("Interview saved with auto assessments");1236 }1237 });1238 }1239 ],1240 ['Use Auto', function($itemScope, $event, model) {1241 if(model.manualAssessedRules.length == 0) {1242 model.manualAssessedRules = [];1243 var assessments = angular.copy(model.autoAssessedRules);1244 for(var i = 0; i < assessments.length; i++) {1245 var assessment = assessments[i];1246 assessment.idRule = '';1247 assessment.conditions = [];1248 model.manualAssessedRules.push(assessment);1249 }1250 InterviewsService.save(model).then(function(response) {1251 if(response.status === 200) {1252 $log.info("Interview saved with manual assessments");1253 }1254 });1255 }1256 }1257 ]1258 ];1259 self.editAssessmentsMenuOptions =1260 [1261 ['Edit Assessment', function($itemScope, $event, model) {1262 var ruleArray = _.filter(model.manualAssessedRules, function(r) {1263 return $itemScope.agent.idAgent === r.agentId;1264 });1265 for(var i = 0; i < ruleArray.length; i++) {1266 var scope = $itemScope.$new();1267 scope.model = model;1268 scope.rule = ruleArray[i];1269 scope.agentName = $itemScope.agent.name;1270 editAssessmentDialog($event.currentTarget.parentElement, scope, $compile);1271 }1272 }1273 ]1274 ];1275 $scope.closeIntDialog = function(elem, $event) {1276 $($event.target).closest('.int-note').remove();1277 $scope.activeIntRuleDialog = '';1278 $scope.activeIntRuleCell = '';1279 safeDigest($scope.activeIntRuleDialog);1280 safeDigest($scope.activeIntRuleCell);1281 };1282 $scope.setActiveIntRule = function(model, el) {1283 $scope.activeIntRuleDialog = el.$id;1284 $scope.activeIntRuleCell = model.idAgent;1285 safeDigest($scope.activeIntRuleDialog);1286 safeDigest($scope.activeIntRuleCell);1287 };1288 var safeDigest = function(obj) {1289 if(!obj.$$phase) {1290 try {1291 obj.$digest();1292 } catch(e) {1293 }1294 }1295 };1296 $scope.saveRule = function(rule) {1297 RulesService.save(rule).then(function(response) {1298 if(response.status === 200) {1299 $log.info('Rule Save was Successful!' + rule);1300 }1301 });1302 };1303 function cascadeFindNode(nodes, node) {1304 _.each(nodes, function(data) {1305 if(data.idNode == node.idNode) {1306 $scope.foundNode = data;1307 } else {1308 if(data.nodes) {1309 if(data.nodes.length > 0) {1310 cascadeFindNode(data.nodes, node);1311 }1312 }1313 }1314 });1315 }1316 self.tableParams.goTo = function(event) {1317 if(event.keyCode == 131318 && self.tableParams.goToPageNumber != null1319 && !isNaN(self.tableParams.goToPageNumber)) {1320 self.tableParams.page(self.tableParams.goToPageNumber);1321 self.tableParams.reload();1322 }1323 };1324 }...
index.ts
Source:index.ts
1import { AzureFunction, Context, HttpRequest } from '@azure/functions';2import { COLLECTIONS } from '../constants/collections';3import { faunadbClient, faunadbQuery } from '../constants/faunadb';4import { INDEXES } from '../constants/indexes';5import { Exposure } from '../interfaces/exposure';67const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {89 if (req.method === 'POST') {1011 if (req.body && req.body.timestamp && req.body.treatmentHash && req.body.userId) {1213 try {1415 const partialExposure: Omit<Exposure, 'id'> = {16 isSuccessful: false,17 ...req.body18 };1920 const updateExposureCount = faunadbQuery.Map(21 faunadbQuery.Paginate(22 faunadbQuery.Match(23 faunadbQuery.Index(INDEXES.ALL_TREATMENT_STATISTICS_BY_TREATMENT_HASH),24 partialExposure.treatmentHash25 )26 ),27 faunadbQuery.Lambda('X', faunadbQuery.Update(28 faunadbQuery.Var('X'), {29 data: {30 exposureCount: faunadbQuery.Add(31 faunadbQuery.Select(['data', 'exposureCount'], faunadbQuery.Get(faunadbQuery.Var('X'))),32 133 )34 }35 }36 ))37 );3839 const saveExposure = faunadbQuery.Create(40 faunadbQuery.Collection(COLLECTIONS.EXPOSURES),41 { data: partialExposure }42 );4344 /* https://docs.fauna.com/fauna/current/api/fql/functions/do?lang=javascript45 *46 * If all of the expressions executed by Do succeed,47 * only the results of the last statements executed are returned.48 * If no expressions are provided, Do returns an error.49 */5051 const transaction = faunadbClient.query(52 faunadbQuery.Do(53 updateExposureCount,54 saveExposure // Order is important55 )56 )5758 const response = await transaction;5960 const exposure: Exposure = {61 ...response['data'],62 id: response['ref'].id63 }6465 context.res = { status: 201, body: exposure };6667 } catch (error) {6869 context.log(error);7071 context.res = { status: 500, body: null };7273 }7475 } else { context.res = { status: 400, body: null }; }7677 } else { context.res = { status: 404, body: null }; }7879};80
...
exposure.service.ts
Source:exposure.service.ts
1import { HttpClient } from '@angular/common/http';2import { Injectable } from '@angular/core';3import { Observable, of } from 'rxjs';4import { ENDPOINTS } from '../../constants/endpoints';5import { Exposure } from '../../interfaces/exposure';6import { TreatmentStatistic } from '../../interfaces/treatment-statistic';7import { User } from '../../interfaces/user';8import { LoaderService } from '../loader/loader.service';9import { UserService } from '../user/user.service';10@Injectable({11 providedIn: 'root'12})13export class ExposureService {14 private exposure: undefined | Exposure = undefined;15 public constructor(16 private httpClient: HttpClient,17 private loaderService: LoaderService,18 private userService: UserService19 ) {20 this.userService.user$.subscribe(21 (user: undefined | User): void => { if (user === undefined) { this.exposure = undefined; } },22 (error: Error): void => { console.log('user$ failed.', error); }23 );24 }25 public postExposure(treatmentHash: TreatmentStatistic['treatmentHash'], userId: User['userId']): void {26 this.loaderService.showLoader();27 const partialExposure: Omit<Exposure, 'id' | 'isSuccessful'> = {28 timestamp: (new Date()).toISOString(),29 treatmentHash,30 userId31 };32 this.httpClient.post<Exposure>(ENDPOINTS.POST_EXPOSURE, partialExposure).subscribe(33 (exposure: Exposure): void => {34 this.exposure = exposure;35 this.loaderService.hideLoader();36 },37 (error: Error): void => {38 console.log('postExposure() failed.', error);39 this.loaderService.hideLoader();40 }41 );42 }43 public markExposureSuccessful(): Observable<void> {44 if (this.exposure === undefined) { return of(undefined); } else {45 return this.httpClient.put<void>(ENDPOINTS.MARK_EXPOSURE_SUCCESSFUL, this.exposure);46 }47 }...
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) {4 console.log(err);5 } else {6 console.log(data);7 }8});9var wpt = require('webpagetest');10var wpt = new WebPageTest('www.webpagetest.org');11 if (err) {12 console.log(err);13 } else {14 console.log(data);15 }16});17### Test (with options)18var wpt = require('webpagetest');19var wpt = new WebPageTest('www.webpagetest.org');20}, function(err, data) {21 if (err) {22 console.log(err);23 } else {24 console.log(data);25 }26});27var wpt = require('webpagetest');28var wpt = new WebPageTest('www.webpagetest.org');29 if (err) {30 console.log(err);31 } else {32 console.log(data);33 }34});35### Get test results (with options)36var wpt = require('webpagetest');37var wpt = new WebPageTest('www.webpagetest.org');38}, function(err, data) {39 if (err) {40 console.log(err);
Using AI Code Generation
1var wpt = require('wpt.js');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.partialExposure(function(err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});10var wpt = require('wpt.js');11var wpt = new WebPageTest('www.webpagetest.org');12wpt.getLocations(function(err, data) {13 if (err) {14 console.log(err);15 } else {16 console.log(data);17 }18});19var wpt = require('wpt.js');20var wpt = new WebPageTest('www.webpagetest.org');21wpt.getTesters(function(err, data) {22 if (err) {23 console.log(err);24 } else {25 console.log(data);26 }27});28var wpt = require('wpt.js');29var wpt = new WebPageTest('www.webpagetest.org');30wpt.getTesters(function(err, data) {31 if (err) {32 console.log(err);33 } else {34 console.log(data);35 }36});37var wpt = require('wpt.js');38var wpt = new WebPageTest('www.webpagetest.org');39wpt.getLocations(function(err, data) {40 if (err) {41 console.log(err);42 } else {43 console.log(data);44 }45});46var wpt = require('wpt.js');47var wpt = new WebPageTest('www.webpagetest.org');48wpt.getTestStatus('testId', function(err, data) {49 if (err) {50 console.log(err);51 } else {52 console.log(data);53 }54});
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new WebPageTest('www.webpagetest.org');3}, function(err, data) {4 if (err) return console.error(err);5 console.log(data);6 wpt.partialExposure(data.data.testId, 1, 1, 1, function(err, data) {7 if (err) return console.error(err);8 console.log(data);9 });10});
Using AI Code Generation
1var exports = module.exports = {};2var exec = require('child_process').exec;3var fs = require('fs');4exports.partialExposure = function(url1, url2, url3, callback) {5 exec('phantomjs partialExposure.js ' + url1 + ' ' + url2 + ' ' + url3, function (error, stdout, stderr) {6 if (error) {7 callback(error, null);8 }9 else {10 callback(null, stdout);11 }12 });13};14var wpt = require('./wpt.js');15 console.log(data);16});17var exports = module.exports = {};18var exec = require('child_process').exec;19var fs = require('fs');20exports.partialExposure = function(url1, url2, url3, callback) {21 exec('phantomjs ' + __dirname + '/partialExposure.js ' + url1 + ' ' + url2 + ' ' + url3, function (error, stdout, stderr) {22 if (error) {23 callback(error, null);24 }25 else {26 callback(null, stdout);27 }28 });29};
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) return console.error(err);4 console.log('Test status: ' + data.statusText);5 wpt.getTestResults(data.data.testId, function(err, data) {6 if (err) return console.error(err);7 console.log(data);8 });9});
Using AI Code Generation
1var wpt = require('webpagetest');2var server = 'www.webpagetest.org';3var options = {4};5var wpt = new WebPageTest(server, options);6 if (err) {7 console.log(err);8 } else {9 console.log(data);10 }11});12### partialExposure()13wpt.partialExposure(url, callback);14 if (err) {15 console.log(err);16 } else {17 console.log(data);18 }19});20### partialExposure() - Options21wpt.partialExposure(url, options, callback);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!