Best JavaScript code snippet using wpt
index.js
Source:index.js
1// Copyright (c) 2018 ml52//3// This software is released under the MIT License.4// https://opensource.org/licenses/MIT5/* eslint prefer-destructuring: ["error", {AssignmentExpression: {array: false}}] */6/* eslint no-await-in-loop: "off" */7/*8A LSTM Generator: Run inference mode for a pre-trained LSTM.9*/10import * as tf from "@tensorflow/tfjs"11import sampleFromDistribution from "./utils/sample"12import CheckpointLoader from "./utils/checkpointLoader"13import callCallback from "./utils/callcallback"14const regexCell = /cell_[0-9]|lstm_[0-9]/gi15const regexWeights = /weights|weight|kernel|kernels|w/gi16const regexFullyConnected = /softmax/gi17class CharRNN {18 constructor(modelPath, callback) {19 this.ready = false20 this.model = {}21 this.cellsAmount = 022 this.cells = []23 this.zeroState = { c: [], h: [] }24 this.state = { c: [], h: [] }25 this.vocab = {}26 this.vocabSize = 027 this.probabilities = []28 this.defaults = {29 seed: "a", // TODO: use no seed by default30 length: 20,31 temperature: 0.5,32 stateful: false,33 }34 this.ready = callCallback(this.loadCheckpoints(modelPath), callback)35 // this.then = this.ready.then.bind(this.ready);36 }37 resetState() {38 this.state = this.zeroState39 }40 setState(state) {41 this.state = state42 }43 getState() {44 return this.state45 }46 async loadCheckpoints(path) {47 const reader = new CheckpointLoader(path)48 const vars = await reader.getAllVariables()49 Object.keys(vars).forEach(key => {50 if (key.match(regexCell)) {51 if (key.match(regexWeights)) {52 this.model[`Kernel_${key.match(/[0-9]/)[0]}`] = vars[key]53 this.cellsAmount += 154 } else {55 this.model[`Bias_${key.match(/[0-9]/)[0]}`] = vars[key]56 }57 } else if (key.match(regexFullyConnected)) {58 if (key.match(regexWeights)) {59 this.model.fullyConnectedWeights = vars[key]60 } else {61 this.model.fullyConnectedBiases = vars[key]62 }63 } else {64 this.model[key] = vars[key]65 }66 })67 await this.loadVocab(path)68 await this.initCells()69 return this70 }71 async loadVocab(path) {72 const json = await fetch(`${path}/vocab.json`)73 .then(response => response.json())74 .catch(err => console.error(err))75 this.vocab = json76 this.vocabSize = Object.keys(json).length77 }78 async initCells() {79 this.cells = []80 this.zeroState = { c: [], h: [] }81 const forgetBias = tf.tensor(1.0)82 const lstm = i => {83 const cell = (DATA, C, H) =>84 tf.basicLSTMCell(85 forgetBias,86 this.model[`Kernel_${i}`],87 this.model[`Bias_${i}`],88 DATA,89 C,90 H,91 )92 return cell93 }94 for (let i = 0; i < this.cellsAmount; i += 1) {95 this.zeroState.c.push(tf.zeros([1, this.model[`Bias_${i}`].shape[0] / 4]))96 this.zeroState.h.push(tf.zeros([1, this.model[`Bias_${i}`].shape[0] / 4]))97 this.cells.push(lstm(i))98 }99 this.state = this.zeroState100 }101 async generateInternal(options) {102 await this.ready103 const seed = options.seed || this.defaults.seed104 const length = +options.length || this.defaults.length105 const temperature = +options.temperature || this.defaults.temperature106 const stateful = options.stateful || this.defaults.stateful107 if (!stateful) {108 this.state = this.zeroState109 }110 const results = []111 const userInput = Array.from(seed)112 const encodedInput = []113 userInput.forEach(char => {114 encodedInput.push(this.vocab[char])115 })116 let input = encodedInput[0]117 let probabilitiesNormalized = [] // will contain final probabilities (normalized)118 for (let i = 0; i < userInput.length + length + -1; i += 1) {119 const onehotBuffer = tf.buffer([1, this.vocabSize])120 onehotBuffer.set(1.0, 0, input)121 const onehot = onehotBuffer.toTensor()122 let output123 if (this.model.embedding) {124 const embedded = tf.matMul(onehot, this.model.embedding)125 output = tf.multiRNNCell(126 this.cells,127 embedded,128 this.state.c,129 this.state.h,130 )131 } else {132 output = tf.multiRNNCell(this.cells, onehot, this.state.c, this.state.h)133 }134 this.state.c = output[0]135 this.state.h = output[1]136 const outputH = this.state.h[1]137 const weightedResult = tf.matMul(138 outputH,139 this.model.fullyConnectedWeights,140 )141 const logits = tf.add(weightedResult, this.model.fullyConnectedBiases)142 const divided = tf.div(logits, tf.tensor(temperature))143 const probabilities = tf.exp(divided)144 probabilitiesNormalized = await tf145 .div(probabilities, tf.sum(probabilities))146 .data()147 if (i < userInput.length - 1) {148 input = encodedInput[i + 1]149 } else {150 input = sampleFromDistribution(probabilitiesNormalized)151 results.push(input)152 }153 }154 let generated = ""155 results.forEach(char => {156 const mapped = Object.keys(this.vocab).find(157 key => this.vocab[key] === char,158 )159 if (mapped) {160 generated += mapped161 }162 })163 this.probabilities = probabilitiesNormalized164 return {165 sample: generated,166 state: this.state,167 }168 }169 reset() {170 this.state = this.zeroState171 }172 // stateless173 async generate(options, callback) {174 this.reset()175 return callCallback(this.generateInternal(options), callback)176 }177 // stateful178 async predict(temp, callback) {179 let probabilitiesNormalized = []180 const temperature = temp > 0 ? temp : 0.1181 const outputH = this.state.h[1]182 const weightedResult = tf.matMul(outputH, this.model.fullyConnectedWeights)183 const logits = tf.add(weightedResult, this.model.fullyConnectedBiases)184 const divided = tf.div(logits, tf.tensor(temperature))185 const probabilities = tf.exp(divided)186 probabilitiesNormalized = await tf187 .div(probabilities, tf.sum(probabilities))188 .data()189 const sample = sampleFromDistribution(probabilitiesNormalized)190 const result = Object.keys(this.vocab).find(191 key => this.vocab[key] === sample,192 )193 this.probabilities = probabilitiesNormalized194 if (callback) {195 callback(result)196 }197 /* eslint max-len: ["error", { "code": 180 }] */198 const pm = Object.keys(this.vocab).map(c => ({199 char: c,200 probability: this.probabilities[this.vocab[c]],201 }))202 return {203 sample: result,204 probabilities: pm,205 }206 }207 async feed(inputSeed, callback) {208 await this.ready209 const seed = Array.from(inputSeed)210 const encodedInput = []211 seed.forEach(char => {212 encodedInput.push(this.vocab[char])213 })214 let input = encodedInput[0]215 for (let i = 0; i < seed.length; i += 1) {216 const onehotBuffer = tf.buffer([1, this.vocabSize])217 onehotBuffer.set(1.0, 0, input)218 const onehot = onehotBuffer.toTensor()219 let output220 if (this.model.embedding) {221 const embedded = tf.matMul(onehot, this.model.embedding)222 output = tf.multiRNNCell(223 this.cells,224 embedded,225 this.state.c,226 this.state.h,227 )228 } else {229 output = tf.multiRNNCell(this.cells, onehot, this.state.c, this.state.h)230 }231 this.state.c = output[0]232 this.state.h = output[1]233 input = encodedInput[i]234 }235 if (callback) {236 callback()237 }238 }239}240const charRNN = (modelPath = "./", callback) => new CharRNN(modelPath, callback)241export default charRNN...
caesar.js
Source:caesar.js
1// Please refrain from tampering with the setup code provided here,2// as the index.html and test files rely on this setup to work properly.3// Only add code (helper methods, variables, etc.) within the scope4// of the anonymous function on line 65const caesarModule = (function () {6 // you can add any code you want within this function scope7 function caesar(input, shift, encode = true) {8 const alphabets=[9 'A','B','C','D','E',10 'F','G','H','I','J','K',11 'L','M','N','O','P','Q','R',12 'S', 'T','U','V','W','X','Y','Z'13 ]14if(!shift || shift< -25 || shift>25) return false15const helperFuncOne=(input) =>{16 return input.toUpperCase().split('').map(character => {17 if(alphabets.indexOf(character)!==-1){18 return alphabets.indexOf(character)19 }else{20 return character21 }22 })23}24 if(shift>0 && encode){25let encodedInput=''26 const modifiedInputToArrayAndGetIndex=helperFuncOne(input)27 for(let index of modifiedInputToArrayAndGetIndex){28 if(typeof index ==='string'){29 encodedInput+=index30 continue31 }32 let addIndexAndShift=index+shift33 if(addIndexAndShift <=25) {34 encodedInput+=alphabets[addIndexAndShift]35 }else {36 let totalIndexInAlphabets=2537 while(addIndexAndShift>totalIndexInAlphabets){38 addIndexAndShift-=totalIndexInAlphabets39 if(addIndexAndShift<=25){40 encodedInput+=alphabets[addIndexAndShift-1]41 break42 }43 }44 }45 }46return encodedInput.toLowerCase()47 }48 else if(shift <0 && encode){49 let encodedInput=''50 const modifiedInputToArrayAndGetIndex=helperFuncOne(input)51 for(let index of modifiedInputToArrayAndGetIndex){52 if(typeof index ==='string'){53 encodedInput+=index54 continue55 }56 let addIndexAndShift=index+shift57 if(Math.sign(addIndexAndShift)===1 ) {58 encodedInput+=alphabets[addIndexAndShift]59 }else{60 let totalIndexInAlphabets=2561 while(addIndexAndShift<0){62 addIndexAndShift+=totalIndexInAlphabets63 if(addIndexAndShift>=0){64 encodedInput+=alphabets[addIndexAndShift+1]65 break66 }67 68 }69 }70 71 }72 return encodedInput.toLowerCase()73 }else if(shift>0 && !encode){74 let decodedInput=''75 const modifiedInputToArrayAndGetIndex=helperFuncOne(input)76 for(let index of modifiedInputToArrayAndGetIndex){77 if(typeof index ==='string'){78 decodedInput+=index79 continue80 }81 let addIndexAndShift=index-shift82 if(Math.sign(addIndexAndShift)===1 || addIndexAndShift===0) {83 decodedInput+=alphabets[addIndexAndShift]84 }else{85 let totalIndexInAlphabets=2586 while(addIndexAndShift<0){87 addIndexAndShift+=totalIndexInAlphabets88 if(addIndexAndShift>=0){89 decodedInput+=alphabets[addIndexAndShift+1]90 break91 }92 93 }94 }95 96 }97 return decodedInput.toLowerCase()98 }else if(shift <0 && !encode){99let encodedInput=''100const modifiedInputToArrayAndGetIndex=helperFuncOne(input)101for(let index of modifiedInputToArrayAndGetIndex){102 if(typeof index ==='string'){103 encodedInput+=index104 continue105 }106 let addIndexAndShift=index-shift107 if(addIndexAndShift <=25) {108 encodedInput+=alphabets[addIndexAndShift]109 }else {110 let totalIndexInAlphabets=25111 while(addIndexAndShift>totalIndexInAlphabets){112 addIndexAndShift-=totalIndexInAlphabets113 if(addIndexAndShift<=25){114 encodedInput+=alphabets[addIndexAndShift-1]115 break116 }117 }118 }119}120return encodedInput.toLowerCase()121 }122 }123 return {124 caesar,125 };126})();...
355.1.js
Source:355.1.js
1const alphabet = "abcdefghijklmnopqrstuvwxyz";2const rotate = n => {3 const slice = alphabet.slice(0, n);4 return alphabet.slice(n).concat(slice);5};6const getCodeString = (keyWord, length) => {7 const keyLength = keyWord.length;8 if (!keyLength) {9 return "";10 }11 return keyWord.repeat(Math.ceil(length / keyLength));12};13const encode = (keyWord, input) => {14 const codeString = getCodeString(keyWord, input.length);15 return input16 .split("")17 .map((letter, index) => {18 const rotatedAlphabet = rotate(alphabet.indexOf(letter));19 return rotatedAlphabet[alphabet.indexOf(codeString.charAt(index))];20 })21 .join("");22};23const decode = (keyWord, encodedInput) => {24 const codeString = getCodeString(keyWord, encodedInput.length);25 return encodedInput26 .split("")27 .map((letter, index) => {28 const rotatedAlphabet = rotate(29 alphabet.indexOf(codeString.charAt(index))30 );31 return alphabet[rotatedAlphabet.indexOf(letter)];32 })33 .join("");34};...
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.runTest(testURL, function(err, data) {4 if (err) return console.error(err);5 wpt.getTestStatus(data.data.testId, function(err, data) {6 if (err) return console.error(err);7 console.log('Test status:');8 console.log(data);9 });10});11var wpt = require('webpagetest');12var wpt = new WebPageTest('www.webpagetest.org');13wpt.runTest(testURL, function(err, data) {14 if (err) return console.error(err);15 wpt.getTestResults(data.data.testId, function(err, data) {16 if (err) return console.error(err);17 console.log('Test status:');18 console.log(data);19 });20});
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.12345678901234567890123456789012');3wpt.runTest('www.webpagetest.org', {location: 'Dulles:Chrome'}, function(err, data) {4 if (err) return console.error(err);5 console.log('Test status:', data.statusText);6 if (data.statusCode == 200) {7 console.log('Test started:', data.data.testUrl);8 console.log('Test ID:', data.data.testId);9 }10});
Using AI Code Generation
1var wptools = require('wptools');2var encodedInput = wptools.encodedInput;3var options = {4};5var page = wptools.page('Albert Einstein', options);6page.get(function(err, info, raw) {7 if (err) {8 console.log(err);9 } else {10 console.log(info);11 }12});13var wptools = require('wptools');14var encodedInput = wptools.encodedInput;15var options = {16};17var page = wptools.page('Albert Einstein', options);18page.get(function(err, info, raw) {19 if (err) {20 console.log(err);21 } else {22 console.log(info);23 }24});25[MIT](LICENSE)
Using AI Code Generation
1var wpt = require('wpt-client');2wpt.getTestInfo('testID', function(err, data) {3 if (err) {4 console.log(err);5 } else {6 console.log(data);7 }8});9MIT © [Rajesh](
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!!