How can I remove even numbers from my array?

Attempting to remove all even numbers from the array.
I have managed to remove some but there are still two persisting. I am unsure what to do as I have very new to coding and only know the very basics.

function findEfficientBulbs(serialNumbers) {
console.log(serialNumbers);
const efficientSerialNumbers = [];
// Below

//create a loop to go through the array
for (let i = 0; i < serialNumbers.length; i++){
    //define a varible to look through the array via loop 
    const currentBulb = serialNumbers[i]
    //create if statement to find odd numbers and has 6 digits
    // remove items containing even numbers
        if (currentBulb === 6 && currentBulb % 2 === 1 ){
            //push variable into efficient array
            efficientSerialNumbers.push(currentBulb)
        }
}

return efficientSerialNumbers;
}    

error I received:

✕ AssertionError: expected [] to deeply equal [ 234567, 456789 ]

logs

[ 123456, 234567, 345678, 456789 ]

I don’t understand why numbers 123456 and 345678 came back.

Fetch request is ignored when running build [closed]

I’m working on a React application that has two requests:

  • One checking the existence of a document in my database. If the document is on my DB my request returns an ID that allow me to consult (GET) the data related with this document via API. Otherwise, I’ll register this document (POST) via API (I’m going with this approach because I have a limited amount of POST requests available, but I can make as many GET requests as I want)

  • The other one will fetch data from already registered documents on my DB using the consult ID returned from the first request

I’m just giving some context here because it might help.

When I execute my application with npm start (both on my local machine and also on my server) everything works completely fine. I make my request and all the data I need will be rendered on a table.

But when I run npm build and serve the application – the second request won’t occur.

I’m consulting this document that already exists on my DB and when executing the application with npm start my network session from dev tools show me:

POST 200 – route that check the existence of the document on my DB (response is the ID)

GET 200 – route that consult the document data based on ID (response is the data I need)

On the other hand, when serving the build application I only got:

POST 200 – route that check the existence of the document on my DB (response is the ID)

But the point is: no error appears. My request is just being ignored.

I have no idea of what is happening. Anyone has ever faced this scenario? How can I solve it?

How can I create this using a for loop in JavaScript?

const add0 = document.querySelector('.add0');
const add1 = document.querySelector('.add1');
const add2 = document.querySelector('.add2');
const add3 = document.querySelector('.add3');
const add4 = document.querySelector('.add4');
const add5 = document.querySelector('.add5');
const add6 = document.querySelector('.add6');

I have tried creating this using a for loop with i such as :

for(let i = 0; i <= 6; i++ {

    const add[i] = document.querySelector('.add' + i);

}

But it doesn’t work.

Javascript Image Slider skipping images on mobile device swipe?

I’ve got this below code for an image slide show I have. It allows the user to both click arrows to scroll through images (this works perfectly), and if on a mobile device, swipe through the images. That said, for some reason, when my user swipes through the images, it skips an image (or sometimes 2!) It’s driving me mental.

It seems like when I do small swipes, the images are in the correct order. But if I do a larger swipe, it starts skipping images. I’ve tried eliminating the swipeDistance and changing the threshold size but nothing seems to work. Help!

Code:

<script>
(() => {

    const images_list = [
{
    "url": "https://www.url.com/image1.png",
    "alt": "",
    "name": "Image 1",
    "link": ""
},
{
    "url": "https://www.url.com/image2.png",
    "alt": "",
    "name": "",
    "link": ""
},
{
    "url": "https://www.url.com/image3.png",
    "alt": "",
    "name": "",
    "link": ""
},
{
    "url": "https://www.url.com/image4.png",
    "alt": "",
    "name": "",
    "link": ""
}
    ];


    let slider_id = document.querySelector("#accessory");

    // append all images
    let dots_div = "";
    let images_div = "";
    for (let i = 0; i < images_list.length; i++) {
        
        let href = (images_list[i].link == "" ? "":' href="'+images_list[i].link+'"');
        images_div += '<a'+href+' class="hcg-slides animated"'+(i === 0 ? ' style="display:flex"':'')+'>'+
                        '<img src="'+images_list[i].url+'" alt="'+images_list[i].name+'">'+
                     '</a>';
        dots_div += '<a href="#" class="hcg-slide-dot'+(i === 0 ? ' dot-active':'')+'" data-id="'+i+'"></a>';
    }
    slider_id.querySelector(".hcg-slider-body").innerHTML = images_div;
    slider_id.querySelector(".hcg-slide-dot-control").innerHTML = dots_div;

    let slide_index = 0;
    let touchStartX = 0;
    let touchEndX = 0;

    const images = slider_id.querySelectorAll(".hcg-slides");
    const dots = slider_id.querySelectorAll(".hcg-slide-dot");
    const prev_button = slider_id.querySelector("#hcg-slide-prev");
    const next_button = slider_id.querySelector("#hcg-slide-next");
    
    
let swipeInProgress = false;

slider_id.addEventListener("touchstart", (event) => {
  touchStartX = event.touches[0].clientX;
  swipeInProgress = true;
});

slider_id.addEventListener("touchmove", (event) => {
  if (swipeInProgress) {
    event.preventDefault(); // Prevent scrolling during swipe
  }
});

slider_id.addEventListener("touchend", (event) => {
  if (swipeInProgress) {
    const touchEndX = event.changedTouches[0].clientX;
    const swipeDistance = touchEndX - touchStartX;

    if (swipeDistance > 0) {
      slide_index--; // Swipe to the right, go back one image
    } else if (swipeDistance < 0) {
      slide_index++; // Swipe to the left, go forward one image
    }

    showSlides();
    updateActiveDot(); // Update the active dot
    swipeInProgress = false; // Reset the swipe flag
  }
});




const handleSwipe = () => {
  const minSwipeDistance = 25; // Adjust the minimum swipe distance as needed

  if (touchEndX - touchStartX > minSwipeDistance) {
    slide_index--;
  } else if (touchStartX - touchEndX > minSwipeDistance) {
    slide_index++;
  }

  showSlides(); // Call showSlides before updating slide_index
  // Update the active dot after calling showSlides
  dots[slide_index].classList.add("dot-active");
};


const showSlides = () => {
  if (slide_index > images.length - 1) {
    slide_index = 0;
  }
  if (slide_index < 0) {
    slide_index = images.length - 1;
  }
  for (let i = 0; i < images.length; i++) {
    images[i].style.display = "none";
  }

  images[slide_index].style.display = "flex";
};



const updateActiveDot = () => {
  for (let i = 0; i < dots.length; i++) {
    dots[i].classList.remove("dot-active");
  }

  dots[slide_index].classList.add("dot-active"); // Update the active dot
};


    
    prev_button.addEventListener("click", event => {
        event.preventDefault();
        slide_index--;
        showSlides();
    }, false);

    next_button.addEventListener("click", event => {
        event.preventDefault();
        slide_index++;
        showSlides();
    }, false);

    const dot_click = event => {
        event.preventDefault();
        slide_index = event.target.dataset.id;
        showSlides();
    }

    for (let i = 0; i < dots.length; i++) {
        dots[i].addEventListener("click", dot_click, false);
    }
    

    
})();

</script>

How to return an empty pushState (or clear the current state) when fetching the index page

I am trying to turn a Tumblr site into a single page application.

Currently my page links work, I parse the href attribute, fetch the corresponding page, the update the pushState as well as an additional popstate eventListener so I can pass this to the history object.

The issue arises if I am on a specific sub page (about, contact etc) and then navigate to the index, the pushState is not replaced, even though for the index I am passing an empty string.

This seems like a pretty fundamental issue that I am assuming lots of JS libraries have resolved (React, Vue etc).

Here is my slightly truncated JS:

let internal = [...links].filter(item => item.getAttribute('href').startsWith('/'));

const updateContent = (input) => {
    pageWrapper.replaceChildren();
    const parser = new DOMParser();
    const doc = parser.parseFromString(input, 'text/html');
    const container = doc.querySelector('#container');
    pageWrapper.appendChild(container);
}

internal.forEach(item => {
    let href = item.getAttribute('href');
    let hrefSplit = href.split('/')[1];
    item.addEventListener('click', (event) => {
        event.preventDefault();
        event.stopPropagation();
        body.classList.add(loadingClass);
        if (href === '/') {
            hrefSplit = "";
        } 
        fetch(href)
            .then((res) => {
                return res.text();
            })
            .then((html) => {
                updateContent(html);
                history.pushState({ path: href }, "", hrefSplit); // does not work when the href is just '/'
                body.classList.remove(loadingClass);
            })
            .catch((err) => {
                console.warn('Something went wrong.', err);
                body.classList.remove(loadingClass);
            });
    });

    document.addEventListener('popstate', (event) => {
        const state = event.originalEvent.state;
        if (state) {
            updateContent(state.path);
        }
    });
});

My only thought it that perhaps an empty string won’t ever work, or if the fetch url is the index page, you have to manually remove the previous pushState, but not 100% sure.

I can add more code here if needed, but in addition all the code can be accessed at the Tumblr URL (it is slightly more verbose but the core functionality should be the same):
https://malarkey-test.tumblr.com/

Why is this regex returning true for everything? [duplicate]

I wanted my regex to return true only for digit-only inputs, but it’s returning true for everything.

const regex = new RegExp(/[0-9]*/g);
console.log(e.target.value);
console.log(regex.test(e.target.value));
if (regex.test(e.target.value)) {field.onChange(e);}

enter image description here
I had a more complete regex but it kept on not working so I simplified it to be a digit-only regex and that doesn’t work either.

How to Customize Cancel Text in Grafana ConfirmButton Component?

I’m currently working on a project where I’m using the ConfirmButton component in Grafana, and I’d like to customize the text for the cancel button. As of my last knowledge update in September 2021, it seems that the ConfirmButton component does not natively support a cancelText prop and it there is no other alternative.

I’ve tried including a cancelText prop in the component, but it doesn’t seem to work as expected. The cancel button still displays the default “Cancel” text. Here’s an example:

<ConfirmButton
  closeOnConfirm
  size="md"
  confirmText="Are you sure?"
  confirmVariant="secondary"
  cancelText="No, thanks" // I expected this to change the cancel button text
  onConfirm={() => {
    console.log('Action confirmed!');
  }}
>
  Click me
</ConfirmButton>

Then I look the grafana open source code: Grafana-ConfirmButton

You see that we no longer have the cancelText, and there is no other alternative.
Do someone have any ideas on how to solve it? I need to make changes to add i18n.

Thank you very much!

Cheers,
Turtles

Get touchstart touches.layerX like mousedown layerX with rotated canvas

I need help. I have rotated canvas with elCanvas.style.transform = ‘rotate(25deg)’; I can get coords i desktop browser mousedown event.layerX and event.layerY. Via LayerX and LayerY i always can get click coords in rotated layer. I need to get rotated coordinates for mobile devices via touchstart. Its seems there no layerX. Need help. Has anyone encountered this problem? Sry for bad English.

Need help with my code.

How to connect different dom elements?

Im a completely noob on js, and i want to know if i want two or more dom element be connected( which means if i got one of them , then i can get another), what is the most currect way?

I tried use id as a simbol, but what if i want to connect more doms?

what im using now is like:

<div id="area_A>
    <div id="block_1"></div>
</div>

<div id="area_B">
    <div id="block_2"></div>
</div>
$("#block_1").attr("connect_target","#block_2")

and then i can do
$("#" + $("#block_1").attr("connect_target"))
to get “block_2”

but it is so unclear to read and i found that i cant use an array like:

var id_array = ["block_2","block_3","block_4"]
$("#block_1").attr("connect_target",id_array)

to get more id that i need

I believe there are some more clever way to solve my needing, and i really need to know what are they

Thanks for any knowledge or experience sharing to me!

I need to check for cookies on reload in Nextjs

I need to do the following:
After reload check if the browser contain cookies
I am doing this in Next.js so there is a way to make this by applying “use client” in the root layout and use useEffect(), but that give me errors.

After that solution didn’t work I did a hook function to execute when the layout mount. But I dont know if that is the right approach.

first approach:
This return an error where the className does not match with the one in the server side. But does not break the app.

"use client"

import {Montserrat} from "next/font/google"
import "../sass/index.scss"
import ProviderWrap from "@/redux/provider"
import { useEffect } from "react"



export const metadata = {
  title: 'Listil',
  description: 'Generated by Next.js',
}

const montserrat = Montserrat({
  weight:["300", "500", "600", "700" ],
  style: ["italic", "normal"],
  subsets: ["latin"]
})

export default function RootLayout({ children }) {


  useEffect(()=> {
    console.log("mounted, ready to check for cookies")
  })

  return (
      <html lang="en">
        <head>
          <link rel="favicon" href="../favicon/favicon.ico" />
          <link rel="apple-touch-icon" sizes="152x152" href="../favicon/apple-touch-icon.png"/>
          <link rel="icon" type="image/png" sizes="32x32" href="../favicon/favicon-32x32.png"/>
          <link rel="icon" type="image/png" sizes="16x16" href="../favicon/favicon-16x16.png"/>
          <link rel="manifest" href="../favicon/site.webmanifest"/>
          <link rel="mask-icon" href="../favicon/safari-pinned-tab.svg" color="#5bbad5"/>
          <meta name="msapplication-TileColor" content="#00aba9"/>
          <meta name="theme-color" content="#ffffff"/>
        </head>
          <ProviderWrap>
            <body className={montserrat.className}>
              {children}
            </body>
          </ProviderWrap>
      </html>
    )
}

second approach:
This works fine, but I don’t think this is the right way to do it.

import {Montserrat} from "next/font/google"
import "../sass/index.scss"
import ProviderWrap from "@/redux/provider"
import rememberUserCheck from "./utils/rememberCheck"


export const metadata = {
  title: 'Listil',
  description: 'Generated by Next.js',
}

const montserrat = Montserrat({
  weight:["300", "500", "600", "700" ],
  style: ["italic", "normal"],
  subsets: ["latin"]
})

export default function RootLayout({ children }) {

  rememberUserCheck()

  return (
      <html lang="en">
        <head>
          <link rel="favicon" href="../favicon/favicon.ico" />
          <link rel="apple-touch-icon" sizes="152x152" href="../favicon/apple-touch-icon.png"/>
          <link rel="icon" type="image/png" sizes="32x32" href="../favicon/favicon-32x32.png"/>
          <link rel="icon" type="image/png" sizes="16x16" href="../favicon/favicon-16x16.png"/>
          <link rel="manifest" href="../favicon/site.webmanifest"/>
          <link rel="mask-icon" href="../favicon/safari-pinned-tab.svg" color="#5bbad5"/>
          <meta name="msapplication-TileColor" content="#00aba9"/>
          <meta name="theme-color" content="#ffffff"/>
        </head>
          <ProviderWrap>
            <body className={montserrat.className}>
              {children}
            </body>
          </ProviderWrap>
      </html>
    )
}

This is the function used in the 2nd

export default function rememberUserCheck(cookie) {
    console.log("mounted, ready to check for cookies")
}

Is there any other way to check the cookies on reload?.

WEB3 error: Transaction has been reverted by the EVM

I have deployed this simple smart contract using Remix

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

contract Counter {
    uint256 private count = 0;

    function setCount(uint256 val) external payable  {
        count = val;
    }

    function viewCount() external view returns (uint256) {
        return count;
    }
}

I deployed this contract using evm version: paris. Code has been successfully deployed and working fine on Remix IDE.

I am trying to interact this using web3.js in my next app in following way using metamask

const loadWeb3 = async () => {
      if (window.ethereum) {
        const web = new Web3(window.ethereum);
        const accounts = await window.ethereum.request({
          method: "eth_requestAccounts",
        });
        console.log("Accounts requested from MetaMask RPC: ", accounts);
        try {
          const contract = new web.eth.Contract(abi,contract-address);
          const transactionReceipt = await contract.methods
            .setCount(10)
            .send({ from: accounts[0], gas: 3000000 });
          console.log(transaction);
        } catch (err) {
          console.log(`error: ${err}`);
        }
      } else {
        console.log("Please install metamask");
      }
    };

I was expecting that transaction would be successful but I am receiving this in my transactionReceipt

error: TransactionRevertedWithoutReasonError: Transaction has been reverted by the EVM:
 {"blockHash":"0x6138b0cdd3a047486419f066ef056aab7b28c11bbaea82b5812c095f96cf86c7","blockNumber":"1382940","cumulativeGasUsed":"21046","from":"0x9ded1ae475bd50a15dde12bbc34b7ea04969cd0b","gasUsed":"21046","logs":[],"logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","status":"0","to":"0xb69254cc37d818fdbcff6501acff400913147c1c","transactionHash":"0x6d3a2d51bae3746069db1cc778b357b92a6348a37d157181943c894cfbfc0d76","transactionIndex":"1"}

Unable to figure out why this error is happening.

why can’t I make a request from a bat file to the truffle console

I have a sol contract and I want to vote through truffle,but I want to try to do it using a bat file

@echo off

echo Enter your account address:
set /p account=""
echo Enter your password:
set /p password=""

echo Attaching to Geth and unlocking the account...
geth attach \.pipegeth.ipc --exec "personal.unlockAccount('%account%', '%password%', 0)"

cd "E:\finishmyTruffle"

echo Deploying contracts...

echo Do you agree to perform this action? (Y/N)
choice /c YN /n

if errorlevel 2 (
    echo "you voted against"
    truffle console --network geth --exec "let voting = await Voting.deployed()"; "voting.voteAgainst({from: '%account%'})"

) else (
    echo "you voted for"
    truffle console --network geth --exec "let voting = await Voting.deployed()"; "voting.voteFor({from:'%account%''})"
)

cmd /k

these lines don’t work:

truffle console --network geth --exec "let voting = await Voting.deployed()"; "voting.voteAgainst({from: '%account%'})"

I don’t use bat files for a long time and thought that –exec would give access with the work of the js console

Can anyone help me, how do I give a line break in JS? [closed]

export const Pelayanan = [
  {
    id: 1,
    image: Service1,
    star1: "fa-solid fa-star",
    star2: "fa-solid fa-star",
    star3: "fa-solid fa-star",
    star4: "fa-solid fa-star",
    star5: "fa-solid fa-star-half-stroke",
    title: "p",
    price: "a",
    buy: "Pesan Sekarang",
    NamaFitur: "Fitur Paket Small",
    Fitur: "jda",
    delay: "300",
  },
]

How do you give a line break in JS?

javascript : if in my function wont work and my function wont call values from array [closed]

javascript : if in my function wont work and my function wont call values from array

enter image description here
this is my code and i point out where is the problem

i made a function that would check largest element in the temperatures array then take the max and min value after that it should subtract min from max but the for part in the function has problem its seems temps.length considered as single string since both temps and length has the same color

Twilio-Video in React-native using Expo: use “module:react-native-twilio-video-webrtc”

I want to use Twilio-Video in react-native project. At the moment we are using Expo and Expo Go to start project. I found two packages: React Native WebRTC and react-native-twilio-video-webrtc. I am not react-native developer, so this is basically new for me. I tried to follow some kind of guides from github. Both packages are not working with my configuration. I tried a lot of staff. If you ever tried and used it before can you help me to write down some kind of steps. which are workable. Basically I am getting this error. I can show you part of my code if needed

enter image description here

I tried to install these packages. installed successfully, but project did not start. I tried expo prebuild and modified content of android directory result was same