Best JavaScript code snippet using storybook-root
force.js
Source:force.js  
1import "../behavior/drag";2import "../core/identity";3import "../core/rebind";4import "../event/event";5import "../event/dispatch";6import "../event/timer";7import "../geom/quadtree";8import "layout";9// A rudimentary force layout using Gauss-Seidel.10d3.layout.force = function() {11  var force = {},12      event = d3.dispatch("start", "tick", "end"),13      size = [1, 1],14      drag,15      alpha,16      friction = .9,17      linkDistance = d3_layout_forceLinkDistance,18      linkStrength = d3_layout_forceLinkStrength,19      charge = -30,20      gravity = .1,21      theta = .8,22      nodes = [],23      links = [],24      distances,25      strengths,26      charges;27  function repulse(node) {28    return function(quad, x1, _, x2) {29      if (quad.point !== node) {30        var dx = quad.cx - node.x,31            dy = quad.cy - node.y,32            dn = 1 / Math.sqrt(dx * dx + dy * dy);33        /* Barnes-Hut criterion. */34        if ((x2 - x1) * dn < theta) {35          var k = quad.charge * dn * dn;36          node.px -= dx * k;37          node.py -= dy * k;38          return true;39        }40        if (quad.point && isFinite(dn)) {41          var k = quad.pointCharge * dn * dn;42          node.px -= dx * k;43          node.py -= dy * k;44        }45      }46      return !quad.charge;47    };48  }49  force.tick = function() {50    // simulated annealing, basically51    if ((alpha *= .99) < .005) {52      event.end({type: "end", alpha: alpha = 0});53      return true;54    }55    var n = nodes.length,56        m = links.length,57        q,58        i, // current index59        o, // current object60        s, // current source61        t, // current target62        l, // current distance63        k, // current force64        x, // x-distance65        y; // y-distance66    // gauss-seidel relaxation for links67    for (i = 0; i < m; ++i) {68      o = links[i];69      s = o.source;70      t = o.target;71      x = t.x - s.x;72      y = t.y - s.y;73      if (l = (x * x + y * y)) {74        l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l;75        x *= l;76        y *= l;77        t.x -= x * (k = s.weight / (t.weight + s.weight));78        t.y -= y * k;79        s.x += x * (k = 1 - k);80        s.y += y * k;81      }82    }83    // apply gravity forces84    if (k = alpha * gravity) {85      x = size[0] / 2;86      y = size[1] / 2;87      i = -1; if (k) while (++i < n) {88        o = nodes[i];89        o.x += (x - o.x) * k;90        o.y += (y - o.y) * k;91      }92    }93    // compute quadtree center of mass and apply charge forces94    if (charge) {95      d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges);96      i = -1; while (++i < n) {97        if (!(o = nodes[i]).fixed) {98          q.visit(repulse(o));99        }100      }101    }102    // position verlet integration103    i = -1; while (++i < n) {104      o = nodes[i];105      if (o.fixed) {106        o.x = o.px;107        o.y = o.py;108      } else {109        o.x -= (o.px - (o.px = o.x)) * friction;110        o.y -= (o.py - (o.py = o.y)) * friction;111      }112    }113    event.tick({type: "tick", alpha: alpha});114  };115  force.nodes = function(x) {116    if (!arguments.length) return nodes;117    nodes = x;118    return force;119  };120  force.links = function(x) {121    if (!arguments.length) return links;122    links = x;123    return force;124  };125  force.size = function(x) {126    if (!arguments.length) return size;127    size = x;128    return force;129  };130  force.linkDistance = function(x) {131    if (!arguments.length) return linkDistance;132    linkDistance = typeof x === "function" ? x : +x;133    return force;134  };135  // For backwards-compatibility.136  force.distance = force.linkDistance;137  force.linkStrength = function(x) {138    if (!arguments.length) return linkStrength;139    linkStrength = typeof x === "function" ? x : +x;140    return force;141  };142  force.friction = function(x) {143    if (!arguments.length) return friction;144    friction = +x;145    return force;146  };147  force.charge = function(x) {148    if (!arguments.length) return charge;149    charge = typeof x === "function" ? x : +x;150    return force;151  };152  force.gravity = function(x) {153    if (!arguments.length) return gravity;154    gravity = +x;155    return force;156  };157  force.theta = function(x) {158    if (!arguments.length) return theta;159    theta = +x;160    return force;161  };162  force.alpha = function(x) {163    if (!arguments.length) return alpha;164    x = +x;165    if (alpha) { // if we're already running166      if (x > 0) alpha = x; // we might keep it hot167      else alpha = 0; // or, next tick will dispatch "end"168    } else if (x > 0) { // otherwise, fire it up!169      event.start({type: "start", alpha: alpha = x});170      d3.timer(force.tick);171    }172    return force;173  };174  force.start = function() {175    var i,176        n = nodes.length,177        m = links.length,178        w = size[0],179        h = size[1],180        neighbors,181        o;182    for (i = 0; i < n; ++i) {183      (o = nodes[i]).index = i;184      o.weight = 0;185    }186    for (i = 0; i < m; ++i) {187      o = links[i];188      if (typeof o.source == "number") o.source = nodes[o.source];189      if (typeof o.target == "number") o.target = nodes[o.target];190      ++o.source.weight;191      ++o.target.weight;192    }193    for (i = 0; i < n; ++i) {194      o = nodes[i];195      if (isNaN(o.x)) o.x = position("x", w);196      if (isNaN(o.y)) o.y = position("y", h);197      if (isNaN(o.px)) o.px = o.x;198      if (isNaN(o.py)) o.py = o.y;199    }200    distances = [];201    if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i);202    else for (i = 0; i < m; ++i) distances[i] = linkDistance;203    strengths = [];204    if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i);205    else for (i = 0; i < m; ++i) strengths[i] = linkStrength;206    charges = [];207    if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i);208    else for (i = 0; i < n; ++i) charges[i] = charge;209    // inherit node position from first neighbor with defined position210    // or if no such neighbors, initialize node position randomly211    // initialize neighbors lazily to avoid overhead when not needed212    function position(dimension, size) {213      if (!neighbors) {214        neighbors = new Array(n);215        for (j = 0; j < n; ++j) {216          neighbors[j] = [];217        }218        for (j = 0; j < m; ++j) {219          var o = links[j];220          neighbors[o.source.index].push(o.target);221          neighbors[o.target.index].push(o.source);222        }223      }224      var candidates = neighbors[i],225          j = -1,226          m = candidates.length,227          x;228      while (++j < m) if (!isNaN(x = candidates[j][dimension])) return x;229      return Math.random() * size;230    }231    return force.resume();232  };233  force.resume = function() {234    return force.alpha(.1);235  };236  force.stop = function() {237    return force.alpha(0);238  };239  // use `node.call(force.drag)` to make nodes draggable240  force.drag = function() {241    if (!drag) drag = d3.behavior.drag()242        .origin(d3_identity)243        .on("dragstart.force", d3_layout_forceDragstart)244        .on("drag.force", dragmove)245        .on("dragend.force", d3_layout_forceDragend);246    if (!arguments.length) return drag;247    this.on("mouseover.force", d3_layout_forceMouseover)248        .on("mouseout.force", d3_layout_forceMouseout)249        .call(drag);250  };251  function dragmove(d) {252    d.px = d3.event.x, d.py = d3.event.y;253    force.resume(); // restart annealing254  }255  return d3.rebind(force, event, "on");256};257// The fixed property has three bits:258// Bit 1 can be set externally (e.g., d.fixed = true) and show persist.259// Bit 2 stores the dragging state, from mousedown to mouseup.260// Bit 3 stores the hover state, from mouseover to mouseout.261// Dragend is a special case: it also clears the hover state.262function d3_layout_forceDragstart(d) {263  d.fixed |= 2; // set bit 2264}265function d3_layout_forceDragend(d) {266  d.fixed &= ~6; // unset bits 2 and 3267}268function d3_layout_forceMouseover(d) {269  d.fixed |= 4; // set bit 3270  d.px = d.x, d.py = d.y; // set velocity to zero271}272function d3_layout_forceMouseout(d) {273  d.fixed &= ~4; // unset bit 3274}275function d3_layout_forceAccumulate(quad, alpha, charges) {276  var cx = 0,277      cy = 0;278  quad.charge = 0;279  if (!quad.leaf) {280    var nodes = quad.nodes,281        n = nodes.length,282        i = -1,283        c;284    while (++i < n) {285      c = nodes[i];286      if (c == null) continue;287      d3_layout_forceAccumulate(c, alpha, charges);288      quad.charge += c.charge;289      cx += c.charge * c.cx;290      cy += c.charge * c.cy;291    }292  }293  if (quad.point) {294    // jitter internal nodes that are coincident295    if (!quad.leaf) {296      quad.point.x += Math.random() - .5;297      quad.point.y += Math.random() - .5;298    }299    var k = alpha * charges[quad.point.index];300    quad.charge += quad.pointCharge = k;301    cx += k * quad.point.x;302    cy += k * quad.point.y;303  }304  quad.cx = cx / quad.charge;305  quad.cy = cy / quad.charge;306}307var d3_layout_forceLinkDistance = 20,...index.js
Source:index.js  
1'use strict';2const Validator = require('jsonschema').Validator;3// Init default options4const defaults = {5  forceProtocol: 'none',6  forceWww: 'www',7  forceTrailingSlash: 'trim',8  forceCase: 'lower',9  forceCaseQuery: 'none',10  redirectType: '301',11  excludedPaths: [],12};13// Define Options schema for validation14const optionsSchema = {15  id: '/Options',16  type: 'object:',17  properties: {18    forceProtocol: {19      enum: ['http', 'https', 'none'],20    },21    forceWww: {22      enum: ['www', 'no-www', 'none'],23    },24    forceTrailingSlash: {25      enum: ['trim', 'keep', 'none'],26    },27    forceCase: {28      enum: ['lower', 'upper', 'none'],29    },30    forceCaseQuery: {31      enum: ['lower', 'upper', 'none'],32    },33    redirectType: {34      enum: ['301', '302'],35    },36    excludedPaths: {37      type: 'array',38      items: {39        type: 'string',40      },41      uniqueItems: true,42    },43  },44};45// Add options schema to validator46const validator = new Validator();47validator.addSchema(optionsSchema, '/Options');48function setupOptions(options) {49  const opts = options;50  // Check to see if each option has been configured, if not use default51  opts.forceProtocol = (opts.forceProtocol === undefined ?52    defaults.forceProtocol : opts.forceProtocol);53  opts.forceWww = (opts.forceWww === undefined ?54    defaults.forceWww : opts.forceWww);55  opts.forceTrailingSlash = (opts.forceTrailingSlash === undefined ?56    defaults.forceTrailingSlash : opts.forceTrailingSlash);57  opts.forceCase = (opts.forceCase === undefined ?58    defaults.forceCase : opts.forceCase);59  opts.forceCaseQuery = (opts.forceCaseQuery === undefined ?60    defaults.forceCaseQuery : opts.forceCaseQuery);61  opts.redirectType = (opts.redirectType === undefined ?62    defaults.redirectType : opts.redirectType);63  opts.excludedPaths = (opts.excludedPaths === undefined ?64    defaults.excludedPaths : opts.excludedPaths);65  // Validate options against schema66  validator.validate(opts, optionsSchema, { throwError: true });67  return opts;68}69// Middleware export70module.exports = options => {71  // Setup Options: if undefined, use defaults, otherwise pass to option handler72  const opts = (options === undefined ? defaults : setupOptions(options));73  /* eslint consistent-return: "off" */74  // Process Request and Redirect75  return (req, res, next) => {76    // Break down request URL into components77    let urlProtocol = req.protocol;78    let urlHost = req.headers.host;79    let urlPath = req.originalUrl.split('?')[0];80    const queryString = req.originalUrl.split('?')[1];81    let urlQueryString = (queryString === undefined ? '' : `?${queryString}`);82    let redirectRequired = false;83    const statusCode = parseInt(opts.redirectType, 10);84    // Check to see if path should be excluded from normalization85    for (const path of opts.excludedPaths) {86      const pattern = new RegExp(path);87      if (pattern.test(urlPath)) {88        return next();89      }90    }91    // Force HTTP or HTTPS92    if (opts.forceProtocol === 'http') {93      if (urlProtocol !== 'http') {94        redirectRequired = true;95        urlProtocol = 'http';96      }97    } else if (opts.forceProtocol === 'https') {98      if (urlProtocol !== 'https') {99        redirectRequired = true;100        urlProtocol = 'https';101      }102    }103    // Force WWW or Remove WWW104    if (opts.forceWww === 'www') {105      const testHost = urlHost.toLowerCase(); // Let's force lower case to make sure we match.106      if (testHost.indexOf('www.') === -1) {107        redirectRequired = true;108        urlHost = `www.${urlHost}`;109      }110    } else if (opts.forceWww === 'no-www') {111      const testHost = urlHost.toLowerCase(); // Let's force lower case to make sure we match.112      if (testHost.indexOf('www.') === 0) {113        redirectRequired = true;114        urlHost = urlHost.slice('www.'.length);115      }116    }117    // Force Trailing Slash Removal118    if (opts.forceTrailingSlash === 'trim') {119      if (urlPath.substr(-1) === '/' && urlPath.length > 1) {120        redirectRequired = true;121        urlPath = urlPath.slice(0, -1);122      }123    }124    // Force Trailing Slash Keep125    if (opts.forceTrailingSlash === 'keep') {126      if (urlPath.substr(-1) !== '/' && !/\w+\.([A-Za-z0-9]{3,4})(?=\?|$)/.test(urlPath)) {127        redirectRequired = true;128        urlPath += '/';129      }130    }131    // Force Lowercase or Uppercase132    if (opts.forceCase === 'lower') {133      if (/[A-Z]/.test(urlProtocol) || /[A-Z]/.test(urlHost) || /[A-Z]/.test(urlPath)) {134        redirectRequired = true;135        urlProtocol = urlProtocol.toLowerCase();136        urlHost = urlHost.toLowerCase();137        urlPath = urlPath.toLowerCase();138      }139    } else if (opts.forceCase === 'upper') {140      if (/[a-z]/.test(urlProtocol) || /[a-z]/.test(urlHost) || /[a-z]/.test(urlPath)) {141        redirectRequired = true;142        urlProtocol = urlProtocol.toUpperCase();143        urlHost = urlHost.toUpperCase();144        urlPath = urlPath.toUpperCase();145      }146    }147    // Force Lowercase or Uppercase Query String148    if (opts.forceCaseQuery === 'lower') {149      if (/[A-Z]/.test(urlQueryString)) {150        redirectRequired = true;151        urlQueryString = urlQueryString.toLowerCase();152      }153    } else if (opts.forceCaseQuery === 'upper') {154      if (/[a-z]/.test(urlQueryString)) {155        redirectRequired = true;156        urlQueryString = urlQueryString.toUpperCase();157      }158    }159    // Compile URL and redirect if needed, otherwise next middleware160    if (redirectRequired) {161      const compiledUrl = `${urlProtocol}://${urlHost}${urlPath}${urlQueryString}`;162      res.redirect(statusCode, compiledUrl);163    } else {164      return next();165    }166  };...commodity-service.js
Source:commodity-service.js  
1angular.module('main')2.service('commodityService', function ($http) {3    var that = this;4    that.getCommodities = function (forceRefresh) {5        var url = 'api/get-commodities';6        var effectiveForceRefresh = forceRefresh !== undefined && forceRefresh !== null7            ? forceRefresh8            : false;9        var serviceModel = { forceRefresh: effectiveForceRefresh };10        return $http.post(url, serviceModel);11    };12    that.getExchangeCommodityByNativeSymbol = function (exchange, nativeSymbol, forceRefresh) {13        var effectiveForceRefresh = forceRefresh !== undefined && forceRefresh !== null ? forceRefresh : false;14        var serviceModel = { exchange: exchange, nativeSymbol: nativeSymbol, forceRefresh: effectiveForceRefresh };15        return $http.post('api/get-commodity-for-exchange', serviceModel);16    };17    that.getExchangeCommodityBySymbol = function (exchange, symbol, forceRefresh) {18        var effectiveForceRefresh = forceRefresh !== undefined && forceRefresh !== null ? forceRefresh : false;19        var serviceModel = { exchange: exchange, symbol: symbol, forceRefresh: effectiveForceRefresh };20        return $http.post('api/get-commodity-for-exchange', serviceModel);21    };22    that.getExchangeCommodityBySymbolExcludeDepositAddress = function (exchange, symbol, forceRefresh) {23        var effectiveForceRefresh = forceRefresh !== undefined && forceRefresh !== null ? forceRefresh : false;24        var serviceModel = { exchange: exchange, symbol: symbol, forceRefresh: effectiveForceRefresh, excludeDepositAddress: true };25        return $http.post('api/get-commodity-for-exchange', serviceModel);26    };27    that.getCommodityDetails = function (symbol, forceRefresh) {28        var effectiveForceRefresh = forceRefresh !== undefined && forceRefresh !== null ? forceRefresh : false;29        var serviceModel = { symbol: symbol, forceRefresh: effectiveForceRefresh, excludeDepositAddress: true };30        return $http.post('api/get-commodity-details', serviceModel);31    };...Using AI Code Generation
1import React from 'react';2import { storiesOf } from '@storybook/react';3import { action } from '@storybook/addon-actions';4import { linkTo } from '@storybook/addon-links';5import { Button, Welcome } from '@storybook/react/demo';6import { Force } from 'storybook-root';7storiesOf('Force', module)8  .add('Force', () => (9      <Button onClick={action('clicked')}>Hello Button</Button>10  ));Using AI Code Generation
1import { addDecorator, addParameters } from '@storybook/react';2import { withThemesProvider } from 'storybook-addon-styled-component-theme';3import { withRootDecorator } from 'storybook-root-decorator';4import { withInfo } from '@storybook/addon-info';5import { withKnobs } from '@storybook/addon-knobs';6import { withA11y } from '@storybook/addon-a11y';7import { withViewport } from '@storybook/addon-viewport';8import { withTests } from '@storybook/addon-jest';9import { theme } from '../src/theme';10import { withConsole } from '@storybook/addon-console';11addDecorator(withRootDecorator);12addDecorator(withInfo);13addDecorator(withKnobs);14addDecorator(withA11y);15addDecorator(withViewport);16addDecorator(withTests({ results }));17addDecorator((storyFn, context) => withConsole()(storyFn)(context));18addDecorator(withThemesProvider([theme]));19addParameters({20  options: {21  },22  viewport: {23    viewports: {24      iPhone5: {25        styles: {26        },27      },28      iPhone6: {29        styles: {30        },31      },32      iPhone6Plus: {33        styles: {34        },35      },36      iPad: {37        styles: {38        },39      },40      iPadPro: {41        styles: {42        },43      },44    },45  },46  info: {47  },48});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!!
