Best JavaScript code snippet using best
VictoryChartsUtils.ts
Source:VictoryChartsUtils.ts
1import { Datapoint, Metric } from 'types/Metrics';2import {3 VCLines,4 VCLine,5 LegendItem,6 VCDataPoint,7 makeLegend,8 RichDataPoint,9 LineInfo,10 BucketDataPoint11} from 'types/VictoryChartInfo';12import { filterAndRenameMetric, LabelsInfo } from 'utils/TimeSeriesUtils';13import { ChartModel, XAxisType } from 'types/Dashboards';14import { Overlay, OverlayInfo } from 'types/Overlay';15export const toVCDatapoints = (dps: Datapoint[], name: string): VCDataPoint[] => {16 return dps17 .map(dp => {18 return {19 name: name,20 x: new Date(dp[0] * 1000),21 y: Number(dp[1]),22 y0: dp.length > 2 ? dp[2] : undefined23 };24 })25 .filter(dp => !isNaN(dp.y) && (dp.y0 === undefined || !isNaN(dp.y0)));26};27export const toVCSinglePoint = (dps: Datapoint[], name: string): VCDataPoint[] => {28 const last = dps.filter(dp => !isNaN(dp[1]) && (dp[2] === undefined || !isNaN(dp[2]))).reduce((p, c) => (c[0] > p[0] ? c : p));29 if (last) {30 return [31 {32 name: name,33 time: new Date(last[0] * 1000),34 x: 0, // placeholder35 y: Number(last[1]),36 y0: last[2] ?? Number(last[1])37 } as VCDataPoint38 ];39 }40 return [];41};42const buildVCLine = <T extends LineInfo>(dps: VCDataPoint[], lineInfo: T): VCLine<VCDataPoint & T> => {43 const datapoints: (VCDataPoint & T)[] = dps.map(dp => ({ ...lineInfo, ...dp }));44 const legendItem: LegendItem = makeLegend(lineInfo.name, lineInfo.color, lineInfo.symbol);45 return {46 datapoints: datapoints,47 legendItem: legendItem,48 color: lineInfo.color49 };50};51export const toVCLine = (dps: Datapoint[], name: string, color: string): VCLine<RichDataPoint> => {52 return buildVCLine(toVCDatapoints(dps, name), { name: name, color: color });53};54export const toVCLines = (55 metrics: Metric[],56 unit: string,57 colors: string[],58 xAxis: XAxisType = 'time'59): VCLines<RichDataPoint> => {60 // In case "reporter" is in the labels, arrange the metrics in source-destination pairs to61 // draw area charts.62 if (metrics.length > 0 && metrics[0].labels?.reporter !== undefined) {63 let pairedMetrics: { [key: string]: [Metric?, Metric?] } = {};64 metrics.forEach(metric => {65 let reporter = metric.labels.reporter;66 let labelsNoReporter = { ...metric.labels };67 delete labelsNoReporter.reporter68 let labelsStr = Object.keys(labelsNoReporter).map(k => `${k}=${labelsNoReporter[k]}`).sort().join(',');69 labelsStr = `name=${metric.name},stat=${metric.stat}%` + labelsStr;70 if (!pairedMetrics[labelsStr]) {71 pairedMetrics[labelsStr] = [undefined, undefined];72 }73 pairedMetrics[labelsStr][reporter === 'source' ? 0 : 1] = metric;74 });75 return Object.values(pairedMetrics).map((twoLines, i) => {76 const color = colors[i % colors.length];77 let datapoints: Datapoint[] = [];78 let name: string = '';79 if (twoLines[0] !== undefined && twoLines[1] !== undefined) {80 name = twoLines[0].name;81 const minDatapointsLength = twoLines[0].datapoints.length < twoLines[1].datapoints.length ?82 twoLines[0].datapoints.length : twoLines[1].datapoints.length;83 for (let j = 0, sourceIdx = 0, destIdx = 0; j < minDatapointsLength; j++) {84 if (twoLines[0].datapoints[sourceIdx][0] !== twoLines[1].datapoints[destIdx][0]) {85 // Usually, all series have the same samples at same timestamps (i.e. series are time synced or synced on the x axis).86 // There are rare cases when there are some additional samples usually at the beginning or end of some series.87 // If this happens, let's skip these additional samples, to have properly x-axis synced values.88 if (twoLines[0].datapoints[sourceIdx][0] < twoLines[1].datapoints[destIdx][0]) {89 sourceIdx++;90 } else {91 destIdx++;92 }93 continue;94 }95 datapoints.push([96 twoLines[0].datapoints[sourceIdx][0],97 twoLines[0].datapoints[sourceIdx][1],98 twoLines[1].datapoints[destIdx][1],99 ]);100 sourceIdx++;101 destIdx++;102 }103 } else if (twoLines[0] !== undefined) {104 // Assign zero value to "y0" to denote "no data" for the destination reporter105 name = twoLines[0].name;106 datapoints = twoLines[0].datapoints.map(d => ([d[0], d[1], 0]));107 } else if (twoLines[1] !== undefined) {108 // Assign zero value to "y" to denote "no data" for the source reporter109 name = twoLines[1].name;110 datapoints = twoLines[1].datapoints.map(d => ([d[0], 0, d[1]]));111 }112 const dps =113 xAxis === 'time' ? toVCDatapoints(datapoints, name) : toVCSinglePoint(datapoints, name);114 return buildVCLine(dps, {name: name, unit: unit, color: color});115 });116 } else {117 return metrics.map((line, i) => {118 const color = colors[i % colors.length];119 const dps =120 xAxis === 'time' ? toVCDatapoints(line.datapoints, line.name) : toVCSinglePoint(line.datapoints, line.name);121 return buildVCLine(dps, {name: line.name, unit: unit, color: color});122 });123 }124};125export const getDataSupplier = (126 chart: ChartModel,127 labels: LabelsInfo,128 colors: string[]129): (() => VCLines<RichDataPoint>) => {130 return () => {131 const filtered = filterAndRenameMetric(chart.metrics, labels);132 return toVCLines(filtered, chart.unit, colors, chart.xAxis || 'time');133 };134};135// toBuckets accumulates datapoints into bukets.136// The result is still a (smaller) list of VCDataPoints, but with Y value being an array of values instead of a single value.137// This data structure is required by VictoryBoxPlot object.138export const toBuckets = <T extends LineInfo>(139 nbuckets: number,140 datapoints: VCDataPoint[],141 lineInfo: T,142 timeWindow?: [Date, Date]143): (T & BucketDataPoint)[] => {144 if (datapoints.length === 0) {145 return [];146 }147 // xBuilder will preserve X-axis type when building buckets (either dates or raw numbers)148 const xBuilder: (x: number) => number | Date = typeof datapoints[0].x === 'object' ? x => new Date(x) : x => x;149 let min = 0;150 let max = 0;151 if (timeWindow) {152 min = timeWindow[0].getTime();153 max = timeWindow[1].getTime();154 } else {155 const times = datapoints.map(dp => Number(dp.x));156 min = Math.min(...times);157 max = Math.max(...times);158 }159 const bucketSize = (1 + max - min) / nbuckets;160 // Create $nbuckets buckets at regular intervals with preset / static content $dpInject161 const buckets: (T & BucketDataPoint)[] = Array.from({ length: nbuckets }, (_, idx) => {162 const start = Math.floor(min + idx * bucketSize);163 const end = Math.floor(start + bucketSize - 1);164 return {165 ...lineInfo,166 start: xBuilder(start),167 end: xBuilder(end),168 x: xBuilder(Math.floor(start + bucketSize / 2)),169 y: []170 };171 });172 datapoints.forEach(dp => {173 // Get bucket index from timestamp174 const idx = Math.floor((Number(dp.x) - min) / bucketSize);175 // This index might be out of range when a timeWindow is provided, so protect against that176 if (idx >= 0 && idx < buckets.length) {177 buckets[idx].y.push(dp.y);178 }179 });180 return buckets.filter(b => b.y.length > 0);181};182export const toOverlay = <T extends LineInfo>(info: OverlayInfo<T>, dps: VCDataPoint[]): Overlay<T> => {183 return {184 info: info,185 vcLine: buildVCLine(dps, info.lineInfo)186 };...
trace.ts
Source:trace.ts
1/*2 * Copyright (c) 2019, salesforce.com, inc.3 * All rights reserved.4 * SPDX-License-Identifier: MIT5 * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT6*/7import fs from 'fs';8import { promisify } from 'util';9import { BenchmarkResults, BenchmarkMetrics, BenchmarkResultNode, BenchmarkMeasureType } from '@best/types';10const asyncReadFile = promisify(fs.readFile);11const asyncUnlink = promisify(fs.unlink);12const asyncExists = promisify(fs.exists);13const TRACED_METRIC_EVENTS = ['Paint', 'Layout', 'UpdateLayoutTree', 'UpdateLayerTree', 'CompositeLayers'];14const TRACED_EVENT_NAME_ALIAS: any = { 'UpdateLayoutTree': 'RecalculateStyles' };15interface TracedMetrics {16 [key: string]: BenchmarkMetrics17}18const isBeginPhase = (event: { ph: string }): boolean => {19 return event.ph.toLowerCase() === 'b';20}21const isEndPhase = (event: { ph: string }): boolean => {22 return event.ph.toLowerCase() === 'e';23}24const hasDurationPhased = (event: { ph: string }): boolean => {25 return isBeginPhase(event) || isEndPhase(event);26}27const sumPairedMetrics = (events: any[]): number => {28 let duration = 0;29 for (const event of events) {30 if (isBeginPhase(event)) {31 duration -= event.ts;32 } else if (isEndPhase(event)) {33 duration += event.ts;34 }35 }36 return duration;37}38// returns the total duration of all paints or layouts, etc in microseconds39const sumEventDurations = (events: any[]): number => {40 const pairedMetrics = events.filter(hasDurationPhased);41 if (pairedMetrics.length > 0 && pairedMetrics.length % 2 === 0) {42 return sumPairedMetrics(events);43 }44 return events.reduce((previous, current) => previous += current.dur, 0);45}46export const parseTrace = async (tracePath: string): Promise<TracedMetrics> => {47 const file = await asyncReadFile(tracePath, 'utf8');48 const trace = JSON.parse(file);49 const tracedMetricEvents = trace.traceEvents.filter((event: any) => TRACED_METRIC_EVENTS.includes(event.name) || event.name.includes((`${BenchmarkMeasureType.Execute}/`)));50 const sortedEvents = tracedMetricEvents.sort((a: any, b: any) => a.ts - b.ts);51 const groupedEvents: { [run: string]: { [event: string]: any[] } } = {};52 let currentRun: string | false = false;53 for (const event of sortedEvents) {54 if (currentRun && TRACED_METRIC_EVENTS.includes(event.name)) {55 if (groupedEvents[currentRun][event.name]) {56 groupedEvents[currentRun][event.name].push(event);57 } else {58 groupedEvents[currentRun][event.name] = [event];59 }60 } else if (event.name.includes(`${BenchmarkMeasureType.Execute}/`)) {61 if (isBeginPhase(event)) {62 currentRun = event.name;63 groupedEvents[event.name] = {};64 } else if (isEndPhase(event)) {65 currentRun = false;66 }67 }68 }69 const tracedMetrics = Object.keys(groupedEvents).reduce((allMetrics, key): TracedMetrics => {70 const runName = key.replace((`${BenchmarkMeasureType.Execute}/`), '');71 const metrics = Object.keys(groupedEvents[key]).reduce((acc, eventName): BenchmarkMetrics => {72 const aliasEventName = TRACED_EVENT_NAME_ALIAS[eventName] || eventName;73 const name = aliasEventName.toLowerCase();74 return {75 ...acc,76 [name]: (sumEventDurations(groupedEvents[key][eventName]) / 1000)77 }78 }, <BenchmarkMetrics>{})79 return {80 ...allMetrics,81 [runName]: metrics82 };83 }, <TracedMetrics>{})84 return tracedMetrics;85}86const mergeTracedMetricsIntoResultNode = (resultNode: BenchmarkResultNode, parsedTrace: TracedMetrics) => {87 if (resultNode.type === "group") {88 resultNode.nodes.forEach(node => {89 mergeTracedMetricsIntoResultNode(node, parsedTrace);90 })91 } else if (resultNode.type === "benchmark") {92 const nodeTraces = parsedTrace[resultNode.name];93 resultNode.metrics = {94 ...resultNode.metrics,95 ...nodeTraces96 }97 }98}99export const mergeTracedMetrics = (benchmarkResults: BenchmarkResults, parsedTrace: TracedMetrics) => {100 benchmarkResults.results.forEach(node => {101 mergeTracedMetricsIntoResultNode(node, parsedTrace);102 })103}104export const removeTrace = async (tracePath: string): Promise<void> => {105 const fileExists = await asyncExists(tracePath);106 if (fileExists) {107 await asyncUnlink(tracePath);108 }...
Using AI Code Generation
1const BestMetrics = require('best-metrics');2let bestMetrics = new BestMetrics();3let pairedMetrics = bestMetrics.pairedMetrics([1,2,3,4,5],[6,7,8,9,10]);4console.log(pairedMetrics);5const BestMetrics = require('best-metrics');6let bestMetrics = new BestMetrics();7let pairedMetrics = bestMetrics.pairedMetrics([1,2,3,4,5],[6,7,8,9,10]);8console.log(pairedMetrics);9const BestMetrics = require('best-metrics');10let bestMetrics = new BestMetrics();11let pairedMetrics = bestMetrics.pairedMetrics([1,2,3,4,5],[6,7,8,9,10]);12console.log(pairedMetrics);13const BestMetrics = require('best-metrics');14let bestMetrics = new BestMetrics();15let pairedMetrics = bestMetrics.pairedMetrics([1,2,3,4,5],[6,7,8,9,10]);16console.log(pairedMetrics);17const BestMetrics = require('best-metrics');18let bestMetrics = new BestMetrics();19let pairedMetrics = bestMetrics.pairedMetrics([1,2,3,4,5],[6,7,8,9,10]);
Using AI Code Generation
1var bestPractices = require('./lib/bestPractices');2var metrics = bestPractices.pairedMetrics();3console.log(metrics);4var bestPractices = require('./lib/bestPractices');5var metrics = bestPractices.pairedMetrics();6console.log(metrics);
Using AI Code Generation
1var BestPathFinder = require('./BestPathFinder.js');2var bestPathFinder = new BestPathFinder();3 {name: 'a', value: 1},4 {name: 'b', value: 2},5 {name: 'a', value: 3},6 {name: 'b', value: 4},7 {name: 'a', value: 5},8 {name: 'b', value: 6}9];10var pairedMetrics = bestPathFinder.pairedMetrics(metrics);11console.log(pairedMetrics);12var BestPathFinder = require('./BestPathFinder.js');13var bestPathFinder = new BestPathFinder();14 {name: 'a', value: 1},15 {name: 'b', value: 2},16 {name: 'a', value: 3},17 {name: 'b', value: 4},18 {name: 'a', value: 5},19 {name: 'b', value: 6},20 {name: 'a', value: 7},21 {name: 'b', value: 8},22 {name: 'a', value: 9},23 {name: 'b', value: 10}24];25var pairedMetrics = bestPathFinder.pairedMetrics(metrics);26console.log(pairedMetrics);
Using AI Code Generation
1var BestMetrics = require('./bestMetrics');2var bestMetrics = new BestMetrics();3var metrics = {4}5var pairedMetrics = bestMetrics.pairedMetrics(metrics);6console.log(pairedMetrics);
Using AI Code Generation
1var bestMetrics = require('./bestMetrics.js');2var bestMetricsObj = new bestMetrics.BestMetrics();3var pairedMetrics = bestMetricsObj.pairedMetrics(0.5);4console.log(pairedMetrics);5var bestMetrics = require('./bestMetrics.js');6var bestMetricsObj = new bestMetrics.BestMetrics();7var pairedMetrics = bestMetricsObj.pairedMetrics(0.5, 0.5);8console.log(pairedMetrics);9var bestMetrics = require('./bestMetrics.js');10var bestMetricsObj = new bestMetrics.BestMetrics();11var pairedMetrics = bestMetricsObj.pairedMetrics(0.5, 0.5, 0.5);12console.log(pairedMetrics);13var bestMetrics = require('./bestMetrics.js');14var bestMetricsObj = new bestMetrics.BestMetrics();15var pairedMetrics = bestMetricsObj.pairedMetrics(0.5, 0.5, 0.5, 0.5);16console.log(pairedMetrics);17var bestMetrics = require('./bestMetrics.js');18var bestMetricsObj = new bestMetrics.BestMetrics();19var pairedMetrics = bestMetricsObj.pairedMetrics(0.5, 0.5, 0.5, 0.5, 0.5);20console.log(pairedMetrics);
Using AI Code Generation
1var BestMetrics = require('./BestMetrics');2var bestMetrics = new BestMetrics();3var pairedMetrics = bestMetrics.pairedMetrics();4console.log(pairedMetrics);5{ '0': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ],6 '9': [ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 ] }
Using AI Code Generation
1var BestMetrics = require('./BestMetrics.js');2var bestMetrics = new BestMetrics();3var data = require('./test4.json');4var metrics = bestMetrics.pairedMetrics(data, 0.5);5console.log(metrics);6var BestMetrics = require('./BestMetrics.js');7var bestMetrics = new BestMetrics();8var data = require('./test5.json');9var metrics = bestMetrics.pairedMetrics(data, 0.5);10console.log(metrics);11var BestMetrics = require('./BestMetrics.js');12var bestMetrics = new BestMetrics();13var data = require('./test6.json');14var metrics = bestMetrics.pairedMetrics(data, 0.5);15console.log(metrics);16var BestMetrics = require('./BestMetrics.js');17var bestMetrics = new BestMetrics();18var data = require('./test7.json');19var metrics = bestMetrics.pairedMetrics(data, 0.5);20console.log(metrics);21var BestMetrics = require('./BestMetrics.js');22var bestMetrics = new BestMetrics();23var data = require('./test8.json');24var metrics = bestMetrics.pairedMetrics(data, 0.5);25console.log(metrics);
Using AI Code Generation
1var BestRoute = require('./BestRoute.js');2var bestRoute = new BestRoute();3var metrics = {4};5bestRoute.pairedMetrics(metrics, function(err, result) {6 if(err) {7 console.log(err);8 } else {9 console.log(result);10 }11});12var BestRoute = require('./BestRoute.js');13var bestRoute = new BestRoute();14var metrics = {15};16bestRoute.pairedMetrics(metrics, function(err, result) {17 if(err) {18 console.log(err);19 } else {20 console.log(result);21 }22});23var BestRoute = require('./BestRoute.js');24var bestRoute = new BestRoute();25var metrics = {26};27bestRoute.pairedMetrics(metrics, function(err, result) {28 if(err) {29 console.log(err);30 } else {31 console.log(result);32 }33});34var BestRoute = require('./BestRoute.js');35var bestRoute = new BestRoute();36var metrics = {37};38bestRoute.pairedMetrics(metrics, function(err, result) {39 if(err) {40 console.log(err);41 } else {42 console.log(result);43 }44});45var BestRoute = require('./BestRoute.js');46var bestRoute = new BestRoute();47var metrics = {48};49bestRoute.pairedMetrics(metrics, function(err, result) {50 if(err) {51 console.log(err);52 } else {53 console.log(result);54 }55});
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!!