Best JavaScript code snippet using wpt
test_tax.py
Source:test_tax.py
...195 # ---------------------------------------------------196 ],197 res198 )199 def test_tax_group_percent(self):200 res = self.group_tax_percent.with_context({'force_price_include':True}).compute_all(100.0)201 self._check_compute_all_results(202 100, # 'total_included'203 83.33, # 'total_excluded'204 [205 # base , amount | seq | amount | incl | incl_base206 # ---------------------------------------------------207 (83.33, 8.33), # | 1 | 10% | |208 (83.33, 8.34), # | 2 | 10% | |209 # ---------------------------------------------------210 ],211 res212 )213 def test_tax_percent_division(self):...
progress.js
Source:progress.js
1/**2 * Progress.js v0.1.03 * https://github.com/usablica/progress.js4 * MIT licensed5 *6 * Copyright (C) 2013 usabli.ca - Afshin Mehrabani (@afshinmeh)7 */8(function (root, factory) {9 if (typeof exports === 'object') {10 // CommonJS11 factory(exports);12 } else if (typeof define === 'function' && define.amd) {13 // AMD. Register as an anonymous module.14 define(['exports'], factory);15 } else {16 // Browser globals17 factory(root);18 }19} (this, function (exports) {20 //Default config/variables21 var VERSION = '0.1.0';22 /**23 * ProgressJs main class24 *25 * @class ProgressJs26 */27 function ProgressJs(obj) {28 if (typeof obj.length != 'undefined') {29 this._targetElement = obj; 30 } else {31 this._targetElement = [obj];32 }33 if (typeof window._progressjsId === 'undefined')34 window._progressjsId = 1;35 if (typeof window._progressjsIntervals === 'undefined') 36 window._progressjsIntervals = {};37 this._options = {38 //progress bar theme39 theme: 'blue',40 //overlay mode makes an overlay layer in the target element41 overlayMode: false,42 //to consider CSS3 transitions in events43 considerTransition: true44 };45 }46 /**47 * Start progress for specific element(s)48 *49 * @api private50 * @method _createContainer 51 */52 function _startProgress() {53 //call onBeforeStart callback54 if (typeof this._onBeforeStartCallback != 'undefined') {55 this._onBeforeStartCallback.call(this);56 }57 //create the container for progress bar58 _createContainer.call(this);59 for (var i = 0, elmsLength = this._targetElement.length; i < elmsLength; i++) {60 _setProgress.call(this, this._targetElement[i]);61 }62 }63 /**64 * Set progress bar for specific element65 *66 * @api private67 * @method _setProgress68 * @param {Object} targetElement69 */70 function _setProgress(targetElement) {71 72 //if the target element already as `data-progressjs`, ignore the init73 if (targetElement.hasAttribute("data-progressjs"))74 return;75 //get target element position76 var targetElementOffset = _getOffset.call(this, targetElement);77 targetElement.setAttribute("data-progressjs", window._progressjsId);78 79 var progressElementContainer = document.createElement('div');80 progressElementContainer.className = 'progressjs-progress progressjs-theme-' + this._options.theme;81 //set the position percent elements, it depends on targetElement tag82 if (targetElement.tagName.toLowerCase() === 'body') {83 progressElementContainer.style.position = 'fixed';84 } else {85 progressElementContainer.style.position = 'absolute';86 }87 progressElementContainer.setAttribute("data-progressjs", window._progressjsId);88 var progressElement = document.createElement("div");89 progressElement.className = "progressjs-inner";90 //create an element for current percent of progress bar91 var progressPercentElement = document.createElement('div');92 progressPercentElement.className = "progressjs-percent";93 progressPercentElement.innerHTML = "1%";94 progressElement.appendChild(progressPercentElement);95 96 if (this._options.overlayMode && targetElement.tagName.toLowerCase() === 'body') {97 //if we have `body` for target element and also overlay mode is enable, we should use a different98 //position for progress bar container element99 progressElementContainer.style.left = 0;100 progressElementContainer.style.right = 0;101 progressElementContainer.style.top = 0;102 progressElementContainer.style.bottom = 0;103 } else {104 //set progress bar container size and offset105 progressElementContainer.style.left = targetElementOffset.left + 'px';106 progressElementContainer.style.top = targetElementOffset.top + 'px';107 progressElementContainer.style.width = targetElementOffset.width + 'px';108 if (this._options.overlayMode) {109 progressElementContainer.style.height = targetElementOffset.height + 'px';110 }111 }112 progressElementContainer.appendChild(progressElement);113 //append the element to container114 var container = document.querySelector('.progressjs-container');115 container.appendChild(progressElementContainer);116 _setPercentFor(targetElement, 1);117 //and increase the progressId118 ++window._progressjsId;119 }120 /**121 * Set percent for all elements122 *123 * @api private124 * @method _setPercent125 * @param {Number} percent126 */127 function _setPercent(percent) {128 for (var i = 0, elmsLength = this._targetElement.length; i < elmsLength; i++) {129 _setPercentFor.call(this, this._targetElement[i], percent);130 }131 }132 /**133 * Set percent for specific element134 *135 * @api private136 * @method _setPercentFor137 * @param {Object} targetElement138 * @param {Number} percent139 */140 function _setPercentFor(targetElement, percent) {141 var self = this;142 143 //prevent overflow!144 if (percent >= 100)145 percent = 100;146 if (targetElement.hasAttribute("data-progressjs")) {147 //setTimeout for better CSS3 animation applying in some cases148 setTimeout(function() {149 //call the onprogress callback150 if (typeof self._onProgressCallback != 'undefined') {151 self._onProgressCallback.call(self, targetElement, percent);152 }153 var percentElement = _getPercentElement(targetElement);154 percentElement.style.width = parseInt(percent) + '%';155 var percentElement = percentElement.querySelector(".progressjs-percent");156 var existingPercent = parseInt(percentElement.innerHTML.replace('%', ''));157 //start increase/decrease the percent element with animation158 (function(percentElement, existingPercent, currentPercent) {159 var increasement = true;160 if (existingPercent > currentPercent) {161 increasement = false;162 }163 164 var intervalIn = 10;165 function changePercentTimer(percentElement, existingPercent, currentPercent) {166 //calculate the distance between two percents167 var distance = Math.abs(existingPercent - currentPercent);168 if (distance < 3) {169 intervalIn = 30;170 } else if (distance < 20) {171 intervalIn = 20;172 } else {173 intervanIn = 1;174 }175 if ((existingPercent - currentPercent) != 0) {176 //set the percent177 percentElement.innerHTML = (increasement ? (++existingPercent) : (--existingPercent)) + '%';178 setTimeout(function() { changePercentTimer(percentElement, existingPercent, currentPercent); }, intervalIn);179 }180 }181 182 changePercentTimer(percentElement, existingPercent, currentPercent);183 184 })(percentElement, existingPercent, parseInt(percent));185 186 }, 50);187 }188 }189 /**190 * Get the progress bar element 191 *192 * @api private193 * @method _getPercentElement194 * @param {Object} targetElement195 */196 function _getPercentElement(targetElement) {197 var progressjsId = parseInt(targetElement.getAttribute('data-progressjs'));198 return document.querySelector('.progressjs-container > .progressjs-progress[data-progressjs="' + progressjsId + '"] > .progressjs-inner'); 199 }200 /**201 * Auto increase the progress bar every X milliseconds202 *203 * @api private204 * @method _autoIncrease205 * @param {Number} size206 * @param {Number} millisecond207 */208 function _autoIncrease(size, millisecond) {209 var self = this;210 211 var progressjsId = parseInt(this._targetElement[0].getAttribute('data-progressjs'));212 213 if (typeof window._progressjsIntervals[progressjsId] != 'undefined') {214 clearInterval(window._progressjsIntervals[progressjsId]);215 }216 window._progressjsIntervals[progressjsId] = setInterval(function() {217 _increasePercent.call(self, size);218 }, millisecond);219 }220 /**221 * Increase the size of progress bar222 *223 * @api private224 * @method _increasePercent225 * @param {Number} size226 */227 function _increasePercent(size) {228 for (var i = 0, elmsLength = this._targetElement.length; i < elmsLength; i++) {229 var currentElement = this._targetElement[i];230 if (currentElement.hasAttribute('data-progressjs')) {231 var percentElement = _getPercentElement(currentElement);232 var existingPercent = parseInt(percentElement.style.width.replace('%', ''));233 if (existingPercent) {234 _setPercentFor.call(this, currentElement, existingPercent + (size || 1));235 }236 }237 }238 }239 /**240 * Close and remove progress bar 241 *242 * @api private243 * @method _end244 */245 function _end() {246 //call onBeforeEnd callback247 if (typeof this._onBeforeEndCallback != 'undefined') {248 if (this._options.considerTransition === true) {249 //we can safety assume that all layers would be the same, so `this._targetElement[0]` is the same as `this._targetElement[1]`250 _getPercentElement(this._targetElement[0]).addEventListener(whichTransitionEvent(), this._onBeforeEndCallback, false);251 } else {252 this._onBeforeEndCallback.call(this);253 }254 } 255 var progressjsId = parseInt(this._targetElement[0].getAttribute('data-progressjs'));256 257 for (var i = 0, elmsLength = this._targetElement.length; i < elmsLength; i++) {258 var currentElement = this._targetElement[i];259 var percentElement = _getPercentElement(currentElement);260 if (!percentElement)261 return;262 var existingPercent = parseInt(percentElement.style.width.replace('%', ''));263 264 var timeoutSec = 1;265 if (existingPercent < 100) {266 _setPercentFor.call(this, currentElement, 100);267 timeoutSec = 500;268 }269 //I believe I should handle this situation with eventListener and `transitionend` event but I'm not sure270 //about compatibility with IEs. Should be fixed in further versions.271 (function(percentElement, currentElement) {272 setTimeout(function() {273 percentElement.parentNode.className += " progressjs-end";274 setTimeout(function() {275 //remove the percent element from page276 percentElement.parentNode.parentNode.removeChild(percentElement.parentNode);277 //and remove the attribute278 currentElement.removeAttribute("data-progressjs");279 }, 1000);280 }, timeoutSec);281 })(percentElement, currentElement);282 }283 //clean the setInterval for autoIncrease function284 if (window._progressjsIntervals[progressjsId]) {285 //`delete` keyword has some problems in IE286 try {287 clearInterval(window._progressjsIntervals[progressjsId]);288 window._progressjsIntervals[progressjsId] = null;289 delete window._progressjsIntervals[progressjsId];290 } catch(ex) { }291 }292 }293 /**294 * Create the progress bar container295 *296 * @api private297 * @method _createContainer298 */299 function _createContainer() {300 //first check if we have an container already, we don't need to create it again301 if (!document.querySelector(".progressjs-container")) {302 var containerElement = document.createElement("div");303 containerElement.className = "progressjs-container";304 document.body.appendChild(containerElement);305 }306 }307 /**308 * Get an element position on the page309 * Thanks to `meouw`: http://stackoverflow.com/a/442474/375966310 *311 * @api private312 * @method _getOffset313 * @param {Object} element314 * @returns Element's position info315 */316 function _getOffset(element) {317 var elementPosition = {};318 if (element.tagName.toLowerCase() === 'body') {319 //set width320 elementPosition.width = element.clientWidth;321 //set height322 elementPosition.height = element.clientHeight;323 } else {324 //set width325 elementPosition.width = element.offsetWidth;326 //set height327 elementPosition.height = element.offsetHeight;328 }329 //calculate element top and left330 var _x = 0;331 var _y = 0;332 while (element && !isNaN(element.offsetLeft) && !isNaN(element.offsetTop)) {333 _x += element.offsetLeft;334 _y += element.offsetTop;335 element = element.offsetParent;336 }337 //set top338 elementPosition.top = _y;339 //set left340 elementPosition.left = _x;341 return elementPosition;342 }343 /**344 * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1345 * via: http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically346 *347 * @param obj1348 * @param obj2349 * @returns obj3 a new object based on obj1 and obj2350 */351 function _mergeOptions(obj1, obj2) {352 var obj3 = {};353 for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }354 for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }355 return obj3;356 }357 var progressJs = function (targetElm) {358 if (typeof (targetElm) === 'object') {359 //Ok, create a new instance360 return new ProgressJs(targetElm);361 } else if (typeof (targetElm) === 'string') {362 //select the target element with query selector363 var targetElement = document.querySelectorAll(targetElm);364 365 if (targetElement) {366 return new ProgressJs(targetElement);367 } else {368 throw new Error('There is no element with given selector.');369 }370 } else {371 return new ProgressJs(document.body);372 }373 };374 /**375 * Get correct transition callback376 * Thanks @webinista: http://stackoverflow.com/a/9090128/375966377 *378 * @returns transition name379 */380 function whichTransitionEvent() {381 var t;382 var el = document.createElement('fakeelement');383 var transitions = {384 'transition': 'transitionend',385 'OTransition': 'oTransitionEnd',386 'MozTransition': 'transitionend',387 'WebkitTransition': 'webkitTransitionEnd'388 }389 for (t in transitions) {390 if (el.style[t] !== undefined) {391 return transitions[t];392 }393 }394 }395 /**396 * Current ProgressJs version397 *398 * @property version399 * @type String400 */401 progressJs.version = VERSION;402 //Prototype403 progressJs.fn = ProgressJs.prototype = {404 clone: function () {405 return new ProgressJs(this);406 },407 setOption: function(option, value) {408 this._options[option] = value;409 return this;410 },411 setOptions: function(options) {412 this._options = _mergeOptions(this._options, options);413 return this;414 },415 start: function() {416 _startProgress.call(this);417 return this;418 },419 set: function(percent) {420 _setPercent.call(this, percent);421 return this;422 },423 increase: function(size) {424 _increasePercent.call(this, size);425 return this;426 },427 autoIncrease: function(size, millisecond) {428 _autoIncrease.call(this, size, millisecond);429 return this;430 },431 end: function() {432 _end.call(this);433 return this;434 },435 onbeforeend: function(providedCallback) {436 if (typeof (providedCallback) === 'function') {437 this._onBeforeEndCallback = providedCallback;438 } else {439 throw new Error('Provided callback for onbeforeend was not a function');440 }441 return this;442 },443 onbeforestart: function(providedCallback) {444 if (typeof (providedCallback) === 'function') {445 this._onBeforeStartCallback = providedCallback;446 } else {447 throw new Error('Provided callback for onbeforestart was not a function');448 }449 return this;450 },451 onprogress: function(providedCallback) {452 if (typeof (providedCallback) === 'function') {453 this._onProgressCallback = providedCallback;454 } else {455 throw new Error('Provided callback for onprogress was not a function');456 }457 return this;458 }459 };460 exports.progressJs = progressJs;461 return progressJs;...
half.py
Source:half.py
1#!/usr/bin/env python32from configruation import *3from threading import Thread4def align():5 sleep(.25)6 print("align")7 tank.stop()8 tank.on_for_degrees(SpeedPercent(-20), SpeedPercent(-20),140)9 leftBlack = True10 rightBlack = True11 tankDegrees = 012 leftMotor.reset()13 rightMotor.reset()14 while color2.reflected_light_intensity >20:15 tank.on(SpeedPercent(-10), SpeedPercent(10))16 tankDegrees = leftMotor.degrees17 if abs(tankDegrees) > 40:18 leftBlack = False19 tank.stop()20 break21 tank.stop()22 print(leftBlack)23 print ("back to straight")24 tankDegrees = tankDegrees * -125 print(tankDegrees)26 leftMotor.reset()27 rightMotor.reset()28 29 if leftBlack:30 tank.on_for_degrees(SpeedPercent(-10),SpeedPercent(-10),tankDegrees*2)31 tank.on_for_degrees(SpeedPercent(10),SpeedPercent(-10),tankDegrees/1)32 tankDegrees=033 tank.stop()34 else:35 tank.on_for_degrees(SpeedPercent(10),SpeedPercent(-10),tankDegrees/1)36 tankDegrees = 037 leftMotor.reset()38 rightMotor.reset()39 while color2.reflected_light_intensity > 20:40 print(color2.color_name)41 tank.on(SpeedPercent(10), SpeedPercent(-10))42 tankDegrees = rightMotor.degrees43 if abs(tankDegrees) > 40:44 rightBlack = False45 tank.stop()46 break47 tank.stop()48 print(rightBlack)49 if (rightBlack):50 tankDegrees = tankDegrees * -151 leftMotor.reset()52 rightMotor.reset()53 print(tankDegrees)54 tank.on_for_degrees(SpeedPercent(-10),SpeedPercent(-10),tankDegrees*2)55 tank.on_for_degrees(SpeedPercent(-10),SpeedPercent(10),tankDegrees)56 tank.stop()57def do_step_tracker():58 # print('lift arm')59 # med.on_for_rotations(100, 2.5, brake=True, block=True)60 print ("going forward out of home")61 l=3062 r=3063 tank.on_for_rotations(SpeedPercent(l), SpeedPercent(r), 0.95)64 print ("reach stepper and push")65 l=2866 r=3067 tank.on_for_rotations(SpeedPercent(l), SpeedPercent(r), 4)68def go_back_from_step_tracker():69 x=-2570 tank.on_for_rotations(SpeedPercent(x), SpeedPercent(x), .2)71 light_intensity = color1.reflected_light_intensity72 while light_intensity < 80:73 tank.on(SpeedPercent(x), SpeedPercent(x))74 light_intensity = color1.reflected_light_intensity75 print(light_intensity)76 tank.on_for_rotations(SpeedPercent(x), SpeedPercent(x), .2)77 light_intensity = color1.reflected_light_intensity78 while light_intensity < 80:79 tank.on(SpeedPercent(x), SpeedPercent(x))80 light_intensity = color1.reflected_light_intensity81 print(light_intensity)82 tank.stop()83 84 print ("reach stepper and push")85 l=-1086 r=2087 tank.on_for_rotations(SpeedPercent(l), SpeedPercent(r), .2)88 x = -1089 tank.on_for_rotations(SpeedPercent(x), SpeedPercent(x), .25)90 x = 1091 #tank.on_for_rotations(SpeedPercent(x), SpeedPercent(x), .25)92 93 print ("reach stepper")94 l=2095 r=2396 tank.on_for_rotations(SpeedPercent(l), SpeedPercent(r), 0.9)97 print ("push stepper")98 l=3599 r=24100 tank.on_for_rotations(SpeedPercent(l), SpeedPercent(r), 2.5)101def ready_treadmill():102 #align()103 print ("align with wall")104 l=20105 r=20106 tank.on_for_seconds(SpeedPercent(l), SpeedPercent(r), 1)107 print ("turning back to face treadmillh")108 l=-20109 r=-20110 tank.on_for_rotations(SpeedPercent(l), SpeedPercent(r), 0.6)111 l=-20112 r=20113 tank.on_for_rotations(SpeedPercent(l), SpeedPercent(r), 0.3)114 print ("turning")115 l=0116 r=20117 tank.on_for_rotations(SpeedPercent(l), SpeedPercent(r), 0.3) 118 print ("getting on treadmill")119 l=20120 r=20121 tank.on_for_rotations(SpeedPercent(l), SpeedPercent(r), 1.1)122def do_treadmill():123 sleep(0.5)124 print('running on treadmill spin one wheel')125 l=0126 r=40127 tank.on_for_seconds(SpeedPercent(l), SpeedPercent(r), 2.75)128def doRowerWithArm():129 print('running on treadmill')130 #go forward131 tank.on_for_seconds(SpeedPercent(20),SpeedPercent(20),1.5)132 #Go Forward133 t = Thread(target=medMotor.on_for_seconds, args=(SpeedPercent(-10),1,))134 t.start()135 tank.on_for_degrees(SpeedPercent(-20),SpeedPercent(-20),260)136 #bring the arm down137 medMotor2.on_for_seconds(SpeedPercent(-10),1)138 #move in to make sure it gets locked139 tank.on_for_degrees(SpeedPercent(5),SpeedPercent(-5),10)140 #move out to make sure it gets locked141 tank.on_for_degrees(SpeedPercent(-5),SpeedPercent(5),10)142def moveRowerArm():143 #move in to the circle144 tank.on_for_degrees(SpeedPercent(0),SpeedPercent(6),140)145 medMotor2.on_for_degrees(SpeedPercent(10),200)146 tank.on_for_degrees(SpeedPercent(2),SpeedPercent(-2),15)147def moveArmDown():148 medMotor.on_for_seconds(SpeedPercent(-100),1.5)149def doPerson():150 medMotor.on_for_seconds(SpeedPercent(-100),1.5)151 #tank.on_for_degrees(SpeedPercent(2),SpeedPercent(-2),30)152def moveArmUp():153 medMotor.on_for_seconds(SpeedPercent(100),3.5)154def goToPullUp():155 sleep(.5)156 #*Turn till white line157 while (color3.reflected_light_intensity < 40):158 tank.on(SpeedPercent(-10),SpeedPercent(10))159 tank.stop()160 #*turn till black line161 while (color3.reflected_light_intensity > 18):162 tank.on(SpeedPercent(-10),SpeedPercent(10))163 tank.stop()164 #sleep(.25)165 tank.cs = ColorSensor(INPUT_3)166 tank.follow_line(167 kp=1.8, ki=0.009, kd=0,168 speed=SpeedPercent(-19),169 follow_for=follow_for_ms,170 ms=2300,171 follow_left_edge=False,172 target_light_intensity=17173 )174 while (color2.reflected_light_intensity < 40):175 tank.on(SpeedPercent(-10),SpeedPercent(-10))176 tank.stop()177 tank.on_for_degrees(SpeedPercent(-10),SpeedPercent(-10),200)178 while (color2.reflected_light_intensity < 40):179 tank.on(SpeedPercent(10),SpeedPercent(-10))180 tank.stop()181 while (color2.reflected_light_intensity > 20):182 tank.on(SpeedPercent(5),SpeedPercent(-5))183 tank.stop() 184 while (color2.reflected_light_intensity < 40):185 tank.on(SpeedPercent(5),SpeedPercent(-5))186 tank.stop()187 while (color2.reflected_light_intensity > 18):188 tank.on(SpeedPercent(-5),SpeedPercent(5))189 tank.stop()190def goUnderPullUp():191 tank.cs = ColorSensor(INPUT_2)192 tank.follow_line(193 kp=1.8, ki=0.009, kd=0,194 speed=SpeedPercent(-15),195 follow_for=follow_for_ms,196 ms=1900,197 follow_left_edge=False,198 target_light_intensity=17199 ) 200 tank.follow_line(201 kp=1.8, ki=0.009, kd=0,202 speed=SpeedPercent(-20),203 follow_for=follow_for_ms,204 ms=900,205 follow_left_edge=False,206 target_light_intensity=17207 )208 tank.on_for_degrees(SpeedPercent(-30),SpeedPercent(30),70) 209 tank.on_for_degrees(SpeedPercent(-35),SpeedPercent(-35),450)210def doDanceNew():211 counter = 1212 while (counter < 12):213 counter = counter + 1214 tank.on_for_degrees(SpeedPercent(-15),SpeedPercent(15),100) 215 tank.on_for_degrees(SpeedPercent(15),SpeedPercent(-15),100) 216def test():217 sound.speak("v4 Victory is I")218 sound.speak("excalibots are fly")219 sound.play_song((220 ('D4', 'e3'), # intro anacrouse221 ('D4', 'e3'),222 ('D4', 'e3'),223 ('G4', 'h'), # meas 1224 ('D5', 'h'),225 ('C5', 'e3'), # meas 2226 ('B4', 'e3'),227 ('A4', 'e3'),228 ('G5', 'h'),229 ('D5', 'q')))230def back_from_treadmill():231 232 print('getting down from treadmilll')233 l=0234 r=-20235 tank.on_for_seconds(SpeedPercent(l), SpeedPercent(r), 0.3)236 x=-20237 tank.on_for_rotations(SpeedPercent(x), SpeedPercent(x),0.75)238 # print(color1.color_name)239 # while color1.color_name !="Black":240 # tank.on(SpeedPercent(x), SpeedPercent(x))241 # tank.stop()242 tank.on_for_degrees(SpeedPercent(20), SpeedPercent(-20),110)243 tank.on_for_degrees(SpeedPercent(20), SpeedPercent(20),400)244def do_rower():245 # align()246 tank.on_for_seconds(SpeedPercent(20),SpeedPercent(20),2.5)247 #nirav's version of doing the rower248 print("go forward")249 tank.on_for_degrees(SpeedPercent(-20), SpeedPercent(-15),500)250 tank.on_for_degrees(SpeedPercent(5), SpeedPercent(-25),94)251 tank.on_for_degrees(SpeedPercent(5), SpeedPercent(-20),85)252 print("turn to the rower")253 tank.on_for_degrees(SpeedPercent(20), SpeedPercent(-20),90)254 tank.on_for_seconds(SpeedPercent(-10), SpeedPercent(-10),1.7)255 tank.on_for_seconds(SpeedPercent(10), SpeedPercent(10),2.1)256 tank.on_for_degrees(SpeedPercent(-18), SpeedPercent(5),30)257 tank.on_for_degrees(SpeedPercent(10), SpeedPercent(0),10)258 tank.on_for_degrees(SpeedPercent(30), SpeedPercent(30),60)259 tank.on_for_degrees(SpeedPercent(10), SpeedPercent(15),30)260 tank.on_for_degrees(SpeedPercent(-10), SpeedPercent(10),50)261 tank.on_for_degrees(SpeedPercent(-10), SpeedPercent(-10),10)262 #end nirav's version of doing the rower263def Going_Weight():264 print('going to Weight Machine')265 tank.on_for_degrees(SpeedPercent(-20), SpeedPercent(20),80)266 tank.on_for_degrees(SpeedPercent(-20), SpeedPercent(-20),390)267 tank.on_for_degrees(SpeedPercent(-20), SpeedPercent(20),165)268 tank.on_for_seconds(SpeedPercent(20), SpeedPercent(20),3)269 #tank.on_for_seconds(SpeedPercent(-20), SpeedPercent(-5),2)270def forklift():271 medMotor.on_for_degrees(SpeedPercent(100),250)272 medMotor.stop()273def forklift_down():274 medMotor.on_for_degrees(SpeedPercent(-100),250)275 medMotor.stop()276def go_back_from_step_tracker2():277 x=-25278 tank.on_for_rotations(SpeedPercent(x), SpeedPercent(x), .2)279 light_intensity = color1.reflected_light_intensity280 while light_intensity < 80:281 tank.on(SpeedPercent(x), SpeedPercent(x))282 light_intensity = color1.reflected_light_intensity283 print(light_intensity)284 tank.on_for_rotations(SpeedPercent(x), SpeedPercent(x), .2)285 light_intensity = color1.reflected_light_intensity286 while light_intensity < 80:287 tank.on(SpeedPercent(x), SpeedPercent(x))288 light_intensity = color1.reflected_light_intensity289 print(light_intensity)290 tank.stop()291 sleep(.5)292 print ("reach stepper and push")293 l=-10294 r=20295 tank.on_for_rotations(SpeedPercent(l), SpeedPercent(r), .2)296 x = -10297 tank.on_for_rotations(SpeedPercent(x), SpeedPercent(x), .25)298 x = 10299 tank.on_for_rotations(SpeedPercent(x), SpeedPercent(x), 1.25)...
main_crypto-price-app.py
Source:main_crypto-price-app.py
1# This app is for educational purpose only. Insights gained is not financial advice. Use at your own risk!2import streamlit as st3from PIL import Image4import pandas as pd5import base646import matplotlib.pyplot as plt7from bs4 import BeautifulSoup8import requests9import json10import time11# ---------------------------------#12# New feature (make sure to upgrade your streamlit library)13# pip install --upgrade streamlit14# ---------------------------------#15# Page layout16# Page expands to full width17st.set_page_config(layout="wide")18# ---------------------------------#19# Title20image = Image.open("logo.jpg")21st.image(image, width=500)22st.title("Crypto Price App")23st.markdown(24 """25This app retrieves cryptocurrency prices for the top 100 cryptocurrency from the **CoinMarketCap**!26"""27)28# ---------------------------------#29# About30expander_bar = st.expander("About")31expander_bar.markdown(32 """33* **Python libraries:** base64, pandas, streamlit, numpy, matplotlib, seaborn, BeautifulSoup, requests, json, time34* **Data source:** [CoinMarketCap](http://coinmarketcap.com).35* **Credit:** Web scraper adapted from the Medium article *[Web Scraping Crypto Prices With Python](https://towardsdatascience.com/web-scraping-crypto-prices-with-python-41072ea5b5bf)* written by [Bryan Feng](https://medium.com/@bryanf).36"""37)38# ---------------------------------#39# Page layout (continued)40# Divide page to 3 columns (col1 = sidebar, col2 and col3 = page contents)41col1 = st.sidebar42col2, col3 = st.columns((2, 1))43# ---------------------------------#44# Sidebar + Main panel45col1.header("Input Options")46# Sidebar - Currency price unit47currency_price_unit = col1.selectbox("Select currency for price", ("USD", "BTC", "ETH"))48# Web scraping of CoinMarketCap data49@st.cache50def load_data():51 cmc = requests.get("https://coinmarketcap.com")52 soup = BeautifulSoup(cmc.content, "html.parser")53 data = soup.find("script", id="__NEXT_DATA__", type="application/json")54 coins = {}55 coin_data = json.loads(data.contents[0])56 listings = coin_data["props"]["initialState"]["cryptocurrency"]["listingLatest"][57 "data"58 ]59 attributes = listings[0]["keysArr"]60 index_of_id = attributes.index("id")61 index_of_slug = attributes.index("slug")62 for i in listings[1:]:63 coins[str(i[index_of_id])] = i[index_of_slug]64 coin_name = []65 coin_symbol = []66 market_cap = []67 percent_change_1h = []68 percent_change_24h = []69 percent_change_7d = []70 price = []71 volume_24h = []72 index_of_slug = attributes.index("slug")73 index_of_symbol = attributes.index("symbol")74 index_of_quote_currency_price = attributes.index(75 f"quote.{currency_price_unit}.price"76 )77 index_of_quote_currency_percent_change_1h = attributes.index(78 f"quote.{currency_price_unit}.percentChange1h"79 )80 index_of_quote_currency_percent_change_24h = attributes.index(81 f"quote.{currency_price_unit}.percentChange24h"82 )83 index_of_quote_currency_percent_change_7d = attributes.index(84 f"quote.{currency_price_unit}.percentChange7d"85 )86 index_of_quote_currency_market_cap = attributes.index(87 f"quote.{currency_price_unit}.marketCap"88 )89 index_of_quote_currency_volume_24h = attributes.index(90 f"quote.{currency_price_unit}.volume24h"91 )92 for i in listings[1:]:93 coin_name.append(i[index_of_slug])94 coin_symbol.append(i[index_of_symbol])95 price.append(i[index_of_quote_currency_price])96 percent_change_1h.append(i[index_of_quote_currency_percent_change_1h])97 percent_change_24h.append(i[index_of_quote_currency_percent_change_24h])98 percent_change_7d.append(i[index_of_quote_currency_percent_change_7d])99 market_cap.append(i[index_of_quote_currency_market_cap])100 volume_24h.append(i[index_of_quote_currency_volume_24h])101 df = pd.DataFrame(102 columns=[103 "coin_name",104 "coin_symbol",105 "market_cap",106 "percent_change_1h",107 "percent_change_24h",108 "percent_change_7d",109 "price",110 "volume_24h",111 ]112 )113 df["coin_name"] = coin_name114 df["coin_symbol"] = coin_symbol115 df["price"] = price116 df["percent_change_1h"] = percent_change_1h117 df["percent_change_24h"] = percent_change_24h118 df["percent_change_7d"] = percent_change_7d119 df["market_cap"] = market_cap120 df["volume_24h"] = volume_24h121 return df122df = load_data()123# Sidebar - Cryptocurrency selections124sorted_coin = sorted(df["coin_symbol"])125selected_coin = col1.multiselect("Cryptocurrency", sorted_coin, sorted_coin)126df_selected_coin = df[(df["coin_symbol"].isin(selected_coin))] # Filtering data127# Sidebar - Number of coins to display128num_coin = col1.slider("Display Top N Coins", 1, 100, 100)129df_coins = df_selected_coin[:num_coin]130# Sidebar - Percent change timeframe131percent_timeframe = col1.selectbox("Percent change time frame", ["7d", "24h", "1h"])132percent_dict = {133 "7d": "percent_change_7d",134 "24h": "percent_change_24h",135 "1h": "percent_change_1h",136}137selected_percent_timeframe = percent_dict[percent_timeframe]138# Sidebar - Sorting values139sort_values = col1.selectbox("Sort values?", ["Yes", "No"])140col2.subheader("Price Data of Selected Cryptocurrency")141col2.write(142 "Data Dimension: "143 + str(df_selected_coin.shape[0])144 + " rows and "145 + str(df_selected_coin.shape[1])146 + " columns."147)148col2.dataframe(df_coins)149# Download CSV data150# https://discuss.streamlit.io/t/how-to-download-file-in-streamlit/1806151def filedownload(df):152 csv = df.to_csv(index=False)153 b64 = base64.b64encode(csv.encode()).decode() # strings <-> bytes conversions154 href = f'<a href="data:file/csv;base64,{b64}" download="crypto.csv">Download CSV File</a>'155 return href156col2.markdown(filedownload(df_selected_coin), unsafe_allow_html=True)157# ---------------------------------#158# Preparing data for Bar plot of % Price change159col2.subheader("Table of % Price Change")160df_change = pd.concat(161 [162 df_coins.coin_symbol,163 df_coins.percent_change_1h,164 df_coins.percent_change_24h,165 df_coins.percent_change_7d,166 ],167 axis=1,168)169df_change = df_change.set_index("coin_symbol")170df_change["positive_percent_change_1h"] = df_change["percent_change_1h"] > 0171df_change["positive_percent_change_24h"] = df_change["percent_change_24h"] > 0172df_change["positive_percent_change_7d"] = df_change["percent_change_7d"] > 0173col2.dataframe(df_change)174# Conditional creation of Bar plot (time frame)175col3.subheader("Bar plot of % Price Change")176if percent_timeframe == "7d":177 if sort_values == "Yes":178 df_change = df_change.sort_values(by=["percent_change_7d"])179 col3.write("*7 days period*")180 plt.figure(figsize=(5, 25))181 plt.subplots_adjust(top=1, bottom=0)182 df_change["percent_change_7d"].plot(183 kind="barh",184 color=df_change.positive_percent_change_7d.map({True: "g", False: "r"}),185 )186 col3.pyplot(plt)187elif percent_timeframe == "24h":188 if sort_values == "Yes":189 df_change = df_change.sort_values(by=["percent_change_24h"])190 col3.write("*24 hour period*")191 plt.figure(figsize=(5, 25))192 plt.subplots_adjust(top=1, bottom=0)193 df_change["percent_change_24h"].plot(194 kind="barh",195 color=df_change.positive_percent_change_24h.map({True: "g", False: "r"}),196 )197 col3.pyplot(plt)198else:199 if sort_values == "Yes":200 df_change = df_change.sort_values(by=["percent_change_1h"])201 col3.write("*1 hour period*")202 plt.figure(figsize=(5, 25))203 plt.subplots_adjust(top=1, bottom=0)204 df_change["percent_change_1h"].plot(205 kind="barh",206 color=df_change.positive_percent_change_1h.map({True: "g", False: "r"}),207 )...
percent-encoding.js
Source:percent-encoding.js
1"use strict";2const { isASCIIHex } = require("./infra");3const { utf8Encode } = require("./encoding");4// https://url.spec.whatwg.org/#percent-encode5function percentEncode(c) {6 let hex = c.toString(16).toUpperCase();7 if (hex.length === 1) {8 hex = "0" + hex;9 }10 return "%" + hex;11}12// https://url.spec.whatwg.org/#percent-decode13function percentDecodeBytes(input) {14 const output = new Uint8Array(input.byteLength);15 let outputIndex = 0;16 for (let i = 0; i < input.byteLength; ++i) {17 const byte = input[i];18 if (byte !== 0x25) {19 output[outputIndex++] = byte;20 } else if (byte === 0x25 && (!isASCIIHex(input[i + 1]) || !isASCIIHex(input[i + 2]))) {21 output[outputIndex++] = byte;22 } else {23 const bytePoint = parseInt(String.fromCodePoint(input[i + 1], input[i + 2]), 16);24 output[outputIndex++] = bytePoint;25 i += 2;26 }27 }28 // TODO: remove the Buffer.from in the next major version; it's only needed for back-compat, and sticking to standard29 // typed arrays is nicer and simpler.30 // See https://github.com/jsdom/data-urls/issues/17 for background.31 return Buffer.from(output.slice(0, outputIndex));32}33// https://url.spec.whatwg.org/#string-percent-decode34function percentDecodeString(input) {35 const bytes = utf8Encode(input);36 return percentDecodeBytes(bytes);37}38// https://url.spec.whatwg.org/#c0-control-percent-encode-set39function isC0ControlPercentEncode(c) {40 return c <= 0x1F || c > 0x7E;41}42// https://url.spec.whatwg.org/#fragment-percent-encode-set43const extraFragmentPercentEncodeSet = new Set([32, 34, 60, 62, 96]);44function isFragmentPercentEncode(c) {45 return isC0ControlPercentEncode(c) || extraFragmentPercentEncodeSet.has(c);46}47// https://url.spec.whatwg.org/#query-percent-encode-set48const extraQueryPercentEncodeSet = new Set([32, 34, 35, 60, 62]);49function isQueryPercentEncode(c) {50 return isC0ControlPercentEncode(c) || extraQueryPercentEncodeSet.has(c);51}52// https://url.spec.whatwg.org/#special-query-percent-encode-set53function isSpecialQueryPercentEncode(c) {54 return isQueryPercentEncode(c) || c === 39;55}56// https://url.spec.whatwg.org/#path-percent-encode-set57const extraPathPercentEncodeSet = new Set([63, 96, 123, 125]);58function isPathPercentEncode(c) {59 return isQueryPercentEncode(c) || extraPathPercentEncodeSet.has(c);60}61// https://url.spec.whatwg.org/#userinfo-percent-encode-set62const extraUserinfoPercentEncodeSet =63 new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]);64function isUserinfoPercentEncode(c) {65 return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c);66}67// https://url.spec.whatwg.org/#component-percent-encode-set68const extraComponentPercentEncodeSet = new Set([36, 37, 38, 43, 44]);69function isComponentPercentEncode(c) {70 return isUserinfoPercentEncode(c) || extraComponentPercentEncodeSet.has(c);71}72// https://url.spec.whatwg.org/#application-x-www-form-urlencoded-percent-encode-set73const extraURLEncodedPercentEncodeSet = new Set([33, 39, 40, 41, 126]);74function isURLEncodedPercentEncode(c) {75 return isComponentPercentEncode(c) || extraURLEncodedPercentEncodeSet.has(c);76}77// https://url.spec.whatwg.org/#code-point-percent-encode-after-encoding78// https://url.spec.whatwg.org/#utf-8-percent-encode79// Assuming encoding is always utf-8 allows us to trim one of the logic branches. TODO: support encoding.80// The "-Internal" variant here has code points as JS strings. The external version used by other files has code points81// as JS numbers, like the rest of the codebase.82function utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate) {83 const bytes = utf8Encode(codePoint);84 let output = "";85 for (const byte of bytes) {86 // Our percentEncodePredicate operates on bytes, not code points, so this is slightly different from the spec.87 if (!percentEncodePredicate(byte)) {88 output += String.fromCharCode(byte);89 } else {90 output += percentEncode(byte);91 }92 }93 return output;94}95function utf8PercentEncodeCodePoint(codePoint, percentEncodePredicate) {96 return utf8PercentEncodeCodePointInternal(String.fromCodePoint(codePoint), percentEncodePredicate);97}98// https://url.spec.whatwg.org/#string-percent-encode-after-encoding99// https://url.spec.whatwg.org/#string-utf-8-percent-encode100function utf8PercentEncodeString(input, percentEncodePredicate, spaceAsPlus = false) {101 let output = "";102 for (const codePoint of input) {103 if (spaceAsPlus && codePoint === " ") {104 output += "+";105 } else {106 output += utf8PercentEncodeCodePointInternal(codePoint, percentEncodePredicate);107 }108 }109 return output;110}111module.exports = {112 isC0ControlPercentEncode,113 isFragmentPercentEncode,114 isQueryPercentEncode,115 isSpecialQueryPercentEncode,116 isPathPercentEncode,117 isUserinfoPercentEncode,118 isURLEncodedPercentEncode,119 percentDecodeString,120 percentDecodeBytes,121 utf8PercentEncodeString,122 utf8PercentEncodeCodePoint...
index.js
Source:index.js
1import React, { Component } from 'react';2import { Row, Col } from 'antd';3import Button, { ButtonGroup } from '../../../components/uielements/button';4import Progress from '../../../components/uielements/progress';5import PageHeader from '../../../components/utility/pageHeader';6import LayoutWrapper from '../../../components/utility/layoutWrapper';7import Box from '../../../components/utility/box';8import basicStyle from '../../../config/basicStyle';9export default class extends Component {10 state = {11 percent: 0,12 };13 increase = () => {14 let percent = this.state.percent + 10;15 if (percent > 100) {16 percent = 100;17 }18 this.setState({ percent });19 };20 decline = () => {21 let percent = this.state.percent - 10;22 if (percent < 0) {23 percent = 0;24 }25 this.setState({ percent });26 };27 render() {28 const { rowStyle, colStyle, gutter } = basicStyle;29 return (30 <LayoutWrapper>31 <PageHeader>Progress Bar</PageHeader>32 <Row style={rowStyle} gutter={gutter} justify="start">33 <Col span={12} style={colStyle}>34 <Box title="Progress bar" subtitle="A standard progress bar.">35 <Progress percent={30} />36 <Progress percent={50} status="active" />37 <Progress percent={70} status="exception" />38 <Progress percent={100} />39 <Progress percent={50} showInfo={false} />40 </Box>41 </Col>42 <Col span={12} style={colStyle}>43 <Box44 title="Circular Progress bar"45 subtitle="A circular progress bar."46 >47 <Progress type="circle" percent={75} />48 <Progress type="circle" percent={70} status="exception" />49 <Progress type="circle" percent={100} />50 </Box>51 </Col>52 </Row>53 <Row style={rowStyle} gutter={gutter} justify="start">54 <Col span={8} style={colStyle}>55 <Box56 title="Mini size progress bar"57 subtitle="Appropriate for a narrow area."58 >59 <Progress percent={30} strokeWidth={5} />60 <Progress percent={50} strokeWidth={5} status="active" />61 <Progress percent={70} strokeWidth={5} status="exception" />62 <Progress percent={100} strokeWidth={5} />63 </Box>64 </Col>65 <Col span={8} style={colStyle}>66 <Box67 title="Mini size circular progress bar"68 subtitle="A smaller circular progress bar."69 >70 <Progress type="circle" percent={30} width={80} />71 <Progress72 type="circle"73 percent={70}74 width={80}75 status="exception"76 />77 <Progress type="circle" percent={100} width={80} />78 </Box>79 </Col>80 <Col span={8} style={colStyle}>81 <Box82 title="Dynamic circular progress bar"83 subtitle="A dynamic progress bar is better."84 >85 <Progress type="circle" percent={this.state.percent} />86 <ButtonGroup>87 <Button onClick={this.decline} icon="minus" />88 <Button onClick={this.increase} icon="plus" />89 </ButtonGroup>90 </Box>91 </Col>92 </Row>93 <Box94 title="Custom text format"95 subtitle="You can custom text format by setting format."96 >97 <Progress98 type="circle"99 percent={75}100 format={percent => `${percent} Days`}101 />102 <Progress type="circle" percent={100} format={() => 'Done'} />103 </Box>104 <Box title="Dashboard" subtitle="A dashboard style of progress.">105 <Progress type="dashboard" percent={75} />106 </Box>107 </LayoutWrapper>108 );109 }...
bounce.ts
Source:bounce.ts
1/*2 * velocity-animate (C) 2014-2018 Julian Shapiro.3 *4 * Licensed under the MIT license. See LICENSE file in the project root for details.5 *6 * Bounce easings, based on code from https://github.com/yuichiroharai/easeplus-velocity7 */8// Project9import {registerEasing} from "./easings";10function easeOutBouncePercent(percentComplete: number): number {11 if (percentComplete < 1 / 2.75) {12 return (7.5625 * percentComplete * percentComplete);13 }14 if (percentComplete < 2 / 2.75) {15 return (7.5625 * (percentComplete -= 1.5 / 2.75) * percentComplete + 0.75);16 }17 if (percentComplete < 2.5 / 2.75) {18 return (7.5625 * (percentComplete -= 2.25 / 2.75) * percentComplete + 0.9375);19 }20 return (7.5625 * (percentComplete -= 2.625 / 2.75) * percentComplete + 0.984375);21}22function easeInBouncePercent(percentComplete: number): number {23 return 1 - easeOutBouncePercent(1 - percentComplete);24}25export function easeInBounce(percentComplete: number, startValue: number, endValue: number): number {26 if (percentComplete === 0) {27 return startValue;28 }29 if (percentComplete === 1) {30 return endValue;31 }32 return easeInBouncePercent(percentComplete) * (endValue - startValue);33}34export function easeOutBounce(percentComplete: number, startValue: number, endValue: number): number {35 if (percentComplete === 0) {36 return startValue;37 }38 if (percentComplete === 1) {39 return endValue;40 }41 return easeOutBouncePercent(percentComplete) * (endValue - startValue);42}43export function easeInOutBounce(percentComplete: number, startValue: number, endValue: number): number {44 if (percentComplete === 0) {45 return startValue;46 }47 if (percentComplete === 1) {48 return endValue;49 }50 return (percentComplete < 0.551 ? easeInBouncePercent(percentComplete * 2) * 0.552 : easeOutBouncePercent(percentComplete * 2 - 1) * 0.5 + 0.553 ) * (endValue - startValue);54}55registerEasing(["easeInBounce", easeInBounce]);56registerEasing(["easeOutBounce", easeOutBounce]);...
IOFTax.js
Source:IOFTax.js
1const taxes = [2 { day: 30, percent: 0 },3 { day: 29, percent: 3 },4 { day: 28, percent: 6 },5 { day: 27, percent: 10 },6 { day: 26, percent: 13 },7 { day: 25, percent: 16 },8 { day: 24, percent: 20 },9 { day: 23, percent: 23 },10 { day: 22, percent: 26 },11 { day: 21, percent: 30 },12 { day: 20, percent: 33 },13 { day: 19, percent: 36 },14 { day: 18, percent: 40 },15 { day: 17, percent: 43 },16 { day: 16, percent: 46 },17 { day: 15, percent: 50 },18 { day: 14, percent: 53 },19 { day: 13, percent: 56 },20 { day: 12, percent: 60 },21 { day: 11, percent: 63 },22 { day: 10, percent: 66 },23 { day: 9, percent: 70 },24 { day: 8, percent: 73 },25 { day: 7, percent: 76 },26 { day: 6, percent: 80 },27 { day: 5, percent: 83 },28 { day: 4, percent: 86 },29 { day: 3, percent: 90 },30 { day: 2, percent: 93 },31 { day: 1, percent: 96 }32]33const findTaxByDays = (days) => taxes.find((tax) => tax.day <= days)34class IOFTax {35 constructor (days) {36 this.days = days37 }38 percent () {39 return findTaxByDays(this.days).percent40 }41 percentOfValue (value) {42 const tax = findTaxByDays(this.days)43 const percentOfValue = value * (tax.percent / 100)44 return Number(percentOfValue.toFixed(2))45 }46}...
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3var options = {4 basicAuth: {5 },6};7 if (err) return console.error(err);8 console.log(data);9});10wpt.getTestStatus('170331_5F_1a8a8d1a6b1d1a9c1e8f2e2f6a2d6a2a', function(err, data) {11 if (err) return console.error(err);12 console.log(data);13});14wpt.getTestResults('170331_5F_1a8a8d1a6b1d1a9c1e8f2e2f6a2d6a2a', function(err, data) {15 if (err) return console.error(err);16 console.log(data);17});18wpt.getLocations(function(err, data) {19 if (err) return console.error(err);20 console.log(data);21});22wpt.getTesters(function(err, data) {23 if (err) return console.error(err);24 console.log(data);25});26wpt.getTesters('Dulles', function(err, data) {
Using AI Code Generation
1var wpt = require('webpagetest');2var client = wpt('www.webpagetest.org');3}, function(err, data) {4 if (err) return console.error(err);5 console.log(data);6 client.getTestResults(data.data.testId, function(err, data) {7 if (err) return console.error(err);8 console.log(data);9 });10});11{ statusCode: 400,12 data: { response: [Object], statusCode: 400, statusText: 'Bad Request' } }13{ statusCode: 400,14 data: { response: [Object], statusCode: 400, statusText: 'Bad Request' } }15{ statusCode: 400,16 data: { response: [Object], statusCode: 400, statusText: 'Bad Request' } }17{ statusCode: 400,18 data: { response: [Object], statusCode: 400, statusText: 'Bad Request' } }
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3var options = { location: 'Dulles:Chrome', runs: 1, firstViewOnly: true, connectivity: 'Cable' };4wpt.runTest(url, options, function(err, data) {5 if (err) return console.error(err);6 wpt.getTestResults(data.data.testId, function(err, data) {7 if (err) return console.error(err);8 console.log('Speed Index: ' + data.data.average.firstView.SpeedIndex);9 console.log('Percent 1: ' + data.data.average.firstView.percentiles.SpeedIndex['1']);10 console.log('Percent 25: ' + data.data.average.firstView.percentiles.SpeedIndex['25']);11 console.log('Percent 50: ' + data.data.average.firstView.percentiles.SpeedIndex['50']);12 console.log('Percent 75: ' + data.data.average.firstView.percentiles.SpeedIndex['75']);13 console.log('Percent 99: ' + data.data.average.firstView.percentiles.SpeedIndex['99']);14 });15});16var wpt = require('webpagetest');17var wpt = new WebPageTest('www.webpagetest.org');18var options = { location: 'Dulles:Chrome', runs: 1, firstViewOnly: true, connectivity: 'Cable' };19wpt.runTest(url, options, function(err, data) {20 if (err) return console.error(err);21 wpt.getTestResults(data.data.testId, function(err, data) {22 if (err) return console.error(err);23 console.log('Speed Index: ' + data.data.average.firstView.SpeedIndex);24 console.log('Percent 1: ' + data.data.average.firstView.percentiles.SpeedIndex['1']);25 console.log('Percent 25: ' + data.data.average.firstView.percentiles.SpeedIndex['25']);26 console.log('Percent 50: ' + data.data.average.firstView.percentiles.SpeedIndex['50']);27 console.log('Percent 75: ' + data.data.average.firstView
Using AI Code Generation
1var wptools = require('wptools');2wptools.percent('en.wikipedia.org/wiki/Barack_Obama', function(data) {3 console.log(data);4});5var wptools = require('wptools');6wptools.percent('en.wikipedia.org/wiki/Barack_Obama', function(data) {7 console.log(data);8});9var wptools = require('wptools');10wptools.percent('en.wikipedia.org/wiki/Barack_Obama', function(data) {11 console.log(data);12});13var wptools = require('wptools');14wptools.percent('en.wikipedia.org/wiki/Barack_Obama', function(data) {15 console.log(data);16});17var wptools = require('wptools');18wptools.percent('en.wikipedia.org/wiki/Barack_Obama', function(data) {19 console.log(data);20});21var wptools = require('wptools');22wptools.percent('en.wikipedia.org/wiki/Barack_Obama', function(data) {23 console.log(data);24});25var wptools = require('wptools');26wptools.percent('en.wikipedia.org/wiki/Barack_Obama', function(data) {27 console.log(data);28});29var wptools = require('wptools');30wptools.percent('en.wikipedia.org/wiki/Barack_Obama', function(data) {31 console.log(data);32});33var wptools = require('wptools');34wptools.percent('en.wikipedia.org/wiki/Barack_Obama', function(data) {35 console.log(data);36});37var wptools = require('wptools');
Using AI Code Generation
1wpt.percent(4, 20, function(err, data) {2 if (err) {3 console.log(err);4 } else {5 console.log(data);6 }7});8wpt.percent(4, 20, function(err, data) {9 if (err) {10 console.log(err);11 } else {12 console.log(data);13 }14});15wpt.percent(4, 20, function(err, data) {16 if (err) {17 console.log(err);18 } else {19 console.log(data);20 }21});22wpt.percent(4, 20, function(err, data) {23 if (err) {24 console.log(err);25 } else {26 console.log(data);27 }28});29wpt.percent(4, 20, function(err, data) {30 if (err) {31 console.log(err);32 } else {33 console.log(data);34 }35});36wpt.percent(4, 20, function(err, data) {37 if (err) {38 console.log(err);39 } else {40 console.log(data);41 }42});43wpt.percent(4, 20, function(err, data) {44 if (err) {45 console.log(err);46 } else {47 console.log(data);48 }49});50wpt.percent(4, 20, function(err, data) {51 if (err) {52 console.log(err);53 } else {54 console.log(data);55 }56});57wpt.percent(4, 20, function(err, data) {58 if (err) {59 console.log(err);60 } else {61 console.log(data);62 }63});
Using AI Code Generation
1console.log('start');2var wpt = require('webpagetest');3var test = new wpt('API_KEY');4 if (err) return console.log(err);5 console.log(data);6 test.getTestStatus(data.data.testId, function(err, data) {7 if (err) return console.log(err);8 console.log(data);9 });10});11test.getTestStatus('140410_8A_1B', function(err, data) {12 if (err) return console.log(err);13 console.log(data);14});15test.getTestStatus('140410_8A_1B', function(err, data) {16 if (err) return console.log(err);17 console.log(data);18});19test.getTestStatus('140410_8A_1B', function(err, data) {20 if (err) return console.log(err);21 console.log(data);22});23test.getTestStatus('140410_8A_1B', function(err, data) {24 if (err) return console.log(err);25 console.log(data);26});27test.getTestStatus('140410_8A_1B', function(err, data) {28 if (err) return console.log(err);29 console.log(data);30});31test.getTestStatus('140410_8A_1B', function(err, data) {32 if (err) return console.log(err);33 console.log(data);34});35test.getTestStatus('140410_8A_1B', function(err, data) {36 if (err) return console.log(err);37 console.log(data);38});39test.getTestStatus('140410_8A_1B', function(err, data) {40 if (err) return console.log(err);41 console.log(data);42});43test.getTestStatus('140410_8A_1B', function(err, data
Using AI Code Generation
1var wpt = require('wpt');2wpt.percent(100, 200, function(err, res) {3 if(!err) {4 console.log(res);5 }6});7var wpt = require('wpt');8wpt.percent(100, 200, true, function(err, res) {9 if(!err) {10 console.log(res);11 }12});13var wpt = require('wpt');14wpt.percent(100, 200, false, function(err, res) {15 if(!err) {16 console.log(res);17 }18});19var wpt = require('wpt');20wpt.percent(100, 200, true, function(err, res) {21 if(!err) {22 console.log(res);23 }24});25var wpt = require('wpt');26wpt.percent(100, 200, false, function(err, res) {27 if(!err) {28 console.log(res);29 }30});31var wpt = require('wpt');32wpt.percent(100, 200, true, function(err, res) {33 if(!err) {34 console.log(res);35 }36});37var wpt = require('wpt');38wpt.percent(100, 200, false, function(err, res) {39 if(!err) {40 console.log(res);41 }42});43var wpt = require('wpt');44wpt.percent(100, 200, true, function(err, res) {45 if(!err) {46 console.log(res);47 }48});49var wpt = require('wpt');50wpt.percent(100, 200, false, function(err, res) {51 if(!err) {52 console.log(res);53 }54});
Using AI Code Generation
1var wpt = require('wpt');2wpt.getTestResults('testID', function(err, data) {3 console.log(err, data);4});5var wpt = require('wpt');6wpt.getTestResults('testID', {json: true}, function(err, data) {7 console.log(err, data);8});9var wpt = require('wpt');10wpt.getTestResults('testID', {json: true, breakDown: true}, function(err, data) {11 console.log(err, data);12});13var wpt = require('wpt');14wpt.getTestResults('testID', {json: true, breakDown: true, requests: true}, function(err, data) {15 console.log(err, data);16});17var wpt = require('wpt');18wpt.getTestResults('testID', {json: true, breakDown: true, requests: true, pagespeed: true}, function(err, data) {19 console.log(err, data);20});21var wpt = require('wpt');22wpt.getTestResults('testID', {json: true, breakDown: true, requests: true, pagespeed: true, pageSpeedVersion: 2}, function(err, data) {23 console.log(err, data);24});25var wpt = require('wpt');26wpt.getTestResults('testID', {json: true, breakDown: true, requests: true, pagespeed: true, pageSpeedVersion: 2, video: true}, function(err, data) {27 console.log(err, data);28});29var wpt = require('wpt');30wpt.getTestResults('testID', {json: true, breakDown: true, requests: true, pagespeed: true, pageSpeedVersion: 2, video: true, timeline:
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new wpt('API_KEY');3wpt.percent('test', function(err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});
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!!