Seeking Assistance to Enhance Weather Forecast Web App Project [closed]

I am currently working on a project titled “Build-a-Website-using-an-API-with-HTML-JavaScript-and-JSON” available on GitHub at GitHub Repository Link. This project involves creating a simple weather forecast web app using HTML, JavaScript, and JSON with API integration to display real-time weather data for various locations in an easy-to-use and informative manner.

While I have made progress on the project and have established the fundamental structure, including essential files like HTML, CSS, and JavaScript, I am encountering challenges in implementing certain functionalities to enhance user experience and improve the overall performance of the application.

Specifically, I am seeking assistance with the following aspects:

  1. Enhancing the visual design and layout of the web app using CSS.
  2. Adding interactive features to make the weather data more engaging for users.
  3. Optimizing the codebase for better performance and efficiency.

If you have expertise in web development, API integration, or working with weather data, I would greatly appreciate any guidance, suggestions, or code snippets that could help me address these challenges and successfully complete the project.

Thank you in advance for your valuable input and support. Any advice or recommendations will be highly appreciated.

Warm regards,
zwanski

I attempted to implement a new feature in my web application by adding a weather forecast module using an API. I expected the module to display real-time weather data for different locations. However, after integrating the API and updating the code, the weather information did not load correctly,

showing blank results instead. I need assistance in troubleshooting this issue and ensuring the weather data is displayed accurately.

How to Call Global Functions from Modules and Maintain Modularity?

I am using Svelte with Ultralight, communication is handled with JavaScriptCore so Ultralight set / call functions on the global javascript object (which I believe is window). Now I want to call these functions in my svelte app, but I am using modules and so I can’t set / use global functions.

So for now I am stuck to something like this :

CppInterop.js module :

import { notification } from "./lib/store";

// Expose store globally
window.store = {
    notification
}

// Expose the C++ functions
export default {
    test: () => window.Test()
}

cpp.js that I include directly in my html file with <script src="/cpp.js"></script> :

// From JS to C++
window.Test = Test;

// From C++ to JS
function notification(message, type)
{
    window.store.notification.notify(message, type);
}

Interop doesn’t seems to work then I try to access the functions via window so that’s why I do window.Test = Test. What I would like is to call / define global function while still having access to modules (to call my own functions and stores), is that possible ?

axios.post do not return anything when api call is made within backend

I’m setting up a account validation page with the following approach. An apiGateway.ts where the request from POSTMAN or UI would hit. The backend is setup at localhost:3001 and here is the code of apiGateway.ts, you can ignore the login methods using fetch, my interest is register here.

import express from "express";
import cors from "cors";
import carRouter from "./Car/Router";
import reservationRouter from "./Reservation/Router";
import userRouter from "./User/Router";
import axios from "axios";

const BASE_RENTAL_URL = "http://localhost:3001/user";
const app = express();
app.use(cors());
app.use(express.json());

app.use("/rentals", carRouter);
app.use("/mybookings", reservationRouter);
app.use("/user", userRouter);

app.post("/login", async (req, res) => {
  try {
    const { email, mobile, password } = req.body;
    let fetchUserToken;
    if (mobile) {
      fetchUserToken = await fetch(BASE_RENTAL_URL + `/mobilelogin`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ mobile: mobile }),
      });
    } else {
      fetchUserToken = await fetch(BASE_RENTAL_URL + `/emaillogin`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ email: email, password: password }),
      });
    }
    const token = fetchUserToken?.json();
    res.status(200).json({ token });
  } catch (error: any) {
    res.status(500).json({ message: error.message });
  }
});

app.post("/register", async (req, res) => {
  try {
    const response = await axios.post(
      "http://localhost:3001/user/register",
      req.body
    );
    console.log("got it", response.data);
    res.status(200).json({ token: response.data });
  } catch (error: any) {
    console.log("hello", error.message);
    res.status(500).json({ message: error.message });
  }
});

axios.interceptors.request.use((request) => {
  console.log("Request URL:", request.url);
  return request;
});

export default app;

Here is the code for the User router.ts

import express from "express";
import Controller from "./Controller";

const router = express.Router();

export default () => {
    router.get("/user", Controller.findAllUsers);
    router.post("/user/mobilelogin", Controller.handleLoginThroughMobile);
    router.post("/user/emaillogin", Controller.handleLoginThroughEmail);
    router.post("/user/register", Controller.handleRegistration);
    return router;
}

and here is the Controller.ts for User

import { Request, Response } from "express";
import Repository from "./Repository";
const bcrypt = require("bcrypt");
const jwt = require('jsonwebtoken');

class Controller {

  async findAllUsers(req: Request, res: Response, next: any) {
    try {
      const users = await Repository.findAll();
      res.status(200).json(users);
    } catch (error: any) {
      res.status(500).json({ message: error.message });
    }
  }

  async handleLoginThroughMobile(req: Request, res: Response, next: any) {
    try {
      const { mobile } = req.body;
      let user = await Repository.findUserByMobile(mobile);
      if (!user) {
        res.status(401).json({ message: "User doesn't exist" });
        return;
      }
      const token = jwt.sign({ email: user[0].email }, 'secret', { expiresIn: '1h' });
      res.status(200).json({ token });
    } catch (error: any) {
      res.status(500).json({ message: error.message });
    }
  }

  async handleLoginThroughEmail(req: Request, res: Response, next: any) {
    try {
      const { email, password } = req.body;
      let user = await Repository.findUserByEmail(email);
      if (!user) {
        res.status(401).json({ message: "User doesn't exist" });
        return;
      }
      const isValidPassword = await bcrypt.compare(password, user[0].password);
      if (!isValidPassword) {
        res
          .status(401)
          .json({ message: "Credentials are not correct. Try again" });
        return;
      }
      const token = jwt.sign({ email: user[0].email }, 'secret', { expiresIn: '1h' });
      res.status(200).json({ token });
    } catch (error: any) {
      res.status(500).json({ message: error.message });
    }
  }

  async handleRegistration(req: Request, res: Response, next: any) {
    try {
      console.log("hits");
      const { email, mobile, licenseNumber } = req.body;
      let userWithSameEmail = await Repository.findUserByEmail(email);
      let userWithSameMobile = await Repository.findUserByMobile(mobile);
      let userWithSameLicenseNumber = await Repository.findUserByLicenseNumber(
        licenseNumber
      );
      if (
        userWithSameEmail ||
        userWithSameMobile ||
        userWithSameLicenseNumber
      ) {
        res.status(401).json({
          message: "User with same email or mobile or license number exists",
        });
        return;
      }
      const user = await Repository.create(req.body);
      const token = jwt.sign({ email: user.email }, 'secret', { expiresIn: '1h' });
      res.status(200).json({ token });
    } catch (error: any) {
      console.log("error", error);
      res.status(500).json({ message: error.message });
    }
  }
}

export default new Controller();

Please let me know why am I not able to get the token or any response for that matter when I make a request from POSTMAN to ‘http://localhost:3001/register’. My understanding is that when i hit ‘http://localhost:3001/register’ from POSTMAN, it would trigger the api.post(‘register’) defined in apiGateway.ts, and then it further makes a call to ‘http://localhost:3001/user/register’ and this should trigger the Controller method for handling Registration. But I don’t see the flow hitting the controller, and the postman request neither returns success or is failed.

How do I fix (or ignore) a TypeScript error that’s inside a HTML template?

I have the following HTML template in a VueJS-2 component:

<template>
  <div>
    <v-data-table
      :headers="headers"
      :items="items"
      :caption="label"
      dense
      hide-default-footer
      hide-default-header
    >
      <template v-slot:item.name="props">
        <MiniTextField
          :value="props.item.name"
          dense
          single-line
          hide-details
          prepend-icon="mdi-account"
          @change="(newValue) => crewEntryUpdated(newValue, props)"
        ></MiniTextField>
      </template>
    </v-data-table>
  </div>
</template>

The following line gives an error:

@change="(newValue) => crewEntryUpdated(newValue, props)"

The error is:

src/components/CrewTable.vue:18:21 - error TS7006: Parameter 'newValue' implicitly has an 'any' type.

18           @change="(newValue) => crewEntryUpdated(newValue, props)"
                       ~~~~~~~~

Adding a type-hint to the function is invalid syntax and breaks the compilation. So the following does not work. It leads to:

7:54:44 AM [vite] Internal server error: Unexpected token, expected "," (1:395)
  Plugin: vite:vue2
  File: /workspaces/frontend/src/components/CrewTable.vue:1:395
  16 |            hide-details
  17 |            prepend-icon="mdi-account"
  18 |            @change="(newValue: string) => crewEntryUpdated(newValue, props)"
     |                   ^
  19 |          ></MiniTextField>
  20 |        </template>

Changing it to a multi-line code-block breaks the event-handler silently. TS no longer complains, but the handler is also not called. So the following also does not work:

          @change="
            // @ts-ignore
            (newValue) => crewEntryUpdated(newValue, props)
          "

I don’t want to ignore the whole file. So how can I modify my code to make TS happy?

Is it possible to use nodemon to watch file changes (but not execute a script)?

I am looking for a setup where I can listen to file changes but also then know what files were changed.

I see that nodemon can be executed in two ways:

  • As a CLI (nodemon ./server.js localhost 8080)
  • or “Using nodemon as a module” (var nodemon = require('nodemon');)

I am not sure if this is possible, but I have two questions:

1) Is it possible to use the CLI version, but somehow to send in the file that got changed as an argument?

For example:

nodemon --ext js --exec "node myscript.js $file"

Where $file is the file that was changed.

or 2) Is it possible to nodemon as a module, but not specify the script?

For example (myscript.js):

const nodemon = require('nodemon');

nodemon({
    ext: 'js',
    verbose: true,
    script: undefined,
});

nodemon.on('start', function () {
    console.log('App has started');
}).on('quit', function () {
    console.log('App has quit');
    process.exit();
}).on('restart', function (files) {
    console.log('App restarted due to: ', files);
});

Where script is undefined or omitted.

But this doesn’t work. Nodemon doesn’t listen to anything, unless i provide a script?

But I don’t want it to execute a second script – I already have my own script file (myscript).


Any suggestions on any setup where I can (in node) listen to file changes, but also easily what files were changed.

I want make JS toggle button.. How Can I Fix It?

HTML

<div class="icon-menu">
      <img src="../images/menu.png" id="navMenu" onclick="changeToCross()">
</div>

JS

function changeToCross() {
    let menu = document.getElementById('navMenu');
    let src = '../images/menu.png'; 

    if (menu.src === src) {
        menu.src = '../images/close.svg';
    } else {
        menu.src = src;
    }
}

I want to change image source when it will be clicked but this code isn’t working. How can I fix it

how to call python function in javascript everionment on selenium

has a way to call python function from the web page ?

or may i have a way inject python methods to selenium, it’s can used by javascript call

i wan’t get some message from ajax request result, if js can call python method,

def test():
   pass
options = Options()
browser = webdriver.Chrome(options)
// it's have a way call python test method ?
window.test() // ??

State that should have been updated in ReactNative is not updated

I want to save the input text to a state and use handleSave to create an item, but when I run handleSave, the console only outputs {name: “”,description: “”,} before it is updated.
The console.log with useEffect outputs the updated state for each input, but I still cannot get the updated state with handleSave.
I would appreciate it if you could tell me if you know how to improve it.

CreateItem.tsx

import React, { useState, useEffect } from "react";
import { styles } from "style/style";
import CloseIcon from "icons/Close";
import InputText from "utils/InputText";

const CreateItem = ({ navigation }: { navigation: any }) => {

  const [item, setItem] = useState({
    name: "",
    description: "",
  });

  const handleInputChange = (name: string, value: string) => {
    setItem({ ...item, [name]: value });
  };

  useEffect(() => {
    navigation.setOptions({
      headerLeft: () => (
        <TouchableOpacity
          onPress={() => navigation.goBack()}
          style={{
            padding: 12,
            margin: -12,
          }}
        >
          <CloseIcon size={24} color="#000" />
        </TouchableOpacity>
      ),
      headerRight: () => (
        <Button title="save" onPress={handleSave} color="#000" />
      ),
    });
  }, [navigation]);

  useEffect(() => {
    console.log(item);
  }, [item]);

  const handleSave = () => {
    console.log(newItem); 
  };

  return (
    <View style={styles.container}>
          <View style={styles.formGroup}>
            <Text style={styles.formLabel}>Name</Text>
            <InputText
              name="name"
              placeholder="Enter Name"
              value={item.name}
              onChangeText={(text) => handleInputChange("name", text)}
            />
          </View>
          <View style={styles.formGroup}>
            <Text style={styles.formLabel}>description</Text>
            <TextInput
              style={styles.formInputMultiLine}
              placeholder="Enter description"
              multiline={true}
              value={item.description}
              onChangeText={(text) => handleInputChange("description", text)}
            />
          </View>
    </View>

InputText.tsx

import React, { useState } from "react";
import { View, Text, TextInput } from "react-native";
import { styles } from "../style/style";

interface InputTextProps {
  name: string;
  placeholder?: string;
  keyboardType?: "default" | "numeric" | "email-address" | "phone-pad";
  value?: string;
  onChangeText?: (text: string) => void;
}

const InputText = ({
  name = "name",
  placeholder = "Enter text",
  keyboardType = "default",
  value = "",
  onChangeText,
}: InputTextProps) => {
  const [borderColor, setBorderColor] = useState("#EFEFEF");

  const onFocus = () => {
    setBorderColor("#c09969");
  };

  const onBlur = () => {
    setBorderColor("#EFEFEF");
  };

  return (
    <View>
      <TextInput
        style={[styles.formInput, { borderBottomColor: borderColor }]}
        placeholder={placeholder}
        keyboardType={keyboardType}
        value={value}
        onChangeText={onChangeText}
        onFocus={onFocus}
        onBlur={onBlur}
      />
    </View>
  );
};

export default InputText;

bcrypt.compare receiving illegal argument string, undefined [closed]

I am creating a web app, and using a mysql database, when i ty to use the bcryptjs library to compare a hash password with the data gathered from a login form, i get that the bcrypt.compare function is receiving string,undefined

this is in my controller, this handles the post login, some parts are in spanish, contrasena = password,

exports.post_login = (request, response, next) => {
    const {email, password} = request.body;
    if(!email || !password){
        return response.render("login", {error: "Llena todos los campos"})
    }

    Usuarios.findByEmail(email)
        .then(user => {
            if (user) {
                // Use bcrypt.compare to check if passwords match
                console.log(user);
                bcrypt.compare(password, user.contrasena)
                    .then(doMatch => {
                        if (doMatch) {
                            request.session.isLoggedIn = true;
                            request.session.user = user;
                            return request.session.save(err => {
                                response.redirect('/');
                            });
                        } else {
                            response.redirect('/users/login');
                        }
                    })
                    .catch(err => {
                        console.error('Error during login', err);
                        response.redirect('/users/login');
                    });
            } else {
                response.redirect('/users/login');
            }
        })
        .catch(err => {
            console.error('Error during login', err);
            response.redirect('/users/login');
        });

};

here is my code from the model.js file, which saves the user info that is received from a signup form

    save() {
        const userData = {
            idUsuario: this.idUsuario,
            IdRol: this.idRol,
            Nombre: this.nombre,
            Contrasena: this.contrasena,
            Correo: this.email,
        }

        return bcrypt.hash(userData.Contrasena, 12)
            .then((hashedPassword) => {
                userData.Contrasena = hashedPassword;
                const values = Object.values(userData);
                return db.execute('INSERT INTO usuario (idUsuario,IdRol,Nombre,Contrasena,Correo) VALUES (?,?,?,?,?)',values);
            })
            .then(([result]) => {
                console.log('Usuario Guardado:', result);
                return result; // Return the ResultSetHeader
            })
            .catch(err => {
                console.log('Error guardando usuario:', err);
                throw err;
            });
    } 


    static findByEmail(email) {
        return db.execute('SELECT * FROM usuario WHERE Correo = ?', [email])
            .then(([rows]) => {
                if (rows.length > 0) {
                    const userData = rows[0];
                    console.log('Esto es lo que esta recuperando de la base de datos: ', userData)
                    const user = new Usuarios(userData.Nombre, userData.Correo, userData.Contrasena, userData.idUsuario, userData.IDRol);
                    console.log('Esto es lo que se va a retornar: ',user);
                    return { user: user, passwordMatch: true }; // Return user data with passwordMatch true
                }
                return { user: null, passwordMatch: false }; // Return null user and passwordMatch false if user not found
            })
            .catch(err => {
                console.error('Error fetching user by email from database:', err);
                throw err;
            });
    }

i have tried printing the users that are retrieved from the database, the info given from the login form, and they all appear to be in order, the database is in fact saving the user info correctly

How to call a function in javascript for google chrome extension? [duplicate]

I am learning programming and I just started to create a simple google chrome extension.

I am trying to call a function from another function, but I get this error from chrome console.

Uncaught ReferenceError: check is not defined
at alertMessage (:2:5)
at :5:5

My program starts by clicking my tab on context menu.
Here is my code

chrome.runtime.onInstalled.addListener(function (details) {

    const parent = chrome.contextMenus.create({
      id: "alert",
      title: "alertChrome",
      contexts: ["all"],
    });
  });
  
  chrome.contextMenus.onClicked.addListener((info, tab) => {
    switch (info.menuItemId) {  
      case "alert":
        chrome.scripting.executeScript({
          target: { tabId: tab.id },
          function: alertMessage,
        });
        break;
      }
  });
  
  
  function alertMessage() {
    if(check){
    alert('Hello World');
    }
  }
  
  function check(){
    return true;
  }

Why function check() cannot be called from alertMessage?
Is there a way to make this work?

I tried running on google chrome console (pasting the code above on console) and it worked, so I believe it is a problem caused by chrome.
I did a lot of research, but I could not find any article that mentions about this simple problem, so I think I am missing something basic.

Spring boot JSON parse error: Unexpected character error

I have a spring boot application where I get request text and files as form-data

If I send text data in code format, I get this error

JSON parse error: Unexpected character ('b' (code 98)): was expecting comma to separate Object entries
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:406) ~[spring-web-6.0.10.jar:6.0.10]

The request value is like this

{
    "content": "      #backgroundImage {
        border: none;
        height: 100%;
        pointer-events: none;
        position: fixed;
        top: 0;
        visibility: hidden;
        width: 100%;
      }
      [show-background-image] #backgroundImage {
        visibility: visible;
      }
    </style>
  </head>
  <body>
    <iframe id="backgroundImage" src=""></iframe>
    <ntp-app></ntp-app>
    <script type="module" src="new_tab_page.js"></script>
    <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
    <link rel="stylesheet" href="chrome://theme/colors.css?sets=ui,chrome">
    <link rel="stylesheet" href="shared_vars.css">
  </body>
</html>",
    "title": "test1"
}

At first I got

JSON parse error: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value

But this one is fixed after using

jackson:
  parser:
    allow-unquoted-control-chars: true

in application.yml

But I don’t know how to deal with this Unexpected character error

Is client-side responsible to parse JSON type

or

server-side should parse the JSON type data?

Checking for bugs

    function captureArguments(arg1, arg2, arg3) {
        if (
//first section
          (arg1 === null && arg2 === null && arg3 === null) ||
          arguments.length === 0
        ) {
          return "Nothing Passed";
        } else if (
          typeof arg1 === typeof arg2 &&
          typeof arg2 === typeof arg3
        ) {
          return "All the same";
        }
//second section
        if (arg1 !== null && arg2 === null && arg3 === null) {
          return alpha;
        }
        if (arg1 === null && arg2 !== null && arg3 === null) {
          return second;
        }
        if (arg1 === null && arg2 === null && arg3 !== null) {
          return gamma;
        }
//third section
        if (arg1 === "string" && arg2 === "string" && garg3 === "string") {
          return {
            first: arg1,
            second: arg2,
            third: arg3
        }
      }

My goal is to 1. check if an argument is being passed, 2. if ex captureArguments(“first”, null, null) then it return the value “first”, 3. if all parameters are of string value for it to return it ex. captureArguments(“ball”, “hill”, “water”) returns {first: “ball”, second “hill, third:”water}. Third section keeps returning undefined

Playwright JS: Getting an error when debugging using line numbers

Playwright provides the option to use line numbers as well as the filename for debugging purpose via the command line.
As per documentation the below format needs to be used for debugging using line numbers
npx playwright test example.spec.ts:10 –debug

Note: I’ve tried the same but got an error.(Using a .js file)

Playwright Version: 1.41.2

Steps to reproduce
I’ve a file named UIBasicsTest.spec.js
And when I try to run the below command to open the debug mode, it throws an error
npx playwright test UIBasicsTest.spec.js:4 –debug

Expected behavior
I expect the debug functionality to work for specific lines as well just as mentioned in the official documentation.

Actual behavior
Error:
Error: No tests found.
Make sure that arguments are regular expressions matching test files.
You may need to escape symbols like “$” or “*” and quote the arguments.

Intl.DateTimeFormat() – return weekday as number?

It appears Intl.DateTimeFormat() only accepts "narrow", "short", "long" as the weekday option. I would like it to return as a number. i.e. Sunday = 0, Monday = 1 and so on. If I’m correct in reading “numerical” is not an option, what would be an easy way to return the value weekday as a number?

const day = new Intl.DateTimeFormat('en-US', {
    timeZone: America/New_York,
    weekday: 'long',
});

const weekdayNumber = ["0", "1", "2", "3", "4", "5", "6"];
const dayNumber = weekdayNumber[day.format(now)];
console.log('Weekday: ' + dayNumber); // returns error

Grouping HTML elements by their class name

Say I have HTML that looks a bit like this

<div>
  <p>Text 1</p>
  <p class="foo">Text 2</p>
  <p>Text 3</p>
  <p>Text 4</p>
  <p>Text 5</p>
  <p>Text 6</p>
  <p class="foo">Text 7</p>
  <p class="foo">Text 8</p>
  <p>Text 9</p>
  <p class="foo">Text 10</p>
  <p>Text 11</p>
  <p class="foo">Text 12</p>
  <p class="foo">Text 13</p>
  <p class="foo">Text 14</p>
  <p class="foo">Text 15</p>
  <p>Text 16</p>
</div>

Any p element with the class “foo” gets wrapped in a div but any contiguous p elements with the class “foo” get wrapped into the same div as the first p (in the series). So the above HTML would end up looking like

<div>
  <p>Text 1</p>
  <div class="wrap">
    <p class="foo">Text 2</p>
  </div>
  <p>Text 3</p>
  <p>Text 4</p>
  <p>Text 5</p>
  <p>Text 6</p>
  <div class="wrap">
    <p class="foo">Text 7</p>
    <p class="foo">Text 8</p>
  </div>
  <p>Text 9</p>
  <div class="wrap">
    <p class="foo">Text 10</p>
  </div>
  <p>Text 11</p>
  <div class="wrap">
    <p class="foo">Text 12</p>
    <p class="foo">Text 13</p>
    <p class="foo">Text 14</p>
    <p class="foo">Text 15</p>
  </div>
  <p>Text 16</p>
</div>

I know how to get elements with the class “foo” but I’m lost trying to work out if there are contiguous p.foo elements that I need to wrap in the same div.

Should I just iterate through the nodes in the container div, append a wrapper div when I find a p.foo and just keep appending contiguous p.foo elements? I’ve had a few goes but it seems to fail for different ways I sort the original p elements.