Validation Errors , Even all the fields filled through JavaScript

Code :
document.getElementById(“input-4”).value = “Dutta”

Screenshots:

[Inspect code for Last name] (https://i.stack.imgur.com/dFcNc.png)
[Validation error when clicks on save button] (https://i.stack.imgur.com/TJDnA.png)

Description :

I got the validation errors when we click on save button(attached screenshot).

Last Name is the input type and type is text.

using the below line code to display the value.

document.getElementById(“input-4”).value = “Dutta”
but value is displaying , validation is not satisfying.

Highly Appreciated if anyone helps.

I tried with

document.getElementById(“input-4”).value = “Dutta”
document.getElementById(“input-4”).defaultValue = “Dutta”
but not working.

While we inspect the code once we enter manually then value is assigned to attribute value = “Dutta”
except that value is not assigning to given attribute in input tag.

How does React’s useState change the value of a constant?

This is the syntax I’m working with.

const [count, setCount] = useState(0);
const handleIncrement = () => {
    setCount((count + 1));
  };

I understand that setCount is creating an instance of count, but I’m really not grasping how exactly count is being changed if it’s a constant or how, if it’s an instance, it’s able to be called and return the most recent value.

Wouldn’t every time React re-renders the page, it reads the constant count first?

It’s working just fine for me, but I can’t wrap my head around why.

How to change color of different things in the same output – JS and Node.js

I am creating a JS RPG CLI game and I have a question about styled output. Once executed, the script outputs a framed Welcome. I need that frame to be colored and the text within needs to be white.

I need this: https://i.stack.imgur.com/XuYYK.png

I did it with the simple console.log():

    console.log(`
    +-----------------------------+
    |          Welcome !          |
    +-----------------------------+
    `)

To change color I am using simple color references of text:

console.log('x1b[36m%sx1b[0m', `
    +-----------------------------+
    |          Welcome !          |
    +-----------------------------+
    `)`

My output is: https://i.stack.imgur.com/NHtaU.png
This changes the color of everything, including the Welcome text and I need that white.

So, how to do that ?

ERROR [ExceptionsHandler] No metadata for “TransactionRepository” was found

I am trying to create a backend using NestJS and I am getting this error

ERROR [ExceptionsHandler] No metadata for “TransactionRepository” was found.
EntityMetadataNotFoundError: No metadata for “TransactionRepository” was found.

Everything is set up correctly. The entity is also set up correctly. What did I do wrong? Kindly help

transaction.repository.ts

import { EntityRepository, Repository } from "typeorm";
import { Transaction } from "../entities/transaction.entity";

@EntityRepository(Transaction)
export class TransactionRepository extends Repository<Transaction> {
}

transaction.service.ts

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateTransactionDto } from '../dto/create-transaction.dto';
import { TransactionRepository } from '../repositories/transaction.repository';

@Injectable()
export class TransactionService {
    
    constructor(
        @InjectRepository(TransactionRepository) private transactionRepository: TransactionRepository,
    ){}
    
    getAllTransactions() {
        return [1, 2, 3, 4];
    }

    async createTransaction(transaction: CreateTransactionDto) {
        return await this.transactionRepository.save(transaction);
    }

}

DOM / Pagination issues causing delete button to stop working after a sort or page change [duplicate]

I have an action column in the table with a delete button. The code is using jQuery to handle the delete button and make an AJAX request to a file called “ajaxfile.php” with the id of the record to be deleted. The success function of the AJAX request is then removing the row from the HTML table if the response is 1, and displaying an alert if the response is not 1 . It deletes on the first page but when I do a sort or change the page, the button stops deleting. Have read it is about the DOM and pagination but struggling to fix it. Here is the code

<td><input type='button' name='id' class='delete btn btn-danger' id='del_{$id}' data-id='{$id}' value='Delete'/>

<script>
           $(document).ready(function () {

               // Delete
               $('.delete').on('click', function () {
                   var el = this;

                   // Delete id
                   var deleteid = $(this).data('id');

                   // Confirm box
                   bootbox.confirm("Do you really want to delete record?", function (result) {

                       if (result) {
                           // AJAX Request
                           $.ajax({
                               url: 'ajaxfile.php',
                               type: 'POST',
                               data: {id: deleteid},
                               success: function (response) {

                                   // Removing row from HTML Table
                                   if (response == 1) {
                                       $(el).closest('tr').css('background', 'tomato');
                                       $(el).closest('tr').fadeOut(800, function () {
                                           $(this).remove();
                                       });
                                   } else {
                                       bootbox.alert('Record not deleted.');
                                   }

                               }
                           });
                       }

                   });

               });
           });


        </script>

Formik handleSubmit is not getting called

I’m trying to validate a form before submitting using formik and yup validation. The form consist of two parts, the first form is validated then loads next one. And am setting a state handleShow(true) to trigger the second form. Below is my code

  const UserOnboardSchema = Yup.object().shape({
    gender: Yup.string().required('please select the gender'),
    firstName: Yup.string().required('Please enter your first name'),
    lastName: Yup.string().required('Please enter your last name'),
    mobile: Yup.string()
      .required('Please enter your mobile number')
      .matches(phoneRegExp, 'Please enter valid phone number'),
    workExperience: Yup.string().required('Please enter your work experience'),
  });



  const formik = useFormik({
    initialValues: {
      gender: '',
      firstName: '',
      lastName: '',
      mobile: '',
      workExperience: '',
      currentRole: '',
    },
    validationSchema: UserOnboardSchema,
    onSubmit: (values) => {
      console.log(values);
      formik.resetForm();
    },
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    formik.handleSubmit();

    if (Object.entries(formik.errors).length === 0) {
      handleShow(true);
    } else {
      handleShow(false);
    }
  };

Here is the problem in the handleSubmit the formik.handleSubmit is not working. It’s directly accessing the if/else condition thus loading second form without validating the first one.

    if (Object.entries(formik.errors).length === 0) {
      handleShow(true);
    } else {
      handleShow(false);
    }

but if I givehandleShow(true) direclty to formik, like this

  const formik = useFormik({
    initialValues: {
      gender: '',
      firstName: '',
      lastName: '',
      mobile: '',
      workExperience: '',
      currentRole: '',
    },
    validationSchema: UserOnboardSchema,
    onSubmit: (values) => {
      console.log(values);

      handleShow(true); #----> Giving here.

      formik.resetForm();
    },
  });

then the formik and Yup validation works. Im unable to figure out whats causing this issue?

Button did not trigger JS function

I create a button, then the button is supposed to triggered a JS function that will call another JS function. I tried to put Alert function in JS to test if it triggered, but it didn’t. Anyone can help me?

Why it didn’t get triggered?

$(document).ready(function() {
  $("#btnProcess3").attr("disabled", "disabled");
  alert("hi")
  jsProcess(0);

  $("#btnProcess3").click(function() {
    alert("hi")
    $(this).attr("disabled", "disabled");
    jsProcess(1);
  });
});

function jsProcess(action) {
  var page;
  var sDate;
  var sBizDate;
  sDate = $('#txtDate').val();

  if ($('#chkuseBizDate').is(':checked')) {
    sBizDate = $('#txtBizDate').val();
  } else {
    sBizDate = sDate;
  }
  page = "LoadPPSFile_details01.asp?TaskId=<%=sTaskId %>&txtDate=" + (sDate) + "&RunProcess=" + action + "&txtBizDate=" + (sBizDate);
  document.getElementById("IProcess").src = page;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<input type="button" name="btnProcess" id="btnProcess3" value="Start - Services" width="250" style="VISIBILITY:show; WIDTH: 150px; HEIGHT: 22px; Background-Color:#1E90FF; Border-Color:white; Color:white; Font-Weight:bold;Font-family:Verdana;Cursor:hand; "
/>

Is 4xx and 5xx network errors?

I have a node server that basically reads a component from a specific path, executes the code, and returns the data to the other server.

Sometimes during the code execution of the component, I get a 403 response.

Error:

ApolloError: Response not successful: Received status code 403

I’m using .catch() to catch the 403 response but it’s not helping and there are frequent pod crashes due to the 403.

I have checked this StackOverflow answer – Fetch: reject promise and catch the error if status is not OK?

It mentions that

Since 4xx and 5xx responses aren’t network errors, there’s nothing to catch

Is this correct?

If the above statement is true, can it be handled like the below:

app.use((req,res) => {
   res.status(403).send('');
})

JavaScript Fetch API: Try to post data to a specific endpoint URL

Try to parse the response body text as JSON (response.json()) and got this error in the console:

Uncaught (in promise) SyntaxError: Unexpected end of input (at script.js:177:33)at postData (script.js:177:33)

This is the code that throw the error in the line of .then(response => response.json()).

fetch('/', {
    method: 'POST', // or 'PUT'
    mode: 'no-cors',
    headers: {
      'Content-Type': 'application/json',
    },
    redirect: 'follow',
    referrerPolicy: 'origin-when-cross-origin',
    body: JSON.stringify({
      "email": emails.val()
    }),
  })
  .then((response) => response.json())
  .then((data) => {
    console.log('Success:', data);
  })
  .catch((error) => {
    console.error('Error:', error);
  });

I expect it to post data (emails.val()) to the body of the endpoint so I can use the controller I wrote to take the data from this endpoint and insert it to model.

Property does not exist on type ‘Query’

I want to create a mongoose schema, and I am trying to add a new property named start to the document. It works in javascript, but in typescript, I am getting an error “Property ‘start’ does not exist on type ‘Query<any, any, {}, any>’.ts(2339)”.

I appreciate any help you can provide to fix the error.

import mongoose from 'mongoose';
interface tourSchemaTypes {
  name: string;
}

const tourSchema = new mongoose.Schema<tourSchemaTypes>({
  name: {
    type: String,
    required: [true, 'A tour must have a name'],
    unique: true,
  },
});

const Tour = mongoose.model<tourSchemaTypes>('Tour', tourSchema);

tourSchema.pre(/^find/, function (next) {
  this.find({ secretTour: { $ne: true } });
  this.start = Date.now(); 
  next();
});

tourSchema.post(/^find/, function (docs, next) {
  console.log(`Query took ${Date.now() - this.start} milliseconds`);
  console.log(docs);
  next();
});

navigator.wakeLock property is missing in some Chrome browsers

I have written some HTML/JS page and if I open the page on different machines (laptop vs. PC) with the very same version of Chrome, one browser has the navigator.wakeLock property but the other one has not.

Debugger shows wakeLock property

Debugger shows no wakeLock

Chrome current version

I’m puzzled.
As far as I know Chrome supports wakeLock. And does obviously on the laptop.
But why not on my PC?
Both run Windows 10.

Search for drive items with $expand parameter

I’m trying serach in a drive for driveItems. I have figured out how to search for driveItems in the API like this:

https://graph.microsoft.com/v1.0/sites/{siteId}/drives/{driveId}/search(q=’test’)

But for my application, I need more detailed information about the documents so I tried to use the $expand without any successful outcome.

Request to look up more details about a single driveItem:

https://graph.microsoft.com/v1.0/sites/{siteID}/drives/{driveId}/items/{itemId}/listItem/?expand=fields($select=Title,ID,etc..)

Is it possible to achieve all the fields I get from this request when I use the $expand parameter in Search for DriveItems within a drive? Or do I need to look up every single driveItem to get the additional parameters?

existe t il une fonction en “vba” Excel qui ne permet de permuter entre les colonne dune matrice [closed]

svp j’ai besoin de votre aide, pour mon projet
voilà je dispose de n rectangle ‘ R1,,,,Rn‘ avec ‘ Ri=(Li, li)‘ ‘ L:LONGEUR‘ ET ‘ l : largeur
L’objectif et de les arranger sur un axe (Ox) avec toute les cas possible (rotation) qui est = 2^n , avec n nombre de rectangle ,
le but c’est d’étudier chaque cas :
Exemple n =2 .

`| L | l | | 
--------
| 8 | 4 |                                                            ' cas1 u= (8,6) et v=(4,3).
| 6 | 3 |                                                            ' cas 2 u= (8,3) et v=(4,6) 
                                                                       cas 3 u= (4,6) et v=(8,3) 
                                                                       cas 4 u= (4,3) et v=(8,6;' `

POUR QUE ENSUIT DANS CHAQUE CAS (chaque positionnement)

je calcule , u= somme( longueur ou largeur) v v vecteur pour récupérer l’indice de min

Dans chaque itération je calcule le u et je supprime l’indice de min v dans la matrice .
J’ai tout essai avec deux tableau, mais…

sub test()
 dim i ,j 

integer

 dim Li,li integer
 dim mat() 
dim n ,nbcas integer ' nbc est nombre de cas possible n= nombre de rectange 
nbc = 2^n 
for i=1 to nbc do 
redim mat(0 to 2 , 1 to n)
 for j= 1to 2 faire 
for k=1 to ubound(mat) faire 
> mat(i,j)= li , Li            ' ce nest pas ca  mai bon 
next k 
next j 
u=som(mat(1,1to n)
 v= ' voile je suis perdu
end for
 end sub`

How to pass single param one param?

How correctly refactor function, instead of duplication

so, now I have :

export const formatAddressLocation = (postcode, house, additions, street) => {
  let address = "";
  if (street) address += street + " ";
  if (house) address += house + " ";
  if (additions) address += additions + " ";
  if (postcode) address += postcode + " ";
  return address;
};

and
export const formatLocationInfo = (name, postcode, house, additions, street) => {
  let address = "";
  if (name) address += name + " ";
  if (street) address += street + " ";
  if (house) address += house + " ";
  if (additions) address += additions + " ";
  if (postcode) address += postcode + " ";
  return address;
};

And I want to pass single param (name) one param is easier to maintain. (location) = {loction.name} + formatAddressLocation(…)