Best JavaScript code snippet using playwright-internal
tracetool.js
Source:tracetool.js
1/*2 * Copyright (C) 2020-2021 Intel Corporation.3 *4 * This program is free software; you can redistribute it and/or modify it5 * under the terms and conditions of the GNU General Public License,6 * version 2, as published by the Free Software Foundation.7 *8 * This program is distributed in the hope it will be useful, but WITHOUT9 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for11 * more details.12 *13 * You should have received a copy of the GNU General Public License along with14 * this program; if not, write to the Free Software Foundation, Inc.,15 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.16 *17 */18import { isValidHttpUrl } from './utils.js';19import { LppNetworkTracer, LppStatus } from './nettrace.js';20import { log } from './logger.js';21import { html, css, LitElement, customElement, property } from "lit-element";22import { directive } from "lit-html";23import { styleMap } from "lit-html/directives/style-map";24import { query } from "lit-element/lib/decorators";25import "@material/mwc-button";26import "@material/mwc-icon-button";27import "@material/mwc-textfield";28import "@material/mwc-formfield";29import "@material/mwc-switch";30import "@material/mwc-linear-progress";31const isEmpty = str => str.length === 0 || !str.trim();32const parsePositiveNumber = str => {33 const num = Number(str); // empty converts to 0.34 return Number.isInteger(num) && num > 0 ? num : null;35}36const animateChange = directive(value => (part) => {37 if (part.value !== value) {38 part.setValue(value);39 part.commit();40 const parentElement = part.startNode.parentElement;41 if ('animate' in parentElement) {42 parentElement.animate({43 backgroundColor: ['lightgray', 'white']44 }, 1000);45 } else {46 parentElement.style.backgroundColor = 'lightgray';47 setTimeout(_ => {48 parentElement.style.backgroundColor = 'white';49 }, 1000);50 }51 }52});53@customElement('main-view')54export class MainView extends LitElement {55 static styles = css`56 mwc-textfield {57 width: 100%;58 max-width: 600px;59 }60 .vertical {61 display: flex;62 flex-direction: column;63 gap: 1em;64 }65 .buttons {66 display: flex;67 flex-direction: row;68 align-items: center;69 flex-wrap: wrap;70 gap: 6px;71 }72 mwc-linear-progress {73 padding: 16px 0 0 0;74 }75 .inline-label {76 margin: 1em 0;77 }78 `;79 sampler = null;80 wakeLock = null;81 @property() isTracing = false;82 @property() isPaused = false;83 @property({type: Number}) progress = 0;84 @property() status = 'Stopped';85 @property() networkType = 'Unknown';86 @property() networkEffectiveType = 'Unknown';87 @property() bandwidth = 0;88 @property() longitude = 0;89 @property() latitude = 0;90 @property() accuracy = 0;91 @query('#description') descriptionRef;92 @query('#clientModel') clientModelRef;93 @query('#clientName') clientNameRef;94 @query('#note') noteRef;95 @query('#dlBwTestInterval') dlBwTestIntervalRef;96 @query('#dlBwTestDuration') dlBwTestDurationRef;97 @query('#dlLimitKbytes') dlLimitKbytesRef;98 @query('#fileUrl') fileUrlRef;99 @query('#tracePosition') tracePositionRef;100 @query('#keepScreenOn') keepScreenOnRef;101 @query('#jsonConsole') jsonConsoleRef;102 connectedCallback() {103 super.connectedCallback();104 if ('connection' in navigator) {105 navigator.connection.onchange = this._onConnectionChange.bind(this);106 }107 }108 disconnectedCallback() {109 if ('connection' in navigator) {110 navigator.connection.onchange = null;111 }112 super.disconnectedCallback();113 }114 _onConnectionChange() {115 const { type, effectiveType } = navigator.connection;116 this.networkType = type || "Unknown";117 this.networkEffectiveType = effectiveType || "Unknown";118 }119 firstUpdated() {120 if ('wakeLock' in navigator) {121 // Reacquire wake lock122 document.addEventListener('visibilitychange', async () => {123 if (this.wakeLock !== null && document.visibilityState === 'visible') {124 this.wakeLock = await this._requestWakeLock();125 this.keepScreenOnRef.checked = !!this.wakeLock;126 }127 });128 this.keepScreenOnRef.checked = localStorage.getItem('keepScreenOn') === String(true);129 this._onKeepScreenOn();130 } else {131 this.keepScreenOnRef.disabled = true;132 }133 this.fileUrlRef.value = localStorage.getItem('lastUrl') || "";134 this.tracePositionRef.checked = localStorage.getItem('inclPosition') === String(true);135 if ('connection' in navigator) {136 this._onConnectionChange();137 }138 }139 _onTracePositionClick(ev) {140 const checked = !!this.tracePositionRef.checked;141 localStorage.setItem('inclPosition', String(checked));142 if (checked && navigator.geolocation) {143 navigator.geolocation.getCurrentPosition(_ => {});144 }145 }146 async _requestWakeLock() {147 const hasLock = !!this.wakeLock;148 const wakeLock = await navigator.wakeLock.request('screen');149 if (!wakeLock) {150 return null;151 }152 console.log("Screen wakelock was", hasLock ? "re-acquired" : "acquired");153 wakeLock.onrelease = () => {154 console.log("Screen wakelock was released")155 };156 return wakeLock;157 }158 async _onKeepScreenOn() {159 const checked = !!this.keepScreenOnRef.checked;160 localStorage.setItem('keepScreenOn', String(checked));161 if (!('wakeLock' in navigator)) {162 this.keepScreenOnRef.checked = false;163 }164 }165 async _onStartClick() {166 const description = this.descriptionRef.value;167 if (isEmpty(description)) {168 return alert('Description must not be empty!');169 }170 const interval = parsePositiveNumber(this.dlBwTestIntervalRef.value);171 if (!interval) {172 return alert('interval must be positive integer!');173 }174 const duration = parsePositiveNumber(this.dlBwTestDurationRef.value);175 if (!duration) {176 return alert('duration must be positive integer!');177 }178 if (duration > interval) {179 return alert('duration must be <= interval!');180 }181 const dlLimitKbytes = parsePositiveNumber(this.dlLimitKbytesRef.value);182 if (!dlLimitKbytes) {183 return alert('limit must be positive integer!');184 }185 const fileUrl = this.fileUrlRef.value.trim();186 if (isEmpty(fileUrl) || !isValidHttpUrl(fileUrl)) {187 return alert('url is invalid!');188 }189 const clientModel = this.clientModelRef.value;190 const clientName = this.clientNameRef.value;191 const note = this.noteRef.value;192 const params = {193 traceDlBw: true,194 tracePosition: !!this.tracePositionRef.checked,195 dlBwTestInterval: interval,196 dlBwTestDuration: duration,197 dlLimitKbytes,198 url: fileUrl,199 clientModel: !isEmpty(clientModel) ? clientModel : undefined,200 clientName: !isEmpty(clientName) ? clientName : undefined,201 note: !isEmpty(note) ? note : undefined,202 };203 this.jsonConsoleRef.value = '';204 this.isTracing = true;205 this.bandwidth = 0;206 this.status = 'running...';207 this.progress = 0;208 this.lppStart(description, params);209 if (this.keepScreenOnRef.checked) {210 this.wakeLock = await this._requestWakeLock();211 }212 }213 async _onStopClick() {214 this.isTracing = false;215 this.isPaused = false;216 this.sampler?.stop();217 this.status = 'Stopped';218 this.jsonConsoleRef.value = this.sampler?.toJSON();219 await this.wakeLock?.release();220 this.wakeLock = null;221 }222 _onPauseClick() {223 if (this.sampler !== null) {224 if (this.sampler.getStatus() === LppStatus.STARTED) {225 this.sampler.stop();226 this.isPaused = true;227 this.status = "Paused";228 } else if (this.sampler.getStatus() === LppStatus.STOPPED) {229 this.status = "Running...";230 this.sampler.start();231 this.isPaused = false;232 }233 }234 }235 lppStart(description, params) {236 params.onDlBwProgress = percentage => this.progress = percentage;237 this.sampler = new LppNetworkTracer(1, description, params);238 this.sampler.setDlBwResultHdlr(() => {239 this.status = 'Running...';240 const bw = this.sampler.getDlBw();241 if (bw) {242 this.progress = 100;243 this.bandwidth = bw;244 }245 const pos = this.sampler.getPosition();246 const err = this.sampler.getPositionError();247 if (err) {248 this.status = `Error: ${err}`;249 }250 if (pos) {251 this.longitude = pos.getLongitude();252 this.latitude = pos.getLongitude();253 this.accuracy = pos.getAccuracy();254 }255 });256 this.sampler.setErrorHdlr(() => {257 let err = this.sampler.getError();258 if (err) {259 this.status = `Error: ${err}`;260 }261 const bw = this.sampler.getDlBw();262 if (bw !== null) {263 this.progress = bw === 0 ? 0 : 100;264 this.bandwidth = bw;265 }266 const pos = this.sampler.getPosition();267 err = this.sampler.getPositionError();268 if (err) {269 this.status = `Error: ${err}`;270 }271 if (pos) {272 this.longitude = pos.getLongitude();273 this.latitude = pos.getLongitude();274 this.accuracy = pos.getAccuracy();275 }276 });277 this.sampler.start();278 }279 render() {280 return html`281 <h1>Network Capture Tool</h1>282 <div class="vertical">283 <mwc-textfield id="description" ?disabled=${this.isTracing} required284 label="Description" helper="Enter trace description" value="Trip from A to B">285 </mwc-textfield>286 <mwc-textfield id="clientModel" ?disabled=${this.isTracing} maxlength="128"287 label="Client model" helper="Enter client model, e.g. SM-G390">288 </mwc-textfield>289 <mwc-textfield id="clientName" ?disabled=${this.isTracing} maxlength="128"290 label="Client name" helper="Enter client name, e.g. Samsung Galaxy S10">291 </mwc-textfield>292 <mwc-textfield id="note" ?disabled=${this.isTracing} maxlength="512"293 label="Additional information" helper="Enter additional description">294 </mwc-textfield>295 <mwc-textfield id="dlBwTestInterval" ?disabled=${this.isTracing} required296 type=number value=10 min=1 max=60297 label="Download bandwidth test interval (sec)"298 helper="Enter measurement interval in seconds. Each measurement is run every interval">299 </mwc-textfield>300 <mwc-textfield id="dlBwTestDuration" ?disabled=${this.isTracing} required301 type=number value=10 min=1 max=60302 label="Download bandwidth test max duration (sec)"303 helper="Enter measurement duration. Each measurement is stopped if this time passes">304 </mwc-textfield>305 <mwc-textfield id="dlLimitKbytes" ?disabled=${this.isTracing} required306 type=number value=2048 min=1307 label="Download limit (Kbytes)"308 helper="Enter download limit in kilobytes. Each measurement is stopped after this amount is downloaded">309 </mwc-textfield>310 <mwc-textfield id="fileUrl" ?disabled=${this.isTracing} maxlength="256" required311 label="URL resource" helper="Enter file http(s) URL to download"312 @change=${ev => localStorage.setItem('lastUrl', ev.currentTarget.value)}>313 </mwc-textfield>314 <mwc-formfield label="Trace GPS position">315 <mwc-switch id="tracePosition" ?disabled=${this.isTracing}316 @change=${this._onTracePositionClick}>317 </mwc-switch>318 </mwc-formfield>319 <mwc-formfield label="Keep screen on while tracing">320 <mwc-switch id="keepScreenOn" ?disabled=${this.isTracing}321 @change=${this._onKeepScreenOn}>322 </mwc-switch>323 </mwc-formfield>324 <div class="buttons">325 <mwc-button dense unelevated id='startButton' ?disabled=${this.isTracing} @click=${this._onStartClick}>Start</mwc-button>326 <mwc-button dense unelevated id='pauseButton' ?disabled=${!this.isTracing} @click=${this._onPauseClick}>${this.isPaused ? "Resume" : "Pause"}</mwc-button>327 <mwc-button dense unelevated id='stopButton' ?disabled=${!this.isTracing} @click=${this._onStopClick}>Stop</mwc-button>328 <div>329 <span>${this.status}</span>330 </div>331 </div>332 </div>333 <div class="inline-label">334 <label for='progress'>Test progress:</label>335 <mwc-linear-progress id=progress progress=${this.progress/100} buffer="0"></mwc-linear-progress>336 </div>337 <div class="inline-label">338 <label for='bandwidth'>Measured download bandwidth:</label> <span>${animateChange(this.bandwidth)}</span> kbps339 </div>340 <div class="inline-label">341 <label for="network">Network:</label> <span>${animateChange(this.networkType)}</span>342 </div>343 <div class="inline-label">344 <label for="effective">Effective type:</label> <span>${animateChange(this.networkEffectiveType)}</span>345 </div>346 <div class="inline-label">347 <div>Longitude: <span>${animateChange(this.longitude)}</span></div>348 <div>Latitude: <span>${animateChange(this.latitude)}</span></div>349 <div>Accuracy: <span>${animateChange(this.accuracy)}</span></div>350 </div>351 <div class="inline-label">352 <label for="jsonConsole">Recorded data as JSON:</label><br><br>353 <json-view id="jsonConsole" ?disabled=${this.isTracing}></json-view>354 </div>355 <br>356 `;357 }358}359function supportDownload() {360 return "download" in document.createElement("a")361}362@customElement('json-view')363export class JsonView extends LitElement {364 static styles = css`365 pre {366 max-height: 200px;367 padding: 1em;368 margin: .5em 0;369 border: 0;370 border-radius: 0.3em;371 min-height: 180px;372 max-width: auto;373 overflow: auto;374 line-height: inherit;375 word-wrap: normal;376 background-color: #2b354f;377 color: white;378 }379 div {380 display: block;381 position: relative;382 }383 mwc-icon-button {384 overflow: unset;385 padding: 0;386 color: white;387 margin: 8px;388 padding: 0px;389 position: absolute;390 right: 0;391 top: 0;392 --mdc-theme-text-disabled-on-light: lightslategray;393 }394 #save {395 right: 52px;396 }397 `;398 @property({ type: String }) value = "";399 copy() {400 window.getSelection().removeAllRanges();401 const range = document.createRange();402 range.selectNode(this.shadowRoot.querySelector('#json'));403 window.getSelection().addRange(range);404 document.execCommand('copy');405 window.getSelection().removeAllRanges();406 }407 save() {408 const blob = new Blob([this.value], {type: "application/json"});409 const anchor = document.createElement("a");410 anchor.href = URL.createObjectURL(blob);411 anchor.download = "tracedata.json";412 anchor.click();413 window.URL.revokeObjectURL(anchor.href);414 }415 render() {416 return html`417 <div>418 <pre id="json">${this.value}</pre>419 <mwc-icon-button id="save" icon="save_alt"420 style=${styleMap({display: !supportDownload() ? 'none' : 'block'})}421 @click=${this.save} ?disabled=${!this.value.length}>422 </mwc-icon-button>423 <mwc-icon-button id="copy" icon="content_copy"424 @click=${this.copy} ?disabled=${!this.value.length}>425 </mwc-icon-button>426 </div>427 `;428 }...
debug.js
Source:debug.js
1// use this to isolate the scope2(function () {3 if(!$axure.document.configuration.showConsole) { return; }4 $(document).ready(function () {5 $axure.player.createPluginHost({6 id: 'debugHost',7 context: 'inspect',8 title: 'Console',9 gid: 310 });11 generateDebug();12 $('#variablesClearLink').click(clearvars_click);13 $('#traceClear').click(cleartrace_click);14 $('#traceToggle').click(stoptrace_click);15 $('#traceStart').click(starttrace_click);16 $('#traceClear').hide();17 $('#traceToggle').hide();18 $('#closeConsole').click(close);19 var currentStack= [];20 var finishedStack = [];21 $axure.messageCenter.addMessageListener(function (message, data) {22 if(message == 'axCompositeEventMessage') {23 for(var i = 0; i < data.length; i++) {24 processMessages(data[i].message, data[i].data);25 }26 } else processMessages(message, data);27 });28 var processMessages = function(message, data) {29 if(message == 'globalVariableValues') {30 $('#variablesDiv').empty();31 for(var key in data) {32 var value = data[key] == '' ? '(blank)' : data[key];33 $('#variablesDiv').append('<div class="variableList"><div class="variableName">' + key + '</div><div class="variableValue">' + value + '</div></div>');34 }35 } else if(message == 'axEvent') {36 var addToStack = "<div class='axEventBlock'>";37 addToStack += "<div class='axEventContainer'>";38 addToStack += " <div class='axTime'>" + new Date().toLocaleTimeString() + "</div>";39 addToStack += " <div class='axEvent'>" + data.event.description + ": </div>";40 addToStack += " <div class='axLabel'>" + data.label + " (" + data.type + ")</div>";41 addToStack += "</div>";42 currentStack.push(addToStack);43 } else if (message == 'axEventComplete') {44 currentStack[currentStack.length - 1] += "</div>";45 finishedStack.push(currentStack.pop());46 if(currentStack.length == 0) {47 $('#traceEmptyState').hide();48 $('#traceClear').show();49 $('#traceToggle').show();50 for(var i = finishedStack.length - 1; i >= 0; i--) {51 if($('#traceDiv').children().length > 99) $('#traceDiv').children().last().remove();52 $('#traceDiv').prepend(finishedStack[i]);53 }54 finishedStack = [];55 }56 } else if (message == 'axCase') {57 //var addToStack = "<div class='axCaseContainer' style='background-color: #" + data.color + "'>";58 var addToStack = "<div class='axCaseContainer'>";59 addToStack += " <div class='axCaseItem'>" + data.item + "</div>";60 if (data.description) { addToStack += " <div class='axCaseDescription' title='" + data.description + "'>" + data.description + "</div>" };61 addToStack += "</div>";62 currentStack[currentStack.length - 1] += addToStack;63 } else if (message == 'axAction') {64 var addToStack = "<div class='axActionContainer'>";65 addToStack += " <div class='axActionItem'>" + data.name + "</div>";66 //addToStack += " <div class='axActionItem'>" + data.item + "</div>";67 //if (data.description) { addToStack += " <div class='axActionDescription' title='" + data.description + "'>" + data.description + "</div>" };68 addToStack += "</div>";69 currentStack[currentStack.length - 1] += addToStack;70 } else if (message == 'axInfo') {71 var addToStack = "<div class='axInfoContainer'>";72 addToStack += " <div class='axInfoItem'>" + data.item + "</div>";73 if (data.description) { addToStack += " <div class='axInfoDescription' title='" + data.longDescription + "'>" + data.description + "</div>" };74 addToStack += "</div>";75 currentStack[currentStack.length - 1] += addToStack;76 }77 }78 // bind to the page load79 $axure.page.bind('load.debug', function () {80 var traceStr = $axure.player.getHashStringVar(TRACE_VAR_NAME);81 if (traceStr.length > 0) $axure.messageCenter.setState("isTracing", true);82 else $axure.messageCenter.setState("isTracing", false);83 $axure.messageCenter.postMessage('getGlobalVariables', '');84 return false;85 });86 function clearvars_click(event) {87 $axure.messageCenter.postMessage('resetGlobalVariables', '');88 }89 function close() {90 $axure.player.pluginClose("debugHost");91 }92 function cleartrace_click(event) {93 $('#traceDiv').html('');94 }95 function starttrace_click(event) {96 $axure.messageCenter.setState("isTracing", true);97 //$('#traceDiv').html('');98 $('#traceEmptyState').hide();99 $('#traceClear').show();100 $('#traceToggle').text('Stop Trace');101 $('#traceToggle').off("click");102 $('#traceToggle').click(stoptrace_click);103 $('#traceToggle').show();104 console.log("starting trace");105 $axure.player.setVarInCurrentUrlHash(TRACE_VAR_NAME, 1);106 }107 function stoptrace_click(event) {108 $axure.messageCenter.setState("isTracing", false);109 $('#traceDiv').prepend('<div class="tracePausedNotification">Trace Paused<div>');110 $('#traceToggle').text('Restart Trace');111 $('#traceToggle').off("click");112 $('#traceToggle').click(starttrace_click);113 console.log("stopping trace");114 $axure.player.deleteVarFromCurrentUrlHash(TRACE_VAR_NAME);115 }116 });117 function generateDebug() {118 var pageNotesUi = "<div id='debugHeader'>";119 pageNotesUi += "<div id='debugToolbar'>";120 pageNotesUi += "<div id='consoleTitle' class='pluginNameHeader'>Console</div>";121 pageNotesUi += "</div>";122 pageNotesUi += "</div>";123 pageNotesUi += "<div id='variablesContainer' style='max-height:300px; overflow-y:auto'>";124 pageNotesUi += "<div id='variablesTitle' class='sectionTitle'>Variables</div>";125 pageNotesUi += "<a id='variablesClearLink' class='traceOption'>Reset Variables</a>";126 pageNotesUi += "<div id='variablesDiv'></div></div>";127 pageNotesUi += "<div id='traceContainer'>";128 pageNotesUi += "<div id='traceHeader'>";129 pageNotesUi += "<span class='sectionTitle'>Trace</span><a id='traceClear' class='traceOption'>Clear Trace</a><a id='traceToggle' class='traceOption'>Stop Trace</a>";130 pageNotesUi += "</div>";131 pageNotesUi += "</div>";132 pageNotesUi += "<div id='debugScrollContainer'>";133 pageNotesUi += "<div id='debugContainer'>";134 pageNotesUi += "<div id='traceEmptyState'>";135 pageNotesUi += "<div class='startInstructions'>Click the button below to start recording interactions as you click through the prototype.</div>";136 pageNotesUi += "<div id='traceStart' class='startButton'>Start Trace</div>";137 pageNotesUi += "</div>";138 pageNotesUi += "<div id='traceDiv'></div></div>";139 pageNotesUi += "</div></div>";140 $('#debugHost').html(pageNotesUi);141 $('#traceEmptyState').show();142 }...
webRTC.js
Source:webRTC.js
1'use strict';2const express = require('express');3const path = require('path');4const PORT = process.env.PORT || 50005var socketIO = require('socket.io');6var { ProcessHands, Set_HSV_Gesture} = require('./gesture');7var { FrameTrace,Set_HSV_Trace} = require('./FrameTrace');8var app = express()9 .use(express.static(path.join(__dirname, '../public')))10 .set('views', path.join(__dirname, 'views'))11 .set('view engine', 'ejs')12 .get('/', (req, res) => res.render('pages/index'))13 .get('/admin', (req, res) => res.render('pages/admin'))14 .listen(PORT, () => { console.log(`Listening on ${PORT}`) })15var io = socketIO.listen(app);16const USER = { INSTRUCTOR: "INSTRUCTOR", OPERATOR: "OPERATOR" }17var isProcessing = false;18var iFrame_isCaptured = false;19var snapshot = null;20// States21var isStreaming = true;22var isTracing = false;23var fg_count = 0, fg_processed_count = 0;24io.sockets.on('connection', function (socket) {25 console.log("conn");26 function log() {27 var array = ['Message from server:'];28 array.push.apply(array, arguments);29 socket.emit('log', array);30 }31 /**32 * Recieved fgFrame, from instructor33 * Capture frame to @param iFrame, stop capturing while processing34 */35 socket.on('fgFrame', data => {36 if (!data) return;37 fg_count++;38 console.log("fgFrame recieved:", fg_count);39 /*** Stop capturing if in progress */40 if (isProcessing) return;41 isProcessing = true;42 snapshot = data;43 if (isStreaming) {44 /*** Process Frame */45 var processedFrame = ProcessHands(data);46 /*** Emit processed frame to all clients */47 io.sockets.emit('fgFrame', processedFrame);48 /*** Reset Conditions */49 isProcessing = false;50 }51 if (isTracing) {52 console.log("STATE: isTracing");53 /*** Process Frame */54 processedFrame = FrameTrace(data);55 /*** Emit processed frame to all clients */56 io.sockets.emit('fgFrame', processedFrame);57 /*** Reset Conditions */58 isProcessing = false;59 }60 });61 /**62 * Client request to trace63 * Turn off streaming64 * Turn on tracing65 * Emit last frame(instructor) to all clients's bgFrame66 */67 socket.on('notify_sketching', () => {68 console.log("STATE: NOTIFY_SKETCHING");69 isStreaming = false;70 isTracing = true;71 io.sockets.emit('do_sketching', true);72 })73 /**74 * Client request to stream75 * Turn off tracing76 * Turn on Stremaing77 * Tell all clints to go back to stremaing78 */79 socket.on('notify_streaming', () => {80 console.log("STATE: NOTIFY_STREAMING");81 isStreaming = true;82 isTracing = false;83 io.sockets.emit('do_streaming', true);84 })85 /**86 * ON Role change requested by a client, notify all clients to change their role87 */88 socket.on('notify_change_role', () => {89 io.sockets.emit('do_change_role', true);90 })91 /**92 * color selector settings for gesture calibration93 */94 socket.on('admin_calibrate_hsv', data => {95 Set_HSV_Gesture(data);96 })97 /**98 * color selector settings for trace calibration99 */100 socket.on('admin_calibrate_hsv_trace', data => {101 Set_HSV_Trace(data);102 })103 104 /**105 * Admin request snapshot(from instructor) from server106 */107 socket.on('admin_get_snapshot', () => {108 io.sockets.emit('snapshot', { isStreaming: isStreaming, isTracing: isTracing, snapshot: snapshot });109 })110 /**111 * @deprecated 'frame' event deprecated, use 'bgFrame' and 'fgFrame' instead;112 * @description Receiving Frames from clients, process according to frame origin/client type113 * */114 socket.on('frame', data => {115 n++;116 console.log("Frames Recieved:::", n);117 /***********************************************118 * Insturctor's frame119 *********************************************** */120 if (data.from == USER.INSTRUCTOR) {121 /** Process instructor's frames */122 if (iFrame_isCaptured && isProcessing) return;123 k++;124 console.log("Frames Captured:::", k);125 /** Capture Frame, stop further capture until processing is done */126 var iFrame = data.data127 iFrame_isCaptured = true128 if (iFrame !== undefined) {129 /**130 * Process Frame, emit to all clients131 */132 var processedFrame = ProcessHands(iFrame);133 io.sockets.emit('cvFrame', { type: 'fgFrame', data: processedFrame });134 /**135 * Reset Conditions136 */137 iFrame_isCaptured = false;138 isProcessing = false;139 }140 }141 /***********************************************142 * Operator's frame143 *********************************************** */144 else if (data.from == USER.OPERATOR) {145 /** 146 * No need to process operator's frames, relay frame back to all clients147 */148 io.sockets.emit('cvFrame', { type: 'bgFrame', data: data.data });149 }150 })151 socket.on('message', function (message) {152 log('Client said: ', message);153 // for a real app, would be room-only (not broadcast)154 socket.broadcast.emit('message', message);155 });156 socket.on('bye', () => {157 io.close();158 })159 /** Request from client to join or create room 160 * 161 */162 socket.on('create or join', function (room) {163 log('Received request to create or join room ' + room);164 if (socket.handshake.headers.referer.indexOf("/admin") > -1) {165 console.log("admin is trying to connect, dont let him join");166 return;167 }168 var clientsInRoom = io.sockets.adapter.rooms[room];169 var numClients = clientsInRoom ? Object.keys(clientsInRoom.sockets).length : 0;170 log('Room ' + room + ' now has ' + numClients + ' client(s)');171 if (numClients === 0) {172 socket.join(room);173 log('Client ID ' + socket.id + ' created room ' + room);174 socket.emit('created', room, socket.id);175 } else if (numClients === 1) {176 log('Client ID ' + socket.id + ' joined room ' + room);177 io.sockets.in(room).emit('join', room);178 socket.join(room);179 socket.emit('joined', room, socket.id);180 io.sockets.in(room).emit('ready');181 } else { // max two clients182 socket.emit('full', room);183 }184 });...
store.spec.js
Source:store.spec.js
1// Copyright 2015-2017 Parity Technologies (UK) Ltd.2// This file is part of Parity.3// Parity is free software: you can redistribute it and/or modify4// it under the terms of the GNU General Public License as published by5// the Free Software Foundation, either version 3 of the License, or6// (at your option) any later version.7// Parity is distributed in the hope that it will be useful,8// but WITHOUT ANY WARRANTY; without even the implied warranty of9// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the10// GNU General Public License for more details.11// You should have received a copy of the GNU General Public License12// along with Parity. If not, see <http://www.gnu.org/licenses/>.13import BigNumber from 'bignumber.js';14import sinon from 'sinon';15import { mockget as mockEtherscan } from '~/3rdparty/etherscan/helpers.spec.js';16import { ADDRESS, createApi } from './transactions.test.js';17import Store from './store';18let api;19let store;20function createStore () {21 api = createApi();22 store = new Store(api);23 return store;24}25function mockQuery () {26 mockEtherscan([{27 query: {28 module: 'account',29 action: 'txlist',30 address: ADDRESS,31 offset: 25,32 page: 1,33 sort: 'desc'34 },35 reply: [{ hash: '123' }]36 }], false, '42');37}38describe('views/Account/Transactions/store', () => {39 beforeEach(() => {40 mockQuery();41 createStore();42 });43 describe('constructor', () => {44 it('sets the api', () => {45 expect(store._api).to.deep.equals(api);46 });47 it('starts with isLoading === false', () => {48 expect(store.isLoading).to.be.false;49 });50 it('starts with isTracing === false', () => {51 expect(store.isTracing).to.be.false;52 });53 });54 describe('@action', () => {55 describe('setHashes', () => {56 it('clears the loading state', () => {57 store.setLoading(true);58 store.setHashes([]);59 expect(store.isLoading).to.be.false;60 });61 it('sets the hashes from the transactions', () => {62 store.setHashes([{ hash: '123' }, { hash: '456' }]);63 expect(store.txHashes.peek()).to.deep.equal(['123', '456']);64 });65 });66 describe('setAddress', () => {67 it('sets the address', () => {68 store.setAddress(ADDRESS);69 expect(store.address).to.equal(ADDRESS);70 });71 });72 describe('setLoading', () => {73 it('sets the isLoading flag', () => {74 store.setLoading(true);75 expect(store.isLoading).to.be.true;76 });77 });78 describe('setNetVersion', () => {79 it('sets the netVersion', () => {80 store.setNetVersion('testing');81 expect(store.netVersion).to.equal('testing');82 });83 });84 describe('setTracing', () => {85 it('sets the isTracing flag', () => {86 store.setTracing(true);87 expect(store.isTracing).to.be.true;88 });89 });90 describe('updateProps', () => {91 it('retrieves transactions once updated', () => {92 sinon.spy(store, 'getTransactions');93 store.updateProps({});94 expect(store.getTransactions).to.have.been.called;95 store.getTransactions.restore();96 });97 });98 });99 describe('operations', () => {100 describe('getTransactions', () => {101 it('retrieves the hashes via etherscan', () => {102 sinon.spy(store, 'fetchEtherscanTransactions');103 store.setAddress(ADDRESS);104 store.setNetVersion('42');105 store.setTracing(false);106 return store.getTransactions().then(() => {107 expect(store.fetchEtherscanTransactions).to.have.been.called;108 expect(store.txHashes.peek()).to.deep.equal(['123']);109 store.fetchEtherscanTransactions.restore();110 });111 });112 it('retrieves the hashes via tracing', () => {113 sinon.spy(store, 'fetchTraceTransactions');114 store.setAddress(ADDRESS);115 store.setNetVersion('42');116 store.setTracing(true);117 return store.getTransactions().then(() => {118 expect(store.fetchTraceTransactions).to.have.been.called;119 expect(store.txHashes.peek()).to.deep.equal(['123', '098']);120 store.fetchTraceTransactions.restore();121 });122 });123 });124 describe('fetchEtherscanTransactions', () => {125 it('retrieves the transactions', () => {126 store.setAddress(ADDRESS);127 store.setNetVersion('42');128 return store.fetchEtherscanTransactions().then((transactions) => {129 expect(transactions).to.deep.equal([{130 blockNumber: new BigNumber(0),131 from: '',132 hash: '123',133 timeStamp: undefined,134 to: '',135 value: undefined136 }]);137 });138 });139 });140 describe('fetchTraceTransactions', () => {141 it('retrieves the transactions', () => {142 store.setAddress(ADDRESS);143 store.setNetVersion('42');144 return store.fetchTraceTransactions().then((transactions) => {145 expect(transactions).to.deep.equal([146 {147 blockNumber: undefined,148 from: undefined,149 hash: '123',150 to: undefined151 },152 {153 blockNumber: undefined,154 from: undefined,155 hash: '098',156 to: undefined157 }158 ]);159 });160 });161 });162 });...
test-run-trace.js
Source:test-run-trace.js
1// Copyright IBM Corp. 2015,2016. All Rights Reserved.2// Node module: strong-supervisor3// This file is licensed under the Artistic License 2.0.4// License text available at https://opensource.org/licenses/Artistic-2.05'use strict';6var debug = require('./debug');7var run = require('./run-with-ctl-channel');8var tap = require('tap');9var options = {};10if (!process.env.STRONGLOOP_LICENSE) {11 options.skip = 'tested feature requires license';12}13tap.test('traces are forwarded via parentCtl', options, function(t) {14 t.plan(2);15 var expressApp = require.resolve('./express-app');16 var app = run([expressApp], ['--cluster=1', '--no-control', '--trace'],17 function(data) {18 debug('received: cmd %s: %j', data.cmd, data);19 switch (data.cmd) {20 case 'trace:object':21 var record = JSON.parse(data.record);22 t.ok(!!record.version, 'Record version should exist');23 t.ok(!!record.packet.metadata, 'Record metadata should exist');24 app.kill();25 break;26 }27 }28 );29 app.ref();30 app.on('exit', function(code, signal) {31 debug('supervisor exit: %s', signal || code);32 t.end();33 });34});35tap.test('traces can be turned on', options, function(t) {36 t.plan(6);37 var expressApp = require.resolve('./express-app');38 var app = run([expressApp], ['--cluster=1', '--no-control'], messageHandler);39 var tracingEnabled = false;40 function messageHandler(data) {41 debug('received: cmd %s: %j', data.cmd, data);42 switch (data.cmd) {43 case 'status:wd':44 if (data.id === 0) {45 t.assert(!data.isTracing);46 } else {47 t.equal(data.isTracing, tracingEnabled);48 if (!tracingEnabled) {49 tracingEnabled = true;50 app.control.request({cmd: 'tracing', enabled: true}, function(res){51 t.assert(!res.error);52 });53 } else {54 app.kill();55 }56 }57 break;58 case 'trace:object':59 t.assert(tracingEnabled);60 var record = JSON.parse(data.record);61 t.ok(!!record.version, 'Record version should exist');62 t.ok(!!record.packet.metadata, 'Record metadata should exist');63 break;64 }65 }66 app.ref();67 app.on('exit', function(code, signal) {68 debug('supervisor exit: %s', signal || code);69 t.end();70 });71});72tap.test('traces hostname can be overridden', options, function(t) {73 t.plan(7);74 var expressApp = require.resolve('./express-app');75 process.env.STRONGLOOP_TRACES_ID = '1234';76 var app = run([expressApp], ['--cluster=1', '--no-control'], messageHandler);77 var tracingEnabled = false;78 function messageHandler(data) {79 debug('received: cmd %s: %j', data.cmd, data);80 switch (data.cmd) {81 case 'status:wd':82 if (data.id === 0) {83 t.assert(!data.isTracing);84 } else {85 t.equal(data.isTracing, tracingEnabled);86 if (!tracingEnabled) {87 tracingEnabled = true;88 app.control.request({cmd: 'tracing', enabled: true}, function(res){89 t.assert(!res.error);90 });91 } else {92 app.kill();93 }94 }95 break;96 case 'trace:object':97 t.assert(tracingEnabled);98 var record = JSON.parse(data.record);99 t.ok(!!record.version, 'Record version should exist');100 t.ok(!!record.packet.metadata, 'Record metadata should exist');101 t.equal(record.packet.monitoring.system_info.hostname, '1234',102 'Record hostname should match');103 break;104 }105 }106 app.ref();107 app.on('exit', function(code, signal) {108 debug('supervisor exit: %s', signal || code);109 t.end();110 });111});112tap.test('traces can be turned off', options, function(t) {113 t.plan(6);114 var expressApp = require.resolve('./express-app');115 var args = ['--cluster=1', '--no-control', '--trace'];116 var app = run([expressApp], args, messageHandler);117 var tracingEnabled = true;118 function messageHandler(data) {119 debug('received: cmd %s: %j', data.cmd, data);120 switch (data.cmd) {121 case 'status:wd':122 if (data.id === 0) {123 t.assert(!data.isTracing);124 } else {125 t.equal(data.isTracing, tracingEnabled);126 if (tracingEnabled) {127 tracingEnabled = false;128 app.control.request({cmd: 'tracing', enabled: false}, function(res){129 t.assert(!res.error);130 });131 } else {132 app.kill();133 }134 }135 break;136 case 'trace:object':137 t.assert(tracingEnabled);138 var record = JSON.parse(data.record);139 t.ok(!!record.version, 'Record version should exist');140 t.ok(!!record.packet.metadata, 'Record metadata should exist');141 break;142 }143 }144 app.ref();145 app.on('exit', function(code, signal) {146 debug('supervisor exit: %s', signal || code);147 t.end();148 });...
store.js
Source:store.js
1// Copyright 2015-2017 Parity Technologies (UK) Ltd.2// This file is part of Parity.3// Parity is free software: you can redistribute it and/or modify4// it under the terms of the GNU General Public License as published by5// the Free Software Foundation, either version 3 of the License, or6// (at your option) any later version.7// Parity is distributed in the hope that it will be useful,8// but WITHOUT ANY WARRANTY; without even the implied warranty of9// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the10// GNU General Public License for more details.11// You should have received a copy of the GNU General Public License12// along with Parity. If not, see <http://www.gnu.org/licenses/>.13import { action, observable, transaction } from 'mobx';14import etherscan from '~/3rdparty/etherscan';15export default class Store {16 @observable address = null;17 @observable isLoading = false;18 @observable isTracing = false;19 @observable netVersion = '0';20 @observable txHashes = [];21 constructor (api) {22 this._api = api;23 }24 @action setHashes = (transactions) => {25 transaction(() => {26 this.setLoading(false);27 this.txHashes = transactions.map((transaction) => transaction.hash);28 });29 }30 @action setAddress = (address) => {31 this.address = address;32 }33 @action setLoading = (isLoading) => {34 this.isLoading = isLoading;35 }36 @action setNetVersion = (netVersion) => {37 this.netVersion = netVersion;38 }39 @action setTracing = (isTracing) => {40 this.isTracing = isTracing;41 }42 @action updateProps = (props) => {43 transaction(() => {44 this.setAddress(props.address);45 this.setNetVersion(props.netVersion);46 // TODO: When tracing is enabled again, adjust to actually set47 this.setTracing(false && props.traceMode);48 });49 return this.getTransactions();50 }51 getTransactions () {52 if (this.netVersion === '0') {53 return Promise.resolve();54 }55 this.setLoading(true);56 // TODO: When supporting other chains (eg. ETC). call to be made to other endpoints57 return (58 this.isTracing59 ? this.fetchTraceTransactions()60 : this.fetchEtherscanTransactions()61 )62 .then((transactions) => {63 this.setHashes(transactions);64 })65 .catch((error) => {66 console.warn('getTransactions', error);67 this.setLoading(false);68 });69 }70 fetchEtherscanTransactions () {71 return etherscan.account.transactions(this.address, 0, false, this.netVersion);72 }73 fetchTraceTransactions () {74 return Promise75 .all([76 this._api.trace.filter({77 fromAddress: this.address,78 fromBlock: 079 }),80 this._api.trace.filter({81 fromBlock: 0,82 toAddress: this.address83 })84 ])85 .then(([fromTransactions, toTransactions]) => {86 return fromTransactions87 .concat(toTransactions)88 .map((transaction) => {89 return {90 blockNumber: transaction.blockNumber,91 from: transaction.action.from,92 hash: transaction.transactionHash,93 to: transaction.action.to94 };95 });96 });97 }...
SaveTrace.js
Source:SaveTrace.js
1define(["sitecore", "/-/speak/v1/ExperienceEditor/ExperienceEditor.js"], function (Sitecore, ExperienceEditor) {2 Sitecore.Commands.SaveTrace =3 {4 canExecute: function (context) {5 var isTracing = ExperienceEditor.isDebugging() && ExperienceEditor.Web.getUrlQueryStringValue("sc_trace") == "1";6 return ExperienceEditor.canToggleDebug() && isTracing;7 },8 execute: function (context) {9 context.currentContext.value = ExperienceEditor.Web.getUrlQueryStringValue("sc_trf");10 context.app.disableButtonClickEvents();11 ExperienceEditor.PipelinesUtil.executePipeline(context.app.SaveDebugTrace, function () {12 ExperienceEditor.PipelinesUtil.executeProcessors(Sitecore.Pipelines.SaveDebugTrace, context);13 });14 context.app.enableButtonClickEvents();15 }16 };...
DownloadTrace.js
Source:DownloadTrace.js
1define(["sitecore", "/-/speak/v1/ExperienceEditor/ExperienceEditor.js"], function (Sitecore, ExperienceEditor) {2 Sitecore.Commands.DownloadTrace =3 {4 canExecute: function (context) {5 var isTracing = ExperienceEditor.isDebugging() && ExperienceEditor.Web.getUrlQueryStringValue("sc_trace") == "1";6 return ExperienceEditor.canToggleDebug() && isTracing;7 },8 execute: function (context) {9 context.currentContext.value = ExperienceEditor.Web.getUrlQueryStringValue("sc_trf");10 ExperienceEditor.PipelinesUtil.generateRequestProcessor("ExperienceEditor.DownloadDebugRequests.ExecuteDownloadTrace", function (response) {11 ExperienceEditor.Web.downloadFile(response.responseValue.value);12 }).execute(context);13 }14 };...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const page = await browser.newPage();5 await page.screenshot({ path: 'screenshot.png' });6 await browser.close();7})();8const { chromium } = require('playwright');9(async () => {10 const browser = await chromium.launch({ headless: false });11 const page = await browser.newPage();12 await page.screenshot({ path: 'screenshot.png' });13 await browser.close();14})();15const { chromium } = require('playwright');16(async () => {17 const browser = await chromium.launch({ headless: false });18 const page = await browser.newPage();19 await page.screenshot({ path: 'screenshot.png' });20 await browser.close();21})();22const { chromium } = require('playwright');23(async () => {24 const browser = await chromium.launch({ headless: false });25 const page = await browser.newPage();26 await page.screenshot({ path: 'screenshot.png' });27 await browser.close();28})();29const { chromium } = require('playwright');30(async () => {31 const browser = await chromium.launch({ headless: false });32 const page = await browser.newPage();33 await page.screenshot({ path: 'screenshot.png' });34 await browser.close();35})();36const { chromium } = require('playwright');37(async () => {38 const browser = await chromium.launch({ headless: false });39 const page = await browser.newPage();40 await page.screenshot({ path: 'screenshot.png' });
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 await context.tracing.start({ screenshots: true, snapshots: true });6 const page = await context.newPage();7 await context.tracing.stop({ path: 'trace.zip' });8 await browser.close();9})();
Using AI Code Generation
1const { isTracing } = require('playwright/lib/internal/trace/recorder');2console.log(isTracing());3const { isTracing } = require('playwright');4console.log(isTracing());5const { isTracing } = require('playwright/lib/server/trace/recorder');6console.log(isTracing());7const { isTracing } = require('playwright/lib/server/trace/recorder');8console.log(isTracing());9const { isTracing } = require('playwright/lib/server/trace/recorder');10console.log(isTracing());11const { isTracing } = require('playwright/lib/server/trace/recorder');12console.log(isTracing());13const { isTracing } = require('playwright/lib/server/trace/recorder');14console.log(isTracing());15const { isTracing } = require('playwright/lib/server/trace/recorder');16console.log(isTracing());17const { isTracing } = require('playwright/lib/server/trace/recorder');18console.log(isTracing());19const { isTracing } = require('playwright/lib/server/trace/recorder');20console.log(isTracing());21const { isTracing } = require('playwright/lib/server/trace/recorder');22console.log(isTracing());23const { isTracing } = require('playwright/lib/server/trace/recorder');24console.log(isTracing());25const { isTracing } = require('playwright/lib/server/trace/recorder');26console.log(isTracing());27const { isTracing } = require('playwright/lib/server/trace/recorder');28console.log(isTracing());
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false});4 const context = await browser.newContext({ recordVideo: { dir: 'videos' }});5 const page = await context.newPage();6 await page.screenshot({ path: 'google.png' });7 await browser.close();8})();
Using AI Code Generation
1const { isTracing } = require('@playwright/test/lib/utils/internal');2console.log(isTracing());3const { test } = require('@playwright/test');4test('example test', async ({ page }) => {5 const { isTracing } = require('@playwright/test/lib/utils/internal');6 console.log(isTracing());7});
Using AI Code Generation
1const { isTracing } = require('@playwright/test/lib/internal/trace');2console.log(isTracing());3const { trace } = require('@playwright/test/lib/internal/trace');4const { test } = require('@playwright/test');5test('test', async ({ page }) => {6 await trace(page, 'trace-name', async () => {7 });8});
Using AI Code Generation
1const { isTracing } = require('playwright/lib/server/trace/recorder');2console.log(isTracing());3const { isTracing } = require('playwright/lib/server/trace/recorder');4const { chromium } = require('playwright');5(async () => {6 const browser = await chromium.launch();7 const page = await browser.newPage();8 console.log(isTracing());9 await page.tracing.start({ path: 'trace.zip' });10 console.log(isTracing());11 await page.tracing.stop();12 console.log(isTracing());13 await browser.close();14})();15const { isTracing } = require('playwright/lib/server/trace/recorder');16const { chromium } = require('playwright');17(async () => {18 const browser = await chromium.launch();19 const page = await browser.newPage();20 console.log(isTracing());21 await page.tracing.start({ screenshots: true, snapshots: true, path: 'trace.zip' });22 console.log(isTracing());23 await page.tracing.stop();24 console.log(isTracing());25 await browser.close();26})();
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!