NodeJS FileSystem Json Read and Write only one works

for a school project I have to rewrite a Json Object using node fs. I wrote a module and if I use deleteCity or addCity on their own, they work perfectly fine. But when I call both after another only one works. In my JSON File there is one array with 10 objects. In my main javascript file I require my module and call upon addCity and deleteCity functions.

//Modules
const fs = require("fs");

//Variablen
const citiesPath = "./cities.json";

//Funktionen
const deleteCity = (name) => {
    fs.readFile(citiesPath, "utf-8", (err, jstring) => {
        if (err) {
            console.log(err);
        }
            try {
                let data = JSON.parse(jstring);
                for (let i = 0; i < data.length; i++) {
                    if (data[i].Name == name) {
                        data.splice(i, 1);
                    }
                }
                fs.writeFile(citiesPath, JSON.stringify(data, null, 2), (err) => {
                    if (err) {
                        console.log(err);
                    }
                });
            } catch (error) {
                console.log(error);
        }
    });
};

const addCity = (obj) => {
    fs.readFile(citiesPath, "utf-8", (err, jstring) => {
        if (err) {
            console.log(err);
        } 
            try {
                let data = JSON.parse(jstring);
                data.push(obj);
                fs.writeFile(citiesPath, JSON.stringify(data, null, 2), (err) => {
                    if (err) {
                        console.log(err);
                    }
                });
            } catch (error) {
                console.log(error);
        }
    });
};

const showCity = () => {
    fs.readFile(citiesPath, "utf-8", (err, jstring) => {
        if (err) {
            console.log(err);
        } 
            try {
                let data = JSON.parse(jstring);
                console.log(data);
            } catch (error) {
                    console.log(error);
        }
    });
};


//Exporte
module.exports = {
    deleteCity,
    addCity,
    showCity
};

Conditional text change for div class

I have a list of grades on web page with identical span class. I Would need to append the current numeric grade and add a alphabet grade after the number. Current information is a text field and i would first need to parse the first 3 characters to identify the number. Then i would need to create a 5 level condition to give correct alphabet based on the number (example 0-40 = D, 40-60 = C, 60-80= B and 80-100 = A). Im newbie and just cant make it to work.

Grades list

I am able to update update the text, but when trying to parse and create conditions just was not able to make it work.

var elements = document.querySelectorAll('.score_value');
for ( var i=elements.length; i--; ) {
    elements[i].textContent += "something else";
}

all the help would be appriciated

How can I determine which data is displayed in a React component using an useState array?

I have a menu of buttons and each button opens the same component containing a title and a textarea. However, the content shown in the title and textarea must change based on the choice in the menu.

The data is taken from an API and put into a useState array. So I want to use this data in the called component. Does anyone know how you can determine, based on the button in the menu, which data is called in the new component?

This is what I have so far:

Menu Component:

import { useState, useEffect } from "react"
import ScenarioContent from "./ScenarioContent";

const ScenarioMenu = (handleScenario, scenarioChoice) => {
    const [scenarioContent, setScenarioContent] = useState(false);
    const [scenarioList, setScenarioList] = useState([]);

    const setContent = () => {
        if (!scenarioContent) {
            setScenarioContent(true);
        }

        console.log(scenarioContent);
    }


    useEffect(() => {
        const getData = async () => {
            const res = await fetch('http://localhost:8080/api/scenario/')
            const data = await res.json();
            setScenarioList(data);
            console.log(scenarioList);
        }
        getData();
    }, []);

    const getButtons = (num) => {
        const newScenarioArr = [];
        for (let i = 1; i <= num; i++) {
            newScenarioArr.push(<button onClick={setContent}>scenario {i}</button>)
        }
        return newScenarioArr;
    }



    return (
        <div className="container-scenarioSelect">
            <div className="btn-group-scenario">
                {
                    getButtons(scenarioList.length)
                }
            </div>
            <div>
                {scenarioContent ? <ScenarioContent /> : ""}
            </div>

        </div >
    )
}

export default ScenarioMenu

And this is the Content component with hardcoded data:

const ScenarioContent = (scenarioTitle, scenarioText) => {
    return (
        <div className="container-scenarioChoice">
            <div>
                <h1>Hamsterwoede!</h1>
                <label className="labels" for="scenario"> Scenario:  </label>
                <textarea className="text-area" type="text" id="scenario" name="scenario" rows="25" cols="80" >Met oplopende Olifantengriepcijfers op de horizon zijn inwoners van Engelse Eiland massaal begonnen met het inslaan van tampons. Deze zouden helpen de Olifantengriep uit de neus te houden en daarmee een infectie te voorkomen. De regering van Engelse Eiland verzoekt haar burgers dringend om te stoppen met hamsteren, en verzekert hen ervan dat de voorraden groot genoeg zijn om iedereen te kunnen bedienen. Over de effectiviteit van het tampongebruik als preventie van de Olifantengriep zijn door experts nog geen uitspraken gedaan. In Digitanzanië beginnen de eerste geluiden al op te gaan om spullen in te slaan. Wat moet de overheid doen?
                </textarea>
            </div>
            <div className="btn-group-scenario">
                <button>Terug</button>
            </div>
            <div>
                <button></button>
            </div>
            <div className="btn-group-scenario">
                <button>Sla op</button>
            </div>



        </div>
    )
}

export default ScenarioContent

This is how it looks right now, so the menu is left and the content is in the middle. the content must therefore be adjusted, but in the same component based on the menu choice

Web scraping in Python from responsive-bootstrap-kit

how to scrape content from a table which shows only after clicking on “show table”. In source code I found the content is shown uder <div class="responsive-bootstrap-toolkit">. When I load the page this class is not visible. It appears only after clicking show button but the url does not change so I cannot use BeautifulSoup (the class I am looking for was not found when I tried to request it using BS).
How to solve this problem and scrape directly from python? What is the library I can use? I believe, the problem is how to load the content remotely from Python so that the source code would contain my table.

Thank you in advance.

Google Map API on Web Rotate and Tilt Map With Mouse

I am trying to Tilt and Rotate Google Map with mouse right click.

I followed the documentation
https://developers.google.com/maps/documentation/javascript/webgl/tilt-rotation#maps_webgl_tilt_rotation-css

but find no help yet to achieve same thing with mouse movement.

google Api provide shift + drag mouse to tilt and rotate but I do not wanted to use shift button
only mouse

An bypass I tried was that on mouse drag create keyboard Event key down of shift key and keep rotating mouse but that did not work,
shift key is pressed by right click but map did not get that

that code is here

  document.body.addEventListener("keydown", (e) => {
    if (e.key == "Enter") {
      console.log('Enter keydown');
      let keyEvent = new KeyboardEvent("keydown", { shiftKey: true});
        document.body.dispatchEvent(keyEvent);
    }
    if(e.shiftKey) {
      console.log('Shift Key keydown');
    }
    if (e.key == "Enter" && e.shiftKey) {
      console.log('Enter + Shift Key keydown');
    }
  });
  document.body.addEventListener("keyup", (e) => {
    if (e.key == "Enter") {
      console.log('Enter keyup');
      let keyEvent = new KeyboardEvent("keyup", { shiftKey: true});
      document.body.dispatchEvent(keyEvent);
    }
    if(e.shiftKey) {
      console.log('Shift Key keyup');
    }
    if (e.key == "Enter" && e.shiftKey) {
      console.log('Enter + Shift Key keyup');
    }
  });
  document.body.addEventListener("keypress", (e) => {
    if (e.key == "Enter") {
      console.log('Enter keypress');
      let keyEvent = new KeyboardEvent("keypress", { shiftKey: true});
      document.body.dispatchEvent(keyEvent);
    }
    if(e.shiftKey) {
      console.log('Shift Key keypress');
    }
    if (e.key == "Enter" && e.shiftKey) {
      console.log('Enter + Shift Key keypress');
    }
  });
  map.addListener("drag", () => {

        let keyEvent = new KeyboardEvent("keydown", { shiftKey: true});
        document.body.dispatchEvent(keyEvent);

  });
  map.addListener("dragend", () => {});
  $('#map').mousedown(function(event) {
    switch (event.which) {
        case 1:
            console.log('Left Mouse button pressed.');
            break;
        case 2:
          console.log('Middle Mouse button pressed.');
            break;
        case 3:
           console.log('Right Mouse button pressed.');
           const keyEvent = new KeyboardEvent("keydown", { shiftKey: true});
           document.body.dispatchEvent(keyEvent);
            break;
        default:
          console.log('You have a strange Mouse!');
    }
});

from above code on shift key press or mouse right click i am able to get console log that shift key is pressed but how to rotate map on that no idea

I’m trying to import a function from a javascript file into my html document, but I cant get it working

I usually work with C# so im pretty new to Javascript. What im trying to do is link each of my functions that are contained within a Javascript file “commands.js” to buttons that are within my html template.

so far I have used a script tag within the head tag to import the commands.js file:

<script src="js/commands.js"></script>

I have then used a div container and used the onclick function to try access the “login()” function inside of the commands.js file, but nothings showing in the console. At this point im just testing the functions to ensure that each of them are responding to the buttons.

 <div id="btnlogin"  class="standard-button" onclick="login()" onmouseenter="hoverMouseOver(event)" onmouseleave="hoverMouseLeave(event)">
        <img src="img/logon.svg" height="100%" width="100%">
        <span class="tooltiptext">Log on</span>  
               
      </div>   

Login function inside of the commands.js file:

alert("hello");
var login = document.getElementById('btnlogin')
login.addEventListener('click', () => {
var data = {RemoteDN: remoteDN};
//var postData = new Login(RemoteDN)
JSON.stringify(data);


const request = net.request({
  method: 'POST',
  protocol: 'https:',
  hostname:  'fir.nd.local',
  port: 443,
  path: `${baseUrl}login`,
  headers: {
  'Content-Type': 'application/json',
  'Content-Length': data.length
}
  });
  request.on('response', (response) => {
console.log(`STATUS: ${response.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(response.headers)}`);
response.on('data', (chunk) => {
  console.log(`BODY:${chunk}`);
})
response.on('finish', () =>{
  console.log("Request has finished")
})
response.on('end', () => {
  console.log('No more data in response.')
});
response.on('error', (error) =>{
console.log("Error has occured")
})

});

request.write(data);
request.end();

});

The alert message doesn’t even pop up when the login button is clicked. However when I include this javascript code within the html document itself, the alert function is triggered. I don’t want to do this however, as I have a lot of different functions that need to be assigned to each button and i want to keep all of the JS code seperate.

Can anyone give me some advice as to why im unable to access these individual functions from another JS file.

Thanks!

Convert the array with nested arrays to the new array without nested arrays (JavaScript)

I have the array “arrs” with nested arrays like below:

let arrs = ["Apple", ["Peach", "Grape"], [["Pear", "Kiwi"], ["Lemon"]]];

Now, I want to convert the array “arrs” to the new array “newArr” without nested arrays like below:

let newArr = [ "Apple", "Peach", "Grape", "Pear", "Kiwi", "Lemon" ];

I created the code to convert “arrs” to “newArr” without nested arrays:

let newArr = [arrs[0], arrs[1][0], arrs[1][1], arrs[2][0][0], arrs[2][0][1], arrs[2][1][0]];

console.log(newArr); // [ "Apple", "Peach", "Grape", "Pear", "Kiwi", "Lemon" ]

This is the full runnable code:

let arrs = ["Apple", ["Peach", "Grape"], [["Pear", "Kiwi"], ["Lemon"]]];

let newArr = [arrs[0], arrs[1][0], arrs[1][1], arrs[2][0][0], arrs[2][0][1], arrs[2][1][0]];

console.log(newArr); // [ "Apple", "Peach", "Grape", "Pear", "Kiwi", "Lemon" ]

However, I want to make this code simpler, cooler or clever. Are there any ways to do this?

let newArr = [arrs[0], arrs[1][0], arrs[1][1], arrs[2][0][0], arrs[2][0][1], arrs[2][1][0]];

console.log(newArr); // [ "Apple", "Peach", "Grape", "Pear", "Kiwi", "Lemon" ]

Is it possible to highlight a specific segment in a Google Gantt Chart?

I am attempting to make a Gantt chart using the Google Charts library. The library gives the ability to indicate the percentage of a task’s completion, but I am not interested in that feature. Instead, I am interested in highlighting the part of the task that is overdue. Say, a task was due by the 4th of this month, but it is currently the 8th and the task is still not finished. I would like to highlight the area that represents the overdue period.

Is there a way to achieve this functionality?

How to download a file using pure javascript?

I’m trying to make a code in pure javascript (an extension for browser) who be capable to download a file to the source code folder.

Using NPM, the code must be like that:

var http = require('http'),                                                
    Stream = require('stream').Transform,                                  
    fs = require('fs');                                                    

var url = 'http://www.google.com/images/srpr/logo11w.png';                    

http.request(url, function(response) {                                        
  var data = new Stream();                                                    

  response.on('data', function(chunk) {                                       
    data.push(chunk);                                                         
  });                                                                         

  response.on('end', function() {                                             
    fs.writeFileSync('image.png', data.read());                               
  });                                                                         
}).end();

But I can´t use the npm in an extension, so, I need to use pure javascript to make that process, and I didn’t find anything on the web about this.

FadeInLeft effect when changing content

      window.addEventListener('scroll', () => {
    let scrollDistance = window.scrollY;

    if (window.innerWidth > 768) {
        document.querySelectorAll('.section1').forEach((el, i) => {
            if (el.offsetTop - document.querySelector('.nav').clientHeight <= scrollDistance) {
                document.querySelectorAll('.nav a').forEach((el) => {
                    if (el.classList.contains('active')) {
                        el.classList.remove('active');
                    }
                });

                document.querySelectorAll('.nav li')[i].querySelector('a').classList.add('active');
            }
        });
    }
});
body {
  background: gray;
  padding: 100px;
}

.block-2 {
  display: flex;
  flex-direction: row;
  background: white;
  width: 100%;
  padding: 50px;
  height: auto;
}

.section-left {
  position: sticky;
  top: 10px;
  height: 300px;
  /* background: gray; */
  width: 100%;
}

.section-right {
  background: blue;
  width: 100%;
}

.wrap {
  margin: 10px;
  background: red;
}

.content {
  height: 500px;
}

.footer {
  width: 100%;
  height: 700px;
  background: red;
}

.nav {
  position: relative;
  left: 0;
  top: 0;
  width: 100%;
  background-color: white;
  /*     padding: 20px;
*/
}

.nav ul {
  display: flex;
  list-style-type: none;
  flex-direction: column;
  padding: 0;
}

.nav a {
  display: flex !important;
  text-decoration: none;
  color: black !important;
  display: inline-block;
  /*     margin-right: 25px !important;
 */
}

@media screen and (max-width: 1024px) {}

.subtitle {

  opacity: 0;

}



.active {

  opacity: 1;

}

.content1 {
  position: absolute;
  background-color: red;
  /*opacity: 0;*/
  width: 100%;
  height: 300px;
}

.content2 {
  position: absolute;
  background-color: gray;
  /*opacity: 0;*/
  width: 100%;
  height: 300px;
}

.content3 {
  position: absolute;
  background-color: green;
  /*opacity: 0;*/
  width: 100%;
  height: 300px;
}

.content4 {
  position: absolute;
  background-color: blue;
  /*opacity: 0;*/
  width: 100%;
  height: 300px;
}
<body>


  <div class="block-2">
    <div class="section-left">
      <nav class="nav">
        <ul>

          <li><a href="" class="active subtitle">
              <div class="content1">
                <h1>O1</h1>
              </div>
            </a></li>

          <li><a href="" class="subtitle">
              <div class="content2">
                <h1>O2</h1>
              </div>
            </a></li>

          <li><a href="" class="subtitle">
              <div class="content3">
                <h1>O3</h1>
              </div>
            </a></li>

          <li><a href="" class="subtitle">
              <div class="content4">
                <h1>O4</h1>
              </div>
            </a></li>



        </ul>
      </nav>
    </div>
    <div class="section-right">
      <div class="section1 wrap">
        <div class="content">asdf</div>
      </div>
      <div class="wrap section1 ">
        <div class="content">asdf</div>
      </div>
      <div class="wrap section1">
        <div class="content">asdf</div>
      </div>
      <div class="wrap section1">
        <div class="content">asdf</div>
      </div>
    </div>
  </div>
  <div class="footer"></div>
</body>

How can I get the FadeInLeft effect when changing content from .opacity=0 to .opasity=1 in the left side.
I tried to solve this problem with the given script, but it did not work for me.
I am not a cool js expert and I will be glad for your help.
P.S. See this layout in fullscreen.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Thanks

Getting Error – Failed to load resource: the server responded with a status of 403 () for server side rendering of angular app through aws lambda

I have implemented SSR for an angular app with Angular universal and Aws lambda.
The HTML content is loaded but the static files are not rendering.

When i try to indvidually access the js file i get {message:forbidden}

Serverless.yml

service: ngx-serverless-starter
plugins:
  - serverless-offline
provider:
  name: aws
  runtime: nodejs12.x
  lambdaHashingVersion: 20201221
  memorySize: 192
  timeout: 10
package:
  patterns:
    - "!/**"
    - "node_modules/@vendia/serverless-express/**"
    - "dist/**"
    - "lambda.js"
functions:
  api:
    handler: lambda.handler
    events:
      - http: GET /
      - http: GET /{proxy+}

React fine uploader not displaying thumbnails and progress?

I have trouble setting react-fine-uploader to work properly. I’m using react-fine-uploader low level components, and after I choose images thumbnails won’t show although I’ve done everything that docs say.

Here are versions I’m using

"fine-uploader": "^5.16.2",
"fine-uploader-wrappers": "^1.0.1",
"react-fine-uploader": "^1.1.1",

Here is my uploader setup:

const uploader = new FineUploaderTraditional({
options: {
  chunking: {
    enabled: isChunkedUpload,
  },
  request: {
    method: 'POST',
    endpoint: `${process.env.REACT_APP_API_URL}/api/images`,
    customHeaders: { Authorization: `Bearer ${accessToken}` },
    filenameParam: 'name',
    uuidName: 'id',
    totalFileSizeName: 'size',
    inputName: 'image',
  },
  multiple: true,
  callbacks: {
    onComplete: (id: number, name: string, response: object) => {
      console.log(id, name, response);
    },
    onSubmitted: (id: number, name: string) => {
      const newSubmitedFiles = submitedfiles;

      newSubmitedFiles.push(id);
      setSubmittedFiles(newSubmitedFiles);
    },
    onError: (id: number, name: string, errorReason: string, xhr: any) => {
      console.log(id, errorReason, xhr);
    },
  },
},
});

And here are components that I’m using:

     <Dropzone
        className="dropzone"
        style={{ backgroundColor: isDragOver ? 'red' : '' }}
        uploader={uploader}
        multiple
        onDropError={(errorCode: string, errorData: string) => console.log(errorCode, 
        errorData)}
      >
        <span className="dz-message">
          Drop Files Here
        </span>

        {submitedfiles.length ? submitedfiles.map((id) => (
          <div className="dz-preview" key={id}>
            <Thumbnail
              className="dz-image"
              id={id}
              fromServer={false}
              uploader={uploader}
            />
            <CancelButton id={id} uploader={uploader} />
          </div>
        )) : null}
      </Dropzone>

Is it possible to execute a python script through react native expo?

I’m working on a project in react native expo, And i want to Execute a python script inside my react native expo project to run a script, where it will then find a JSON file in my project and use that information to create an excel sheet and email it to the user, that is all it needs to do, I don’t need information to come back to me I just need the file to be executed within my project.

Creating Connection of an existing Mongo DB Database in an existing Docker Container

I want to create a connection from an existing Mongo DB collection to an existing Docker container. Can anybody see it out.

I tried out several syntaxes and approaches but It always give me error.
Thanks in advance!

player-cloud_1  | error  { MongoError: failed to connect to server [cluster0.bgso9.mongodb.net:27017] on first connect [MongoError: getaddrinfo ENOTFOUND cluster0.bgso9.mongodb.net cluster0.bgso9.mongodb.net:27017]
player-cloud_1  |     at Pool.<anonymous> (/app/node_modules/mongodb-core/lib/topologies/server.js:336:35)
player-cloud_1  |     at Pool.emit (events.js:182:13)
player-cloud_1  |     at Pool.EventEmitter.emit (domain.js:442:20)
player-cloud_1  |     at Connection.<anonymous> (/app/node_modules/mongodb-core/lib/connection/pool.js:280:12)
player-cloud_1  |     at Object.onceWrapper (events.js:273:13)
player-cloud_1  |     at Connection.emit (events.js:182:13)
player-cloud_1  |     at Connection.EventEmitter.emit (domain.js:442:20)
player-cloud_1  |     at Socket.<anonymous> (/app/node_modules/mongodb-core/lib/connection/connection.js:189:49)
player-cloud_1  |     at Object.onceWrapper (events.js:273:13)
player-cloud_1  |     at Socket.emit (events.js:182:13)
player-cloud_1  |     at Socket.EventEmitter.emit (domain.js:442:20)
player-cloud_1  |     at emitErrorNT (internal/streams/destroy.js:82:8)
player-cloud_1  |     at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
player-cloud_1  |     at process._tickCallback (internal/process/next_tick.js:63:19)
player-cloud_1  |   name: 'MongoError',
player-cloud_1  |   message:
player-cloud_1  |    'failed to connect to server [cluster0.bgso9.mongodb.net:27017] on first connect [MongoError: getaddrinfo ENOTFOUND cluster0.bgso9.mongodb.net cluster0.bgso9.mongodb.net:27017]' }
player-cloud_1  | error connecting to the database