q.jpg:1 Failed to load resource: the server responded with a status of 404 (Not Found)

The image files are at the correct path. Still the console shows error: GET http://127.0.0.1:5500/images/q.jpg 404 (Not Found) and also he error in the title sometimes. Please tell the solution

My HTML file:


<!DOCTYPE html>
<link rel="stylesheet" href="./style.css">

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="code.js"></script>s
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <div id="entries" class="container">    
        <input type="number" id="a" name="a" placeholder="A" on click="sum">x² +</input><br>
        <input type="number" id="b" name="b" placeholder="B" on click="sum">x +</input><br>
        <input type="number" id="c" name="c" placeholder="C" on click="sum"></input><br>
        <button onclick= "solvequadratic()" id="btn"> Find roots </button>
    </div>
    <div id="result"></div>
    <div id="dvImage" style="height: 308px; width: 410px">
    </div>

</body>
</html>

and JS file

    var images = ["q.jpg", "q1.jpg"];
    $(function () {
        var i = 0;
        $("#dvImage").css("background-image", "url(images/" + images[i] + ")");
        setInterval(function () {
            i++;
            if (i == images.length) {
                i = 0;
            }
            $("#dvImage").fadeOut("slow", function () {
                $(this).css("background-image", "url(images/" + images[i] + ")");
                $(this).fadeIn("slow");
            });
        }, 5000);
    });
    

Can we call one test case from the another test case in Cypress?

I am doing automation testing using Cypress with JavaScript.

I have to manage a test case for add, search and edit user. I have created a different test case for each. After adding user, I verified recent created user by searching it. I also search same user before to edit it.

In Cypress, test cases run in a sequence. My first case for ‘add user’, second for ‘Search user’ and last one for ‘Edit user’. After adding it automatically perform search actions. But before edit, I have to call all functions which are used in a ‘Search’ test case. I am using the POM framework.

Here is the code I have written:

describe('User management', function(){
    it('Add user', function(){
        obj.clickOnAddUserButton()
        obj.fillDetails()
        obj.clickOnSaveButton()
    })
    it('Search user', function(){
        obj.searchName()
        obj.searchRole()
        obj.verifyName()
        obj.verifyRole()
    })
    it('Edit user', function(){
        obj.searchName()
        obj.searchRole()
        obj.verifyName()
        obj.verifyRole()
        obj.editUser()
    })
})

Is it possible to call it() from the other it(), like a function we call?

I tried the following solution to understand but I was fail: Cypress – have 1 test call another test and run it

I also go through the following link which doesn’t help me:
How to call the common test case in other test case in protractor

Let give me an example what I want exactly.

describe('User management', function(){
    it('Add user', function(){
        obj.clickOnAddUserButton()
        obj.fillDetails()
        obj.clickOnSaveButton()
    })
    it('Search user', function(){
        obj.searchName()
        obj.searchRole()
        obj.verifyName()
        obj.verifyRole()
    })
    it('Edit user', function(){
        //Here I want to call it() instead of calling same functions here
        //i.e. it('Search user')
        obj.editUser()
    })
})

Email not sending smtpJS

Trying to send an email from an HTML Form. I have followed the instructions to use smtpJS and elastic email. When I click the submit button on my form I just get an alert that says “OK” and a status of 200. However, I do not receive an email. Has anyone else ran into this?

  function sendEmail()
  {
    Email.send({
      SecureToken : "secure token here",
      To : "[email protected]",
      From : "[email protected]",
      Subject : "This is the subject",
      Body : "And this is the body"
     }).then(
      message => alert(message)
     );  
  }

How to name bookmarks based on text in pdf?

I have a pdf with numerous pages. I want to create bookmarks for groups of pages based on the userid that is in the pdf. So one bookmark per userid. I would like to do this using JavaScript, but not sure how to go about this.

I not sure where to start.

How to Count Number of Key : Values pair for given Key for JSON

How to know __metadata and ItemToEkbeNav are root elements for its children (Key : Value) pair?

I tried many options Object.keys().length, Array.isArray(), but did not get the proper output.

For Object.keys('__metadata').length = 10, but I need it as 3 (id, uri, type).

For Object.keys('Ebeln').length = 10, but I need it as 1.

For Object.keys('ItemToEkbeNav') I want to know it’s a root element for its childern.

 "results": [
        {
            "__metadata": {
                "id": "https:// ,
                "uri": "https:// ,
                "type": "YGW"
            },
            "Ebeln": "5200000719",
            "Ebelp": "00010",
            "Loekz": "111",
            "Statu": "222",
            "ItemToEkbeNav": {
                "__deferred": {
                    "uri": "https: 
                }
            }
        }
  ]

Control code character not working, italian fiscal code (codice fiscale)

I was making a tax code calculator, but the check character is wrong! Example if I were to enter name: Mario, surname: Rossi, born: Milan, sex: male, province: MI, birth: 01-01-1980. It should read: RSSMRA80A01F205X, instead it reads: RSSMRA80A01F205K. Here is the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Calcolatore codice fiscale</title>
</head>
<body>
    <div class="container">
        <div class="input">
            <h1 id="titolo">Calcolatore Codice Fiscale</h1>
            <h3>Nome</h3>
            <input id="nome" type="text" required placeholder="Inserisci il nome" >
            <h3>Cognome</h3>
            <input type="text" id="cognome" required placeholder="Inserisci il cognome" >
            <h3>Data Di Nascità</h3>
            <input type="date" name="dataDiNascita" id="dataNascita">
            <h3>Sesso</h3>
            <select name="sesso" id="sesso">
                <option value="maschio">Maschio</option>
                <option value="femmina">Femmina</option>
            </select>
            <br>
            <h3>Provincia</h3>
            <input type="text" id="provincia" required placeholder="Provincia">
            <h3>Luogo Di Nascità</h3>
            <input type="text" name="luogoNascita" id="luogoNascita" placeholder="Luogo di Nascità">
            <br>
            <button id="inserisciDatiBtn">Inserisci Dati</button>
        </div>
    </div>
    <script src="main.js"></script>
</body>
</html>

function calcolaCodiceFiscale() {
  const cognome = document.getElementById('cognome').value.toUpperCase();
  const nome = document.getElementById('nome').value.toUpperCase();
  const dataNascita = new Date(document.getElementById('dataNascita').value);
  const sesso = document.getElementById('sesso').value;
  const luogoNascita = document.getElementById('luogoNascita').value.toUpperCase();
  const provincia = document.getElementById('provincia').value.toUpperCase();

  const annoNascita = dataNascita.getFullYear() % 100;
  const meseNascita = dataNascita.getMonth() + 1;
  const giornoNascita = dataNascita.getDate();

  const vocali = ['A', 'E', 'I', 'O', 'U'];
  const consonanti = 'BCDFGHJKLMNPQRSTVWXYZ';
  
  // Calcola i caratteri per il cognome
  let caratteriCognome = '';
  for (const char of cognome) {
    if (consonanti.includes(char)) {
      caratteriCognome += char;
      if (caratteriCognome.length === 3) break;
    }
  }

  if (caratteriCognome.length < 3) {
    for (const char of cognome) {
      if (vocali.includes(char)) {
        caratteriCognome += char;
        if (caratteriCognome.length === 3) break;
      }
    }
  }

  while (caratteriCognome.length < 3) {
    caratteriCognome += 'X';
  }

  // Calcola i caratteri per il nome
  let caratteriNome = '';
  for (const char of nome) {
    if (consonanti.includes(char)) {
      caratteriNome += char;
      if (caratteriNome.length === 3) break;
    }
  }

  if (caratteriNome.length < 3) {
    for (const char of nome) {
      if (vocali.includes(char)) {
        caratteriNome += char;
        if (caratteriNome.length === 3) break;
      }
    }
  }

  while (caratteriNome.length < 3) {
    caratteriNome += 'X';
  }

  // Calcola i caratteri per la data di nascita e sesso
  let caratteriDataSesso = '';
  const giornoSesso = sesso === 'femmina' ? giornoNascita + 40 : giornoNascita;
  caratteriDataSesso += annoNascita.toString().padStart(2, '0').slice(-2);
  
  const mesi = {
    1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', 6: 'H', 7: 'L', 8: 'M', 9: 'P', 10: 'R', 11: 'S', 12: 'T'
  };
  
  caratteriDataSesso += mesi[meseNascita];
  
  caratteriDataSesso += giornoSesso.toString().padStart(2, '0');

  // Genera un codice di 3 numeri random se la provincia non è presente
  let codiceNumerico = '';
  
  const codiciCitta = {
    'BS': 'B157' , 'MI': 'F205' , 'NA': 'F839' , 'RM': 'H501' , 'VE': 'L736'
  };

  if (provincia in codiciCitta) {
    codiceNumerico = codiciCitta[provincia];
  }else{
    codiceNumerico = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  }

  // Calcola il codice fiscale senza il carattere di controllo
  const codiceFiscaleParziale = caratteriCognome + caratteriNome + caratteriDataSesso + codiceNumerico;

  // Calcola il carattere di controllo
  const carattereControllo = calcolaCarattereControllo(codiceFiscaleParziale);

  // Visualizza il codice fiscale risultante
  const codiceFiscaleCompleto = codiceFiscaleParziale + carattereControllo;
  alert("Codice Fiscale: " + codiceFiscaleCompleto);
}

function calcolaCarattereControllo(codiceFiscaleParziale) {
  const caratteriPari = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  const caratteriDispari = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let somma = 0;

  for (let i = 0; i < 15; i++) {
    if (i % 2 === 0) {
      somma += caratteriPari.indexOf(codiceFiscaleParziale[i]);
    } else {
      somma += caratteriDispari.indexOf(codiceFiscaleParziale[i]);
    }
  }

  const carattereControllo = caratteriDispari[somma % 26];
  return carattereControllo;
}

const inserisciDati = document.getElementById('inserisciDatiBtn');
inserisciDati.addEventListener('click', calcolaCodiceFiscale);

This is how it works: tax code

I tried using other ways but nothing worked.

Javascript sort array but each key is unique

For a chess app, I need to sort this array based on the value in javascript:

[e7e5: '-42', g8f6: '-16', h7h6: '-38', c8d7: '-29']

Something along the lines:

Moves.sort((a,b)=>a.?? > b.??))

Whereby, the missing bit to get it to work is the ??.

Have look on the net for a solution, but could not find.

Any help would be appreciated.

David

React Native ImagePicker causes Invalid hook call

I’m trying to select a picture from the gallery via ImagePicker.
It doesn’t matter which ImagePicker i try, ‘expo-image-picker’ or ‘react-native-image-crop-picker’ I always face the error

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

I dont try to call a hook outside a function..
But when I select a picture I return a right response:

{"cropRect": {"height": 2242, "width": 1682, "x": 1155, "y": 0}, "height": 400, "mime": "image/jpeg", "modificationDate": "1695307585000", "path": "file:///storage/emulated/0/Android/data/com.clip/files/Pictures/4e0ae973-fd55-43ba-9758-34119952b375.jpg", "size": 103041, "width": 300}

The code looks like:

import React from 'react'
import { NativeModules, StyleSheet, View, Text, ImageBackground, Pressable} from "react-native";
import { Feather } from '@expo/vector-icons'; 
import ImagePicker from 'react-native-image-crop-picker';


export default function ProfileScreen({ navigation, route}){
   
    const [image, setImage] = React.useState(null);
   
    async function changeProfilePicture(){
        await ImagePicker.openPicker({
            width: 300,
            height: 400,
            cropping: true
        }).then(image => {
            console.log(image);
        }); 
    }

    return (
        <View style={styles.ViewStyle}>             

                    <Pressable style={styles.PressableProfilePictureStyle} 
                               onPress={()=> changeProfilePicture()}>
                        <Feather name="edit" size={30} color="black" />
                    </Pressable>
            </View>
    </View>
);

}

Get current time in JavaScript when the browser retrieves a cached html page

I’m having a html-page which is cachable. At the end of the page, I put:

<script>
    console.log(Date.now());  
</script>

I load the page: The console shows 1695306780514.
I follow a link on that page.
I press the back-button of the browser.

My assumption was that I now get the current datetime, a little bit later than the previous one.

But:

  • Chrome (on Windows) shows the same 1695306780514, not the current datetime in console.
  • Firefox (on Windows) shows just nothing in console.

I even tried

$(document).ready(function() {
    console.log(Date.now());
});   

or

var showDate = function(){
    console.log(Date.now());
};
window.setTimeout(showDate, 1000);

but the effect is exactly the same.

How can I make sure the javascript is executed again and uses the correct datetime?

Horizontal scroll bar js html

I’m trying to create a horizontal scroll bar which will therefore replace the browser default one (the one on the right), which shows the position of the page. But I can’t find anything on the web. Can someone help me?

I have only found scrollbars to insert into a div to scroll some text

Cannot get props in nextjs app router passed from server page to client component

I am using app router with Nextjs v13.5
I have a /dashboard page (server component) and ApiKeyOption client component inside it. When I pass props from dashboard page to ApiKeyOption component, I am getting undefined.

Here is /dashboard page:

import ApiKeyOptions from "@/components/client-compoents/ApiKeyOptions";
import KeyStatics from "@/components/client-compoents/KeyStatics";
import RequestApiKey from "@/components/client-compoents/RequestApiKey";
import authoptions from "@/lib/authOptions";
import { db } from "@/lib/db/db";
import { getServerSession } from "next-auth";
import React from "react";

const page = async () => {
  const session = await getServerSession(authoptions);
  const apiKey = await db.apiKey.findFirst({
    where: {
      userId: session?.user.id,
      enabled: true,
    },
  });

  return (
    <section className="container mt-24 sm:px-16 ">
      <div className="flex w-full justify-between items-center">
        <h2>
          Howdy, <span className="font-medium">{session?.user.name} ?</span>
        </h2>
        <img
          src={session?.user.image!}
          alt={session?.user.name as string}
          width={45}
          height={45}
          referrerPolicy="no-referrer"
          className="border-2 border-solid border-slate-500 p-[2px] rounded-full"
        />
      </div>
      {apiKey && (
        <div className="flex items-center gap-x-4 mt-2">
          <h2 className="font-light text-sm p-2 bg-[rgba(0,0,0,0.15)] w-fit rounded-md">
            {apiKey?.key}
          </h2>
          <ApiKeyOptions key={"whatever"} />
        </div>
      )}
      <div className="flex justify-center mt-6">
        {apiKey ? <KeyStatics /> : <RequestApiKey />}
      </div>
    </section>
  );
};

export default page;**

**And ApiKeyOptions client component:

"use client";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { DotsVerticalIcon } from "@radix-ui/react-icons";
import { useToast } from "../ui/use-toast";

export default function ApiKeyOptions({ key }: { key: string }) {
  console.log(key);
  const { toast } = useToast();

  function copyText(text: string) {
    navigator.clipboard.writeText(text);
    toast({
      description: "Copied to clipboard.",
    });
  }
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="outline" size="icon">
          <DotsVerticalIcon className="h-4 w-4" />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent className="w-40 dark:bg-slate-700 text-left">
        <Button
          variant="ghost"
          className="block w-full hover:dark:bg-slate-800 text-left"
          // onClick={() => copyText(key)}
        >
          Copy
        </Button>
        <DropdownMenuSeparator />
        <Button
          variant="ghost"
          className="block w-full hover:dark:bg-slate-800 text-left"
        >
          Revoke
        </Button>
        <DropdownMenuSeparator />
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

I have tried to destructure the props and it is also not working. All of other stuffs are working properly and I am not getting errors too. I am just getting key props as undefined.

Autofill forms not updating react state (formValues)

When I fill my form fields separately they work fine. But when I try to use google auto fill option, the logging works, state update happens for each one of the fields it comes in the log, but the change does not persist from one update to another. How can I fix this? I needed validation on the go

This is my form input file.

import React, {FC, useCallback, useEffect, useState} from "react" 
import './FormInput.css'
import { InputFieldParams } from "./interfaces"
import { ifFieldValueValid } from "./utils.ts"

interface FormInputProps {
    inputField: InputFieldParams
    setFieldValues: CallableFunction
}

const FormInput:FC<FormInputProps> = ({inputField, setFieldValues}) => {
    const {labelName, fieldName, inputType} = inputField;
    const [value, setValue] = useState();
    const [valid, setValid] = useState<boolean>(false);

    const handleFormInputChange = useCallback((e) => {
        e.stopPropagation();
        setValue(e.target.value)
        setValid(ifFieldValueValid(e.target.value, fieldName))
    },[value])

    useEffect(() => {    
        const delayInputTimeout = setTimeout(() => {
            console.log('value1', value)
            console.log('valid1', valid)
            setFieldValues(fieldName, value, valid)
        }, 1000);

        return () => clearTimeout(delayInputTimeout);
        
    },[value, valid])

    return (
        <div className="FormInput">
            <label>{labelName}</label>
            <input type={inputType} value={value} name={labelName} onChange={handleFormInputChange}/>
        </div>
    )
}

export default FormInput

This is the hook I am using

import { useCallback, useEffect, useState } from "react";
import { InputFieldParams, FieldValue } from "./interfaces";
import { getFormValuesState } from "./utils.ts";


const inputFields: InputFieldParams[] = [
    {id: 1, fieldName: 'username', labelName: 'Name', inputType: 'text', placeHolder: 'Name'}, 
    {id: 2, fieldName: 'age' ,labelName: 'Age', inputType: 'number', placeHolder: '0'},
    {id: 3, fieldName: 'dateOfBirth' ,labelName: 'DOB', inputType: 'text', placeHolder: 'DD/MM/YYYY'},
    {id: 4, fieldName: 'email' ,labelName: 'Email', inputType: 'text', placeHolder: '[email protected]'},
    {id: 5, fieldName: 'mobileNumber' ,labelName: 'Mobile Number', inputType: 'text', placeHolder: '9462501990'}
]

const checkIfAllValuesValid = (fieldValuesArray: FieldValue[]) => {
    fieldValuesArray.forEach((fieldValue) => {
        if(fieldValue.validated == false) {
            return false;
        }
    })
    return true;
}

export const useFormStateAndValidate = () => {
    const [isSubmitValid, setIsSubmitValid] = useState(false);
    const [formFieldValues, setFormFieldValues] = useState<FieldValue[]>(getFormValuesState(inputFields));

    const setFieldValues = useCallback((fieldName: string, newValue: any, isValueValid: boolean) => {
        let invalidFieldCount = 0;
        const newFieldValueState: FieldValue[]  = formFieldValues.map((prevStateFormField) => {
            if(prevStateFormField.fieldName == fieldName) {
                if(!isValueValid) invalidFieldCount++
                return {...prevStateFormField, value: newValue, validated: isValueValid}
            } else {
                if(!prevStateFormField.validated) invalidFieldCount++;
                return prevStateFormField
            }
        })

        setFormFieldValues(newFieldValueState)

        console.log(newFieldValueState)

        console.log(invalidFieldCount)

        if(invalidFieldCount > 0) setIsSubmitValid(false);
        else setIsSubmitValid(true)
    }, [formFieldValues])

    return {
        inputFields: inputFields,
        isSubmitValid: isSubmitValid,
        setFieldValues: setFieldValues,
    }
}

this is the main file where form renders.

import React, { useCallback, useState } from "react";
import './MyForm.css'
import FormInput from "./FormInput.tsx"
import { useFormStateAndValidate } from "./hooks.tsx";

const MyForm = () => {
    
    const {isSubmitValid, inputFields, setFieldValues} = useFormStateAndValidate();

    return (
        <div className="MainFormContainer">
            <div className="CustomForm">
                <h2 className="FormHeading">Fill the deatils and then submit</h2>
                <div className="FormInputs">
                    {inputFields.map((field, index) => {
                        return (
                            <FormInput 
                                key={`field_${index}`}
                                inputField={field}
                                setFieldValues={setFieldValues}
                            />
                        )
                    })}
                </div>
                <div className="SubmitButton">
                    <button disabled={!isSubmitValid}>SUBMIT</button>
                </div>
            </div>
        </div>
    )
}

export default MyForm

Aria expanded value read incorrectly by screenreader

I generate some collapsable div with checkboxes. I would like the screenreader to indicate whether the div is collapsed or not. I am trying to use the template from https://techservicesillinois.github.io/accessibility/aria-examples/accordion.html:

my code is:

'<div class="accordion"><h3 class="label label--secondary filter__heading" id="' + toggleId + '" ><button class="aria-button accordion-trigger" aria-expanded="true">'

This is not a full code, but the relevant part only. All other functionality is correct. In the console, the aria-expanded attribute is added to the h3 and indicates the state correctly, but not used by the screenreader. The SR uses the aria-expanded attribute value from the button, and that for some reason is always “false”. How to fix it?

how to get an HTML element value in liquid?

<span id="product_wished_id">value</span>

I want to get that value and store it in liquid variable.

for example : {% assign myvalue = ? %}

Is there no way to getting an html element value and store it in liquid variable? to perform if else statement in liquid?