Select option can’t be set after loading data

checkEndYear();  //load data to select
change_val()
function change_val(){
    grade.value = grade_val
}

grade – var for select element HTML

grade_val – value I want to be set

After loading data I want to set value to a select HTML element. It works if I call change_val() manually (I added a test button and set change_val() as onClick to it), but it doesn’t work if I call it just after data to select is loaded.

Getting calendars from Guesty API

I’m currently working in a inside system for the place i’m working in, so we want to get the calendar for every listing we have in Guesty, but everytime we make test every time it fails because a thing called “CORS”, and i alredy did everything i had to do with it, but i cannot get the information i need. Anyone knows how to solve CORS problem? i heard it was a backend trouble, and not front, but i need to get all the info with my petition on JavaScript.
Attached photo of the error
CORS Error

pass a referenced parent div id to js function through onclick attribute

i want to get the element of a child div from a SPECIFIC parent div. my div may have the same id which is id="petAttribute. what im going to do is iterate through a list of pet details, store their information in a card and when i click the button IN the card, it will alert the content of that particular card.

the problem in my code was, i successfully prompt the name of the pet, but when i click on a different card, it does not prompt the name from the card that i clicked.

function pet(){
    
    let petAttribute = document.getElementById("petAttribute").children;

    let petname = petAttribute[0].innerHTML;

    alert(petname);
  }
* {
    box-sizing: border-box;
  }
  
  body {
    font-family: Arial, Helvetica, sans-serif;
  }
  
  /* Float four columns side by side */
  .column {
    float: left;
    width: 25%;
    padding: 0 10px;
  }
  
  /* Remove extra left and right margins, due to padding */
  .row {margin: 0 -5px;}
  
  /* Clear floats after the columns */
  .row:after {
    content: "";
    display: table;
    clear: both;
  }
  
  /* Responsive columns */
  @media screen and (max-width: 600px) {
    .column {
      width: 100%;
      display: block;
      margin-bottom: 20px;
    }
  }
  
  /* Style the counter cards */
  .card {
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
    padding: 16px;
    text-align: center;
    background-color: #f1f1f1;
  }
  img {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    border: 1px solid black;
  }
  .button {
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 3px 3px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 2px 2px;
    cursor: pointer;
  }
h2>Choose your pet to groom</h2>

<div class="row">
  <div class="column">
    <div class="card" id="petcard">
    <img src="https://logowik.com/content/uploads/images/t_cat8600.jpg" alt="Paris" width="300" height="300">
      <div id = "petAttribute">
      <div id="name">Nomi</div>
      <div id="breed">Domestic Long Hair</div>
      <div id="age">Adult</div>
    </div>
      <input type="button" class="button" value="Groom my pet"  onclick="pet()">
    
    </div>
  </div>

  <div class="row">
  <div class="column">
    <div class="card" id="petcard">
    <img src="https://logowik.com/content/uploads/images/t_cat8600.jpg" alt="Paris" width="300" height="300">
      <div id="petAttribute">
      <div id="name">kuchi</div>
      <div id="breed">Domestic short Hair</div>
      <div id="age">kitten</div>
      </div>
      <input type="button" class="button" value="Groom my pet" onclick="pet()">
    </div>
  </div>

TypeScript: Is it possible to define a variadic function that accepts different types of arguments?

I want to write a generic function that accepts variable number of arguments that may have different types and returns a tuple based on those arguments.

Here is an example in JavaScript:

function evaluate (...fns) {
  return fns.map(fn => fn())
}

evaluate(
  () => 10
) // [ 10 ]

evaluate(
  () => 10,
  () => 'f',
  () => null
) // [ 10, 'f', null ]

And in TypeScript I need to somehow convert the spread argument tuple to a resulting one:

function evaluate<T1, T2 ... Tn> (
  ...fns: [() => T1, () => T2 ... () => Tn]
): [T1, T2 ... Tn] {
  return fns.map(fn => fn()) as [T1, T2 ... Tn]
}

evaluate(
  () => 10
) // [ 10 ]: [number]

evaluate(
  () => 10,
  () => 'f',
  () => null
) // [ 10, 'f', null ]: [number, string, null]

I’ve tried a naive approach of creating an overload for all reasonable lengths of tuple:

function evaluate<T1> (
  fn1: () => T1
): [T1]
function evaluate<T1, T2> (
  fn1: () => T1,
  fn2: () => T2
): [T1, T2]
function evaluate<T1, T2, T3> (
  fn1: () => T1,
  fn2: () => T2,
  fn3: () => T3
): [T1, T2, T3]
function evaluate<T1, T2, T3> (
  ...fns: Array<(() => T1) | (() => T2) | (() => T3)>
): [T1] | [T1, T2] | [T1, T2, T3] {
  return fns.map(fn => fn()) as [T1] | [T1, T2] | [T1, T2, T3]
}

But it looks horribly, doesn’t scale well and causes issues with a more complex function body.

Is there any way this could be done dynamically? Thanks!

Clear before appending an element in javascript

I am building an app, when I create on the search button or click on a link, a html element is created. When I click on another link or button, the old element isn’t cleared, they just keep piling on the same page. The new result is moved to the bottom while the old one remains on top.

Also, when I load my page, the data immediately shows on the page, which means the onclick function isn’t working. The page automatically loads with the data and nothing changes when i CLICK.

I have shared my code, any idea what is wrong?

I tried row.innerHTML=”, but that didn’t change anything.

const createElement = (tag, ...content) => {
    const el = document.createElement(tag);
    el.append(...content);
    return el;
  };
  
  const setData = (entity, isHRrequired=false) =>{
  const dl = document.createElement('dl');
  
  for (const entityProps of entity) {
     for (const currentkey of Object.keys(entityProps)) {
      const dt =  document.createElement('dt');
      const dd =  document.createElement('dd');
       dt.innerText = currentkey;
       if(Array.isArray(entityProps[currentkey])) {
         dd.append(formatData(entityProps[currentkey]));
  
       } else {
  
       dd.innerText = entityProps[currentkey];
  
       
  
      }
  
      dl.append(dt);
      dl.append(dd);
    }
  
    if (isHRrequired) {
      const hr = document.createElement('hr');
      dl.append(hr);
    }
  }
  
  return dl;
  
  }
  
    const results = document.getElementById("results");
  // refresh the page
  myResult.innerHTML = '';
  
  
  function RetrieveResult(url){
    //http request
    fetch(url
   )
  .then((res) => (res.ok ? res.json() : Promise.reject(res)))
  .then((data) => {
    const dataResults = setData(data, true)
    results.append(dataResults)
          document.createElement("br"),
          document.createElement("br")
  })
  .catch(console.error);
  }

const log=document.getElementById("log");

catalog.addEventListener("onclick",  RetrieveResult(`http://localhost:8001/v1/logs/`));

HTML

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/styles.css">

</head>
<body>
    
<button id="logs">View logs</button>
<div id="myResult"></div>

<body></body>

React Confirm Alert library showing “Warning: ReactDOM.render is no longer supported in React 18.”

I’m trying to use the react-confirm-alert library for a confirmation dialog. But it’s giving me a warning when the confirmation pop-up is opening for the react version upgrade. “Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it’s running React 17.” Is there any way to get rid of the warning? Or is there any good alternative library that I can use for a confirmation dialog?

Thank you!

Handlebars is failing to render identical templates

I’m using Handlebars.js to render two templates, both completely identical bar a different ID. The first render is not functional (No list rendered) but the second renders perfectly. What could explain this?
HTML:

          <div class="input-group mb-3">
            <div class="input-group-prepend">
              <label class="input-group-text" for="inputGroupSelect01">Src</label>
            </div>
            <select class="custom-select" id="inputGroupSelect01" onChange="takeSelectedSourceValue(this);">
              <option id="source-language" value="" selected disabled>Auto</option>
            </select>
          
            <script type="text/handlebar-template" id="selectPersonTemplate">
              {{#each people}}
                <option value="{{valueLang}}">{{htmlLang}}</option>
              {{/each}}
            </script>
            </select>
          </div>
          
            <div class="input-group mb-3">
              <div class="input-group-prepend">
                <label class="input-group-text" for="inputGroupSelect01">Src</label>
              </div>
              <select class="custom-select" id="inputGroupSelect02" onChange="takeSelectedSourceValue(this);">
                <option id="source-language" value="" selected disabled>Auto</option>
              </select>
            
              <script type="text/handlebar-template" id="selectPersonTemplate">
                  {{#each people}}
                    <option value="{{valueLang}}">{{htmlLang}}</option>
                  {{/each}}
                </script>
              </select>
            </div>
              

JS:

$(function () {
  var people = [
    { valueLang: 'DE', htmlLang: 'DE' },
    { valueLang: 'FR', htmlLang: 'FR' },
    { valueLang: 'IT', htmlLang: 'IT' },
    { valueLang: 'ES', htmlLang: 'ES' },
    { valueLang: 'SV', htmlLang: 'SV' },
    { valueLang: 'DA', htmlLang: 'DA' }
  ];
  
  var templateText = $("#selectPersonTemplate").html();
  
  var selectPersonTemplate = Handlebars.compile(templateText);
  
  var html = selectPersonTemplate({ people: people });
  
  $("#inputGroupSelect01").html(html);
  $("#inputGroupSelect02").html(html);
});
  

Mocking a default export function with Jest: TypeError: (0 , _sampleFunction).default is not a function

I have the following files:

sampleFunction.ts:

export default (x: number) => x * 2;

testFile:

import sampleFunction from './sampleFunction';

export default () => {
  const n = sampleFunction(12);
  return n - 4;
};

testFile.test.ts:

import testFile from './testFile';

const mockFn = jest.fn();

jest.mock('./sampleFunction', () => mockFn);

test('sample test', () => {
  testFile();
  expect(mockFn).toBeCalled();
});

When I run testFile.test.ts, I get the following error:

TypeError: (0 , _sampleFunction).default is not a function

Question:
How can I mock sampleFunction.ts with jest when it has a default exported function? Thanks!

ApiRTC IP RANGE

I’m using Apizee’s ApiRTC API Video Call module.

However, some of our customers are experiencing firewall blocks.
The only way to fix the problem is to manually change the IP.

I would like to know whether or not you have an IP Range released to use the API.

Thank you!

How to change a value in MySQL Database to a value of a variable defined in JS/Node?

In the database a customer has unique id which is defined below as idEmail = id, I am trying to find the customer in the database against this id and then replace their hashed password but I’m struggling with the SQL syntax as I’m not sure how I can give the “password” & “emailId” in the query a value rather than setting “password” to “password” where “id” = “emailId” and not the actual value of the emailId variable:

app.post("/reset_password/:id/:token", (req, res, next) => {
const { id, token} = req.params;
const idEmail = id;
const {password, password2} = req.body;
db.query("SELECT * FROM user WHERE id = ?", [idEmail], async (error, results) => {
if (id != results[0].id) {
  res.send("Invalid id" + id + results[0].id)
  return
}

const secret = JWT_SECRET + results[0].password
try {
  const payload = jwt.verify(token, secret)
  if (password === password2) {
    let hashedPassword = await bcrypt.hash(password, 8);
    
    db.query(
      "UPDATE user SET password = 'password' WHERE id = 'emailId' ",
      {
        password: hashedPassword,
        emailId: idEmail,
      },
      (error, results) => {
        if (error) {
          console.log(error);
        } else {

How to create groups and allocate a quantity per group depending on maximum value per group?

I am trying to create a function that creates groups and allocates a quantity per group, depending on the user input.

For example:

// Input
User input: 150

// Rule
Maximum quantity per group: 100

// Created groups
Group 1: { quantity: 100 }
Group 2: { quantity: 50 }

Goal

This is my desired outcome:

[{ quantity: 100 }, { quantity: 50 }]

What I have tried

function group(input, maximum) {
  let arr = (new Array(Math.floor(input / maximum))).fill(maximum);

  input % maximum && arr.push(input % maximum);

  console.log(arr);
}

group(150, 100);

Output

This will return me: [100, 50].

Now I tried implementing this to output me an object:

function group(input, maximum) {
  let arr = (new Array({quantity: Math.floor(input / maximum)})).fill(maximum);

  input % maximum && arr.push({quantity: input % maximum});

  console.log(arr);
}

group(150, 100);

Output

This returns me: [100, { "quantity": 50 }].

quantity is only added to the second element, but not the first.

Question

How can I fix this, so all the array elements is an object?

persons.filter is not a function

so i am triyng to make a filter search. i am calling the funciton using


      <h2>Numbers</h2>
      {
        persons.map((persons) => <Persons persons={persons} setFilter= {setFilter} key={persons.id} />)
      }
    </div>

so i created an array using map however when i pass it through

  const Persons = ({ persons, setFilter }) => {
    const checkPersonsName = setFilter === '' ? 
      persons
    :
      persons.filter((person) => person.name.toLowerCase().includes(setFilter) )
    return (<li>{checkPersonsName.name} {checkPersonsName.number}</li>)

  }
  

it gives me an error saying Uncaught TypeError: persons.filter is not a function. i did a const log and persons should be an array. so i am not quite sure what to do here and why i am getting this error.