Dependency injection question / small example problem

Can simple vanilla dependency injection, such as modules exporting a function that expects an object of dependencies fix the below problem of helper files trying to share their helper functions with each other? Thanks.

index.js

const { sumEvens } = require("./math");

const nums = [1, 2, 1, 1, 2];

console.log(sumEvens(nums));

math.js

const { removeOdds } = require("./filters");

const isEven = (n) => n % 2 === 0;

const sumEvens = (nums) => removeOdds(nums)
  .reduce((sum, n) => sum + n, 0);

module.exports = {
  isEven,
  sumEvens
}

filters.js

const { isEven } = require("./math");

const removeOdds = (nums) => nums.filter((n) => isEven(n));

module.exports = {
  removeOdds
}

TypeError: isEven is not a function, I think because of some circular requiring?

Uncaught TypeError: Cannot read properties of undefined (reading ‘target’) & (reading ‘value’)

After JQuery Version Upgrades to 3.5.0 from 2.14, I am receiving the following error, but I did not fully understand what the problem is,there is radio = event.target The error I received in the definition of Cannot Read Properties of Undefined (Reading ‘target’)
Anyone can you help me solve?
*

var testMethod = {
    testSubMethod: function (event) {
    
        var radio = event.target;
        var isMultiInput = $('#MultipleInputYes').is(':checked');

        if (isMultiInput) {
            $('.divMultiInput').removeClass("dp-none");

            $('.divMinMaxVal').addClass("dp-none")
            $('#divMinMaxDate').addClass("dp-none")

            $('#divRgxWarnMsg').addClass("dp-none")

            $('#minValueInpt').val('');
            $('#maxValueInpt').val('');

            $('.divInputValUpper').addClass("dp-none");
            $('[name=ValueType]').val('');
            $('#inputValueTypeSelect').removeClass('required');
            $('#inputValueTypeSelect').removeClass('customError');

        }
        else if (!isMultiInput || radio.value == undefined) {
            $('.divMultiInput').addClass("dp-none");

            $('.divMinMaxVal').removeClass("dp-none");
            $('#divMinMaxDate').removeClass("dp-none");
            $('#divRgxWarnMsg').removeClass("dp-none")

            $('.divInputValUpper').removeClass("dp-none");
            $('[name=ValueType]').val('1');
            $('#inputValueTypeSelect').addClass('required');

            $('#divWarnMsg').css("display", "inherit");
            $('#placeHolderInpt').val('');
            $("#maskInpt").select2("val", "");

            if (radio.value == 'false') {
                $('#divInputValueType').prop('disabled', false);
                $('#divInputValueType').attr('style', '');
            }

            $('#htmlEditorDiv').css("display", "inherit");
            $('#useMultiLineDiv').css("display", "inherit");

            $("#Tags").tagit("removeAll");
        }
    },
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<div class="radio radio-success">
<input type="radio" id="MultipleInputYes" value="true" name="IsMultiInput" onchange="testMethod.testSubMethod(this)">
<label for="MultipleInputYes"> Yes</label>
</div>

<div class="radio radio-success">
<input type="radio" id="MultipleInputNo" value="false" checked="checked" name="IsMultiInput" onchange="testMethod.testSubMethod(this)">
<label for="MultipleInputNo">No</label>
</div>

Create React App. Loading code split from dependency

I have a component library that I want to work with create-react-app style apps.

This component library is being built with webpack and it has a dependency on a WASM module which is being built with wasm_pack.

In the component library, I dynamically import the required wasm library. This produces a code split in the component library and webpack creates an index.js file and a separate file for the code split, call it spec.js as expected.

When I try to import this library in create-react-app however, it attempts to load /static/js/spec.js when the dynamic import code is hit, but nothing is served from that endpoint.

How do you get CRA to simply grab and host the split.js file from the component library?

I have played around with the output.publicPath variable in the webpack config for the component library but that seems to simply change where CRA is trying to pull the spec.js file from.

Do I need to specify something in the package.json file for the component library to include both the main js file and the split file?

For reference the dynamic import code within the component library is

import { useEffect, useState } from 'react'

export const useValidator = () => {
  const [validator, setValidator] = useState<any>(null)
  const [validatorReady, setValidatorReady] = useState<boolean>(false)
  const [error, setError] = useState<any | undefined>(undefined)

  useEffect(() => {
    let f = async () => {
      try {
        console.log("attempting to import wasm")
        const wasm = await import( /*webpackChunkName:"spec"*/ '@maticoapp/matico_spec');
        console.log("gotWasm ", wasm)
        setValidator(wasm)
        setValidatorReady(true)
      } catch (err) {
        setError(`failed to load wasm: ${err}`)
        console.log("unexpected error in load wasm ", err);
      }
    };
    f();
  }, []);
  return { validator, validatorReady, error }
}

the webpack setup for the component library has the entry and output set as

const config = {
  entry: "./src/index.ts",
  output: {
    path: path.resolve(__dirname, "dist"),
    publicPath:"auto",
    filename: "index.js",
    library: {
      name: "matico_components",
      type: "umd"
    },
  },

and to handle the WASM import I have this in the component library webpack

  experiments: {
    asyncWebAssembly: true
  },

and I am using react-app-rewired on the CRA to also load in the WASM files.

Also just to note that the actual code split file ends up getting called something else. Just using spec.js here as an example.

Start and Crashed

I can turn on the app normally, but when I go to use it, it stops, no idea what the problem might be.

Logs:

Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
Stopping process with SIGKILL
Process exited with status 137
State changed from starting to crashed

Lazy loading of multiple sliders using verlock/vanilla-lazyload

There are several sliders with different settings in the project, following the library documentation, but the problem is that the documentation describes an example for several sliders with the same settings. My approach:

const gallerySlider = {
  slidesPerView: 1,
  slidesPerColumnFill: 'row',
  spaceBetween: 50,
  observer: true,
  observeParents: true,
  observeSlideChildren: true,
  grid: {
    fill: 'row',
  },
  pagination: {
    el: '.swiper-pagination',
    type: 'fraction',
    clickable: 'true',
  },
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  },
  breakpoints: {
    421: {
      grid: {
        rows: 2,
      },
      slidesPerView: 2,
      spaceBetween: 34,
      slidesPerGroup: 2,
    },
    1200: {
      grid: {
        rows: 2,
      },
      slidesPerGroup: 2,
      spaceBetween: 34,
    },
    1600: {
      grid: {
        rows: 2,
      },
      slidesPerView: 3,
      slidesPerGroup: 3,
      spaceBetween: 50,
    },
  },
  a11y: {
    prevSlideMessage: 'Prev',
    nextSlideMessage: 'Next',
  },
  on: {
    // LazyLoad swiper images after swiper initialization
    afterInit: (swiper) => {
      new LazyLoad({
        container: swiper.el,
        cancel_on_exit: false
      });
    }
  }
};

then I initialize the vanilla-lazyload:

new LazyLoad({
  elements_selector: ".swiper-lazy",
  unobserve_entered: true,
  callback_enter: function (swiperElement) {
    new Swiper("#" + swiperElement.id, gallerySlider); 
// gallerySlider - settings Swiper-slider
  }
});

I also tried initializing a new instance of the library for each slider, but this approach also turned out to be ineffective, the settings for the first slider were applied to all sliders

new LazyLoad({
  elements_selector: ".swiper-lazy",
  unobserve_entered: true,
  callback_enter: function (swiperElement) {
    new Swiper("#" + swiperElement.id, gallerySlider);
  }
});

new LazyLoad({
  elements_selector: ".swiper-lazy",
  unobserve_entered: true,
  callback_enter: function (swiperElement) {
    new Swiper("#" + swiperElement.id, projectsSlider);
  }
});

new LazyLoad({
  elements_selector: ".swiper-lazy",
  unobserve_entered: true,
  callback_enter: function (swiperElement) {
    new Swiper("#" + swiperElement.id, eventsSlider);
  }
});

Javascript “”Function not found”

I have a very simple HTML page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test 2 V2</title>
</head>
<body>
    <p>
        <label id="wordCat"></label>
        <input type="text" id="txtCat">
        <input type="button" id="btnCat" value="Load Word" onclick="fetchData(document.getElementById('txtCat').value)">
    </p> 
    <p>
        <label>Your Guess Word is:</label>
        <label id="hiddenWord"></label>
    </p>
    <script src="scripts/app.js"></script>
</body>
</html>

On clicking the button it should call the function:

async function fetchData(req) {
    console.log(req.value)
    let response = await fetch(req);
    var selectBox, option, prop;

    

    selectBox = document.getElementById("drivers");

    if (response.statusText == "OK") {
        return await response.json();      
    }else{
        throw new Error(response.statusText);
    }
}

The problem is that when I click the button it says: GET http://127.0.0.1:5500/{input value in the text box} 404 (Not Found)

Anyone can help me fixing this? This method is supposed to load all the keys present in json file and print them.

words.json

{
    "sports":       ["golf", "hockey", "football"],
    "animals":      ["giraffe", "snake", "lizard", "puma"],
    "video games":  ["pacman", "asteroids", "super mario brothers", "donkey kong"]
}

I need to print the keys in alphabetical order on HTML page.

Thanks.

How do you test an RTKQuery endpoint using jest.spyOn

I’m trying to test RTKQuery that an endpoint has been called using jest.

I eventually want to also be able to mock what the return data will be, but first I wanted to just check that the hook had been called.

An example below where I am trying to spy on myApi for the useGetMyListQuery hook which is autogenerated.

This throws and error when it runs, can anyone help?

it('Should render', async () => {
    jest.spyOn(myApi, 'useGetMyListQuery')

    render(
      <Provider store={store}>
        <MyComponent />
      </Provider>
    )

    expect(myApi.useGetMyListQuery).toBeCalled()
})

In react.js, updated state values aren’t showing in table list( table list use state value )

I just made a table to display customers emails and added functions to remove or add new emails.
but for add function, I saved new email into state(users). but it’s not showing in email table list. remove function is working great! could you help me to fix this issue?
Just attached my code

import React, {useState} from 'react';

const Admin: NextPage = () => {

  const [users, setUsers] = useState([
    { email: "[email protected]" },
    { email: "[email protected]"},
  ]);

  const [email, setEmail] = useState('');

  const removeUser = rowEmail => {
    const updatedArray = users.filter((row) => row.email !== rowEmail);
    setUsers(updatedArray);
  }

  const addUser = () => {
    console.log(email);
    const lists = users;
    lists.push({'email' : email});
    setUsers(lists);
  }
  
  return (
    <>
    <div className="user-user">
      <input type="email" onChange={event => setEmail(event.target.value)} />
      <span onClick={() => addUser()}>Add User</span>
    </div>
    <div className="user-list">
      <table>
        <thead>
          <tr>
            <th>Users</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          {users.map((val, key) => {
            return (
              <tr key={key}>
                <td>{val.email}</td>
                <td><span onClick={() => removeUser(val.email)}>Remove</span></td>
              </tr>
            )
          })}
        </tbody>
      </table>
    </div>
    </>
  );
}
  
export default Admin;

How to connect js program to a database

I am trying to make a js program that can interact with an external database (hosted online) and 1) add new fields or 2) add to the number in an existing field.
I wants to make the database with 2 columns (lets say ‘name’ and ‘quantity’), and I want the js program be able to either add a new item to the database and set the quantity for that new item to 1, or increase the quantity of an item already in the database by 1. How can I do that on the side of the js program, and how do I do that on the side of the database? I have a basic knowledge of js from web development, but I’ve only worked with Django (the python web framework) so I don’t know how to do anything with databases. Thanks!

In react, can’t display state values as well [duplicate]

I want to make a table for user email lists. but when I create new email(click add user btn), users state doesn’t update. could you help me to fix this issue? thank you

import React, {useState} from 'react';

const Admin: NextPage = () => {

  const [users, setUsers] = useState([
    { email: "[email protected]" },
    { email: "[email protected]"},
  ]);

  const [email, setEmail] = useState('');

  const removeUser = rowEmail => {
    const updatedArray = users.filter((row) => row.email !== rowEmail);
    setUsers(updatedArray);
  }

  const addUser = () => {
    console.log(email);
    const lists = users;
    lists.push({'email' : email});
    setUsers(lists);
  }
  
  return (
    <>
    <div className="user-user">
      <input type="email" onChange={event => setEmail(event.target.value)} />
      <span onClick={() => addUser()}>Add User</span>
    </div>
    <div className="user-list">
      <table>
        <thead>
          <tr>
            <th>Users</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          {users.map((val, key) => {
            return (
              <tr key={key}>
                <td>{val.email}</td>
                <td><span onClick={() => removeUser(val.email)}>Remove</span></td>
              </tr>
            )
          })}
        </tbody>
      </table>
    </div>
    </>
  );
}
  
export default Admin;

Is it possible to store each return of the same http request in an array in jmeter?

In my post processor I have the following code:

if (i as Integer < protocolsArray.length){


          
protocolsArray[i as Integer] = "${requestProtocolId}" ;

}

and it worked, I put the “requestProtocolId” that I got via JsonExtractor in the position of “i”, position of i == 0

but the number of virtual users defined in this http request is greater than one.

so it sends the request again and saves the new “requestProtocolId” again in position zero, overwriting the other protocol,I understand that with the new request it starts all over again, taking the initial values ​​assigned to the variables again, but I’ve already tried incrementing the i (i ++) and returning the new array with the zero position filled in:

vars.putObject("protocolsArray", protocolsArray);

but it always returns the value set before the htpp request, is there a way to change that?

If I changed and put an iteration controller and it was a group of users but in iteration controller “5”, it would be like the same user would send it five times, right?

I wanted to simulate different users, but always keep the “requestProtocolId” value saved in the array positions because I’m going to use it in another request.

Uncaught ReferenceError: Unable to process binding with KnockoutJS

We have a multiple page form like below , each page on the form is associated with different model classes. I am trying use the value the users selected in Page 1 and based upon that value selected in Pg1 I need to show/hide the field in Page2. Below is what I am trying

<div id="Page_1" style="display: none;">
    <div class="form-group required">
        <label for="Solution" class="control-label">Solution</label>
        <select id="Solution" name="Solution" class="form-control" data-bind="options: solutions, value: solution, optionsCaption: 'Select'"></select>
    </div>
    ...................
    <button type="submit" id="NtPg" class="SubmitButton" data-bind="click: next">Next</button>         
 </div>
 <div id="Page_2" style="display: none;">
    <button type="submit" id="AddCourseInfo" class="SubmitButton" data-bind="click: addCourse">Add Course Info</button>
   <div data-bind="foreach:CourseDetails" >
     <div class="form-group required" data-bind="visible: solution() == 'Other'">
       <label for="OtherSolution" class="control-label">Explain Other Solution : </label>
       <input type="text" maxlength="1000" id="OtherSolution" name="OtherSolution" class="form-control" data-bind="value : otherSolution" required/>
     </div> 
   </div>
   ...........................

Page2 has a button which allows the users add courses, when they click on the button few fields shows up in the page in foreach loop and one of the field should show/hide based on the selection made on the previous page. But the above logic throws error like Uncaught ReferenceError: Unable to process binding "visible:" below is the viewmodel

self.Solution= ko.observable().extend({ required: { params: true, message: "Required" } });

self.CourseDetails= ko.observableArray();

self.addCourse= function () {
    self.CourseDetails.push(new coursesList());
}

function coursesList() {
var self = this;
 self.otherSolution= ko.observable().extend({ required: { params: true, message: "Required" } });
 ........
}

How can I have the binding work properly here and get rid of the error

d3: how to focus separate tooltips for stacked area chart?

I’m creating a stacked area chart using d3.js. Right now im not able to figure out on mousemove how to focus separate tooltip on the respective chart curve.
I’m trying to achieve this but for stacked area chart

I have created a sandbox of my progress here: https://codesandbox.io/s/recursing-carlos-3t0lg

Relevant code:

    function mouseMove() {
      d3.event.preventDefault();
      const mouse = d3.mouse(d3.event.target);
      const [xCoord, yCoord] = mouse;
      const mouseDate = x.invert(xCoord);
      const mouseDateSnap = d3.timeDay.floor(mouseDate);
      const bisectDate = d3.bisector((d) => d.date).left;
      const xIndex = bisectDate(data, mouseDateSnap, 0);
      const mouseHours = data[xIndex].hours;
      let demandHours =
        data[xIndex].resourceType === "DMND" ? data[xIndex].hours : "";
      let supplyHours =
        data[xIndex].resourceType === "SPLY" ? data[xIndex].hours : "";

      if (x(mouseDateSnap) <= 0) return;

      svg
        .selectAll(".hoverLine")
        .attr("x1", x(mouseDateSnap))
        .attr("y1", margin.top)
        .attr("x2", x(mouseDateSnap))
        .attr("y2", height - margin.bottom)
        .attr("stroke", "#69b3a2")
        .attr("fill", "#cce5df");

      svg
        .select(".hoverPoint1")
        .attr("cx", x(mouseDateSnap))
        .attr("cy", y(supplyHours))
        .attr("r", "7")
        .attr("fill", "green");
      svg
        .select(".hoverPoint2")
        .attr("cx", x(mouseDateSnap))
        .attr("cy", y(demandHours))
        .attr("r", "7")
        .attr("fill", "yellow");

      const isLessThanHalf = xIndex > data.length / 2;
      const hoverTextX = isLessThanHalf ? "-0.75em" : "0.75em";
      const hoverTextAnchor = isLessThanHalf ? "end" : "start";

      svg
        .selectAll(".hoverText")
        .attr("x", x(mouseDateSnap))
        .attr("y", y(mouseHours))
        .attr("dx", hoverTextX)
        .attr("dy", "-1.25em")
        .style("text-anchor", hoverTextAnchor)
        .text(
          data[xIndex].resourceType === "DMND"
            ? demandHours + "sec"
            : supplyHours + "sec"
        );
    }

    svg.append("line").classed("hoverLine", true);
    svg.append("circle").classed("hoverPoint1", true);
    svg.append("circle").classed("hoverPoint2", true);
    svg.append("text").classed("hoverText", true);
    svg
      .append("rect")
      .attr("fill", "transparent")
      .attr("x", 0)
      .attr("y", 0)
      .attr("width", width)
      .attr("height", height);
    svg.on("mousemove", mouseMove);

In above code I’m creating 2 separate tooltips using selections hoverPoint1 (to show hours SPLY hours) and hoverPoint2 (to show DMND hours)

Expected:
on mousemove, the green circle should move along the curve of blue plotted area AND at same time yellow circle should move along curve of gray plotted area. (please see this as example which shows single area tooltip https://observablehq.com/@elishaterada/simple-area-chart-with-tooltip)

thanks!

How are Jest mocks structured for different npm package imports/exports?

Using Jest testing in a React Native Expo project

I’m trying to mock some node modules in my project, but many of them have different import export methods.

1 Some are destructured:

import { myFunc } from 'my-module'

2 Some are default:

import myModule from 'my-module'

3 Some are the everything import:

import * as myModule from 'my-module'

4 In other cases, I need to mock a nested function like:

myModule.dosomething()

How do I mock each of these? I cannot for the life of me find a guide that explains it.