Email validation with zod – Multiple error descriptions

I need to verify the email and the confirm email with zod, and when my refine check if emails don’t match i would like to show in both fields my erros, but its not working with path in refine.

I’m trying to use path: ['emai', 'confirmEmail'], but its not working and is giving me an undefined message on form.

const SignUpFormInputsSchema = z.object({
    email: z
      .string({
        required_error: 'email is required.',
        invalid_type_error: 'email is invalid.',
      })
      .email('email is invalid.'),
    confirmEmail: z
      .string({
        required_error: 'email confirmation is required.',
        invalid_type_error: 'email confirmation is invalid.',
      })
      .email('email is invalid.'),
  })
  .refine(
    ({ email, confirmEmail }) => {
      return email === confirmEmail
    },
    {
      message: 'emails must match.',
      path: ['emai', 'confirmEmail'],
    },
  )

How can I configure CORS properly on my AWS API Gateway to handle POST Requests to my Lambda function?

I am trying to set up a very basic API that returns a selected state from a drop down box from the front end. I want to send the state in the request body, and then return the state back in the response to make sure I can get it into my lambda function.

I am trying to make a post request from my frontend to my backend and I keep getting the following exception:

Access to fetch at '(my-endpoint)' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Here is my code when making the API call:

fetch(url, {
    method: "POST",
    body: JSON.stringify({
      state: "Colorado"
    }),
    headers: {
      "Content-type": "application/json",
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "*",
    },
  })

Here is my deployed API Gateway CORS configuration:
CORS Config Image

Here are my API Gateway Trigger details:

API type: HTTP
Authorization: NONE
CORS: Yes
Detailed metrics enabled: No
Method: ANY

And finally, my python code in my lambda function:

import json

def lambda_handler(event, context):
    
    request_body = json.loads(event['body'])
    state = request_body['state']
    
    return {
        'statusCode': 200,
        'headers': {
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': '*'
        },
        'body': json.dumps(state)
        
    }

I am confused as to why it is not picking up my CORS configuration on the resource side?

I tried to send the request using the js fetch method, and I see the error in the console upon sending the request. I have configured CORS on the backend so I am stuck with why it it’s allowing the request to go through. I am testing with my frontend hosted locally, and my API hosted on AWS. It works in postman, but I aware that postman works without needing a valid CORS configuration.

distube SyntaxError: Unexpected token ‘?’

I decided to add the ability to play music using “distube” to my bot.
The bot was written according to the old guides, and I connected the “distube” using the same manuals.
But the following error pops up at startup

W:discord_botnode_modules@distubeytsrnode_modulesundicilibhandlerRetryHandler.js:29
    } = retryOptions ?? {}
                      ^

SyntaxError: Unexpected token '?'
    at wrapSafe (internal/modules/cjs/loader.js:1053:16)
    at Module._compile (internal/modules/cjs/loader.js:1101:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Module.require (internal/modules/cjs/loader.js:1025:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (W:discord_botnode_modules@distubeytsrnode_modulesundiciindex.js:18:22)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)

As soon as I comment on this line const DisTube = require('distube') . The bot starts to run again.
How can I understand the situation in distube, is there any idea how to solve the problem without rewriting the code to new versions

I tried reinstalling nodes and npm. When reinstalling, I specified versions that should be 99.9% compatible with each other.
I do not know how to describe my problem in more detail, so ask questions, I will try to answer

Media Recording works once, but fails on subsequent dumps to endpoint

I have the following script being triggered on click by a button. There is some boilerplate for CSRFTokens etc I’m leaving in case I’ve done something weird there, but the crux of the script is to send an audioBlob (sendData) every thirty seconds to the transcribe endpoint. A 200 is returned, but on a somewhat substantial dely, hence the async so the audio can (in theory) move on to the next chunk of recording.

Right now, however, the script works on the first pass to the endpoint, but on all subsequent passes seems to send an empty blob.

Been debugging for a while, any help would be appreciated.

    let audioChunks = [];
    let isRecording = false;
    let intervalId;
    const retryLimit = 1;
    let retryCount = 0;
    let wakeLock = null;


    function getCSRFToken() {
      return document.querySelector("input[name=csrfmiddlewaretoken]").value;
    }

    function getQueryParam(param) {
      const urlParams = new URLSearchParams(window.location.search);
      return urlParams.get(param);
    }

    async function sendData(audioBlob) {
      try {
        const formData = new FormData();
        formData.append("file", audioBlob, "audio.wav");
        const session_id = getQueryParam("session_id"); // Get session_id from URL
        if (session_id) {
          formData.append("session_id", session_id); // Add session_id to the formData
        }
        const response = await fetch("transcribe", {
          method: "POST",
          headers: {
            "X-CSRFToken": getCSRFToken(), // Add CSRF token to the request headers
          },
          body: formData,
        });
        if (!response.ok) throw new Error("Upload failed");
        retryCount = 0; // Reset retry count on successful upload
      } catch (error) {
        if (retryCount < retryLimit) {
          retryCount++;
          sendData(audioBlob); // Retry sending data
        } else {
          console.error("Failed to upload after retries:", error);
          retryCount = 0; // Reset retry count
        }
      }
    }

    async function initiateMediaRecorder(stream) {
      mediaRecorder = new MediaRecorder(stream);
      mediaRecorder.ondataavailable = (event) => {
        if (event.data.size > 0) {
          audioChunks.push(event.data);
        }
      };
      mediaRecorder.onstop = async () => {
        const audioBlob = new Blob(audioChunks, { type: "audio/wav" });
        sendData(audioBlob); // Send the last chunk of audio
        audioChunks = []; // Reset chunks for the next recording
      };
      mediaRecorder.start();

      intervalId = setInterval(async () => {
        mediaRecorder.requestData(); // Get current audio chunk
        if (audioChunks.length) {
          const currentChunks = [...audioChunks]; // Copy current chunks
          audioChunks = []; // Clear the chunks for the next interval
          const audioBlob = new Blob(currentChunks, { type: "audio/wav" });
          await sendData(audioBlob); // Wait for sendData to complete
        }
      }, 30000); // 30 seconds
    }

    async function toggleRecording() {
      if (!isRecording) {
        if (!navigator.mediaDevices) {
          console.error("MediaDevices API not supported");
          return;
        }
        try {
          const stream = await navigator.mediaDevices.getUserMedia({
            audio: true,
          });
          initiateMediaRecorder(stream);
          document.getElementById("record_audio").textContent =
            "Stop Recording";
          document.getElementById("record_audio").className =
            "btn btn-lg btn-danger";
          isRecording = true;
    
          // Request a wake lock
          try {
            wakeLock = await navigator.wakeLock.request('screen');
            console.log('Wake Lock is active');
          } catch (err) {
            console.error(`${err.name}, ${err.message}`);
          }
    
        } catch (error) {
          console.error("Error accessing audio device:", error);
        }
      } else {
        mediaRecorder.stop();
        clearInterval(intervalId);
        document.getElementById("record_audio").textContent = "Start Recording";
        document.getElementById("record_audio").className =
          "btn btn-lg btn-outline-primary";
        isRecording = false;
    
        // Release the wake lock
        if (wakeLock !== null) {
          wakeLock.release().then(() => {
            console.log('Wake Lock was released');
            wakeLock = null;
          });
        }
      }
    }```

Refreshing JWT access token and refresh token in react

I have my Django backend with URL for user/token/refresh where it sends this tokens when I hit with refresh token in body

{
    "access": "access_token",
    "refresh": "refresh_token"
}

access token is valid for 5 mins. When someone logs in they get both tokens and I’m saving them in localStorage. But after 5 mins they refresh and get new access_token and refresh_token. I have this endpoint with createApi from Redux-Toolkit.

refreshToken: builder.mutation({
  query: (refreshToken) => {
    return {
      url: "user/token/refresh/",
      method: "POST",
      body: { refresh: refreshToken },
      headers: {
        "Content-type": "application/json",
      },
    };
  },
}),

When someone logs in I’m using these functions to store and retreive the token data.

const storeToken = (value) => {
  if (value) {
    const { access, refresh } = value;
    localStorage.setItem("access_token", access);
    localStorage.setItem("refresh_token", refresh);
  }
};

const getToken = () => {
  let access_token = localStorage.getItem("access_token");
  let refresh_token = localStorage.getItem("refresh_token");
  return { access_token, refresh_token };
};

in my cart component i’m fetching data from backend if it does not get the data or get an error i’m trying to refresh the token and refetch the data but it’s not working. refreshToken function from mutation does work i’ve tested it seperately. but it seems here is the is in this code from cart.jsx

const { access_token, refresh_token } = getToken();
const {
    data: cartData,
    refetch,
    isError,
  } = useCartObjectListQuery(access_token);
  // ...
  const [refreshToken] = useRefreshTokenMutation();
  useEffect(() => {
    const fetchData = async () => {
      try {
        const refreshResponse = await refreshToken(refresh_token);
        console.log("refreshResponse Object" + refreshResponse);
        if (refreshResponse.data) {
          const { access, refresh } = refreshResponse.data;
          console.log("consoling refresh response from cart" + access, refresh);
          storeToken({
            access: access,
            refresh: refresh,
          });
          // Now, refetch the cart data with the updated access token
          await refetch();
        } else {
          console.error("Token refresh failed:", refreshResponse.error);
        }
      } catch (refreshError) {
        console.error("Unexpected error during token refresh:", refreshError);
      }
    };
    if (isError) {
      fetchData();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

Please add a comment if i need to add any more info.

Passing param to function getting JS error

I am trying to understand this error as to why it is happening, but also understand how to fix it.

I have code

serviceDiv += '<small><i onclick="editService("'+service.serviceId+'")" class="bi bi-pencil-fill"></i> </i><i onclick="deleteService("'+service.serviceId+'")" class="bi bi-trash3-fill"></i></small>';
               

The error in console:

Uncaught SyntaxError: Unexpected end of input

The HTML. I assume its because there is a space before the ID? but im honestly not sure.

enter image description here

enter image description here

window.location.hash doesn’t “see” URLs containing #:~:text=

When Google features a block of a text at the top of its results page, it will link to the site and add a hash with some text in it.

For example, this is the URL from the top result if I search for “daily management system”:

https://tervene.com/blog/daily-management-system-dms/#:~:text=A%20Daily%20Management%20System%2C%20commonly,as%20planned%20and%20continuously%20improves.

If I run “window.location.hash” in the JS console on that page, I get an empty strong. What gives?

it is giving error 401 and my hyper is pointing out the temp variable as the problem. any suggestions?

const express = require("express");
const https = require("https");
const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({extended: true}));


app.get("/", function(req, res){

    res.sendFile(__dirname + "/index.html");
});


app.post("/", function(req, res){

    const query = req.body.cityname;
    const apikey = "be542b6232b2bc2d159d89e25bf419fc";
    const unit = "metric";
    const url = "https://api.openweathermap.org/data/2.5/weather?q= " + query + "&appid= " + apikey + "&units= " + unit;

    https.get(url, function(response){

        console.log(response.statusCode);

        response.on("data", function(data){
            const weatherData = JSON.parse(data);
            const temp = weatherData.main.temp;
            const weatherDescription = weatherData.weather[0].description;
            const icon = weatherData.weather[0].icon;
            const imageURL = "https://openweathermap.org/img/wn/" + icon + "@2x.png";
            res.write("<p>The weather is currently " + weatherDescription + " </p>");
            res.write("<h1>The temperature in " + query + " is " + temp + " degree celsius.</h1>");
            res.write("<img src = " + imageURL + ">");
            res.send();
        });
    });
});





app.listen(1500, function(){

    console.log("Server is running on port 1500");
});

Cy log output values are not showing in Mocha Awesome HTML Report

I have written a code for Page Load time in Cypress/support/commands, but when calling the method in test and running with npx cypress run –spec spec path then actual value for page load is not showing in Mocha Awesome Report.

NOTE:- when executing same code with npx cypress open, then page load time value is showing in test runner

CY.LOG() OUTPUT should be displayed IN MOCHAWESOME HTML REPORT

Why does running ‘npm build’ in InboxSDK example project revert the final executable ‘dist’ to original version of ‘manifest.json’ file?

I am new to web-development and am trying to learn how to develop chrome extensions following manifest version 3. I specifically want to create a chrome extension using InboxSDK which simplifies the process of altering UI elements in the DOM of a GMail inbox.

The project I am trying to modify can be found here: https://github.com/InboxSDK/hello-world

I want to use the project provided in this repo as a template for the creation of my own extension. How can I alter the webpack configuration such that the final executable, ‘dist’ directory, that is created after running ‘npm build’ only contains the single ‘manifest.json’ file and reflects changes I want to make to the file?

Thank you in advance for any help or resources that can be offered to further my understanding.

I tried altering manifest.json directly in the executable file, but using webpack to build a new executable directory reverts it back to its original state.

Change the Value of MultiSelect after Query-Params

I have 4 MultiSelects from PrimeNg and they are being filled with a global GET.
Whey they are closed, they call a function with a service inside tha basically sets the query-params to the backend.

The query-params is working just fine and i can send these multiselects to the backend in a form.

The problem is that if the query-params in the response remove a camp that was selected in the multiselects, it will remove from the list options, but no from the value of the multiselect.

For Example, if i select 4 Fornecedores and at some point the response returns me 2 Fornecedores, they will not be showed on the list but will stays as values in the form and in the multiselect when i send them back to the backend, but i want to just send the selected one that are being listed.

            [options]="filterOptions.produto.fornecedores"
            optionLabel="fornecedor_desc"
            formControlName="cod_fornecedor"
            [filter]="true"
            filterBy="fornecedor_desc"
            placeholder="Sem Filtro"
            appendTo="body"
            (onPanelHide)="onMultiSelectChange()"
            selectedItemsLabel="{filterOptions.produto.fornecedores} escolhidos"
          >
          </p-multiSelect>
        </div>
        <div class="flex flex-column">
          <span>Marcas</span>
          <p-multiSelect
            [options]="filterOptions.produto.marcas"
            optionLabel="marca_desc"
            formControlName="cod_marca"
            [filter]="true"
            filterBy="marca_desc"
            placeholder="Sem Filtro"
            appendTo="body"
            (onPanelHide)="onMultiSelectChange()"
            selectedItemsLabel="{filterOptions.produto.marcas} escolhidos"
          >
          </p-multiSelect>
        </div>
      </div>
      <div class="section col-6">
        <div class="flex flex-column">
          <span>Categorias</span>
          <p-multiSelect
            [options]="filterOptions.produto.categorias"
            optionLabel="grupo_desc"
            formControlName="cod_grupo"
            [filter]="true"
            filterBy="grupo_desc"
            placeholder="Sem Filtro"
            appendTo="body"
            (onPanelHide)="onMultiSelectChange()"
            selectedItemsLabel="{filterOptions.produto.categorias} escolhidos"
          >
          </p-multiSelect>
        </div>
        <div class="flex flex-column">
          <span>Subcategorias</span>
          <p-multiSelect
            [options]="filterOptions.produto.subcategorias"
            optionLabel="subgrupo_desc"
            formControlName="cod_subgrupo"
            [filter]="true"
            filterBy="subgrupo_desc"
            placeholder="Sem Filtro"
            appendTo="body"
            (onPanelHide)="onMultiSelectChange()"
            selectedItemsLabel="{filterOptions.produto.subcategorias} escolhidos"
          >
          </p-multiSelect>`


`  onMultiSelectChange() {
    const queryParams: any = {};
    
    Object.keys(this.formFilter.controls).forEach(controlName => {
      const selectedItems = this.formFilter.value[controlName];
    
      if (Array.isArray(selectedItems) && selectedItems.length > 0) {
        const codValues = selectedItems.map((item) => item[controlName]);
        queryParams[controlName] = codValues;
      }
    });
    
    this.cuboService.updateUrlWithParams(queryParams)
      .subscribe(response => {
        console.log(response);
        this.filterOptions = response.result;
        
      });
  }`

service:

`  updateUrlWithParams(queryParams: any): Observable<ResponseFilter> {
    const url = `${environment.BackEndAPI}/filter`;

    let params = new HttpParams();
    
    Object.keys(queryParams).forEach(key => {
      queryParams[key].forEach((value: any) => {
        params = params.append(key, value);
      });
    });

    return this.httpClient.get<ResponseFilter>(url, { params: params });
  }`

I’ve tried redoing the formvalues, but i was did not work

Implementing ||= (object,object) operator for older browsers

Android WebView have trouble with emscripten generated code. When trying to load page, it complains = is unexpected in ||= string. ||= is logical OR operator with assignment. I am locking for documentation in case, where both operands are objects.
I think it simply copy each property of right-side onto left-side with overlap, so if right object had property a = 1 and left object had a = 2, result object will have a = 1. Have I right?

SVG Path incorrect size and position

I am generating an SVG document and have a library generating SVG from LaTeX.

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svgjs="http://svgjs.dev/svgjs" width="500px" height="300px" id="svgSurface">
   <svg viewBox="0 -883.9 1186.6 883.9" x="0" y="0" width="100">
      <defs>
         <path id="MJX-1-TEX-N-31" d="M213 578L200 573Q186 568 160 563T102 556H83V602H102Q149 604 189 617T245 641T273 663Q275 666 285 666Q294 666 302 660V361L303 61Q310 54 315 52T339 48T401 46H427V0H416Q395 3 257 3Q121 3 100 0H88V46H114Q136 46 152 46T177 47T193 50T201 52T207 57T213 61V578Z"></path>
         <path id="MJX-1-TEX-N-48" d="M128 622Q121 629 117 631T101 634T58 637H25V683H36Q57 680 180 680Q315 680 324 683H335V637H302Q262 636 251 634T233 622L232 500V378H517V622Q510 629 506 631T490 634T447 637H414V683H425Q446 680 569 680Q704 680 713 683H724V637H691Q651 636 640 634T622 622V61Q628 51 639 49T691 46H724V0H713Q692 3 569 3Q434 3 425 0H414V46H447Q489 47 498 49T517 61V332H232V197L233 61Q239 51 250 49T302 46H335V0H324Q303 3 180 3Q45 3 36 0H25V46H58Q100 47 109 49T128 61V622Z"></path>
      </defs>
      <g stroke="currentColor" fill="currentColor" stroke-width="0" transform="matrix(1,0,0,-1,0,0)">
         <g data-mml-node="math">
            <g data-mml-node="msup">
               <g data-mml-node="mi"></g>
               <g data-mml-node="TeXAtom" transform="translate(33,413) scale(0.707)" data-mjx-texclass="ORD">
                  <g data-mml-node="mn">
                     <use data-c="31" xlink:href="#MJX-1-TEX-N-31"></use>
                  </g>
               </g>
            </g>
            <g data-mml-node="mtext" transform="translate(436.6,0)">
               <use data-c="48" xlink:href="#MJX-1-TEX-N-48"></use>
            </g>
         </g>
      </g>
   </svg>
</svg>

It is essentially a group which references a path in defs. I want to be able to resize the entire embedded SVG part. I set the x and y, nothing happens, I set the width to 100 and it resizes, not to 100 but to 90.something and changes the height too? I understand <g> fills its container, but it appears to be effecting the container too?

https://jsfiddle.net/thk9cago/

I expect the content in the embedded SVG to resize and position subject to the x, y and width properties.

Adding inputs from html form gives nan

I tried to check all questions here, but they didn’t answer my problem.
am trying to add Number1 and Number2 using external Javascript but it is giving me NaN.
here is my html code

 <!DOCTYPE html>
<html>
<head><title>Simple Calculator</title>
<script src="new.js">
</script>
</head>
<body>
<div align="center">
<p><b><u>Calculator</u></b></p>
<form>
<table>
<tr>
<td><input type="text" placeholder="Number1" id="n1" ><br><input type="text" placeholder="Number2" id="n2"><br>
<button onclick="Add()">Add</button></td>
<td><input type="number" placeholder="Number1" id="n3"><br><input type="number" placeholder="Number2" id="n4"><br>
<button onclick="Dicvide()">Divide</button></td>
<td><input type="number" placeholder="Number1" id="n5"><br><input type="number" placeholder="Number2" id="n6"><br>
<button onclick="Multi()">Mutliply</button></td>
</tr> 
<tr>
<td>Answer:<input type="text" id="add"></td><td>Answer:<input id="div"></td><td>Answer:<input id="mul"></td>
</tr>
</table>
</form>
</div>
</body>
</html>

Here is new.css

    function Add(){
   var a,b,c;
    a = parseInt(document.getElementById("n1").value);
    a = parsceInt(document.getElementById("n2").value);
    c = a+b;
    document.getElementById("add").value = c;
    alert(c);
    }

Any help is appreciated!

digital root code gives wrong answer and an error

I’m really new to javascript, and i’m working on a project for my class. I needed to make a digital root calculator and when I finally thought I got it, it just alerts that the digital root is a random number like 1 or 2 before giving the actual root,,,then the alert says “NaN” and the page breaks. I’m not entirely sure what’s wrong

     <form><input type = "text" name = "root" id="root">
  <input type = "text" name = "root2" id="root2">
 <input type = "text" name = "root3" id="root3">
 <input type = "text" name = "root4" id="root4">
 <input type = "text" name = "root5" id="root5"> 
 <br><br>
 <button type="submit" name="rootchecker" id="rootchecker">Check digital root</button>
</form>
<br>

 <script>

 function digroot () {

var num1 =       document.getElementById("root").value
var num2 = document.getElementById("root2").value
var num3 = document.getElementById("root3").value
var num4 = document.getElementById("root4").value
var num5 = document.getElementById("root5").value

var sum = Number(num1) + Number(num2) + Number(num3) + Number(num4) + Number(num5);

var sumstr = sum.toString();

var total = 0;

for (let i = 0; sumstr.length; i++) {
    total += Number(sumstr[i]);
    alert(total);
}

alert(total);
 }

document.getElementById("rootchecker").addEventListener('click', digroot);

 </script>