JavaScript – counting clicks on array values while presenting them in a nested loop

I am trying to extend some sample code I found in this LogRocket blog article. The code is for a to-do app using localStorage. I want to extend it in the following way:

First, let me explain what I do on paper when I’m trying to decide between choices. Say I have a list of 5 options, maybe places to volunteer for work. I look at the first and second choices and I put a checkmark by the one I prefer. I then compare the first and third choices and put a checkmark by the one I prefer. I then do the first and fourth and first and fifth. Then, I move down to the second choice and compare the second and third, then the second and fourth, then the second and fifth. Then it’s the third and fourth and third and fifth, then finally the fourth and fifth. When I’m done I have compared all choices against each other, and the items are ranked from 4 checkmarks down to 0 checkmarks.

This may sound goofy to you, but it works for me. And I want to be able to do it as an extension of the LogRocket code. Regardless of whether it’s the best way to prioritize, I just want to know how to implement this particular way of coding.

So below the list of tasks populated by the user is a Prioritize button. Below that I have two empty divs with plus icons next to them. In the code I have an empty Counter array. When the user clicks the Prioritize button the code creates the same number of values in the Counter array as there are to do tasks. Each of those values are set to 0. Next I have a for loop with another for loop nested in that. The for loops are for displaying the tasks to be compared. What should happen when the button is clicked is that the screen displays in the divs the first and second tasks. When the user clicks either of the plus icons next to one of the divs, the value in the counter array at either the first or second index is incremented by 1. Then the second task disappears from the second div and the third task appears, and upon a click the value at either the first or third index of the Counter array is incremented, etc. Once the inner for loop has displayed all other tasks besides the first in the second div, the first task disappears from the first div and the second task appears there, with the remaining tasks looping through in the second div. You can see where it should go from there.

In my current code I have event listeners in the for loops to try to capture the clicks, but the for loop is not waiting for those clicks. Instead, the for loops run completely through so that on the screen I am only seeing the second to last task in the first div and the last task in the second div. I also have console logs to show the number of clicks. To test this out I put in 5 tasks. The click event is currently on the divs themselves. When the screen displayed just the 4th and 5th tasks and I clicked on the 4th task, the code said items 1 through 4 (indexes 0-3) were now 1, and when I clicked the 5th task, it said items 1 through 4 were equal to 2. So instead of incrementing the value at the index of the task that was clicked, it incremented the first four values simultaneously, plus when the fifth value was clicked, it incremented the others but not the fifth itself.

At first I thought the issue might be one of how to pause a for loop until a click occurs, but now I think my whole approach may be wrong. Here is the code at issue:

The HTML (from within the body element):

<!-- LogRocket code -->
<div class="container">
    <div class="to-do-app">
        <h2>To-do App</h2>
        <br>
        <input type="text" id="item" placeholder="Enter item...">
        <br><br>
        <button onclick="add()">Add Item <i class="fa-solid fa-plus"></i></button>
        <button onclick="del()">Clear all <i class="fa-solid fa-ban"></i></button>
    </div>
    <ul class="to-do-list"></ul>
<!-- end of LogRocket code -->
<!-- my code -->
    <button onclick="prioritize()">Prioritize</button>
    <div id="task1"><i class="fa-solid fa-circle-plus"></i></div>
    <div id="task2"><i class="fa-solid fa-circle-plus"></i></div>
</div>
<script src="./script.js"></script>

The CSS:

/* all LogRocket code */
@import url("https://fonts.googleapis.com/css2?family=Asap&display=swap");
* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}
body {
    width: 100%;
    height: 100vh;
    background-color: #e0d6e9;
    font-family: "Asap", sans-serif;
}
.container {
    max-width: 405px;
    margin: 137px auto;
    padding: 20px;
    display: flex;
    flex-direction: column;
}
.to-do-app {
    width: 100%;
    padding: 20px;
    border-radius: 5px;
    background-color: whitesmoke;
    border: 1px solid #d3d3d3;
}
.to-do-app h2 {
    padding: 10px;
}
.to-do-app input {
    width: 250px;
    padding: 5px;
    border-radius: 5px;
    border: 1px solid #d3d3d3;
}
.to-do-app button {
    width: fit-content;
    padding: 5px;
    cursor: pointer;
    border: 1px solid #d3d3d3;
    border-radius: 5px;
    background-color: whitesmoke;
}
.to-do-app button:hover {
    background-color: rgba(0, 0, 0, 0.1);
}
li {
    font-size: 1.5rem;
}
.to-do-list {
    margin-top: 20px;
    margin-right: 5px;
    padding: 0 20px 10px 25px;
    display: flex;
    flex-direction: column;
    gap: 15px;
    list-style: none;
}
.to-do-list li {
    font-size: small;
    background-color: whitesmoke;
    padding: 20px;
}

JavaScript:

// mostly LogRocket code except for counter declaration
const ul = document.querySelector('ul');
const input = document.getElementById('item');
let itemsArray = localStorage.getItem('items') ? JSON.parse(localStorage.getItem('items')) : [];
let counter = [];

itemsArray.forEach(addTask);
function addTask(text) {
    const li = document.createElement('li');
    li.textContent = text;
    ul.appendChild(li);

}
function add() {
    itemsArray.push(input.value);
    localStorage.setItem('items', JSON.stringify(itemsArray));
    addTask(input.value);
    input.value = '';
}

function del() {
    localStorage.clear();
    ul.innerHTML = '';
    itemsArray = [];
}
// end of LogRocket code and beginning of my code
function prioritize() {
    let task1 = document.getElementById("task1");
    let task2 = document.getElementById("task2");
    let task1span = task1.appendChild(document.createElement("span"));
    let task2span = task2.appendChild(document.createElement("span"));
    for (let i = 0; i < itemsArray.length; i++) {
        counter[i] = 0;
        console.log('Item ' + (i + 1) + ' = ' + counter[i]);
    }
    for (let j = 0; j < itemsArray.length-1; j++) {
        task1span.textContent = ``;
        task1span.textContent = `${itemsArray[j]}`;
        task1span.addEventListener("click", function () {
            counter[j] += 1; 
            console.log('Item ' + (j + 1) + ' = ' + counter[j]);
        });

        for (let k = 0; k < itemsArray.length; k++) {
            task2.textContent = ``;
            task2.textContent = `${itemsArray[k]}`;
            task2span.addEventListener("click", function () {
                counter[k] += 1;
                console.log('Item ' + (k + 1) + ' = ' + counter[k]);
            });
        }
    }
    console.log('Final tally');
    for (let l = 0; l < itemsArray.length; l++) {
        console.log(`Item ${l + 1} = ${counter[l]}`);
    }
}

Any help is appreciated.

displaying random questions at onces using react

i am creating a quiz app which has an array that includes five questions but i want the five questions to display randomly but all the 5 questions at the same time

const randomQuestion = (array) => {
    let random = array[Math.floor(Math.random() * array.length)]
    return random
}
const [current, setCurrent] = useState(() => randomQuestion(questions));

discord.js-selfbot-v13 Button Click

Maybe I will ask a very simple question for most of you, which I could not find the answer to because the documentation was also explained incompletely. Is it possible for you to post an example of the button click function?

I could not see a place where I can enter information such as server id, channel id, message id. How can I get this button working?

Only examples can be given for me

Ejs scriplet function not working for forloop

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>To Do List</title>
</head>
<body>

<h1><%=KindOfDay%> </h1>
<ul>
<%for(var i =0 ;i <newitems.lenght;i++){%>
    <li><%=newitems[i]%></li>
<%}%>
</ul>
<form action="/" method="post">
    <input type="text" placeholder="What do you want to do" name = "newitem">
    <button type="submit">Add</button>
</form>

</body>
</html>

This the what i did,My aim was to make a to do list site but the issue is that the for loop js that i added here is not working properly

This is my app.js

const express = require("express");
const app = express();
const bodyParser = require("express");
var NewItems =["Buy food","Cook food","Eat the food"];
app.use(bodyParser.urlencoded({extended:true}));
app.set('view engine', 'ejs');



app.get("/",function(req,res){
    var today = new Date();
    var options = {
        weekday:"long",
        day:"numeric",
        month:"long"
    }
    var day = today.toLocaleDateString("en-US",options);
    res.render("list", {KindOfDay: day,newitems: NewItems});

});


app.post("/",function(req,res){
    NewItems.push(req.body.newitem);
    res.redirect("/");
})







app.listen(3000,function(){
    console.log("Server is running on port 3000");
});

According to what i have coded here.I should get an to do list page with the pre-existing list items that i have added,but when i load up the site this is how my site looks.enter image description here

I tried updating vs code
Installed ejs npm again
When i just use brute force method whitout the for loop everything works perfectly

Can not achieve sync between scrollview nav buttons and react native swiper tabs

Tried many ways, including using swiperRef, but I can not get sync between nav buttons and swiping content. Separately features work properly, but when I try to swipe after pressing tab button and in reverse, I got inadeqate results. I think the problem is that I can not handle swiper index properly, I’d be happy to get some good advice on this.

import React, { useState, useEffect, useRef } from 'react';
import { Text, StyleSheet, ScrollView, TouchableOpacity, BackHandler, View } from 'react-native';
import Swiper from 'react-native-swiper';
import InfoCard from './InfoCard';

const DetailsOverlay = ({ onClose }) => {
  const scrollViewRef = useRef(null);

  const handleCloseBtnPress = () => {
    onClose();
  };

  useEffect(() => {
    const backAction = () => {
      handleCloseBtnPress();
      return true;
    };

    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      backAction
    );

    return () => backHandler.remove();
  }, []);

  const [activeTab, setActiveTab] = useState('0');

  const handleTabPress = (tab) => {
    setActiveTab(tab);
    scrollToActiveTab(tab);
  };

  const scrollToActiveTab = (tab) => {
    const tabWidth = 100; // Adjust this value based on your tab width
    const offsetX = tabWidth * (parseInt(tab));
    scrollViewRef.current.scrollTo({ x: offsetX, animated: true });
  };

  const handleSwiperIndexChanged = (index) => {
    setActiveTab((index).toString());
    scrollToActiveTab((index).toString());
  };

  const tabContent = [
    {
      id: '0',
      title: 'Марии Ульяновой',
      cards: [
        { id: 'RV', row: '9' },
        { id: 'MG', row: '10' },
        { id: 'EF', row: '11' },
        { id: 'CT', row: '12' },
        { id: 'LS', row: '13' },
        { id: 'RT', row: '14' },
        { id: 'SR', row: '15' },
      ],
    },
    {
      id: '1',
      title: 'Троицк',
      cards: [
        { id: 'RV', row: '17' },
        { id: 'MG', row: '18' },
        { id: 'EF', row: '19' },
        { id: 'CT', row: '20' },
        { id: 'LS', row: '21' },
        { id: 'RT', row: '22' },
        { id: 'SR', row: '23' },
      ],
    },
    {
      id: '2',
      title: 'Академика Анохина',
      cards: [
        { id: 'RV', row: '25' },
        { id: 'MG', row: '26' },
        { id: 'EF', row: '27' },
        { id: 'CT', row: '28' },
        { id: 'LS', row: '29' },
        { id: 'RT', row: '30' },
      ],
    },
    {
      id: '3',
      title: 'Сумской проезд',
      cards: [
        { id: 'RV', row: '32' },
        { id: 'MG', row: '33' },
        { id: 'EF', row: '34' },
        { id: 'CT', row: '35' },
        { id: 'LS', row: '36' },
        { id: 'RT', row: '37' },
      ],
    },
    {
      id: '4',
      title: 'Обручева',
      cards: [
        { id: 'RV', row: '39' },
        { id: 'MG', row: '40' },
        { id: 'EF', row: '41' },
        { id: 'CT', row: '42' },
        { id: 'LS', row: '43' },
        { id: 'RT', row: '44' },
      ],
    },
    {
      id: '5',
      title: 'Ясная',
      cards: [
        { id: 'RV', row: '46' },
        { id: 'MG', row: '47' },
        { id: 'EF', row: '48' },
        { id: 'CT', row: '49' },
        { id: 'LS', row: '50' },
        { id: 'RT', row: '51' },
        { id: 'SR', row: '52' },
      ],
    },
    {
      id: '6',
      title: 'Офис',
      cards: [
        { id: 'CT', row: '54' },
        { id: 'SR', row: '55' },
      ],
    }

  return (
    <View style={styles.overlayScreen}>
      <View style={styles.tabContainer}>
        <ScrollView
          contentContainerStyle={styles.tabContentContainer}
          horizontal
          showsHorizontalScrollIndicator={false}
          ref={scrollViewRef}
        >
          {tabContent.map((tab) => (
            <TouchableOpacity
              key={tab.id}
              style={[styles.tab, activeTab === tab.id && styles.activeTab]}
              onPress={() => handleTabPress(tab.id)}
            >
              <Text style={[styles.tabText, activeTab === tab.id && styles.tabTextActive]}>
                {tab.title}
              </Text>
            </TouchableOpacity>
          ))}
        </ScrollView>
      </View>

      <Swiper
        loop={false}
        showsPagination={false}
        index={parseInt(activeTab)}
        onIndexChanged={handleSwiperIndexChanged}
      >
        {tabContent.map((tab) => (
          <ScrollView
            key={tab.id}
            contentContainerStyle={styles.overlayContent}
            showsVerticalScrollIndicator={false}
          >
            <Text key="header" style={styles.header}>
              {tab.title}
            </Text>
            {tab.cards.map((card) => (
              <InfoCard key={card.id} row={card.row} />
            ))}
          </ScrollView>
        ))}
      </Swiper>
    </View>
  );
};

Method that I tried, it was close, but ScrollView starts to set random active tabs

import React, { useState, useEffect, useRef } from 'react';
import { Text, StyleSheet, ScrollView, TouchableOpacity, BackHandler, View } from 'react-native';
import Swiper from 'react-native-swiper';
import InfoCard from './InfoCard';

const DetailsOverlay = ({ onClose }) => {
  const scrollViewRef = useRef(null);
  const swiperRef = useRef(null);

  const handleCloseBtnPress = () => {
    onClose();
  };

  useEffect(() => {
    const backAction = () => {
      handleCloseBtnPress();
      return true;
    };

    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      backAction
    );

    return () => backHandler.remove();
  }, []);

  const [activeTab, setActiveTab] = useState('0');
  const [swipeIndex, setSwipeIndex] = useState(0);

  const handleTabPress = (tab) => {
    setActiveTab(tab);
    const index = parseInt(tab);
    setSwipeIndex(index);
    swiperRef.current.scrollTo(index, true);
  };

.......

 return (
    <View style={styles.overlayScreen}>
      <View style={styles.tabContainer}>
        <ScrollView
          contentContainerStyle={styles.tabContentContainer}
          horizontal
          showsHorizontalScrollIndicator={false}
          ref={scrollViewRef}
        >
          {tabContent.map((tab) => (
            <TouchableOpacity
              key={tab.id}
              style={[styles.tab, activeTab === tab.id && styles.activeTab]}
              onPress={() => handleTabPress(tab.id)}
            >
              <Text style={[styles.tabText, activeTab === tab.id && styles.tabTextActive]}>
                {tab.title}
              </Text>
            </TouchableOpacity>
          ))}
        </ScrollView>
      </View>

      <Swiper
        loop={false}
        showsPagination={false}
        index={swipeIndex}
        onIndexChanged={setSwipeIndex}
        ref={swiperRef}
      >
        {tabContent.map((tab) => (
          <ScrollView
            key={tab.id}
            contentContainerStyle={styles.overlayContent}
            showsVerticalScrollIndicator={false}
          >
            <Text key="header" style={styles.header}>
              {tab.title}
            </Text>
            {tab.cards.map((card) => (
              <InfoCard key={card.id} row={card.row} />
            ))}
          </ScrollView>
        ))}
      </Swiper>
    </View>
  );
};

How to use a trained yolov8 object box detection model directly in tensorflow js in pure javascript?

I’m currently trying to use a trained yolov8 object box detection model (for 13 ish classes) from ultralytics, directly in tensorflow js in pure javascript.
I don’t want to use roboflow js, onnx etc for running it ; or any framework like node-js implementation etc to serve it..
I want to have a fully working yolov8n model detecting custom objects in images/videos/webcam direclty on browser using only tensorflow js.
In the purpose of having something quite usefull (more than 10fps in webcam), i know that i have to use a quantized model for it.
So my second question : What’s also the code needed to use a custom yolov8n quantized model ?
I looked pretty much at hundreds of links, topics etc on the subject but i haven’t found any for this particular use case.
I’m also open to someone that has the full solution for an ssd-mobilenet custom training/deploying solution in pure tensorflow js for object detection with boxes.

You would be very nice and serving a lot of people i think if you share the full solution with codes on how to do it here !

Ps : I know that it’s possible but any examples I’have found yet are either using node-js, or are for object classification etc… I haven’t found any for my specific purpose : pure smooth tjfs yolov8 object detection with boxes.

how to write complex queries with supabase sdk?

i have this postgresql query, not sure i can translate it to a supabase query by using the standard supabase sdk.
please ignore the fact that some parts of it are in hebrew,
but basically the goal of this query is to retrieve a new table with some predefined options to filter on the FE, and the count of each filter

when i run it via sql editor in supabase dashboard i get something like this:

category name value
difficulty mental 25
difficulty financial 153
diagnosis psychodidactic 12
diagnosis didactic 87
WITH 
  flat_filters AS (
    SELECT
      students.class AS class,
      students.gender AS gender,
      students.diagnosis AS diagnosis,
      students.health AS health,
      difficulties.type AS difficulty_type,
      COUNT(DISTINCT(students.id)) AS cnt
    FROM
      students
    LEFT JOIN
      difficulties ON students.id = difficulties.student_id
    GROUP BY
      class, gender, diagnosis, health, difficulties.type
  ),
  filters_count AS (
    SELECT
      'כיתה' AS category,
      class::varchar AS name,
      SUM(cnt) AS value
    FROM
      flat_filters
    GROUP BY
      name
    UNION ALL
    SELECT
      'מין' AS category,
      gender::varchar AS name,
      SUM(cnt) AS value
    FROM
      flat_filters
    GROUP BY
      name
    UNION ALL
    SELECT
      'אבחון' AS category,
      diagnosis::varchar AS name,
      SUM(cnt) AS value
    FROM
      flat_filters
    GROUP BY
      name
    UNION ALL
    SELECT
      'קושי' AS category,
      difficulty_type::varchar AS name,
      SUM(cnt) AS value
    FROM
      flat_filters
    GROUP BY
      name
    UNION ALL
    SELECT
      'תכנית' AS category,
      'סודקות' AS name,
      COUNT(*) AS value
    FROM
      programs
    WHERE
      sodkot = true
    GROUP BY
      sodkot
    UNION ALL
    SELECT
      'תכנית' AS category,
      'ממצים' AS name,
      COUNT(*) AS value
    FROM
      programs
    WHERE
      mamazim = true
    GROUP BY
      mamazim
    UNION ALL
    SELECT
      'תכנית' AS category,
      'ממריאים' AS name,
      COUNT(*) AS value
    FROM
      programs
    WHERE
      mamriim = true
    GROUP BY
      mamriim
    UNION ALL
    SELECT
      'תכנית' AS category,
      'עמיתים' AS name,
      COUNT(*) AS value
    FROM
      programs
    WHERE
      amitim = true
    GROUP BY
      amitim
  )
SELECT
  *
FROM
  filters_count
WHERE
  name != ''
ORDER BY
  category, name ASC

as said earlier, tried running the query via dashboard. attached a table for example

how to upload image android to mysqli?

Here my code java android

i want save image to server.

private void createDokumentasi(){
    final String lat = editTextLatitude.getText().toString().trim();
    final String lon = editTextLongitude.getText().toString().trim();
    final String alamat = editTextAlamat.getText().toString().trim();
    final String kota = editTextKota.getText().toString().trim();
    final String keterangan = textInputKeterangan.getText().toString().trim();
    final String userID = editTextUserid.getText().toString().trim();

    progressDialog.setMessage("Lapor Dokumentasi...");
    progressDialog.show();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, 
    Constants.URL_DOKUMENTASI, response -> {
        progressDialog.dismiss();

        try {
            JSONObject jsonObject = new JSONObject(response);

            editTextLatitude.setText("");
            editTextLongitude.setText("");
            editTextAlamat.setText("");
            editTextKota.setText("");
            textInputKeterangan.setText("");

            textViewLatitude.setText("Latitude :");
            textViewLongitude.setText("Longitude :");
            textViewAlamat.setText("Alamat :");
            textViewKota.setText("Kota :");

            img.setImageResource(R.drawable.camera_dokumentasi);

            Toast.makeText(getApplicationContext(), jsonObject.getString("message"), 
            Toast.LENGTH_LONG).show();
            //startActivity(new Intent(getApplicationContext(), ProfileActivity.class));

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            progressDialog.hide();
            Toast.makeText(getApplicationContext(), error.toString(), 
            Toast.LENGTH_LONG).show();
            //Log.d("volleyError", "${volleyError.message}");
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> map = new HashMap<String, String>();

            map.put("upload", encodedimage);
            map.put("lat", lat);
            map.put("lon", lon);
            map.put("alamat", alamat);
            map.put("kota", kota);
            map.put("keterangan", keterangan);
            map.put("user_id", userID);
            return map;
        }
    };

    RequestHandler.getInstance(this).addToRequestQueue(stringRequest);
}

Operationdb.php

    function createDokumentasi($upload, $lat, $lon, $alamat, $kota,$keterangan,$user_id) 
    {
        if($this->isDokumentasiExist($nama_gambar)){

            return 0;
        }else{
                        
            $nama_gambar="IMG".rand().".jpg";               
            file_put_contents("images/".$nama_gambar.base64_decode($upload));

            $stmt = $this->con->prepare("INSERT INTO `dokumentasi`(`id_dokumentasi`, 
            `nama_gambar`, `lat`, `lon`, `alamat`, `kota`, `keterangan`, `user_id`) 
             VALUES (NULL,?,?,?,?,?,?,?);");
            $stmt->bind_param("sssssss",$nama_gambar, $lat, $lon, $alamat,                $kota,$keterangan,$user_id);

            if($stmt->execute()){
                return 1;
            }else{
                return 2;
            }
        }

    }

my POST php

here my post

    <?php

    require_once '../includes/DbOperations.php';

    $response = array();

    if($_SERVER['REQUEST_METHOD']=='POST'){
        if(
            isset($_POST['upload']) and
            isset($_POST['lat']) and
            isset($_POST['lon']) and
            isset($_POST['alamat']) and
            isset($_POST['kota']) and
            isset($_POST['keterangan']) and
            isset($_POST['user_id']))
          {
            //operate the data

            $db = new DbOperations();

            $result = $db->createDokumentasi($_POST['upload'],
                                        $_POST['lat'],
                                        $_POST['lon'],
                                        $_POST['alamat'],
                                        $_POST['kota'],
                                        $_POST['keterangan'],
                                        $_POST['user_id']
                                    );
            if($result == 1){
                $response['error'] = false;
                $response['message']= "Dokumentasi berhasil Ditambahkan";
            }elseif($result == 2){
                $response['error'] = true;
                $response['message']= "Beberapa kesalahan terjadi silakan coba lagi";
            }elseif($result == 0){
                $response['error'] = true;
                $response['message']= "Sepertinya Dokumntasi sudah terdaftar, silahkan 
                Ambil Gambar lagi";
            }
            
        }else{
            $response['error'] =true;
            $response['message']= "Bidang yang wajib diisi tidak ada";
        }
    }else{
        $response['error'] = true;
        $response['message']= "Permintaan Tidak Valid";
    }

    echo json_encode($response);

error

What is wrong my code?

2023-07-03 03:09:33.702 17001-17001 System.err com.avdproduction.passipakiapp W org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
2023-07-03 03:09:33.702 17001-17001 System.err com.avdproduction.passipakiapp W at org.json.JSON.typeMismatch(JSON.java:112)
2023-07-03 03:09:33.702 17001-17001 System.err com.avdproduction.passipakiapp W at org.json.JSONObject.(JSONObject.java:169)
2023-07-03 03:09:33.702 17001-17001 System.err com.avdproduction.passipakiapp W at org.json.JSONObject.(JSONObject.java:182)
2023-07-03 03:09:33.702 17001-17001 System.err com.avdproduction.passipakiapp W at com.avdproduction.passipakiapp.LaporActivity.lambda$createDokumentasi$0$com-avdproduction-passipakiapp-LaporActivity(LaporActivity.java:170)
2023-07-03 03:09:33.702 17001-17001 System.err com.avdproduction.passipakiapp W at com.avdproduction.passipakiapp.LaporActivity$$ExternalSyntheticLambda0.onResponse(Unknown Source:4)
2023-07-03 03:09:33.702 17001-17001 System.err com.avdproduction.passipakiapp W at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
2023-07-03 03:09:33.702 17001-17001 System.err com.avdproduction.passipakiapp W at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
2023-07-03 03:09:33.702 17001-17001 System.err com.avdproduction.passipakiapp W at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
2023-07-03 03:09:33.702 17001-17001 System.err com.avdproduction.passipakiapp W at android.os.Handler.handleCallback(Handler.java:938)
2023-07-03 03:09:33.702 17001-17001 System.err com.avdproduction.passipakiapp W at android.os.Handler.dispatchMessage(Handler.java:99)
2023-07-03 03:09:33.702 17001-17001 System.err com.avdproduction.passipakiapp W at android.os.Looper.loop(Looper.java:246)
2023-07-03 03:09:33.702 17001-17001 System.err com.avdproduction.passipakiapp W at android.app.ActivityThread.main(ActivityThread.java:8550)
2023-07-03 03:09:33.703 17001-17001 System.err com.avdproduction.passipakiapp W at java.lang.reflect.Method.invoke(Native Method)
2023-07-03 03:09:33.703 17001-17001 System.err com.avdproduction.passipakiapp W at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
2023-07-03 03:09:33.703 17001-17001 System.err com.avdproduction.passipakiapp W at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)

Fetched data with key of type objects are undefined?

i try to learn a bit about fetching from APIs but have a hard time.
Can someone explain me, why the pokemon[‘sprites’][‘back_default’] is undefined,
but pokemon[‘name’] works just fine?

import React, { useState } from "react";

export default function Mybutton() {
    const [pokemon, setPokemon] = useState("");

    const getPokemon = () => {
      fetch("https://pokeapi.co/api/v2/pokemon/4/").then(
        (response) => response.json())
        .then((data) => {
          setPokemon(data);
        });
    };

    return (
      <div>
        <button onClick={getPokemon}>Get pOKIMON</button>
        {pokemon['name']}
        {pokemon.sprites[0].back_default}
      </div>
    );
  }
  

I tried to google the problem, but i dont know, what exactly i am looking for!

WebDriver throws Exception: TypeError: JSON.stringify is not a function

I am working on selenium automation using java. Selenium version used : 4.10.0

Though I see two tabs ( 1. parent tab main page and 2. is the child tab) but when I switch to child through below code I don`t see any kind of exception thrown. But when I perform any operations like click on any button in child window it throws an exception “TypeError: JSON.stringify is not a function”.

Below is the code snippet.

//Loop through until we find a new window handle

    for (String windowHandle : driver.getWindowHandles()) {
        
        if(!originalWindow.contentEquals(windowHandle)) {
            System.out.println("Child win : "+windowHandle);
            driver.switchTo().window(windowHandle);
            break;
        }
    }

driver.findElement(By.name(“aspnetForm”)).click();

Can somebody please advise me here why i should be getting this error “Exception in thread “main” org.openqa.selenium.WebDriverException: unknown error: Runtime.callFunctionOn threw exception: TypeError: JSON.stringify is not a function”

Consloe log below :

Child win : DEFC56C2E255CB00E7CF1C779B81E7EE
Exception in thread “main” org.openqa.selenium.WebDriverException: unknown error: Runtime.callFunctionOn threw exception: TypeError: JSON.stringify is not a function
at buildError (:323:18)
(Session info: chrome=114.0.5735.199)
Build info: version: ‘4.10.0’, revision: ‘c14d967899’
System info: os.name: ‘Windows 10’, os.arch: ‘amd64’, os.version: ‘10.0’, java.version: ‘11.0.18’
Driver info: org.openqa.selenium.chrome.ChromeDriver
Command: [748156ce82a3898c61c8bc461a5ecbbb, findElement {using=name, value=aspnetForm}]
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 114.0.5735.199, chrome: {chromedriverVersion: 114.0.5735.90 (386bc09e8f4f…, userDataDir: C:UsersbaluzAppDataLoca…}, goog:chromeOptions: {debuggerAddress: localhost:58574}, networkConnectionEnabled: false, pageLoadStrategy: normal, platformName: windows, proxy: Proxy(), se:cdp: ws://localhost:58574/devtoo…, se:cdpVersion: 114.0.5735.199, setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true, webauthn:extension:minPinLength: true, webauthn:extension:prf: true, webauthn:virtualAuthenticators: true}
Session ID: 748156ce82a3898c61c8bc461a5ecbbb
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:199)
at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:132)
at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:51)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:191)
at org.openqa.selenium.remote.service.DriverCommandExecutor.invokeExecute(DriverCommandExecutor.java:196)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:171)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:531)
at org.openqa.selenium.remote.ElementLocation$ElementFinder$2.findElement(ElementLocation.java:165)
at org.openqa.selenium.remote.ElementLocation.findElement(ElementLocation.java:66)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:350)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:344)
at com.basePage.EX3.main(EX3.java:91)

“Error: Could not establish connection. Receiving end does not exist” for Chrome Extension

I am trying to create a chrome extension that sends the DOM body from the active tab to some backend server, which will return some response which I will do later. However, I cannot figure out how send information via event listeners from the content-script to the service-worker. Heres the code I have now:
Service-Worker:

chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) {
  if (request.action === "submit") {
      console.log("submit stage 1")
      const response_tabs = sendMessageToActiveTab('sendDOM')
      console.log(response_tabs)
      const response_runtime = chrome.runtime.sendMessage({message: 'sendDOM', action: 'sendDOM'})
      console.log(response_runtime)


async function sendMessageToActiveTab(message) {
  const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
  const response = await chrome.tabs.sendMessage(tab.id, {message: message, action: 'sendDOM'});
  return response
}

Content-Script:

chrome.tabs.addListener(async function(request, sender, sendResponse) {
  if (request.action === "sendDOM") {
    const article = await document.querySelector("body");
    console.log("article: ", article);
    sendResponse(article);
    return article;
  }
});
chrome.runtime.onMessage.addListener(function(message, sender) {
  if (message.action === "sendDOM") {
    const article = await document.querySelector("body");
    console.log("article: ", article);
    sendResponse(article);
    return article;
  }
});

And manifest.json:

{
  "manifest_version": 3,
  "name": "Nuntia",
  "version": "1.0",
  "permissions": ["activeTab","tabs"],  
  "action": {
    "default_popup": "popup.html"
  },
  "background": {
    "service_worker": "service-worker.js"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content-script.js"]
    }
  ],
  "externally_connectable": {
    "matches": ["*://*.google.com/*"]
  },
  "host_permissions": [
    "http://*/*",
    "https://*/*"
  ]
}

Any advice on how to go about doing this or fixing my approach would be greatly appreciated!

So far I have tried different ways to make the two js files communicate with each other such as chrome.tabs and chrome.runtime. Both are returning this same error

How do i call a function from a module in another file in javascript

i have this .jsx code where i created a character using threejs.

import React, { useRef, useEffect } from "react";
import { useFrame, useThree } from "react-three-fiber";
import * as THREE from "three";

const Actor = () => {
  const meshRef = useRef();
  const { scene } = useThree();

  useEffect(() => {
    const geometry = new THREE.BoxGeometry(1, 1, 1);
    const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
    const mesh = new THREE.Mesh(geometry, material);
    mesh.rotateY(Math.PI);

    // Set initial properties and functions
    mesh.instructions = [];
    mesh.target = new THREE.Object3D().copy(mesh, false);
    mesh.targetRadiansOnY = 0;
    mesh.currentRadiansOnY = 0;
    mesh.mass = 0.1;
    mesh.velocity = new THREE.Vector3();
    mesh.angularVelocity = 0.015;
    mesh.topSpeed = 0.05;
    mesh.topAccelleration = 0.0015;
    mesh.accelleration = new THREE.Vector3();
    mesh.currentInstruction = null;
    mesh.gravityForce = new THREE.Vector3(0.0, -0.01, 0.0);

    // Add mesh to the scene
    scene.add(mesh);
    meshRef.current = mesh;

    return () => {
      // Clean up the mesh when the component unmounts
      scene.remove(mesh);
    };
  }, [scene]);

     // Update function to consume commands
    const consumeCommands = () => {
      const mesh = meshRef.current;
      if (mesh.currentInstruction) {
        let instruction = mesh.currentInstruction;
        let movementType = instruction["type"];
        let movementValue = instruction["value"];
        let dir = null;
        switch (movementType) {
          case "move_forward":
            dir = new THREE.Vector3().subVectors(mesh.target.position, mesh.position);
            dir.setLength(mesh.topAccelleration);
            mesh.applyForce(dir);
            mesh.applyForce(mesh.gravityForce);
            mesh.velocity.add(mesh.accelleration);
            mesh._limitVelocity(mesh.topSpeed);
            mesh.position.add(mesh.velocity);
            mesh._limitGravity();
            mesh.accelleration.multiplyScalar(0.0);
            break;
          case "jump_forward":
            dir = new THREE.Vector3().subVectors(mesh.target.position, mesh.position);
            let upForce = new THREE.Vector3(0, (0.012 * (dir.length() / movementValue)), 0);
            dir.setLength(mesh.topAccelleration);
            mesh.applyForce(dir);
            mesh.applyForce(upForce);
            mesh.applyForce(mesh.gravityForce);
            mesh.velocity.add(mesh.accelleration);
            mesh._limitVelocity(mesh.topSpeed);
            mesh.position.add(mesh.velocity);
            mesh._limitGravity();
            mesh.accelleration.multiplyScalar(0.0);
            break;
          case "turn":
            if (movementValue === "turnLeft") {
              mesh.rotateY(mesh.angularVelocity);
              mesh.currentRadiansOnY += mesh.angularVelocity;
            } else {
              mesh.rotateY(-mesh.angularVelocity);
              mesh.currentRadiansOnY += mesh.angularVelocity;
            }
            break;
          default:
            console.log("command not implemented");
            break;
        }
        if (mesh._targetReached(movementType)) {
          mesh._nextAnimation();
        }
      }
    };

    // Set the consumeCommands function as an update function
    useFrame(() => {
      consumeCommands();
    });

  return null; // We don't render anything for this component
};

export default Actor;

and i want to call the function “startConsume” in another .js file under the run code function here

import Actor from "./actor";

function globalFunction() {
  // Your function code here
  console.log("This is a global function.");
}

window.onload = function() {
  window.globalFunction = globalFunction;
};

// window.global = 'hhhhh'
// let instructions=['llll'];

// window.load_blockly = function(blockly) {
//   console.log('blockly here')
//     // init the game only after window.Blockly definition
// }

window.blockly_loaded = function(blockly) {

// init the game only after window.Blockly definition
window.Blockly = blockly;
defineActions();

};

window.run_code = function() {
  instructions=[];
  var code = window.Blockly.JavaScript.workspaceToCode(window.Blockly.mainWorkspace);
  eval(code);
  console.log(instructions)
  startConsume(instructions);
};



function defineActions(){
window.Blockly.JavaScript['actor_move_forward'] = function(block) {
    var dropdown_actor_move_forward_distance = block.getFieldValue('actor_move_forward_distance');
    var code = "instructions.push({type:'move_forward',value:"+dropdown_actor_move_forward_distance+"});";
    return code;
};

window.Blockly.JavaScript['actor_turn'] = function(block) {
    var direction = block.getFieldValue('actor_turn_direction');
    var code = "instructions.push({type:'turn',value:'"+direction+"'});";
    return code;
};

window.Blockly.JavaScript['actor_jump_forward'] = function(block) {
    var dropdown_actor_jump_forward_distance = block.getFieldValue('actor_jump_forward_distance');
    var code = "instructions.push({type:'jump_forward',value:"+dropdown_actor_jump_forward_distance+"});";
    return code;
};
}

But then i get the error “Uncaught SyntaxError: Cannot use import statement outside a module”

Can someone help me out with what is wrong?

How to test for object passed as …rest argument to a function

I am practicing using ...rest operator to pass arguments to functions. I have run into an issue that I’m unable to resolve for when passing an object to the function.

Here is the function:

function sum(...args){
  if (args.length === 1 && Array.isArray(args[0])) {
    args = args[0];
  }
  return args.reduce((a,b) => a + b);
}

console.log(sum([5,4,3,2,1])); // Returns 15
console.log(sum(5,4,3,2,1)); // Returns 15
console.log(sum({a:5,b:4,c:3,d:2,e:1})); // Returns {a:5,b:4,c:3,d:2,e:1}

I’m stuck at how to test for and handle the last use case.