Best JavaScript code snippet using testcafe
shiftSchedulerReducer.js
Source:shiftSchedulerReducer.js
1import {addMonth, handleDateClick, subMonth} from "../logic/shifts/scheduler";2import {isSameDate} from "../logic/time/timeUtils";3//FOR TESTING ONLY4var scheduler = {5 employees: [6 {7 name: "Cindy Rees", id: 1885959, avatarImg: "image base64 <--", avatarColor: "red", place: {8 id: 84486565,9 name: "Supermarket StredoÄeská"10 }11 },12 {13 name: "Kyle Perry", id: 1885958, avatarImg: "image base64 <--", avatarColor: "green", place: {14 id: 84486565,15 name: "Supermarket StredoÄeská"16 }17 },18 {19 name: "Andreas Talbot", id: 1885957, avatarImg: "image base64 <--", avatarColor: "blue", place: {20 id: 84486565,21 name: "Supermarket StredoÄeská"22 }23 },24 {25 name: "Vickie Neville", id: 1885956, avatarImg: "image base64 <--", avatarColor: "orange", place: {26 id: 84486565,27 name: "Supermarket StredoÄeská"28 }29 },30 {31 name: "Amanda Hamlet", id: 1885955, avatarImg: "image base64 <--", avatarColor: "brown", place: {32 id: 84486565,33 name: "Supermarket StredoÄeská"34 }35 },36 {37 name: "Lillie Rowley", id: 1885954, avatarImg: "image base64 <--", avatarColor: "violet", place: {38 id: 84486565,39 name: "Supermarket StredoÄeská"40 }41 },42 ],43 selectedDays: [],44 selectedEmployees: [],45 currentMonth: new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0),46 calendarLock: false,47 selected: []48};49function empComparator(e1, e2) {50 if (e1.shiftStart > e2.shiftStart) return 1;51 if (e1.shiftStart < e2.shiftStart) return -1;52 return 0;53}54function addEmployee(state, employee, selectedPlaceId, selectedDepartmentId) {55 var places = state.selected; //todo rename selected56 if (!isPlacePresent(places, selectedPlaceId)57 && employee58 && state.selectedDays && state.selectedDays.length > 0) places.push(getNewPlace(selectedPlaceId));59 var place = getElementById(places, selectedPlaceId);60 state.selectedDays.forEach(d => {61 let date = new Date(d);62 let trackId = Math.floor(Math.random() * 100000000000);63 /*najdi Äi už taky neexistuje*/64 place.employees.push({65 departmentId: selectedDepartmentId,66 departmentName: "department " + selectedDepartmentId,67 trackId: trackId,68 id: employee.id,69 name: employee.name,70 avatarColor: employee.avatarColor,71 avatarImg: employee.avatarImg,72 shiftStart: new Date(date.getFullYear(), date.getMonth(), date.getDate(), 12).getTime(),73 shiftEnd: new Date(date.getFullYear(), date.getMonth(), date.getDate(), 12).getTime(),74 })75 state.selectedEmployees.push(trackId);76 state.calendarLock = true;77 })78 place.employees.sort(empComparator).reverse();79 return state;80}81function removeSelected(state, employee) {82 /*83 * ak je selectnuty - vymaz vsetkych selectnutych84 * 1. filtruj selectnutych a ked sa nejaky rovna nejakemu v selectedDays,85 * tak ho vymaz so selectnutych aj so selected days86 * ak selected length === 0 return87 *88 * ak nieje selectnuty - vymaz iba jeho89 *90 * */91 let isSelected = state.selectedEmployees.filter(trackId => trackId === employee.trackId).length > 0;92 //if (e.trackId === employee.trackId) found = true;93 if (!isSelected) state.selected.forEach(place => {94 let found = false;95 //vymaz zmenu zamestnanca96 place.employees = place.employees.filter(e => {97 if (e.trackId === employee.trackId) found = true;98 return e.trackId !== employee.trackId99 });100 //vymaz employeeho zo selected employees101 state.selectedEmployees = state.selectedEmployees.filter(trackId => trackId !== employee.trackId)102 //ak place nema ani jednoho employee vymza ho103 if (place.employees.length < 1) state.selected = state.selected.filter(p => p.id !== place.id)104 if (found) return state;105 })106 else state.selected.forEach(place => {107 place.employees = place.employees.filter(e => {108 let returnValue = true;109 state.selectedEmployees = state.selectedEmployees.filter(trackId => {110 if (trackId === e.trackId) returnValue = false;111 return trackId !== e.trackId112 })113 return returnValue;114 })115 if (place.employees.length < 1) state.selected = state.selected.filter(p => p.id !== place.id)116 })117 return state;118}119function selectedClick(state, employee) {120 let filteredEmp = state.selectedEmployees.filter(e => e === employee.trackId);121 //unselect if was selected122 if (filteredEmp.length > 0) state.selectedEmployees = state.selectedEmployees.filter(e => e !== employee.trackId);123 //select if wasn't selected124 else state.selectedEmployees.push(employee.trackId)125 return state;126}127function handleStartClick(state, type, value) {128 let selectedEmployees = [];129 let selEmp = [...state.selectedEmployees];130 //find all selected employees131 state.selected.forEach(place => {132 place.employees.filter(e => {133 let filEmp = selEmp.filter(s => {134 if (s === e.trackId) {135 selEmp = selEmp.filter(s => s !== e.trackId);136 return true;137 }138 return false;139 });140 if (!isEmpty(filEmp))141 selectedEmployees.push(e);142 })143 });144 selectedEmployees.forEach((e) => {145 /*146 * posun dopredu ak nebude cas väÄÅ¡Ã ako end a bude to rovnaky deÅ147 * posuÅ dozadu ak to bude stale rovnaky deÅ148 *149 *150 * posun dopredu ak nie je viac ako 24h151 * posun dozadu ak je viac ako start152 *153 * */154 if (type === "START_ADD") {155 if (e.shiftStart + value <= e.shiftEnd156 && isSameDate(new Date(e.shiftStart + value), new Date(e.shiftStart))) {157 e.shiftStart += value;158 } else {159 if (isSameDate(new Date(e.shiftStart), new Date(e.shiftEnd))) {160 e.shiftStart = e.shiftEnd;161 }162 else {163 let shDate = new Date(e.shiftStart);164 e.shiftStart = new Date(shDate.getFullYear(), shDate.getMonth(), shDate.getDate(), 23, 55).getTime();165 }166 }167 } else if (type === "START_SUB") {168 if (isSameDate(new Date(e.shiftStart - value), new Date(e.shiftStart))) {169 e.shiftStart -= value;170 } else {171 let shDate = new Date(e.shiftStart);172 e.shiftStart = new Date(shDate.getFullYear(), shDate.getMonth(), shDate.getDate()).getTime();173 };174 } else if (type === "END_ADD") {175 if ((e.shiftEnd + value) - e.shiftStart <= (3600000 * 24)) {176 e.shiftEnd += value;177 } else e.shiftEnd = e.shiftStart + 3600000 * 24;178 } else if (type === "END_SUB") {179 if ((e.shiftEnd - value) >= e.shiftStart) {180 e.shiftEnd -= value;181 } else e.shiftEnd = e.shiftStart;182 }183 })184 return state;185}186export var shiftSchedulerReducer = (state = scheduler, action) => {187 switch (action.type) {188 case "CALENDAR_DATE_CLICK":189 return {...handleDateClick(state, action.dayTimestamp)};190 case "SHIFT_SCHEDULER_ARROW_NEXT_CLICK":191 return {...state, currentMonth: addMonth(state.currentMonth)};192 case "SHIFT_SCHEDULER_ARROW_BACK_CLICK":193 return {...state, currentMonth: subMonth(state.currentMonth)};194 case "SCHEDULER_EMPLOYEE_ADD":195 return addEmployee(state, action.employee, action.selectedPlaceId, action.selectedDepartmentId)196 case "CALENDAR_UNLOCK":197 return {...state, calendarLock: false};198 case "SELECTED_REMOVE":199 return {...removeSelected(state, action.employee)}200 case "SELECTED_CLICK":201 return {...selectedClick(state, action.employee)}202 case "MULTIPLE_SELECTED":203 let st = state;204 action.employees.forEach(e => {205 st = selectedClick(st, e)206 })207 return {state, ...st}208 case "SHIFT_START_BACK_CLICK":209 return {...handleStartClick(state, "START_SUB", action.value)};210 case "SHIFT_START_NEXT_CLICK":211 return {...handleStartClick(state, "START_ADD", action.value)};212 case "SHIFT_END_BACK_CLICK":213 return {...handleStartClick(state, "END_SUB", action.value)};214 case "SHIFT_END_NEXT_CLICK":215 return {...handleStartClick(state, "END_ADD", action.value)};216 default:217 return state;218 }219}220function getNewPlace(id) {221 if (!id) {222 console.log("getNewPlace wrong id");223 return null;224 }225 return {226 id: id,227 name: "Place " + id, //todo fetch name from redux placeReducer228 employees: []229 }230}231function isPlacePresent(places, placeId) {232 let filteredPlace = places.filter(p => p.id === placeId);233 if (isEmpty(filteredPlace)) return false;234 return true;235}236function isDepartmentPresent(place, depId) {237}238function getElementById(array, id) {239 let element = array.filter(p => p.id === id);240 if (isEmpty(element)) return null;241 return element[0];242}243function getNewDepartment(depId) {244 return {245 id: depId,246 days: []247 };248}249/*______-*/250export function isEmpty(array) {251 return !(array.length > 0);252}253function selectEmployee(state, employeeId) {254 let filteredEmployees = state.selectedEmployees.filter(e => e === employeeId)255 if (filteredEmployees && filteredEmployees.length < 1) state.selectedEmployees.push(employeeId);256 return state.selectedEmployees;257}258export function uniqueDepartmentsFilter(v, i, a) {259 return a.findIndex(t => (t.departmentId === v.departmentId)) === i;260}261export function uniqueDaysFilter(v, i, a) {262 return a.findIndex(t => (t.dayStart === v.dayStart) && (t.dayEnd === v.dayEnd)) === i;263}264export function uniqueDayStarts(v, i, a, depId) {265 // return a.findIndex(t => (t.departmentId === v.departmentId) && t.departmentId === depId) === i;266 return a.findIndex(t => (t.departmentId === depId)) === i;267}268//arr2.filter((v, i, a) => a.findIndex(t => (t.label === v.label && t.value === v.value)) === i)269export function uniqueDayReducer(270 unique, o) {271 if (!unique.some(obj => obj.dayStart === o.dayStart && obj.dayEnd === o.dayEnd)) {272 unique.push(o);273 }274 return unique;275}276export function uniqueTimeReducer(277 unique, o) {278 if (!unique.some(obj => {279 //console.log("unique: "+unique+" o: "+o)280 return ((obj.shiftStart === o.shiftStart && obj.shiftEnd === o.shiftEnd)281 //m|| (obj.shiftStart === o.shiftStart) //&& obj.shiftEnd !== o.shiftEnd)282 )283 //return isSameDateRange(obj,o)284 //|| (obj.shiftStart === o.shiftStart && obj.shiftEnd !== o.shiftEnd)285 })) {286 unique.push(o);287 }288 return unique;289}290export function uniqueDepartmentsReducer(291 unique, o) {292 if (!unique.some(obj => {293 //console.log("unique: "+unique+" o: "+o)294 return obj.departmentId === o.departmentId295 })) {296 unique.push(o);297 }298 return unique;299}300export function uniqueDateReducer(301 unique, o) {302 // console.log("unique: "+unique+" o: "+o)303 if (!unique.some(obj => {304 // console.log("obj end: "+obj.shiftEnd+" o end: "+o.shiftEnd)305 //return (obj.shiftStart === o.shiftStart && obj.shiftEnd !== o.shiftEnd)306 return isSameDateRange(obj, o)307 }308 )) {309 unique.push(o);310 }311 return unique;312}313export function uniqueDateTimeReducer(314 unique, o) {315 // console.log("unique: "+unique+" o: "+o)316 if (!unique.some(obj => {317 // console.log("obj end: "+obj.shiftEnd+" o end: "+o.shiftEnd)318 return (obj.shiftStart === o.shiftStart && obj.shiftEnd !== o.shiftEnd)319 // return isSameDateRange(obj,o)320 }321 )) {322 unique.push(o);323 }324 return unique;325}326export function isSameDateRange(o1, o2) {327 //if (o1.shiftStart === o2.shiftStart && o1.shiftEnd === o2.shiftEnd) return true;328 if (isSameDate(new Date(o1.shiftStart), new Date(o2.shiftStart))329 && isSameDate(new Date(o1.shiftEnd), new Date(o2.shiftEnd))330 && isSameDate(new Date(o1.shiftStart), new Date(o1.shiftEnd))331 ) return true;332 if ((o1.shiftStart === o2.shiftStart && isSameDate(new Date(o1.shiftStart), new Date(o2.shiftStart)))333 && (o1.shiftEnd !== o2.shiftEnd) && isSameDate(new Date(o1.shiftEnd), new Date(o2.shiftEnd))334 ) return true;335 if ((o1.shiftStart === o2.shiftStart && isSameDate(new Date(o1.shiftStart), new Date(o2.shiftStart)))336 && (o1.shiftEnd === o2.shiftEnd) && isSameDate(new Date(o1.shiftEnd), new Date(o2.shiftEnd))337 ) return true;338 return false;...
shift_scripts.js
Source:shift_scripts.js
1function FillAggregates(tablediv, headerdiv, myinstitute){2 $.getJSON('shifts/total_shift_aggregates', function(data){3 html = "";4 console.log(data);5 console.log(myinstitute);6 var yr = (new Date()).getFullYear();7 var total = 0;8 var totalyr = 0;9 $(headerdiv).html("Shifts " + yr.toString());10 for(var i=0; i<data.length; i+=1){11 html += "<tr";12 if(i==0)13 html+= " title='winner winner chicken dinner'";14 if(data[i]['_id'].includes(myinstitute))15 html+= " style='background-color:#ef476f;color:white'";16 html+= "><td>" + data[i]['_id'] + "</td><td>" + data[i]['total'].toString() + "</td>";17 total+=data[i]['total'];18 var this_year = 0;19 for(var j = 0; j<data[i]["years"].length; j++)20 if(data[i]["years"][j]["year"] == yr)21 this_year = data[i]["years"][j]["count"];22 totalyr+=this_year;23 html += "<td>" + this_year.toString() + "</td></tr>";24 }25 html+= "<tr style='border-bottom:1px solid black'><td colspan='100%'></td></tr>";26 html+="<tr><td></td><td><strong>"+total.toString()+"</strong></td><td><strong>"+totalyr.toString()+"</strong></td></tr>";27 $(tablediv).html(html);28 });29}30function InitializeCalendar(divname, calling_user){31 var colors = {"free": "#06d6a0",32 "run coordinator": "#0c1178",33 "taken": "#0c1178",34 "shifter": "#0c1178",35 "training": "#ef476f",36 "credit": "#ff3300"};37 $('#sign_up_form').submit(function(e){38 e.preventDefault();39 $.ajax({40 url:'shifts/modify_shift',41 type:'post',42 data:$('#sign_up_form').serialize(),43 success:function(){44 $("#calendarview").fullCalendar('refetchEvents'); 45 $("#ttip").css('display', 'none');46 $("[data-dismiss=modal]").trigger({ type: "click" });47 }48 });49 });50 $('#add_shift_form').submit(function(e){51 e.preventDefault();52 $.ajax({53 url: 'shifts/add_shifts',54 type: 'post',55 data: $('#add_shift_form').serialize(),56 success: function(){57 alert("Added your shifts! Check out the calendar page.");58 },59 error: function(){60 alert("Error adding your shifts... sorry? Hey, could it be that you don't have permission?");61 }62 });63 });64 $('#remove_shift_form').submit(function(e){65 e.preventDefault();66 $.ajax({67 url: 'shifts/remove_shifts',68 type: 'post',69 data: $('#remove_shift_form').serialize(),70 success: function(){71 alert("Removed the specified shifts! Check out the calendar page.");72 },73 error: function(){74 alert("Error removing your shifts... sorry? Hey, could it be that you don't have permission?");75 }76 });77 });78 $('#' + divname).fullCalendar(79 {80 // defaultView: 'weekList',81 eventLimit: true,82 events: 'shifts/get_shifts', // use the `url` property 83 color: 'yellow', // an option! 84 textColor: 'black', // an option! 85 height: "parent",86 header: {87 left: '',88 center: 'title',89 },90 viewRender: function(){91 // date=$("#"+divname).fullCalendar('getDate');92 // MakeSidebar("inst_table_body", date.year());93 },94 error: function() {95 alert('there was an error while fetching events!');96 },97 eventRender: function(event, element, view){98 element.find('.fc-time').html(""); 99 type = 'free';100 if(event['available']) type='free';101 else type=event.type;102 if(event.type=='credit') type='credit';103 element.css('background-color', colors[type]);104 event.color = colors[type];105 },106 eventLimitClick: 'day',107 eventClick: function(calEvent, jsEvent, view) {108 document.getElementById("shift_modal_title").innerHTML = "Week " + moment(calEvent.start, "MM-DD-YYYY").week() + "<strong> "+calEvent.type+"</strong>";109 document.getElementById("shift_modal_start").innerHTML =110 moment(calEvent.start, "MM-DD-YYYY").format("MM-DD-YYYY");111 document.getElementById("shift_modal_end").innerHTML=112 moment(calEvent.end, "MM-DD-YYYY").format("MM-DD-YYYY");113 document.getElementById("shift_modal_institute").innerHTML=calEvent.institute;114 document.getElementById("shift_modal_user").innerHTML=calEvent.shifter;115 if(calEvent.available)116 document.getElementById("shift_modal_available").innerHTML =117 "<strong>Available</strong>";118 else119 document.getElementById("shift_modal_available").innerHTML =120 "<strong>Unavailable</strong>";121 if(calEvent.available){122 $('#btn_mark_available').attr("disabled", true);123 $('#btn_sign_up').attr("disabled", false);124 }125 else{126 $('#btn_sign_up').attr("disabled", true);127 128 // Want to allow people to set as available only if allowed 129 console.log(calEvent);130 console.log(calling_user);131 if( calling_user == calEvent.shifter )132 $('#btn_mark_available').attr("disabled", false);133 else134 $('#btn_mark_available').attr("disabled", true);135 }136 // Set on click event 137 $("#btn_sign_up").attr("onclick",138 "SignUp('"+calEvent.type+"', '"139 +calEvent.start+"', '"140 +calEvent.end+"')");141 $("#btn_mark_available").attr("onclick",142 "MarkAvailable('"+calEvent.type+"', '"143 +calEvent.start+"', '"144 +calEvent.end+"', '"+calEvent.shifter+"', '"+145 calEvent.institute+"')");146 $("#btn_train").attr("onclick",147 "SignUpTrain('"+calEvent.type+"', '"148 +calEvent.start+"', '"149 +calEvent.end+"')");150 $("#btn_credit").attr("onclick",151 "SignUpCredit('"+calEvent.type+"', '"152 +calEvent.start+"', '"153 +calEvent.end+"')");154 // Put at proper location 155 var x = (jsEvent.clientX + 20) + 'px',156 y = (jsEvent.clientY + 20) + 'px';157 if((jsEvent.clientX+20)+$("#ttip").width() > $(window).width())158 x=$(window).width()-$("#ttip").width() + 'px';159 if((jsEvent.clientY+20)+$("#ttip").height() > $(window).height())160 y=$(window).height()-$("#ttip").height() + 'px';161 $("#ttip").css('top', y);162 $("#ttip").css('left', x);163 $("#ttip").css('display', 'block');164 }165 }); 166 }167function CloseTooltip(){168$(".ttip").css('display', 'none');//removeClass("show");169}170function SignUp(shiftType, shiftStart, shiftEnd){171 $('#id_start_date').val(moment(parseInt(shiftStart)).format("YYYY-MM-DD"));172 $("#id_start_date").prop("readonly", true);173 $('#id_end_date').val(moment(parseInt(shiftEnd)).format("YYYY-MM-DD"));174 $("#id_end_date").prop("readonly", true);175 $('#signUpModal').modal('show');176 ret = "";177 ret+="<option value='"+shiftType+"'>"+shiftType+"</option>";178 ret+="<option value='training'>training</option>";179 document.getElementById("id_shift_type").innerHTML=ret;180 document.getElementById("id_remove").checked = false;181 $("#id_remove").val(false);182}183function SignUpTrain(shiftType, shiftStart, shiftEnd){184 $('#id_start_date').val(moment(parseInt(shiftStart)).format("YYYY-MM-DD"));185 $("#id_start_date").prop("readonly", true);186 $('#id_end_date').val(moment(parseInt(shiftEnd)).format("YYYY-MM-DD"));187 $("#id_end_date").prop("readonly", true);188 $('#signUpModal').modal('show');189 ret = "";190 ret+="<option value='training'>training</option>";191 document.getElementById("id_shift_type").innerHTML=ret;192 document.getElementById("id_remove").checked = false;193 $("#id_remove").val(false);194}195function SignUpCredit(shiftType, shiftStart, shiftEnd){196 $('#id_start_date').val(moment(parseInt(shiftStart)).format("YYYY-MM-DD"));197 $("#id_start_date").prop("readonly", true);198 $('#id_end_date').val(moment(parseInt(shiftEnd)).format("YYYY-MM-DD"));199 $("#id_end_date").prop("readonly", true);200 $('#signUpModal').modal('show');201 ret = "";202 ret+="<option value='credit'>credit</option>";203 document.getElementById("id_shift_type").innerHTML=ret;204 document.getElementById("id_remove").checked = false;205 $("#id_remove").val(false);206}207function MarkAvailable(shiftType, shiftStart, shiftEnd, shifter, institute){208 $('#id_start_date').val(moment(parseInt(shiftStart)).format("YYYY-MM-DD"));209 $("#id_start_date").prop("readonly", true);210 $('#id_end_date').val(moment(parseInt(shiftEnd)).format("YYYY-MM-DD"));211 $("#id_end_date").prop("readonly", true);212 $("#id_institute").val(institute);213 $("#id_user").val(shifter);214 console.log($("#id_institute").val());215 console.log($("#id_user").val());216 console.log(shifter);217 ret = "";218 ret+="<option value='"+shiftType+"'>"+shiftType+"</option>";219 ret+="<option value='training'>training</option>";220 document.getElementById("id_shift_type").innerHTML=ret;221 document.getElementById("id_remove").checked = true;222 $("#id_remove").val(true);223 $("#sign_up_form").submit();224}225function EnableShiftSubmit(){226 if( $("#id_disclaimer").is(":checked") && $("#id_has_car").is(":checked"))227 $("#shift_submit_button").prop("disabled", false);228 else229 $("#shift_submit_button").prop("disabled", true);...
load-dump.service.js
Source:load-dump.service.js
1(() => {2 const angular = window.angular;3 Service.$inject = ['IrisUtils', '$filter', 'Utils'];4 angular5 .module('app')6 .service('LoadDump', Service);7 function Service(IrisUtils, $filter, Utils) {8 return {9 getDumpDetails,10 getLoadAndDumpEvents,11 getGanttData12 };13 function getDumpDetails(truckName, date) {14 const dateNumber = IrisUtils.getDateNumber(date);15 const minutes = date.getHours() * 60 + date.getMinutes();16 const rows = [17 {path: '[Equipment].[H1].[Name].Members'},18 {path: '[EquipmentTruck].[H1].[Name].Members'},19 {path: '[Measures].[Capacity]'},20 {path: '[Measures].[MeasuredTons]'},21 {path: '[Location].[H1].[Name].Members'},22 {path: '[Location].[H2].[Grade].Members'}23 ];24 const filters = [25 {dimension: 'ProductionStatus', hierarchy: 'H1', hierarchyLevel: 'Description', values: ['Dumping']},26 {dimension: 'Equipment', hierarchy: 'H1', hierarchyLevel: 'Name', values: [truckName]},27 {dimension: 'StartTime', hierarchy: 'H1', hierarchyLevel: 'StartTimeDay', values: [dateNumber]},28 {dimension: 'StartTime', hierarchy: 'H1', hierarchyLevel: 'StartTimeMinute', values: [minutes]}29 ];30 let query = IrisUtils.buildQuery('ASPMINING.ANALYTICS.ProductionEventsCube', null, rows, null, filters);31 return IrisUtils.executeQuery(query)32 .then(response => {33 if (!response.rows.length) {34 return null;35 }36 const [truck, excavator, capacity, measuredTons, location, grade] = response.rows;37 return {38 truck: truck.caption,39 excavator: excavator.caption,40 capacity: response.data[2],41 measuredTons: response.data[3],42 location: location.caption,43 grade: grade.caption44 };45 });46 }47 function getLoadAndDumpEvents(truckName, date) {48 const dateNumber = IrisUtils.getDateNumber(date);49 const cols = [{50 path: '[Measures].[MeasuredTons]',51 children: [{52 dimension: 'ProductionEvent',53 hierarchy: 'H1',54 hierarchyLevel: 'ProductionStatusType',55 members: '&[Dumping]'56 }, {57 dimension: 'ProductionEvent',58 hierarchy: 'H1',59 hierarchyLevel: 'ProductionStatusType',60 members: '&[Loading]'61 }]62 }];63 const rows = [{64 dimension: 'EventDateTime',65 hierarchy: 'H1',66 hierarchyLevel: 'EventDateTimeMinute',67 members: 'Members'68 }];69 const filters = [70 {dimension: 'Equipment', hierarchy: 'H1', hierarchyLevel: 'EquipmentName', values: [truckName]},71 {dimension: 'EventDateTime', hierarchy: 'H1', hierarchyLevel: 'EventDateTimeDay', values: [dateNumber]}72 ];73 let query = IrisUtils.buildQuery('ASPMINING.ANALYTICS.UNIFIEDEVENTSCUBE', cols, rows, null, filters);74 return IrisUtils.executeQuery(query)75 .then(data => {76 return IrisUtils.parseTreeDimensionalResponse(data);77 });78 }79 function getGanttData(trucks, date, shiftId, shiftType) {80 trucks = trucks.map(current => current.name);81 const truckFilter = trucks.map(current => `[EQUIPMENT].[H1].[NAME].&[${current}]`);82 const query = `SELECT NON EMPTY83 NONEMPTYCROSSJOIN({84 [ProductionStatus].[H1].[Description].&[TransitToLoadSite],85 [ProductionStatus].[H1].[Description].&[WaitingForLoad],86 [ProductionStatus].[H1].[Description].&[Loading],87 [ProductionStatus].[H1].[Description].&[TransitToDumpSite],88 [ProductionStatus].[H1].[Description].&[WaitingForDump],89 [ProductionStatus].[H1].[Description].&[Dumping]90 }, [Measures].[Duration]) ON 0,91 NON EMPTY HEAD(92 NONEMPTYCROSSJOIN(93 [StartTime].[H1].[StartTimeMinute].Members,94 NONEMPTYCROSSJOIN(95 [StartTime].[H1].[StartTimeDay].Members,96 [Equipment].[H1].[Name].Members97 )98 ),2000,SAMPLE99 ) ON 1 100 FROM [ASPMINING.ANALYTICS.PRODUCTIONEVENTSCUBE]101 %FILTER NONEMPTYCROSSJOIN(102 [Shift].[H1].[Id].&[${shiftId}],103 %OR({${truckFilter.join()}})104 )`;105 let shiftEnd = new Date(date.getTime());106 shiftEnd.setMinutes(0, 0, 0);107 if (shiftType === 'A') {108 shiftEnd.setHours(20);109 } else if (shiftType === 'B') {110 shiftEnd.setHours(8);111 shiftEnd.setDate(shiftEnd.getDate() + 1);112 }113 return IrisUtils.executeQuery(query)114 .then(response => {115 const result = {116 trucks: trucks,117 data: {}118 };119 const columns = response.columns;120 const rows = response.rows;121 const data = response.data;122 let rowIndex = 0;123 rows.forEach(row => {124 const minuteStr = row.caption;125 const children = row.children || [];126 children.forEach(child => {127 const dateStr = child.caption;128 const date = new Date(`${dateStr} ${minuteStr}:00`);129 const minute = date.getTime();130 child.children.forEach(truck => {131 const truckName = truck.caption;132 const truckIndex = trucks.findIndex(current => current === truckName);133 const accumulated = 0;134 columns.forEach((column, columnIndex) => {135 const event = column.caption;136 let value = data[rowIndex * columns.length + columnIndex];137 if (typeof value !== 'number') {138 return;139 }140 const start = minute + accumulated * 1000;141 let finish = start + value * 1000;142 if (finish > shiftEnd.getTime()) {143 finish = shiftEnd.getTime();144 }145 result.data[event] = result.data[event] || {146 name: event,147 data: [],148 dimensions: ['truckIndex', 'start', 'finish']149 };150 result.data[event].data.push([truckIndex, start, finish, value, truckName, date.toISOString()]);151 });152 rowIndex++;153 });154 });155 });156 for (let key in result.data) {157 result.data[key].data.sort((a, b) => a[5] > b[5] ? 1 : -1);158 }159 return result;160 })161 .catch(err => {162 return Promise.reject(err);163 });164 }165 }...
ShiftController.js
Source:ShiftController.js
1"use strict";2import { query } from "express-validator";3import models from "../db/models/index";4import status from "http-status";5import url from "url";6import db from "../db/models/index";7import { Op, Sequelize } from "sequelize";8const moment = require('moment-timezone');9import stream from 'stream';10import readXlsxFile from "read-excel-file/node";11const { Duplex } = stream;12function bufferToStream(buffer) {13 const duplexStream = new Duplex();14 duplexStream.push(buffer);15 duplexStream.push(null);16 return duplexStream;17}18export default {19 view: {20 async get(req, res, next) {21 try {22 const shiftTypes = await models.Shift.findAll({23 attributes: {24 exclude: ["createdAt", "updatedAt"],25 },26 });27 for (let i = 0; i < shiftTypes.length; i++) {28 var shiftStart = shiftTypes[i].getDataValue("shiftStart");29 var shiftEnd = shiftTypes[i].getDataValue("shiftEnd");30 shiftStart = new Date(31 "2020-02-02T" + shiftStart + ".000Z"32 ).toLocaleTimeString("en-US", {33 hour12: false,34 timeZone: "Asia/Ho_Chi_Minh",35 });36 shiftEnd = new Date(37 "2020-01-01T" + shiftEnd + ".000Z"38 ).toLocaleTimeString("en-US", {39 hour12: false,40 timeZone: "Asia/Ho_Chi_Minh",41 });42 shiftTypes[i].setDataValue("shiftStart", shiftStart);43 shiftTypes[i].setDataValue("shiftEnd", shiftEnd);44 }45 res.status(status.OK).send({46 success: true,47 message: shiftTypes,48 });49 } catch (error) {50 next(error);51 }52 },53 },54 create_bulk: {55 async post(req, res, next) {56 let shifts = []57 try {58 if (req.file == undefined) {59 return res.status(400).send("Please upload an excel file!");60 }61 const stream = bufferToStream(req.file.buffer);62 await readXlsxFile(stream).then(async (rows) => {63 // skip header64 rows.shift(); 65 for (let index = 0; index < rows.length; index++) {66 let row = rows[index] 67 shifts.push({name: row[1], 68 shiftStart: moment.tz("2020-02-02 " + String(row[2]).substring(0, 5), "Asia/Ho_Chi_Minh").utc().format("HH:mm:ss"), 69 shiftEnd: moment.tz("2020-02-02 " + String(row[3]).substring(0, 5), "Asia/Ho_Chi_Minh").utc().format("HH:mm:ss")70 })71 }72 })73 74 75 if(shifts.length > 0){76 const result = await models.Shift.bulkCreate(shifts)77 if(result){78 result.forEach(element => {79 element.setDataValue("createdAt", undefined)80 element.setDataValue("updatedAt", undefined)81 });82 res.status(status.CREATED).send({83 success: true,84 message: { shifts: result.length },85 });86 }87 } 88 } catch (error) {89 next(error);90 }91 },92 },93 update_bulk: {94 async put(req, res, next) {95 const shifts = req.body.shifts96 try {97 if(shifts.length > 0){98 for (let index = 0; index < shifts.length; index++) {99 shifts[index].shiftStart = moment.tz("2020-02-02 " + shifts[index].shiftStart.substring(0, 5), "Asia/Ho_Chi_Minh").utc().format("HH:mm:ss")100 shifts[index].shiftEnd = moment.tz("2020-02-02 " + shifts[index].shiftEnd.substring(0, 5), "Asia/Ho_Chi_Minh").utc().format("HH:mm:ss") 101 }102 const result = await models.Shift.bulkCreate(shifts, { updateOnDuplicate: ["name", "shiftStart", "shiftEnd", "updatedAt"] })103 if(result){104 result.forEach(element => {105 element.setDataValue("createdAt", undefined)106 element.setDataValue("updatedAt", undefined)107 });108 res.status(status.CREATED).send({109 success: true,110 message: { shifts: result.length },111 });112 }113 } 114 } catch (error) {115 next(error);116 }117 },118 },119 bulk_delete: {120 async delete(req, res, next) {121 const queryInterface = db.sequelize.getQueryInterface();122 const ids = req.body.ids123 try {124 let result = await queryInterface.bulkDelete('shift', {id: {[Op.in]: ids}})125 res.status(status.OK).send({126 success: true,127 message: result[0].affectedRows,128 });129 } catch (error) {130 console.log(`----------------${error}`)131 next(error);132 }133 },134 },...
index.js
Source:index.js
1#!/usr/bin/env node2'use strict';3const fs = require('fs');4const moment = require('moment');5const program = require('commander');6const { version } = require('../package.json');7const TIME_FORMAT = 'HH:mm:ss,SSS';8const TIME_SEPARATOR = ' --> ';9const NEGATIVE_PATCH = 'NegativeNumber';10let matchingCommand = false;11program12 .version(version)13 .option('-o --output <path>', 'Path to output shifted file.')14 .option('-b --backup', 'Create a ".bak" backup file.');15program16 .command('shift <path> <shift> [shiftEnd]')17 .description(18 'Shifts .srt subtitle files by milliseconds, providing a shift-end will perform a linear correction.'19 )20 .action((path, shiftStartArg, shiftEndArg = shiftStartArg) => {21 matchingCommand = true;22 const shiftStart = parseNumericArg(shiftStartArg);23 const shiftEnd = parseNumericArg(shiftEndArg);24 const subs = fs.readFileSync(path, 'utf-8');25 const shiftedSubs = shift(subs, shiftStart, shiftEnd);26 write(program, path, subs, shiftedSubs);27 });28program29 .command('sync <path> <startTime> <endTime>')30 .description(31 'Syncs the subtitles with a linear correction based on the start times of the first and last subtitle. Time format is HH:mm:ss,SSS.'32 )33 .action((path, startTimeArg, endTimeArg) => {34 matchingCommand = true;35 const startTime = parseTime(startTimeArg);36 const endTime = parseTime(endTimeArg);37 const subs = fs.readFileSync(path, 'utf-8');38 const shiftedSubs = sync(subs, startTime, endTime);39 write(program, path, subs, shiftedSubs);40 });41program.parse(patchNegatives(process.argv));42if (!matchingCommand) {43 program.help();44}45function sync(subs, startTime, endTime) {46 const [firstTime, lastTime] = getBoundingTimes(subs);47 const shiftStart = startTime.diff(firstTime);48 const shiftEnd = endTime.diff(lastTime);49 return shift(subs, shiftStart, shiftEnd);50}51function shift(subs, shiftStart, shiftEnd) {52 const [firstTime, lastTime] = getBoundingTimes(subs);53 const shiftFactor = (shiftEnd - shiftStart) / firstTime.diff(lastTime);54 return subs55 .split('\n')56 .map(57 line =>58 isTimeLine(line)59 ? shiftTimeLine(line, shiftFactor, shiftStart, firstTime)60 : line61 )62 .join('\n');63}64function shiftTimeLine(line, shiftFactor, shiftStart, firstTime) {65 return parseTimes(line)66 .map(time => {67 const shiftBy = calculateShift(time, firstTime, shiftStart, shiftFactor);68 return time.add(shiftBy, 'ms').format(TIME_FORMAT);69 })70 .join(TIME_SEPARATOR);71}72function calculateShift(time, firstTime, shiftStart, shiftFactor) {73 const elapsedSinceFirst = firstTime.diff(time);74 return shiftStart + elapsedSinceFirst * shiftFactor;75}76function getBoundingTimes(subs) {77 const lines = subs.split('\n');78 const timeLines = lines.filter(isTimeLine);79 if (timeLines.length === 0) {80 throw new Error('No valid subtitles found');81 }82 const [firstTime] = parseTimes(timeLines[0]);83 const [lastTime] = parseTimes(timeLines[timeLines.length - 1]);84 return [firstTime, lastTime];85}86function parseTimes(line) {87 return line.split(TIME_SEPARATOR).map(timeString => parseTime(timeString));88}89function parseTime(timeString) {90 return moment(timeString.trim(), TIME_FORMAT);91}92function isTimeLine(line) {93 return line.indexOf(TIME_SEPARATOR) > -1;94}95function write(program, path, originalSubs, shiftedSubs) {96 if (program.backup) {97 fs.writeFileSync(path + '.bak', originalSubs);98 }99 fs.writeFileSync(program.output || path, shiftedSubs);100}101function patchNegatives(args) {102 return args.map(103 arg => (isNumber(arg) ? arg.replace('-', NEGATIVE_PATCH) : arg)104 );105}106function isNumber(string) {107 return !isNaN(string) && isFinite(string);108}109function parseNumericArg(arg) {110 return Number(arg.replace(NEGATIVE_PATCH, '-'));...
Shift.js
Source:Shift.js
1const moment = require('moment-timezone');2const { split, merge, clone } = require('lodash');3const { getDateArr } = require('./Date');4const timezone = process.env.TIMEZONE;5const SHIFT = {6 day: { name: 'day', start: '06:15:00', end: '18:50:00' },7 night: { name: 'night', start: '18:50:00', end: '06:15:00' },8};9const defaultConfig = { date: moment(), toUTC: true };10function getShiftRange(shift, paramConfig = defaultConfig) {11 const config = merge(defaultConfig, paramConfig);12 let { date } = clone(config);13 let shiftStart;14 let shiftEnd;15 switch (shift) {16 case SHIFT.day.name: {17 const dateArr = getDateArr(date);18 const dayShiftStartArr = [...dateArr, ...split(SHIFT.day.start, ':')];19 shiftStart = moment.tz(dayShiftStartArr, timezone);20 const dayShiftEndArr = [...dateArr, ...split(SHIFT.day.end, ':')];21 shiftEnd = moment.tz(dayShiftEndArr, timezone);22 break;23 }24 case SHIFT.night.name: {25 const startDateArr = getDateArr(date);26 const endDate = date.add(1, 'd');27 const endDateArr = getDateArr(endDate);28 const nightShiftStartArr = [...startDateArr, ...split(SHIFT.night.start, ':')];29 shiftStart = moment.tz(nightShiftStartArr, timezone);30 const nightShiftEndArr = [...endDateArr, ...split(SHIFT.night.end, ':')];31 shiftEnd = moment.tz(nightShiftEndArr, timezone);32 break;33 }34 default:35 throw new Error(`Unknown shift: ${shift}`);36 }37 if (config.toUTC) {38 date = date.utc();39 shiftStart = shiftStart.utc();40 shiftEnd = shiftEnd.utc();41 }42 return {43 start: shiftStart.format(),44 end: shiftEnd.format(),45 };46}47function getCurrentShiftRangeName() {48 const currentTime = moment().tz(timezone);49 const dayShiftStart = moment.tz(SHIFT.day.start, 'HH:mm:ss', timezone);50 const dayShiftEnd = moment.tz(SHIFT.day.end, 'HH:mm:ss', timezone);51 if (currentTime.isBetween(dayShiftStart, dayShiftEnd)) {52 return SHIFT.day.name;53 }54 return SHIFT.night.name;55}56function getLastDayShiftRange(toUTC = true) {57 const currentTime = moment().tz(timezone);58 let shiftStart = moment.tz(SHIFT.day.start, 'HH:mm:ss', timezone);59 let shiftEnd = moment.tz(SHIFT.day.end, 'HH:mm:ss', timezone);60 if (!currentTime.isAfter(shiftEnd)) {61 // Last completed day shift is from yesterday62 shiftStart = shiftStart.subtract(1, 'd');63 shiftEnd = shiftEnd.subtract(1, 'd');64 }65 if (toUTC) {66 shiftStart = shiftStart.utc();67 shiftEnd = shiftEnd.utc();68 }69 return {70 start: shiftStart.format(),71 end: shiftEnd.format(),72 };73}74function getLastNightShiftRange(toUTC = true) {75 const currentTime = moment().tz(timezone);76 // Last completed day shift started at least a day ago77 let shiftStart = moment.tz(SHIFT.night.start, 'HH:mm:ss', timezone).subtract(1, 'd');78 let shiftEnd = moment.tz(SHIFT.night.end, 'HH:mm:ss', timezone);79 if (currentTime.isBefore(shiftEnd)) {80 // Between midnight and the shift end,81 // last completed night shift is from a day before82 shiftStart = shiftStart.subtract(1, 'd');83 shiftEnd = shiftEnd.subtract(1, 'd');84 }85 if (toUTC) {86 shiftStart = shiftStart.utc();87 shiftEnd = shiftEnd.utc();88 }89 return {90 start: shiftStart.format(),91 end: shiftEnd.format(),92 };93}94module.exports = {95 SHIFT,96 getShiftRange,97 getCurrentShiftRangeName,98 getLastDayShiftRange,99 getLastNightShiftRange,...
LogHours.js
Source:LogHours.js
1import React, { Component } from "react";2import {3 View,4 Text,5 Dimensions,6 StyleSheet,7 TouchableOpacity,8 ScrollView,9 StatusBar,10 Image,11 TextInput12} from "react-native";13const { height, width } = Dimensions.get("window");14import ShiftCard from "./ShiftCard.js";15const data = [16 {17 date: 16,18 day: "MON",19 shiftDetails: [20 {21 clinic: "Parashant Dental clinic",22 shiftStart: "10:30",23 shiftEnd: "12:30"24 },25 {26 clinic: "Unknown Dental clinic",27 shiftStart: "10:30",28 shiftEnd: "12:30"29 },30 {31 clinic: "Good Dental clinic",32 shiftStart: "10:30",33 shiftEnd: "12:30"34 }35 ]36 },37 {38 date: 16,39 day: "MON",40 shiftDetails: [41 {42 clinic: "Best Dental clinic",43 shiftStart: "10:30",44 shiftEnd: "12:30"45 },46 {47 clinic: "Chai clinic",48 shiftStart: "10:30",49 shiftEnd: "12:30"50 }51 ]52 },53 {54 date: 16,55 day: "MON",56 shiftDetails: [57 {58 clinic: "Romil clinic",59 shiftStart: "10:30",60 shiftEnd: "12:30"61 },62 {63 clinic: "somit clinic",64 shiftStart: "10:30",65 shiftEnd: "12:30"66 }67 ]68 },69 {70 date: 16,71 day: "MON",72 shiftDetails: [73 {74 clinic: "Parashant Dental clinic",75 shiftStart: "10:30",76 shiftEnd: "12:30"77 },78 {79 clinic: "Parashant Dental clinic",80 shiftStart: "10:30",81 shiftEnd: "12:30"82 }83 ]84 },85 {86 date: 16,87 day: "MON",88 shiftDetails: [89 {90 clinic: "Parashant Dental clinic",91 shiftStart: "10:30",92 shiftEnd: "12:30"93 }94 ]95 }96];97export default class LogHours extends Component {98 constructor(props) {99 super(props);100 this.state = {};101 }102 componentWillMount = () => {};103 render() {104 let {logHoursData} = this.props;105 console.log('logggggghourData',logHoursData)106 return (107 <ScrollView style={{ flex: 1, backgroundColor: "#FFFFFF" }}>108 {logHoursData.map((item, index) => {109 console.log('datadatdatda',item,index)110 return (111 <View112 style={{113 // height: height * 0.1,114 paddingHorizontal: height * 0.025,115 // marginHorizontal: height * 0.01,116 backgroundColor: "#FFFFFF"117 }}118 >119 <ShiftCard item={item} index={index} />120 </View>121 );122 })}123 </ScrollView>124 );125 }126}127const styles = StyleSheet.create({128 center: {129 justifyContent: "center",130 alignItems: "center"131 }...
shiftSeed.js
Source:shiftSeed.js
1'use strict'2import { setEpochMillisTime } from '../../utils/timeUtil';3export default [4 {5 name: 'Shift 1',6 shiftStart: setEpochMillisTime(0, 17, 0, 0, 0),7 shiftEnd: setEpochMillisTime(0, 21, 0, 0, 0)8 },9 {10 name: 'Shift 2',11 shiftStart: setEpochMillisTime(0, 21, 0, 0, 0),12 shiftEnd: setEpochMillisTime(0, 1, 0, 0, 0)13 },14 {15 name: 'Shift 3',16 shiftStart: setEpochMillisTime(0, 1, 0, 0, 0),17 shiftEnd: setEpochMillisTime(0, 5, 0, 0, 0)18 },19 {20 name: 'Shift 4',21 shiftStart: setEpochMillisTime(0, 5, 0, 0, 0),22 shiftEnd: setEpochMillisTime(0, 9, 0, 0, 0)23 },24 {25 name: 'Shift 5',26 shiftStart: setEpochMillisTime(0, 9, 0, 0, 0),27 shiftEnd: setEpochMillisTime(0, 13, 0, 0, 0)28 },29 {30 name: 'Shift 6',31 shiftStart: setEpochMillisTime(0, 13, 0, 0, 0),32 shiftEnd: setEpochMillisTime(0, 17, 0, 0, 0)33 },...
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'Peter')4 .click('#submit-button')5 .expect(Selector('#article-header').innerText).eql('Thank you, Peter!');6});7test('My second test', async t => {8 .click('#tried-test-cafe')9 .expect(Selector('#tried-test-cafe').checked).ok()10 .click('#tried-test-cafe')11 .expect(Selector('#tried-test-cafe').checked).notOk();12});13import { Selector } from 'testcafe';14test('My first test', async t => {15 .typeText('#developer-name', 'Peter')16 .click('#submit-button')17 .expect(Selector('#article-header').innerText).eql('Thank you, Peter!');18});19test('My second test', async t => {20 .click('#tried-test-cafe')21 .expect(Selector('#tried-test-cafe').checked).ok()22 .click('#tried-test-cafe')23 .expect(Selector('#tried-test-cafe').checked).notOk();24});25import { Selector } from 'testcafe';26test('My first test', async t => {27 .typeText('#developer-name', 'Peter')28 .click('#submit-button')29 .expect(Selector('#article-header').innerText).eql('Thank you, Peter!');30});31test('My second test', async t => {32 .click('#tried-test-cafe')33 .expect(Selector('#tried-test-cafe').checked).ok()34 .click('#tried-test-cafe')35 .expect(Selector('#tried-test-cafe').checked).notOk();36});
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#submit-button');5});6test('My second test', async t => {7 .click('#tried-test-cafe')8 .expect(Selector('#tried-test-cafe').checked).ok();9});10import { Selector } from 'testcafe';11test('My first test', async t => {12 .typeText('#developer-name', 'John Smith')13 .click('#submit-button');14});15test('My second test', async t => {16 .click('#tried-test-cafe')17 .expect(Selector('#tried-test-cafe').checked).ok();18});19import { Selector } from 'testcafe';20test('My first test', async t => {21 .typeText('#developer-name', 'John Smith')22 .click('#submit-button');23});24test('My second test', async t => {25 .click('#tried-test-cafe')26 .expect(Selector('#tried-test-cafe').checked).ok();27});28import { Selector } from 'testcafe';29test('My first test', async t => {30 .typeText('#developer-name', 'John Smith')31 .click('#submit-button');32});33test('My second test', async t => {34 .click('#tried-test-cafe')35 .expect(Selector('#tried-test-cafe').checked).ok();36});37import {
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My Test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#tried-test-cafe')5 .click('#submit-button')6 .wait(5000)7 .click('#tried-test-cafe')8 .click('#submit-button')9 .wait(5000)10 .click('#tried-test-cafe')11 .click('#submit-button')12 .wait(5000)13 .click('#tried-test-cafe')14 .click('#submit-button')15 .wait(5000)16 .click('#tried-test-cafe')17 .click('#submit-button')18 .wait(5000)19 .click('#tried-test-cafe')20 .click('#submit-button')21 .wait(5000)22 .click('#tried-test-cafe')23 .click('#submit-button')24 .wait(5000)25 .click('#tried-test-cafe')26 .click('#submit-button')27 .wait(5000)28 .click('#tried-test-cafe')29 .click('#submit-button')30 .wait(5000)31 .click('#tried-test-cafe')32 .click('#submit-button')33 .wait(5000)34 .click('#tried-test-cafe')35 .click('#submit-button')36 .wait(5000)37 .click('#tried-test-cafe')38 .click('#submit-button');39});
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#macos')5 .click('#submit-button');6});7test('My test', async t => {8 .typeText('#developer-name', 'John Smith')9 .click('#macos')10 .click('#submit-button')11 .selectText('#developer-name')12 .pressKey('delete');13});14test('My test', async t => {15 const developerName = Selector('#developer-name');16 .typeText(developerName, 'John Smith')17 .click('#macos')18 .click('#submit-button')19 .expect(developerName.value).eql('John Smith');20});21test('My test', async t => {22 const developerName = Selector('#developer-name');23 .expect(developerName.exists).ok()24 .expect(developerName.visible).ok();25});26test('My test', async t => {27 const developerName = Selector('#developer-name');28 .expect(developerName.value).eql('')29 .typeText(developerName, 'Peter Parker')30 .expect(developerName.value).eql('Peter Parker');31});32test('My test', async t => {33 const articleHeader = Selector('.result-content').find('h1');34 .expect(articleHeader.innerText).eql('Thank you, John Smith!');35});36test('My test', async t => {37 const headerText = Selector('.result-content').find('h1').innerText;38 .expect(headerText).eql('Thank you, John Smith!');39});40test('My test', async t => {41 const articleHeader = Selector('.result-content').find('h1');42 .expect(articleHeader.count).eql(1)43 .expect(articleHeader.visible).ok();44});45test('My test', async t => {46 const checkBox = Selector('input[type=checkbox]');47 .expect(checkBox.checked).notOk()48 .click(checkBox)49 .expect(checkBox.checked).ok();50});
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3 const developerName = Selector('#developer-name');4 .typeText(developerName, 'Peter')5 .click('#submit-button')6 .expect(Selector('#article-header').innerText).eql('Thank you, Peter!');7});8test('My second test', async t => {9 const developerName = Selector('#developer-name');10 .typeText(developerName, 'Peter', { caretPos: 5 })11 .click('#submit-button')12 .expect(Selector('#article-header').innerText).eql('Thank you, Peter!');13});14test('My third test', async t => {15 const developerName = Selector('#developer-name');16 .typeText(developerName, 'Peter', { replace: true })17 .click('#submit-button')18 .expect(Selector('#article-header').innerText).eql('Thank you, Peter!');19});20test('My fourth test', async t => {21 const developerName = Selector('#developer-name');22 .typeText(developerName, 'Peter', { replace: true, paste: true })23 .click('#submit-button')24 .expect(Selector('#article-header').innerText).eql('Thank you, Peter!');25});26test('My fifth test', async t => {27 const developerName = Selector('#developer-name');28 .typeText(developerName, 'Peter', { replace: true, paste: true, caretPos: 5 })29 .click('#submit-button')30 .expect(Selector('#article-header').innerText).eql('Thank you, Peter!');31});32test('My sixth test', async t => {33 const developerName = Selector('#developer-name');34 .typeText(developerName, 'Peter', { replace: true, paste: true, caretPos: 5, timeout: 1000 })35 .click('#submit
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My Test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#submit-button')5 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');6});
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#macos')5 .click('#submit-button');6 const articleHeader = await Selector('.result-content').find('h1');7 let headerText = await articleHeader.innerText;8 let id = await articleHeader.id;9 let headerNode = await articleHeader();10 let headerTextJquery = await $(headerNode).text();11});
Using AI Code Generation
1function shiftEnd(selector, count) {2 return selector.addCustomMethods({3 shiftEnd: function (node, count) {4 var value = node.value;5 var end = value.length;6 var start = end - count;7 node.setSelectionRange(start, end);8 }9 });10}11function shiftStart(selector, count) {12 return selector.addCustomMethods({13 shiftStart: function (node, count) {14 var value = node.value;15 var start = 0;16 var end = start + count;17 node.setSelectionRange(start, end);18 }19 });20}21function shiftHome(selector) {22 return selector.addCustomMethods({23 shiftHome: function (node) {24 var value = node.value;25 var start = 0;26 var end = value.length;27 node.setSelectionRange(start, end);28 }29 });30}31function shiftEnd(selector) {32 return selector.addCustomMethods({33 shiftEnd: function (node) {34 var value = node.value;35 var end = value.length;36 var start = 0;37 node.setSelectionRange(start, end);38 }39 });40}41function shiftEnd(selector, count) {42 return selector.addCustomMethods({43 shiftEnd: function (node, count) {44 var value = node.value;45 var end = value.length;46 var start = end - count;47 node.setSelectionRange(start, end);48 }49 });50}51function shiftStart(selector, count) {52 return selector.addCustomMethods({53 shiftStart: function (node, count) {54 var value = node.value;55 var start = 0;56 var end = start + count;57 node.setSelectionRange(start, end);58 }59 });60}61function shiftHome(selector) {62 return selector.addCustomMethods({63 shiftHome: function (node
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!!