Best JavaScript code snippet using wpt
HaskellServer.js
Source:HaskellServer.js  
...23// -=-=-=-=-=-=-=-=-=-=-=-=-=-24var haskellState = global.haskellState || (global.haskellState = {processes: []});25global.printHaskellServerState = function printHaskellServerState(thenDo) {26    27    function printEvalState(evalState, i) {28        return util.format(29            "%s: id: %s, expr: %s, enqueueTime: %s, startTime: %s, endTime: %s, hasCallback: %s, result %s",30            i,31            evalState.id,32            evalState._options.expr.replace(/\n/g, '').slice(0,40),33            new Date(evalState.enqueueTime),34            new Date(evalState.startTime),35            new Date(evalState.endTime),36            !!evalState._callback,37            JSON.stringify(evalState.result));38    }39    function printProcState(procState) {40        return [41            util.format(42                'process %s (prompt: %s, cwd: %s, running: %s)',43                procState.id,44                procState.prompt,45                procState.baseDirectory,46                procState.proc && !!procState.proc._handle)47        ].concat(procState.evalQueue.map(printEvalState)).join('\n  ');48    }49    var output = haskellState.processes.length ?50        haskellState.processes.map(printProcState).join('\n\n')51        : 'no haskell processes running';52    log(output);53    thenDo && thenDo(null, output);54}55global.resetHaskellState = function resetHaskellState(thenDo) {56    debug && log("Resetting Haskell processes and states...");57    if (haskellState.processes) {58        haskellState.processes.forEach(cancelAllQueuedEvals);59        haskellState.processes.forEach(stopProcess);60        haskellState.processes = [];61    }62    thenDo && thenDo(null);63}64// process.kill(process.pid, 'SIGUSR1')65// global.printHaskellServerState()66// haskellState.processes67// haskellState.processes[0].evalQueue[1]._options68// resetHaskellState();69function ensureProcessState(options) {70    for (var i = 0; i < haskellState.processes.length; i++) {71        var procState = haskellState.processes[i];72        if (procState.id === options.sessionId) return procState;73    }74    var procState = {75        id: options.sessionId,76        prompt: options.prompt || '>>',77        baseDirectory: options.baseDirectory || process.cwd(),78        proc: null,79        evalQueue: []80    };81    haskellState.processes.push(procState);82    return procState;83}84function getProcess(procState) { return procState.proc; }85function setProcess(procState, proc) { return procState.proc = proc; }86function removeProcess(procState) { procState.proc = null; }87function stopProcess(procState) { procState.proc && procState.proc.kill('SIGKILL'); }88function haskellProcessIsRunning(procState) { return procState.proc && !!procState.proc._handle; }89function initHaskellProcess(procState, thenDo) {90    log('initing haskell process...');91    var statements = [92        ":set prompt " + procState.prompt,93        ":cd " + procState.baseDirectory,94        //95        // ":def ghc-pkg (\\l->return $ \":!\"++GHC.Paths.ghc_pkg++\" \"++l)",96        // ":def browser (\\l->return $ \":!open file://\"++l)",97        // "let doc p = return $ \":browser \"++GHC.Paths.docdir++relative where { relative | p==\"\" = \"/index.html\" | otherwise = p }",98        // ":def doc doc",99        // "GHCi on Acid" http://www.haskell.org/haskellwiki/GHC/GHCi100        // "import qualified GOA",101        // "GOA.setLambdabotHome \"" + process.env.HOME + "/.cabal/bin\"",102        // ":def bs        GOA.lambdabot \"botsnack\"",103        // ":def pl        GOA.lambdabot \"pl\"",104        // ":def unpl      GOA.lambdabot \"unpl\"",105        // ":def redo      GOA.lambdabot \"redo\"",106        // ":def undo      GOA.lambdabot \"undo\"",107        // ":def index     GOA.lambdabot \"index\"",108        // ":def docs      GOA.lambdabot \"docs\"",109        // ":def instances GOA.lambdabot \"instances\"",110        // ":def hoogle    GOA.lambdabot \"hoogle\"",111        // ":def source    GOA.lambdabot \"fptools\"",112        // ":def where     GOA.lambdabot \"where\"",113        // ":def version   GOA.lambdabot \"version\"",114        // ":def src       GOA.lambdabot \"src\"",115        // ":def pretty    GOA.lambdabot \"pretty\"",116        // "import qualified Debug.HTrace",117        // "trace = Debug.HTrace.htrace . unwords"118    ].join('\n') + '\n';119    haskellEval({120        id: 'initial',121        _options: {122            sessionId: procState.id,123            evalId: 'initial',124            expr: statements125        }}, function(err, evalState) {126            log('haskell init done');127            thenDo(err, procState); });128}129function ensureHaskell(options, thenDo) {130    var procState = ensureProcessState(options);131    var proc = getProcess(procState);132    if (haskellProcessIsRunning(procState)) { thenDo(null, procState); return; }133    var proc = setProcess(procState, spawn("ghci", [], {}));134    proc.on('exit', function() { removeProcess(procState); });135    // debug && proc.stdout.pipe(process.stdout)136    // debug && proc.stderr.pipe(process.stdout)137    initHaskellProcess(procState, thenDo);138}139function ensureHaskellWithListeners(options, onData, onError, thenDo) {140    ensureHaskell(options, function(err, procState) {141        if (err) { thenDo(err, proc); return; }142        var proc = getProcess(procState);143        // log('attaching listeners for ', options);144        proc.stdout.on('data', onData);145        proc.stderr.on('data', onData);146        proc.on('error', onError);147        proc.on('exit', onError);148        function uninstall() {149            // log('detaching listeners for ', options);150            proc.stdout.removeListener('data', onData);151            proc.stderr.removeListener('data', onData);152            proc.removeListener('exit', onError);153            proc.removeListener('error', onError);154        }155        thenDo(null, proc, uninstall);156    })157}158// -=-=-=-=-=-=-=-=-=-159// haskell evaluation160// -=-=-=-=-=-=-=-=-=-161function addNewEvalState(procState, options, callback) {162    var evalId = options.evalId,163        s = getEvalState(procState, evalId);164    if (s) return s;165    var s = {166        id: evalId,167        enqueueTime: Date.now(),168        startTime: null,169        endTime: null,170        result: '',171        _options: options, // transient172        _callback: callback // transient173    };174    procState.evalQueue.push(s);175    return s;176}177function cancelAllQueuedEvals(procState) {178    log('cancelAllQueuedEvals for %s', procState.sessionId);179    var q = procState.evalQueue;180    procState.evalQueue = [];181    q.forEach(function(evalState) {182        if (evalState.startTime) {183            log("cancelAllQueuedEvals: stopping evalState that is already started?!", evalState);184        }185        var thenDo = evalState._callback;186        delete evalState._callback;187        thenDo && thenDo(new Error('eval interrupted', evalState));188    });189}190function getEvalState(procState, evalId) {191    for (var i = 0; i < procState.evalQueue.length; i++) {192        if (procState.evalQueue[i].id === evalId) return procState.evalQueue[i];193    }194}195function removeEvalState(procState, evalId) {196    var idx = procState.evalQueue.indexOf(getEvalState(procState, evalId));197    if (idx > -1) procState.evalQueue.splice(idx, 1);198}199global.haskellEval = function haskellEval(evalState, thenDo) {200    // softAssert(!evalState.startTime, 'calling haskell eval for same task twice?' + util.inspect(evalState));201    // softAssert(!!evalState._options, 'calling haskell eval with no eval options?' + util.inspect(evalState));202    203    var prompt    = evalState._options.prompt || '',204        expr      = evalState._options.expr || "error \"Lively Haskell received no expression\"",205        output    = new Buffer(''),206        timeout   = 30*1000, // ms207        startTime = evalState.startTime = Date.now(),208        sentinel, error,209        uninstallListeners,210        haskellProcState;211    log('Haskell eval %s', expr);212    function checkForOutputAndClose() {213        var stringified = String(output),214            time = Date.now();215        if (stringified.indexOf(prompt) === -1216         && time - startTime < timeout) return;217        clearTimeout(sentinel);218        uninstallListeners && uninstallListeners();219        log('eval %s done', stringified);220        evalState.endTime = time;221        printHaskellServerState();222        thenDo && thenDo(error, stringified);223    }224    function onError(err) {225        log('Error: ', err);226        error = err;227        checkForOutputAndClose();228    }229    function onData(data) {230        // debug && console.log('Haskell output %s', expr);231        output = Buffer.concat([output, data]);232        if (sentinel) clearTimeout(sentinel);233        sentinel = setTimeout(checkForOutputAndClose, 200);234    }235    ensureHaskellWithListeners(evalState._options, onData, onError, function(err, haskellProc, uninstall) {236        uninstallListeners = uninstall;237        if (err) { thenDo(err); return; }238        if (!expr[expr.length-1] === '\n') expr += '\n';239        haskellProc.stdin.write(expr);240    });241}242function haskellEvalQueuedNext(procState) {243    var evalState = procState.evalQueue[0];244    if (!evalState) return;245    softAssert(!evalState.startTime, "haskellEvalQueuedNext starting eval that is already running?");246    log('Resuming eval %s', evalState._options.expr);247    var thenDo = evalState._callback;248    delete evalState._callback;249    haskellEval(evalState, thenDo);250}251function haskellEvalQueued(options, thenDo) {252    var procState = ensureProcessState(options),253        idle      = isIdle(procState),254        evalState = addNewEvalState(procState, options, addEvalResultToEvalState);255    if (idle) haskellEvalQueuedNext(procState);256    else log('Queuing eval %s at position %s', options.expr, procState.evalQueue.length);257    // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-258    function addEvalResultToEvalState(err, resultString) {259        // log('Haskell output %s: %s', evalState._options.expr, resultString);260        evalState.result = resultString;261        removeEvalState(procState, evalState.id);262        thenDo(err, evalState);263        haskellEvalQueuedNext(procState);264    }265    function isIdle(procState) { return procState.evalQueue.length === 0; }266}267// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-268// haskell related task that don't directly use haskell eval processes and need to269// start their own tools270// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-271var haskellTasks = {}; // id - {proc: PROCESS, callback: FUNCTION, killInitialized: BOOL}272function getTask(id) { return haskellTasks[id]; }273function createTask(id, callback) {274    return haskellTasks[id] = {275        proc: null,...StateTaskEither.ts
Source:StateTaskEither.ts  
1import * as assert from 'assert'2import * as E from 'fp-ts/lib/Either'3import * as IO from 'fp-ts/lib/IO'4import * as IOE from 'fp-ts/lib/IOEither'5import * as O from 'fp-ts/lib/Option'6import * as S from 'fp-ts/lib/State'7import * as T from 'fp-ts/lib/Task'8import * as TE from 'fp-ts/lib/TaskEither'9import { pipe } from 'fp-ts/lib/pipeable'10import * as _ from '../src/StateTaskEither'11describe('StateTaskEither', () => {12  describe('pipeables', () => {13    it('map', async () => {14      const len = (s: string): number => s.length15      assert.deepStrictEqual(await _.evalState(pipe(_.right('aaa'), _.map(len)), {})(), E.right(3))16    })17    it('ap', async () => {18      const len = (s: string): number => s.length19      assert.deepStrictEqual(await _.evalState(pipe(_.right(len), _.ap(_.right('aaa'))), {})(), E.right(3))20    })21    it('ap sequential', async () => {22      const len = (s: string): number => s.length23      assert.deepStrictEqual(await _.evalState(_.stateTaskEitherSeq.ap(_.right(len), _.right('aaa')), {})(), E.right(3))24    })25    it('apFirst', async () => {26      assert.deepStrictEqual(await _.evalState(pipe(_.right('aaa'), _.apFirst(_.right('bbb'))), {})(), E.right('aaa'))27    })28    it('apSecond', async () => {29      assert.deepStrictEqual(await _.evalState(pipe(_.right('aaa'), _.apSecond(_.right('bbb'))), {})(), E.right('bbb'))30    })31    it('chain', async () => {32      const f = (s: string) => (s.length > 2 ? _.right(s.length) : _.right(0))33      assert.deepStrictEqual(await _.evalState(pipe(_.right('aaa'), _.chain(f)), {})(), E.right(3))34    })35    it('chainFirst', async () => {36      const f = (s: string) => (s.length > 2 ? _.right(s.length) : _.right(0))37      assert.deepStrictEqual(await _.evalState(pipe(_.right('aaa'), _.chainFirst(f)), {})(), E.right('aaa'))38    })39    it('chainEitherK', async () => {40      const f = (s: string) => E.right(s.length)41      assert.deepStrictEqual(await _.evalState(pipe(_.right('aa'), _.chainEitherK(f)), {})(), E.right(2))42    })43    it('chainIOEitherK', async () => {44      const f = (s: string) => IOE.right(s.length)45      assert.deepStrictEqual(await _.evalState(pipe(_.right('aa'), _.chainIOEitherK(f)), {})(), E.right(2))46    })47    it('chainTaskEitherK', async () => {48      const f = (s: string) => TE.right(s.length)49      assert.deepStrictEqual(await _.evalState(pipe(_.right('aa'), _.chainTaskEitherK(f)), {})(), E.right(2))50    })51    it('flatten', async () => {52      assert.deepStrictEqual(await _.evalState(pipe(_.right(_.right('aaa')), _.flatten), {})(), E.right('aaa'))53      assert.deepStrictEqual(await _.evalState(pipe(_.right(_.left('aaa')), _.flatten), {})(), E.left('aaa'))54    })55    it('filterOrElse', async () => {56      const p = (s: string) => s.length > 257      assert.deepStrictEqual(58        await _.evalState(59          pipe(60            _.right('aaa'),61            _.filterOrElse(p, (s) => s.length)62          ),63          {}64        )(),65        E.right('aaa')66      )67      assert.deepStrictEqual(68        await _.evalState(69          pipe(70            _.right('aa'),71            _.filterOrElse(p, (s) => s.length)72          ),73          {}74        )(),75        E.left(2)76      )77    })78  })79  describe('constructors', () => {80    it('leftIO', async () => {81      const io: IO.IO<number> = IO.of(1)82      assert.deepStrictEqual(await _.evalState(_.leftIO(io), {})(), E.left(1))83    })84    it('rightIO', async () => {85      const io: IO.IO<number> = IO.of(1)86      assert.deepStrictEqual(await _.evalState(_.rightIO(io), {})(), E.right(1))87    })88    it('leftTask', async () => {89      const ta: T.Task<number> = T.of(1)90      assert.deepStrictEqual(await _.evalState(_.leftTask(ta), {})(), E.left(1))91    })92    it('rightTask', async () => {93      const ta: T.Task<number> = T.of(1)94      assert.deepStrictEqual(await _.evalState(_.rightTask(ta), {})(), E.right(1))95    })96    it('rightState', async () => {97      const state: S.State<{}, number> = (s) => [1, s]98      assert.deepStrictEqual(await _.evalState(_.rightState(state), {})(), E.right(1))99    })100    it('leftState', async () => {101      const state: S.State<{}, number> = (s) => [1, s]102      assert.deepStrictEqual(await _.evalState(_.leftState(state), {})(), E.left(1))103    })104    it('fromOption', async () => {105      assert.deepStrictEqual(106        await _.evalState(107          pipe(108            O.some(1),109            _.fromOption(() => 'none')110          ),111          {}112        )(),113        E.right(1)114      )115      assert.deepStrictEqual(116        await _.evalState(117          pipe(118            O.none,119            _.fromOption(() => 'none')120          ),121          {}122        )(),123        E.left('none')124      )125    })126    it('fromEither', async () => {127      assert.deepStrictEqual(await _.evalState(_.fromEither(E.right(1)), {})(), E.right(1))128      assert.deepStrictEqual(await _.evalState(_.fromEither(E.left(1)), {})(), E.left(1))129    })130    it('fromEitherK', async () => {131      const f = (s: Array<string>) => E.right(s.length)132      assert.deepStrictEqual(await _.evalState(_.fromEitherK(f)(['a', 'b']), {})(), E.right(2))133    })134    it('fromPredicate', async () => {135      const p = (n: number): boolean => n > 2136      assert.deepStrictEqual(137        await _.evalState(138          pipe(139            3,140            _.fromPredicate(p, () => 'false')141          ),142          {}143        )(),144        E.right(3)145      )146      assert.deepStrictEqual(147        await _.evalState(148          pipe(149            2,150            _.fromPredicate(p, () => 'false')151          ),152          {}153        )(),154        E.left('false')155      )156    })157  })158  it('evalState', async () => {159    const ma = _.right('aaa')160    const s = {}161    assert.deepStrictEqual(await _.evalState(ma, s)(), E.right('aaa'))162  })163  it('execState Right', async () => {164    const ma = _.right('aaa')165    const s = {}166    assert.deepStrictEqual(await _.execState(ma, s)(), E.right(s))167  })168  it('execState Left', async () => {169    assert.deepStrictEqual(await _.execState(_.left('aaa'), { a: 0 })(), E.left('aaa'))170  })171  it('run', async () => {172    const ma: _.StateTaskEither<{}, never, number> = _.of(1)173    const s = {}174    assert.deepStrictEqual(await _.run(ma, s), E.right([1, {}]))175  })...eval-handler.ts
Source:eval-handler.ts  
1import { ContentScriptMessage } from "./messages";2class Deferred<T> {3  id: string;4  promise: Promise<T>;5  resolve: (value?: T) => void;6  reject: (reason?: any) => void;7  timer: number;8  constructor(id: string, timeout = 1000) {9    this.id = id;10    this.promise = new Promise((resolve, reject) => {11      this.resolve = resolve;12      this.reject = reject;13    });14    this.timer = window.setTimeout(() => {15      this.reject(new Error("timeout"));16    }, timeout);17  }18}19type EvalState = {20  pending: Map<string, Deferred<boolean>>;21  sendContentMessage: (message: ContentScriptMessage) => void;22}23export const evalState: EvalState = {24  pending: new Map(),25  sendContentMessage: null,26}27export function requestEval(code: string): Promise<boolean> {28  let id;29  if (crypto && typeof crypto.randomUUID !== 'undefined') {30    id = crypto.randomUUID();31  } else {32    id = Math.random().toString();33  }34  evalState.sendContentMessage({35    type: 'eval',36    id,37    code,38  });39  const deferred = new Deferred<boolean>(id);40  evalState.pending.set(deferred.id, deferred);41  return deferred.promise;42}43export function resolveEval(id: string, value: boolean) {44  const deferred = evalState.pending.get(id);45  if (deferred) {46    evalState.pending.delete(id);47    deferred.timer && window.clearTimeout(deferred.timer);48    deferred.resolve(value);49  } else {50    console.warn('no eval #', id);51  }...Using AI Code Generation
1function Test() {2    var wpt = new WebPageTest('www.webpagetest.org');3        if (err) return console.log(err);4        wpt.getTestResults(data.data.testId, function (err, data) {5            if (err) return console.log(err);6            console.log(data);7        });8    });9}10function Test2() {11    var wpt = new WebPageTest('www.webpagetest.org');12        if (err) return console.log(err);13        wpt.getTestResults(data.data.testId, function (err, data) {14            if (err) return console.log(err);15            console.log(data);16        });17    });18}19function Test3() {20    var wpt = new WebPageTest('www.webpagetest.org');21        if (err) return console.log(err);22        wpt.getTestResults(data.data.testId, function (err, data) {23            if (err) return console.log(err);24            console.log(data);25        });26    });27}28function Test4() {29    var wpt = new WebPageTest('www.webpagetest.org');30        if (err) return console.log(err);31        wpt.getTestResults(data.data.testId, function (err, data) {32            if (err) return console.log(err);33            console.log(data);34        });35    });36}37function Test5() {38    var wpt = new WebPageTest('www.webpagetest.org');39    wpt.runTest('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!!
