How to use evaluationString method in Puppeteer

Best JavaScript code snippet using puppeteer

desklet.js

Source:desklet.js Github

copy

Full Screen

1//Imports2const Desklet = imports.ui.desklet;3const St = imports.gi.St;4const Clutter = imports.gi.Clutter;5const Soup = imports.gi.Soup;6const Mainloop = imports.mainloop;7const Lang = imports.lang;8const Settings = imports.ui.settings;9const GLib = imports.gi.GLib;10const Gettext = imports.gettext;11//Constant strings12const API_LINK_INST = "https://kretaglobalmobileapi.ekreta.hu/api/v1/Institute";13const UUID = "eKreta@thegergo02";14//Some variable initialization15var httpSession = new Soup.SessionAsync();16var isSettingChangedRunning = true;17//Setting up translations18Gettext.bindtextdomain(UUID, GLib.get_home_dir() + "/.local/share/locale")19function _(str) {20 return Gettext.dgettext(UUID, str);21}22//Constructor function23function EKretaDesklet(metadata, desklet_id) {24 this._init(metadata, desklet_id);25}26//Desklet27EKretaDesklet.prototype = {28 __proto__: Desklet.Desklet.prototype,29 //Initialization function30 /*31 We start to load up the desklet, 32 it's settings, and start the mainloop creator function. 33 */34 _init(metadata, desklet_id) {35 Desklet.Desklet.prototype._init.call(this, metadata, desklet_id);36 this.deskletId = desklet_id;37 this.showLoadingScreen();38 this.setHeader("eKreta");39 this.loadSettings();40 this.onUpdate();41 },42 //Settings loader function43 /*44 This function loads in our settings.45 */46 loadSettings() {47 this.settings = new Settings.DeskletSettings(this, this.metadata.uuid, this.deskletId);48 // Settings for eKreta desklet.49 this.settings.bind("inst_id", "instID", this.onSettingChanged);50 this.settings.bind("usr", "usrN", this.onSettingChanged);51 this.settings.bind("pass", "passW", this.onSettingChanged);52 this.settings.bind("delay_minutes", "delayMinutes", this.onSettingChanged);53 this.settings.bind("gzip_enabled", "gzipEnabled", this.onSettingChanged);54 // Grade averages55 this.settings.bind("show_grades", "showGrades", this.onSettingChanged);56 this.settings.bind("group_sub_categ", "groupSubCateg", this.onSettingChanged);57 this.settings.bind("show_class_av", "showClassAv", this.onSettingChanged);58 this.settings.bind("show_grade_diff", "showGradeDiff", this.onSettingChanged);59 this.settings.bind("perfect_grade_value", "perfectGradeValue", this.onSettingChanged);60 this.settings.bind("almost_perfect_grade_value", "almostPerfectGradeValue", this.onSettingChanged);61 this.settings.bind("perfect_grade_value", "perfectGradeValue", this.onSettingChanged);62 this.settings.bind("good_grade_value", "goodGradeValue", this.onSettingChanged);63 this.settings.bind("middle_grade_value", "middleGradeValue", this.onSettingChanged);64 this.settings.bind("bad_grade_value", "badGradeValue", this.onSettingChanged);65 this.settings.bind("really_bad_grade_value", "reallyBadGradeValue", this.onSettingChanged);66 // Grades67 this.settings.bind("show_grade_panel", "showGradePanel", this.onSettingChanged);68 this.settings.bind("group_grades_sub", "groupGradesSub", this.onSettingChanged);69 //Absences70 this.settings.bind("show_absences", "showAbsences", this.onSettingChanged);71 this.settings.bind("sort_absences", "sortAbsences", this.onSettingChanged);72 //Lessons73 this.settings.bind("show_lessons", "showLessons", this.onSettingChanged);74 this.settings.bind("show_filtered_days", "showFilteredDays", this.onSettingChanged);75 76 return;77 },78 //Data updater function79 /*80 This function gets a new auth token, 81 with it the current data from the KRETA servers.82 */83 updateData() {84 this.showLoadingScreen();85 this.getAuthToken(this.instID, this.usrN, this.passW, function(result, upperThis) {86 upperThis.curAuthToken = result;87 upperThis.getStudentDetails(upperThis.instID,upperThis.curAuthToken,function(result, upperThis) {88 upperThis.curStudentDetails = result;89 if (!upperThis.showLessons) {90 upperThis.setupUI(result,null);91 } else {92 upperThis.getCurrentWeek(function(StartDate,EndDate,upperThis) {93 var startDate = StartDate.getFullYear() + "-" + ((StartDate.getMonth() == 0) ? "01" : StartDate.getMonth()) + "-" + ((StartDate.getDate() < 10) ? "0" + StartDate.getDate() : StartDate.getDate());94 var endDate = EndDate.getFullYear() + "-" + ((EndDate.getMonth() == 0) ? "01" : EndDate.getMonth()) + "-" + ((EndDate.getDate() < 10) ? "0" + EndDate.getDate() : EndDate.getDate());95 96 upperThis.getLessons(upperThis.curAuthToken,upperThis.instID,startDate, endDate,function(result,upperThis) {97 for (let i = 0; i < result.length; i++) {98 var n = result[i]["Date"].lastIndexOf('T');99 result[i]["Date"] = result[i]["Date"].substring(0,n);100 }101 result["EndDate"] = endDate;102 upperThis.setupUI(upperThis.curStudentDetails,result);103 });104 }, upperThis);105 }106 isSettingChangedRunning = false;107 });108 });109 return;110 },111 //onUpdate() function112 /*113 This function gets called in time intervals, 114 this reloads the data and sets up the UI with the new data. 115 */116 onUpdate() {117 this.setUpdateTimer();118 this.updateData();119 return;120 },121 122 //Mainloop creator function123 /*124 This function creates the mainloop,125 and with it we fetch the current data, 126 */127 setUpdateTimer() {128 this.updateLoop = Mainloop.timeout_add(this.delayMinutes * 60 * 1000, Lang.bind(this, this.onUpdate));129 return;130 },131 //Mainloop remover function132 /*133 This function removes the mainloop 134 when we don't need it. 135 */136 removeUpdateTimer() {137 if (this.updateLoop !== null) {138 Mainloop.source_remove(this.updateLoop);139 }140 return;141 },142 //UI creator function143 /*144 This creates the user interface for our desklet,145 so it's an important function. 146 */147 setupUI(studentDetails,lessonDetails) {148 this.window = new St.BoxLayout({149 vertical: true,150 style_class: "container"151 });152 if (studentDetails === "cantgetauth") {153 this.bigText = new St.Label({style_class: "boldLabel"});154 this.bigText.set_text(_("Error: Couldn't login with the credetinals given. (Check the desklet settings.)"));155 this.window.add(this.bigText);156 this.setContent(this.window);157 return;158 }159 var studentName = studentDetails["Name"]160 var studentInstituteName = studentDetails["InstituteName"];161 var studentSubjectAverages = studentDetails["SubjectAverages"];162 this.nameText = new St.Label({style_class: "normalLabel"});163 this.nameText.set_text(studentName + " (" + studentInstituteName + ")");164 this.window.add(this.nameText);165 this.panelText = new St.Label({style_class: "boldLabel"});166 if (this.showGrades) {167 this.panelText.set_text("Grade averages");168 this.window.add(this.panelText);169 if (this.groupSubCateg) {170 this.fetchSubjectsFromResponse(studentSubjectAverages,"SubjectCategoryName", function(result, upperThis) {171 upperThis.subjects = result;172 });173 var subjectCategories = this.subjects;174 for(let j = 0; j < subjectCategories.length; j++) {175 this.currentSubjectText = new St.Label({style_class: "boldLabel"});176 this.currentSubjectText.set_text(subjectCategories[j]);177 this.window.add(this.currentSubjectText);178 for(let i = 0; i < studentDetails["SubjectAverages"].length; i++) {179 var gradeAverage = studentSubjectAverages[i]["Value"];180 var subjectName = studentSubjectAverages[i]["Subject"];181 var classAverage = studentSubjectAverages[i]["ClassValue"];182 var subjectCategoryName = studentSubjectAverages[i]["SubjectCategoryName"];183 if (subjectCategoryName === subjectCategories[j]) {184 this.getGradeColor(gradeAverage,function(result,upperThis) {185 upperThis.gradeColor = result;186 });187 188 this.currentText = new St.Label({style_class: this.gradeColor});189 this.currentSubText = subjectName + ": " + gradeAverage;190 191 if (this.showClassAv) {192 this.currentSubText += " (Class Av.: " + classAverage +")";193 194 if (this.showGradeDiff) {195 this.getClassGradeDiff(gradeAverage, classAverage, function(result, upperThis) {196 upperThis.currentSubText += result;197 });198 }199 }200 this.currentText.set_text(this.currentSubText);201 this.window.add(this.currentText);202 }203 }204 }205 } else {206 for(let i = 0; i < studentDetails["SubjectAverages"].length; i++) {207 this.gradeAverage = studentDetails["SubjectAverages"][i]["Value"];208 this.subjectName = studentDetails["SubjectAverages"][i]["Subject"];209 this.classAverage = studentDetails["SubjectAverages"][i]["ClassValue"];210 this.getGradeColor(this.gradeAverage,function(result,upperThis) {211 upperThis.gradeColor = result;212 });213 this.currentText = new St.Label({style_class: this.gradeColor});214 this.currentSubText = this.subjectName + ": " + this.gradeAverage;215 if (this.showClassAv) {216 this.currentSubText += " (Class Av.: " + this.classAverage +")";217 if (this.showGradeDiff) {218 this.getClassGradeDiff(this.gradeAverage, this.classAverage, function(result, upperThis) {219 upperThis.currentSubText += result;220 });221 }222 }223 this.currentText.set_text(this.currentSubText);224 this.window.add(this.currentText);225 }226 }227 } else if (this.showGradePanel) {228 this.panelText.set_text("Your grades");229 this.window.add(this.panelText);230 if (this.groupGradesSub) {231 this.fetchSubjectsFromResponse(studentDetails["Evaluations"],"Subject", function(result, upperThis) {232 upperThis.subjects = result;233 });234 var subjects = this.subjects;235 for (let j = 0; j < subjects.length; j++) {236 var subjectText = new St.Label({style_class: "boldLabel"});237 subjectText.set_text(subjects[j]);238 this.window.add(subjectText);239 for (let i = 0; i < studentDetails["Evaluations"].length; i++) {240 var gradeSubject = studentDetails["Evaluations"][i]["Subject"];241 if (gradeSubject === subjects[j]) {242 var gradeForm = studentDetails["Evaluations"][i]["Form"];243 var gradeMode = studentDetails["Evaluations"][i]["Mode"];244 var gradeTheme = studentDetails["Evaluations"][i]["Theme"];245 var gradeNumValue = studentDetails["Evaluations"][i]["NumberValue"];246 var gradeTypeName = studentDetails["Evaluations"][i]["TypeName"];247 var gradeValue = studentDetails["Evaluations"][i]["Value"];248 249 if (gradeNumValue !== null) {250 this.getGradeColor(gradeNumValue,function(result,upperThis) {251 upperThis.gradeColour = result;252 });253 }254 255 if (gradeForm !== "Diligence" && gradeForm !== "Deportment") {256 if (gradeTheme !== "" && gradeTheme !== null) {257 var evaluationString = gradeSubject + " : " + gradeMode + " : " + gradeTheme + " : " + gradeNumValue;258 } else {259 var evaluationString = gradeSubject + " : " + gradeMode + " : " + gradeNumValue;260 }261 var currentText = new St.Label({style_class: this.gradeColour});262 263 currentText.set_text(evaluationString);264 this.window.add(currentText);265 } else {266 var evaluationString = gradeForm + " : " + gradeTypeName + " : " + gradeValue;267 var currentText = new St.Label({style_class: "normalLabel"});268 269 currentText.set_text(evaluationString);270 this.window.add(currentText);271 }272 }273 }274 }275 } else {276 for (let i = 0; i < studentDetails["Evaluations"].length; i++) {277 var gradeForm = studentDetails["Evaluations"][i]["Form"];278 var gradeSubject = studentDetails["Evaluations"][i]["Subject"];279 var gradeMode = studentDetails["Evaluations"][i]["Mode"];280 var gradeTheme = studentDetails["Evaluations"][i]["Theme"];281 var gradeNumValue = studentDetails["Evaluations"][i]["NumberValue"];282 var gradeTypeName = studentDetails["Evaluations"][i]["TypeName"];283 var gradeValue = studentDetails["Evaluations"][i]["Value"];284 285 if (gradeNumValue !== null) {286 this.getGradeColor(gradeNumValue,function(result,upperThis) {287 upperThis.gradeColour = result;288 });289 }290 291 if (gradeForm !== "Diligence" && gradeForm !== "Deportment") {292 if (gradeTheme !== "" && gradeTheme !== null) {293 var evaluationString = gradeSubject + " : " + gradeMode + " : " + gradeTheme + " : " + gradeNumValue;294 } else {295 var evaluationString = gradeSubject + " : " + gradeMode + " : " + gradeNumValue;296 }297 var currentText = new St.Label({style_class: this.gradeColour});298 299 currentText.set_text(evaluationString);300 this.window.add(currentText);301 } else {302 var evaluationString = gradeForm + " : " + gradeTypeName + " : " + gradeValue;303 var currentText = new St.Label({style_class: "normalLabel"});304 305 currentText.set_text(evaluationString);306 this.window.add(currentText);307 }308 }309 }310 } else if (this.showAbsences) {311 this.panelText.set_text("Absences");312 this.window.add(this.panelText);313 if (this.sortAbsences) {314 this.fetchSubjectsFromResponse(studentDetails["Absences"],"Subject", function(result, upperThis) {315 upperThis.subjects = result;316 });317 var subjects = this.subjects;318 for (let j = 0; j < subjects.length;j++) {319 var curSubjectText = new St.Label({style_class: "boldLabel"});320 curSubjectText.set_text(subjects[j]);321 this.window.add(curSubjectText);322 for(let i = 0;i < studentDetails["Absences"].length;i++) {323 if (studentDetails["Absences"][i]["Subject"] === subjects[j]) {324 var absenceLessonStartTime = studentDetails["Absences"][i]["LessonStartTime"];325 var n = absenceLessonStartTime.lastIndexOf('T');326 absenceLessonStartTime = absenceLessonStartTime.substring(0,n);327 328 var absenceString = absenceLessonStartTime + " : " + studentDetails["Absences"][i]["TypeName"] + " : " + studentDetails["Absences"][i]["ModeName"] + " : " + studentDetails["Absences"][i]["JustificationStateName"] + " : " + studentDetails["Absences"][i]["JustificationTypeName"];329 var currentTextColor;330 if (studentDetails["Absences"][i]["JustificationType"] === "Justified") {331 currentTextColor = "perfectGrade";332 } else if (studentDetails["Absences"][i]["JustificationType"] === "UnJustified") {333 currentTextColor = "reallyBadGrade";334 } else if (studentDetails["Absences"][i]["JustificationType"] === "Medical") {335 currentTextColor = "medicalAbsence";336 }337 338 var currentText = new St.Label({style_class: currentTextColor});339 currentText.set_text(absenceString);340 this.window.add(currentText);341 }342 }343 }344 } else {345 for(let i = 0;i < studentDetails["Absences"].length;i++) {346 var absenceLessonStartTime = studentDetails["Absences"][i]["LessonStartTime"];347 var n = absenceLessonStartTime.lastIndexOf('T');348 absenceLessonStartTime = absenceLessonStartTime.substring(0,n);349 var absenceString = absenceLessonStartTime + " : " + studentDetails["Absences"][i]["TypeName"] + " : " + studentDetails["Absences"][i]["ModeName"] + " : " + studentDetails["Absences"][i]["JustificationStateName"] + " : " + studentDetails["Absences"][i]["JustificationTypeName"];350 var currentTextColor;351 if (studentDetails["Absences"][i]["JustificationType"] === "Justified") {352 currentTextColor = "perfectGrade";353 } else if (studentDetails["Absences"][i]["JustificationType"] === "UnJustified") {354 currentTextColor = "reallyBadGrade";355 } else if (studentDetails["Absences"][i]["JustificationType"] === "Medical") {356 currentTextColor = "medicalAbsence";357 }358 359 var currentText = new St.Label({style_class: currentTextColor});360 currentText.set_text(absenceString);361 this.window.add(currentText);362 }363 }364 } else if (this.showLessons) {365 this.panelText.set_text("Lessons");366 this.window.add(this.panelText);367 var lastRun = -1;368 for (let j = 0;j <= 6;j++) {369 this.curIterationDay = j;370 this.isCurrentDay(j + 1,function(result, upperThis) {371 upperThis.getDayStyleClass(result,function(result, upperThis) {372 upperThis.curIterationDayStyle = result;373 upperThis.getDayName(upperThis.curIterationDay,function(result, upperThis) {374 upperThis.dayText = new St.Label({ style_class: upperThis.curIterationDayStyle });375 upperThis.dayText.set_text(result);376 });377 });378 });379 if (!this.showFilteredDays) {380 this.window.add(this.dayText);381 }382 this.alreadyIn = new Array();383 for (let i = 0; i < lessonDetails.length; i++) {384 var startDate = new Date(lessonDetails[i]["Date"]);385 if (startDate < new Date(lessonDetails["EndDate"]) && startDate.getDay() === j + 1 && this.alreadyIn.indexOf(lessonDetails[i]["LessonId"]) === -1) {386 var n = lessonDetails[i]["StartTime"].lastIndexOf('T');387 var nE = lessonDetails[i]["EndTime"].lastIndexOf('T');388 lessonDetails[i]["StartTimeHour"] = lessonDetails[i]["StartTime"].substring(n+1);389 lessonDetails[i]["EndTimeHour"] = lessonDetails[i]["EndTime"].substring(nE+1);390 lessonDetails[i]["StartTime"] = lessonDetails[i]["StartTime"].substring(0,n);391 var lessonText = new St.Label({ style_class: "medicalAbsence" })392 lessonText.set_text(lessonDetails[i]["Count"] + " : " + lessonDetails[i]["Subject"] + " : " + lessonDetails[i]["StartTimeHour"] + " - " + lessonDetails[i]["EndTimeHour"]);393 if (lastRun !== j) {394 this.window.add(this.dayText);395 lastRun = j;396 }397 this.window.add(lessonText);398 }399 }400 }401 }402 403 this.setContent(this.window); 404 },405 //Auth token fetcher function406 /*407 This function fetches the auth token, 408 with the given login details. 409 */410 getAuthToken(instID, usrN, passW, callbackF) {411 var postParameters = "institute_code=" + instID + "&userName=" + usrN + "&password=" + passW + "&grant_type=password&client_id=919e0c1c-76a2-4646-a2fb-7085bbbf3c56";412 this.httpRequest("POST","https://" + instID + ".e-kreta.hu/idp/api/v1/Token",null,postParameters,function(result,upperThis) {413 callbackF(result["access_token"],upperThis);414 })415 },416 //Student data fetcher function417 /*418 This function fetches the user's data, 419 with the given auth token. 420 */421 getStudentDetails(instID,authToken,callbackF) {422 if (authToken == "cantgetauth") {423 callbackF("cantgetauth", this);424 return;425 }426 this.httpRequest("GET", "https://" + instID + ".e-kreta.hu/mapi/api/v1/Student", [["Authorization", "Bearer " + authToken]], null,function(result,upperThis) {427 callbackF(result,upperThis);428 });429 },430 //Institute fetcher function431 /*432 This function fetches the institutions where KRETA is implemented, 433 the code doesn't use it currently. 434 */435 //TODO: The user can automatically select his/her institution.436 getInstitutes(callbackF) {437 this.httpRequest("GET", API_LINK_INST, [["apiKey", "7856d350-1fda-45f5-822d-e1a2f3f1acf0"]], null, function(result,upperThis) {438 callbackF(result);439 });440 },441 getLessons(authToken,instID,fromDate,toDate,callbackF) {442 this.httpRequest("GET", "https://" + instID + ".e-kreta.hu/mapi/api/v1/Lesson", [["Authorization", "Bearer " + authToken]], "fromDate=" + fromDate + "&toDate=" + toDate, function(result,upperThis) {443 callbackF(result,upperThis);444 });445 },446 //HTTP request creator function447 /*448 This function creates all of our HTTP requests.449 */450 httpRequest(method,url,headers,postParameters,callbackF) {451 var message = Soup.Message.new(452 method,453 url454 );455 if (headers !== null) {456 for (let i = 0;i < headers.length;i++) {457 message.request_headers.append(headers[i][0],headers[i][1]);458 }459 }460 if (this.gzipEnabled)461 message.request_headers.append("Accept-Encoding","gzip");462 if (postParameters !== null) 463 message.set_request("application/x-www-form-urlencoded",2,postParameters);464 httpSession.queue_message(message,465 Lang.bind(this, function(session, response) {466 if (response.status_code !== Soup.KnownStatusCode.OK) {467 global.log(response.status_code + " : " + response.response_body.data);468 callbackF("cantgetauth", this); //TODO: Correct error value.469 return;470 }471 472 var result = JSON.parse(message.response_body.data);473 callbackF(result, this);474 return;475 })476 );477 return478 },479 getDayName(dayNumber,callbackF) {480 switch (dayNumber) {481 case 0: { 482 callbackF(_("Monday"), this); 483 break;484 }485 case 1: { 486 callbackF(_("Tuesday"), this); 487 break;488 }489 case 2: { 490 callbackF(_("Wednesday"), this); 491 break;492 }493 case 3: { 494 callbackF(_("Thursday"), this); 495 break;496 }497 case 4: { 498 callbackF(_("Friday"), this); 499 break;500 }501 case 5: { 502 callbackF(_("Saturday"), this); 503 break;504 }505 case 6: { 506 callbackF(_("Sunday"), this); 507 break;508 }509 default: {510 callbackF(_("Not a day"), this);511 }512 }513 },514 isCurrentDay(dayNumber,callbackF) {515 callbackF(dayNumber == new Date().getDay(), this);516 },517 getDayStyleClass(isCurrentDay, callbackF) {518 if (isCurrentDay)519 callbackF("boldLabel", this);520 else 521 callbackF("normalLabel", this);522 },523 fetchSubjectsFromResponse(array,subjectString,callbackF) {524 var subjects = new Array();525 for(let i = 0; i < array.length; i++) {526 var currentSubject = array[i][subjectString];527 if (subjects.indexOf(currentSubject) === -1 && currentSubject !== null) {528 subjects.push(currentSubject);529 }530 }531 callbackF(subjects, this);532 },533 //Grade coloring mechanism534 /*535 From the grade average, get what range it belongs. 536 */537 getGradeColor(gradeValue, callbackF) {538 if (gradeValue == this.perfectGradeValue) {539 callbackF("perfectGrade", this);540 } else if (gradeValue >= this.almostPerfectGradeValue && gradeValue < this.perfectGradeValue) {541 callbackF("almostPerfectGrade", this);542 } else if (gradeValue >= this.goodGradeValue && gradeValue < this.almostPerfectGradeValue) {543 callbackF("goodGrade", this);544 } else if (gradeValue >= this.middleGradeValue && gradeValue < this.goodGradeValue) {545 callbackF("middleGrade", this);546 } else if (gradeValue >= this.badGradeValue && gradeValue < this.middleGradeValue) {547 callbackF("badGrade", this);548 } else if (gradeValue == this.reallyBadGradeValue){549 callbackF("reallyBadGrade", this);550 } else {551 callbackF("reallyBadGrade", this);552 }553 },554 //Your and class average comparer function555 /*556 Returns how you compare to your class. 557 */558 getClassGradeDiff(gradeAverage, classAverage, callbackF) {559 var diff = +(gradeAverage - classAverage).toFixed(2);560 if (gradeAverage > classAverage) {561 callbackF(" (Your grade is better with: +" + diff +")", this);562 } else if (gradeAverage < classAverage) {563 callbackF(" (Your grade is worse with: -" + diff +")", this);564 } else {565 callbackF(" (Your grade is equal)", this);566 }567 },568 getCurrentWeek(callbackF, upperThis) {569 var today = new Date();570 var day = today.getDay();571 var StartDate = new Date();572 var EndDate = new Date();573 StartDate.setHours(0,0,0,0); EndDate.setHours(0,0,0,0);574 StartDate.setDate(today.getDate()-day);575 EndDate.setDate(today.getDate()-day+6);576 EndDate.setDate(EndDate.getDate()-5);577 callbackF(StartDate,EndDate,upperThis);578 global.log(StartDate + " : " + EndDate);579 },580 //Loading screen shower function581 /*582 Show the loading screen. 583 */584 showLoadingScreen() {585 this.loadingWindow = new St.BoxLayout({586 vertical: true,587 style_class: "container"588 });589 this.loadingText = new St.Label({style_class: "normalLabel"});590 this.loadingText.set_text("Loading...");591 this.loadingWindow.add(this.loadingText);592 this.setContent(this.loadingWindow)593 },594 //When the settings gets changed595 /*596 It reloads the desklet with the new settings.597 */598 onSettingChanged() {599 if (!isSettingChangedRunning) {600 isSettingChangedRunning = true;601 this.removeUpdateTimer();602 this.onUpdate();603 }604 },605 //When the desklet gets removed606 /* 607 It fires when the desklet gets removed,608 and cleans up after it.609 */610 on_desklet_removed() {611 this.removeUpdateTimer();612 }613};614//Calls the desklet.615function main(metadata, desklet_id) {616 return new EKretaDesklet(metadata, desklet_id);...

Full Screen

Full Screen

GlideEditorJSCommon.js

Source:GlideEditorJSCommon.js Github

copy

Full Screen

1/*! RESOURCE: /scripts/classes/syntax_editor5/GlideEditorJSCommon.js */2var GlideEditorJSCommon = (function () {3 var contextMenuOpened = false,4 liSelected,5 displayedContextMenuItems,6 gutterContextMenuId,7 LINE_ID,8 GUTTER,9 EDITOR,10 LINE_NUMBER,11 CONTEXT_EVENT,12 breakConditionId,13 logStatementId,14 addBreakpointId,15 addConditionId,16 editConditionId,17 removeConditionId,18 removeBreakpointId,19 addConditionalBreakpointId,20 lintingEnabled,21 addLogpointId,22 editLogpointId,23 removeLogpointId,24 hasBreakpointRole = false,25 subscriberCollection = { gutterContextMenu: [], change: [] };26 function init(id, editor, debugpoints) {27 var isNewRecord = g_form.isNewRecord();28 if (isNewRecord) return;29 hasBreakpointRole = debugpoints.hasBreakpointRole;30 hasLogpointRole = debugpoints.hasLogpointRole;31 var lineNumberSelector =32 '.Debugger-breakpoints-gutter-marker div.CodeMirror-linenumber';33 var lineNumberGhostClass = 'Debugger-linenumber-ghost';34 $j(window.document).on('mouseover', lineNumberSelector, function (e) {35 e.target.classList.add(lineNumberGhostClass);36 updateContextEvent(e);37 });38 $j(window.document).on('mouseout', lineNumberSelector, function (e) {39 e.target.classList.remove(lineNumberGhostClass);40 $j('.logpoint-readonly,.breakpoint-readonly').css({41 display: 'none',42 });43 });44 window.document.oncontextmenu = function (e) {45 if (isContextMenuClickedOnGutter(e.target.classList)) return false;46 };47 $j('#gutterContextMenu')48 .find('li')49 .hover(function () {50 $j(this).focus();51 });52 $j(window).keydown(function (e) {53 if (contextMenuOpened) {54 if (e.which === 40) {55 if (liSelected) {56 var nextNotHidden;57 $j(displayedContextMenuItems).each(function (index, item) {58 if ($j(item).is(':focus'))59 nextNotHidden = $j(item)60 .nextAll('.breakpoint-menu-item')61 .not('.hide-me')62 .first();63 });64 nextNotHidden.focus();65 } else {66 liSelected = $j(displayedContextMenuItems[0])67 .nextAll('.breakpoint-menu-item')68 .not('.hide-me')69 .first();70 liSelected.focus();71 }72 } else if (e.which === 38) {73 if (liSelected) {74 var prevNotHidden;75 $j(displayedContextMenuItems).each(function (index, item) {76 if ($j(item).is(':focus'))77 prevNotHidden = $j(item)78 .prevAll('.breakpoint-menu-item')79 .not('.hide-me')80 .first();81 });82 prevNotHidden.focus();83 } else {84 liSelected = $j(displayedContextMenuItems[0])85 .prevAll('.breakpoint-menu-item')86 .not('.hide-me')87 .first();88 liSelected.focus();89 }90 } else if (e.which === 27) {91 if (contextMenuOpened) hideContextMenu();92 }93 }94 });95 GlideEditorJSBreakpoints.init(id, editor);96 GlideEditorJSLogpoints.init(id, editor);97 loadPoints(id, editor, function () {98 editor.on('gutterClick', function (cm, line, gutter, event) {99 $j('.logpoint-readonly,.breakpoint-readonly').css({100 display: 'none',101 });102 onGutterClick(id, cm, line, gutter, event);103 });104 var _lastLineCount = editor.lineCount();105 editor.on('change', function (cm, changed) {106 var curLineCount = editor.lineCount();107 if (curLineCount !== _lastLineCount) {108 _lastLineCount = curLineCount;109 updateGutterMarkers(editor, changed);110 }111 });112 editor.on('gutterContextMenu', function (cm, line, gutter, event) {113 subscriberCollection['gutterContextMenu'].forEach(function (handler) {114 handler(id, cm, line, gutter, event);115 });116 onGutterContextMenu(id, editor, line, gutter, event);117 });118 lintingEnabled = editor.getOption('lint');119 editor.on('optionChange', function (cm, option) {120 if (option === 'gutters' || option === 'lint') {121 var lintEnabled = cm.options.lint;122 if (lintEnabled === false) {123 $j('.CodeMirror-lines').each(function (index, item) {124 item.classList.add('linter-toggled');125 });126 lintingEnabled = false;127 } else {128 $j('.CodeMirror-lines').each(function (index, item) {129 item.classList.remove('linter-toggled');130 });131 lintingEnabled = true;132 }133 }134 if (option === 'format_code') {135 updateGutterMarkers(editor);136 }137 });138 });139 $j(window.document).mouseup(function (e) {140 var contextMenu = $j(gutterContextMenuId);141 if (142 !contextMenu.is(e.target) &&143 contextMenu.has(e.target).length === 0 &&144 !(145 $j(e.target).hasClass('CodeMirror-linenumber') ||146 $j(e.target).hasClass('CodeMirror-gutter-background')147 )148 )149 hideContextMenu();150 });151 window.addEventListener(152 'scroll',153 function () {154 hideContextMenu();155 },156 true157 );158 initializeReferences();159 }160 function initializeReferences() {161 addBreakpointId = '#addBreakpoint';162 addConditionId = '#addCondition';163 editConditionId = '#editCondition';164 removeConditionId = '#removeCondition';165 removeBreakpointId = '#removeBreakpoint';166 addConditionalBreakpointId = '#addConditionalBreakpoint';167 breakConditionId = '#breakCondition';168 gutterContextMenuId = '#gutterContextMenu';169 addLogpointId = '#addLogpoint';170 editLogpointId = '#editLogpoint';171 removeLogpointId = '#removeLogpoint';172 logStatementId = '#logCondition';173 gutterContextMenuId = '#gutterContextMenu';174 }175 function subscriberToGutterEvent(eventName, handler) {176 if (subscriberCollection[eventName])177 subscriberCollection[eventName].push(handler);178 }179 function updateContextEvent(e) {180 CONTEXT_EVENT = e;181 }182 function hideAllElements() {183 $j('.breakpoint-menu-item').addClass('hide-me');184 }185 function hideElement(elementId) {186 $j(elementId).addClass('hide-me');187 }188 function hideContextMenu() {189 hideElement(gutterContextMenuId);190 if (EDITOR)191 EDITOR.removeLineClass(192 LINE_NUMBER - 1,193 'gutter',194 'Debugger-linenumber-ghost-clone'195 );196 contextMenuOpened = false;197 }198 function updateGutterMarkers(editor, changed) {199 editor.operation(function () {200 editor.eachLine(function (line) {201 editor.removeLineClass(line, 'gutter');202 editor.addLineClass(203 line,204 'gutter',205 'Debugger-breakpoints-gutter-marker'206 );207 });208 });209 subscriberCollection['change'].forEach(function (handler) {210 handler(editor, changed);211 });212 }213 function updatePointerStyles(214 editor,215 changedOrigin,216 line,217 className,218 lineCount,219 highlightClass220 ) {221 var lineNumber = Number(line);222 if (lineCount >= lineNumber)223 editor.addLineClass(lineNumber - 1, 'gutter', className);224 editor.addLineClass(lineNumber - 1, 'background', highlightClass);225 }226 function getKey() {227 var tbl = g_form.getTableName();228 var sysId = g_form.getUniqueValue();229 return tbl + '.' + sysId;230 }231 function removeConditionClass(EDITOR, LINE_NUMBER) {232 EDITOR.removeLineClass(233 LINE_NUMBER - 1,234 'gutter',235 'Debugger-breakpoints-condition-gutter'236 );237 }238 function removeOutlineClass() {239 if (EDITOR && LINE_NUMBER)240 EDITOR.removeLineClass(LINE_NUMBER - 1, 'gutter', 'Debugger-outline');241 }242 function showElement(elementId) {243 $j(elementId).removeClass('hide-me');244 }245 function isContextMenuClickedOnGutter(targetContextMenuClassList) {246 return (247 targetContextMenuClassList.contains('CodeMirror-gutter-elt') ||248 targetContextMenuClassList.contains('CodeMirror-linenumber') ||249 targetContextMenuClassList.contains('CodeMirror-gutter-background') ||250 targetContextMenuClassList.contains('breakpoint-menu-item')251 );252 }253 function focusContextMenu(gutterContextMenuElement) {254 var listNodes = gutterContextMenuElement.children().first().children();255 displayedContextMenuItems = [];256 listNodes.each(function (index, item) {257 if (!item.classList.contains('hide-me'))258 displayedContextMenuItems.push(item);259 });260 if (displayedContextMenuItems && displayedContextMenuItems.length > 0)261 displayedContextMenuItems[0].focus();262 }263 function showContextMenu() {264 var gutterContextMenuElement = $j(gutterContextMenuId);265 gutterContextMenuElement.css({266 top: CONTEXT_EVENT.pageY + 'px',267 left: CONTEXT_EVENT.pageX + 'px',268 position: 'fixed',269 });270 if (!isBrowserIE()) {271 gutterContextMenuElement.css({272 'z-index': '1000',273 });274 }275 EDITOR.addLineClass(276 LINE_NUMBER - 1,277 'gutter',278 'Debugger-linenumber-ghost-clone'279 );280 showElement(gutterContextMenuId);281 contextMenuOpened = true;282 var contextmenuHeight = gutterContextMenuElement283 .children()284 .first()285 .height();286 if (window.innerHeight < CONTEXT_EVENT.pageY + contextmenuHeight) {287 gutterContextMenuElement.css({288 top: CONTEXT_EVENT.pageY - contextmenuHeight + 'px',289 });290 }291 focusContextMenu(gutterContextMenuElement);292 }293 function isBrowserIE() {294 var userAgent = navigator.userAgent.toLowerCase();295 return (296 userAgent.indexOf('msie ') > -1 || userAgent.indexOf('trident/') > -1297 );298 }299 function onGutterClick(id, editor, lineNumber, gutter, event) {300 if (event.which === 3) {301 event.preventDefault();302 var userAgent = navigator.userAgent.toLowerCase();303 if (304 userAgent.indexOf('firefox') > -1 ||305 isBrowserIE() ||306 userAgent.indexOf('edge') > -1307 ) {308 onGutterContextMenu(id, editor, lineNumber, gutter, event);309 subscriberCollection['gutterContextMenu'].forEach(function (handler) {310 handler(id, editor, lineNumber, gutter, event);311 });312 }313 return;314 }315 if (316 event.target.classList.contains('CodeMirror-foldgutter-open') ||317 event.target.classList.contains('CodeMirror-foldgutter-folded')318 )319 return;320 var isLogpointExist = ifLineHasPoint(321 lineNumber + 1,322 GlideEditorJSLogpoints.getLogPoints()323 );324 if (hasBreakpointRole && !isLogpointExist) {325 var evaluationString =326 GlideEditorJSBreakpoints.getBreakPoints()[lineNumber + 1];327 if (evaluationString == null)328 GlideEditorJSBreakpoints.toggleBreakpoint(329 id,330 editor,331 lineNumber + 1,332 gutter,333 ''334 );335 else336 GlideEditorJSBreakpoints.toggleBreakpoint(337 id,338 editor,339 lineNumber + 1,340 gutter341 );342 } else if (hasLogpointRole && isLogpointExist)343 GlideEditorJSLogpoints.toggleLogpoint(id, editor, lineNumber + 1, gutter);344 editor.removeLineClass(lineNumber, 'gutter', 'Debugger-breakpoints-gutter');345 editor.removeLineClass(346 lineNumber,347 'gutter',348 'Debugger-breakpoints-condition-gutter'349 );350 editor.removeLineClass(351 lineNumber,352 'background',353 'Debugger-breakpoints-highlight'354 );355 }356 function ifLineHasPoint(lineNum, Collection) {357 return (358 Object.keys(Collection).filter(function (point) {359 return point == lineNum;360 }).length > 0361 );362 }363 function onGutterContextMenu(id, editor, lineNumber, gutter, event) {364 var isWidgetDisplayed =365 $j(breakConditionId).is(':visible') || $j(logStatementId).is(':visible');366 if (isWidgetDisplayed) return;367 removeOutlineClass();368 if (CONTEXT_EVENT) hideContextMenu();369 LINE_NUMBER = lineNumber + 1;370 CONTEXT_EVENT = event;371 LINE_ID = id;372 GUTTER = gutter;373 EDITOR = editor;374 hideAllElements();375 if (376 ifLineHasPoint(LINE_NUMBER, GlideEditorJSBreakpoints.getBreakPoints())377 ) {378 showElement(removeBreakpointId);379 if (380 GlideEditorJSBreakpoints.ifBreakpointAtLineHasCondition(LINE_NUMBER)381 ) {382 showElement(editConditionId);383 showElement(removeConditionId);384 } else {385 showElement(addConditionId);386 hideElement(editConditionId);387 }388 } else if (389 ifLineHasPoint(LINE_NUMBER, GlideEditorJSLogpoints.getLogPoints())390 ) {391 showElement(editLogpointId);392 showElement(removeLogpointId);393 } else {394 showElement(addBreakpointId);395 showElement(addConditionalBreakpointId);396 showElement(addLogpointId);397 }398 if (document.getElementById('gutterContextMenu')) showContextMenu();399 event.preventDefault();400 }401 function removeErrorClass(errorElement, selector) {402 hideElement(errorElement);403 $j(selector).removeClass('condition-input-error');404 }405 function updatePointContent(id, lineNumber, then, evaluationString, api) {406 var scriptType = g_form.getTableName();407 var scriptId = g_form.getUniqueValue();408 var scriptField = id.split('.')[1];409 var requestData = null;410 if (evaluationString != null)411 requestData = JSON.stringify({ evaluationString: evaluationString });412 var url =413 '/api/now/js/' +414 api +415 '/' +416 scriptType +417 '/' +418 scriptId +419 '/' +420 scriptField +421 '/' +422 lineNumber;423 $j.ajax({424 url: url,425 method: 'POST',426 headers: {427 'X-UserToken': window.g_ck,428 Accept: 'application/json',429 'Content-Type': 'application/json',430 },431 data: requestData,432 }).done(function (response) {433 then(true);434 });435 }436 function togglePoint(id, editor, lineNumber, gutter, statement, api) {437 hideContextMenu();438 var lineInfo = editor.lineInfo(lineNumber - 1);439 var gutters = lineInfo.gutterMarkers || {};440 if ('CodeMirror-foldgutter' === gutter && gutters[gutter]) {441 return;442 }443 updatePointContent(444 id,445 lineNumber,446 function (ok) {447 if (ok) loadPoints(id, editor);448 },449 statement,450 api451 );452 }453 function removeEditorClass(lineNumber, context, className) {454 EDITOR.removeLineClass(lineNumber, context, className);455 }456 function hidePointReadonlyMode(selector) {457 $j(selector).css({458 display: 'none',459 });460 }461 function stopDotPropogation(e) {462 if (event.keyCode === 190) event.stopPropagation();463 }464 function loadPoints(id, editor, then) {465 var scriptType = g_form.getTableName();466 var scriptId = g_form.getUniqueValue();467 var scriptField = id.split('.')[1];468 var url =469 '/api/now/js/debugpoints/script' +470 '/' +471 scriptType +472 '/' +473 scriptId +474 '/' +475 scriptField;476 $j.ajax({477 url: url,478 method: 'GET',479 headers: { 'X-UserToken': window.g_ck },480 }).done(function (data) {481 if (!data || typeof data !== 'object') return;482 var result = data.result || {};483 var debugpoints = result.debugpoints || {};484 setPoints(debugpoints);485 updateGutterMarkers(editor);486 if (then) then();487 });488 }489 function setPoints(debugpoints) {490 var logpoints = {};491 var breakpoints = {};492 var debugBreakpoints = debugpoints.BREAKPOINT || {};493 var debugLogpoints = debugpoints.LOGPOINT || {};494 breakpoints = getDebugpoints(debugBreakpoints);495 logpoints = getDebugpoints(debugLogpoints);496 GlideEditorJSBreakpoints.setBreakpoints(breakpoints);497 GlideEditorJSLogpoints.setLogpoints(logpoints);498 }499 function getDebugpoints(debugPoints) {500 var points = {};501 Object.keys(debugPoints).map(function (line) {502 var pointData = debugPoints[line];503 points[line] = pointData ? pointData.evaluationString : null;504 });505 return points;506 }507 function hideEditor(event, containerId, conditionId, point, saveHandler) {508 var container = $j(containerId);509 if (510 !container.is(event.target) &&511 container.has(event.target).length === 0512 ) {513 var conditionTextboxElement = $j(conditionId);514 var isWidgetDisplayed = conditionTextboxElement.is(':visible'),515 conditionValue = $j.trim(conditionTextboxElement.val());516 if (517 isWidgetDisplayed &&518 point !== conditionValue &&519 !saveHandler(conditionValue)520 )521 return;522 GlideEditorJSCommon.hideElement(containerId);523 if (EDITOR) {524 GlideEditorJSCommon.removeOutlineClass(EDITOR, LINE_NUMBER);525 EDITOR.refresh();526 }527 }528 }529 function isLintingEnabled() {530 return lintingEnabled;531 }532 return {533 init: init,534 contextMenuOpened: contextMenuOpened,535 hideContextMenu: hideContextMenu,536 updateGutterMarkers: updateGutterMarkers,537 updatePointerStyles: updatePointerStyles,538 getKey: getKey,539 removeConditionClass: removeConditionClass,540 removeOutlineClass: removeOutlineClass,541 isContextMenuClickedOnGutter: isContextMenuClickedOnGutter,542 onGutterContextMenu: onGutterContextMenu,543 showElement: showElement,544 hideElement: hideElement,545 focusContextMenu: focusContextMenu,546 showContextMenu: showContextMenu,547 isBrowserIE: isBrowserIE,548 onGutterClick: onGutterClick,549 removeErrorClass: removeErrorClass,550 updatePointContent: updatePointContent,551 togglePoint: togglePoint,552 subscriberToGutterEvent: subscriberToGutterEvent,553 removeEditorClass: removeEditorClass,554 hidePointReadonlyMode: hidePointReadonlyMode,555 loadPoints: loadPoints,556 stopDotPropogation: stopDotPropogation,557 hideEditor: hideEditor,558 isLintingEnabled: isLintingEnabled,559 };...

Full Screen

Full Screen

helper.js

Source:helper.js Github

copy

Full Screen

...112 if (result instanceof Error)113 throw result;114 return result;115}116function evaluationString(fun, ...args) {117 if (isString(fun)) {118 assert(args.length === 0, 'Cannot evaluate a string with arguments');119 return fun;120 }121 function serializeArgument(arg) {122 if (Object.is(arg, undefined))123 return 'undefined';124 return JSON.stringify(arg);125 }126 return `(${fun})(${args.map(serializeArgument).join(',')})`;127}128function pageBindingInitString(type, name) {129 function addPageBinding(type, bindingName) {130 /* Cast window to any here as we're about to add properties to it131 * via win[bindingName] which TypeScript doesn't like.132 */133 const win = window;134 const binding = win[bindingName];135 win[bindingName] = (...args) => {136 const me = window[bindingName];137 let callbacks = me.callbacks;138 if (!callbacks) {139 callbacks = new Map();140 me.callbacks = callbacks;141 }142 const seq = (me.lastSeq || 0) + 1;143 me.lastSeq = seq;144 const promise = new Promise((resolve, reject) => callbacks.set(seq, { resolve, reject }));145 binding(JSON.stringify({ type, name: bindingName, seq, args }));146 return promise;147 };148 }149 return evaluationString(addPageBinding, type, name);150}151function pageBindingDeliverResultString(name, seq, result) {152 function deliverResult(name, seq, result) {153 window[name].callbacks.get(seq).resolve(result);154 window[name].callbacks.delete(seq);155 }156 return evaluationString(deliverResult, name, seq, result);157}158function pageBindingDeliverErrorString(name, seq, message, stack) {159 function deliverError(name, seq, message, stack) {160 const error = new Error(message);161 error.stack = stack;162 window[name].callbacks.get(seq).reject(error);163 window[name].callbacks.delete(seq);164 }165 return evaluationString(deliverError, name, seq, message, stack);166}167function pageBindingDeliverErrorValueString(name, seq, value) {168 function deliverErrorValue(name, seq, value) {169 window[name].callbacks.get(seq).reject(value);170 window[name].callbacks.delete(seq);171 }172 return evaluationString(deliverErrorValue, name, seq, value);173}174function makePredicateString(predicate, predicateQueryHandler) {175 function checkWaitForOptions(node, waitForVisible, waitForHidden) {176 if (!node)177 return waitForHidden;178 if (!waitForVisible && !waitForHidden)179 return node;180 const element = node.nodeType === Node.TEXT_NODE ? node.parentElement : node;181 const style = window.getComputedStyle(element);182 const isVisible = style && style.visibility !== 'hidden' && hasVisibleBoundingBox();183 const success = waitForVisible === isVisible || waitForHidden === !isVisible;184 return success ? node : null;185 function hasVisibleBoundingBox() {186 const rect = element.getBoundingClientRect();...

Full Screen

Full Screen

App.js

Source:App.js Github

copy

Full Screen

1import React from 'react';2import { StyleSheet, Text, View, Dimensions, SafeAreaView } from 'react-native';3import Button from './components/Button';4import isOperator from './utilities/isOperator';5import joinNumbers from './utilities/joinNumbers';6import baseToDec from './utilities/baseToDec';7import decToBase from './utilities/decToBase';8const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get('window');9type State = {10 buttons: Array<string>11};12export default class App extends React.Component<State> {13 state = {14 buttons: [15 { operation: 'C' },16 { operation: '+' },17 { operation: '-' },18 { operation: '*' },19 { number: '0' },20 { number: '1' },21 { number: '2' },22 { operation: '/' },23 { number: '3' },24 { number: '4' },25 { number: '5' },26 { operation: '=' }27 ],28 base: 6,29 display: '0',30 evaluate: []31 };32 onPressButton = (button) => {33 const { evaluate, display } = this.state;34 const { number, operation } = button;35 if (operation === '=') {36 this.onPressEquals();37 return;38 }39 if (operation === 'C') {40 this.onPressClear();41 return;42 }43 if (!this.validInput(button)) {44 return;45 }46 const newEvaluate = JSON.parse(JSON.stringify(evaluate));47 let newDisplay = JSON.parse(JSON.stringify(display));48 if (newEvaluate[0] === '0') {49 newEvaluate.pop();50 }51 if (newDisplay.charAt(0) === '0') {52 newDisplay = '';53 }54 newEvaluate.push(number || operation);55 newDisplay = `${newDisplay}${number || operation}`;56 this.setState({ evaluate: newEvaluate, display: newDisplay });57 };58 onPressClear = () => {59 this.setState({ display: '0', evaluate: [] });60 };61 onPressEquals = () => {62 const { evaluate, base } = this.state;63 let evaluationString = '';64 let number = '';65 evaluate.forEach((str) => {66 if (!isOperator(str)) {67 number = joinNumbers(number, str);68 } else {69 evaluationString = `${evaluationString}${baseToDec(70 number,71 base72 )}${str}`;73 number = '';74 }75 });76 evaluationString = `${evaluationString}${Number.parseInt(number, base)}`;77 this.setState({78 display: decToBase(eval(evaluationString), base),79 evaluate: [decToBase(eval(evaluationString), base)]80 });81 };82 validInput = (button) => {83 const { display, evaluate } = this.state;84 const lastEntry = display.slice(-1)[0];85 const firstEntry = display.slice(0)[0];86 if (isOperator(lastEntry)) {87 this.setState({ display: display.replace(/.$/, `${button.operation}`) });88 this.setState({ evaluate: evaluate.splice(-1, button.operation) });89 if (button.operation) return false;90 }91 if (firstEntry === '0' && button.number && button.number === '0') {92 return false;93 }94 return true;95 };96 render() {97 const { display, buttons } = this.state;98 return (99 <SafeAreaView style={styles.safeViewContainer}>100 <View style={styles.mainContainer}>101 <View style={styles.resultContainer}>102 <Text style={styles.resultText}>{display}</Text>103 </View>104 <View style={styles.buttonContainer}>105 {buttons.map(button => (106 <Button107 key={`button_${button.number || button.operation}`}108 {...button}109 onPress={() => this.onPressButton(button)}110 />111 ))}112 </View>113 <View style={styles.historyContainer} />114 </View>115 </SafeAreaView>116 );117 }118}119const styles = StyleSheet.create({120 safeViewContainer: {121 flex: 1, backgroundColor: 'darkgreen'122 },123 mainContainer: {124 flex: 1125 },126 resultContainer: {127 flex: 1,128 borderWidth: 0,129 borderColor: 'green',130 alignItems: 'flex-end',131 justifyContent: 'center',132 borderRadius: 0,133 paddingHorizontal: 10,134 backgroundColor: 'darkgreen'135 },136 resultText: {137 color: '#e0ffe2', fontSize: 30138 },139 buttonContainer: {140 flex: 5,141 borderWidth: 0,142 borderColor: 'green',143 flexDirection: 'row',144 flexWrap: 'wrap',145 alignSelf: 'center',146 justifyContent: 'center',147 alignContent: 'stretch'148 },149 historyContainer: {150 flex: 3, backgroundColor: '#243c26'151 },152 phoneScale: {153 transform: [154 {155 scaleX: SCREEN_HEIGHT / 750156 },157 {158 scaleY: SCREEN_HEIGHT / 750159 }160 ]161 }...

Full Screen

Full Screen

ScriptBreakdownForPart.js

Source:ScriptBreakdownForPart.js Github

copy

Full Screen

1/* Copyright (C) 2011-2014 Mattias Ekendahl. Used under MIT license, see full details at https://github.com/developedbyme/dbm/blob/master/LICENSE.txt */2/**3 * Script breakdown for a for loop.4 */5dbm.registerClass("dbm.compiler.breakdown.ScriptBreakdownForPart", "dbm.compiler.breakdown.ScriptBreakdownPart", function(objectFunctions, staticFunctions, ClassReference) {6 //console.log("dbm.compiler.breakdown.ScriptBreakdownForPart");7 8 //Self reference9 var ScriptBreakdownForPart = dbm.importClass("dbm.compiler.breakdown.ScriptBreakdownForPart");10 11 //Error report12 var ErrorManager = dbm.importClass("dbm.core.globalobjects.errormanager.ErrorManager");13 var ReportTypes = dbm.importClass("dbm.constants.error.ReportTypes");14 var ReportLevelTypes = dbm.importClass("dbm.constants.error.ReportLevelTypes");15 16 //Dependencies17 var ScriptBreakdownLinePart = dbm.importClass("dbm.compiler.breakdown.ScriptBreakdownLinePart");18 var ScriptBreakdownCodePart = dbm.importClass("dbm.compiler.breakdown.ScriptBreakdownCodePart");19 20 //Utils21 var ArrayFunctions = dbm.importClass("dbm.utils.native.array.ArrayFunctions");22 var ScopeFunctions = dbm.importClass("dbm.utils.native.string.ScopeFunctions");23 var VariableAliases = dbm.importClass("dbm.utils.data.VariableAliases");24 var JavascriptLanguageFunctions = dbm.importClass("dbm.utils.native.string.JavascriptLanguageFunctions");25 var StringFunctions = dbm.importClass("dbm.utils.native.string.StringFunctions");26 27 //Constants28 var BreakdownTypes = dbm.importClass("dbm.constants.compiler.BreakdownTypes");29 30 /**31 * Constructor32 */33 objectFunctions._init = function() {34 //console.log("dbm.compiler.breakdown.ScriptBreakdownForPart::_init");35 36 this.superCall();37 38 this._type = BreakdownTypes.FOR;39 this._evaluation = null;40 this._code = null;41 42 return this;43 };44 45 objectFunctions._breakdown = function() {46 //console.log("dbm.compiler.breakdown.ScriptBreakdownForPart::_breakdown");47 48 var evaluationIndex = this._script.indexOf("(");49 var evaluationScope = ScopeFunctions.getScope(this._script, evaluationIndex, "(", ")");50 this._evaluation = ScriptBreakdownCodePart.create(this, StringFunctions.trim(this._script.substring(evaluationScope.start+1, evaluationScope.end)));51 this._evaluation.keepBlankLines = true;52 var resultString = StringFunctions.trim(this._script.substring(evaluationScope.end+1, this._script.length));53 if(resultString.charAt(0) === "{" && ScopeFunctions.getScope(resultString, 0, "{", "}").end === resultString.length-1) {54 this._code = ScriptBreakdownCodePart.create(this, resultString.substring(1, resultString.length-1));55 this._code.setScope("{", "}");56 }57 else {58 this._code = ScriptBreakdownLinePart.create(this, resultString);59 }60 this._childBreakdowns.push(this._evaluation);61 this._childBreakdowns.push(this._code);62 };63 64 objectFunctions.compile = function(aCompileData) {65 66 var evaluationString = this._evaluation.compile(aCompileData);67 var isInType = evaluationString.match(new RegExp("^[^;]* in .[^;]*$"));68 69 if(!isInType) {70 var evaluationSplitArray = evaluationString.split(";");71 for(var i = evaluationSplitArray.length; i < 3; i++) {72 evaluationSplitArray.push("");73 }74 evaluationString = evaluationSplitArray.join(";");75 }76 77 var returnString = "for(" + evaluationString + ")";78 returnString += this._code.compile(aCompileData);79 80 return returnString;81 };82 83 objectFunctions.setAllReferencesToNull = function() {84 85 this._evaluation = null;86 this._result = null;87 88 this.superCall();89 };90 91 staticFunctions.create = function(aParent, aScript) {92 var newScriptBreakDown = (new ClassReference()).init();93 newScriptBreakDown.setParent(aParent);94 newScriptBreakDown.setScript(aScript);95 return newScriptBreakDown;96 };...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1let currNumber = document.getElementById("currNumber");2let history = document.getElementById("history");3const buttons = document.getElementsByClassName("calcButton");4const CE = document.getElementById("CE");5const C = document.getElementById("C");6let EvaluationString = history.innerText;7const setCurrNumber = (number) => {8 currNumber.value = number;9};10const setHistory = (historyValue) => {11 history.innerText = historyValue;12};13const handleMultiplication = (number) => {14 EvaluationString = EvaluationString + number + "*";15 setHistory(EvaluationString);16 setCurrNumber("");17};18const handleDivision = (number) => {19 EvaluationString = EvaluationString + number + "/";20 setHistory(EvaluationString);21 setCurrNumber("");22};23const handleSubtraction = (number) => {24 EvaluationString = EvaluationString + number + "-";25 setHistory(EvaluationString);26 setCurrNumber("");27};28const handleAddition = (number) => {29 EvaluationString = EvaluationString + number + "+";30 setHistory(EvaluationString);31 setCurrNumber("");32};33const changeOperation = (operation) => {34 EvaluationString =35 String(EvaluationString).substring(0, EvaluationString.length - 1) +36 operation;37 setHistory(EvaluationString);38};39const calcResult = (number) => {40 let result = eval(EvaluationString + number);41 return String(result).length > 16 ? String(result).substring(0, 16) : result;42};43C.addEventListener("click", () => {44 setHistory("");45 setCurrNumber("");46 EvaluationString = "";47});48CE.addEventListener("click", () => {49 let number = currNumber.value;50 number = number.substring(0, number.length - 1);51 setCurrNumber(number);52});53for (let i = 0; i < buttons.length; i++) {54 buttons[i].addEventListener("click", (e) => {55 let number = currNumber.value;56 let key = e.target.innerText;57 switch (key) {58 case "+":59 if (!number == "") {60 handleAddition(number);61 }62 if (EvaluationString != "") {63 changeOperation("+");64 }65 break;66 case "-":67 if (!number == "") {68 handleSubtraction(number);69 }70 if (EvaluationString != "") {71 changeOperation("-");72 }73 break;74 case "x":75 if (!number == "") {76 handleMultiplication(number);77 }78 if (EvaluationString != "") {79 changeOperation("*");80 }81 break;82 case "÷":83 if (!number == "") {84 handleDivision(number);85 }86 if (EvaluationString != "") {87 changeOperation("/");88 }89 break;90 case "=":91 if (!number == "") {92 setHistory(EvaluationString + number + "=");93 setCurrNumber(calcResult(number));94 EvaluationString = "";95 }96 break;97 default:98 if (key == "." && number == "") {99 number += "0.";100 } else {101 number += key;102 }103 if (!isNaN(number)) {104 setCurrNumber(number);105 }106 break;107 }108 });...

Full Screen

Full Screen

test.js

Source:test.js Github

copy

Full Screen

1import React, {Component} from 'react';2import './test.css';3import TestQuestion from './test-question.js'4class Test extends Component {5 constructor(props) {6 super(props);7 this.handleEvaluateClick = this.handleEvaluateClick.bind(this);8 this.state = {9 isFinished: false,10 evaluationString: ""11 };12 }13 handleEvaluateClick(){14 let rightAnswersCount = 0;15 this.props.data.items.forEach(item => {16 rightAnswersCount += checkAnswers(item.answers);17 });18 let mark = this.props.data.evaluations[0].result;19 for(let i = 1; i < this.props.data.evaluations.length; ++i)20 if(rightAnswersCount >= this.props.data.evaluations[i].count) mark = this.props.data.evaluations[i].result;21 let result = "Правильных ответов: " + rightAnswersCount + " из " + this.props.data.items.length +22 "; Оценка: " + mark;23 this.setState({24 isFinished: true,25 evaluationString: result26 });27 this.props.data.result = result;28 }29 render() {30 return (31 <div className="test">32 <div dangerouslySetInnerHTML={{__html: this.props.data.annotation}}/>33 {34 this.props.data.items.map((item, i)=>35 <TestQuestion36 key={"testQuestion" + i} text={item.text} answers={item.answers}37 />38 )39 }40 <div className="test-button" onClick={this.handleEvaluateClick}>Закончить тест</div>41 <div className="test-result">{(this.state.isFinished && this.state.evaluationString)}</div>42 </div>43 );44 }45}46export default Test;47function checkAnswers(answers) {48 for(let i=0; i<answers.length; ++i) {49 if(answers[i].userChoice !== answers[i].isRight) return 0;50 }51 return 1;...

Full Screen

Full Screen

utility.js

Source:utility.js Github

copy

Full Screen

1/* eslint no-eval: 0 */2export const computeInputsBasedOnOperator = (3 firstOperand,4 secondOperand,5 operator6) => {7 const evaluationString = `${firstOperand} ${operator} ${secondOperand}`;8 const result = eval(evaluationString);9 return result;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 const dimensions = await page.evaluate(() => {6 return {7 };8 });9 console.log('Dimensions:', dimensions);10 await browser.close();11})();12const puppeteer = require('puppeteer');13(async () => {14 const browser = await puppeteer.launch();15 const page = await browser.newPage();16 const dimensions = await page.evaluate(() => {17 return {18 };19 });20 console.log('Dimensions:', dimensions);21 await browser.close();22})();23const puppeteer = require('puppeteer');24(async () => {25 const browser = await puppeteer.launch();26 const page = await browser.newPage();27 const dimensions = await page.evaluate(() => {28 return {29 };30 });31 console.log('Dimensions:', dimensions);32 await browser.close();33})();34const puppeteer = require('puppeteer');35(async () => {36 const browser = await puppeteer.launch();37 const page = await browser.newPage();38 const dimensions = await page.evaluate(() => {39 return {40 };41 });42 console.log('Dimensions:', dimensions);43 await browser.close();44})();45const puppeteer = require('puppeteer');46(async () => {47 const browser = await puppeteer.launch();48 const page = await browser.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 const dimensions = await page.evaluate(() => {6 return {7 };8 });9 console.log('Dimensions:', dimensions);10 await browser.close();11})();12Dimensions: { width: 800, height: 600, deviceScaleFactor: 1 }

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.evaluate(() => {6 const input = document.querySelector('input');7 input.value = 'Puppeteer';8 input.dispatchEvent(new Event('input', {bubbles: true}));9 });10 await page.waitForSelector('ul.erkvQe li span');11 const text = await page.evaluate(() => {12 const list = document.querySelectorAll('ul.erkvQe li span');13 return Array.from(list).map(el => el.textContent);14 });15 console.log(text);16 await browser.close();17})();18const puppeteer = require('puppeteer');19(async () => {20 const browser = await puppeteer.launch({headless: false});21 const page = await browser.newPage();22 await page.evaluate(() => {23 const input = document.querySelector('input');24 input.value = 'Puppeteer';25 input.dispatchEvent(new Event('input', {bubbles: true}));26 });27 await page.waitForSelector('ul.erkvQe li span');28 const text = await page.evaluate(() => {29 const list = document.querySelectorAll('ul.erkvQe li span');30 return Array.from(list).map(el => el.textContent);31 });32 console.log(text);33 await browser.close();34})();35const puppeteer = require('puppeteer');36(async () => {37 const browser = await puppeteer.launch({headless: false});38 const page = await browser.newPage();39 await page.evaluate(() => {40 const input = document.querySelector('input');41 input.value = 'Puppeteer';42 input.dispatchEvent(new Event('input', {bubbles: true}));43 });44 await page.waitForSelector('ul.erkvQe li span');45 const text = await page.evaluate(() => {46 const list = document.querySelectorAll('ul.erkvQe li span');47 return Array.from(list).map(el => el.textContent);48 });49 console.log(text);50 await browser.close();51})();

Full Screen

Using AI Code Generation

copy

Full Screen

1(async () => {2const browser = await puppeteer.launch();3const page = await browser.newPage();4const dimensions = await page.evaluate(() => {5return {6};7});8console.log('Dimensions:', dimensions);9await browser.close();10})();11(async () => {12const browser = await puppeteer.launch();13const page = await browser.newPage();14const dimensions = await page.evaluate(() => {15return {16};17});18console.log('Dimensions:', dimensions);19await browser.close();20})();21(async () => {22const browser = await puppeteer.launch();23const page = await browser.newPage();24const dimensions = await page.evaluate(() => {25return {26};27});28console.log('Dimensions:', dimensions);29await browser.close();30})();31(async () => {32const browser = await puppeteer.launch();33const page = await browser.newPage();34const dimensions = await page.evaluate(() => {35return {36};37});38console.log('Dimensions:', dimensions);39await browser.close();40})();41(async () => {42const browser = await puppeteer.launch();43const page = await browser.newPage();44const dimensions = await page.evaluate(() => {45return {46};47});48console.log('Dimensions:', dimensions);49await browser.close();50})();51(async () => {52const browser = await puppeteer.launch();53const page = await browser.newPage();54const dimensions = await page.evaluate(() => {

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 let title = await page.evaluate(() => {6 return document.title;7 });8 console.log(title);9 await browser.close();10})();11const puppeteer = require('puppeteer');12(async () => {13 const browser = await puppeteer.launch();14 const page = await browser.newPage();15 let title = await page.evaluate(() => {16 return document.title;17 });18 console.log(title);19 await browser.close();20})();21const puppeteer = require('puppeteer');22(async () => {23 const browser = await puppeteer.launch();24 const page = await browser.newPage();25 let title = await page.evaluate(() => {26 return document.title;27 });28 console.log(title);29 await browser.close();30})();31const puppeteer = require('puppeteer');32(async () => {33 const browser = await puppeteer.launch();34 const page = await browser.newPage();35 let title = await page.evaluate(() => {36 return document.title;37 });38 console.log(title);39 await browser.close();40})();41const puppeteer = require('puppeteer');42(async () => {43 const browser = await puppeteer.launch();44 const page = await browser.newPage();45 let title = await page.evaluate(() => {46 return document.title;47 });48 console.log(title);49 await browser.close();50})();51const puppeteer = require('puppeteer');52(async () => {53 const browser = await puppeteer.launch();54 const page = await browser.newPage();55 let title = await page.evaluate(() => {56 return document.title;

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.waitForSelector('input');6 await page.click('input');7 await page.type('input', 'puppeteer');8 await page.waitForSelector('input[type="submit"]');9 await page.click('input[type="submit"]');10 await page.waitForSelector('div#resultStats');11 const count = await page.evaluate(() => {12 const result = document.querySelector('div#resultStats').innerText;13 return result;14 });15 console.log(count);16 await browser.close();17})();18About 4,500,000 results (0.54 seconds)

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2var evaluationString = require('evaluation-string');3(async () => {4 const browser = await puppeteer.launch();5 const page = await browser.newPage();6 let title = await evaluationString(page, () => document.querySelector('h1').innerText);7 console.log(title);8 await browser.close();9})();

Full Screen

Using AI Code Generation

copy

Full Screen

1async function evaluateString(page, selector, property){2 return await page.evaluate((selector, property) => {3 return document.querySelector(selector)[property];4 }, selector, property);5}6async function evaluateString(page, selector, property){7 return await page.evaluate((selector, property) => {8 return document.querySelector(selector)[property];9 }, selector, property);10}11async function evaluateString(page, selector, property){12 return await page.evaluate((selector, property) => {13 return document.querySelector(selector)[property];14 }, selector, property);15}16async function evaluateString(page, selector, property){17 return await page.evaluate((selector, property) => {18 return document.querySelector(selector)[property];19 }, selector, property);20}21async function evaluateString(page, selector, property){22 return await page.evaluate((selector, property) => {23 return document.querySelector(selector)[property];24 }, selector, property);25}26async function evaluateString(page, selector, property){27 return await page.evaluate((selector, property) => {28 return document.querySelector(selector)[property];29 }, selector, property);30}31async function evaluateString(page, selector, property){32 return await page.evaluate((selector, property) => {33 return document.querySelector(selector)[property];34 }, selector, property);35}36async function evaluateString(page, selector, property){37 return await page.evaluate((selector, property) => {38 return document.querySelector(selector)[property];39 }, selector, property);40}41async function evaluateString(page, selector, property){42 return await page.evaluate((selector, property) => {43 return document.querySelector(selector)[property];44 }, selector, property);45}46async function evaluateString(page, selector, property){47 return await page.evaluate((selector, property) => {48 return document.querySelector(selector)[property];49 }, selector, property);50}51async function evaluateString(page, selector, property){52 return await page.evaluate((selector, property

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful