How to Customize Browser’s PDF Viewer Without Changing the URL in the Omnibox

I’m trying to develop a browser extension to customize the PDF preview page. In the Stack Overflow question Chrome Extension: How to show custom UI for a PDF file, the main author of the PDF.js Chrome extension provided an excellent answer on how to intercept PDF requests in webRequest and redirect them to a custom page. However, this method changes the URL displayed in the address bar.

Interestingly, the Google Scholar PDF Reader (available here) does not alter the URL in the omnibox when opening PDF files. How is this achieved? Could someone analyze this behavior or provide insights on how to implement a similar feature? Any help would be greatly appreciated!

I used CRX Viewer to examine the source code of the Google Scholar PDF Reader extension. I noticed that it has permissions for “webNavigation”, “webRequest”, “declarativeNetRequest”, “scripting”, “storage”, “offscreen”, and “clipboardWrite”. When accessing any page, it loads a script called contentscript-compiled.js.

Could someone provide guidance on how to maintain the original URL while customizing the PDF viewer, or suggest what I might be missing in my approach? Any advice would be greatly appreciated!

How to structure scalable data for a drag-and-drop page builder with responsive styling?

I’m building a drag-and-drop page builder using React, and I’m trying to design a scalable data structure for the canvas. The goal is to support dynamic layouts (using Flexbox/Grid) and responsive styling for different screen sizes.

Here’s the current data structure I’m using:

const canvasData = [
  {
    canvasItemId: uuidv4(),
    elType: 'Container',
    id: uuidv4(),
    settings: {
      containerType: 'flex',
      flexDirection: 'row',
      gap: '24px',
      size: '2',
      unit: 'fr',
    },
    elements: [
      {
        canvasItemId: uuidv4(),
        settings: {
          title: 'Add Your Heading Text Here',
          titleLink: {
            url: '',
            isExternal: false,
            target: false,
          },
          width: { unit: '%', size: '100%' }, // Desktop
          widthTablet: { unit: '%', size: '100%' },
          widthMobile: { unit: '%', size: '100%' },
          title_color: '',
          font_family: 'Poppins',
          tagType: 'h1',
          style: 'normal',
          decoration: 'none',
          background_color: 'transparent',
          weight: '400',
          size: 20,
          typographyFontSize: {
            unit: 'px',
            size: 36,
          },
          typographyFontSizeTablet: {
            unit: 'px',
            size: 30,
          },
          typographyFontSizeMObile: {
            unit: 'px',
            size: 20,
          },
          transform: 'capitalize',
          textAlign: 'left',
          padding: {
            bottom: 0,
            left: 0,
            right: 0,
            top: 0,
          },
          margin: {
            bottom: 0,
            left: 0,
            right: 0,
            top: 0,
          },
        },
      },
    ],
  },
];

For responsive styling, I’m currently generating CSS dynamically for each item and injecting it into the DOM:

<div key={item.canvasItemId} className={`${item.canvasItemId}`}>
  <style>{`
    .${item.canvasItemId} .heading {
      font-size: ${settings.typographyFontSizeMobile.size}${settings.typographyFontSizeMobile.unit};
    }
    @media (min-width: 768px) {
      .${item.canvasItemId} .heading {
        font-size: ${settings.typographyFontSizeTablet.size}${settings.typographyFontSizeTablet.unit};
      }
    }
    @media (min-width: 1024px) {
      .${item.canvasItemId} .heading {
        font-size: ${settings.typographyFontSize.size}${settings.typographyFontSize.unit};
      }
    }
  `}</style>
  <p className="heading">{item.settings.title}</p>
</div>

Questions:

Scalability:

Is this data structure scalable for a page builder that supports nested layouts, containers, and dynamic elements?
Are there better ways to handle layout and element settings?
Responsive Styling:

Is embedding dynamic tags an efficient approach, or should I use another method like CSS-in-JS (e.g., Styled Components)?
Flexbox and Grid Support:

How should I design the canvasData structure to handle both Flexbox and Grid layouts effectively?

Any guidance or suggestions would be greatly appreciated!

i tried several way to avoid inline css.

Next-auth 403 forbidden important error while everything is correct

after entering correct email and password combination i can see the user in the server console which means it is correctly returning the user but after the signin the response i get in the console is:

POST http://localhost:3000/api/auth/callback/credentials 403 (Forbidden)
{error: 'AccessDenied', status: 403, ok: false, url: null}

pls try to Help me

I am trying to sign in the account with email and password which is saved in mongodb in format:

{
  "_id": {
    "$oid": "676d1d11309c3cdb5b8c37df"
  },
  "email": "[email protected]",
  "name": "Amit Dwivedi",
  "isverified": true,
  "age": "50",
  "password": "yash"
}

But when i was entering right email and password i was getting an unusual behaviour in the client console:

POST http://localhost:3000/api/auth/callback/credentials 403 (Forbidden)
{error: 'AccessDenied', status: 403, ok: false, url: null}

i think someone more experienced could help me in this.

this is in api/auth/[…nextauth]/route.js:

import NextAuth from 'next-auth'
import GithubProvider from 'next-auth/providers/github'
import GoogleProvider from 'next-auth/providers/google'
import CredentialsProvider from 'next-auth/providers/credentials'
import clientPromise from '@/app/lib/clientprom'

export const authOptions = NextAuth({
  providers: [
    CredentialsProvider({
      name: 'Credentials',
      async authorize(credentials) {
        let client = await clientPromise
        const db = client.db()
        const collection = db.collection('users')
        const user = await collection.findOne({ email: credentials.email, password: credentials.password })

        if (user) {
          console.log(user)
          return Promise.resolve(user)
        } else {
          return null  // or throw new Error("Invalid credentials");
        }
      },
    }),
    GithubProvider({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET,
      authorization: { params: { prompt: 'login' } },
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET
    }),
  ],
  callbacks: {
    async signIn({ user, account, profile, email }) {
      const client = await clientPromise
      const db = client.db()
      const collection = db.collection('users')

      if (account.provider === 'google' || account.provider === 'github') {
        let existingUser = await collection.findOne({ email: user.email, isverified: true })
        
        if (existingUser) {
          return true
        } else {
          await collection.insertOne({ email: user.email, name: profile.name, isverified: false })
          return true
        }
      }
    },
  },
})

export { authOptions as GET, authOptions as POST }

and
this is in login/page.js:

"use client";
import React, { useEffect ,useState} from "react";
import { signIn ,getCsrfToken} from "next-auth/react";
import { useForm } from "react-hook-form";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";

const Login = () => {
   
    const router = useRouter();
    const [csrfToken, setCsrfToken] = useState("")
    
    const {data:session} = useSession()

    useEffect(() => { 
      const fetchCsrfToken = async () => {
      const token = await getCsrfToken();
      setCsrfToken(token);
    };

    fetchCsrfToken();
        document.title = "Login - Get Me a Chai"
        if (session) {
            router.push("/createaccount");
        }
     
   }, [ session])
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm();

  const onSubmit = async (data) => {
   let response = await signIn("credentials", {
      email: data.email,
      password: data.password,
      csrfToken,
      redirect: false,
    });
    console.log(response)
  }

  const handleProviderSignIn = async (provider) => {
    const response = await signIn(provider);
  
  };
  return (
    <main className="flex">
      <div className="w-1/2 p-10">
      <div className="flex font-semibold text-[28px] leading-9 items-center"><p>Bittree</p> <img className="" width={22} src="greenlogo.svg" alt="" /></div>
     <div className="flex items-center flex-col gap-4 py-10 mt-16">
      <h1 className="font-extrabold text-[42px] leading-9 text-black">Sign Up or Log In</h1> 
      <p className="text-[#676b5f] font-normal">Welcome! Welcome! Welcome!</p>
      </div>
      <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4 px-10">
        <div className="flex flex-col">
        {errors.email && <span className="text-sm text-[#ff6b6b] font-semibold ">Please enter an email</span>}
        
        <input
          {...register("email", { required: true })}
          type="text"
          placeholder="Enter your Email*"
          className="bg-[#f6f7f5] p-4 outline-none border rounded-lg border-[#9a9a9a]"
        id="email"
        />
        </div>
        <div className="flex flex-col">
          {errors.password && <span className="text-sm text-[#ff6b6b] font-semibold ">Please enter an Password</span>}
        <input
          {...register("password", { required: true })}
          type="password"
          placeholder="Enter your Password*"
          className="bg-[#f6f7f5] p-4 outline-none border rounded-lg border-[#9a9a9a]"
        />
        </div>
          <button className="bg-[#8129d9] disabled:bg-[#8129d9c8] text-white p-3 font-semibold rounded-full" disabled={isSubmitting} type="submit">
          Sign In
        </button>
      </form>
      <p className="text-[#676b5f] font-normal text-center my-4">OR</p>
      <div className="flex flex-col gap-3 px-10">
      <button
        onClick={() => handleProviderSignIn("google")}
        type="button"
        className="text-black bg-[white] justify-center hover:bg-[#f6f7f5] border font-bold rounded-full items-center hover:border-[#f6f7f5] px-5 py-2.5 text-center inline-flex dark:focus:ring-[#4285F4]/55  gap-2"
      >
        <img src="google.svg" alt="" />
        Continue with Google
      </button>
      <button
        onClick={() =>handleProviderSignIn("github")}
        type="button"
        className="text-white bg-[#24292F] justify-center hover:bg-[#24292F]/90 font-bold rounded-full gap-1 px-5 py-2.5 text-center inline-flex items-center dark:focus:ring-gray-500 dark:hover:bg-[#050708]/30 me-2 mb-2"
      >
        <svg
          className="w-4 h-4 me-2"
          aria-hidden="true"
          xmlns="http://www.w3.org/2000/svg"
          fill="currentColor"
          viewBox="0 0 20 20"
        >
          <path
            fillRule="evenodd"
            d="M10 .333A9.911 9.911 0 0 0 6.866 19.65c.5.092.678-.215.678-.477 0-.237-.01-1.017-.014-1.845-2.757.6-3.338-1.169-3.338-1.169a2.627 2.627 0 0 0-1.1-1.451c-.9-.615.07-.6.07-.6a2.084 2.084 0 0 1 1.518 1.021 2.11 2.11 0 0 0 2.884.823c.044-.503.268-.973.63-1.325-2.2-.25-4.516-1.1-4.516-4.9A3.832 3.832 0 0 1 4.7 7.068a3.56 3.56 0 0 1 .095-2.623s.832-.266 2.726 1.016a9.409 9.409 0 0 1 4.962 0c1.89-1.282 2.717-1.016 2.717-1.016.366.83.402 1.768.1 2.623a3.827 3.827 0 0 1 1.02 2.659c0 3.807-2.319 4.644-4.525 4.889a2.366 2.366 0 0 1 .673 1.834c0 1.326-.012 2.394-.012 2.72 0 .263.18.572.681.475A9.911 9.911 0 0 0 10 .333Z"
            clipRule="evenodd"
          />
        </svg>
        Continue with Github
      </button>

</div>
      </div>

      <div className="w-1/2 relative overflow-hidden"><img className="absolute translate-y-[-20%]" src="images/banner.png" alt="" /></div>
    </main>
  );
};

export default Login;

Jquery : Uncaught SyntaxError: Failed to execute ‘appendChild’ on ‘Node’: missing ) after argument list

I’m trying to upload an image with jquery $.ajax method. I have been using the $.ajax code since many years, but strangely it is not working on this particular project. Here is the code

 <form id="adimgform">
       <input type="file" id="adimage" name="adimage" accept="image/png, image/gif, image/jpeg, image/webp" required>
 </form>   

Javascript code

$('#adimage').change(function(){
    uploadimage();
});

function uploadimage()
{
                const adimgform = new FormData($('#adimgform')[0]);
        
                $.ajax({
                    url: '/controller/upload-ad-image.php',
                    type : 'POST',
                    async: true,
                    cache: false,
                    contentType: false,
                    processData: false,
                    data: adimgform,
                    enctype: 'multipart/form-data', 
                    success: function (returndata) {            
                    $('#adform1result').html(returndata);    
                    }
                }); 
}

And this is the error im getting

Uncaught SyntaxError: Failed to execute 'appendChild' on 'Node': missing ) after argument list
    at m (jquery-3.7.1.min.js:2:880)
    at $e (jquery-3.7.1.min.js:2:46274)
    at ce.append (jquery-3.7.1.min.js:2:47633)
    at ce.<anonymous> (jquery-3.7.1.min.js:2:48729)
    at M (jquery-3.7.1.min.js:2:29497)
    at ce.html (jquery-3.7.1.min.js:2:48405)
    at Object.success (post-now.php?category=1&name=Automobiles:220:41)
    at c (jquery-3.7.1.min.js:2:25304)
    at Object.fireWith [as resolveWith] (jquery-3.7.1.min.js:2:26053)
    at l (jquery-3.7.1.min.js:2:77782)

strangely, all other forms are working on this site, so im really confused. Any help would be much appreciated, please.

WebGL mesh not working when I add things to mesh

I’m making a 3D physics engine and I need to add balls when I press a button, but whenever I click it, everything goes blank.

Here’s the code for the loop, event, and Ball object.
Loop: Cleares mesh, does physics and draws, solves collisions, updates mesh, and finally draws it.

initGL()
function loop(){
    //clear to animate
    
    mesh.verts=[
    ]
    mesh.inds=[]

    mesh.ind=0
    //do physics math
    balls.forEach(ball => {
        //draw sphere
        ball.draw()
        ball.phys()
    })
    //collisions
    for (let i = 0; i < substeps; i++){
        balls.forEach(ball => {
            ball.collwall()
            ball.collballs()
        })
    }
    //update the WebGL vertex array buffer and index array buffer
    mesh.update()
    runGLFrame()
    
    requestAnimationFrame(loop)
}
requestAnimationFrame(loop)

Event: Adds ball, updates mesh, clear mesh, draw all balls, updates mesh.


    balls.push(new Ball(5,5,0,0,0,0,1,0,1,1,1,0.8)) 
    //update the WebGL vertex array buffer and index array buffer
    mesh.update()
    //clear to animate
    mesh.verts=[
    ]
    mesh.inds=[]

    mesh.ind=0
    balls.forEach(ball => {
        ball.draw()
    })
    mesh.update()

Ball constructor: Initializes the ball object and draws a sphere.

constructor(x,y,z,vx,vy,vz,rad,r,g,b,w,bons){
    //sphere number
        this.sn=balls.length
        //current pos.
        this.p={x,y,z}
        //past pos.
        this.pp={x:x-vx,y:y-vy,z:z-vz}
        //velocity
        this.v={x:vx,y:vy,z:vz}
        //weight
        this.w=w
        //bounciness
        this.b=bons
        //radius
        this.rad=rad
        //color
        this.c={r,g,b}
        //add sphere to mesh, vertices and indices
        mesh.addSphere(20,20,x,y,z,rad,r,g,b)
   }
It was supposed to create a ball at 0,5,0, but instead it cleared everything. I copied the clear mesh code to the event to try to copy the thing that happens when I initialize it (before the loop and event) but it still doesn't work.

How can I get this d3js custom shape?

enter image description here

I am trying to create the shape of the image using d3js (if it’s any simpler way, please let me know)

I tried doing it but I don’t get it right, I don’t get the end and start position quite well, i tried adding numbers manually until it kinda looks good, and also i want to remove the gapangle, I think is useless:

enter image description here

This is the code that I used for getting the shape till now:

document.addEventListener("DOMContentLoaded", () => {
    const width = 1000; // Canvas width
    const height = 1000; // Canvas height
    const innerOuterRadius = 280; // Outer radius of the inner segments
    const outerInnerRadius = 295; // Inner radius of the outer segments
    const segmentColor = "#265152"; // Color for the segments
    const lineColor = "#FF0000"; // Color for the connecting lines
    const gapAngle = 0.05; // Gap between segments (in radians)
    const inclinationAngle = 0.06; // Small inclination for connectors (in radians)

    // Segment sizes (in degrees)
    const innerSegmentSizes = [133, 133]; // Inner segments
    const outerSegmentSizes = [40, 40]; // Outer segments to fill gaps

    // Convert degrees to radians
    const innerSegmentSizesRadians = innerSegmentSizes.map((deg) => (deg * Math.PI) / 180);
    const outerSegmentSizesRadians = outerSegmentSizes.map((deg) => (deg * Math.PI) / 180);

    // Create the SVG canvas
    const svg = d3
        .select("#c4")
        .append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", `translate(${width / 2}, ${height / 2})`);

    // Function to calculate polar coordinates
    const polarToCartesian = (radius, angle) => ({
        x: radius * Math.cos(angle),
        y: radius * Math.sin(angle),
    });

    // Draw inner segments (large, positioned symmetrically)
    innerSegmentSizesRadians.forEach((segmentAngle, index) => {
        const startAngle = index === 0 ? 0 : Math.PI; // Opposite sides
        const endAngle = startAngle + segmentAngle;

        const arc = d3
            .arc()
            .innerRadius(innerOuterRadius - 3)
            .outerRadius(innerOuterRadius)
            .startAngle(startAngle)
            .endAngle(endAngle);

        svg.append("path")
            .attr("d", arc)
            .attr("fill", segmentColor);
    });

    // Draw outer segments to fill spaces between inner segments
    outerSegmentSizesRadians.forEach((segmentAngle, index) => {
        const startAngle = index === 0
            ? innerSegmentSizesRadians[0] + gapAngle
            : innerSegmentSizesRadians[0] + Math.PI + gapAngle;
        const endAngle = startAngle + segmentAngle;

        const arc = d3
            .arc()
            .innerRadius(outerInnerRadius)
            .outerRadius(outerInnerRadius + 3)
            .startAngle(startAngle)
            .endAngle(endAngle);

        svg.append("path")
            .attr("d", arc)
            .attr("fill", segmentColor);
    });

    // Add connecting lines between the start and end of inner segments
    innerSegmentSizesRadians.forEach((segmentAngle, index) => {
        const startAngle = index === 0
            ? innerSegmentSizesRadians[0] + gapAngle + 1.517
            : innerSegmentSizesRadians[0] + Math.PI + 1.567; // Start of the inner segment
        
        const endAngle = startAngle + segmentAngle * 0.357; // End of the inner segment

        // Calculate the start and end points for the red lines
        const pointsToConnect = [
            { angle: startAngle }, // Start of the segment
            { angle: endAngle },   // End of the segment
        ];

        pointsToConnect.forEach(({ angle }) => {
            const innerPoint = polarToCartesian(innerOuterRadius, angle);

            // Shift the outer angle slightly to incline the connector
            const inclinedOuterAngle = angle + (index === 0 ? -inclinationAngle : inclinationAngle);
            const outerPoint = polarToCartesian(outerInnerRadius, inclinedOuterAngle);

            svg.append("line")
                .attr("x1", innerPoint.x)
                .attr("y1", innerPoint.y)
                .attr("x2", outerPoint.x)
                .attr("y2", outerPoint.y)
                .attr("stroke", lineColor)
                .attr("stroke-width", 2);
        });
    });
});

center megamenu div under nav button

I have used some code which I got from W3 schools to create a megamenu. I want the box to appear centred to the nav button selected, not centred to the whole page. I’m not really concerned about the mini view, it is full screen mode I am trying to set up. Everything else works fine apart from the alignment issue. My full code is here without the header code.

function myFunction() {
    var x = document.getElementById("myTopnav");
    if (x.className === "navbar") {
        x.className += " responsive";
    } else {
        x.className = "navbar";
    }
}
* {
    box-sizing: border-box;
}

body {
    margin: 0;
}

.navbar {
    overflow: hidden;
    background-color: #333;
    border-radius: 5px;
}

.navbar a {
    float: left;
    font-size: 16px;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

.navbar .icon {
    display: none;
}

.dropdown {
    float: left;
    overflow: hidden;
}

.dropdown .dropbtn {
    font-size: 16px;
    border: none;
    outline: none;
    color: white;
    padding: 14px 16px;
    background-color: inherit;
    font: inherit;
    margin: 0;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    width: 60%;
    left: 0;
    box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
    z-index: 1;
    border-radius: 10px;
}

.navbar .dropdown>.dropdown-content {
    left: 50%;
    transform: translate3d(-50%, 10px, 0);
}

.dropdown-content a {
    float: none;
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.navbar a:hover,
.dropdown:hover .dropbtn {
    background-color: #555;
    color: white;
}

.dropdown-content a:hover {
    background-color: #ddd;
    color: black;
}

.dropdown:hover .dropdown-content {
    display: block;
}

@media screen and (max-width: 992px) {
    .navbar a:not(:first-child),
    .dropdown .dropbtn {
        display: none;
    }

    .navbar a.icon {
        float: right;
        display: block;
    }
}

/* Create three equal columns that floats next to each other */
.column {
    float: left;
    width: 33.33%;
    padding: 10px;
    background-color: #fff;
    height: 250px;
    border-radius: 10px;
}

.column a {
    float: none;
    color: black;
    padding: 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.column a:hover {
    background-color: #eff;
}

/* Clear floats after the columns */
.row:after {
    content: "";
    display: table;
    clear: both;
}

@media screen and (max-width: 992px) {
    .navbar.responsive {
        position: relative;
    }

    .navbar.responsive .icon {
        position: absolute;
        right: 0;
        top: 0;
    }

    .navbar.responsive a {
        float: none;
        display: block;
        text-align: left;
    }

    .navbar.responsive .dropdown {
        float: none;
    }

    .navbar.responsive .dropdown-content {
        position: relative;
    }

    .navbar.responsive .dropdown .dropbtn {
        display: block;
        width: 100%;
        text-align: left;
    }

    .column {
        width: 100%;
        height: auto;
    }
}
<div class="line">
    <div class="s-12 l-12 center">
        <div class="navbar margin-bottom" id="myTopnav">
            <a href="#home">Home</a>
            <a href="#news">News</a>
            <a href="#news">News</a>
            <a href="#news">News</a>
            <a href="#news">News</a>
            <div class="dropdown">
                <button class="dropbtn">Dropdown <i class="fa fa-caret-down"></i>
                </button>
                <div class="dropdown-content">
                    <div class="row">
                        <div class="column">
                            <h3>Category 1</h3>
                            <a href="#">Link 1</a>
                            <a href="#">Link 2</a>
                            <a href="#">Link 3</a>
                        </div>
                        <div class="column">
                            <h3>Category 2</h3>
                            <a href="#">Link 1</a>
                            <a href="#">Link 2</a>
                            <a href="#">Link 3</a>
                        </div>
                        <div class="column">
                            <h3>Category 3</h3>
                            <a href="#">Link 1</a>
                            <a href="#">Link 2</a>
                            <a href="#">Link 3</a>
                        </div>
                    </div>
                </div>
            </div>
            <a href="#news">News</a>
            <a href="#news">News</a>
            <div class="dropdown">
                <button class="dropbtn">Dropdown <i class="fa fa-caret-down"></i>
                </button>
                <div class="dropdown-content">
                    <div class="row">
                        <div class="column">
                            <h3>Category 1</h3>
                            <a href="#">Link 1</a>
                            <a href="#">Link 2</a>
                            <a href="#">Link 3</a>
                        </div>
                        <div class="column">
                            <h3>Category 2</h3>
                            <a href="#">Link 1</a>
                            <a href="#">Link 2</a>
                            <a href="#">Link 3</a>
                        </div>
                        <div class="column">
                            <h3>Category 3</h3>
                            <a href="#">Link 1</a>
                            <a href="#">Link 2</a>
                            <a href="#">Link 3</a>
                        </div>
                    </div>
                </div>
            </div>
            <a href="javascript:void(0);" class="icon" onclick="myFunction()">
                <i class="fa fa-bars"></i>
            </a>
        </div>
    </div>
</div>

I have tried targeting the .dropdown-content class mostly. It always seems to break the navbar which inserts the dropdown box inside the navbar instead of below the navbar.

How to format POST request for Microsoft Graph API to create a new choice column on Sharepoint List with multi-select enabled?

I have a simple script that adds new columns to a specific List on my company’s Sharepoint site. I am having trouble figuring out how to create a new column/column definition as a Choice Field that has Allow Multiple Selections enabled. Below is the working default choice column creation code:

const apiUrl = `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${listId}/columns`;
console.log(JSON.stringify(columnPayload));
// Make the API request to create the column
const response = await fetch(apiUrl, {
    method: "POST",
    headers: {
        Authorization: `Bearer ${accessToken}`,
        "Content-Type": "application/json",
    },
    body: JSON.stringify(columnPayload),
});

The column payload looks like this:

{
  "name": "Color",
  "choice": {
    "choices": ["Red", "Green", "Blue", "Purple"],
    "displayAs": "dropDownMenu"
  }
}

The resulting column then appears on the Sharepoint list: (Edit Column Field Selected to see more details)
Column Settings View

If we expand the “More Options” we see that, as expected, the Allow Multiple Selections toggle is off.
More Options

I have looked within the Graph API documentation and have not come across anything that lets us configure the fields that would have this option enabled. I only see the following options: From here: https://learn.microsoft.com/en-us/graph/api/resources/choicecolumn?view=graph-rest-1.0
Graph API Choice Field Description

When asking AI, it spits out something like this:

{
    name: "Categories",
    choice: {
        choices: ["Option1", "Option2", "Option3", "Option4"],
        allowMultipleValues: true,
        displayAs: "dropDownMenu",
    },
}

However, there is no mention of “allowMultipleValues” in the documentation. I ultimately will be setting up the columns, then adding Items, and some of which will have multiple options for a given Choice field.

Any guidance would be appreciated.

(python socket) Is there a way to trigger a JS script on the front-end when a condition is met?

Merry Christmas. I am making a website and I want to change the view past-login with JavaScript.

The code responsible for detecting a valid login attempt looks like this:

def messages(status_OK, status_400, status_401, filtered_data):
    # change page after signup
    if filtered_data[0] == 'method=sign_up':
        if filtered_data[1] == 'username=' or filtered_data[2] == 'password=' or filtered_data[3] == 'email=':
            with open('status/error/signup_400.html', 'rb') as err: response = err.read()
            return status_400 + response
        with open('status/signup_success.html', 'rb') as success: response = success.read()
        return status_OK + response
        # change page after login
    elif filtered_data[0] == 'method=login_name':
        if postlogin.username():
            with open('status/username_success.html', 'rb') as success: response = success.read()
            return status_OK + response
        elif filtered_data[1] == 'username=' or filtered_data[2] == 'password=':
            with open('status/error/username_400.html', 'rb') as err: response = err.read()
            return status_400 + response
        else:
            with open('status/username_failed.html', 'rb') as fail: response = fail.read()
            return status_401 + response
    elif filtered_data[0] == 'method=login_email':
        if postlogin.username():
            with open('status/email_success.html', 'rb') as success: response = success.read()
            return status_OK + response
        elif filtered_data[1] == 'email=' or filtered_data[2] == 'password=':
            with open('status/error/email_400.html', 'rb') as err: response = err.read()
            return status_400 + response
        else:
            with open('status/email_failed.html', 'rb') as fail: response = fail.read()
            return status_401 + response

I want it to do more than just returning another webpage, specifically, I want it to execute JS on the front-end to set a flag that changes the webpage view ACCORDING TO THE MENTIONED CODE ^^^^^^^

So, how do I do it?

I know how to change the view, I just need a way to execute JS on the front-end without needing user actions.

Error: Unable to resolve module ‘../../tls_certs/server-keystore.p12’ in React Native project

I am working on a React Native project where I am trying to include a .p12 file for TLS configuration. However, I am facing the following error:

Error: Unable to resolve module ../../tls_certs/server-keystore.p12 from C:UsershamzaDesktopshareItshareITsrcservicesTCPProvider.jsx:

None of these files exist:
  * tls_certsserver-keystore.p12(.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)
  * tls_certsserver-keystore.p12
  24 |
  25 | const options = {
> 26 |   keystore: require('../../tls_certs/server-keystore.p12'),
     |                      ^
  27 | };
  28 |
  29 | export const TCPProvider = ({children}) => {}

  • Verified the file path and ensured that the server-keystore.p12 file exists in the tls_certs directory.

  • Cleaned the build cache using npm start –reset-cache and npx react-native start –reset-cache.

  • Tried changing the import to use import syntax instead of require.

Astro JS with astro@i18next at Cannot read properties of undefined (reading ‘map’) at supportedLanguages.map

I am using Astro js With astro-i18next
I have correctly integrated at astro.config

import astroI18next from "astro-i18next";

// https://astro.build/config
export default defineConfig({
  integrations: [ tailwind(), 
    astroI18next(),
   ],
   output: 'server',
   adapter: vercel(),
});


//astro-i18next.config.mjs

/** @type {import('astro-i18next').AstroI18nextConfig} */
export default {
    defaultLocale: "en",
    locales: ["en", "zh-CN"],
    backend: {
        loadPath: "/locales/{{lng}}/{{ns}}.json", // Ensure this matches your file structure
      },
  }

I have prepared my Json file for both language & generated the page
& I am trying to import HeadHrefLangs component in my layout file

//Layout.astro

import i18next, { t } from "i18next";
import { HeadHrefLangs } from "astro-i18next/components";

<!doctype html>
<html lang={i18next.language}>
  <head>
    <meta charset="UTF-8" />
    <meta name="description" content={description} />
    <meta name="viewport" content="width=device-width" />
    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
    <meta name="generator" content={Astro.generator} />
    <title>{title}</title>
    <HeadHrefLangs />
  </head>

but getting this error

the error
Cannot read properties of undefined (reading ‘map’)
at supportedLanguages.map((supportedLanguage) => (


components/HeadHrefLangs.astro:10:19
---
import i18next from "i18next";
import { localizeUrl } from "../..";

const supportedLanguages = i18next.languages;
const currentUrl = Astro.url.href;
---

{
  supportedLanguages.map((supportedLanguage) => (

    <link
      rel="alternate"
      hreflang={supportedLanguage}
      href={localizeUrl(currentUrl, supportedLanguage)}
    />
  ))
}

window.open equivalent to axios Sending post data

I made the data with FormDta

  var url = `/myapi`;

  var formData = new FormData();        
  formData.append('metadata',JSON.stringify(export_param));
  var dataurl = imagePreviewRef.current.makeImageDataUrl();
  var blobData = createBlob(dataurl);
  formData.append("file",blobData);

   axios.post(url,formData
    ,{headers: {'Content-Type': 'application/form-data'}}).then(res=>{});// it works

It works well so I want to replace the axios post to window.open

  window.myWin = window.open(url,"mywin",'status=yes,width=800,height=600');

However how can I pass the POST data to this window.open??

How to detect if an iframe fails to load due to X-Frame-Options or CSP frame-ancestors restrictions?

I’m trying to detect if an iframe fails to load because the target website has either:

  • Set X-Frame-Options to prevent embedding
  • Implemented Content Security Policy (CSP) with restrictive frame-ancestors directive

Here’s my current code:

<iframe id="myFrame" src="https://example.com"></iframe>
document.getElementById('myFrame').onload = function() {
    console.log('iframe loaded');
};

document.getElementById('myFrame').onerror = function() {
    console.log('iframe failed to load');
};

The iframe can fail to load in these scenarios:

  1. When target site sets X-Frame-Options: SAMEORIGIN or X-Frame-Options: DENY
  2. When target site has CSP header like:
    Content-Security-Policy: frame-ancestors 'none';
    // or
    Content-Security-Policy: frame-ancestors 'self';
    

However, in both cases, the onerror event doesn’t fire. I’ve tried these approaches:

  1. Checking iframe.contentWindow
  2. Using window.addEventListener(‘error’,…)
  3. Monitoring the iframe’s readyState
  4. Trying to access iframe.contentDocument (throws security error)

None of these methods reliably detect when the iframe fails to load due to either X-Frame-Options or CSP restrictions.

Is there a reliable way to detect these security-related loading failures? I need to show appropriate fallback content when embedding is prevented.

Expected behavior:

  • Detect when iframe content fails to load due to X-Frame-Options or CSP frame-ancestors
  • Show alternative content to users

Current behavior:

  • Silent failure
  • No error events triggered
  • Empty iframe displayed

Blank screen when lazy loading many images in NextJS tsx + Tailwindcss

I am displaying a series of images hosted in CDN on my NextJS page in the “masonry layout” structure (Just like Pinterest). As shown in Layout.

When I try to load it on my desktop it’s working fine. But only when I load it on my iPhone or lower screen sizes, the screen turns blank

or it displays “A problem repeatedly occurred”(problem message) Can you please tell me how to fix it or debug it.

The code is as below for this page. All of this happens inside a [slug] folder for multi page rendering.

'use client'
import React, { useEffect, useState } from 'react'
import Image from 'next/image'
import { useParams, useRouter } from 'next/navigation'
import { IoDownloadOutline } from "react-icons/io5";
import { useInView } from 'react-intersection-observer';
import LoadingSpinner from '../../components/LoadingSpinner'
import { RiGeminiFill } from "react-icons/ri";

interface Wallpaper {
  id: string | number
  thumbnail_url: string
  downloads: number
  categories: Array<string>
  resolution_count: number
}

function CategoryPage() {
  const [wallpapers, setWallpapers] = useState<Wallpaper[]>([])
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const { ref, inView } = useInView()
  const params = useParams()
  const router = useRouter()
  const [initialLoading, setInitialLoading] = useState(true)

  useEffect(() => {
    const fetchWallpapers = async () => {
      try {
        const response = await fetch(`${process.env.BACKEND_PUBLIC_API_URL}/fetch_wallpapers/category/${params.category}?page=${page}`)
        const data = await response.json()
        
        if (data.length === 0) {
          setHasMore(false)
          return
        }

        setWallpapers(prev => {
          const existingIds = new Set(prev.map((w: Wallpaper) => w.id))
          const newWallpapers = data.filter((w: Wallpaper) => !existingIds.has(w.id))
          return [...prev, ...newWallpapers]
        })
      } catch (error) {
        console.error('Error fetching wallpapers:', error)
      } finally {
        setInitialLoading(false)
        setIsLoading(false)
      }
    }

    if (hasMore) {
      fetchWallpapers()
    }
  }, [params.category, page, hasMore])

  const [isLoading, setIsLoading] = useState(false)

  useEffect(() => {
    if (inView && hasMore && !isLoading) {
      setIsLoading(true)
      setPage(prev => prev + 1)
    }
  }, [inView, hasMore, isLoading])
  
  useEffect(() => {
    setWallpapers([])
    setPage(1)
    setHasMore(true)
    setIsLoading(false)
  }, [params.category])

  const handleWallpaperClick = (wallpaper: Wallpaper) => {
    router.push(`/wallzone/wallpaper_view/${wallpaper.id}?categories=${wallpaper.categories.join(',')}`)
  }

  return (
    <div className="p-4 bg-paper-white min-h-screen pt-20
    max-sm:p-1 max-sm:pt-20">
      {initialLoading ? (
        <div className="h-[calc(100vh-80px)] flex items-center">
          <LoadingSpinner />
        </div>
      ) : (
        <div className="gap-3
        max-sm:columns-2 max-sm:gap-1 
        md:columns-3 
        lg:columns-5 
        2xl:columns-6 2xl:gap-4 [column-fill:_balance]">
          {wallpapers.map((wallpaper) => (
            <div key={wallpaper.id} className="break-inside-avoid mb-4" onContextMenu={(e) => e.preventDefault()}>
              <div 
                className="relative w-full overflow-hidden rounded-lg group cursor-pointer" 
                onClick={() => handleWallpaperClick(wallpaper)}
              >
                {wallpaper.thumbnail_url && (<Image
                  src={wallpaper.thumbnail_url}
                  alt={wallpaper.id.toString()}
                  width={0}
                  height={0}
                  loading="lazy"
                  className="w-full h-auto lg:hover:scale-105 lg:transition-transform lg:duration-300"
                  sizes="(max-width: 640px) 90vw,
                         (max-width: 768px) 45vw,
                         (max-width: 1024px) 30vw,
                         22vw"
                  style={{
                    width: '100%',
                    height: 'auto',
                    minHeight: '100px',
                  }}
                  unoptimized
                />)}
                {wallpaper.resolution_count === 4 && (
                  <div className="absolute top-2 right-2">
                    <RiGeminiFill className="text-yellow-400 text-xl" />
                  </div>
                )}
                <button className="absolute flex items-center rounded-full px-2 shadow-md text-white opacity-0 group-hover:opacity-100 transition-opacity duration-300
                max-lg:bottom-2 max-lg:right-2 
                lg:bottom-1 lg:right-1">
                  <IoDownloadOutline className="mr-1" />
                  {wallpaper.downloads}
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
      {isLoading && !initialLoading && (
        <div className="py-4">
          <LoadingSpinner />
        </div>
      )}
    </div>
  )
}

export default CategoryPage

“SyntaxError: Cannot use import statement outside a module” when running compiled javascript code with Node.js

I am using TypeScript to build a Node.js application. After compiling the code, when I run the output JavaScript file using npm start, it throws the following error:

When I run the following command:

npm start

I get this error:

SyntaxError: Cannot use import statement outside a module

My app.ts (mainfile):

import "reflect-metadata"

import express from 'express';
import dotenv from 'dotenv';
import { useExpressServer } from 'routing-controllers';
import { connectDB } from './config/db';
import { CONNECTED_MESSAGE } from './common';
import { ENV_DETAILS } from './env';


dotenv.config();

// Create an instance of an Express app
const app = express();

// Configure built-in middleware to parse various types of request bodies
app.use(express.json()); // For parsing application/json
app.use(express.urlencoded({ extended: true })); // For parsing application/x-www-form-urlencoded


// Configure routing-controllers with the Express app
useExpressServer(app, {
  controllers: ENV_DETAILS.dirs.controllers
});

// Connect to the database and start the server
const port =  3000;
connectDB().then(() => {
  app.listen(port, () => {
    console.log(CONNECTED_MESSAGE.listenPort, `${port}`);
  });
});

My package.json File:

"scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start": "node dist/app.js",
    "dev": "tsx src/app.ts",
    "build": "tsc && tsc-alias"
  },

My tsconfig.json File:

{
  "compilerOptions": {
    "module": "ESNext",
    "target": "ESNext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "resolveJsonModule": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "baseUrl": ".",
    "paths": {
      "@src/*": [
        "src/*"
      ]
    }
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "dist"
  ]
}

Environment : Node.js version: 20.12.2 and npm version: 6.14.11

I expect the command npm start to execute the compiled code without throwing an error.
Are there any issues with my configuration, or am I missing something critical?
How can I resolve this Error?