JavaScript ‘filter’ array method not working as expected for leetcode problem [closed]

I was doing a leetcode problem (‘Remove Element’) and thought that I had the right approach, but I kept failing some of the test cases. The problem is as follows:

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

My attempt:

const removeElement = (nums, val) => {

  nums = nums.filter(num => num != val);

  return nums.length;
};

The test case that failed was when nums = [3, 2, 2, 3] & val = 3.
My code would give nums = [3, 2] when the test case expects nums = [2, 2].

I’m not sure what I’ve done wrong here; please help.
Thanks

how to solusion codeAssist?

enter image description here

ERROR: 04-09 05:10:46.935 24190 24190 E AndroidRuntime: FATAL EXCEPTION: main ERROR: 04-09 05:10:46.935 24190 24190 E AndroidRuntime:

Process: com.cs.videocalling, PID: 24190

ERROR: 04-09 05:10:46.935 24190 24190 E AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method ‘void com.cs.videocalling. PreferenceManager.putBool ean(java.lang.String, java.lang.Boolean) on a null object reference

ERROR: 04-09 05:10:46.935 24190 24190 E AndroidRuntime: at

com.cs.videocalling.SignUp$4.onSuccess(SignUp.java:91)

ERROR: 04-09 05:10:46.935 24190 24190 E AndroidRuntime: at

com.cs.videocalling.SignUp$4.onSuccess(SignUp.java:88)

ERROR: 04-09 05:10:46.935 24190 24190 E AndroidRuntime: at com.google.android.gms.tasks.zzm.run(com.google.android.gms: play-services-tasks@@18.0.2:1)

ERROR: 04-09 05:10:46.935 24190 24190 E AndroidRuntime: at

android.os.Handler.handleCallback(Handler.java:938)

ERROR: 04-09 05:10:46.935 24190 24190 E AndroidRuntime: at

android.os.Handler.dispatchMessage(Handler.java:99)

ERROR: 04-09 05:10:46.935 24190 24190 E AndroidRuntime: at

android.os.Looper.loopOnce (Looper.java:210)

ERROR: 04-09 05:10:46.935 24190 24190 E AndroidRuntime: at android.os.Looper.loop(Looper.java:299)

ERROR: 04-09 05:10:46.935 24190 24190 E AndroidRuntime: at

android.app.ActivityThread.main(ActivityThread.java:8298)

ERROR: 04-09 05:10:46.935 24190 24190 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method) ERROR: 04-09 05:10:46.935 24190 24190 E AndroidRuntime: at

com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(

RuntimeInit.java:576)

ERROR: 04-09 05:10:46.935 24190 24190 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1873

package com.cs.videocalling;

2

3 import android.content.Context; import android.content. SharedPreferences;

5

6 public class PreferenceManager {

7

8

private SharedPreferences sharedPreferences;

9

10 public PreferenceManager (Context context) { sharedPreferences = context.getSharedPreferences (Constants.

11

12

13

}

14

15

public void putBoolean (String key, Boolean value) { SharedPreferences. Editor editor = sharedPreferences.edit(); editor.putBoolean(key, value);

16

17

18

editor.apply();

19 } 21 public Boolean getBoolean (String key){ return sharedPreferences.getBoolean (key, false); }

20

22

23

24

25

26

27

28

public void putString(String key, String value){

SharedPreferences. Editor editor = sharedPreferences.edit(); editor.putString(key, value); editor.apply(); }

29

30

31

32

public String getString(String key) { return sharedPreferences.getString(key, enabled);

}

33

34

35

36

public void clearPreference(){ SharedPreferences. Editor editor = sharedPreferences.edit(); editor.clear(); editor.apply();

37

38

39

40

}

41

How can I convert an array of Promises to an AsyncIterable (or a normal Iterable)?

I have a function that puts a bunch of async operations into an array and waits for them to resolve before continuing.

function foo(reqs: () => Promise<string>): Promise<string[]> {
  const ops: Array<Promise<string>> = []

  for (const req of reqs) {
    ops.push(req())
  }

  return Promise.all(ops)
}

I would like to be notified when each promise resolves, regardless of order. I can do this easily with a callback.

function foo(
  reqs: () => Promise<string>, 
  onResolved: (value: string) => any,
): Promise<string[]> {
  const ops: Array<Promise<string>> = []

  for (const req of reqs) {
    const f = async () => {
      const s = await req()
      onResolved(s)
      return s
    }
    ops.push(f())
  }

  return Promise.all(ops)
}

The async iterable syntax is interesting and I am wondering if this is the type of use case it’s expected to handle.

Is it possible to use an async iterator for this so these events can be consumed as a for loop?

for await (const req of foo(reqs)) {
  console.log(req)
}

Or due to back pressure issues, can a normal iterator be used for this where the loop runs in order of promise resolution?

for (const req of foo(reqs)) {
  (async () => {
    console.log(await req)
  })()
}

White screen after installing django-unfold

I got a problem, it’s with JS which we got with the package or with me, which made a mistake on django-side, i’m not sure. I have installed the django-unfold package using “pip install django-unfold” and added it to my INSTALLED_APPS list as follows:

INSTALLED_APPS = [
    "unfold",
    "unfold.contrib.filters",
    "unfold.contrib.forms",
    # "nested_admin",
    'django.contrib.admin',
    
    # base
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    # project apps
    'work',


    # third-party-apps
    'rest_framework',
    'djoser',
    
    # 'corsheaders',
    'django_filters',
]

I have also made some changes to my admin.py as shown below:

from unfold.admin import ModelAdmin
    
    
@admin.register(Genre)
class GenreAdmin(ModelAdmin):
    pass

However, when I try to access the admin page at /admin/, I am presented with a white screen. Upon checking the console, I found the error message “Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data” in the alpine.persist.js file. I am not proficient in JS but I find the code in this file difficult to understand.

Therefore, I asked ChatGPT to make the code in alpine.persist.js more descriptive. The updated code is shown below:

(() => {
  function persistPlugin(alpineInstance) {
    let createPersistInterceptor = () => {
      let key, storage = localStorage;
      
      return alpineInstance.interceptor(
        (componentState, getState, setState, propName, uid) => {
          let stateKey = key || `_alpine_persist_${propName}_${uid}`;
          let storedValue = storage.getItem(stateKey);

          let updatedState = storedValue !== null ?
            JSON.parse(storedValue) :
            componentState;

          setState(updatedState);

          alpineInstance.effect(() => {
            let updatedValue = getState();
            storage.setItem(stateKey, JSON.stringify(updatedValue));
            setState(updatedValue);
          });

          return updatedState;
        },
        (options) => {
          options.as = (newKey) => (key = newKey, options);
          options.using = (newStorage) => (storage = newStorage, options);
        }
      );
    };

    Object.defineProperty(
      alpineInstance,
      "$persist",
      { get: () => createPersistInterceptor() }
    );

    alpineInstance.magic("persist", createPersistInterceptor);
  }

  function isKeyInLocalStorage(key, storage) {
    return storage.getItem(key) !== null;
  }

  function getStoredValue(key, storage) {
    return JSON.parse(storage.getItem(key));
  }

  function saveValueToLocalStorage(key, value, storage) {
    storage.setItem(key, JSON.stringify(value));
  }

  document.addEventListener("alpine:init", () => {
    window.Alpine.plugin(persistPlugin);
  });
})();

And here is the original one:

(() => {
  function g(t) {
    let e = () => {
      let n,
        s = localStorage;
      return t.interceptor(
        (r, i, a, p, m) => {
          let o = n || `_x_${p}`,
            l = c(o, s) ? d(o, s) : r;
          return (
            a(l),
            t.effect(() => {
              let u = i();
              f(o, u, s), a(u);
            }),
            l
          );
        },
        (r) => {
          (r.as = (i) => ((n = i), r)), (r.using = (i) => ((s = i), r));
        }
      );
    };
    Object.defineProperty(t, "$persist", { get: () => e() }),
      t.magic("persist", e);
  }
  function c(t, e) {
    return e.getItem(t) !== null;
  }
  function d(t, e) {
    return JSON.parse(e.getItem(t, e));
  }
  function f(t, e, n) {
    n.setItem(t, JSON.stringify(e));
  }
  document.addEventListener("alpine:init", () => {
    window.Alpine.plugin(g);
  });
})();

I have attempted to create a new, empty project and install django-unfold there, but the white screen issue persists. I would be extremely grateful if someone could help me resolve this issue

Google login authentication button not working, Firebase

I am an electrical engineering student and have to code a database for my senior design project. I am writting a small website to access this database to demo it. On the website I have a google login button on a javascript website (https://smartamberalert.web.app/) that is not working. I click the button and nothing happens.

here is my javascript code:

document.addEventListener("DOMContentLoaded", event =>{
    const app = firebase.app();
    
    const db = firebase.firestore();
    
    const testPost = db.collection('posts').doc();
    
    testPost.get().then(doc =>{
            const data = doc.data();
            document.write( data.title + '<br>')
            document.write( data.createdAt)
    })

//console.log(app)});

function googleLogin() { const provider = new firebase.auth.GoogleAuthProvider();
    firebase.auth().signInWithPopup(provider)

    .then(result =>{
        const user = result.user;
        document.write('Hello ${user.displayName}');
        console.log(user)
    })
    .catch(console.log)}

it is the googleLogin function that my problem should be in.

Here is my html code:

Welcome to Firebase Hosting

<!DOCTYPE html>

<!-- update the version number as needed -->
<script defer src="/__/firebase/9.17.2/firebase-app-compat.js"></script>
<!-- include only the Firebase features as you need -->
<script defer src="/__/firebase/9.17.2/firebase-auth-compat.js"></script>
<script defer src="/__/firebase/9.17.2/firebase-database-compat.js"></script>
<script defer src="/__/firebase/9.17.2/firebase-firestore-compat.js"></script>
<script defer src="/__/firebase/9.17.2/firebase-functions-compat.js"></script>
<script defer src="/__/firebase/9.17.2/firebase-messaging-compat.js"></script>
<script defer src="/__/firebase/9.17.2/firebase-storage-compat.js"></script>
<script defer src="/__/firebase/9.17.2/firebase-analytics-compat.js"></script>
<script defer src="/__/firebase/9.17.2/firebase-remote-config-compat.js"></script>
<script defer src="/__/firebase/9.17.2/firebase-performance-compat.js"></script>
<!-- 
  initialize the SDK after all desired features are loaded, set useEmulator to false
  to avoid connecting the SDK to running emulators.
-->



</script src = app.js>

<button onclick ="googleLogin()">
  Login in with google
</button>

`

I was following the tutorial (https://www.youtube.com/watch?v=9kRgVxULbag&list=PLg3EctrW99v2bRSrkALXrTWFH_fva1xvv&index=34&t=325s&ab_channel=Fireship) for firebase and working to get the google authentication function to work. The button will be displayed on the website but does not execute anything when clicked. I was expecting the regular google sign in popup window to appear when clicked

Get a value of a button in the textbox

I’m trying to build a calculator and I want to get the values of the clicked buttons in the textbox

this just an example how can I get the values of the clicked buttons here



<input type="text" name="" id="textfield" placeholder="Text" class="Text" readonly><br>
<button class="Y" value="Y"  onclick="">Y</button>
<button class="A" value ="A" onclick="">A</button>
<button class="S" value ="S" onclick="">S</button>
<button class="I" value ="I" onclick="">I</button>
<button class="R" value ="R" onclick="">R</button>

Is it possible to access whatsapp message database history using javascript or python?

I’m trying to get the chat history of my whatsapp account using whatsapp web. I could actually use selenium and go chat by chat, extracting every conversation (scraping, basically).

Is there any way to access the database where this messages are stored, so I don’t actually need to scrape it? I have looked into some libraries, like whatsapp-web.js, but I couldn’t find anything that just gives me the messages.

React Typescript: Can’t filter an array after refactoring code

I am building a To Do list project using React and TypeScript. In the process of refactoring my code and breaking up different divs (Active tasks, Done tasks, All tasks) into separate files within my component folder, my project is no longer able to filter out tasks that are “Done” or “Active” (this is determined by the checkbox value that is in my ToDoItem file, it has been condensed to a prop: onUpdateToDo) I am confused and stuck over where to filter out my ToDoItem within my “Done” file as I believe that it should be mapped out within the visibleTodos function. The visibleToDos function is in my App.tsx file.

App.tsx

  const [toDos, setToDos] = useState<ToDo[]>(initialTodos);
  const [addingToDo, setAddingToDo] = useState(false);
  const [showingDoneTasks, setShowDoneTasks] = useState(false); // show true if not
  const [showingActiveTasks, setShowActiveTasks] = useState(false); // show true if not
  const [showingAllTasks, setShowAllTasks] = useState(false);
  const [filterTodosCompleted, setFilterTodosCompleted] = useState<any | null>(
    null
  );

// VISIBLE TO DOS FUNCTION BELOW //

  const visibleTodos = useMemo(
    () =>
      toDos.filter((toDo) => {
        if (filterTodosCompleted === null) {
          return true;
        }
        return filterTodosCompleted === toDo.checked;
      }),
    [filterTodosCompleted, toDos]
  );

  useEffect(
    function () {
      localStorage.setItem("toDoList", JSON.stringify(toDos));
    },
    [toDos]
  );

/// showing Done Tasks function and jsx component with props being passed within

  function showDone() {
    setShowDoneTasks(true);
    setFilterTodosCompleted(true);
    setShowActiveTasks(false);
  }

  if (showingDoneTasks) {
    return (
      <DoneTasks
        newTask={newTask}
        showActive={showActive}
        toDos={toDos}
        showDone={showDone}
        visibleTodos={toDos}
        setToDos={setToDos}
        showAllTasks={showAllTasks}
      />
    );
  }

Done.tsx

export const DoneTasks = (props:{
  newTask: () => void
  showActive: () => void
  toDos: ToDo[];
  showDone: () => void
  visibleTodos: ToDo[];
  setToDos: (value: React.SetStateAction<ToDo[]>) => void
  showAllTasks: () => void


}) => (
  <div className="App">
    <div className="greeting-container">
      <div className="greeting">
        <Greeting />
      </div>
      <button className="task-button" onClick={props.newTask}>
        New Task
      </button>
      <div className="date-container">
        Today is {new Date().toLocaleString("en-US", { weekday: "long" })}
        <br />
        <div className="current-date">
          {new Date().toLocaleString("en-US", {
            month: "long",
            day: "2-digit",
          })}
          , {new Date().getFullYear()}
        </div>
      </div>
    </div>
    <div className="task-container">
      <div id="completed-task-counter">
        {props.toDos.length}{" "}
        {props.toDos.length === 1 ? "Completed Task" : "Completed Tasks"}
      </div>
      <div className="status-container">
      <button id="allButton" onClick={props.showAllTasks}>
            All
          </button>
        <button className="activeButton" onClick={props.showActive}>
          Active
        </button>
        <button className="doneButton" onClick={props.showDone}>
          Done
        </button>
      </div>
    </div>
    <hr />

    const visibleTodos = useMemo(
    () =>
      toDos.filter((toDo) => {
        if (filterTodosCompleted === null) {
          return true;
        }
        return filterTodosCompleted === toDo.checked;
      }),
    [filterTodosCompleted, toDos]
  );

    {props.visibleTodos.map((toDoItem: ToDo) => (
        <ToDoItem
          onDeleteToDo={function () {
            const updatedToDos = props.toDos.filter((x) => x !== toDoItem);
            props.setToDos(updatedToDos);

          }}
         
          onUpdateTodo={function (updates: any) {
            const updatedToDos = props.toDos.map((x) =>
              x === toDoItem ? ({ ...x, ...updates } as any) : x
            );
            console.log(updates);
            props.setToDos(updatedToDos);
          }}
          toDo={toDoItem}
        />
      ))}
    </div>
  );

ToDoItem.tsx

export function ToDoItem(props: {
  toDo: ToDo;
  onDeleteToDo: any;
  onUpdateTodo: any;
}) {
  const handleOptionsChange = (event: any) => {
    const selectBox = event.target;
    const newValue = selectBox.value;
    const newPriority = parseInt(newValue);
  
    props.onUpdateTodo({ priority: newPriority })
  };
  const checkBoxCheck = (event: any) => {
    const checkBox = event.currentTarget.checked;
    const newCheckBoxValue = checkBox;

    props.onUpdateTodo({ checked: newCheckBoxValue })
    console.log(newCheckBoxValue)
  };
  const handleDateChange =(event: any) => {
    const newDate = event.target.value;

    props.onUpdateTodo({ duedate: newDate })

    console.log(newDate)
  }

  if (!props.toDo) {
    return <p>Missing To Do</p>;
  }

  return (
    <div
      className="to-do-item"
      data-priority={props.toDo.priority}
      id="to-do-item"
    >
      <div className="checkbox-title-container">
        <div className="check-title-div">
          <div>
            <input
              type="checkbox"
              id="checkbox"
              onChange={checkBoxCheck}
              checked={props.toDo.checked}
            />
          </div>

          <h2 className="to-do-title">{props.toDo.title}</h2>
        </div>
        <div id="delete-div">
          <select
            name="Priority"
            className="select-field"
            value={props.toDo.priority}
            onChange={handleOptionsChange}
          >
            <option value="1">Important</option>
            <option value="2">Normal</option>
          </select>
          <button id="delete" onClick={props.onDeleteToDo}>
            Delete
          </button>
        </div>
        <span className="to-do-date-container">
        <input name="Date" type="date" className="to-do-date-input" value={props.toDo.duedate
            ? new Date(props.toDo.duedate).toISOString().split('T')[0]
            : undefined} onChange={handleDateChange}/>
         
        </span>
        <div className="description-box">
          <span className="description">{props.toDo.description}</span>
        </div>
      </div>
      <br />
    </div>
  );
}

I am unsure if I am passing the wrong props into DoneTasks? Before I refactored my code, my ShowDone() function worked fine, for some reason the conditions within the showDone function are not being called and I am getting a duplicate of my App.tsx file when it should be returning my ToDoItems that are checked.

How to normalize float values in the html table

I have a table in my html file:

<table class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th>timestamp</th>
      <th>cid1</th>
      <th>cid2</th>
      <th>cid3</th>
      <th>cid4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>2023-04-08 15:39:21</td>
      <td>1.0</td>
      <td>55.560000</td>
      <td>5.123143e+06</td>
    </tr>
    <tr>
      <td>2023-04-08 15:39:21</td>
      <td>1.0</td>
      <td>27913.540000</td>
      <td>4.653931e+04</td>
    </tr>
  </tbody>
</table>

As we can see there is many float values in cells with exponential form or with many zero in the end. I write a calc:

<form onsubmit="return false;"oninput="document.getElementById('rez_float').innerHTML= 
parseFloat(document.getElementById('expo').value).toFixed(20).replace(/.?0+$/,'')">
<input id="expo" value="Paste exponential" onfocus="if (this.value === 'Paste exponential') this.value=''">  
<br>float = <output id="rez_float"></output>
</form>

This calc return me 2572962000 if I input 2.572962e+09.
But how I can replace all strange values in the selected columns? My table have 9 columns in real, not 4 only, and 5 columns is the float.

But more my method return strange values in the case when I input 1852.100000. It return 1852.09999999999990905053 but I want 1852.1

How to normalize all float values in the selected columns (for example cid3 and cid4)?

Need to have a search filter option with marker clusters on Leaflet

I am using csv files to create marker cluster groups. I am trying to allow users the option to search for a specific species and filter the map to display that species’ marker clusters. Because of the way that my marker cluster groups are set up I cannot get the search bar to read the csv files to find the column scientific_name which would allow users to search.

I’m new to using Javascript and have been having trouble searching for leaflet functions using csv files. I’ve tried a different way to create the search bar but it didn’t work. I need the variable bullataMarkers to have access to the csv data.

It would also be helpful if there was a way to create a condensed chunk of code for the marker cluster groups so that I can eventually add multiple csv files without having to create a new marker cluster group for each one.

// Marker cluster group for Orientallactaga balikunica

var balikunicaMarkers = L.markerClusterGroup();

$.get('Species/Orientallactaga_balikunica.csv', function (csvString) {

  var data = Papa.parse(csvString, { header: true, dynamicTyping: true }).data;
  for (var i in data) {
    var row = data[i];
    var Orientallactaga_balikunicaMarker = L.circleMarker([row.latitude, row.longitude], {
      opacity: 1,
      radius: 3,
      color: "#ff1100",
      fillColor: "#ff1100",
      fillOpacity: 1,
    }).bindPopup(row.scientific_name + "<br>" + row.MSB_mammal_number + "<br>" + row.Date);


    balikunicaMarkers.addLayer(Orientallactaga_balikunicaMarker);
  }
});
map.addLayer(balikunicaMarkers)

// Marker cluster group for Orientallactaga bullata

var bullataMarkers = L.markerClusterGroup();

$.get('Species/Orientallactaga_bullata.csv', function (csvString) {

  var data = Papa.parse(csvString, { header: true, dynamicTyping: true }).data;
  for (var i in data) {
    var row = data[i];
    var Orientallactaga_bullataMarker = L.circleMarker([row.latitude, row.longitude], {
      opacity: 1,
      radius: 3,
      color: "#FFFFFF",
      fillColor: "#FFFFFF",
      fillOpacity: 1,
    }).bindPopup(row.scientific_name + "<br>" + row.MSB_mammal_number + "<br>" + row.Date);


    bullataMarkers.addLayer(Orientallactaga_bullataMarker);
  }
});
map.addLayer(bullataMarkers)



//Search option



/*


function search() {
  var search =$('#search').val().toLowerCase();

  Orientallactaga_bullataMarker.setFilter(showSpecies);

  function showSpecies(row) {
    return row.scientific_name
    .toLowerCase()
    .indexOf(search) !== -1;
  }
}
*/


$(document).on('keyup', '#search', function () {
  var userInput = this.value;
  bullataMarkers.eachLayer(function (layer) {
    console.log(layer)

    if (layer.rows.scientific_name.indexOf(userInput) > -1) {
      layer.addTo(map);
    } else {
      map.removeLayer(layer);
    }
  }
  )
})

break text at line breaks

basically, i’m making a discord music bot, and i made a lyrics command for it:

const { lyricsExtractor } = require('@discord-player/extractor');
const lyricsFinder = lyricsExtractor();
const result = await lyricsFinder.search(track.title);
const lyrics = [];
for (let i = 0; i < result.lyrics.length; i += 2000) {
    lyrics.push(result.lyrics.substring(i, i + 2000));
}

it splits the lyrics at every 2000 characters (it’s the maximum number of characters per message), but there is a problem: it’s spliting the lyrics in the middle of the line. how could i make it split the lyrics only at line breaks? (sorry for my bad english)

i tried this, but it didn’t work:

for (let i = 0; i < result.lyrics.length; i += result.lyrics.lastIndexOf('n', i + 2000) !== -1 ? result.lyrics.lastIndexOf('n', i + 2000) % 2000 : 2000) {
    lyrics.push(result.lyrics.substring(i, result.lyrics.lastIndexOf('n', i + 2000) !== -1 ? result.lyrics.lastIndexOf('n', i + 2000) : i + 2000));
}

how can I bypass a single quote to inject javascript code

how can I bypass a single quote filter `the web application escape my single quote


  (function(i,s,o,g,r,a,m){i['ProfitWellObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m);
  })(window,document,'script','https://dna8twue3dlxq.cloudfront.net/js/profitwell.js','profitwell');
  profitwell('auth_token', 'd95d82b71e0622345678954378');
  profitwell('user_email', '[email protected]&#39;);alert(document.cookie);//');

please help me to solve this.

Unable to add products to corresponding categories/subcategories using WooCommerce API

`Hi, so I have some categories/subcategories(even multiple nested subcategories) added by Js to a woocommerce site. The issue is, that I try to assign the products (they have a category_path array of objects, including the id,name,url – for each product ) to it’s corresponding category/subcategory when I try to post them, but the only thing that matches between them, is the name. I tried to assign the name only as I pass the categories property, but an ID is needed inside the post of the products, or else it doesnt save the products to a category, just add them uncategorized. Snippet of my code:

P.S: I know Im receiving back an array of names when I loop over the detailsData, and I have tried many ways, but I got stuck.`

const WooCommerce = new WooCommerceAPI({
  url: "https://X.X/",
  consumerKey: "ck_X",
  consumerSecret: "cs_X0",
  wpAPI: true,
  version: "wc/v3",
});

await createCategories(WooCommerce);

for (let i = 0; i < searchResults.products.length; i++) {
  const product = searchResults.products[i];
  const detailsData = await details(apiKey, product.id);

  const sections = detailsData.category_path;

  const productData = {
    name: product.title,
    type: "simple",
    categories: [
      {
        name: sections.name, 

      },
    ],
  };
  await WooCommerce.post("products", productData);
}

the name from the category_path is amtching the category/sbcategories name
Im expecting to achieve the products in the cateogries they should be based on the matching name.

How to export input data from website to excel

I have a website with a table with several inputs on. After I click a button a function is called and it makes some calculations I defined. What i wanted, is to export not only those input values but also the result from those calculations into an excel spreadsheet that I previously created, something like a template that it would only have to fill those specific cells.

I don’t know if it helps but here is the function that does the calculations:

function CalculateMedia(){
    // Defining every var to retrieve the values from inputs
    // Média de cada disciplina por ano, Provas de Ingresso, Peso PI e Peso Média
    let pt10 = document.getElementById("pt_10").value;
    let pt11 = document.getElementById("pt_11").value;
    let pt12 = document.getElementById("pt_12").value;

    let le10 = document.getElementById("le_10").value;
    let le11 = document.getElementById("le_11").value;

    let fil10 = document.getElementById("fil_10").value;
    let fil11 = document.getElementById("fil_11").value;

    let trienal10 = document.getElementById("trienal_10").value;
    let trienal11 = document.getElementById("trienal_11").value;
    let trienal12 = document.getElementById("trienal_12").value;

    let bienali10 = document.getElementById("bienal_i_10").value;
    let bienali11 = document.getElementById("bienal_i_11").value;

    let bienalii10 = document.getElementById("bienal_ii_10").value;
    let bienalii11 = document.getElementById("bienal_ii_11").value;

    let edf10 = document.getElementById("edf_10").value;
    let edf11 = document.getElementById("edf_11").value;
    let edf12 = document.getElementById("edf_12").value;

    let anuali = document.getElementById("anual_i").value;

    let anualii = document.getElementById("anual_ii").value;

    let Pi1 = document.getElementById("pi_pt").value;
    let Pi2 = document.getElementById("pi_le").value;
    let Pi3 = document.getElementById("pi_fil").value;
    let Pi4 = document.getElementById("pi_trienal").value;
    let Pi5 = document.getElementById("pi_bienal_i").value;
    let Pi6 = document.getElementById("pi_bienal_ii").value;

    let PPI = document.getElementById("peso_pi").value;


    //Média Final de cada disciplina
    let pt_final = (parseFloat(pt10) + parseFloat(pt11) + parseFloat(pt12)) / 3;
    let le_final = (parseFloat(le10) + parseFloat(le11)) / 2;
    let fil_final = (parseFloat(fil10) + parseFloat(fil11)) / 2;
    let trienal_final = (parseFloat(trienal10) + parseFloat(trienal11) + parseFloat(trienal12)) / 3;
    let bienal_i_final = (parseFloat(bienali10) + parseFloat(bienali11)) / 2;
    let bienal_ii_final = (parseFloat(bienalii10) + parseFloat(bienalii11)) / 2;
    let edf_final = (parseFloat(edf10) + parseFloat(edf11) + parseFloat(edf12)) / 3;
    let anual_i_final = parseFloat(anuali);
    let anual_ii_final = parseFloat(anualii);

    let PiPt = (parseFloat(Pi1)) / 10;
    let PiLe = (parseFloat(Pi2)) / 10;
    let PiFil = (parseFloat(Pi3)) / 10;
    let PiTrienal = (parseFloat(Pi4)) / 10;
    let PiBienali = (parseFloat(Pi5)) / 10;
    let PiBienalii = (parseFloat(Pi6)) / 10;

    let PesoProvasIngresso = (parseFloat(PPI)) / 100;
    let PesoMediaFinal = 1 - PesoProvasIngresso;

    let MediaFinalSecundario = ((pt_final + le_final + fil_final + trienal_final + bienal_i_final + bienal_ii_final + edf_final + anual_i_final + anual_ii_final) / 9).toFixed(3);

    //This part of the code puts the PI into an array and only returns the not NaN after that it calculates the average
    let piArray = [PiPt, PiLe, PiFil, PiTrienal, PiBienali, PiBienalii];
    let validPiArray = piArray.filter(function(value) {
        return !isNaN(value);
    });

    let MediaProvasIngresso = validPiArray.length > 0 ? validPiArray.reduce(function(acc, value) {
        return acc + value;
    }, 0) / validPiArray.length : 0;

    
    let MediaFinalAcessoES = ((MediaFinalSecundario * PesoMediaFinal) + (MediaProvasIngresso * PesoProvasIngresso)).toFixed(3);

    }
}