Best JavaScript code snippet using wpt
simple-connect.js
Source:simple-connect.js
1/**2 * Declare namespace3 */4simpleConnect = {};5/**6 * This member is an auxiliary counter used for generate unique identifiers.7 */8simpleConnect._idGenerator = 0;9/**10 * This member is an associative array which contains all the document's connections.11 */12simpleConnect._connections = {};13/**14 * Gets the position of an element, optionally takes a second element to use15 * in calculating a relative position.16 * 17 * @param {object} elem The element.18 * @param {object} relativeElem The element to use for relative positioning.19 * @returns {object} An associative array containg the properties: top, vcenter (vertical20 * center), bottom, left, hcenter (horizontal center) and right.21 */22simpleConnect._getPosition = function (elem, relativeElem) {23 var rect = elem.getBoundingClientRect();24 var top = rect.top + window.pageYOffset;25 var left = rect.left + window.pageXOffset;26 if (relativeElem) {27 var relativeRect = relativeElem.getBoundingClientRect();28 top = rect.top - relativeRect.top;29 left = rect.left - relativeRect.left;30 }31 return {32 top: top,33 vcenter: top + (elem.offsetHeight / 2 | 0),34 bottom: top + elem.offsetHeight,35 left: left,36 hcenter: left + (elem.offsetWidth / 2 | 0),37 right: left + elem.offsetWidth38 };39}40/**41 * Positions a canvas object based on the position of the two supplied42 * elements.43 * 44 * @param {object} canvas The canvas object.45 * @param {object} elemA The first element.46 * @param {object} elemB The second element.47 */48simpleConnect._positionCanvas = function (canvas, elemA, elemB) {49 var elemAPos = simpleConnect._getPosition(elemA);50 var elemBPos = simpleConnect._getPosition(elemB);51 var width = Math.max(elemAPos.right, elemBPos.right) - Math.min(elemAPos.left, elemBPos.left);52 var height = Math.max(elemAPos.bottom, elemBPos.bottom) - Math.min(elemAPos.top, elemBPos.top);53 var dpr = window.devicePixelRatio;54 canvas.style.left = Math.min(elemAPos.left, elemBPos.left) + "px";55 canvas.style.top = Math.min(elemAPos.top, elemBPos.top) + "px";56 canvas.width = width * dpr;57 canvas.height = height * dpr;58 canvas.style.width = width + "px";59 canvas.style.height = height + "px";60 canvas.getContext('2d').scale(dpr, dpr);61}62/**63 * Creates a canvas and positions it relative to the two supplied elements.64 * 65 * @param {object} elemA The first element.66 * @param {object} elemB The second element.67 * @param {string} id The ID for the canvas object.68 * @returns {object} The canvas object.69 */70simpleConnect._createCanvas = function (elemA, elemB, id) {71 var canvas = document.createElement("canvas");72 canvas.id = "canvas_" + id;73 canvas.style.zIndex = -1;74 canvas.style.position = "absolute";75 //canvas.style.border = "1px dashed black";76 document.body.appendChild(canvas);77 simpleConnect._positionCanvas(canvas, elemA, elemB);78 return canvas;79}80/**81 * Draws a connection between two elements.82 *83 * @param {string} elemAId The ID of the first element.84 * @param {string} elemBId The ID of the second element.85 * @param {object} options An associative array with the properties 'color' (which defines the color of the connection),86 * 'lineWidth' (the width of the connection), 'type' (the preferred type of the connection: 'horizontal' or 'vertical'),87 * 'offset' (distance between connector and elements), 'arrowWidth' (width of the arrowhead, 0 for none) and88 * 'arrowHeight' (height of the arrowhead, 0 for none)89 * @returns {string} The connection identifier or 'null' if the connection could not be draw.90 */91simpleConnect.connect = function (elemAId, elemBId, options) {92 // Get the elements and verify they exist.93 var elemA = document.getElementById(elemAId);94 if (!elemA) return null;95 var elemB = document.getElementById(elemBId);96 if (!elemB) return null;97 // Create connection object.98 var connection = {};99 connection.id = "simpleConnect_" + simpleConnect._idGenerator++;100 connection.elemA = elemA;101 connection.elemB = elemB;102 connection.lineWidth = (options && options.lineWidth !== null && !isNaN(options.lineWidth)) ? (options.lineWidth | 0) : 4;103 connection.color = (options && options.color !== null) ? options.color + "" : "#000";104 connection.type = (options && options.type !== null && (options.type === "vertical" || options.type === "horizontal")) ? options.type : "horizontal";105 connection.offset = (options && options.offset !== null && !isNaN(options.offset)) ? (options.offset | 0) : 10;106 connection.canvas = simpleConnect._createCanvas(elemA, elemB, connection.id);107 connection.arrowWidth = (options && options.arrowWidth !== null && !isNaN(options.arrowWidth)) ? (options.arrowWidth | 0) : 10;108 connection.arrowHeight = (options && options.arrowHeight !== null && !isNaN(options.arrowHeight)) ? (options.arrowHeight | 0) : 10;109 // Add connection to the connection's list.110 simpleConnect._connections[connection.id] = connection;111 // Populate the connection with the actual lines.112 simpleConnect._populateConnection(connection);113 // Return result.114 return connection.id;115}116/**117 * Repaints a connection.118 *119 * @param {string} connectionId The connection identifier.120 * @returns {boolean} 'true' if the operation was done, 'false' if the connection no exists.121 */122simpleConnect.repaintConnection = function (connectionId) {123 var connection = simpleConnect._connections[connectionId];124 if (connection) {125 simpleConnect._positionCanvas(connection.canvas, connection.elemA, connection.elemB);126 simpleConnect._populateConnection(connection);127 return true;128 }129 return false;130}131/**132 * Calculates the middle of two points. 133 *134 * @param {object} elemAPos The position of the first element.135 * @param {object} elemBPos The position of the second element.136 * @param {string} pointA The property name of the first position.137 * @param {string} pointB The property name of the second position.138 * @returns {int} The middle of the given points.139 */140simpleConnect._calculateMiddle = function (elemAPos, elemBPos, pointA, pointB) {141 var p1 = pointA;142 var p2 = pointB;143 // The point with the smallest value needs to come first144 if (Math.min(elemAPos[pointB], elemBPos[pointB]) > Math.min(elemAPos[pointA], elemBPos[pointA])) {145 p1 = pointB;146 p2 = pointA;147 }148 return (Math.min(elemAPos[p1], elemBPos[p1]) + (Math.abs(Math.max(elemAPos[p2], elemBPos[p2]) - Math.min(elemAPos[p1], elemBPos[p1])) / 2) | 0);149}150/**151 * Draws a connection.152 *153 * @param {object} c The connection properties.154 * @param {object} ctx The canvas context.155 * @param {object} elemAPos The position of the first element.156 * @param {object} elemBPos The position of the second element.157 * @param {string} type The type of the connection, either 'vertical' or 'horizontal'.158 * @returns {boolean} 'true' if the operation was successful, 'false' if it wasn't.159 */160simpleConnect._drawConnection = function (c, ctx, elemAPos, elemBPos, type) {161 // Default is horizontal, e.g. a line connection left and right162 var pointA = "left";163 var pointB = "right";164 var pointC = "vcenter";165 if (type === "vertical") {166 pointA = "top";167 pointB = "bottom";168 pointC = "hcenter";169 }170 // An array to contain our calculated co-ordinates171 var coords = [];172 // Are we drawing from element A to B, or is the reverse true?173 var reverse = elemAPos[pointA] > elemBPos[pointA];174 // The available space to draw the line in175 var availableSpace = Math.max(elemAPos[pointA], elemBPos[pointA]) - Math.min(elemAPos[pointB], elemBPos[pointB]);176 // We're going to have problems fitting this in (buffer of 5).177 // Don't draw it in this scenario.178 if ((availableSpace / 2) <= (c.offset + c.arrowHeight + (c.lineWidth / 2) + 5)) {179 return false;180 }181 // Calculate the midpoint between our two points to be connected182 var midpoint = simpleConnect._calculateMiddle(elemAPos, elemBPos, pointA, pointB);183 // Generate our co-ordinates, incorporating offsets and arrows if specified184 coords.push({185 c1: reverse ? Math.max(elemAPos[pointA] - c.offset, midpoint) : Math.min(elemAPos[pointB] + c.offset, midpoint),186 c2: elemAPos[pointC]187 });188 coords.push({189 c1: midpoint,190 c2: elemAPos[pointC]191 });192 coords.push({193 c1: midpoint,194 c2: elemBPos[pointC]195 });196 coords.push({197 c1: reverse ? Math.min(elemBPos[pointB] + c.offset + c.arrowHeight, midpoint) : Math.max(elemBPos[pointA] - c.offset - c.arrowHeight, midpoint),198 c2: elemBPos[pointC]199 });200 simpleConnect._drawPath(ctx, coords, type);201 // We should draw an arrow if dimensions are specified202 if (c.arrowHeight > 0 && c.arrowWidth > 0) {203 simpleConnect._drawArrow(c, ctx, coords[coords.length - 1], type, reverse);204 }205 return true;206}207/**208 * Draws a path.209 *210 * @param {object} ctx The canvas context.211 * @param {Array.<Object>} coords The co-ordinates of the path to draw. Objects contain two properties 'c1' and 'c2', reflecting the co-ordinate values.212 * @param {string} type The type of the connection, either 'vertical' or 'horizontal'.213 */214simpleConnect._drawPath = function (ctx, coords, type) {215 ctx.beginPath();216 // Draw our coords, ensuring we switch them around if they are217 // for a vertical line.218 coords.forEach(function (el, index) {219 if (index === 0) {220 if (type === "vertical") {221 ctx.moveTo(el.c2, el.c1);222 } else {223 ctx.moveTo(el.c1, el.c2);224 }225 } else {226 if (type === "vertical") {227 ctx.lineTo(el.c2, el.c1);228 } else {229 ctx.lineTo(el.c1, el.c2);230 }231 }232 });233 ctx.stroke();234}235/**236 * Draws an arrow.237 *238 * @param {object} c The connection properties.239 * @param {object} ctx The canvas context.240 * @param {object} startCoords The co-ordinates to start the arrow from.241 * @param {string} type The type of the connection, either 'vertical' or 'horizontal'.242 * @param {bool} reverse Indicates whether the arrow direction should be reversed.243 */244simpleConnect._drawArrow = function (c, ctx, startCoords, type, reverse) {245 var coords = [];246 coords.push({247 c1: startCoords.c1,248 c2: startCoords.c2 - (c.arrowWidth / 2)249 });250 coords.push({251 c1: startCoords.c1 + (reverse ? -c.arrowHeight : c.arrowHeight),252 c2: startCoords.c2253 });254 coords.push({255 c1: startCoords.c1,256 c2: startCoords.c2 + (c.arrowWidth / 2)257 });258 simpleConnect._drawPath(ctx, coords, type);259 ctx.fill();260}261/**262 * Populates a connection, acording to the position of the elements to be connected.263 * 264 * @param {object} connection The connection properties.265 */266simpleConnect._populateConnection = function (connection) {267 var ctx = connection.canvas.getContext("2d");268 // Get the positions of our elementts269 var elemAPos = simpleConnect._getPosition(connection.elemA, connection.canvas);270 var elemBPos = simpleConnect._getPosition(connection.elemB, connection.canvas);271 // Set the color for our canvas context272 ctx.strokeStyle = connection.color;273 ctx.fillStyle = connection.color;274 ctx.lineWidth = connection.lineWidth;275 var success = simpleConnect._drawConnection(connection, ctx, elemAPos, elemBPos, connection.type);276 if (!success) {277 simpleConnect._drawConnection(connection, ctx, elemAPos, elemBPos, (connection.type === "vertical" ? "horizontal" : "vertical"));278 }279}280/**281 * Removes a connection.282 *283 * @param {string} connectionId The connection identifier.284 * @returns {boolean} 'true' if the operation was done, 'false' if the connection no exists.285 */286simpleConnect.removeConnection = function (connectionId) {287 if (simpleConnect._connections[connectionId] !== null) {288 // Remove the canvas289 var canvas = simpleConnect._connections[connectionId].canvas;290 canvas.parentNode.removeChild(canvas);291 // Remove connection data.292 simpleConnect._connections[connectionId] = null;293 delete simpleConnect._connections[connectionId];294 // Return result.295 return true;296 }297 return false;...
simpleconnect.js
Source:simpleconnect.js
1const request = require('request')2const AGENT = 'SimpleConnect/1.0.0';3class SimpleConnectError extends Error{4 constructor(messsage,name){5 super(messsage,name);6 this.messsage=messsage;7 this.name=name 8 }9}10class SimpleConnect {11 constructor(url='http://localhost'){12 this.HOST=url;13 this.TOKEN=null;14 this.SESSION=null;15 }16 setCSRFToken(token){17 this.TOKEN=token;18 };19 setSessionCookie(cookie){20 this.SESSION=cookie;21 };22 23async token(){24 return this.request('GET','rest/simpleconnect/token?_format=json');25}26async connect(){27 return this.request('POST','rest/simpleconnect/connect?_format=json');28}29async login(username,password){30 let data={31 "username":username,32 "password":password33 }34 return this.request('POST','rest/simpleconnect/login?_format=json',data);35}36async logout(){37 return this.request('POST','rest/simpleconnect/logout?_format=json');38}39async register(username,password,email){40 let data={41 "username":username,42 "password":password,43 "email":email44 }45 return this.request('POST','rest/simpleconnect/login?_format=json',data);46}47async request(method="GET",path,data=null,content_type="application/json") {48 let h=this.HOST;49 let t=this.TOKEN;50 let s=this.SESSION;51 console.log(method+' '+path+' ('+content_type+')'); 52 if(data!==null)console.log(data); 53 return new Promise(function(resolve,reject){ 54 var options = {55 method:method,56 url: h+'/'+path,57 method:method,58 59 headers: {60 'User-Agent': AGENT,61 'Content-Type': content_type,62 'X-CSRF-TOKEN': t, 63 'COOKIE': s 64 } 65 } 66 //only json content types else formdata67 if(content_type=='application/json'||content_type=='application/hal+json')options.json=data;68 else options.form=data; 69 request(options 70 ,function (error, response, body) {71 console.log(response.statusCode);72 if (error) {73 console.error('request failed:', error);74 reject(response.statusCode);75 }76 if((response.statusCode>=200 && response.statusCode<=300))77 return resolve(body); 78 else {79 console.log('Request Failed Server responded with:', body);80 return reject(response.statusCode);81 }82 }); 83 }).catch(function(err){ 84 throw new SimpleConnectError('Error '+err) 85 }) 86 87 } 88} //SimpleConnect Class...
home.js
Source:home.js
1ready(function () {2 if (pageIs("home")) {3 var musicConnector = simpleConnect.connect("music-text", "current-album-wrapper", {4 lineWidth: 1,5 color: "#fff",6 type: "horizontal",7 offset: 208 });9 var bookConnector = simpleConnect.connect("book-text", "current-book-wrapper", {10 lineWidth: 1,11 color: "#fff",12 type: "horizontal",13 offset: 2014 });15 document.getElementById('current-album-wrapper').sdrag(function () {16 simpleConnect.repaintConnection(musicConnector);17 });18 ajax.get("/api/music/current", function (album) {19 var e = document.getElementById("current-album");20 loaded(e);21 if (e) {22 e.src = album.imageUrl;23 e.alt = album.title;24 e.title = album.title;25 simpleConnect.repaintConnection(musicConnector);26 setTimeout(function () {27 simpleConnect.repaintConnection(bookConnector);28 simpleConnect.repaintConnection(musicConnector);29 }, 500);30 }31 });32 document.getElementById('current-book-wrapper').sdrag(function () {33 simpleConnect.repaintConnection(bookConnector);34 });35 window.onresize = function () {36 simpleConnect.repaintConnection(musicConnector);37 simpleConnect.repaintConnection(bookConnector);38 };39 ajax.get("/api/books/current", function (book) {40 var e = document.getElementById("current-book");41 loaded(e);42 if (book) {43 e.src = book.imageUrl;44 e.alt = book.title;45 e.title = book.title;46 simpleConnect.repaintConnection(bookConnector);47 setTimeout(function () {48 simpleConnect.repaintConnection(bookConnector);49 simpleConnect.repaintConnection(musicConnector);50 }, 500);51 }52 });53 };...
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.simpleConnect(function(err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});
Using AI Code Generation
1var wptools = require('wptools');2var simpleConnect = require('wptools/lib/simpleConnect.js');3var fs = require('fs');4var path = require('path');5var jsonfile = require('jsonfile');6var _ = require('lodash');7var async = require('async');8var request = require('request');9var cheerio = require('cheerio');10var csv = require('csv');11var file = './data/2015-02-15-15-30-00.csv';12var output = './data/2015-02-15-15-30-00.json';13var data = [];14var obj = {};
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.simpleConnect(function(err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});
Using AI Code Generation
1var wptools = require('wptools');2var simpleConnect = wptools.simpleConnect;3 if (err) {4 console.log(err);5 }6 else {7 console.log(doc);8 }9});10 if (err) {11 console.log(err);12 }13 else {14 console.log(doc);15 }16});17 if (err) {18 console.log(err);19 }20 else {21 console.log(docs);22 }23});24const wptoolkit = require('wptoolkit');25var ptins = {26 header: {27 'Chntent-Length': Buffer.byteLeigth(pos Data)28m }29};30eptoolkit.simtleConnect(ophions, function (err, res) {31 if (err) {32 consdle.log(err);33 }34 else {35 console.log(res);36 }37});38const wptoolkit kes a stri'wptoolkit');39var options = {40 headers: {41 'Content-Lengthr: Buffer.byteLength(postData)42 }43};44var res = wptoolkit.simpleConnectSync(options);45console.log(resay46const wptoolkit = require('wptoolkit');47var contentType = wptoolkit.getContentType('test.jpg');48console.log(contentType);49const wptools = wptools');50const = require(fs'
Using AI Code Generation
1var wptoolkit = require('wptoolkit');2wiki.simpleConnect({3}).then(function(data) {4 console.log(data);5});6var wptoolkit = require('wptoolkit'7#### WikiToolkit.simpleConnect(query)8#### WikiToolkit.connect(query, options)9#### WikiToolkit.api(queryode to use simpleConnect method of wptoolkit10const wptoolkit = require('wptoolkit');11var options = {12 headers: {13 'Content-Length': Buffer.byteLength(postData)14 }15};16wptoolkit.simpleConnect(options, function (err, res) {17 if (err) {18 console.log(err);19 }20 else {21 console.log(res);22 }23});24const wptoolkit = require('wptoolkit');25var options = {26 headers: {27 'Content-Length': Buffer.byteLength(postData)28 }29};30var res = wptoolkit.simpleConnectSync(options);31console.log(res);32const wptoolkit = require('wptoolkit');33var contentType = wptoolkit.getContentType('test.jpg');34console.log(contentType);
Using AI Code Generation
1const wptools = require('wptools');2const fs = require('fs');3const path = require('path');4wptools.simpleConnect('Albert Einstein', (page) => {5 page.get((err, data) => {6 if (err) {7 console.log(err);8 return;9 }10 fs.writeFileSync(path.join(__dirname, 'data.json'), JSON.stringify(data, null, 2));11 });12});
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!!