How to use percentageDiff method in Cypress

Best JavaScript code snippet using cypress

dashboard.js

Source:dashboard.js Github

copy

Full Screen

1var globalreleaseName = 'BRMAR18'; 2var globalreleaseLocation = '../enterpriseServices/BRMAR18/';3var globalReturnCallsCount = 0;4var servicesDashboardReleaseObject = null;5var globalcapmDataList = [];6var delay = ( function() {7 var timer = 0;8 return function(callback, ms) {9 clearTimeout (timer);10 timer = setTimeout(callback, ms);11 };12})();13function capmChecker(){14 var allProvidersURL = 'http://compass-prod-web:8080/CompassWeb/GetObjects?id=-1&action=doAttributes&type=JSONP&env=e9&domain=Production&reportname=provider.sql&end=now&start=-4w';15 console.log('checking');16 $("#red-light").hide();17 $("#yellow-light").show();18 $("#green-light").hide();19 delay(function(){20 $("#red-light").hide();21 $("#yellow-light").show();22 $("#green-light").hide();23 $.ajax({24 'url': allProvidersURL,25 'type': 'GET',26 'dataType': 'jsonp',27 'jsonp': 'callback',28 'cache':false,29 'timeout':10000,30 'success': function (data){31 console.log(data);32 if((data.rows!=null)&&(data.rows.length==0)){33 $("#yellow-light").hide();34 $("#red-light").show();35 //$('div#servicePerformanceData').html('<h2>Red</h2>');36 $("#green-light").hide();37 //console.log('red');38 delay(function(){39 capmChecker();40 }, 5000 ); // end delay41 //console.log('capmDown');42 43 }else{44 $("#red-light").hide();45 $("#yellow-light").hide();46 $("#green-light").show();47 //console.log('green');48 } 49 },50 'error': function (xhr,status,error){51 $("#red-light").show();52 $("#yellow-light").hide();53 $("#green-light").hide();54 delay(function(){55 capmChecker();56 }, 5000 );57 }58 });59 }, 500 );60 61}62function buildServiceDashboardPage(){63 //not sure?64 65 //replicate the otherstuff66 var cacheBuster = getCacheBuster();67 var jsonLinkRel = 'data/releases.json?' + cacheBuster;68 $.ajax({69 'url': jsonLinkRel,70 'type': 'GET',71 'dataType': 'json',72 'success': function (releaseData) {73 //now verify this data is what I expect or throw the releaseList error74 if ((releaseData !== null) &&(releaseData !== 'undefined') &&(releaseData.releases !== null) && ($.isArray(releaseData.releases))) {75 //now make sure each release has a name and location76 var releaseArray = returnArray(releaseData.releases);77 forceSortArray(releaseArray, 'order', false, function (releaseIndex, releaseObject) {78 //just get the selected one for now?79 if(releaseObject.selected==true){80 globalSelectedRelease = releaseObject;81 getAllCAPMServicesJSONData(false);82 return false;83 }84 });85 }86 },87 'error': function (XMLHttpRequest, textStatus, errorThrown) {88 console.log(textStatus, errorThrown, jsonLinkRel);89 }90 }); 91 92}93function processDashboard(servicesObj, buildInfo){94 var allProvidersURL = 'http://compass-prod-web:8080/CompassWeb/GetObjects?id=-1&action=doAttributes&type=JSONP&env=e9&domain=Production&reportname=provider.sql&end=now&start=-4w';95 //now I go and get all the CAPM services I can find...96 $.ajax({97 'url': allProvidersURL,98 'type': 'GET',99 'dataType': 'jsonp',100 jsonp: 'callback',101 'success': function (capmProviders) {102 //now verify this data is what I expect or throw the releaseList error103 if ((capmProviders !== null) &&(capmProviders.rows!==null) &&(capmProviders.rows.length>0)) {104 var capmProviderList = capmProviders.rows;105 //console.log(capmProviderList);106 //now pass to this next function a list of both services and capmstuff107 var capmList = mergeCAPMDatawithServices(capmProviderList,servicesObj);108 //set the global109 globalcapmDataList = capmList;110 mainLoop(false);111 }112 },113 'error': function (XMLHttpRequest, textStatus, errorThrown) {114 console.log(textStatus, errorThrown, jsonLinkRel);115 }116 }); 117}118function mergeCAPMDatawithServices(capmList, servicesList){119 //simply loop and find stuff that matches?120 var urlStart = 'http://compass-prod-web:8080/CompassWeb/GetObjects?action=doAttributes&next=4&env=e9&domain=Production&other=PLACEHOLDER&';121 var urlEnd = '&type=JSONP&callback=?&start=-1h&end=now&graph_sampletime=on&graph_avg_elapsed_nr=on&graph_avg_elapsed_hits_nr=on';122 var newCAPMList = [];123 for(var i = 0;i<capmList.length;i++){124 var capmObject = capmList[i];125 //console.log(capmObject);126 //must have rootelement and namepsace127 128 if((capmObject.rootelement!=null)&&(capmObject.namespace!=null)){129 capmObject.id = id = 'id=EnterpriseServices-%3E' + capmObject.namespace + '-%3E' + capmObject.rootelement + '-%3Edp:ServiceCompleted'; 130 capmObject.url = urlStart + capmObject.id + urlEnd;131 //now I can see if I find the service that goes with this one?132 for(var k = 0;k<servicesList.length;k++){133 var serviceObj = servicesList[k];134 if(capmObject.namespace==serviceObj.shortNamespace){135 //now check of the name matches either of the schemas schemanames136 for(var m = 0;m<serviceObj.schemaList.length;m++){137 var schemaObj = serviceObj.schemaList[m];138 if(schemaObj.schemaName==capmObject.rootelement){139 capmObject.service = serviceObj;140 break; 141 }142 }143 }144 if(capmObject.service!=null){145 break;146 }147 }148 newCAPMList.push(capmObject); 149 }150 }151 return newCAPMList;152}153function getAllCAPMServicesJSONData(repeatFlag){154 console.time('getAllCAPMServicesJSONData');155 getSchemasJSONData('enterprise', 'processDashboard');156}157function mainLoop(repeatFlag){158 //console.log(globalcapmDataList);159 //make each of the calls in an ajax and paint it up?160 console.time('mainLoop');161 //$("div#badServices").append(htmlTableMsg);162 //$("div#goodServices").append(htmlTableMsg);163 uiid = 'servicePerformanceData';164 //console.log(divhtml);165 if(repeatFlag!=true){166 var htmlTableMsg = buildCAPMServiceListTH();167 var divhtml = buildAccordionDivWithSearch(uiid,htmlTableMsg);168 $('div#' + uiid).html(divhtml);169 $('tbody#' + uiid+'TableBody').empty();170 }171 172 if((globalcapmDataList!=null)&&(globalcapmDataList.length>0)){173 var totalCalls = globalcapmDataList.length;174 //console.log(totalCalls);175 176 $('#'+'servicePerformanceData'+'SearchLabel').text(' Waiting for CAPM for ' + totalCalls + ' to be made');177 $.each(globalcapmDataList, function(i,capmData){178 var callNumber = i+1;179 180 var cacheBuster = getCacheBuster();181 var invocationTimeStamp = Date.now();182 var addurl = capmData.url + '&cacheBuster=' + cacheBuster; 183 //console.log(capmData.id);184 $.ajax({185 'url': addurl,186 'type': 'GET',187 'dataType': 'jsonp',188 'jason': capmData.id,189 'jsonp': 'callback',190 'success': function (data){191 displaySingleService(data, capmData, callNumber, totalCalls, invocationTimeStamp); 192 }193 });194 });195 }196}197function displaySingleService(argument, capmObject, callNumber, totalCalls, invocationTimeStamp){198 globalReturnCallsCount = globalReturnCallsCount + 1;199 //can I detect that this is the very last call?200 //console.log('testStuffSingle');201 202 $('#'+'servicePerformanceData'+'SearchLabel').text(' ' + globalReturnCallsCount + ' of ' + totalCalls + ' calls made and number ' + callNumber + ' in the list.');203 204 //console.log(capmObject);205 //does the service exist?206 if((capmObject!=null)&&(argument!=null)&&(argument.rows!=null)&&(argument.rows.length>1)){207 //I have something to do208 209 var rootelement = capmObject.rootelement;210 211 var namespace = capmObject.namespace;212 var svNumber = 'Undocumented';213 var provider = capmObject.provider;214 var uniqueID = replaceAll(replaceAll(replaceAll(replaceAll(namespace + rootelement + provider,'/','-'),':','-').split('.').join('-'), '_', '-'), '--', '-');215 if((capmObject.service!=null)&&(capmObject.service.ServiceNumber!=null)){216 svNumber = capmObject.service.ServiceNumber;217 }218 219 //I have rows of data but not sure whats on here?220 var attr = argument.attributes;221 var firstRow = argument.rows[0];222 var secondRow = argument.rows[1];223 //console.log(firstRow);224 //just get the first row of data for now?225 //console.log(argument);226 if((firstRow.avg_elapsed_nr!=null)&&(firstRow.avg_elapsed_nr!=null)){227 var elapsed = firstRow.avg_elapsed_nr;228 var prevElapsed = secondRow.avg_elapsed_nr;229 var diff = elapsed - prevElapsed;230 var trend = '-';231 var trendclass = 'steady';232 var percentageDiff = Math.round(diff/elapsed * 100);233 /*234 console.log('uniqueID:' + uniqueID);235 console.log('percentageDiff:' + percentageDiff);236 console.log('elapsed:' + elapsed);237 console.log('prevElapsed:' + prevElapsed);238 */ 239 240 if(percentageDiff>50 && percentageDiff<400){241 trendclass = 'upSingle';242 }else if(percentageDiff>400){243 trendclass = 'upDouble';244 }else if(percentageDiff>0 && percentageDiff<50){245 trendclass = 'up45';246 }else if(percentageDiff<0 && percentageDiff>-50){247 trendclass = 'down45';248 }else if(percentageDiff<-50 && percentageDiff>-400){249 trendclass = 'downSingle';250 }else if(percentageDiff<-400){251 trendclass = 'downDouble';252 }253 //console.log('trendclass:' + trendclass);254 var sampleTimeRaw = firstRow.sampletime;255 var sampleTimeDate = new Date(+sampleTimeRaw);256 var sampleTime = getFormattedTime(sampleTimeDate);257 //console.log(sampleTimeRaw);258 //console.log(sampleTimeDate);259 //console.log(invocationTimeStamp);260 var nowTimeStamp = Date.now();261 //var timeDiff = invocationTimeStamp-sampleTimeRaw;262 var timeDiff = nowTimeStamp-sampleTimeRaw;263 //console.log(timeDiff);264 var timeDiffSecs = Math.round(timeDiff/1000);265 //console.log('timeDiffSecs:' + timeDiffSecs);266 var status = 'unknown';267 //if it is an async event I really need to lower these ratings....268 if((capmObject.service!=null)&&(capmObject.service.MessagePattern.Name=="PublishSubscribe")){269 if(elapsed>1000){270 status = 'CATASTROPHIC';271 }else if(elapsed>500){272 status = 'POOR';273 }else if(elapsed>200){274 status = 'FAIR';275 }else if(elapsed>100){276 status = 'GOOD';277 }else if(elapsed>50){278 status = 'VERY-GOOD';279 }else if(elapsed>0){280 status = 'EXCELLENT';281 }282 }else{283 if(elapsed>15000){284 status = 'CATASTROPHIC';285 }else if(elapsed>5000){286 status = 'POOR';287 }else if(elapsed>1000){288 status = 'FAIR';289 }else if(elapsed>500){290 status = 'GOOD';291 }else if(elapsed>100){292 status = 'VERY-GOOD';293 }else if(elapsed>0){294 status = 'EXCELLENT';295 } 296 }297 298 var hits = firstRow.avg_elapsed_hits_nr;299 //display it?300 elapsed = Math.round(elapsed);301 sortid = elapsed; 302 var htmlMsg = '';303 htmlMsg+='<tr id="' + uniqueID + '" class="' + status + '" order="' + sortid +'">';304 305 htmlMsg+='<td>';306 htmlMsg+=fancyTimeFormat(timeDiffSecs);307 htmlMsg+='</td>';308 htmlMsg+='<td>';309 htmlMsg+=svNumber;310 htmlMsg+='</td>';311 htmlMsg+='<td>';312 htmlMsg+=rootelement;313 htmlMsg+='</td>';314 htmlMsg+='<td>';315 htmlMsg+=namespace;316 htmlMsg+='</td>';317 htmlMsg+='<td>';318 htmlMsg+=provider;319 htmlMsg+='</td>';320 htmlMsg+='<td class="' + trendclass + '">';321 //htmlMsg+=numberWithCommas(elapsed) + ' ms ' + trend;322 htmlMsg+=numberWithCommas(elapsed) + ' ms';323 htmlMsg+='</td>';324 htmlMsg+='<td>';325 htmlMsg+=hits;326 htmlMsg+='</td>';327 htmlMsg+='<td class="' + status.toLowerCase() + '">';328 htmlMsg+=status;329 htmlMsg+='</td>';330 htmlMsg+='</tr>';331 var uiid = 'servicePerformanceData';332 //$('tbody#' + uiid +'TableBody').append(htmlMsg);333 //if this already exists then delete it?334 var existingRow = $('#' + uniqueID);335 $('#' + uniqueID).remove();336 //console.log(existingRow.length);337 338 trRows = $('tbody#' + uiid +'TableBody tr').length;339 //console.log('trRows:' + trRows); 340 if(trRows==0){341 $('tbody#' + uiid +'TableBody').append(htmlMsg);342 }else{343 var inserted = false;344 $('tbody#' + uiid +'TableBody tr').each(function(index, Element) {345 //console.log('Is ' + sortid + ' greater than ' + $(Element).attr('order')); 346 if (Number(sortid) > Number($(Element).attr('order'))) {347 //console.log('Yes its greater so append');348 $(Element).before(htmlMsg);349 inserted = true;350 return false351 }352 });353 if(inserted!=true){354 //console.log('inserted isnt true so just add this entry to the end of the table');355 $('tbody#' + uiid +'TableBody').append(htmlMsg);356 }357 }358 var qs = buildStandardSearch(uiid+'Search', uiid+'Table', uiid+'noresults', uiid+'SearchLabel');359 }360 }361 //console.log('globalReturnCallsCount:' + globalReturnCallsCount);362 //console.log('totalCalls:' + totalCalls);363 if(globalReturnCallsCount>=totalCalls){364 globalReturnCallsCount = 0;365 console.log('this is the very last call so repeat everything?');366 $('#'+'servicePerformanceData'+'SearchLabel').text(' All ' + totalCalls + ' calls made.');367 //a=diehereosidontrepeatfornow;368 delay(function(){369 370 mainLoop(true);371 }, 30000 ); // end delay372 373 } 374}375function testStuff(arguments){376 console.log('testStuff');377 //console.log(arguments);378 console.log(arguments[0][0]);379 //console.log(arguments[0][0].rows);380 $.each(arguments, function(i, argument){381 //console.log(argument[0].rows);382 383 if((argument[0].rows!=null)&&(argument[0].rows.length>0)){384 //I have rows of data but not sure whats on here?385 var attr = argument[0].attributes;386 var capmObject = JSON.parse(attr.name);387 var firstRow = argument[0].rows[0];388 console.log(firstRow);389 //just get the first row of data for now?390 if((firstRow.avg_elapsed_nr!=null)&&(firstRow.avg_elapsed_nr!=null)){391 var elapsed = firstRow.avg_elapsed_nr;392 var hits = firstRow.avg_elapsed_hits_nr;393 //display it?394 var htmlMsg = '';395 htmlMsg+='capmObjectRoot=' + capmObject.rootelement;396 htmlMsg+=', elapsed=' + elapsed + 'ms';397 htmlMsg+=', hits=' + hits;398 htmlMsg+='<br>';399 $("div#container").append(htmlMsg);400 }401 402 403 //console.log(argument[0].rows);404 }405 });406}407function mergeServicesData2CAPMServicesData(servicesList,capmList){408 console.time('mergeServicesData2CAPMServicesData');409 //console.log('servicesList');410 //console.log(servicesList);411 //console.log('capmList');412 //console.log(capmList);413 //"provider":"DHUB", "rootelement":"SearchPartyRequest", "namespace":"Party/Service/V7.0"}414 415 $.each(capmList,function (index,capmService){416 var rootelement = capmService.rootelement;417 var namespace = capmService.namespace;418 var provider = capmService.provider;419 //console.log('capmService:' + namespace + '/' + rootelement);420 $.each(servicesList,function (index,serviceObject){421 var name = cleanMacroName(serviceObject.name);422 var number = undefinedToEmpty(serviceObject.number).toUpperCase();423 var version = undefinedToEmpty(serviceObject.version).toUpperCase();424 //console.log(name);425 var mockRoot1 = name + 'Request';426 var mockRoot2 = name + 'Response';427 var mockRoot3 = name;428 //console.log('mock_rootelement:' + mockRoot1);429 var location = serviceObject.location;430 var splitlocation = location.split('/');431 if(splitlocation.length==5){432 //core?433 var mocknamespace = splitlocation[0] + '/' + splitlocation[1].replace('Services','Service') + '/' + splitlocation[2]; 434 }else if(splitlocation.length==6){435 //normal?436 //console.log('splitlocation:' + splitlocation);437 var mocknamespace = splitlocation[0] + '/' + splitlocation[1].replace('Services','Service') + '/' + splitlocation[3];438 439 }else{440 //console.log('splitlocation:' + splitlocation);441 //a=b;442 var mocknamespace = null;443 }444 445 if((rootelement==mockRoot3)||(rootelement==mockRoot2)||(rootelement==mockRoot1)){446 //now check version is a match?447 var capmNameSpaceArray = namespace.split('/');448 var capmVersion = capmNameSpaceArray[capmNameSpaceArray.length-1];449 if(version==capmVersion){450 //console.log('This is a match with CAPM on the Service Object' + index);451 capmService.serviceObject = serviceObject;452 }453 }454 });455 //now add the capmServiceObject back in to a new list456 457 });458 459 //console.log(capmList);460 console.timeEnd('mergeServicesData2CAPMServicesData');461 return capmList;462}463function buildAllCAPMServicesListAccordion(allProvidersData,allServicesData){464 console.time('buildAllCAPMServicesListAccordion');465 var id = 'capmServiceList';466 var headerID = id + 'Header';467 var contentID = id + 'Content';468 if((allServicesData!=null)&&(allServicesData.macroLocations!=null)&&(allServicesData.macroLocations.category!=null)&&(allProvidersData!=null)&&(allProvidersData.attributes!=null)&&(allProvidersData.rows!=null)){469 var servicesList = returnArray(flattenMacroList(allServicesData.macroLocations.category).macroList);470 console.log('servicesList');471 console.log(servicesList);472 var providersList = returnArray(allProvidersData.rows);473 console.log('providersList');474 console.log(providersList);475 //so loop though the service list and the provider list and match and add476 var mergedServicesCAPMList = mergeServicesData2CAPMServicesData(servicesList,providersList);477 console.log('mergedServicesCAPMList');478 console.log(mergedServicesCAPMList);479 console.log(mergedServicesCAPMList[0]);480 var thHTML = buildCAPMServiceListTH();481 var divhtml = buildAccordionDivWithSearch(id,thHTML);482 //$('#' + headerID).text('CAPM Service List');483 $('#' + 'container').html(divhtml);484 var htmlBody = '';485 //now loop486 var macroListObjCount = 0;487 forceSortArray(mergedServicesCAPMList, 'location', false, function(i, capmObj) {488 console.log(capmObj);489 var macroObj = capmObj.serviceObject;490 if((macroObj!=null)&&(macroObj.number!='Core')&&(macroObj.number!='Msg')){491 var svNumber = undefinedToEmpty(macroObj.number);492 var svCategory = undefinedToEmpty(macroObj.category);493 var svVersion = undefinedToEmpty(macroObj.version);494 }495 else{496 var svNumber = '?';497 var svCategory = '?';498 var svVersion = '?';499 };500 var status = 'Unknown';501 var providerMsg = '';502 if(changedInCurrentRelease(macroObj)==true){503 //now I want to check the change summary...504 status = 'Changed this Release';505 }else{506 status = 'unChanged';507 }508 htmlBody += '<tr><td>' + svNumber + '</td><td>' + capmObj.rootelement + '</td><td>' + svCategory + '</td><td>' + svVersion + '</td><td>' + status + '</td><td>' + providerMsg + '</td></tr>';509 });510 $('tbody#' + id+'TableBody').empty();511 $('tbody#' + id+'TableBody').append(htmlBody);512 var qs = buildStandardSearch(id+'Search', id+'Table', id+'noresults', id+'SearchLabel');513 //I actually want to update the Macro Header?514 //appendAccordionHeader(headerID, macroListObjCount + ' Service Schemas');515 }else{516 //console.log(allProvidersData);517 if((allProvidersData.status!=null)&&(allProvidersData.status!=null)){518 var status = allProvidersData.status;519 var statusText = allProvidersData.statusText;520 }else{521 var status = 'unknown';522 var statusText = 'unknown';523 }524 $('#' + contentID).html('No status found.' + ' Error : ' + statusText + ' - Code : ' + status);525 appendAccordionHeader(headerID, 'No Status found');526 527 }528 $("#serviceArchitectureAccordion" ).accordion( "refresh" );529 console.timeEnd('buildAllCAPMServicesListAccordion');...

Full Screen

Full Screen

analysis.js

Source:analysis.js Github

copy

Full Screen

1const {CONSTANTS} = require("../../libs/constants");2const tags = CONSTANTS.TAGS;3class Analysis {4 constructor(price) {5 this.tags = [];6 this.name = price.name;7 this.symbol = price.symbol;8 this.price = price.price;9 this.identifier = price.identifier;10 this.priceChangeLastHour = this.calc(price, 'percentChangeLastHour');11 this.priceChangeLastDay = this.calc(price, 'percentChangeLastDay');12 this.priceChangeLastWeek = this.calc(price, 'percentChangeLastWeek');13 this.priceChangeLastMonth = this.calc(price, 'percentChangeLastMonth');14 this.priceChangeLast60Days = this.calc(price, 'percentChangeLast60Days');15 this.priceChangeLast90Days = this.calc(price, 'percentChangeLast90Days');16 this.isDecline = this.getIsDecline();17 this.median = this.getMedian();18 this.stabilityRating = this.checkPriceStability();19 this.createdAt = new Date();20 }21 calc(price, prop) {22 return price.price * (price[prop] < 0 ? Math.abs((100 - price[prop]) / 100) : price[prop] / 100 + 1);23 }24 getMedian() {25 return (this.priceChangeLastMonth + this.priceChangeLast60Days + this.priceChangeLast90Days) / 3;26 }27 getIsDecline() {28 const tag = this.price < this.priceChangeLastHour29 && this.price < this.priceChangeLastDay30 ? tags.DECLINING : tags.INCLINING;31 this.tags.push(tag);32 return tag;33 }34 checkPriceStability() {35 const percentageDiff = this.price / this.median;36 let tag = '';37 if (percentageDiff < 1) {38 tag = percentageDiff + 0.1 > 139 ? {grade: 1, label: tags.WEAK_BUY} : percentageDiff + 0.2 > 140 ? {grade: 2, label: tags.OKAY_BUY} : percentageDiff + 0.3 > 141 ? {grade: 3, label: tags.FAIRLY_GOOD_BUY} : percentageDiff + 0.4 > 142 ? {grade: 4, label: tags.VERY_GOOD_BUY} : {grade: 5, label: tags.WELL_BELOW};43 } else {44 tag = percentageDiff - 0.1 > 145 ? {grade: -1, label: tags.STEADY_PRICE} : percentageDiff - 0.2 > 146 ? {grade: -2, label: tags.OKAY_SALE} : percentageDiff - 0.3 > 147 ? {grade: -3, label: tags.GOOD_SALE} : percentageDiff - 0.4 > 148 ? {grade: -4, label: tags.VERY_GOOD_SALE} : {grade: -5, label: tags.EXCELLENT_SALE};49 }50 this.tags.push(tag.label);51 return tag;52 }53}...

Full Screen

Full Screen

app.js

Source:app.js Github

copy

Full Screen

1import { getMarketPrice } from "./api.js";2import { placeSellOrder, placeBuyOrder } from "./api.js";3let isBuyMode = true;4const UPWARD_TREND_THRESHOLD = 1.0;5const DIP_THRESHOLD = -3.25;6const PROFIT_THRESHOLD = 0.65;7const STOP_LOSS_THRESHOLD = -3.0;8let lastOrderPrice = 1.160234;9const buy = async (percentageDiff) => {10 if (11 percentageDiff >= UPWARD_TREND_THRESHOLD ||12 percentageDiff <= DIP_THRESHOLD13 ) {14 lastOrderPrice = await placeBuyOrder();15 console.log(`[BUY] Bought XRP at price ${lastOrderPrice}`);16 isBuyMode = false;17 }18};19const sell = async (percentageDiff) => {20 if (21 percentageDiff >= PROFIT_THRESHOLD ||22 percentageDiff <= STOP_LOSS_THRESHOLD23 ) {24 lastOrderPrice = await placeSellOrder();25 console.log(`[SELL] Sold XRP at price ${lastOrderPrice}`);26 isBuyMode = true;27 }28};29const trade = async () => {30 const currentPrice = await getMarketPrice();31 const percentageDiff =32 ((currentPrice - lastOrderPrice) / lastOrderPrice) * 100;33 console.log(`[CURRENT PRICE] ${currentPrice}`);34 console.log(`[LAST ORDER PRICE] ${lastOrderPrice}`);35 console.log(`[PERCENTAGE DIFF] ${percentageDiff}%\n`);36 if (isBuyMode) {37 await buy(percentageDiff);38 } else {39 await sell(percentageDiff);40 }41};42const sleep = (ms) => {43 return new Promise((resolve) => setTimeout(resolve, ms));44};45const printDateTime = () => {46 const today = new Date();47 const yyyy = `${today.getFullYear()}`.padStart(2, "0");48 const mm = `${today.getMonth() + 1}`.padStart(2, "0");49 const dd = `${today.getDate()}`.padStart(2, "0");50 const date = `${yyyy}-${mm}-${dd}`;51 const hh = `${today.getHours()}`.padStart(2, "0");52 const min = `${today.getMinutes()}`.padStart(2, "0");53 const sec = `${today.getSeconds()}`.padStart(2, "0");54 const time = `${hh}:${min}:${sec}`;55 const dateTime = `==========${date} ${time}==========\n`;56 console.log(dateTime);57};58const start = async () => {59 while (true) {60 printDateTime();61 await trade();62 await sleep(30000);63 }64};...

Full Screen

Full Screen

utils.js

Source:utils.js Github

copy

Full Screen

1// return a number to US format2const formatNumber = number => {3 return number.toLocaleString('en-US');4}5// given an array of objects (object MUST contain a value field that's an integer),6// it returns that array sorted in descending(default) or ascending order7const sort = (array, order = 'desc') => {8 if (order === 'desc') {9 return array.sort((a, b) => b.value - a.value)10 } else if (order === 'asc') {11 return array.sort((a, b) => a.value - b.value)12 } else {13 // not recognized order, return the array as is14 return array15 }16}17const handleCircleRadius = (value, highestValue) => {18 const highestRadius = 6019 if (value === highestValue) return highestRadius20 if (value <= 0) return 1021 const percentageDiff = percentageDifference(highestValue, value)22 if (percentageDiff <= 25) return 5523 if (percentageDiff <= 50) return 5024 if (percentageDiff <= 100) return 4025 if (percentageDiff <= 150) return 2526 return 2027}28// calculates the percentage difference between 2 numbers29const percentageDifference = (a, b) => {30 const [highestNumber, lowestNumber] = [a,b].sort((a,b) => b - a)31 const absolute = highestNumber - lowestNumber32 var avg = (highestNumber + lowestNumber) / 233 return (absolute / avg) * 100 34}35// takes a number and returns a beautified one (eg, 100,000 --> 100k)36const beautifyNumber = (number) => {37 const formatter = Intl.NumberFormat('en', { notation: 'compact'})38 return formatter.format(number).toLowerCase()39}40const decodeHtml = (html) => {41 let txt = document.createElement("textarea");42 txt.innerHTML = html;43 return txt.value;44}45export {46 formatNumber,47 sort,48 handleCircleRadius,49 beautifyNumber,50 decodeHtml...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import React from 'react';2import { toPercentageString } from '../../../core/utils';3import IconButtonWithTooltip from '../../IconButtonWithTooltip';4const TimingItem = ({5 result,6 label,7 tooltipId,8 tooltipTitle,9 tooltipText,10 percentageDiff,11 highlighted,12 positiveLabel = 'faster',13 negativeLabel = 'slower',14}) => {15 const renderDiff = React.useCallback(() => {16 if (!percentageDiff) {17 return null;18 }19 const isFaster = percentageDiff <= 0;20 const className = [21 'card__gtmetrix-percentage',22 isFaster ? 'card__gtmetrix-percentage--limeade' : 'card__gtmetrix-percentage--dusty-gray-light',23 ].join(' ');24 return (25 <span className={className}>26 {toPercentageString(percentageDiff)} {isFaster ? positiveLabel : negativeLabel}27 </span>28 );29 }, [percentageDiff, positiveLabel, negativeLabel]);30 return (31 <ul className="card__gtmetrix-results-result">32 <li>33 <span className={highlighted ? 'color color--curious-blue' : ''}>{result}</span>34 </li>35 <li>36 {label}37 <IconButtonWithTooltip tooltipTitle={tooltipTitle} tooltipText={tooltipText} tooltipId={tooltipId}>38 <i className="fal fa-question-circle" />39 </IconButtonWithTooltip>40 </li>41 <li>{renderDiff()}</li>42 </ul>43 );44};...

Full Screen

Full Screen

Indicator.jsx

Source:Indicator.jsx Github

copy

Full Screen

1import React from "react";2import CountUp from "react-countup";3import PropTypes from "prop-types";4import usePrevious from "hooks/usePrevious";5import formatter from "utils/formatter";6export default function Indicator({ start, end, precision = 2 }) {7 const percentFormatter = formatter.percent();8 const percentageDiff = React.useMemo(9 () => ((end - start) / start) * 100,10 [end, start]11 );12 const diffColor = React.useMemo(13 () => (percentageDiff > 0 ? "text-success" : "text-danger"),14 [percentageDiff]15 );16 const diffArrow = React.useMemo(17 () => (percentageDiff > 0 ? "bi-arrow-up-short" : "bi-arrow-down-short"),18 [percentageDiff]19 );20 const previousPercentageDiff = usePrevious(percentageDiff) || 0;21 return (22 <span className={`fs-6 fw-bold ${diffColor} text-nowrap`}>23 <CountUp24 duration={1}25 start={previousPercentageDiff}26 end={percentageDiff}27 decimals={precision}28 formattingFn={percentFormatter}29 />30 <i className={`bi ${diffArrow}`} />31 </span>32 );33}34Indicator.propTypes = {35 start: PropTypes.number.isRequired,36 end: PropTypes.number.isRequired,37 precision: PropTypes.number,38};39Indicator.defaultProps = {40 precision: 2,...

Full Screen

Full Screen

testModel.js

Source:testModel.js Github

copy

Full Screen

1const trainModel= require('./trainModel')2exports.testModel = (list, tempPredictedValue, percentageIncrease) => {3 let epoch = list.length - 1; // Find the length of the data list.4 let percentageDiff=[epoch - 2]; // Create an array of size double to store the percentage5 // differences6 let index = 0, value;7 // Loop until there are only 2 datas left.8 while (epoch > 2) {9 let testingResult = list[epoch]; // Store the last data as the result.10 let tempList = list.slice(0, epoch); // Copy all the datas except the last data into11 // tempList12 value = trainModel.trainModel(tempList, percentageIncrease); // Get the trained value for the tempList.13 // Find the Percentage difference between the trained value and the14 // testingResult and store in percentageDiff.15 percentageDiff[index] = (testingResult * 100);16 if (value != 0)17 percentageDiff[index] /= value;18 percentageDiff[index] /= 100;19 // Increase the index and decrease the epoch.20 index++;21 epoch--;22 }23 // Return the percentageDiff.24 // console.log("Percentage Difference After Testing : ", percentageDiff);25 return percentageDiff;...

Full Screen

Full Screen

game.js

Source:game.js Github

copy

Full Screen

1const getScore = function(userResponse, productPrice) {2 if (userResponse == productPrice) {3 return 1000;4 }5 let percentageDiff = (userResponse - productPrice)/productPrice;6 if (percentageDiff < 0) {7 percentageDiff = percentageDiff * -1;8 }9 if (percentageDiff <= 0.1) {10 return 800;11 }12 if (percentageDiff <= 0.3) {13 return 500;14 }15 return 0;16};17module.exports = {18 getScore: getScore...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.get('#lst-ib').type('cypress')4 cy.get('.lsb').click()5 cy.get('h3').contains('Cypress.io').click()6 cy.get('img').should('have.attr', 'src').and('include', 'logo')7 cy.get('img').should(($img) => {8 expect($img[0].naturalWidth).to.be.greaterThan(0)9 })10 })11})12describe('My First Test', function() {13 it('Does not do much!', function() {14 cy.get('#lst-ib').type('cypress')15 cy.get('.lsb').click()16 cy.get('h3').contains('Cypress.io').click()17 cy.get('img').should('have.attr', 'src').and('include', 'logo')18 cy.get('img').should(($img) => {19 expect($img[0].naturalWidth).to.be.greaterThan(0)20 })21 })22})23Cypress.Commands.add('percentageDiff', (actual, expected, percentage) => {24 expect(actual).to.be.closeTo(expected, expected * percentage / 100)25})26describe('My First Test', function() {27 it('Does not do much!', function() {28 cy.get('#lst-ib').type('cypress')29 cy.get('.lsb').click()30 cy.get('h3').contains('Cypress.io').click()31 cy.get('img').should('have.attr', 'src').and('include', 'logo')32 cy.get('img').should(($img) => {33 expect($img[0].naturalWidth).to.be.greaterThan(0)34 })35 cy.get('img').should(($img) => {36 expect($img[0].naturalWidth).to.be.greaterThan(0)37 cy.percentageDiff($img[

Full Screen

Using AI Code Generation

copy

Full Screen

1import percentageDiff from 'cypress-visual-regression/dist/percentageDiff'2import { checkWindow } from 'cypress-visual-regression/dist/command'3import { checkElement } from 'cypress-visual-regression/dist/command'4describe('My first test', () => {5 it('Does not do much!', () => {6 expect(true).to.equal(true)7 })8 it('Visits the Kitchen Sink', () => {9 cy.contains('type').click()10 cy.url().should('include', '/commands/actions')11 cy.get('.action-email')12 .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1const { percentageDiff } = require("cypress-visual-regression/dist/plugin/commands")2const { percentageDiff } = require("cypress-visual-regression/dist/plugin/commands")3cy.get("#selector").screenshot("test", { capture: "fullPage" })4cy.get("#selector").screenshot("test", { capture: "fullPage" })5cy.task("compareScreenshots", {6cy.task("compareScreenshots", {7}).then((result) => {8}).then((result) => {9 cy.wrap(result.percentage).should("be.lessThan", 0.01)10 cy.wrap(result.percentage).should("be.lessThan", 0.01)11})12})13})

Full Screen

Using AI Code Generation

copy

Full Screen

1const { percentageDiff } = require('cypress-image-diff-js/dist/plugin/percentageDiff');2Cypress.Commands.add('compareSnapshot', (name, options = {}) => {3 const { threshold = 0.01, thresholdType = 'percent' } = options;4 cy.task('compareSnapshot', { name, threshold, thresholdType });5});6import './commands';7const { addMatchImageSnapshotPlugin } = require('cypress-image-snapshot/plugin');8module.exports = (on, config) => {9 addMatchImageSnapshotPlugin(on, config);10};11{12 "reporterOptions": {13 },14}15describe('Test', () => {16 it('Test', () => {17 cy.compareSnapshot('test');18 });19});20const { addMatchImageSnapshotPlugin } = require('cypress-image-snapshot/plugin');21module.exports = (on, config) => {22 addMatchImageSnapshotPlugin(on, config);23};24const { addMatchImageSnapshotPlugin } = require('cypress-image-snapshot/plugin');25module.exports = (on, config) => {26 addMatchImageSnapshotPlugin(on, config);27};28const { addMatchImageSnapshotPlugin } = require('cypress-image-snapshot/plugin');29module.exports = (on, config) => {30 addMatchImageSnapshotPlugin(on, config);31};32const { addMatchImageSnapshotPlugin } = require('cypress-image-snapshot/plugin');33module.exports = (on, config) => {34 addMatchImageSnapshotPlugin(on, config);35};36const { addMatchImageSnapshotPlugin } = require('cypress-image-snapshot/plugin');37module.exports = (on, config) => {

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', function() {2 it('Test', function() {3 cy.matchImageSnapshot('google');4 });5});6{7 "env": {8 },9 "visualRegression": {10 "compare": {11 },12 "update": {13 }14 }15}

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.get('[data-cy=element]').should('have.css', 'property', 'value');2cy.get('[data-cy=element]').should('have.css', 'property', 'value').and('percentageDiff', 10);3cy.get('[data-cy=element]').should('have.css', 'property', 'value').and('percentageDiff', 10, 20);4cy.get('[data-cy=element]').should('have.css', 'property', 'value').and('percentageDiff', 10, 20, 30);5expect('[data-cy=element]').to.have.css('property', 'value');6expect('[data-cy=element]').to.have.css('property', 'value').and.percentageDiff(10);7expect('[data-cy=element]').to.have.css('property', 'value').and.percentageDiff(10, 20);8expect('[data-cy=element]').to.have.css('property', 'value').and.percentageDiff(10, 20, 30);9cy.get('[data-cy=element]').should('have.css', 'property', 'value');10cy.get('[data-cy=element]').should('have.css', 'property', 'value').and('percentageDiff', 10);11cy.get('[data-cy=element]').should('have.css', 'property', 'value').and('percentageDiff', 10, 20);12cy.get('[data-cy=element]').should('have.css', 'property', 'value').and('percentageDiff', 10, 20, 30);13expect('[data-cy=element]').to.have.css('property', 'value');14expect('[data-cy=element]').to.have.css('property', 'value').and.percentageDiff(10);15expect('[data-cy=element]').to.have.css('property', 'value').and.percentageDiff(10, 20);16expect('[data-cy=element]').to.have.css('property', 'value').and.percentageDiff(10, 20, 30);17cy.get('[data-cy=element]').should('have.css', 'property', 'value');18cy.get('[data-cy=element]').should('have.css', 'property',

Full Screen

Using AI Code Generation

copy

Full Screen

1it('should be 100% different', function () {2 cy.document().then((doc) => {3 cy.get('body').then((body) => {4 cy.percentageDiff({5 })6 })7 })8})

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress 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