Finding the hundredth prime in Javascript

I’m trying to get back into coding and I want to figure out what is causing my code to not spit out the hundredth prime. I have tried looking at others code and have gone through many variations of this but I believe I’ll understand better if I know exactly what I messed up. Sorry if this is a dumb question but I’d appreciate the help.

int count = 0; //counts the amount of primes found so far
int divisor = 1; //what we divide against our maybe prime
int mPrime = 1;
boolean cBeDiv = false;//to see if our mPrime was able to be divided before divisor was able to reach it

  while(count < 100) { //need to find the hundredth prime
      if(mPrime%divisor!=0) { //checks if the remainder is 0 or not
          cBeDiv=false;
      }else if(mPrime%divisor==0) {
          cBeDiv = true;
      }
      if ((divisor==mPrime&&cBeDiv)) { //if divisor is equal to mPrime AND it wasn't able to 
be divided by another number
          divisor = 1;
          count++;
          mPrime++;
      }else{
          divisor++;
      }
      if(count==100){
        System.out.println("" + mPrime);
        break;
     }
  }

Why does my addeventlistener code that changes some code when the animation is complete getting the error reading property of null? [duplicate]

I am trying to an event listener that will run some code to change the objects position on the game screen but when I run the code I keep getting an error reading

‘Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’)
at HTMLButtonElement. (script.js:40:18)’

and the object is staying in the same place.

here is the code that I am trying to run:

carAnimation.addEventListener('animationiteration', () => {
        var random = Math.floor(Math.random() * 5);
        left = random * 90 + 15;
        carAnimation.style.left = left + "px";
        counter++;
        console.log(counter)
    });

here is the rest of the code if needed

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div  class="game">
        <div class="car"></div>
        <div class="npcCar"></div>
        <div class="npcCar npcCar2"></div>
        <div class="npcCar npcCar3"></div>
    </div>
    <button class="start">Start!</button>
    <div class="controlContainer">
        <button class="btn pause"></button>
        <button class="btn play"></button>
        <button class="btn restart"></button>
        <button class="btn help"></button>
    </div>
    <div class="helpModal hidd">
        <div class="modal hidden">
            <button class="close-modal">&times;</button>
            <h1>Help</h1>
            <p>
              HOW TO PLAY:
                Use WASD to the arrow keys to move the red car around.
                You need to avoid hitting the blue cars.
                When you hit a car you will automatically lose
                The longer you last the more points you get
                Good luck racer!
            </p>
          </div>
    </div>
   
    
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Oswald&display=swap');

        *{
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }

        body {
            display: flex;
            min-height: 100vh;
            width: 100%;
            background-color: rgb(69, 169, 240);
            font-family: 'Oswald', sans-serif;
        }

        .game{
            position: absolute;
            left: calc(50% - 450px/2);;
            height: 600px;
            width: 450px;
            border: 3px solid black;
            border-radius: 5%;
            background: url('road.png');
            overflow: hidden;
        }

        .start{
            position: absolute;
            height: 30px;
            width: 150px;
            background-color: rgb(1, 255, 1);
            border: 3px solid black;
            border-radius: 5%;
            font-size: 15px;
            font-weight: bold;
            top: 600px;
            left : calc(50% - 150px/2);
            transition: 0.5s;
        }
        .start:hover{
            background: red;
        }

        .controlContainer{
            padding: 5px;
            width: 120px;
            height: 120px;
            border: 3px solid black;
            border-radius: 5%;
            background-color: lawngreen;
        }
        .btn{
            height: 50px;
            width: 50px;
            border: 2px solid black;
            border-radius: 50%;
        }
        .play{
            background-image: url('play.png');
        }
        .pause{
            background-image: url('pause.png');
        }
        .help{
            background-image: url('help.png');
        }
        .restart{
            background-image: url('restart.png');
        }


        .animate{
            animation: road linear infinite 0.5s;
        }
        .hidden{
            display: none;
        }

        @keyframes road{
            0%{
                background-position-y: 0px;
            }
            100%{
                background-position-y: 600px;
            }
        }
        .modal {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 45%;
            background-color: white;
            padding: 6rem;
            border-radius: 5px;
            box-shadow: 0 3rem 5rem rgba(0, 0, 0, 0.3);
            z-index: 100000000;
        }
        .close-modal {
            position: absolute;
            top: 1.2rem;
            right: 2rem;
            font-size: 5rem;
            color: #333;
            cursor: pointer;
            border: none;
            background: none;
        }  
        
        .car{
            position: relative;;
            height: 120px;
            width: 60px;
            border-radius: 5%;
            top: 435px;
            background: url('Player (1).png');
            transform: rotate(180deg);
            z-index: 100000;
            
        }
        .npcCar{
            width: 60px;
            height: 120px;
            background: url('obsacle.png');
            position: relative;
            left: 15px;
            top: -300px;
        }

        .npcCar2{
            top: -420px;
            left: 195px;;
        }

        .npcCar3{
            top: -540px;
            left: 375px

        }

        .carAnimate{
            animation: vroom 0.8s linear infinite;
        }
        .carAnimate2{
            animation: vroom 0.8s linear infinite;
        }
        .carAnimate3{
            animation: vroom 0.8s linear infinite;
        }
        @keyframes vroom{
            0%{
                top: -120px;
            }
            100%{
                top: 600px;
            }
        }
    </style>
     <script>
        'use strict'

        const startBtn = document.querySelector('.start')
        const pauseBtn = document.querySelector('.pause')
        const playBtn = document.querySelector('.play')
        const restartBtn = document.querySelector('.restart')
        const helpBtn = document.querySelector('.help')
        const modal = document.querySelector('.modal');
        const closeModal = document.querySelector('.close-modal');
        const game = document.querySelector('.game');
        const player = document.querySelector('.car');
        const npcPlayer = document.querySelector('.npcCar');
        const npcPlayer2 = document.querySelector('.npcCar2');
        const npcPlayer3 = document.querySelector('.npcCar3');
        const carAnimation = document.querySelector('.carAnimate');
        const carAnimation2 = document.querySelector('.carAnimate2');
        const carAnimation3 = document.querySelector('.carAnimate3');
        let click = 0;
        let interval;
        let both = 0;
        let counter = 0;


        //onLoad
        window.addEventListener("load", () => {
            player.style.position = "relative";
            player.style.left = '195px';
            player.style.top = '485px';
        });

        // Start the Game
        startBtn.addEventListener('click', function(){
            console.log('button clicked');
            game.classList.add('animate');
            click+=2;
            npcPlayer.classList.add('carAnimate')
            npcPlayer2.classList.add('carAnimate2')
            npcPlayer3.classList.add('carAnimate3')

            carAnimation.addEventListener('animationiteration', () => {
                var random = Math.floor(Math.random() * 5);
                left = random * 90 + 15;
                carAnimation.style.left = left + "px";
                counter++;
                console.log(counter)
            });
            carAnimation2.addEventListener('animationiteration', () => {
            var random1 = Math.floor(Math.random() * 5);
            left = random1 * 90 + 15;
            carAnimation2.style.left = left + "px";
            counter++;
            console.log(counter)
            });
            carAnimation3.addEventListener('animationiteration', () => {
            var random1 = Math.floor(Math.random() * 5);
            left = random1 * 90 + 15;
            carAnimation3.style.left = left + "px";
            counter++;
            });
            
        });


        //Pausing the Game
        pauseBtn.addEventListener('click', function(){
            console.log('button clicked');
            if(click>1){
                game.classList.remove('animate');
                click--
            }
            console.log(click)
        });

        //Resuming the Game
        playBtn.addEventListener('click', function(){
            console.log('button clicked');
            if(click===1){
                game.classList.add('animate');
                click++;
                console.log(click);
            }
            
        });

        //Opening the Help Model
        helpBtn.addEventListener('click', function(){
            console.log('modal clicked')
            modal.classList.remove('hidden')
        });
        //closing the help modal
        closeModal.addEventListener('click', function(){
            console.log('button clicked')
            modal.classList.add('hidden')
        });

        //Moving Functions
        function moveLeft() {
            var left = parseInt(window.getComputedStyle(player).getPropertyValue("left"));
            var transform = parseInt(window.getComputedStyle(player).getPropertyValue("transform")); 
        
            if (left > -0) {
            player.style.left = left - 2 + "px";
            player.style.transform = 'rotate(-' + 215 + 'deg)'
            }
        }
        function moveRight() {
            var left = parseInt(window.getComputedStyle(player).getPropertyValue("left"));
            if (left < 385) {
            player.style.left = left + 2 + "px";
            player.style.transform = 'rotate(' + 215 + 'deg)'
            }
        }
        function moveUp() {
            var top = parseInt(window.getComputedStyle(player).getPropertyValue("top"));
            if (top > 0) {
            player.style.top = top - 2 + "px";
            player.style.transform = 'rotate(' + 180 + 'deg)'
            }
        }
        function moveDown() {
            var top = parseInt(window.getComputedStyle(player).getPropertyValue("top"));
            if (top < 490) {
            player.style.top = top + 2 + "px";
            player.style.transform = 'rotate(' + 180 + 'deg)'
            }
        }
        

        //Make the pLayer move
        document.addEventListener("keydown", (event) => {
            if (both == 0) {
            both++;
            if (event.key === "ArrowLeft") {
                interval = setInterval(moveLeft, 1);
            }
            if (event.key === "ArrowRight") {
                interval = setInterval(moveRight, 1);
            }
            if (event.key === "ArrowUp") {
                interval = setInterval(moveUp, 1);
            }
            if (event.key === "ArrowDown") {
                interval = setInterval(moveDown, 1);
            }
            if (event.key === "a") {
                interval = setInterval(moveLeft, 1);
            }
            if (event.key === "d") {
                interval = setInterval(moveRight, 1);
            }
            if (event.key === "w") {
                interval = setInterval(moveUp, 1);
            }
            if (event.key === "s") {
                interval = setInterval(moveDown, 1);
            }
            }
        });
        document.addEventListener("keyup", (event) => {
            clearInterval(interval);
            both = 0;
            player.style.transform = 'rotate(' + 180 + 'deg)'
        });

    </script>
</body>
</html>

Thanks!

Get Stock Price for few Stocks at every few seconds from server

I want to write one screen of UI in react.js

1.will show the price of the stocks
2.and it will show color [ red or green ] depending upon the comparison from previous stock price.

Is there any to get fake stream online created for study purpose which can be used to continuously get stock price for few stock. The stocks price are updated every few seconds or is there way it can be created on server side( using any programming language ) and used in javascript.

I am assuming web sockets have to be used in javascript to read the stream from server.

Initialize state with async function data NextJS?

I’m looking to initialize a state using an asynchronous function:

...
export default function Catalog() {
  const [productsShow, setProductsShow] = useState(getAllProducts())

  ...
  return(
    ... Render products using `productsShow` ... 
  )

getAllProducts()

...
export async function getAllProducts() {

    ...
    return productSet  // Of type Set()
}

The issue I have is the productsShow state is undefined when the page renders. I figure this because the page renders without waiting for the results of the async function to complete. Is there a way to initialize the state with results?

I’ve tried using the then() function but this results in the same error:

getAllProducts().then(initialProducts => {
    useEffect(() => {
      setProductsShow(preProducts => initialProducts)
    }, [productsShow])
  })

I’m using NextJS

There are some similar questions but differ in technologies used:

JSON file of Accesss_token save in my db?

at firts

i use java script, python, django and Maria DB.

I want to save the information logged in with sns in the DB.

enter image description here

this is Kakao talk’s login code.

enter image description here

I want to save the underlined information in my DB.

enter image description here

Code indicating the message window of the second photo.

I want to know how to extract and save the JSON file of Accesss_token and save in my db

How to load a html to a variable in next.config.js

I use standard nextron (Next + electron.js) to jump start my project (https://github.com/saltyshiomix/nextron)

In one particular case, I need to read a file template.html to variable (String). so I think I’ll use fs.readFileSync()

When I use import fs from "fs", the compiler complains that fs is not available. (refer to this Module not found: Can’t resolve ‘fs’ in Next.js application)

The accepted answer on that thread, recommends me to update the next.config.js file into:

/// I need this to load image from static files
const withImages = require('next-images')

module.exports = withImages({
  webpack: (config, { isServer }) => {
    // Fixes npm packages that depend on `fs` module
    if (!isServer) {
      config.node = {
        fs: 'empty'
      }
    }

    return config
  }
})

But the solution doesn’t work for me.

enter image description here
enter image description here

How can i set a node as selected in Kendo Treeview?

I am finding a node in the treeview by id and then by uid and setting it as selected , but the selected node is undefined ?

here is my code so far:

            id_node_to_select = Id <---that is a property on the node object
            var treeview = $("#mytree").data("kendoTreeView");
            var getitem = treeview.dataSource.get(id_node_to_select);
            treeview.findByUid(getitem.uid);
            var selectitem = treeview.findByUid(getitem.uid);
            var node = treeview.select(selectitem);   <--- this is undefined ?

How can i do this ?
Also I am adding a parent node to the grid and then gettting that parent and adding a child , all from reading a jsn string.
Surely there must be and easier way by setting children on the schema like kendo grids ?

Why is my React Infinite Scrolling is not working?

Main constructor

constructor(props) {
    super(props); 
    this.state = {
      page: 1,
      articles: [],
      loading: false,
      isActive: false,
    };
  }
  

Using componentDidMount method

    async componentDidMount() {
    const url = `https://newsapi.org/v2/top-headlines?country=us&category=${this.props.category}&apiKey=ff954e750b914328a0bc65c2e45304c4&page=1&pageSize=${this.props.pageSize}`;
    this.setState({ loading: true });
    let data = await fetch(url);
    let parsedData = await data.json(data);

    this.setState({
      articles: parsedData.articles,
      totalArticlesResults: parsedData.totalResults,
      loading: false,
    });
  }

Trying to debug in the console “testing”, but this function (loadFunc) isn’t trigger inside the

    loadFunc = async () => {
    console.log('testing');
    const url = `https://newsapi.org/v2/top-headlines?country=us&category=${this.props.category}&apiKey=ff954e750b914328a0bc65c2e45304c4&page=${this.state.page + 1}&pageSize=${this.props.pageSize}`;
    this.setState({ loading: true });
    let data = await fetch(url);
    let parsedData = await data.json(data);
    this.setState({
      articles: [...this.state.articles, ...this.parsedData.articles],
      totalArticlesResults: parsedData.totalResults,
      loading: false
    })
  }
  

Rendering jsx and mapping through the elements from API

   render() {
    return (
      <div className="container my-3"> 
        {/* Infinite scrolling */}

        <InfiniteScroll
          dataLength={this.state.articles.length}
          next={this.loadFunc}
          hasMore={this.state.articles.length !== this.state.totalArticlesResults}
          loader={<Spinner />}
        >

container inside InfiniteScroll Component

          <div className="container">
            <div className="row">
              {!this.state.loading && 
                this.state.articles.map((element, index) => {

returning in mapping

                  return (
                    <div className="col-md-4" key={index}>
                     ..
                    </div>
                  );
                })}
            </div>
          </div>
        </InfiniteScroll>
      </div>
    );
  }

Not Able to Get Input Range Value Simultaneously As it Changes

jQuery change even fires only when the event stops( Please check the snippet demo)

As you can see the console.log( $(this).val()) triggers only when the range input stops. Can you please let me know how I can make this more interactive in way that we can get the current value of input type="range" live and simultaneously as it change (Step by Step)

$("input").on("change", function(event){
  console.log( $(this).val())
 });  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="range" min="0" value="100" max="600">
          

dweetpro javascript API

I am migrating working code from regular dweet.io to dweetpro.io

In the javascript API documentation for dweetpro, it says to initialize using

var dweetClient = require(“dweetio-client”);

var dweetio = new dweetClient(“username”, “password”);

But “require” is not supported in client side javascript.
What do I need to do?

How would I ignore excel error in ExcelJS?

How do I ignore excel error for the entire workbook in ExcelJS.

Currently I am trying to ignore “Number stored as text” error.

I do not want to store number as number I want to keep it as text, and just want to ignore the error so it does not show up in excel.

I’ve read the exceljs documentation and tried to search answer but seems this has not been answered, appreciate any help.

Link to exceljs : https://github.com/exceljs/exceljs

How do you build your own filter() that is similar to the native built in filter() with all of its parameters?

I am learning about filter() and what this method does. So far I understood what it does and how to use it. The part I am struggling with is trying to understand all of its optional parameters and what they do. I understand how to use all of its required parameters (callbackFunction, currentValue) but not its optional ones (index,arr,thisValue).

syntax:
array.filter(callbackFunction(currentValue, index, arr), thisValue)

I would like to know the code behind the filter() method. I have made one using the required parameters (callbackFunction, currentValue), but couldn’t figure out how to incorporate the index, arr, and thisValue into my code. If you can help me do that so that I can see what’s going on inside the filter() method and what it’s doing to the index,arr, and thisValue parameters, you will help me out a TON!

Here is my code so far:

// The global variable
const s = [23, 65, 98, 5];
 
Array.prototype.myFilter = function(callback) {
  const newArray = [];
  for (let i =0; i < this.length; i++){
    let currentElement = this[i]
    let check = callback(currentElement);
    //if true (item is odd) then it pass the filter and can be included in new array
    if (check){
      newArray.push(currentElement);
    }
  }
  return newArray;
};
 
const new_s = s.myFilter(function(item) {
  return item % 2 === 1;
  //if true (item is odd) then it pass the filter and can be included in new array
});

console.log(new_s) //[23, 65, 5]

Keep getting caught TypeError: Cannot read properties of null (reading ‘classList’) at window.onscroll (script.js:6:16)

I’m trying to make the navbar switch colors when it goes down a specific y level using classList. For example if you have scrolled down 50 on the y axis it should add a class which has css making it a different color.

This is my js

`

const navbar = document.querySelector('nav');
window.onscroll = () => {
    if (window.scrollY > 70) {
        navbar.classList.add('sch');
    } else {
        navbar.classList.remove('sch');
    }
};

`

is there a way to iterate through array, listing each item in fixed-height container until all available space taken?

Using Vue, I have a div container with fixed height, overflow: hidden, I want to iterate through javascript array, adding each item to the div, and stop when the bottom of the div space is reached. Would also need it to be responsive.

<div class="container">
  <div class="header">Header</div>
  <div class="body" v-for="item in items">
    <div>{{ item.data }}</div>
  </div>
  <div class="footer">Footer</div>
</div>

.container {
  display: flex;
  height: 100%;
  flex-direction: column;
}

.header {
  height: 100px;
}

.footer {
  height: 100px;
}

.body {
  flex: 1;
  overflow: hidden;
}

Maybe you would need to retrieve the height of the container in pixels and divide by font height of your item.data perhaps? In any case the number of items displayed would need to change whenever window is resized in order to make it responsive.