Best JavaScript code snippet using wpt
gesture-store.ts
Source:gesture-store.ts
1import { computed, observable, action } from "mobx";2import { Gesture, MotionReading, GestureExampleData, Match } from "./motion";3import { SingleDTWCore } from "./model";4import { serialData } from "./serial-data";5const READING_HISTORY_LIMIT = 30;6const createLowPassFilter = () => {7 const alpha = 0.5;8 let previousSmoothed = 0;9 return (value: number) => {10 const smoothed = alpha * value + (1 - alpha) * previousSmoothed;11 previousSmoothed = smoothed;12 return smoothed;13 }14}15export class GestureStore {16 // contains all of the gesture data17 @observable public gestures: Gesture[] = [];18 // is the Circuit Playground streaming accelerometer data or not19 @observable public connected: boolean;20 // needs saving21 @observable public hasBeenModified: boolean = false;22 @observable public readings: MotionReading[] = []; // 0 <= length < READING_HISTORY_LIMIT 23 @observable public latestTimestamp: number = 0;24 @observable public matches: Match[] = [];25 private models: SingleDTWCore[] = [];26 private idToType: pxt.Map<string> = {};27 private extId: string;28 private curGestureIndex: number = 0;29 public saveBlocks = debounce(() => this.saveBlocksNow(), 2000);30 constructor() {31 this.extId = window.location.hash.substr(1);32 console.log(`extension id: ${this.extId}`)33 window.addEventListener(34 "message",35 ev => ev.data.type == "pxtpkgext" ? this.receiveMessage(ev.data) : undefined,36 false);37 this.sendRequest("extinit");38 const filterX = createLowPassFilter();39 const filterY = createLowPassFilter();40 const filterZ = createLowPassFilter();41 serialData.register(data => {42 const accelX = filterX(data.accVec.accelX);43 const accelY = filterY(data.accVec.accelY);44 const accelZ = filterZ(data.accVec.accelZ);45 this.readings.push(new MotionReading(accelX, accelY, accelZ));46 this.latestTimestamp++;47 if (this.readings.length > READING_HISTORY_LIMIT) {48 this.readings.shift();49 }50 if (this.currentModel && this.currentModel.isRunning()) {51 let match = this.currentModel.feed(data.accVec);52 if (match) {53 this.matches.push(match);54 }55 }56 });57 }58 public get readingLimit() { return READING_HISTORY_LIMIT; }59 @computed public get currentModel() {60 return this.models[this.curGestureIndex];61 }62 @computed public get currentGesture() {63 return this.gestures[this.curGestureIndex];64 }65 @computed public get currentOrientation() {66 return this.readings.length ?67 this.readings[this.readings.length - 1] :68 undefined;69 }70 public isMatch(readingIndex: number): boolean {71 const time = this.latestTimestamp - (this.readings.length - 1 - readingIndex);72 return this.matches.findIndex(m => m.startTime <= time && time <= m.endTime) >= 0;73 }74 @action public setCurrentGesture(gestureId: number): void {75 this.curGestureIndex = this.gestures.findIndex(g => g.gestureID === gestureId);76 this.currentModel.update(this.gestures[this.curGestureIndex].getCroppedData(), this.latestTimestamp); 77 }78 @action public deleteSample(gesture: Gesture, sample: GestureExampleData) {79 let cloneData = this.gestures.slice();80 const gi = this.gestures.indexOf(gesture);81 const si = this.gestures[gi].samples.indexOf(sample);82 cloneData[gi].samples.splice(si, 1);83 const model = this.models[gi];84 model.update(cloneData[gi].getCroppedData(), this.latestTimestamp);85 cloneData[gi].displayGesture = model.prototype;86 this.gestures = cloneData;87 this.markDirty();88 }89 @action public addSample(gesture: Gesture, newSample: GestureExampleData) {90 let cloneData = this.gestures.slice();91 const gestureIndex = this.gestures.indexOf(gesture);92 // do not change the order of the following lines:93 cloneData[gestureIndex].samples.unshift(newSample);94 gestureStore.currentModel.update(cloneData[gestureIndex].getCroppedData(), this.latestTimestamp);95 cloneData[gestureIndex].displayGesture = gestureStore.currentModel.prototype;96 this.gestures = cloneData;97 this.markDirty();98 }99 private receiveMessage(data: pxt.editor.ExtensionMessage) {100 const ev = data as pxt.editor.ExtensionEvent;101 if (ev.event) {102 switch (ev.event) {103 case "extconsole":104 const cons = ev as pxt.editor.ConsoleEvent;105 // drop sim106 if (cons.body.sim) return;107 this.onSerialData(cons.body.data);108 break;109 case "extshown":110 console.log('pxt-gestures shown')111 this.connected = true;112 this.sendRequest("extdatastream");113 this.sendRequest("extreadcode")114 break;115 case "exthidden":116 console.log('pxt-gestures hidden')117 this.connected = false;118 break;119 default:120 break;121 }122 return;123 }124 const action = this.idToType[data.id];125 console.log(`msg: ${action}`)126 delete this.idToType[data.id];127 switch (action) {128 case "extinit":129 this.sendRequest("extdatastream");130 this.sendRequest("extreadcode");131 break;132 case "extreadcode":133 // received existing code134 const usercode = data as pxt.editor.ReadCodeResponse;135 this.loadBlocks(usercode.resp.code, usercode.resp.json);136 break;137 default: break;138 }139 }140 private sendRequest(action: string, body?: any) {141 const id = Math.random().toString();142 this.idToType[id] = action;143 const msg = {144 type: "pxtpkgext",145 action: action,146 extId: this.extId,147 response: true,148 id: id,149 body150 };151 if (window.parent && window != window.parent)152 window.parent.postMessage(msg, "*");153 }154 /**155 * Initializes the serial port (using hid for the Circuit Playground) and sets the onSerialData event function156 * to update the realtime graph, feed the recorder, and feed the realtime DTW model (if it is running)157 */158 private onSerialData(strBuf: string) {159 const newData = parseString(strBuf);160 if (newData && newData.acc)161 serialData.notify(newData);162 this.connected = true;163 }164 /**165 * updates this.state.data[] array and the models[] array with a 166 * new Gesture and switches to the editGesture window167 */168 @action public addGesture() {169 this.gestures.push(new Gesture());170 // TODO: change this method of keeping the current gesture index to something more reliable171 this.curGestureIndex = this.gestures.length - 1;172 const model = new SingleDTWCore(this.gestures[this.curGestureIndex].gestureID + 1, this.gestures[this.curGestureIndex].name);173 this.models.push(model);174 }175 /**176 * will generate the code blocks for each running DTW model and will rewrite 177 * the contents of the custom.ts file with 178 */179 private saveBlocksNow() {180 if (!this.hasBeenModified) return;181 let cloneData = this.gestures.slice();182 const codeBlocks: string[] = this.models183 .filter(m => m.isRunning())184 .map(m => m.generateBlock());185 const code = SingleDTWCore.generateNamespace(codeBlocks);186 const json = JSON.stringify(this.gestures, null, 2);187 this.sendRequest("extwritecode", { code, json });188 this.hasBeenModified = false;189 this.gestures = cloneData; // FIXME: Why did Majeed do this?190 }191 markDirty() {192 if (!this.hasBeenModified) {193 this.hasBeenModified = true;194 this.saveBlocks();195 }196 }197 @action private loadBlocks(code: string, json: string) {198 if (!json) return;199 let jsonGestures: Gesture[] = JSON.parse(json);200 if (!jsonGestures) return;201 this.gestures = jsonGestures.map(importedGesture => 202 Gesture.parseGesture(importedGesture));203 this.models = this.gestures.map(gesture => {204 let model = new SingleDTWCore(gesture.gestureID + 1, gesture.name);205 model.update(gesture.getCroppedData(), this.latestTimestamp);206 return model;207 });208 }209 /**210 * Removes the currently active gesture if it contains no samples211 */212 @action public deleteIfGestureEmpty() {213 if (this.gestures.length > 0 && this.gestures[this.curGestureIndex].samples.length == 0) {214 // delete the gesture215 let cloneData = this.gestures.slice();216 cloneData.splice(this.curGestureIndex, 1);217 // delete the model218 this.models.splice(this.curGestureIndex, 1);219 this.gestures = cloneData;220 }221 }222 @action public deleteGesture(gesture: Gesture) {223 const index = this.gestures.indexOf(gesture);224 if (index >= 0) {225 this.gestures.splice(index, 1);226 this.models.splice(index, 1);227 this.markDirty();228 }229 }230}231// Returns a function, that, as long as it continues to be invoked, will not232// be triggered. The function will be called after it stops being called for233// N milliseconds. If `immediate` is passed, trigger the function on the234// leading edge, instead of the trailing.235function debounce(func: (...args: any[]) => any, wait: number, immediate?: boolean): any {236 let timeout: any;237 return function () {238 let context = this;239 let args = arguments;240 let later = function () {241 timeout = null;242 if (!immediate) func.apply(context, args);243 };244 let callNow = immediate && !timeout;245 clearTimeout(timeout);246 timeout = setTimeout(later, wait);247 if (callNow) func.apply(context, args);248 };249}250function parseString(strBuf: string): any {251 // populate members of newData (type: SensorData) with the values received from the device252 let strBufArray = strBuf.split(" ");253 let result = {254 acc: false, accVec: new MotionReading(0, 0, 0),255 /*mag: false, magVec: new Vector(0, 0, 0)*/256 };257 for (let i = 0; i < strBufArray.length; i++) {258 if (strBufArray[i] == "A") {259 result.accVec = new MotionReading(260 parseInt(strBufArray[i + 1]), 261 parseInt(strBufArray[i + 2]), 262 parseInt(strBufArray[i + 3]));263 result.acc = true;264 i += 3;265 }266 }267 return result;268}...
biquad-filters.js
Source:biquad-filters.js
...4//5// The formulas for the various filters were taken from6// http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt.7// Lowpass filter.8function createLowpassFilter(freq, q, gain) {9 var b0;10 var b1;11 var b2;12 var a0;13 var a1;14 var a2;15 if (freq == 1) {16 // The formula below works, except for roundoff. When freq = 1,17 // the filter is just a wire, so hardwire the coefficients.18 b0 = 1;19 b1 = 0;20 b2 = 0;21 a0 = 1;22 a1 = 0;...
Using AI Code Generation
1var context = new wptAudioContext();2var filter = context.createLowpassFilter();3var context = new wptAudioContext();4var audioElement = document.getElementById("audio");5var source = context.createMediaElementSource(audioElement);6var context = new wptAudioContext();7var source = context.createMediaStreamSource(stream);8var context = new wptAudioContext();9var destination = context.createMediaStreamDestination();10var context = new wptAudioContext();11var oscillator = context.createOscillator();12var context = new wptAudioContext();13var real = new Float32Array(2);14var imag = new Float32Array(2);15var wave = context.createPeriodicWave(real, imag);16var context = new wptAudioContext();17var bufferSize = 1024;18var numberOfInputChannels = 2;19var numberOfOutputChannels = 2;20var scriptProcessor = context.createScriptProcessor(bufferSize, numberOfInputChannels, numberOfOutputChannels);21var context = new wptAudioContext();22var panner = context.createStereoPanner();23var context = new wptAudioContext();24var waveShaper = context.createWaveShaper();25var context = new wptAudioContext();26var audioData = new ArrayBuffer();27var successCallback = function(decodedData) {28};29var errorCallback = function() {30};
Using AI Code Generation
1var wpt = new webkitAudioContext();2var lowpassFilter = wpt.createLowpassFilter();3var wpt = new webkitAudioContext();4var biquadFilter = wpt.createBiquadFilter();5var wpt = new webkitAudioContext();6var delay = wpt.createDelay();7var wpt = new webkitAudioContext();8var scriptProcessor = wpt.createScriptProcessor();9var wpt = new webkitAudioContext();10var waveShaper = wpt.createWaveShaper();11var wpt = new webkitAudioContext();12var panner = wpt.createPanner();13var wpt = new webkitAudioContext();14var convolver = wpt.createConvolver();15var wpt = new webkitAudioContext();16var channelSplitter = wpt.createChannelSplitter();17var wpt = new webkitAudioContext();18var channelMerger = wpt.createChannelMerger();19var wpt = new webkitAudioContext();20var dynamicsCompressor = wpt.createDynamicsCompressor();21var wpt = new webkitAudioContext();22var oscillator = wpt.createOscillator();23var wpt = new webkitAudioContext();24var gain = wpt.createGain();25var wpt = new webkitAudioContext();26var analyser = wpt.createAnalyser();27var wpt = new webkitAudioContext();28var mediaElementSource = wpt.createMediaElementSource();29var wpt = new webkitAudioContext();30var mediaStreamSource = wpt.createMediaStreamSource();
Using AI Code Generation
1var wptools = require('webaudio-peaks');2var audioContext = new AudioContext();3var audioBuffer = audioContext.createBuffer(2, 44100, 44100);4var peaks = wptools.createLowpassFilter(audioBuffer, 2000);5var wptools = require('webaudio-peaks');6var audioContext = new AudioContext();7var audioBuffer = audioContext.createBuffer(2, 44100, 44100);8var peaks = wptools.createHighpassFilter(audioBuffer, 2000);9var wptools = require('webaudio-peaks');10var audioContext = new AudioContext();11var audioBuffer = audioContext.createBuffer(2, 44100, 44100);12var peaks = wptools.createBandpassFilter(audioBuffer, 2000, 4000);13var wptools = require('webaudio-peaks');14var audioContext = new AudioContext();15var audioBuffer = audioContext.createBuffer(2, 44100, 44100);16var peaks = wptools.createBandstopFilter(audioBuffer, 2000, 4000);17var wptools = require('webaudio-peaks');18var audioContext = new AudioContext();19var audioBuffer = audioContext.createBuffer(2, 44100, 44100);20var peaks = wptools.createAllpassFilter(audioBuffer, 2000);21var wptools = require('webaudio-peaks');22var audioContext = new AudioContext();23var audioBuffer = audioContext.createBuffer(2, 44100, 44100);24var peaks = wptools.createPeakingFilter(audioBuffer, 2000, 4000);25var wptools = require('webaudio-peaks');26var audioContext = new AudioContext();27var audioBuffer = audioContext.createBuffer(2, 44100, 44100);28var peaks = wptools.createLowshelfFilter(audioBuffer, 2000);
Using AI Code Generation
1var wpt = new WebAudioTestAPI();2var context = new wpt.AudioContext();3var filter = context.createLowpassFilter();4var filter2 = context.createLowpassFilter();5filter.connect(filter2);6filter.frequency.value = 5000;7filter2.frequency.value = 10000;8var wpt = new WebAudioTestAPI();9var context = new wpt.AudioContext();10var panner = context.createPanner();11panner.panningModel = "HRTF";12panner.distanceModel = "inverse";13panner.refDistance = 1;14panner.maxDistance = 10000;15panner.rolloffFactor = 1;16panner.coneInnerAngle = 360;17panner.coneOuterAngle = 0;18panner.coneOuterGain = 0;19panner.setOrientation(0, 0, 1);20panner.setPosition(0, 0, 0);21panner.setVelocity(0, 0, 0);22var wpt = new WebAudioTestAPI();23var context = new wpt.AudioContext();24var real = new Float32Array([0, 0, 1, 0, 0, 0, 0, 0, 0, 0]);25var imag = new Float32Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);26var wave = context.createPeriodicWave(real, imag);27var wpt = new WebAudioTestAPI();28var context = new wpt.AudioContext();29var panner = context.createStereoPanner();30panner.pan.value = 0;31var wpt = new WebAudioTestAPI();32var context = new wpt.AudioContext();33var shaper = context.createWaveShaper();34var curve = new Float32Array([0, 0, 1, 0, 0, 0, 0, 0, 0, 0]);35shaper.curve = curve;36shaper.oversample = 'none';
Using AI Code Generation
1var wptoolkit = require('wptoolkit');2var filter = wptoolkit.createLowpassFilter(1000, 0.707, 44100);3var wptoolkit = require('wptoolkit');4var context = wptoolkit.createAudioContext();5var filter = wptoolkit.createLowpassFilter(1000, 0.707, context);6var wptoolkit = require('wptoolkit');7var filter = wptoolkit.createHighpassFilter(1000, 0.707, 44100);8var wptoolkit = require('wptoolkit');9var context = wptoolkit.createAudioContext();10var filter = wptoolkit.createHighpassFilter(1000, 0.707, context);11var wptoolkit = require('wptoolkit');12var filter = wptoolkit.createBandpassFilter(1000, 0.707, 44100);13var wptoolkit = require('wptoolkit');14var context = wptoolkit.createAudioContext();15var filter = wptoolkit.createBandpassFilter(1000, 0.707, context);16var wptoolkit = require('wptoolkit');17var filter = wptoolkit.createBandstopFilter(1000, 0.707, 44100);18var wptoolkit = require('wptoolkit');19var context = wptoolkit.createAudioContext();20var filter = wptoolkit.createBandstopFilter(1000, 0.707, context);
Using AI Code Generation
1var wptoolkit = require('wptoolkit');2var lowpassFilter = wptoolkit.createLowpassFilter();3init()4init(sampleRate, cutoffFrequency)5var wptoolkit = require('wptoolkit');6var lowpassFilter = wptoolkit.createLowpassFilter();7lowpassFilter.init(100, 0.1);8filter()9filter(value)10var wptoolkit = require('wptoolkit');11var lowpassFilter = wptoolkit.createLowpassFilter();12lowpassFilter.init(100, 0.1);13var filteredValue = lowpassFilter.filter(5);14filterArray()15filterArray(valueArray)16var wptoolkit = require('wptoolkit');17var lowpassFilter = wptoolkit.createLowpassFilter();18lowpassFilter.init(100, 0.1);19var valueArray = [1, 2, 3, 4, 5];
Using AI Code Generation
1var lowPassFilter = new LowPassFilter(0.5);2var filteredValue = lowPassFilter.filter(1.0);3var highPassFilter = new HighPassFilter(0.5);4var filteredValue = highPassFilter.filter(1.0);5var bandPassFilter = new BandPassFilter(0.5,0.5);6var filteredValue = bandPassFilter.filter(1.0);7var lowShelfFilter = new LowShelfFilter(0.5,0.5);8var filteredValue = lowShelfFilter.filter(1.0);9var highShelfFilter = new HighShelfFilter(0.5,0.5);10var filteredValue = highShelfFilter.filter(1.0);11var peakingFilter = new PeakingFilter(0.5,0.5,0.5);12var filteredValue = peakingFilter.filter(1.0);13var notchFilter = new NotchFilter(0.5,0.5);14var filteredValue = notchFilter.filter(1.0);15var allPassFilter = new AllPassFilter(0.5);16var filteredValue = allPassFilter.filter(1.0);17var delay = new Delay(0.5);18var delayedValue = delay.delay(1.0);19var convolver = new Convolver();20var convolvedValue = convolver.convolve(1.0);21var gain = new Gain(0.5);22var gainValue = gain.gain(1.0);23var panner = new Panner(0.5,0.5);24var pannerValue = panner.panner(1.0);25var compressor = new Compressor(0.5
Using AI Code Generation
1var filter = wptools.createLowpassFilter( 100, 1000, 0.01, 0.1);2var filter = wptools.createHighpassFilter( 100, 1000, 0.01, 0.1);3var filter = wptools.createBandpassFilter( 100, 1000, 0.01, 0.1);4var filter = wptools.createBandstopFilter( 100, 1000, 0.01, 0.1);5var filter = wptools.createAllpassFilter( 100, 1000, 0.01, 0.1);6var filter = wptools.createPeakingFilter( 100, 1000, 0.01, 0.1);7var filter = wptools.createNotchFilter( 100, 1000, 0.01, 0.1);8var filter = wptools.createLowShelfFilter( 100, 1000, 0.01, 0.1);9var filter = wptools.createHighShelfFilter( 100, 1000, 0.01, 0.1);10var delayNode = wptools.createDelayNode( 0.5 );11var gainNode = wptools.createGainNode( 0.5 );12var pannerNode = wptools.createPannerNode( 0.5, 0.5, 0.5 );
Using AI Code Generation
1var wptools = require('wptools');2var wp = new wptools('en.wikipedia.org/wiki/Node.js');3wp.createLowpassFilter('Node.js', function(err, res){4 if (err) {5 console.log(err);6 } else {7 console.log(res);8 }9});10var wptools = require('wptools');11var wp = new wptools('en.wikipedia.org/wiki/Node.js');12wp.createHighpassFilter('Node.js', function(err, res){13 if (err) {14 console.log(err);15 } else {16 console.log(res);17 }18});19var wptools = require('wptools');20var wp = new wptools('en.wikipedia.org/wiki/Node.js');21wp.createBandpassFilter('Node.js', function(err, res){22 if (err) {23 console.log(err);24 } else {25 console.log(res);26 }27});28var wptools = require('wptools');29var wp = new wptools('en.wikipedia.org/wiki/Node.js');30wp.createBandstopFilter('Node.js', function(err, res){31 if (err) {32 console.log(err);33 } else {34 console.log(res);35 }36});37var wptools = require('wptools');38var wp = new wptools('en.wikipedia.org/wiki/Node.js');39wp.createPeakingFilter('Node.js', function(err, res){40 if (err) {41 console.log(err);42 } else {43 console.log(res);44 }45});46var wptools = require('wptools');47var wp = new wptools('en.wikipedia.org/wiki/Node.js');48wp.createAllpassFilter('Node.js', function(err, res){49 if (err) {50 console.log(err);51 } else {52 console.log(res);53 }54});
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!!