Extra White space in the page

extra white space is showing in the webpage in responsive design for mobile only after applying the script tag how to remove it

help me with the solution on how to remove it and get rid of these white spaces which are unnecessary coming on my page

Unable to update state in React while creating Like Button

I am new in learning React. I am encountering a small problem and have grinded my brain over the issue, but not been able to come up with the solution.
I am making Comment’s like/dislike component. I am unable to maintain the state on initial run. It gets undefined on initial run, but state gets updated after pressing like button for second time. Following is my JSX:

<div className="flex justify-between gap-5" onL>
   <h4 className="text-text font-medium text-base">
       {comment?.userID?.name}
   </h4>
   <Button
     className="flex-shrink-0 flex-grow-0"
     onClick={() => {
       setHasLiked((prevHasLiked) => {
           return {
             ...prevHasLiked,
             [comment?.userID?._id]:
             !prevHasLiked[comment?.userID?._id],
             };
           });

           onSubmmitLikeComment(
             comment?._id,
             comment?.userID?._id
            );
           }}
           >
           {hasLiked[comment?.userID._id] ? (
             <Empheart stroke="red" fill="red" />
                ) : (
                  <Empheart stroke="black" fill="black" />
                    )}

                    {comment?.like_count}
           </Button>
         </div>

Following is my onSubmmitLikeComment:

const onSubmmitLikeComment = async (commentID, userID) => {
    console.log("userID", userID); //getiing userID correctly
    const userHasLiked = hasLiked[userID]; //getting undefined in initial click render. But this state gets updated after clicking like button like button for second time
    console.log("userHasLiked", userHasLiked);
    console.log("hasLiked", hasLiked);
    try {
      const response = await fetch("/api/likeComment", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-App-Type": "WEB_APP",
        },
        body: JSON.stringify({ commentID, userID, hasLiked: userHasLiked }),
      });
      const result = await response.json();
      console.log("result", result);
      if (result.isSuccess) {
        setComments((prevComments) =>
          prevComments.map((comment) =>
            comment?._id == commentID && comment?.userID?._id === userID
              ? {
                  ...comment,
                  like_count: userHasLiked
                    ? comment.like_count - 1
                    : comment.like_count + 1,
                }
              : comment
          )
        );
        setHasLiked((prev) => ({
          ...prev,
          [userID]: !userHasLiked,
        }));
      }
    } catch (error) {
      console.error("Unable to update like/unlike comment ", error);
      alert(
        "An error occurred while liking/disliking comment. Please try again."
      );
    }
  };

These are two states being used:
const [comments, setComments] = useState([]);
const [hasLiked, setHasLiked] = useState({});

Your help will make my day. 🙂

SVG line chart using d3 is not rendering to full height along y-axis

I am rendering a svg line chart using d3. For y axis the maximum value in chart data is 104 and minimum is 0. I have taken height of chart to 500. But the maximum value i.e 104 should be rendered at top height but its rendering at height somewhere near height of 270.
Also how can I get y value of svg path from x position inside svg bounds?

I am using timestamps for x axis values in chart data

My Code:

import * as shape from "d3-shape";
import { scaleLinear } from "d3-scale";
const SIZE = 500
const data2 = [
    { "weight": 0, "date": 1723939200000 },
    { "weight": 0, "date": 1724284800000 },
    { "weight": 0, "date": 1724371200000 },
    { "weight": 60, "date": 1724493742250 },
    { "weight": 0, "date": 1724544000000 },
    { "weight": 104, "date": 1724653305251 },
    { "weight": 0, "date": 1724716800000 },
    { "weight": 0, "date": 1724803200000 },
    { "weight": 0, "date": 1725235200000 }]

const formattedValues = data2.map((rec) => [rec.weight, rec.date] as [number, number]);
const weights = formattedValues.map((value) => value[0]);
const dates = formattedValues.map((value) => value[1]);
const scaleX = scaleLinear().domain([Math.min(...dates), Math.max(...dates)]).range([0, SIZE]);
const minWeight = Math.min(...weights);
const maxWeight = Math.max(...weights);
const scaleY = scaleLinear().domain([maxWeight, minWeight]).range([0, SIZE])
const path = shape.line().x(([, x]) => scaleX(x) as number).y(([y]) => {
    return scaleY(y) as number
})
    .curve(shape.curveBasis)(formattedValues) as string
export function Home() {
    return (
        <div className="homeContainer">
            <svg 
                height={SIZE} width={SIZE} fill="yellow" style={{ border: '2px solid blue' }}>
                <path
                    d={path}
                    stroke="black"
                    strokeWidth={2}
                />
            </svg>

        </div>
    )
}

export default Home

blue border is svg width and height and this is how chart renders

converting WebService response to JSON

I want to convert indexed Object response to proper JSON. I’ve already tried using JSON.stringify but no success. Here is the response:

enter image description here

<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
        var catsorted;

        $(document).ready(function () {
            getCategoriesSorted();

            var recordset = catsorted;
            //console.log(recordset);
            var rset = GenerateNestedJSON(recordset);
            var arr = rset;
            console.log(arr);
        });

        function GenerateNestedJSON(recordset) {
            var array = recordset;

                async function getNestedChildren(arr, parent) {
                    var children = [];
                    for (var i = 0; i < arr.length; ++i) {
                        if (arr[i].parentid == parent) {
                            var grandChildren = await getNestedChildren(arr, arr[i].id);
                            if (grandChildren.length) {
                                arr[i].children = grandChildren;
                            }
                            children.push(arr[i]);
                        }
                    }
                    return children;
                }
                nest = getNestedChildren(array, 0);
            return nest;
        }

        function getCategoriesSorted() {

            $.ajax({

                type: 'POST',
                url: '/CategorieService.asmx/GetCategoriesSorted',
                data: "{}",
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                async: false,
                success: function (response) {

                    catsorted = response.d;

                },
                error: function (xhr) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);
                }
            });
        }
    </script>
</head>
<body>

</body>
</html>

getCategoriesSorted() calls a C# webservice. This webservice returns id, parentid and catname from a table. GenerateNestedJSON(recordset) nests children for each category.

Buffer is not defined

Here’s an improved version of your description:


I am using the @otplib/preset-browser package, which requires the buffer. I’ve polyfilled buffer using vite-plugin-node-polyfills. This works in development mode (vite dev), but I encounter an error buffer is not defined in the production build.

Here is my vite.config.js:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { nodePolyfills } from "vite-plugin-node-polyfills";
import inject from "@rollup/plugin-inject";

// https://vitejs.dev/config/
export default defineConfig(async () => ({
  plugins: [
    react(),
    nodePolyfills({
      include: ["buffer"],
    }),
  ],

  // Vite options for Tauri development, applied in `tauri dev` or `tauri build`
  clearScreen: false, // Prevents Vite from obscuring Rust errors
  server: {
    port: 1420, // Tauri expects a fixed port, fails if unavailable
    strictPort: true,
    watch: {
      ignored: ["**/src-tauri/**"], // Tells Vite to ignore the `src-tauri` directory
    },
  },
}));

I’ve tried every solution found in google with query buffer is not defined vite.

How does the BERT algorithm interpret the contextual relevance of synonyms in search queries?

Problem Introduction: Exploring how BERT impacts SEO for synonym usage in queries.

Technical Depth: Utilizing Google Analytics and SEMrush to analyze query relevance changes post-update; investigating potential shifts in SERP due to NLP algorithm adjustments.

What I Tried: Implemented semantic analysis tools to track how synonyms in search queries influenced page rankings before and after the BERT update.

What I Expected: Anticipated more nuanced understanding by BERT leading to improved rankings for contextually relevant but synonymously varied content.

What Actually Resulted: Saw no significant change in rankings for tested keywords, contrary to expectations. Analysis suggests potential oversight in synonym context integration within BERT’s framework.

How to add an array item inside array of objects of an object in react-redux toolkit?

I am trying to update the user object’s blockedUsers array, while keeping other data not changed. user object can have blockedUsers array or not, it is not certain. In slice I have:

    reducers: { CHANGE_USER: (state, action) => {
      state.user.push(action.payload)
    },
   }

And in component, I am trying to update this way:

dispatch(CHANGE_USER({blockedUsers: [...user?.blockedUsers, selectedUser] }))

where selectedUser is an object: {id: "xxxx", name: "yyyy"}. But error comes:

Possible unhandled promise rejection (id:2). 
TypeError: Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator()] method.

How can I solve this?

VueUse useIntersectionObserver causes initial flash before transition

I’m using useIntersectionObserver from VueUse to apply a fade-in transition on elements when they come into view. However, on initial page load, the elements briefly appear before the intersection observer triggers, causing a flash and applying the fade-in effect with a delay.

I want the elements to fade in smoothly as soon as the page loads, without this initial flash.
Here’s the reproduction:
https://stackblitz.com/edit/nuxt-starter-vd6hka?file=app%2Fpages%2Findex.vue

Observer component:

<template>
  <div>
    <div ref="observerRef">
      <div :class="{ 'fade-in': isVisible }">
        <img crossOrigin="anonymous" src="https://unsplash.it/600/400" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { useIntersectionObserver } from '@vueuse/core';

const observerRef = ref(null);
const isVisible = ref(false);

const { stop } = useIntersectionObserver(
  observerRef,
  ([{ isIntersecting }]) => {
    isVisible.value = isIntersecting;
    if (isIntersecting) stop();
  }
);
</script>

Looking for a possible solution.

jquery disable arrow keys of keyboard on web page

I want to disable left and right arrows key of keyboard on a webpage, preventing the scroll to the previous or next slide.

I’ve this code:

jQuery(document).ready(function( $ ){  

document.onkeydown = function(e) {
  if (e.keyCode == 39 ) {
    alert('Not allowed');
     event.preventDefault();
    e.stop();
  }
    if (e.keyCode == 37 ) {
    alert('Not Allowed!');
    event.preventDefault(); 
    e.stop();
  } 
};
});

This is working: when I click on arrow key, the site shows alert, and then when I close it, its righty do anything (so I stay on the current slide).

The problem is when I disable the alerts: in this case, when I click on rigt or left key,the site goes to the next or to the previous slide, ignoring the block of the keyboard.

Any suggestion?
Thanks

Sending email upon document creation in firebase with cloud function

I’m currently building a flutter app that allows users to request meetings with others. When one user requests another user, the requested user should receive an email saying they got a request. when a new request is created, a new document is appended into the collection meeting_requests. Using the Google Cloud functions, I was able to write the following code with nodemailer to send an email upon creation of a request:

const transporter = nodemailer.createTransport({
  service: "gmail",
  auth: {
    user: <MY EMAIL HERE>
    pass: <MY APPS PASSWORD HERE>,
  },
});

exports.sendMeetingNotification = functions.firestore
    .document("meeting_requests/{docId}")
    .onCreate(async (snap, context) => {
      const data = snap.data();
      const receiverId = data.receiverId;

      console.log("Fetching user data for receiverId:", receiverId);

      try {
        const userDoc = await admin.firestore().collection(
            "users").doc(receiverId).get();

        if (!userDoc.exists) {
          console.log("No user found with the given receiverId:", receiverId);
          return;
        }

        const email = userDoc.data().email;

        console.log("Found user with email:", email);

        const mailOptions = {
          from: ""ConnectEd" [email protected]",
          to: email,
          subject: "New Meeting Request from Teacher",
          html: `
        <div style="background-color: #f9f7cf; padding: 20px;
         font-family: Arial, sans-serif; color: #333;">
          <div style="text-align: center; margin-bottom: 20px;">
            <img src="https://your-logo-url.com/logo.png" alt="ConnectEd Logo" style="width: 100px; height: auto;" />
          </div>
          <div style="background-color: #fff; 
          padding: 20px; border-radius: 8px; 
          box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);">
            <h2 style="color: #2c3e50;
            ">New Meeting Request from ${data.senderName}</h2>
            <p style="font-size: 16px; line-height: 1.6;">
              <strong>Note from teacher:</strong> ${data.note}
            </p>
            <p style="font-size: 16px; line-height: 1.6;">
              Please click the link below to view the request:
            </p>
            <div style="text-align: center; margin: 20px 0;">
              <a href="yourapp://app/openRequest?requestId=${context.params.docId}" style="background-color: #f39c12; color: #fff; padding: 10px 20px; text-decoration: none; border-radius: 5px; font-size: 16px;">View Request</a>
            </div>
          </div>
          <div style="text-align: center; 
          margin-top: 20px; font-size: 12px; color: #999;">
            <p>© 2024 ConnectEd. All rights reserved.</p>
            <p>If you did not request this email, please ignore it.</p>
          </div>
        </div>
        `,
        };

        console.log("Sending email to:", email);

        await transporter.sendMail(mailOptions);
        console.log("Email sent successfully to:", email);
      } catch (error) {
        console.error("Error sending email notification:", error);
      }
    });


However, when I run it, no email is sent, and I get the following log error:

2024-09-07T14:37:34.038106Z ? sendMeetingNotification: Error sending email notification: Error: 7 PERMISSION_DENIED: Missing or insufficient permissions.
2024-09-07T14:37:34.038127Z ? sendMeetingNotification:     at callErrorFromStatus (/workspace/node_modules/@grpc/grpc-js/build/src/call.js:31:19)

2024-09-07T14:37:34.038251Z ? sendMeetingNotification:   code: 7,
2024-09-07T14:37:34.038256Z ? sendMeetingNotification:   details: 'Missing or insufficient permissions.',
s.',
2024-09-07T14:37:34.038261Z ? sendMeetingNotification:   metadata: Metadata {
2024-09-07T14:37:34.038266Z ? sendMeetingNotification:     internalRepr: Map(1) { 'x-debug-tracking-id' => [Array] },
d' => [Array] },
2024-09-07T14:37:34.038270Z ? sendMeetingNotification:     options: {}
2024-09-07T14:37:34.038274Z ? sendMeetingNotification:   }
2024-09-07T14:37:34.038274Z ? sendMeetingNotification:   }
2024-09-07T14:37:34.038279Z ? sendMeetingNotification: }
2024-09-07T14:37:34.039269068Z D sendMeetingNotification: Function execution took 54 ms, finished with status: 'ok'

I’m new to this, so really did not understand what was going on.

I tried changing the firebase permissions, adding this gmail account to my cloud permissions, but nothing has worked. The odd thing was that it was working perfectly yesterday, and today it just doesn’t which is really confusing to me.

Thanks for the help!

How to change the clothes color of a JavaScript modal dynamically based on user selection?

I’m building a fashion stylist app in react naitve, and I want to add a feature where, when a user clicks on a specific color, the clothes color of a JavaScript modal changes dynamically. This would allow users to visualize how different colors look in real time.

I have no idea where to start with implementing this. Could someone guide me on how to achieve this functionality using JavaScript and react native?

Looking for a Calendar Package for Basic Calculations instead of Events

I’m looking for a calendar package / library in React Native or Flutter that allows me to do basic calculations rather than just adding events. For example, instead of creating events, I want to be able to add numbers—like if I add 100 every Tuesday, I want the calendar to total these entries at the end of the month automatically.

Ideally, it would be something I could use for recurring entries and basic math calculations on dates.

ASP.net code web app (MVC) retrieving data from sql is bringing the old data to the first columns

I am retrieving alot of data from the datatabse which bring it into a paged list and datatable. I would like to reverse the order so my new transactions are displayed on the first page and not last page.Everything works good except i need to bring the latest to the first page
Controller Code

using Deadfiles.Data;
using Deadfiles.Models;
using Deadfiles.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.EntityFrameworkCore;


namespace Deadfiles.Controllers
{
    public class DeadfilesController : Controller
    {


        private readonly ApplicationDbContext _context;

        public DeadfilesController(ApplicationDbContext context)
        {
            _context = context;
        }


        // GET: Deadfiles
        [Authorize(Roles = "Admin,User,Viewer")]
        public Task<IActionResult> Index(int pg = 1)

        {
            List<Deadfile> deadfiles = [.. _context.Deadfiles];

            const int pageSize = 10;
            if (pg < 1)
                pg = 1;

            var recsCount = deadfiles.Count;
            var pager = new Pager(recsCount, pg, pageSize);

            int recSkip = (pg - 1) * pageSize;

            var data = deadfiles.Skip(recSkip).Take(pageSize).ToArray();
            this.ViewBag.Pager = pager;
            // return Task.FromResult<IActionResult>(View(data));
            if (User.Identity.IsAuthenticated)
            {
                return Task.FromResult<IActionResult>(View(data));
            }
            else
            {
                return Task.FromResult<IActionResult>(this.Redirect("~/identity/account/login"));
            }


        }

Index Code

 @using Microsoft.AspNetCore.Identity                                                                                                                                                                                                                                                                                                                             @using Microsoft.AspNetCore.Identity
@model IEnumerable<ApplicationUser>
@{
    ViewData["Title"] = "Users";

}
<h1>Registered Users</h1>

<p>
    <a asp-action="Create" class="btn btn-primary"> <i class="fa fa-plus"></i> Add New User</a>
</p>


<div class="card">
    <div class="card-header">
        <h3 class="card-title">User List</h3>
    </div>
    <!-- /.card-header -->
    <div class="card-body">

        <table id="rolesTable" class="table table-bordered table-striped">
            <thead> 
                <tr>
                    <th>Name</th>
                    <th>Surname</th>
                    <th>Email Address</th>
                    <th>User Role</th>
                    <th>Action</th>
                </tr>
            </thead>    
            <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                        <td>@Html.DisplayFor(modelitem => item.FirstName)</td>
                        <td>@Html.DisplayFor(modelitem => item.LastName)</td>
                        <td>@Html.DisplayFor(modelitem => item.Email)</td>
                        <td>@Html.DisplayFor(modelitem => item.Role.Name)</td>
                        <td><a asp-action="Edit" asp-controller="Account" asp-route-id="@item.Id" class="btn btn-primary"><i class=" fa fa-pencil"></i>Edit</a></td>
                        <td><a asp-action="Delete" asp-controller="Account" asp-route-id="@item.Id" class="btn btn-danger"><i class=" fa fa-edit"></i>Delete</a></td>
                  
                    </tr>
            
                }
            </tbody>
        </table>
    </div>
</div>                                                                  

Paging Model

namespace Deadfiles.Models
{
    public class Pager
    {
        public int TotalItems { get; private set; }
        public int CurrentPage { get; private set; }
        public int PageSize { get; private set; }
        public int TotalPages { get; private set; }
        public int StartPage { get; private set; }
        public int EndPage { get; private set; }

        public Pager()
        {

        }
        public Pager(int totalItems, int page, int pageSize = 30)
        {
            int totalPages = (int)Math.Ceiling((decimal)totalItems / (decimal)pageSize);
            int currentPage = page;

            int startPage = currentPage - 5;
            int endPage = currentPage + 4;

            if (startPage <= 0)
            {
                endPage = endPage - (startPage - 1);
                startPage = 1;
            }

            if (endPage > totalPages)
            {
                endPage = totalPages;
                if (endPage > 10)
                {
                    startPage = endPage - 9;
                }
            }

            TotalItems = totalItems;
            CurrentPage = currentPage;
            PageSize = pageSize;
            TotalPages = totalPages;
            StartPage = startPage;
            EndPage = endPage;

        }


    }
}

I have spent days trying to get this to work

Nodemailer – Emails send but i do not recieve them

I am working on a project that uses nodemailer, when i submit the form, i get a 200 sucess and no errors from nodemailer but i don not recieve the email in my mail.

import nodemailer from "nodemailer";


const Email = (options) => {
    let transporter = nodemailer.createTransport({
        name: '[email protected]',
        service: "gmail",
        host: "smtp.gmail.com",
        port: 587,
        secure: false,
        auth:{
            user:'user',
            pass:'password',
        }
    })
     
    transporter.sendMail(options, (err, info) => {
        if (err) {
            console.log(err);
            return;
        }
        console.log("Email sent: " + info.response); // Log success message
    });
};

//SEND EMAIL
const EmailSender = ({firstName, lastName, email, companyName, typeOfDeveloper, recruitmentType}) => {
    const options = {
        from: `Darcia⚜️`,
        to: `[email protected]`,
        subject: "Message from Darcia",
        html:`
    <div style="width: 100%; background-color: #f3f9ff; padding: 5rem 0">
        <div style="max-width: 700px; background-color: #feffe1; margin: 0 auto; background-image: url('https://res.cloudinary.com/dlxrzazn6/image/upload/v1725041898/jepdinustkmgor5cltdp.png'); background-repeat: no-repeat; background-size: 50%; background-position: 130% 300%;">
          <div style="width: 100%; background-color: #2b2b2b; padding: 20px 0">
          <a href="https://darcia-frontend.vercel.app" >
            <img
              src="https://res.cloudinary.com/dlxrzazn6/image/upload/v1725043148/mmciecekert56v0xc3y9.png"
              style="width: 100%; height: 70px; object-fit: contain"
            />
        </a> 
          
          </div>
          <div style="width: 100%; gap: 10px; padding: 30px 0; display: grid">
            <p style="font-weight: 800; font-size: 1.2rem; padding: 0 30px">
              Darcia hiring agnecy
            </p>
            <div style="font-size: .8rem; margin: 0 30px">
                <p>FullName: <b>${firstName}</b> <b>${lastName}</b></p>
                <p>Email: <b>${email}</b></p>
                <p>CompanyName: <b>${companyName}</b></p>
                <p>Type of Developer: <b>${typeOfDeveloper}</b></p>
                <p>Recruitment type: <b>${recruitmentType}</b></p>
            </div>
          </div>
        </div>
      </div> 
        `

    };
    Email(options)
}

export default EmailSender;

i have tried using a different mailing service and even changing the host and port but nothing