How to fix this error (querySelector is used): Cannot read properties of undefined (reading ‘style’) at showSlides

I am unable to resolve this error; I’ve been “fighting” to solve it for two days.

This is the error:

215: Uncaught TypeError: Cannot read properties of undefined (reading ‘style’) at showSlides

enter image description here

var slideIndex = 1;


    var outerXmlhttp = new XMLHttpRequest();
    var url = "https://wjko8t4509.execute-api.us-east-2.amazonaws.com/books";
    outerXmlhttp.onreadystatechange = function () {
      var innerXmlhttp;
      if (this.readyState == 4 && this.status == 200) {
        var allbook = JSON.parse(this.responseText);
        for (var i = 0, len = allbook.Items.length; i < len; i++) {
          id = allbook.Items[i].id
          document.querySelector('.slideshow-container').innerHTML += `
          <div class="mySlides fade">
            <div class="numbertext">${i+1}/${allbook.Items.length}</div>
            <img id="img" src onerror="this.onerror=null; this.src=myFunction(id);" style="width:100%">
            <div class="text" id="title" onclick="myFunction(id)"></div>
          </div>`;
          document.querySelector('#punt').innerHTML += `
          <span class="dot" onclick=currentSlide(${i+1})></span>`;
          myFunction(id);
        }
      }
    };
    outerXmlhttp.open("GET", url, true);
    outerXmlhttp.send();

    showSlides(slideIndex);

    function plusSlides(n) {
      showSlides(slideIndex += n);
    }

    function currentSlide(n) {
      showSlides(slideIndex = n);
    }

    function showSlides(n) {
      var i;
      var slides = document.getElementsByClassName("mySlides fade");
      var dots = document.getElementsByClassName("dot");
      if (n > slides.length) { slideIndex = 1 }
      if (n < 1) { slideIndex = slides.length }
      for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";
      }
      for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" active", "");
      }
      slides[slideIndex - 1].style.display = "block";
      dots[slideIndex - 1].className += " active";
    }

    function myFunction(id) {
      var url1 = "https://wjko8t4509.execute-api.us-east-2.amazonaws.com/books/" + id;
      innerXmlhttp = new XMLHttpRequest();
      innerXmlhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
          var myArr = JSON.parse(this.responseText);
          document.getElementById("img").src = "book_img/" + myArr.Item.immagine;
          document.getElementById("title").innerHTML = `<a href="fragmentProva.html?id=${id}">${myArr.Item.titolo}</a>`;
        }
      };
      innerXmlhttp.open("GET", url1, true);
      innerXmlhttp.send();
    }
<div class="slideshow-container" id="slideshow">
    <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
    <a class="next" onclick="plusSlides(1)">&#10095;</a>
  </div>

  <br>

  <div id="punt" style="text-align:center">
  </div>

I would not like there to be some setup problem regarding the querySelector or the function call. I need your help, help me please!

Why filtering isn’t working in React and JS. Help me to find a mistake

Can not understand why filter is not working.
The function get an object. If there is the same object in the state, the function delete this object from the state. If not, add to the state.
The problem is that the object rewrites the state, but not add it to the state.

For example, object {a: 1, b: 2}

const [products, setProducts] = useState<any[]>([]);

const addObject = (data) => {
    const sameData = !!products.find((item) => item.id === data.id);
    const deleteData = products.filter((item) => item.id !== data.id);
    const newData = sameData ? deleteData : [...products, data]; 
    return setCheckedRoles(newData);
  };

As a result I get not [{a: 1, b: 2}, {a: 2, b: 4}, {a: 8, b: 3}];
but only one object that come to function [{a: 1, b: 2}]

Adding POM version number to an HTML page

I have a POM file that looks like this:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.capgemini.jira.plugin</groupId>
    <artifactId>security-service</artifactId>
    <version> ${POM_JIRAVERSION}-${BUILD_NUMBER}-SNAPSHOT</version>

I’ve got an HTML page where I want to display my POM version number, my version number is dynamic as you can see and changes with every build I make on Jenkins.

Bluetooth web control led stripe

Was using the Happylighting application on android and I try to make a simple web application to control the led color, but can’t figure how to do it, and witch ‘gatt’ I’ve to request, I’m really new to bluetooth thing.

function onRequestBluetoothDeviceButtonClick() {
    navigator.bluetooth.requestDevice({
        filters: [{name:"QHM-0A0B"}],
    })
    .then(device => {
        // device.gatt.connect()
        console.log(device)
    }).then(server =>{
        console.log(server)
    })
    .catch(error => {
        console.log('Argh! ' + error);
    });
  }

I’ve seen this on api documention, but can’t figure witch service I’ need to request and how

Javascript Map delete / set is slow

Could somebody explain, why Map is slower, than Object in the code below?
Docs says, that Map is optimized for performance, but tests shows poor results.

#!/usr/bin/env node

const object = {},
    map = new Map(),
    prefix = "a",
    iteratiions = 100_000;

for ( let n = 0; n < 100_000; n++ ) {
    object[prefix + n] = n;
    map.set( prefix + n, n );
}

const t1 = Date.now();
for ( let n = 0; n < iteratiions; n++ ) {
    map.delete( prefix );
    map.set( prefix, 1 );
}
console.log( "Map:", Date.now() - t1, "ms" );

const t0 = Date.now();
for ( let n = 0; n < iteratiions; n++ ) {
    delete object[prefix];
    object[prefix] = 1;
}
console.log( "object:", Date.now() - t0, "ms" );

Output:

Map: 7558 ms
object: 11 ms

Changing the values of a radio button programatically with jQuery

I want to change the value of a radio button programatically on a website built on Spring, with jQuery on the frontend.

I’ve managed to change other values, but the radio button is kind of tricky.

Here’s the HTML for the button:

<table id="formCheltuialaBuget:radioTVA" role="presentation" class="ui-selectoneradio ui-widget">
    <tbody>
        <tr>
            <td>
                <div class="ui-radiobutton ui-widget">
                    <div class="ui-helper-hidden-accessible"><input id="formCheltuialaBuget:radioTVA:0"
                            name="formCheltuialaBuget:radioTVA" type="radio" value="true"
                            onchange="PrimeFaces.ab({s:&quot;formCheltuialaBuget:radioTVA&quot;,e:&quot;change&quot;,p:&quot;formCheltuialaBuget:radioTVA&quot;,u:&quot;formCheltuialaBuget:tvaelig formCheltuialaBuget:totalELigg formCheltuialaBuget:publicBuget formCheltuialaBuget:tvanonelig formCheltuialaBuget:contributie&quot;,onst:function(cfg){document.body.style.cursor='wait';},onco:function(xhr,status,args){document.body.style.cursor='default';}});"
                            wtx-context="F08D1A11-AFD1-4F6C-80FC-F02488900FAB"></div>
                    <div class="ui-radiobutton-box ui-widget ui-corner-all ui-state-default"><span
                            class="ui-radiobutton-icon ui-icon ui-icon-blank ui-c"></span></div>
                </div>
            </td>
            <td><label for="formCheltuialaBuget:radioTVA:0">Da</label></td>
            <td>
                <div class="ui-radiobutton ui-widget">
                    <div class="ui-helper-hidden-accessible"><input id="formCheltuialaBuget:radioTVA:1"
                            name="formCheltuialaBuget:radioTVA" type="radio" value="false"
                            onchange="PrimeFaces.ab({s:&quot;formCheltuialaBuget:radioTVA&quot;,e:&quot;change&quot;,p:&quot;formCheltuialaBuget:radioTVA&quot;,u:&quot;formCheltuialaBuget:tvaelig formCheltuialaBuget:totalELigg formCheltuialaBuget:publicBuget formCheltuialaBuget:tvanonelig formCheltuialaBuget:contributie&quot;,onst:function(cfg){document.body.style.cursor='wait';},onco:function(xhr,status,args){document.body.style.cursor='default';}});"
                            checked="checked" wtx-context="3412B572-AE39-4A78-B34C-87A13760C805"></div>
                    <div class="ui-radiobutton-box ui-widget ui-corner-all ui-state-default ui-state-active"><span
                            class="ui-radiobutton-icon ui-icon ui-icon-bullet ui-c"></span></div>
                </div>
            </td>
            <td><label for="formCheltuialaBuget:radioTVA:1">Nu</label></td>
        </tr>
    </tbody>
</table>

How can I change the value of the radio button to true/false?

Changing it this way:

document.getElementById("formCheltuialaBuget:radioTVA:0").value = false;
document.getElementById("formCheltuialaBuget:radioTVA:1").value = true;

didn’t do it anything.

Thanks!

Parsing/scraping Javascript from web in C/C++ [closed]

Please tell me – are there libraries for C or C ++ that can do something like the following:

I make a GET request and get HTML, then I open the same page using Chrome, for example, and look at the HTML code of this page.

And they don’t match!

And if I understand correctly, they do not match for the following reason:

-I made a GET request to the server and the server returned the HTML of the requested page.

-Chrome made the same GET request to the server and the server returned the requested page to Chrome, BUT here is the difference: Chrome, as it receives the HTML page, analyzes it for JS code / scripts and executes it on the fly requesting additional data and modifying HTML.

And here is the QUESTION: are there libraries C/C++ that could analyze the JS code and execute the queries that are specified in the JS code?

Segmented Control In Header

im trying to add a segmented tab to my header let me show you an example before i start.

enter image description here

if you’ve been on the twitter app you know you can swipe through these tabs while these tabs remain on the header, i cant quite find out how i would complete this tho

Some of the code:

 <Stack.Screen name="Find" component={Home} options={{
            header: () => (
                <View style={{ backgroundColor: 'black', paddingBottom: 10 }}>
                    <View style={{ paddingLeft: 10, flexDirection: 'row', paddingTop: 25, backgroundColor: 'black' }}>
                        <View style={{}}>
                            <View style={{ paddingRight: 10, flexDirection: 'row', alignItems: 'center' }}>
                                <View>
                                    <Image style={{ width: 30, height: 30, borderRadius: 30 }} source={require('../assets/forever.png'} />
                                </View>
                                <View style={{ width: '84%', paddingHorizontal: 10 }}>
                                    <Formik
                                        initialValues={{ formData: "" }}
                                        onSubmit={async (values, { setSubmitting }) => {
                                            setSubmitting(true)
                                            await setData({
                                                values
                                            })
                                            console.log(sdata)
                                            setSubmitting(false)
                                        }}
                                    >
                                        {({ handleChange, handleBlur, handleSubmit, values }) => (
                                            <>

                                                <View
                                                    style={{
                                                        backgroundColor: '#0D0D0D',
                                                        padding: 10,
                                                        borderRadius: 18,
                                                        flexDirection: 'row',
                                                        height: 34
                                                    }}
                                                >
                                                    <View style={{ alignItems: 'center' }}>
                                                        <Icon name="search" type="ionicon" size={15} color="grey" />
                                                    </View>
                                                    <TextInput
                                                        autoCorrect={false}
                                                        clearButtonMode="always"
                                                        placeholderTextColor="grey"
                                                        onChangeText={handleChange('formData.form')}
                                                        value={values.formData.form}
                                                        onBlur={handleBlur('formData')}
                                                        placeholder="Search"
                                                        style={{ backgroundColor: '#0D0D0D', paddingHorizontal: 20 }}
                                                    />
                                                </View>
                                            </>
                                        )}
                                    </Formik>


                                </View>
                                <View style={{ flexDirection: 'row' }}>
                                    <Icon onPress={() => create.current.show()} type="ionicon" size={28} color="white" name="create-outline" />
                                </View>
                            </View>

                        </View>

                    </View>
                    <ScrollableTabView style={{}} renderTabBar={() =>
          <DefaultTabBar
            style={{
              borderWidth: 0,
            }}
          />
        } tabBarUnderlineStyle={{ backgroundColor: "#fff", borderWidth: 1}} tabBarTextStyle={{ color: "#fff" }} tabBarBackgroundColor="#000">
          <View tabLabel="Home">

          </View>
          <Quotes tabLabel="Quotes" />
          <View tabLabel="Posts" >

          </View>
          <View tabLabel="Home" >

          </View>
         
        </ScrollableTabView>
                </View>
            ),

        }} />

If you need anymore information, just comment and thanks in addvanced

Accessing updated state inside the same function

I am having trouble accessing state after saving it, when calling the same function. My state is setup like this:

const perLanguageDefault = {
  calculated_skill: null,
  display_skill: null,
  published: false,
  premium: false,
  id: null,
};

  const [perLanguage, setPerLanguage] = useState(perLanguageDefault);

I have a save function inside one of my components as such:

  const _savePerLanguageArticle = async () => {
    if (perLanguage.id === null) {
      await _createPerLanguage();
    } else if (perLanguage.id !== null) {
      await _updatePerLanguage();
    }
    if (props.sentences.length !== 0 && perLanguage.id) {
      await _iterateSentences();
    }
    await _saveRulesArticle();
  };

If a perLanguage object doesn’t exist, I create one in the database, and set it in state as such:

  const createPerLanguage = async () => {
    const body = {
      published: perLanguage.published,
      premium: perLanguage.premium,
      article: props.article.id,
      language: props.lang_id,
      calculated_skill: perLanguage.calculated_skill,
      display_skill: perLanguage.display_skill,
    };
    try {
      const response = await api.post("perLanguageCreateAPI", {
        body: body,
      });
      await setPerLanguage(response.data);
    } catch (e) {
      console.log(e.response);
    }
  };

saveRulesArticle above looks like this:

  const _saveRulesArticle = async () => {
    const newRules = props.rules.map((rule) => {
      let ruleobj = {};
      ruleobj["rule"] = rule;
      ruleobj["per_language"] = perLanguage.id;
      return ruleobj;
    });
    try {
      const response = await api.post("ruleMappingCreateAPI", {
        body: newRules,
      });
    } catch (e) {
      console.log(e.response);
      return;
    }
  };

However, because it’s all within the same top function, _saveRulesArticle doesn’t get access to the new perLanguage variable, it isn’t updated, even though createPerLanguage supposedly creates it and sets it.

I suspect there’s some relation to this stack overflow page:

useState set method not reflecting change immediately

Most particularly the highest upvoted answer. I understand how that works for useEffect, but how would it work here? How do I update state inside a function, and then later inside that function, access the same updated state? Is this possible? Is this an anti-pattern?

Why’s only one image being displayed instead of all the images present in the object?

I’m facing a weird issue where only the first image that’s present in the object is being displayed via the Grid component instead of all of them being displayed at once (there are three images in total). It’s basically justifiable grabbing the first URL and displaying and ignoring the other images URLs present in the object.

Note: Upon expanding the object in the console I see a blue ! that says: The value was evaluated upon first expanding. It may have chaneged since then.. I’m not sure if this has anything to do with the issue I’m facing, I’m just including it here for extra information.

Anyone know what the issue could be and how I can fix it?

Here’s Gallery.js:

import React, { useEffect, useState } from 'react';

const Gallery = () => {
    let authToken = localStorage.getItem('token');

    const [uploadsData, setUploadsData] = useState([]);

    // Referring the uploadsData inside the useEffect hook's callback and in order to get correct console log,
    // Run the code in a separate useEffect hook.
    // In this way, the getUploads function is called only once and it outputs correct uploadData to the browser console.
    useEffect(() => {
        getUploads();
    }, []);

    useEffect(() => {
        // logs empty array in the console if dependency array is empty
        // logs correct data when dependency array isn't empty - i.e. [uploadsData]
        // console.log(uploadsData);
    }, [uploadsData]);

    const getUploads = () => {
        const headers = {
            "Accept": 'application/json',
            "Authorization": `Bearer ${authToken}`
        }

        axios.get('http://localhost:8005/api/get-uploads', {headers})
            .then(resp => {
                // console.log(resp);
                setUploadsData([resp.data]);
            }).catch(error => {
            console.log(error);
        });
    };

    return (    
            {
                uploadsData.map((photos, index) => {
                    console.log(photos, index);
                    return <Grid src={photos[index].url} key={index}/>
                })
            }
    );
}

export default Gallery;

Here’s Grid.js:

import React, { useEffect } from 'react';

const Grid = (props) => {
    useEffect(() => {
        createUserPhotoNodes();
    }, []);

    const createUserPhotoNodes = () => {
        return (
            <div className="container">
                <div className="img-container">
                    <img src={props.src} alt="Photo" className="gallery-img" />
                </div>
            </div>
        );
    }

    return (
        <>
            <section className="gallery">
                {createUserPhotoNodes()}
            </section>
        </>
    );
}

export default Grid;

Type {X} is missing the following properties from type

Im trying to create a custom carousel with @trendyol-js/react-carousel but running im missing some properties in the but i dont know how to structure the code to solve it.

error: Type '{ leftArrow: Element; rightArrow: Element; }' is missing the following properties from type 'CarouselProps': children, show, slide

const CustomCarousel: React.FC = () => {
  const classes = useStyles();

  return (
    <Carousel
      leftArrow={
        <IconButton className={classes.arrow}>
          <ArrowBackIos />
        </IconButton>
      }
      rightArrow={
        <IconButton className={classes.arrow}>
          <ArrowForwardIos />
        </IconButton>
      }
    ></Carousel>
  );
};

How to loop through an array an put create an array of objects using react and javascript?

i want to loop through an array elements and create an array of objects with its values.

below is the array example which comes from querying from an api.

const array = [
    "first",
    "second",
]

now i want to create an array of objects like below

const arr_obj = [
    {
         label: "first",
         value: "first",
     }
     {
         label: "second",
         value: "second",
      }
  ]

i have tried like below

const arr_obj = React.useMemo(() => {
    const output = arr.forEach(item => { //error
        return {
            label: item,
             value: item,
         }
     }, [arr]});

but this gives error arr could be possibly undefined or null and also i think this is not the way to create an array of objects with label, value pairs from the array elements.

could someone help me with this. thanks.

Component not getting render when importing from folder

I am trying to render a component which is in another folder called “Component” but the component are not getting render when importing them from this folder and when I am creating component in index.js it got render.Header not getting render and sometimes ChallengeOne not getting render
my code

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";

import Content from "./component/Content";
// import ChallengeOne from "./component/ChallengeOne";
import ChallengeTwo from "./component/ChallengeTwo";
// import ChallengeTwo from "./component/ChallengeTwo";
// import Page from "./component/Challenge Three/Page";
const Header=()=>{
  <>
  <h1>Reason I'm exicted to learn react</h1>
  </>
}
const ChallengeOne =()=>{
  return(
      <nav>
          <h1>DRY FRUIT CENTER</h1>
          <ul>
              <li>Price</li>
              <li>About</li>
              <li>Contact</li>
          </ul>
      </nav>
  )
}
ReactDOM.render(
  <React.StrictMode>
    <ChallengeOne/>
    <ChallengeTwo/>
    <Content />
    <Header/>
   </React.StrictMode>,
  document.getElementById("root")
);