Best JavaScript code snippet using wpt
awardHierarchyShared.js
Source:awardHierarchyShared.js
...15 * 16 * You should have received a copy of the GNU Affero General Public License17 * along with this program. If not, see <http://www.gnu.org/licenses/>.18 */19function RequestTracker(liNode, callback) {20 this.liNode = liNode;21 this.callback = callback;22 this.startDate = new Date;23 this.children = null;24}25var DEBUG = false;26function debugLog(str) {27 console.log(str);28}29jQuery(document).ready(function(){30 jQuery('#awardHierarchyScrollable').scroll(function() {saveScrollPosition(this);});31 jQuery.ajaxSettings.cache = false; 32 jQuery("#awardhierarchy").treeview({33 toggle: function() {34 //this method must be implemented by the page, not here in shared funcs35 treeViewToggle(this); 36 },37 animated: "fast",38 collapsed: true,39 control: "#treecontrol"40 });41 jQuery('#treecontrol').hide();42 jQuery('#shownCollapseLink').click(function() {43 jQuery('#treecontrol a:eq(0)').click();44 });45 46 jQuery('#shownExpandLink').click(function() {47 if (jQuery('#awardhierarchy').find('li.expandable').length > 0) {48 forceLoading();49 jQuery('li.expandable').each(function() {50 var liItem = this;51 queueToggle(liItem, expandAll); 52 });53 }54 });55}); // $(document).ready56function expandAll(requestTracker) {57 if (requestTracker.liNode != null) {58 jQuery(requestTracker.liNode).find('div.expandable-hitarea:first').click();59 }60 jQuery(requestTracker.children).each(function() {61 queueToggle(this, expandAll);62 });63 if (activeRequest != null) {64 debugLog('Active Request - ' + getAwardNumber(activeRequest.liNode));65 }66 logPending();67 if (activeRequest == null && pendingRequests.length == 0) {68 clearForceLoading();69 }70 71}72var pendingRequests = [];73var activeRequest;74var forceLoadingMessage = null;75function showLoading() {76 jQuery('#loading span.statusMessage').html('Loading ' + (pendingRequests.length) + ' items');77 jQuery('#loading').show();78}79function logPending() {80 var str = 'pending requests = ';81 jQuery(pendingRequests).each(function() {82 str += getAwardNumber(this.liNode) + ',';83 });84 debugLog(str);85}86function finishLoading(requestTracker) {87 debugLog('finished loading something');88 logPending();89 if (requestTracker == activeRequest) {90 activeRequest = null;91 }92 if (requestTracker != null && requestTracker.callback != null) {93 requestTracker.callback(requestTracker);94 }95 if (pendingRequests.length > 0 && activeRequest == null) {96 activeRequest = pendingRequests.shift() 97 loadChildren(activeRequest);98 } else if (activeRequest == null) {99 if(!forceLoadingMessage) {100 jQuery('#loading').hide();101 }102 fixDatePickers(); 103 }104}105function forceLoading() {106 debugLog('forcing loading message to be displayed until cleared');107 forceLoadingMessage = true;108 showLoading();109}110function clearForceLoading() {111 debugLog('clearing forced loading message');112 forceLoadingMessage = false;113 finishLoading(null);114}115function queueToggle(liNode, callback) {116 var requestTracker = new RequestTracker(liNode, callback);117 showLoading();118 if (pendingRequests.length <= 0 && activeRequest == null) {119 activeRequest = requestTracker;120 loadChildren(requestTracker);121 } else {122 pendingRequests.push(requestTracker);123 }124}125 126function fixDatePickers(listItem) {127 //when loading children, we must remove all of the previous images and scripts. Otherwise, there will be multiple128 //datepickers added to each cell depending on how deep we dig into the hierarchy and how many times we toggle.129 jQuery('.datepickerImage').remove();130 jQuery('.datepickerScript').remove();...
auth.service.ts
Source:auth.service.ts
...26 async isUsernameOverRateLimit_old(27 username: string,28 ): Promise<RateLimitResponse> {29 const requestTracker =30 this.RequestsByUser.get(username) || new RequestTracker();31 const timeDifference = AuthService.calculateTimeDifference(requestTracker);32 // reset rate limit if over time limit.33 if (this.isOverTimeLimit(timeDifference)) {34 this.RequestsByUser.set(username, new RequestTracker());35 return new RateLimitResponse(false, null);36 }37 // return a response if the user is over the limit.38 const numberOfPreviousRequests = requestTracker.numberOfRequests;39 if (numberOfPreviousRequests >= this.MAX_REQUESTS_PER_TOKEN) {40 return new RateLimitResponse(true, new Date(this.calculateResetAtTime()));41 }42 // if not over limit, return false43 requestTracker.addRequest();44 this.RequestsByUser.set(username, requestTracker);45 return new RateLimitResponse(false, null);46 }47 async isUsernameOverRateLimit(username: string): Promise<RateLimitResponse> {48 return this.cacheManager.get(username).then((res: any) => {49 const requestTracker = AuthService.loadRequestTrackerFromRedisObject(res);50 const timeDifference =51 AuthService.calculateTimeDifference(requestTracker);52 // reset rate limit if over time limit.53 if (this.isOverTimeLimit(timeDifference)) {54 this.cacheManager.set(username, new RequestTracker());55 return new RateLimitResponse(false, null);56 }57 // return a response if the user is over the limit.58 const numberOfPreviousRequests = requestTracker.numberOfRequests;59 if (numberOfPreviousRequests >= this.MAX_REQUESTS_PER_TOKEN) {60 return new RateLimitResponse(61 true,62 new Date(this.calculateResetAtTime()),63 );64 }65 // if not over limit, return false66 requestTracker.addRequest();67 this.cacheManager.set(username, requestTracker);68 return new RateLimitResponse(false, null);69 });70 }71 async isIPOverRateLimit(ipAddress: string): Promise<RateLimitResponse> {72 return this.cacheManager.get(ipAddress).then((res: any) => {73 const requestTracker = AuthService.loadRequestTrackerFromRedisObject(res);74 const timeDifference =75 AuthService.calculateTimeDifference(requestTracker);76 if (this.isOverTimeLimit(timeDifference)) {77 this.cacheManager.set(ipAddress, new RequestTracker());78 return new RateLimitResponse(false, null);79 }80 const numberOfPreviousRequests = requestTracker.numberOfRequests;81 if (numberOfPreviousRequests >= this.MAX_REQUESTS_PER_IP) {82 return new RateLimitResponse(true, this.calculateResetAtTime());83 }84 requestTracker.addRequest();85 this.cacheManager.set(ipAddress, requestTracker);86 return new RateLimitResponse(false, null);87 });88 }89 private static loadRequestTrackerFromRedisObject(res: any) {90 let requestTracker: RequestTracker;91 if (res == null) {92 requestTracker = new RequestTracker();93 } else {94 requestTracker = new RequestTracker();95 requestTracker._numberOfRequests = res._numberOfRequests;96 requestTracker._timeOfFirstRequest = new Date(res._timeOfFirstRequest);97 }98 return requestTracker;99 }100 private static calculateTimeDifference(requestTracker: RequestTracker) {101 const currentTime = new Date();102 const timeOfFirstRequest: Date = requestTracker._timeOfFirstRequest;103 return Math.abs(currentTime.getTime() - timeOfFirstRequest.getTime());104 }105 private calculateResetAtTime() {106 const currentTime = new Date();107 const limitResetTimeMilliseconds: number = parseInt(108 this.configService.get('RATE_LIMIT_RESET_TIME_IN_MILLISECONDS'),...
transport.js
Source:transport.js
1// @flow2import $ from 'jquery'3import { DEFAULT_LOCALE } from '_/intl'4import uniqueId from 'lodash/uniqueId'5import { Exception } from '../exceptions'6import Selectors from '../selectors'7//8// SSO Token Checks9//10/**11 * Return the SSO token for the current user session12 */13function _getLoginToken (): string {14 return Selectors.getLoginToken()15}16/**17 * Throw an Exception if the current user session SSO token is missing or expired.18 */19function assertLogin ({ methodName }: { methodName: string }) {20 if (!_getLoginToken()) {21 throw new Exception(`OvirtApi in '${methodName}': missing login`)22 }23 if (Selectors.isTokenExpired()) {24 throw new Exception(`OvirtApi in '${methodName}': sso token is expired`)25 }26}27//28// HTTP Listener Handling29//30type MethodType = 'GET' | 'POST' | 'PUT' | 'DELETE'31type RequestTrackerType = {32 method: MethodType,33 url: string,34 uid: string35}36type ListenerType = (requestTracker: RequestTrackerType, eventType: 'START' | 'STOP') => void37const listeners: Set<ListenerType> = new Set()38function addHttpListener (listener: ListenerType) {39 listeners.add(listener)40}41let currentLocale = DEFAULT_LOCALE42function updateLocale (locale: string) {43 currentLocale = locale44}45function notifyStart (method: MethodType, url: string): RequestTrackerType {46 const requestTracker = { method, url, uid: uniqueId('t_') }47 listeners.forEach(listener => listener(requestTracker, 'START'))48 return requestTracker49}50function notifyStop (requestTracker: RequestTrackerType) {51 listeners.forEach(listener => listener(requestTracker, 'STOP'))52}53//54// HTTP Verbs55//56type GetRequestType = { url: string, custHeaders?: Object}57type InputRequestType = { url: string, input: string, contentType?: string }58type DeleteRequestType = { url: string, custHeaders?: Object }59const logHeaders = (headers) => JSON.stringify({ ...headers, Authorization: '*****' })60function httpGet ({ url, custHeaders = {} }: GetRequestType): Promise<Object> {61 const requestTracker = notifyStart('GET', url)62 const headers = {63 Accept: 'application/json',64 Authorization: `Bearer ${_getLoginToken()}`,65 'Accept-Language': currentLocale,66 Filter: Selectors.getFilter(),67 ...custHeaders,68 }69 console.log(`http GET[${requestTracker.uid}] ð¡ url: "${url}", headers: ${logHeaders(headers)}`)70 return $.ajax(url, {71 type: 'GET',72 headers,73 })74 .then((data: Object): Object => {75 notifyStop(requestTracker)76 console.log(`http GET[${requestTracker.uid}] ð¡ data:`, data)77 return data78 })79 .catch((data: Object): Promise<Object> => {80 console.log(`Ajax GET failed: ${JSON.stringify(data)}`)81 notifyStop(requestTracker)82 return Promise.reject(data)83 })84}85function httpPost ({ url, input, contentType = 'application/json' }: InputRequestType): Promise<Object> {86 const requestTracker = notifyStart('POST', url)87 return $.ajax(url, {88 type: 'POST',89 headers: {90 Accept: 'application/json',91 Authorization: `Bearer ${_getLoginToken()}`,92 'Accept-Language': currentLocale,93 Filter: Selectors.getFilter(),94 'Content-Type': contentType,95 },96 data: input,97 })98 .then((data: Object): Object => {99 notifyStop(requestTracker)100 return data101 })102 .catch((data: Object): Promise<Object> => {103 console.log(`Ajax POST failed: ${JSON.stringify(data)}`)104 notifyStop(requestTracker)105 return Promise.reject(data)106 })107}108function httpPut ({ url, input, contentType = 'application/json' }: InputRequestType): Promise<Object> {109 const requestTracker = notifyStart('PUT', url)110 return $.ajax(url, {111 type: 'PUT',112 headers: {113 Accept: 'application/json',114 Authorization: `Bearer ${_getLoginToken()}`,115 'Accept-Language': currentLocale,116 Filter: Selectors.getFilter(),117 'Content-Type': contentType,118 },119 data: input,120 })121 .then((data: Object): Object => {122 notifyStop(requestTracker)123 return data124 })125 .catch((data: Object): Promise<Object> => {126 console.log(`Ajax PUT failed: ${JSON.stringify(data)}`)127 notifyStop(requestTracker)128 return Promise.reject(data)129 })130}131function httpDelete ({ url, custHeaders = { Accept: 'application/json' } }: DeleteRequestType): Promise<Object> {132 const requestTracker = notifyStart('DELETE', url)133 return $.ajax(url, {134 type: 'DELETE',135 headers: {136 Authorization: `Bearer ${_getLoginToken()}`,137 Filter: Selectors.getFilter(),138 ...custHeaders,139 },140 })141 .then((data: Object): Object => {142 notifyStop(requestTracker)143 return data144 })145 .catch((data: Object): Promise<Object> => {146 console.log(`Ajax DELETE failed: ${JSON.stringify(data)}`)147 notifyStop(requestTracker)148 return Promise.reject(data)149 })150}151//152// Exports153//154export type {155 MethodType,156 RequestTrackerType,157 ListenerType,158}159export {160 addHttpListener,161 updateLocale,162 assertLogin,163 httpGet,164 httpPost,165 httpPut,166 httpDelete,...
Using AI Code Generation
1var wpt = require('webpagetest');2var request = wpt('www.webpagetest.org');3var options = {4};5 if (err) {6 console.log(err);7 } else {8 console.log(data);9 }10});11var wpt = require('webpagetest');12var api = wpt('www.webpagetest.org');13var options = {14};15 if (err) {16 console.log(err);17 } else {18 console.log(data);19 }20});
Using AI Code Generation
1var wpt = require('webpagetest');2var util = require('util');3var test = new wpt('www.webpagetest.org', 'A.90e2e2c1f1d1d0b7b8c0f8f7e6c9c6d9');4test.getLocations(function(err, data) {5 if (err) console.log(err);6 else console.log(util.inspect(data, false, null));7});8var wpt = require('webpagetest');9var util = require('util');10var test = new wpt('www.webpagetest.org', 'A.90e2e2c1f1d1d0b7b8c0f8f7e6c9c6d9');11test.getLocations(function(err, data) {12 if (err) console.log(err);13 else console.log(util.inspect(data, false, null));14});15var wpt = require('webpagetest');16var util = require('util');17var test = new wpt('www.webpagetest.org', 'A.90e2e2c1f1d1d0b7b8c0f8f7e6c9c6d9');18test.getLocations(function(err, data) {19 if (err) console.log(err);20 else console.log(util.inspect(data, false, null));21});22var wpt = require('webpagetest');23var util = require('util');24var test = new wpt('www.webpagetest.org', 'A.90e2e2c1f1d1d0b7b8c0f8f7e6c9c6d9');25test.getLocations(function(err, data) {26 if (err) console.log(err);27 else console.log(util.inspect(data, false, null));28});29var wpt = require('webpagetest');30var util = require('util');31var test = new wpt('www.webpagetest.org', 'A.90e2e
Using AI Code Generation
1var wpt = require('webpagetest');2var request = new wpt('www.webpagetest.org', 'A.8c1a1e0b7f0c9d1b9e6c4f6a0c0f5a5a');3request.getTestStatus('170204_2B_2d9b9b1f1a0a7a5e5e5b5f5c5a5a5c5f', function(err, data) {4 console.log(data);5});6var wpt = require('webpagetest');7var request = new wpt('www.webpagetest.org', 'A.8c1a1e0b7f0c9d1b9e6c4f6a0c0f5a5a');8request.getTestStatus('170204_2B_2d9b9b1f1a0a7a5e5e5b5f5c5a5a5c5f', function(err, data) {9 console.log(data);10});11var wpt = require('webpagetest');12var request = new wpt('www.webpagetest.org', 'A.8c1a1e0b7f0c9d1b9e6c4f6a0c0f5a5a');13request.getTestStatus('170204_2B_2d9b9b1f1a0a7a5e5e5b5f5c5a5a5c5f', function(err, data) {14 console.log(data);15});16var wpt = require('webpagetest');17var request = new wpt('www.webpagetest.org', 'A.8c1a1e0b7f0c9d1b9e6c4f6a0c0f5a5a');18request.getTestStatus('170204
Using AI Code Generation
1var wpt = require('webpagetest');2var request = require('request');3var options = {4};5var wpt = new WebPageTest('www.webpagetest.org', 'A.4d1e4f8b8a1fd1d9a2f2d9b8c8e8f8e1');6 if (err) return console.error(err);7 console.log('Test status:', data.statusText);8 console.log('Test ID:', data.data.testId);9 console.log('Test URL:', data.data.userUrl);10 console.log('Test results:', data.data.summary);11});12var wpt = require('webpagetest');13var request = require('request');14var options = {15};16var wpt = new WebPageTest('www.webpagetest.org', 'A.4d1e4f8b8a1fd1d9a2f2d9b8c8e8f8e1');17 if (err) return console.error(err);18 console.log('Test status:', data.statusText);19 console.log('Test ID:', data.data.testId);20 console.log('Test URL:', data.data.userUrl);21 console.log('Test results:', data.data.summary);22});23var wpt = require('webpagetest');24var request = require('request');25var options = {26};27var wpt = new WebPageTest('www
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!!