Best JavaScript code snippet using best
sketch.js
Source:sketch.js
1/// <reference path="C:/Users/nicsn/projects/resources/p5_definitions/global.d.ts" />2// parameters to be controlledst3const controls = {4 sigma: 10,5 rho: 28,6 beta: 8.0 / 3.0,7 t: 0.01,8 partNum: 400,9 partSize: 1,10 outlines: false,11 view: "rotate",12 trace: false,13 spread: 5,14 spawnPoint: {x: 7, y: -9, z: 0}15}16let paused = false;17let fpsGraph;18let clock = -600; // allows the camera to orbit in "rotate" view. -600 looks good at the start of the default settings19let fov; // used for remembering current field of view and resizing the window20// looking back, I could have just moved the camera to get a similar effect as this.21// however, this lets me directly use 1 as the smallest particle size which is nice.22let scaleFactor = 4;23let scaleFactorTail = scaleFactor * 1; // in case you want to to exaggerate speed stretch (doesn't look that good)24const particles = [];25// define a particle class26class particle {27 constructor(x, y, z, color) {28 this.x = x;29 this.y = y;30 this.z = z;31 this.color = color;32 this.dir = createVector(0, 0, 0);33 }34 35 // move the particle to its next position in time and get new size from speed 36 update(sigma, rho, beta, t) {37 let dx = sigma * (this.y - this.x);38 let dy = this.x * (rho - this.z) - this.y;39 let dz = this.x * this.y - beta * this.z;40 this.x += dx * t;41 this.y += dy * t;42 this.z += dz * t;43 this.dir.set(dx * t, dy * t, dz * t); // set the velocity vector44 }45 // draw a speed-stretched box between the current and previous positions46 draw() {47 let initVec = createVector(1, 0, 0); // represents the box's x axis (arbitrarily, but so that I can scale the box's width property)48 push();49 translate(this.x * scaleFactor, this.y * scaleFactor, this.z * scaleFactor); // get to position50 // this line is bonkers.51 // we decide the box is traveling along its x axis (or the vector [1, 0, 0]), so that we can simply scale its width.52 // we get the angle between that vector and the velocity vector which together define a plane.53 // we then rotate by that angle around an axis normal to that plane (axis vector obtained from cross product).54 // it's important to use the absolute value of that angle (0 <= angle <= 180), otherwise it doesn't work right (i don't know why, mathematically).55 rotate(abs(initVec.angleBetween(this.dir)), initVec.cross(this.dir)); // align box x axis with direction56 translate(-this.dir.mag() * scaleFactorTail / 2, 0, 0); // adjust box origin from the center to front face57 fill(this.color);58 box(max(this.dir.mag() * scaleFactorTail, controls.partSize), controls.partSize, controls.partSize); // draw box elongated to previous location59 pop();60 }61}62// spawn particles63function createParticles(number) {64 const colRand = [0, 0, 0];65 for(let i = 0; i < number; i++) {66 let colRandIndex = random([0, 1, 2]);67 colRand[colRandIndex] = 255;68 // this wacky lil formula randomly targets an rgb component other than the one selected previously69 // and assigns it a random value 0-25570 colRand[(random([1, 2]) + colRandIndex) % 3] = random(255);71 particles.push(new particle(72 random(-1, 1) * max(controls.spread, .000000001) + controls.spawnPoint.x, // minimum spread is 1 billionth of a unit73 random(-1, 1) * max(controls.spread, .000000001) - controls.spawnPoint.y,74 random(-1, 1) * max(controls.spread, .000000001) + controls.spawnPoint.z + 27,75 color(...colRand)));76 }77}78// reset trace when switching views79function viewChanged() {80 trace.checkbox.checked(false);81}82// yup, it's that easy.83function windowResized() {84 resizeCanvas(windowWidth, windowHeight);85}86function setup() {87 pixelDensity(1); // account for high-density displays88 createCanvas(windowWidth, windowHeight, WEBGL); // 3D mode89 background(0); // initialize90 91 // set up gui92 // define where the control panel should go93 const controlsContainer = createDiv();94 controlsContainer.id("controlsContainer");95 controlsContainer.style("position", "fixed"); // always visible, even when scrolling96 controlsContainer.style("top", "10px");97 controlsContainer.style("right", "10px"); // left or right98 controlsContainer.style("width", "300px");99 // create a pane as a child of the previously created div100 const pane = new Tweakpane.Pane({container: document.getElementById("controlsContainer"), title: "controls", expanded: true});101 pane.registerPlugin(TweakpaneEssentialsPlugin); // add plugin for fpsgraph102 pane.addSeparator();103 const pauseBtn = pane.addButton({title: "pause"}); // create pause button104 pauseBtn.on("click", () => { // alternatively, use () => yourFunc(anArg, anotherArg) to call any function with arguments105 if(!paused) {106 paused = true;107 pauseBtn.title = "resume";108 } else {109 paused = false;110 pauseBtn.title = "pause";111 }112 });113 pane.addSeparator();114 pane.addInput(controls, "t", {label: "time step", min: 0.0001, max: 0.01, format: (v) => v.toFixed(4)});115 pane.addInput(controls, "partNum", {label: "particle number", min: 1, max: 1000, step: 1}).on("change", (ev) => {116 // IS THIS SETTING PART NUM BEFORE THIS CODE??117 if(controls.partNum > particles.length) { // update particles118 createParticles(controls.partNum - particles.length);119 } else {120 let dif = particles.length - controls.partNum;121 for(let i = 0; i < dif; i++) {122 particles.shift();123 }124 }125 });126 pane.addInput(controls, "partSize", {label: "particle size", min: 1, max: 30, step: 1});127 pane.addInput(controls, "outlines", {label: "draw outlines"});128 pane.addInput(controls, "trace");129 pane.addInput(controls, "view", {options: {rotate: "rotate", top: "top", bottom: "bottom", side: "side"}}).on("change", () => {130 background(0);131 });132 pane.addSeparator();133 pane.addButton({title: "respawn particles"}).on("click", () => {134 background(0);135 while(particles.length > 0) { // delete existing particles136 particles.pop();137 }138 createParticles(controls.partNum);139 if(paused) {140 paused = false;141 pauseBtn.title = "pause";142 }143 })144 pane.addInput(controls, "spread");145 pane.addInput(controls, "spawnPoint", {label: "spawn point", x: {min: -30, max: 30}, y: {min: -30, max: 30}, z: {min: -30, max: 30}});146 147 pane.addSeparator();148 const stats = pane.addFolder({title: "stats", expanded: false});149 fpsGraph = stats.addBlade({view: "fpsgraph", label: "fps"});150 // set up particles151 createParticles(controls.partNum);152}153function draw() {154 fpsGraph.begin();155 if(!paused) {156 if(!controls.trace) { // clear every frame or not157 background(0);158 }159 // camera controls160 switch(controls.view) { // based on the currently selected view161 case "rotate":162 if(!controls.trace) {163 traceClicked = true;164 // draw box to help visualize rotation165 push();166 stroke(255, 64);167 noFill();168 box(60 * scaleFactor);169 pop();170 } else if(traceClicked) {171 background(0); // clear the box when clicking trace172 traceClicked = false;173 }174 camera(sin(clock / 360) * 100 * scaleFactor, cos(clock / 360) * 100 * scaleFactor, 0, 0, 0, 0, 0, 0, -1); // orbital camera175 fov = PI / 3;176 perspective(fov, width / height); // reset FoV, update aspect ratio to allow proper screen resizing177 break;178 case "top":179 camera(0, 0, 212 * scaleFactor, 0, 0, 0, 0, 1, 0); // fixed camera180 fov = .4;181 perspective(fov, width / height); // zoom in with FoV182 break;183 case "bottom":184 camera(0, 0, -212 * scaleFactor, 0, 0, 0, 0, 1, 0);185 fov = .4;186 perspective(fov, width / height);187 break;188 case "side":189 camera(150 * scaleFactor, -150 * scaleFactor, 0, 0, 0, 0, 0, 0, -1);190 fov = .4;191 perspective(fov, width / height);192 break;193 }194 push();195 if(controls.outlines) { // draw outlines or not196 stroke(64);197 strokeWeight(.66); // good value if you want to use larger particle sizes198 } else {199 noStroke();200 }201 translate(0, 0, -27 * scaleFactor); // center the system202 let len = particles.length;203 for(let i = 0; i < len; i++) { // calculate and draw the actual particles204 particles[i].update(controls.sigma, controls.rho, controls.beta, controls.t);205 particles[i].draw();206 }207 pop();208 clock++;209 }210 fpsGraph.end();...
map.component.ts
Source:map.component.ts
1import { Component, EventEmitter, OnInit, Output, ViewChild } from '@angular/core';2import { Layout, PlotData, PlotMouseEvent } from 'plotly.js';3import { PlotlyComponent } from 'angular-plotly.js';4import { Map, MapboxEvent, Popup } from 'mapbox-gl';5import { cloneDeep } from 'lodash';6import { ExerciseService } from 'src/app/core/exercise.service';7import { SqlResult } from 'src/app/core/models/sql-result';8import { CustomEvent } from './../custom-event.model';9import { environment } from 'src/environments/environment';10@Component({11 selector: 'app-map',12 templateUrl: './map.component.html',13 styleUrls: ['./map.component.scss']14})15export class MapComponent implements OnInit {16 // Inputs and outputs17 @Output() traceClicked = new EventEmitter<CustomEvent>();18 @Output() traceFocused = new EventEmitter<CustomEvent>();19 // reference to the plotly object20 @ViewChild(PlotlyComponent) private plotlyComponent: PlotlyComponent;21 // component state22 exampleName: string;23 // setup the layout24 layout = {25 autosize: true,26 showlegend: false,27 margin: {t: 0, b: 0, l: 0, r: 0},28 mapbox: {29 style: 'carto-darkmatter',30 center: {lon: 8.383461377967592, lat: 48.991553942176864},31 zoom: 13.2,32 bearing: 57.2,33 pitch: 42.234 },35 paper_bgcolor: '#1A2A32',36 plot_bgcolor: '#1A2A32'37 } as Layout;38 // layer array39 data: PlotData[] = [{40 name: 'Example data',41 type: 'scattermapbox',42 lon: [8.383461377967592], lat: [48.991553942176864],43 text: ['Examples are about to be loaded'],44 marker: {size: 24, color: 'cyan'}45 } as PlotData];46 // instances47 plot: any;48 map: Map;49 popup = new Popup();50 // examples51 examplesCache: {[key: string]: any} = {};52 queries = {53 hobo: 'select m.id, device_id, st_x(location) as lon, st_y(location) as lat, avg(value) as day from raw_data d JOIN metadata m ON m.id=d.meta_id where variable_id=1 and date_part(\'hour\', tstamp) >= 6 and date_part(\'hour\', tstamp) < 19 group by m.id, lon, lat',54 };55 constructor(private exerciseService: ExerciseService) { }56 ngOnInit(): void {57 }58 onPlotlyLoaded(plotlyObject: any): void {59 // store the references60 this.plot = (this.plotlyComponent.plotlyInstance as any)._fullLayout;61 this.map = this.plot.mapbox ? this.plot.mapbox._subplot.map : undefined;62 // add to window in debug mode63 if (!environment.production) {64 (window as any).map = this.map;65 }66 this.hoboExample();67 }68 private hoboExample(): Promise<void> {69 // check if data is available70 if (!this.examplesCache.hobo) {71 this.exerciseService.executeSql('SELECT count(*) as amt FROM metadata;')72 .then((result: SqlResult) => {73 if (result.data[0].amt > 10) {74 this.exerciseService.executeSql(this.queries.hobo)75 .then((res: SqlResult) => {76 this.examplesCache.hobo = cloneDeep(res.data);77 return this.hoboExample();78 });79 } else {80 return new Promise(resolve => {81 console.log('HOBO example has not enough data.');82 resolve();83 });84 }85 });86 } else {87 // data is available88 const d: {device_id: string, lon: number, lat: number, day: number}[] = this.examplesCache.hobo;89 this.data = [{90 name: 'Uni Freiburg Hobo data',91 type: 'scattermapbox',92 lon: d.map(v => v.lon),93 lat: d.map(v => v.lat),94 text: d.map(v => `HOBO ${v.device_id}: ${v.day.toFixed(1)}°C`),95 z: d.map(v => v.day),96 marker: {size: 16, colorscale: 'Reds', color: d.map(v => v.day)}97 } as PlotData];98 // set the current example99 this.exampleName = 'hobo';100 // start animation101 return this.animateHobo(0, true);102 }103 }104 private animateHobo(index: number, rand?: boolean): Promise<void> {105 const rotateFn = (e: MapboxEvent): void => {106 // rotate107 const map = e.target;108 map.rotateTo(109 map.getBearing() + 90 > 360 ? map.getBearing() + 90 - 360 : map.getBearing() + 90,110 { duration: 40000 }111 );112 };113 const idx = rand ? Math.round(Math.random() * this.examplesCache.hobo.length) : index;114 const hobo = (this.examplesCache.hobo as {device_id: string, lon: number, lat: number, day: number}[])[idx];115 // first fly to the new Point116 this.map.flyTo({117 center: {lon: hobo.lon, lat: hobo.lat},118 zoom: Math.random() * 5 + 14,119 bearing: Math.random() * 360,120 duration: 8000121 });122 this.map.on('moveend', rotateFn);123 // emit the focus event124 this.traceFocused.emit({125 activeExample: 'hobo',126 feature: hobo,127 reference: this.examplesCache.hobo.map(h => h.day)128 });129 return new Promise(resolve => {130 // set the Timeout to go to the next point131 const time = Math.round(Math.random() * 25000) + 8000;132 setTimeout(() => {133 this.map.off('moveend', rotateFn);134 }, time);135 if (index + 1 < (this.examplesCache.hobo as any[]).length) {136 setTimeout(() => this.animateHobo(index + 1, rand), time);137 } else {138 setTimeout(() => resolve(), time);139 }140 });141 }142 onPlotlyClicked(e: PlotMouseEvent): void {143 if (!environment.production) {144 console.log(e);145 }146 this.traceClicked.emit({activeExample: this.exampleName, points: e.points});147 }...
trace_buttons_component.js
Source:trace_buttons_component.js
...9 this.state = {10 parentFlight : this.props.parentFlight11 };12 }13 traceClicked(seriesName) {14 this.props.showPlot();15 let parentFlight = this.state.parentFlight;16 //check to see if we've already loaded this time series17 if (!(seriesName in parentFlight.state.traceIndex)) {18 var thisTrace = this;19 console.log(seriesName);20 console.log("seriesName: " + seriesName + ", flightId: " + this.props.flightId);21 var submissionData = {22 flightId : this.props.flightId,23 seriesName : seriesName24 }; 25 $.ajax({26 type: 'POST',27 url: '/protected/double_series',28 data : submissionData,29 dataType : 'json',30 success : function(response) {31 console.log("received response: ");32 console.log(response);33 var trace = {34 x : response.x,35 y : response.y,36 mode : "lines",37 //marker : { size: 1},38 name : thisTrace.props.flightId + " - " + seriesName39 }40 //set the trace number for this series41 parentFlight.state.traceIndex[seriesName] = $("#plot")[0].data.length;42 parentFlight.state.traceVisibility[seriesName] = true;43 parentFlight.setState(parentFlight.state);44 Plotly.addTraces('plot', [trace]);45 }, 46 error : function(jqXHR, textStatus, errorThrown) {47 errorModal.show("Error Loading Flight Coordinates", errorThrown);48 }, 49 async: true 50 }); 51 } else {52 //toggle visibility for this series53 let visibility = !parentFlight.state.traceVisibility[seriesName];54 parentFlight.state.traceVisibility[seriesName] = visibility;55 parentFlight.setState(parentFlight.state);56 console.log("toggled visibility to: " + visibility);57 Plotly.restyle('plot', { visible: visibility }, [ parentFlight.state.traceIndex[seriesName] ])58 }59 }60 render() {61 let cellClasses = "d-flex flex-row p-1";62 let cellStyle = { "overflowX" : "auto" };63 let buttonClasses = "m-1 btn btn-outline-secondary";64 const styleButton = {65 flex : "0 0 10em"66 };67 let parentFlight = this.state.parentFlight;68 return (69 <div>70 <b className={"p-1"} style={{marginBottom:"0"}}>Flight Parameters:</b>71 <div className={cellClasses} style={cellStyle}>72 {73 parentFlight.state.commonTraceNames.map((traceName, index) => {74 let ariaPressed = parentFlight.state.traceVisibility[traceName];75 let active = "";76 if (ariaPressed) active = " active";77 return (78 <button className={buttonClasses + active} key={traceName} style={styleButton} data-toggle="button" aria-pressed={ariaPressed} onClick={() => this.traceClicked(traceName)}>79 {traceName}80 </button>81 );82 })83 }84 </div>85 <div className={cellClasses} style={cellStyle}>86 {87 parentFlight.state.uncommonTraceNames.map((traceName, index) => {88 let ariaPressed = parentFlight.state.traceVisibility[traceName];89 let active = "";90 if (ariaPressed) active = " active";91 return (92 <button className={buttonClasses + active} key={traceName} style={styleButton} data-toggle="button" aria-pressed={ariaPressed} onClick={() => this.traceClicked(traceName)}>93 {traceName}94 </button>95 );96 })97 }98 </div>99 </div>100 );101 }102}...
Using AI Code Generation
1var BestBuyAPI = require('bestbuy');2var bestbuy = new BestBuyAPI('yourapikey');3bestbuy.traceClicked({sku: 12345}, function(err, data) {4 if (err) { console.log(err); }5 console.log(data);6});7var BestBuyAPI = require('bestbuy');8var bestbuy = new BestBuyAPI('yourapikey');9bestbuy.traceClicked({sku: 12345}, function(err, data) {10 if (err) { console.log(err); }11 console.log(data);12});13var BestBuyAPI = require('bestbuy');14var bestbuy = new BestBuyAPI('yourapikey');15bestbuy.traceClicked({sku: 12345}, function(err, data) {16 if (err) { console.log(err); }17 console.log(data);18});19var BestBuyAPI = require('bestbuy');20var bestbuy = new BestBuyAPI('yourapikey');21bestbuy.traceClicked({sku: 12345}, function(err, data) {22 if (err) { console.log(err); }23 console.log(data);24});25var BestBuyAPI = require('bestbuy');26var bestbuy = new BestBuyAPI('yourapikey');27bestbuy.traceClicked({sku: 12345}, function(err, data) {28 if (err) { console.log(err); }29 console.log(data);30});31var BestBuyAPI = require('bestbuy');32var bestbuy = new BestBuyAPI('yourapikey');33bestbuy.traceClicked({sku: 12345}, function(err, data) {34 if (err) { console.log(err); }35 console.log(data);36});37var BestBuyAPI = require('bestbuy');38var bestbuy = new BestBuyAPI('yourapikey');39bestbuy.traceClicked({sku: 12345}, function(err, data) {40 if (err) { console.log(err); }
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!!