问:
How to send requests including token using next-auth and fetch
I am implementing a project for seller hub (dashboard) for ecommerce website and I used next js and next-auth for making login and protected routes. I am using node js as a backend for the website. I have the route for login as follows:

```<code>const express = require('express')
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const { auth } = require('../Authentication/basicAuth');
const { sellerRole } = require('../Authorization/sellerRole');

const router = express();

router.post('/seller/login/', async(req, res) => {
    try{
        const { email, password } = req.body;
        const user = await sellerModel.findOne({email: email});
        console.log(user);
        console.log(password);
        if(user){
            const passwordValidate = await bcrypt.compare(req.body.password, user.password);
            console.log(passwordValidate);
            if(passwordValidate){
                const token = jwt.sign({
                    data: {username: user.username, userId: user.id}
                }, process.env.SECRET_KEY)
                res.json(token);
            }else{
                res.status(403).send("Invalid Authentication");
            }
        }else{
            res.status(403).send("Invalid Authentication");
        }
    }catch (err) {
        res.status(500).send(err.message);
    }
})

router.post('/product/', auth, sellerRole, async (req, res) => {
    try {
        const newProduct = req.body;
        res.json(registeredProduct);

    } catch (err) {
        res.status(403).send(err.message);
    }

})
</code>```

and  I have set the authentication as:

```<code>const jwt = require('jsonwebtoken');

function auth(req, res, next) {
 const { Authorization } = req.headers;
 console.log(Authorization);

 jwt.verify(Authorization, process.env.SECRET_KEY, function (error, decoded) {
 if(decoded){
 req.userId = decoded.data.userId;
 console.log(decoded.data);
        }
 if(error){
 res.status(401).send('You must Log in first !!!');
 return;

        }
 next();
    })
}
</code>```

module.exports = { auth };

The same for seller Authorization:

```<code>const { sellerModel } = require('../Models/seller')

async function sellerRole(req, res, next) {
 const seller = await sellerModel.findById(req.userId);
 console.log(seller);
 if (seller != null) {
 next();
    }else{
 res.status(403).send("Not Auhtorized user");
    }
}

module.exports = { sellerRole };
</code>```

In the front, I made the [...nextauth] file in the pages/api/auth with the following code:

```<code>import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials";
import { getToken } from "next-auth/jwt";

let userAccount = null;
let token = null;

export const authOptions = {
  session: {
    strategy: 'jwt'
  },
  providers: [
    CredentialsProvider({
      type: 'credentials',
      credentials: {},
      async authorize(credentials, req){

        const res = await fetch("http://localhost:3030/seller/login", {
            method: 'POST',
            body: JSON.stringify(credentials),
            headers: { "Content-Type": "application/json" }
        })

        const user = await res.json();

        token = await getToken({ req })

        if(res.ok && user) {
          userAccount = user;
            return user
        }

        return null;
      }
    })
  ],
  pages: {
    signIn: '/auth/login',
  },
  callbacks: {
    async jwt(token, account) {
      console.log("JWT Token User");
      console.log(token.account);
      if (typeof user !== typeof undefined)
      {
          token.accessToken = account.access_token;
      }
      return token;
    },
    async session(session, token, user) {
      console.log("Session token");
      console.log(token);
      if (userAccount !== null)
      {
          session.user = userAccount;
      }
      else if (typeof token !== typeof undefined)
      {
          session.accessToken = token.accessToken
      }
      console.log("session callback returning");
      console.log(session);
      return session;
  },

  },

}

export default NextAuth(authOptions)

</code>```

I have a login page which take my credintials and check with database

```<code>
import React from 'react'
import { useSession, signIn, signOut } from "next-auth/react";
import Router from 'next/router';

const Login = () => {
  const session = useSession();
  React.useEffect(() => {
    if(session.status === 'authenticated') Router.replace("/dashboard");
  }, [session.status]);
    const [userInfo, setUserInfo] = React.useState({email: '', password: ''})
    const handleSubmit = async (e) => {
      e.preventDefault();
      const res = await signIn("credentials", {
        email: userInfo.email,
        password: userInfo.password,
        redirect: false,
      });
      console.log(res);
    };
  return (
   ...
  )

export default Login

</code>```

Now, I have a page for posting new product to the database, which requires a token to be send with the request

```<code>import React from 'react'
import { useSession } from 'next-auth/react';
import { getToken } from "next-auth/jwt"
import { getCookie } from 'cookies-next';
import Router from 'next/router';
import { forwardRef } from 'react';
import { useFormik, Formik } from 'formik';
import * as Yup from 'yup';
import { FiDollarSign } from 'react-icons/fi';
import NavbarPage from '../../components/navBar';
import Footer from '../../components/footer';

const newproduct = () => {
  const { data: session, status } = useSession({
    required: true,
  })
  console.log(session)

    React.useEffect(() => {
      if(status === 'unauthenticated') Router.replace("/auth/login");
    }, [status]);
    if(status === 'loading'){
      return <div className='h-screen w-screen flex justify-center items-center'><Spinner color="#f59e0b" className="h-12" /></div>
    }

    if(status === 'authenticated'){

    return (
        <div className=" bg-gray-700">

    <div className='bg-white'>
        <NavbarPage />
    </div>
        <div className='p-4 dashboardHeight' style={{minHeight: 'calc(100vh-206px)'}}>
        <h1 className='p-6 font-bold text-4xl text-slate-50'>Inbox</h1>
        <div className='flex justify-center w-full'>

            <Formik
            initialValues= {{
            title: '',
            brand: '',
            category: '',
            price: '',
            quantity: '',
            mImage: '',
            aImages: '',
            }}
            validationSchema= {validateSchema}
            onSubmit={ async(values) => {
              // window.alert(JSON.stringify(values));
              console.log(JSON.stringify(values))
              const res = await fetch("http://localhost:3030/product", {
                method: 'POST',
                body: JSON.stringify(values),
                headers: {
                  "Content-Type": "application/json",
                  "authentication": session.user ### <<< here
              }
        })

                const user = await res.json();
            }}
            >
        {props => (
      <form onSubmit={props.handleSubmit} className="w-4/5" method='post' encType='multipart/form-data'>
        <Field
          dot={true}
          error={props.touched?.title && props.errors?.title}
          label="Title (Latin)"
          name="title"
          onChange={props.handleChange}
          type="text"
        />
        <Field
          dot={true}
          error={props.touched?.brand && props.errors?.brand}
          label="Brand (Latin)"
          name="brand"
          onChange={props.handleChange}
          type="text"
        />
        <Field
          dot={true}
          error={props.touched?.category && props.errors?.category}
          label="Category (Latin)"
          name="category"
          onChange={props.handleChange}
          type="select"
          >
            <option>-Select Product Category-</option>
            <option value="Supermarket">Supermarket</option>
            <option value="Fashion">Fashion</option>
            <option value="Health & Beauty">Health & Beauty</option>
            <option value="Baby Products">Baby Products</option>
            <option value="Phones & Tablets">Phones & Tablets</option>
            <option value="Home & Office">Home & Office</option>
            <option value="Electronics">Electronics</option>
            <option value="Computing">Computing</option>
            <option value="Sporting Goods">Sporting Goods</option>
            <option value="Gaming">Gaming</option>
            <option value="Automobile">Automobile</option>
          </Field>
        <Field
          dot={true}
          error={props.touched?.price && props.errors?.price}
          icon={<PriceIcon />}
          label="Price"
          name="price"
          onChange={props.handleChange}
          type="text"
        />
        <Field
          dot={true}
          error={props.touched?.quantity && props.errors?.quantity}
          label="Quantity"
          name="quantity"
          onChange={props.handleChange}
          type="text"
        />
        <Field
          dot={true}
          error={props.touched?.mImage && props.errors?.mImage}
          label="Main Image"
          name="mImage"
          onChange={props.handleChange}
          type="file"
        />
        <Field
          dot={false}
          error={props.touched?.aImages && props.errors?.aImages}
          label="Addtional Images"
          name="aImages"
          onChange={props.handleChange}
          type="file"
          // multiple="multiple"
        />
        <button
          className="mt-8 bg-black active:bg-gray-900 focus:outline-none text-white rounded px-4 py-1"
          type="submit"
        >
          Add Product
        </button>
      </form>)}
            </Formik>
            </div>
        </div>
        <Footer/>
        </div>
    )
    }
}

export default newproduct

// Yup validation schema
const validateSchema = Yup.object().shape({
    title: Yup.string().required('Field is required'),
    brand: Yup.string().required('Field is required'),
    category: Yup.string().required('Field is required'),
    price: Yup.string().required('Field is required'),
    quantity: Yup.string().required('Field is required'),
    mImage: Yup.string().required('Field is required'),
    aImages: Yup.string(),
  });

  /*  COMPONENT LOGIC */

  const style = {
    dot: `after:content-['*'] after:ml-0.5 after:text-red-500`,
    error: `ring-red-500 ring-1`,
    disabled: `cursor-not-allowed`,
    container: `relative mb-6 mt-3`,
    errorMessage: `text-sm text-red-500 mt-2`,
    checkboxLabel: `block overflow-hidden h-6 rounded-full bg-gray-300`,
    checkboxContainer: `relative w-10 mr-2 align-middle select-none mt-2`,
    iconContainer: `absolute flex border border-transparent left-0 top-0 h-full w-10`,
    icon: `flex items-center justify-center rounded-tl rounded-bl z-10 text-gray-400 text-lg h-full w-full`,
    checkbox: `checked:bg-blue-500 checked:right-0 focus:outline-none right-4 duration-200 ease-in absolute block w-6 h-6 rounded-full bg-white border-4 appearance-none cursor-pointer`,
    default: `text-base relative flex flex-1 w-full mt-1 rounded-md py-2 px-4 bg-white text-gray-700 placeholder-gray-400 text-base focus:outline-none focus:ring-1 focus:border-transparent border`,
  };

  const Field = forwardRef(
    (
      { disabled, dot, error, icon, label, name, type = 'text', ...rest },
      ref,
    ) => {
      let component;

      // if you won't use select, you can delete this part
      if (type === 'select') {
        component = (
          <select
            aria-required={dot}
            aria-invalid={!!error}
            className={`${style.default} ${disabled ? style.disabled : ''}
               ${error ? style.error : 'border-gray-300'}
            `}
            disabled={disabled}
            id={name}
            name={name}
            ref={ref}
            {...rest}
          />
        );
      }

      // if you won't use textarea, you can delete this part
      if (type === 'textarea') {
        component = (
          <textarea
            aria-required={dot}
            aria-invalid={!!error}
            className={`${style.default} ${disabled ? style.disabled : ''}
               ${error ? style.error : 'border-gray-300'}
            `}
            disabled={disabled}
            id={name}
            name={name}
            ref={ref}
            {...rest}
          />
        );
      }

      // if you won't use checkbox, you can delete this part and the classes checkbox, checkboxContainer and checkboxLabel
      if (type === 'checkbox') {
        component = (
          <div className={style.checkboxContainer}>
            <input
              aria-required={dot}
              aria-invalid={!!error}
              className={`${style.checkbox} ${disabled ? style.disabled : ''}`}
              disabled={disabled}
              id={name}
              name={name}
              type="checkbox"
              {...rest}
            />
            <span className={style.checkboxLabel} />
          </div>
        );
      }

      // if you won't use input, you can delete this part
      if (type !== 'checkbox' && type !== 'select' && type !== 'textarea') {
        component = (
          <div className="relative">
            <div className={style.iconContainer}>
              <div className={style.icon}>{icon}</div>
            </div>
            <input
              aria-required={dot}
              aria-invalid={!!error}
              className={`${style.default} ${icon ? 'pl-12' : ''}
                 ${error ? style.error : 'border-gray-300'}
                 ${disabled ? style.disabled : ''}
              `}
              disabled={disabled}
              id={name}
              name={name}
              type={type}
              ref={ref}
              {...rest}
            />
            {error && <ErrorIcon />}
          </div>
        );
      }

      return (
        <div className={`${style.container} ${disabled ? 'opacity-50' : ''}`}>
          <label htmlFor={name} className={`text-white ${dot && style.dot}`}>
            {label}
          </label>
          {component}
          {error && (
            <span role="alert" className={style.errorMessage}>
              {error}
            </span>
          )}
        </div>
      );
    },
  );

  Field.displayName = 'Field';

  const ErrorIcon = () => (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      width="15"
      height="15"
      fill="currentColor"
      className="absolute right-2 -mt-7 text-red-500"
      viewBox="0 0 1792 1792"
    >
      <path d="M1024 1375v-190q0-14-9.5-23.5t-22.5-9.5h-192q-13 0-22.5 9.5t-9.5 23.5v190q0 14 9.5 23.5t22.5 9.5h192q13 0 22.5-9.5t9.5-23.5zm-2-374l18-459q0-12-10-19-13-11-24-11h-220q-11 0-24 11-10 7-10 21l17 457q0 10 10 16.5t24 6.5h185q14 0 23.5-6.5t10.5-16.5zm-14-934l768 1408q35 63-2 126-17 29-46.5 46t-63.5 17h-1536q-34 0-63.5-17t-46.5-46q-37-63-2-126l768-1408q17-31 47-49t65-18 65 18 47 49z" />
    </svg>
  );

  const LockIcon = () => (
    <svg
      height="20"
      width="20"
      stroke="currentColor"
      fill="currentColor"
      strokeWidth="0"
      viewBox="0 0 448 512"
      xmlns="http://www.w3.org/2000/svg"
    >
      <path d="M400 224h-24v-72C376 68.2 307.8 0 224 0S72 68.2 72 152v72H48c-26.5 0-48 21.5-48 48v192c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V272c0-26.5-21.5-48-48-48zm-104 0H152v-72c0-39.7 32.3-72 72-72s72 32.3 72 72v72z" />
    </svg>
  );

  const PriceIcon = () => (
    <FiDollarSign className="text-3xl"/>
  );

  const Spinner = ({ color, className }) => (
    <svg
      fill={color}
      viewBox="0 0 1792 1792"
      className={`${className} flex-no-shrink animate-spin`}
      xmlns="http://www.w3.org/2000/svg"
    >
      <path d="M1760 896q0 176-68.5 336t-184 275.5-275.5 184-336 68.5-336-68.5-275.5-184-184-275.5-68.5-336q0-213 97-398.5t265-305.5 374-151v228q-221 45-366.5 221t-145.5 406q0 130 51 248.5t136.5 204 204 136.5 248.5 51 248.5-51 204-136.5 136.5-204 51-248.5q0-230-145.5-406t-366.5-221v-228q206 31 374 151t265 305.5 97 398.5z" />
    </svg>
  );
</code>```

Now, there is an error with session.user is not recognized although when I logged it, it gave me object

Note: I already tested the backend and is working fine and the app is working if I entered the token manually, the problem of getting the token to be in the header of the requests dynamically.

I tried to get the token from the session, but I couldn't reach any data inside. also I tried to get the token from the cookie, but it gives me undefined

Even when I copy The token manually from the terminal gives me the error
Error: newproduct.js?84e9:54          POST http://localhost:3030/product 401 (Unauthorized)
which means token is wrong

Body:
I am implementing a project for seller hub (dashboard) for ecommerce website and I used next js and next-auth for making login and protected routes. I am using node js as a backend for the website. I have the route for login as follows:

const express = require('express')
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const { auth } = require('../Authentication/basicAuth');
const { sellerRole } = require('../Authorization/sellerRole');

const router = express();

router.post('/seller/login/', async(req, res) => {
    try{
        const { email, password } = req.body;
        const user = await sellerModel.findOne({email: email});
        console.log(user);
        console.log(password);
        if(user){
            const passwordValidate = await bcrypt.compare(req.body.password, user.password);
            console.log(passwordValidate);
            if(passwordValidate){
                const token = jwt.sign({
                    data: {username: user.username, userId: user.id}
                }, process.env.SECRET_KEY)
                res.json(token);
            }else{
                res.status(403).send("Invalid Authentication");
            }
        }else{
            res.status(403).send("Invalid Authentication");
        }
    }catch (err) {
        res.status(500).send(err.message);
    }
})

router.post('/product/', auth, sellerRole, async (req, res) => {
    try {
        const newProduct = req.body;
        res.json(registeredProduct);

    } catch (err) {
        res.status(403).send(err.message);
    }

})

and  I have set the authentication as:

const jwt = require('jsonwebtoken');

function auth(req, res, next) {
 const { Authorization } = req.headers;
 console.log(Authorization);

 jwt.verify(Authorization, process.env.SECRET_KEY, function (error, decoded) {
 if(decoded){
 req.userId = decoded.data.userId;
 console.log(decoded.data);
        }
 if(error){
 res.status(401).send('You must Log in first !!!');
 return;

        }
 next();
    })
}

module.exports = { auth };

The same for seller Authorization:

const { sellerModel } = require('../Models/seller')

async function sellerRole(req, res, next) {
 const seller = await sellerModel.findById(req.userId);
 console.log(seller);
 if (seller != null) {
 next();
    }else{
 res.status(403).send("Not Auhtorized user");
    }
}

module.exports = { sellerRole };

In the front, I made the [...nextauth] file in the pages/api/auth with the following code:

import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials";
import { getToken } from "next-auth/jwt";

let userAccount = null;
let token = null;

export const authOptions = {
  session: {
    strategy: 'jwt'
  },
  providers: [
    CredentialsProvider({
      type: 'credentials',
      credentials: {},
      async authorize(credentials, req){

        const res = await fetch("http://localhost:3030/seller/login", {
            method: 'POST',
            body: JSON.stringify(credentials),
            headers: { "Content-Type": "application/json" }
        })

        const user = await res.json();

        token = await getToken({ req })

        if(res.ok && user) {
          userAccount = user;
            return user
        }

        return null;
      }
    })
  ],
  pages: {
    signIn: '/auth/login',
  },
  callbacks: {
    async jwt(token, account) {
      console.log("JWT Token User");
      console.log(token.account);
      if (typeof user !== typeof undefined)
      {
          token.accessToken = account.access_token;
      }
      return token;
    },
    async session(session, token, user) {
      console.log("Session token");
      console.log(token);
      if (userAccount !== null)
      {
          session.user = userAccount;
      }
      else if (typeof token !== typeof undefined)
      {
          session.accessToken = token.accessToken
      }
      console.log("session callback returning");
      console.log(session);
      return session;
  },

  },

}

export default NextAuth(authOptions)

I have a login page which take my credintials and check with database

import React from 'react'
import { useSession, signIn, signOut } from "next-auth/react";
import Router from 'next/router';

const Login = () => {
  const session = useSession();
  React.useEffect(() => {
    if(session.status === 'authenticated') Router.replace("/dashboard");
  }, [session.status]);
    const [userInfo, setUserInfo] = React.useState({email: '', password: ''})
    const handleSubmit = async (e) => {
      e.preventDefault();
      const res = await signIn("credentials", {
        email: userInfo.email,
        password: userInfo.password,
        redirect: false,
      });
      console.log(res);
    };
  return (
   ...
  )

export default Login

Now, I have a page for posting new product to the database, which requires a token to be send with the request

import React from 'react'
import { useSession } from 'next-auth/react';
import { getToken } from "next-auth/jwt"
import { getCookie } from 'cookies-next';
import Router from 'next/router';
import { forwardRef } from 'react';
import { useFormik, Formik } from 'formik';
import * as Yup from 'yup';
import { FiDollarSign } from 'react-icons/fi';
import NavbarPage from '../../components/navBar';
import Footer from '../../components/footer';

const newproduct = () => {
  const { data: session, status } = useSession({
    required: true,
  })
  console.log(session)

    React.useEffect(() => {
      if(status === 'unauthenticated') Router.replace("/auth/login");
    }, [status]);
    if(status === 'loading'){
      return
<Spinner color="#f59e0b" className="h-12" />

    }

    if(status === 'authenticated'){

    return (

        <NavbarPage />

Inbox

            <Formik
            initialValues= {{
            title: '',
            brand: '',
            category: '',
            price: '',
            quantity: '',
            mImage: '',
            aImages: '',
            }}
            validationSchema= {validateSchema}
            onSubmit={ async(values) => {
              // window.alert(JSON.stringify(values));
              console.log(JSON.stringify(values))
              const res = await fetch("http://localhost:3030/product", {
                method: 'POST',
                body: JSON.stringify(values),
                headers: {
                  "Content-Type": "application/json",
                  "authentication": session.user ### <<< here
              }
        })

                const user = await res.json();
            }}
            >
        {props => (
      <form onSubmit={props.handleSubmit} className="w-4/5" method='post' encType='multipart/form-data'>
        <Field
          dot={true}
          error={props.touched?.title && props.errors?.title}
          label="Title (Latin)"
          name="title"
          onChange={props.handleChange}
          type="text"
        />
        <Field
          dot={true}
          error={props.touched?.brand && props.errors?.brand}
          label="Brand (Latin)"
          name="brand"
          onChange={props.handleChange}
          type="text"
        />
        <Field
          dot={true}
          error={props.touched?.category && props.errors?.category}
          label="Category (Latin)"
          name="category"
          onChange={props.handleChange}
          type="select"
          >
            <option>-Select Product Category-</option>
            <option value="Supermarket">Supermarket</option>
            <option value="Fashion">Fashion</option>
            <option value="Health & Beauty">Health & Beauty</option>
            <option value="Baby Products">Baby Products</option>
            <option value="Phones & Tablets">Phones & Tablets</option>
            <option value="Home & Office">Home & Office</option>
            <option value="Electronics">Electronics</option>
            <option value="Computing">Computing</option>
            <option value="Sporting Goods">Sporting Goods</option>
            <option value="Gaming">Gaming</option>
            <option value="Automobile">Automobile</option>
          </Field>
        <Field
          dot={true}
          error={props.touched?.price && props.errors?.price}
          icon={<PriceIcon />}
          label="Price"
          name="price"
          onChange={props.handleChange}
          type="text"
        />
        <Field
          dot={true}
          error={props.touched?.quantity && props.errors?.quantity}
          label="Quantity"
          name="quantity"
          onChange={props.handleChange}
          type="text"
        />
        <Field
          dot={true}
          error={props.touched?.mImage && props.errors?.mImage}
          label="Main Image"
          name="mImage"
          onChange={props.handleChange}
          type="file"
        />
        <Field
          dot={false}
          error={props.touched?.aImages && props.errors?.aImages}
          label="Addtional Images"
          name="aImages"
          onChange={props.handleChange}
          type="file"
          // multiple="multiple"
        />
        <button
          className="mt-8 bg-black active:bg-gray-900 focus:outline-none text-white rounded px-4 py-1"
          type="submit"
        >
          Add Product
        </button>
      </form>)}
            </Formik>

    )
    }
}

export default newproduct

// Yup validation schema
const validateSchema = Yup.object().shape({
    title: Yup.string().required('Field is required'),
    brand: Yup.string().required('Field is required'),
    category: Yup.string().required('Field is required'),
    price: Yup.string().required('Field is required'),
    quantity: Yup.string().required('Field is required'),
    mImage: Yup.string().required('Field is required'),
    aImages: Yup.string(),
  });

  /*  COMPONENT LOGIC */

  const style = {
    dot: `after:content-['*'] after:ml-0.5 after:text-red-500`,
    error: `ring-red-500 ring-1`,
    disabled: `cursor-not-allowed`,
    container: `relative mb-6 mt-3`,
    errorMessage: `text-sm text-red-500 mt-2`,
    checkboxLabel: `block overflow-hidden h-6 rounded-full bg-gray-300`,
    checkboxContainer: `relative w-10 mr-2 align-middle select-none mt-2`,
    iconContainer: `absolute flex border border-transparent left-0 top-0 h-full w-10`,
    icon: `flex items-center justify-center rounded-tl rounded-bl z-10 text-gray-400 text-lg h-full w-full`,
    checkbox: `checked:bg-blue-500 checked:right-0 focus:outline-none right-4 duration-200 ease-in absolute block w-6 h-6 rounded-full bg-white border-4 appearance-none cursor-pointer`,
    default: `text-base relative flex flex-1 w-full mt-1 rounded-md py-2 px-4 bg-white text-gray-700 placeholder-gray-400 text-base focus:outline-none focus:ring-1 focus:border-transparent border`,
  };

  const Field = forwardRef(
    (
      { disabled, dot, error, icon, label, name, type = 'text', ...rest },
      ref,
    ) => {
      let component;

      // if you won't use select, you can delete this part
      if (type === 'select') {
        component = (
          <select
            aria-required={dot}
            aria-invalid={!!error}
            className={`${style.default} ${disabled ? style.disabled : ''}
               ${error ? style.error : 'border-gray-300'}
            `}
            disabled={disabled}
            id={name}
            name={name}
            ref={ref}
            {...rest}
          />
        );
      }

      // if you won't use textarea, you can delete this part
      if (type === 'textarea') {
        component = (
          <textarea
            aria-required={dot}
            aria-invalid={!!error}
            className={`${style.default} ${disabled ? style.disabled : ''}
               ${error ? style.error : 'border-gray-300'}
            `}
            disabled={disabled}
            id={name}
            name={name}
            ref={ref}
            {...rest}
          />
        );
      }

      // if you won't use checkbox, you can delete this part and the classes checkbox, checkboxContainer and checkboxLabel
      if (type === 'checkbox') {
        component = (

            <input
              aria-required={dot}
              aria-invalid={!!error}
              className={`${style.checkbox} ${disabled ? style.disabled : ''}`}
              disabled={disabled}
              id={name}
              name={name}
              type="checkbox"
              {...rest}
            />

        );
      }

      // if you won't use input, you can delete this part
      if (type !== 'checkbox' && type !== 'select' && type !== 'textarea') {
        component = (

{icon}

            <input
              aria-required={dot}
              aria-invalid={!!error}
              className={`${style.default} ${icon ? 'pl-12' : ''}
                 ${error ? style.error : 'border-gray-300'}
                 ${disabled ? style.disabled : ''}
              `}
              disabled={disabled}
              id={name}
              name={name}
              type={type}
              ref={ref}
              {...rest}
            />
            {error && <ErrorIcon />}

        );
      }

      return (
        <div className={`${style.container} ${disabled ? 'opacity-50' : ''}`}>
          <label htmlFor={name} className={`text-white ${dot && style.dot}`}>
            {label}

          {component}
          {error && (

              {error}

          )}

      );
    },
  );

  Field.displayName = 'Field';

  const ErrorIcon = () => (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      width="15"
      height="15"
      fill="currentColor"
      className="absolute right-2 -mt-7 text-red-500"
      viewBox="0 0 1792 1792"
    >
      <path d="M1024 1375v-190q0-14-9.5-23.5t-22.5-9.5h-192q-13 0-22.5 9.5t-9.5 23.5v190q0 14 9.5 23.5t22.5 9.5h192q13 0 22.5-9.5t9.5-23.5zm-2-374l18-459q0-12-10-19-13-11-24-11h-220q-11 0-24 11-10 7-10 21l17 457q0 10 10 16.5t24 6.5h185q14 0 23.5-6.5t10.5-16.5zm-14-934l768 1408q35 63-2 126-17 29-46.5 46t-63.5 17h-1536q-34 0-63.5-17t-46.5-46q-37-63-2-126l768-1408q17-31 47-49t65-18 65 18 47 49z" />
    </svg>
  );

  const LockIcon = () => (
    <svg
      height="20"
      width="20"
      stroke="currentColor"
      fill="currentColor"
      strokeWidth="0"
      viewBox="0 0 448 512"
      xmlns="http://www.w3.org/2000/svg"
    >
      <path d="M400 224h-24v-72C376 68.2 307.8 0 224 0S72 68.2 72 152v72H48c-26.5 0-48 21.5-48 48v192c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V272c0-26.5-21.5-48-48-48zm-104 0H152v-72c0-39.7 32.3-72 72-72s72 32.3 72 72v72z" />
    </svg>
  );

  const PriceIcon = () => (
    <FiDollarSign className="text-3xl"/>
  );

  const Spinner = ({ color, className }) => (
    <svg
      fill={color}
      viewBox="0 0 1792 1792"
      className={`${className} flex-no-shrink animate-spin`}
      xmlns="http://www.w3.org/2000/svg"
    >
      <path d="M1760 896q0 176-68.5 336t-184 275.5-275.5 184-336 68.5-336-68.5-275.5-184-184-275.5-68.5-336q0-213 97-398.5t265-305.5 374-151v228q-221 45-366.5 221t-145.5 406q0 130 51 248.5t136.5 204 204 136.5 248.5 51 248.5-51 204-136.5 136.5-204 51-248.5q0-230-145.5-406t-366.5-221v-228q206 31 374 151t265 305.5 97 398.5z" />
    </svg>
  );

Now, there is an error with session.user is not recognized although when I logged it, it gave me object

Note: I already tested the backend and is working fine and the app is working if I entered the token manually, the problem of getting the token to be in the header of the requests dynamically.

I tried to get the token from the session, but I couldn't reach any data inside. also I tried to get the token from the cookie, but it gives me undefined

Even when I copy The token manually from the terminal gives me the error
Error: newproduct.js?84e9:54          POST http://localhost:3030/product 401 (Unauthorized)
which means token is wrong


来源: stackexchange

问:
implement dynamic handler for different endpoints in Golang
I"m trying to implement a dynamic handler for my integrational test.
I want to pass some fields like status , response, path, Method etc, and create a handler for that.

integration snippet:

```<code>func TestSomething(t *testing.T) {
    sampleID := "33"
    mocks := []fakes.SalesforceMock{
        {
            Endpoint: "/services/Soap/u/44.0",
            Method:   http.MethodPost,
            Response: func() []byte {
                s := &salesforce.LoginResponse{
                    SessionID:           "test",
                    SessionSecondsValid: "1000",
                }
                rb, _ := xml.Marshal(s)
                return rb
            },
            Status: http.StatusOK,
        }, {
            Endpoint: "/services/data/v44.0.0/jobs/ingest",
            Method:   http.MethodPost,
            Response: func() []byte {
                s := bulk.Response{
                    ID: sampleID,
                }
                rb, _ := json.Marshal(s)
                return rb
            },
            Status: http.StatusCreated,
        }, {
            Endpoint: fmt.Sprintf("/services/data/v44.0.0/jobs/ingest/%s", sampleID),
            Method:   http.MethodGet,
            Response: func() []byte {
                s := bulk.Info{
                    Response: bulk.Response{
                        State: "Completed",
                    },
                    NumberRecordsFailed:    2,
                    NumberRecordsProcessed: 10,
                }
                rb, _ := json.Marshal(s)
                return rb
            },
            Status: http.StatusOK,
        }, {
            Endpoint: fmt.Sprintf("/services/data/v44.0.0/jobs/ingest/%s/failedResults/", sampleID),
            Method:   http.MethodGet,
            Response: func() []byte {
                record := []string{"sf__Error", "sf__Id"}
                b := &bytes.Buffer{}
                wr := csv.NewWriter(b)
                _ = wr.Write(record)
                wr.Flush()
                return b.Bytes()
            },
            Status:        http.StatusOK,
            CustomHeaders: map[string]string{"Content-Type": "text/csv"},
        }, {
            Endpoint: fmt.Sprintf("/services/data/v44.0.0/jobs/ingest/%s/batches", sampleID),
            Method:   http.MethodPut,
            Response: func() []byte {
                return []byte("")
            },
            Status: http.StatusCreated,
        },
    }
    srv, err := fakes.NewSalesforceServer(mocks)
</code>```

On my handler side, due to I have it in a loop, sounds like a status code will be overwritten and be a case for superfluous.
I didn't get that part, even though I create a shadow variable and struct in each step and use it to handle but seems it is like it is only one handler thant handle all endpoints.

```<code>type SalesforceMock struct {
    Endpoint      string
    Method        string
    Response      func() []byte
    Status        int
    CustomHeaders map[string]string
}

type myHandler struct {
    mock SalesforceMock
}

func (m *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if len(m.mock.CustomHeaders) > 0 {
        for hn, hv := range m.mock.CustomHeaders {
            w.Header().Set(hn, hv)
        }
    }
    w.WriteHeader(m.mock.Status)
    _, _ = w.Write(m.mock.Response())

    if r.Method != m.mock.Method {
        http.Error(w, fmt.Sprintf("method not allowed: %s", r.Method), http.StatusMethodNotAllowed)
    }
}

func NewSalesforceServer(mocks []SalesforceMock) (*httptest.Server, error) {
    mux := http.NewServeMux()
    for _, m := range mocks {
        mock := m
        handler := new(myHandler)
        handler.mock = m
        fmt.Println(&handler)
        mux.Handle(mock.Endpoint, handler)
    }
    s := httptest.NewServer(mux)
    return s, nil
}
</code>```

General idea is do not create N different handler for N endpoint.

ContentLicense: CC BY-SA 4.0

Body:
I"m trying to implement a dynamic handler for my integrational test.
I want to pass some fields like status , response, path, Method etc, and create a handler for that.

integration snippet:

func TestSomething(t *testing.T) {
    sampleID := "33"
    mocks := []fakes.SalesforceMock{
        {
            Endpoint: "/services/Soap/u/44.0",
            Method:   http.MethodPost,
            Response: func() []byte {
                s := &salesforce.LoginResponse{
                    SessionID:           "test",
                    SessionSecondsValid: "1000",
                }
                rb, _ := xml.Marshal(s)
                return rb
            },
            Status: http.StatusOK,
        }, {
            Endpoint: "/services/data/v44.0.0/jobs/ingest",
            Method:   http.MethodPost,
            Response: func() []byte {
                s := bulk.Response{
                    ID: sampleID,
                }
                rb, _ := json.Marshal(s)
                return rb
            },
            Status: http.StatusCreated,
        }, {
            Endpoint: fmt.Sprintf("/services/data/v44.0.0/jobs/ingest/%s", sampleID),
            Method:   http.MethodGet,
            Response: func() []byte {
                s := bulk.Info{
                    Response: bulk.Response{
                        State: "Completed",
                    },
                    NumberRecordsFailed:    2,
                    NumberRecordsProcessed: 10,
                }
                rb, _ := json.Marshal(s)
                return rb
            },
            Status: http.StatusOK,
        }, {
            Endpoint: fmt.Sprintf("/services/data/v44.0.0/jobs/ingest/%s/failedResults/", sampleID),
            Method:   http.MethodGet,
            Response: func() []byte {
                record := []string{"sf__Error", "sf__Id"}
                b := &bytes.Buffer{}
                wr := csv.NewWriter(b)
                _ = wr.Write(record)
                wr.Flush()
                return b.Bytes()
            },
            Status:        http.StatusOK,
            CustomHeaders: map[string]string{"Content-Type": "text/csv"},
        }, {
            Endpoint: fmt.Sprintf("/services/data/v44.0.0/jobs/ingest/%s/batches", sampleID),
            Method:   http.MethodPut,
            Response: func() []byte {
                return []byte("")
            },
            Status: http.StatusCreated,
        },
    }
    srv, err := fakes.NewSalesforceServer(mocks)

On my handler side, due to I have it in a loop, sounds like a status code will be overwritten and be a case for superfluous.
I didn't get that part, even though I create a shadow variable and struct in each step and use it to handle but seems it is like it is only one handler thant handle all endpoints.

type SalesforceMock struct {
    Endpoint      string
    Method        string
    Response      func() []byte
    Status        int
    CustomHeaders map[string]string
}

type myHandler struct {
    mock SalesforceMock
}

func (m *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if len(m.mock.CustomHeaders) > 0 {
        for hn, hv := range m.mock.CustomHeaders {
            w.Header().Set(hn, hv)
        }
    }
    w.WriteHeader(m.mock.Status)
    _, _ = w.Write(m.mock.Response())

    if r.Method != m.mock.Method {
        http.Error(w, fmt.Sprintf("method not allowed: %s", r.Method), http.StatusMethodNotAllowed)
    }
}

func NewSalesforceServer(mocks []SalesforceMock) (*httptest.Server, error) {
    mux := http.NewServeMux()
    for _, m := range mocks {
        mock := m
        handler := new(myHandler)
        handler.mock = m
        fmt.Println(&handler)
        mux.Handle(mock.Endpoint, handler)
    }
    s := httptest.NewServer(mux)
    return s, nil
}

General idea is do not create N different handler for N endpoint.


问:
ModuleNotFoundError: No module named 'openai'
I am getting the following exception when I run the Python code having import openai:

```<code>import openai
ModuleNotFoundError: No module named 'openai'
</code>```

I have manually installed openai using pip3. Any suggestions as to where I could be wrong?

I have also included my current working directory (where the Python code is) in the environment PATH.

Thanks for your help.

I'm running the Python code in VS Code.

Body:
I am getting the following exception when I run the Python code having import openai:

import openai
ModuleNotFoundError: No module named 'openai'

I have manually installed openai using pip3. Any suggestions as to where I could be wrong?

I have also included my current working directory (where the Python code is) in the environment PATH.

Thanks for your help.

I'm running the Python code in VS Code.


问:
Apache James Fetchmail not showing correct dates with Apple Mail client (both iOS and Mac)
I embarked on a project to migrate 20 years of email out of GMail and into my own Apache James mail server.

I downloaded and set up Apache James 3.7.2 on Ubuntu Linux with MySQL as the local repository.

I configured the Fetchmail module within Apache James to pull down all of my old emails from my GMail account. However, I realised that when using my iPad to connect to Apache James, my old emails were showing the date that Fetchmail performed the migration, and not the original date I received it in GMail.

I configured Thunderbird on my PC, and it was showing the correct dates, so I thought it must be a client setting.

I searched high and low on the the internet and could not find anything to change the displayed date on my iPad.

I did find that there is a setting within Apple Mail on my Mac where if I change to "View -> Use Column Layout" and then "option right click" the columns would let me see both the "Date Sent" and "Date Received" columns. The "Date Received" column had the Fetchmail migrated date, while the "Date Sent" had the original date I was looking for.

I then started digging deeper, and as I had set up MySQL as the database repository for Apache James, I could poke around within the database. I found that the MAIL_DATE column in the JAMES_MAIL table had the date that Fetchmail performed the migration. I also found that the HEADER_BYTES column of the JAMES_MAIL table had the original headers for the email. The HEADER_BYTES column was a Blob so I had to convert it to text to see the headers.

One of the headers had the date on a line, e.g.:

```<code>\nDate: Wed, 24 Aug 2016 12:06:54 +1000
</code>```

I gambled that most of my emails would contain this header and started writing an SQL to update JAMES_MAIL.MAIL_DATE with the parsed header date from JAMES_MAIL.HEADER_BYTES.

Other emails had a slightly differnt date format such as:

```<code>\nDate: 13 Jul 2013 11:47:23 GMT
</code>```

My gamble paid off as every single one of my 30k+ emails had that date header line it, some had slightly different date formats, but there was only a couple of variations, with a few different time zones.

I was lucky enough that MySQL had enough RegEx functions to help me parse everything.

After running the SQL to update the database in a few small batches, I reloaded all my email on my iPad and the dates were now showing correctly.

Below is the SQL that I wrote to perform the update.

```<code>update JAMES_MAIL set MAIL_DATE =
CONVERT_TZ(STR_TO_DATE(SUBSTR(REGEXP_SUBSTR(CONVERT(HEADER_BYTES USING utf8), '\nDate: [A-Za-z, ]+[0-9]+ [A-Za-z]+ [0-9]+ [0-9]+:[0-9]+:[0-9]+'), 8),'%a, %d %b %Y %T'),
  REGEXP_SUBSTR(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(SUBSTR(REGEXP_SUBSTR(CONVERT(HEADER_BYTES USING utf8), '\nDate: .*'), 8), 'GMT', '+0000'), 'UTC', '+0000'), '([+-])([0-9]{2})([0-9]{2})', '$1$2:$3'), '[+-][0-9]{2}:[0-9]{2}'),
  '+10:00')
where MAIL_UID between 1 and 1000 AND MAILBOX_ID = 12734;
</code>```
```<code>update JAMES_MAIL set MAIL_DATE =
CONVERT_TZ(STR_TO_DATE(SUBSTR(REGEXP_SUBSTR(CONVERT(HEADER_BYTES USING utf8), '\nDate: [A-Za-z, ]*[0-9]+ [A-Za-z]+ [0-9]+ [0-9]+:[0-9]+:[0-9]+'), 8),'%d %b %Y %T'),
  REGEXP_SUBSTR(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(SUBSTR(REGEXP_SUBSTR(CONVERT(HEADER_BYTES USING utf8), '\nDate: .*'), 8), 'GMT', '+0000'), 'UTC', '+0000'), '([+-])([0-9]{2})([0-9]{2})', '$1$2:$3'), '[+-][0-9]{2}:[0-9]{2}'),
  '+10:00')
where MAILBOX_ID = 12734 AND MAIL_DATE is null;
</code>```

The MAILBOX_ID is just the IMAP folder which can be found with this SQL:

```<code>select MAILBOX_ID, MAILBOX_NAME, USER_NAME from JAMES_MAILBOX;
</code>```

My question is, is this a bug with Apache James, or is my use-case too obscure?

For any future email that comes in through Fetchmail, the dates will correlate correctly. It's only the past dates that
I had trouble with, and then it's only with the Apple Mail client.

And, is there a better SQL that I could have written?

Body:
I embarked on a project to migrate 20 years of email out of GMail and into my own Apache James mail server.

I downloaded and set up Apache James 3.7.2 on Ubuntu Linux with MySQL as the local repository.

I configured the Fetchmail module within Apache James to pull down all of my old emails from my GMail account. However, I realised that when using my iPad to connect to Apache James, my old emails were showing the date that Fetchmail performed the migration, and not the original date I received it in GMail.

I configured Thunderbird on my PC, and it was showing the correct dates, so I thought it must be a client setting.

I searched high and low on the the internet and could not find anything to change the displayed date on my iPad.

I did find that there is a setting within Apple Mail on my Mac where if I change to "View -> Use Column Layout" and then "option right click" the columns would let me see both the "Date Sent" and "Date Received" columns. The "Date Received" column had the Fetchmail migrated date, while the "Date Sent" had the original date I was looking for.

I then started digging deeper, and as I had set up MySQL as the database repository for Apache James, I could poke around within the database. I found that the MAIL_DATE column in the JAMES_MAIL table had the date that Fetchmail performed the migration. I also found that the HEADER_BYTES column of the JAMES_MAIL table had the original headers for the email. The HEADER_BYTES column was a Blob so I had to convert it to text to see the headers.

One of the headers had the date on a line, e.g.:

\nDate: Wed, 24 Aug 2016 12:06:54 +1000

I gambled that most of my emails would contain this header and started writing an SQL to update JAMES_MAIL.MAIL_DATE with the parsed header date from JAMES_MAIL.HEADER_BYTES.

Other emails had a slightly differnt date format such as:

\nDate: 13 Jul 2013 11:47:23 GMT

My gamble paid off as every single one of my 30k+ emails had that date header line it, some had slightly different date formats, but there was only a couple of variations, with a few different time zones.

I was lucky enough that MySQL had enough RegEx functions to help me parse everything.

After running the SQL to update the database in a few small batches, I reloaded all my email on my iPad and the dates were now showing correctly.

Below is the SQL that I wrote to perform the update.

update JAMES_MAIL set MAIL_DATE =
CONVERT_TZ(STR_TO_DATE(SUBSTR(REGEXP_SUBSTR(CONVERT(HEADER_BYTES USING utf8), '\nDate: [A-Za-z, ]+[0-9]+ [A-Za-z]+ [0-9]+ [0-9]+:[0-9]+:[0-9]+'), 8),'%a, %d %b %Y %T'),
  REGEXP_SUBSTR(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(SUBSTR(REGEXP_SUBSTR(CONVERT(HEADER_BYTES USING utf8), '\nDate: .*'), 8), 'GMT', '+0000'), 'UTC', '+0000'), '([+-])([0-9]{2})([0-9]{2})', '$1$2:$3'), '[+-][0-9]{2}:[0-9]{2}'),
  '+10:00')
where MAIL_UID between 1 and 1000 AND MAILBOX_ID = 12734;

update JAMES_MAIL set MAIL_DATE =
CONVERT_TZ(STR_TO_DATE(SUBSTR(REGEXP_SUBSTR(CONVERT(HEADER_BYTES USING utf8), '\nDate: [A-Za-z, ]*[0-9]+ [A-Za-z]+ [0-9]+ [0-9]+:[0-9]+:[0-9]+'), 8),'%d %b %Y %T'),
  REGEXP_SUBSTR(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(SUBSTR(REGEXP_SUBSTR(CONVERT(HEADER_BYTES USING utf8), '\nDate: .*'), 8), 'GMT', '+0000'), 'UTC', '+0000'), '([+-])([0-9]{2})([0-9]{2})', '$1$2:$3'), '[+-][0-9]{2}:[0-9]{2}'),
  '+10:00')
where MAILBOX_ID = 12734 AND MAIL_DATE is null;

The MAILBOX_ID is just the IMAP folder which can be found with this SQL:

select MAILBOX_ID, MAILBOX_NAME, USER_NAME from JAMES_MAILBOX;

My question is, is this a bug with Apache James, or is my use-case too obscure?

For any future email that comes in through Fetchmail, the dates will correlate correctly. It's only the past dates that
I had trouble with, and then it's only with the Apple Mail client.

And, is there a better SQL that I could have written?


问:
How to play any sound in kernel mode driver (Windows)
I have a kernel driver and I need to play any sound by pressing the keyboard's key. This is what I have now, but can't figure out how to actually play the sound.

That's my University project and you can see my code below:

```<code>
NTSTATUS ReadCompletionRoutine(IN PDEVICE_OBJECT pDeviceObject, IN PIRP theIrp, IN PVOID Context)
{
    PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION)pDeviceObject->DeviceExtension;
    PKEYBOARD_INPUT_DATA kidData;

    if (NT_SUCCESS(theIrp->IoStatus.Status))
    {
        kidData = (PKEYBOARD_INPUT_DATA)theIrp->AssociatedIrp.SystemBuffer;
        int n = theIrp->IoStatus.Information / sizeof(KEYBOARD_INPUT_DATA);
        for (int i = 0; i < n; ++i)
        {
            USHORT keyCode = kidData[i].MakeCode;

            switch (keyCode) {
                case 2: {
                    // Key "1" was pressed
                    DbgPrint("PLAY SOUND 1");
                    Sound();
                    break;
                }
                case 3: {
                    // Key "2" was pressed
                    DbgPrint("PLAY SOUND 2");
                    break;
                }
                case 4: {
                    // Key "3" was pressed
                    DbgPrint("PLAY SOUND 3");
                    break;
                }
                break;
            }

            //DbgPrint("Code: %x\n", keyCode);
        }
    }

    if (theIrp->PendingReturned) {
        IoMarkIrpPending(theIrp);
    }

    gnRequests--;
    /*__asm {
        lock dec gnRequests
    }*/
    return theIrp->IoStatus.Status;
}

</code>```

Body:
I have a kernel driver and I need to play any sound by pressing the keyboard's key. This is what I have now, but can't figure out how to actually play the sound.

That's my University project and you can see my code below:

NTSTATUS ReadCompletionRoutine(IN PDEVICE_OBJECT pDeviceObject, IN PIRP theIrp, IN PVOID Context)
{
    PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION)pDeviceObject->DeviceExtension;
    PKEYBOARD_INPUT_DATA kidData;

    if (NT_SUCCESS(theIrp->IoStatus.Status))
    {
        kidData = (PKEYBOARD_INPUT_DATA)theIrp->AssociatedIrp.SystemBuffer;
        int n = theIrp->IoStatus.Information / sizeof(KEYBOARD_INPUT_DATA);
        for (int i = 0; i < n; ++i)
        {
            USHORT keyCode = kidData[i].MakeCode;

            switch (keyCode) {
                case 2: {
                    // Key "1" was pressed
                    DbgPrint("PLAY SOUND 1");
                    Sound();
                    break;
                }
                case 3: {
                    // Key "2" was pressed
                    DbgPrint("PLAY SOUND 2");
                    break;
                }
                case 4: {
                    // Key "3" was pressed
                    DbgPrint("PLAY SOUND 3");
                    break;
                }
                break;
            }

            //DbgPrint("Code: %x\n", keyCode);
        }
    }

    if (theIrp->PendingReturned) {
        IoMarkIrpPending(theIrp);
    }

    gnRequests--;
    /*__asm {
        lock dec gnRequests
    }*/
    return theIrp->IoStatus.Status;
}


问:
How to set SwiftUI ScrollView position via CGPoint
I have this view where I'd like to insert an image inside a scroll view so when the user zooms in they can scroll through the zoomed in photo, however, I'd like to add a double tap functionality which zooms in and sets the position of the picture where the user tapped. I have successfully been able to zoom the picture in and allow scrolling, it just zooms in to the exact centre of the image each time, instead of where they double tapped. I have the location data via a CGPoint

```<code> GeometryReader { proxy in
        ScrollView([.vertical, .horizontal], showsIndicators: false){
            image?
                .resizable()
                .aspectRatio(contentMode: .fit)
                .onTapGesture(count: 2) { location in
                    print(location)
                    // set scroll view position here
                    onImageDoubleTapped(locationTapped: location)
                }
                .gesture(zoomGesture)
                .frame(width: proxy.size.width * max(minZoomScale, zoomScale))
                .frame(maxHeight: .infinity)
        }
    }
</code>```

Body:
I have this view where I'd like to insert an image inside a scroll view so when the user zooms in they can scroll through the zoomed in photo, however, I'd like to add a double tap functionality which zooms in and sets the position of the picture where the user tapped. I have successfully been able to zoom the picture in and allow scrolling, it just zooms in to the exact centre of the image each time, instead of where they double tapped. I have the location data via a CGPoint

 GeometryReader { proxy in
        ScrollView([.vertical, .horizontal], showsIndicators: false){
            image?
                .resizable()
                .aspectRatio(contentMode: .fit)
                .onTapGesture(count: 2) { location in
                    print(location)
                    // set scroll view position here
                    onImageDoubleTapped(locationTapped: location)
                }
                .gesture(zoomGesture)
                .frame(width: proxy.size.width * max(minZoomScale, zoomScale))
                .frame(maxHeight: .infinity)
        }
    }


问:
What would be the best way of implementing saved state while routing
I would like to implement a routing system where if the user presses the back or forward button, the state of the page would look like just as they left it.

So,

1- Back and forward button should preserve state(generally this would be filters of a list) and this should only happen for some components but data from the server should be refetched on every routing since data might have changed.

2- But other navigation(such as navbar navigation) to these component shouldn't lead to getting the saved state.

Firstly, I thought of using a service for this where the system would be:

1- Components that need their state to be saved, subscribe to a service in the constructor or the oninit with a key and a state getter. While they are subscribing they would also receive their saved state by service. Something like this:

const state: MyComponentState | undefined = this.routingService.subscribe(
   somekey,
   () => this.filterState
)

```

2- Then, the service would have a stack and a pointer to where they are on the stack, and listen to NavigationStart and save their "subscriber's" state with their key and return their saved state while the components are subscribing.

But, I learned that there is this thing RouteReuseStrategy. It should be more efficient then my service implementation but I don't know how to implement my desired system with it.

So,

Has anybody implemented such a thing? Is my implementation sensible?
Is there a better way?

Body:
I would like to implement a routing system where if the user presses the back or forward button, the state of the page would look like just as they left it.

So,

1- Back and forward button should preserve state(generally this would be filters of a list) and this should only happen for some components but data from the server should be refetched on every routing since data might have changed.

2- But other navigation(such as navbar navigation) to these component shouldn't lead to getting the saved state.

Firstly, I thought of using a service for this where the system would be:

1- Components that need their state to be saved, subscribe to a service in the constructor or the oninit with a key and a state getter. While they are subscribing they would also receive their saved state by service. Something like this:

const state: MyComponentState | undefined = this.routingService.subscribe(
   somekey,
   () => this.filterState
)

2- Then, the service would have a stack and a pointer to where they are on the stack, and listen to NavigationStart and save their "subscriber's" state with their key and return their saved state while the components are subscribing.

But, I learned that there is this thing RouteReuseStrategy. It should be more efficient then my service implementation but I don't know how to implement my desired system with it.

So,

Has anybody implemented such a thing? Is my implementation sensible?
Is there a better way?


问:
CMake - building and linking to ExternalProject_Add
I'm trying to download a dependency from GitHub, build it, and link to it.

```<code># External dependency
ExternalProject_Add(libdatachannel
    GIT_REPOSITORY      git@github.com:paullouisageneau/libdatachannel.git
    GIT_TAG             v0.18.0
    GIT_PROGRESS        TRUE
    GIT_SHALLOW         TRUE
)

# My library - actual main target
add_library(
    test
    SHARED
    src/main/cpp/test.cpp # and so on
)

add_dependencies(test libdatachannel)

</code>```

Now libdatachannel uses CMake. But it does not build a static variant by default, using EXCLUDE_FROM_ALL:

https://github.com/paullouisageneau/libdatachannel/blob/v0.18.0/CMakeLists.txt#L237

Question 1 - how can I build this custom target inside libdatachannel - datachannel-static?

Question 2 - how can I set include paths for accessing datachannel includes from my test library - as well as link to the static version of datachannel?

Question 3 - Libdatachannel's readme file here

https://github.com/paullouisageneau/libdatachannel/blob/v0.18.0/BUILDING.md

mentions that "The CMake build exports the targets with namespace LibDataChannel::LibDataChannel and LibDataChannel::LibDataChannelStatic to link the library from another CMake project".

I'm not sure how to use these custom targets exported by libdatachannel in my project.

I tried this, but got errors from cmake:

```<code>target_link_libraries(plugin PRIVATE LibDataChannel::LibDataChannelStatic)
</code>```

I'm running the top level CMake project as part of an Android build which uses Gradle and specific stanzas to invoke CMake.

Body:
I'm trying to download a dependency from GitHub, build it, and link to it.

# External dependency
ExternalProject_Add(libdatachannel
    GIT_REPOSITORY      git@github.com:paullouisageneau/libdatachannel.git
    GIT_TAG             v0.18.0
    GIT_PROGRESS        TRUE
    GIT_SHALLOW         TRUE
)

# My library - actual main target
add_library(
    test
    SHARED
    src/main/cpp/test.cpp # and so on
)

add_dependencies(test libdatachannel)

Now libdatachannel uses CMake. But it does not build a static variant by default, using EXCLUDE_FROM_ALL:

https://github.com/paullouisageneau/libdatachannel/blob/v0.18.0/CMakeLists.txt#L237

Question 1 - how can I build this custom target inside libdatachannel - datachannel-static?

Question 2 - how can I set include paths for accessing datachannel includes from my test library - as well as link to the static version of datachannel?

Question 3 - Libdatachannel's readme file here

https://github.com/paullouisageneau/libdatachannel/blob/v0.18.0/BUILDING.md

mentions that "The CMake build exports the targets with namespace LibDataChannel::LibDataChannel and LibDataChannel::LibDataChannelStatic to link the library from another CMake project".

I'm not sure how to use these custom targets exported by libdatachannel in my project.

I tried this, but got errors from cmake:

target_link_libraries(plugin PRIVATE LibDataChannel::LibDataChannelStatic)

I'm running the top level CMake project as part of an Android build which uses Gradle and specific stanzas to invoke CMake.


问:
how to remove space between image and container
I believe the code snippet does not work since the images are stored on my physical computer however the problem is I have a very small space. This is an image:

.front-image {
  position: relative;
  width: 1600px;
  height: 500px;
  left: 0px;
  top: 0px;
}

.front-image2 {
  position: relative;
  width: 1600px;
  height: 337px;
  left: 0px;
  background: #162F1A;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="kqmjdmqs">
            <img class="front-image" src="rename.png" alt="front-fountain">
            <div class="front-image2"></div>
</div></code>```


问:
Uploading an image into node.js server and using sql and i get this error: TypeError: Cannot convert object to primitive value
I've been trying to use console.log's with ther errors and can't figure it out.
I have a form to create an account and upload an image in the process. To send the data to sql i have an if(!req.files){}, and to upload the image I have an if(req.files){}.

I'm getting the error: "TypeError: Cannot convert object to primitive value" in the uploading image part as I made console.log of the other information and it's

PS: I'm using the Post method for submiting the form

this is the snip of the node.js code:

```<code>        //The code before saved a row of data in sql
        //The atribute of the path has been filled with something for it to be updated

        //UPDATE the atribute that saves the path for the image
        //Save the image in the chosen file

        else if (req.files.fotografia_funcionario) {
            //novo query para fazer o update do atributo
            console.log("Estamos no " + req.files);
            console.log("Estamos no req.files");
            query += "UPDATE Funcionarios SET fotografia_funcionario = " + req.files.fotografia_funcionario + ";";

            pool.query(query, function (err, result, fields) {
                var html = "";
                html += head;
                html += "<h2>Regista um funcionário</h2>\n";
                if (!err) {
                    if (result[0] && result[0].affectedRows > 0) {
                        html += "<p>O funcionário'" + req.body.nome_funcionario + "' foi inserido com sucesso</p>\n";
                    }
                    else {
                        html += "<p>Não foi possivel inserir o funcionário '" + req.body.nome_funcionario + "'</p>\n";
                        html += "<p>Não foi possivel inserir a fotografia de'" + req.body.nome_funcionario + "'</p>\n";
                    }
                    if (result[1] && result[1].affectedRows > 0) {
                        html += "<p>A fotografia de'" + req.body.nome_funcionario + "' foi inserida com sucesso</p>\n";
                    }
                    else {
                        html += "<p>Não foi possivel inserir a  fotografia de '" + req.body.nome_funcionario + "'</p>\n";
                    }
                    req.files.fotografia_funcionario.mv("public/fotografias_funcionarios/" + req.files.fotografia_funcionario, function (err) {
                        if (err) {
                            console.error(err);
                            console.error("Erro ao guardar a imagem no ficheiro");
                        }
                    });
                }
</code>```

I'm trying to save the image and its name
The form works if I sont use the upload of the image

Body:
I've been trying to use console.log's with ther errors and can't figure it out.
I have a form to create an account and upload an image in the process. To send the data to sql i have an if(!req.files){}, and to upload the image I have an if(req.files){}.

I'm getting the error: "TypeError: Cannot convert object to primitive value" in the uploading image part as I made console.log of the other information and it's

PS: I'm using the Post method for submiting the form

this is the snip of the node.js code:

        //The code before saved a row of data in sql
        //The atribute of the path has been filled with something for it to be updated

        //UPDATE the atribute that saves the path for the image
        //Save the image in the chosen file

        else if (req.files.fotografia_funcionario) {
            //novo query para fazer o update do atributo
            console.log("Estamos no " + req.files);
            console.log("Estamos no req.files");
            query += "UPDATE Funcionarios SET fotografia_funcionario = " + req.files.fotografia_funcionario + ";";

            pool.query(query, function (err, result, fields) {
                var html = "";
                html += head;
                html += "
Regista um funcionário
\n";
                if (!err) {
                    if (result[0] && result[0].affectedRows > 0) {
                        html += "
O funcionário'" + req.body.nome_funcionario + "' foi inserido com sucesso
\n";
                    }
                    else {
                        html += "
Não foi possivel inserir o funcionário '" + req.body.nome_funcionario + "'
\n";
                        html += "
Não foi possivel inserir a fotografia de'" + req.body.nome_funcionario + "'
\n";
                    }
                    if (result[1] && result[1].affectedRows > 0) {
                        html += "
A fotografia de'" + req.body.nome_funcionario + "' foi inserida com sucesso
\n";
                    }
                    else {
                        html += "
Não foi possivel inserir a  fotografia de '" + req.body.nome_funcionario + "'
\n";
                    }
                    req.files.fotografia_funcionario.mv("public/fotografias_funcionarios/" + req.files.fotografia_funcionario, function (err) {
                        if (err) {
                            console.error(err);
                            console.error("Erro ao guardar a imagem no ficheiro");
                        }
                    });
                }

I'm trying to save the image and its name
The form works if I sont use the upload of the image


问:
How to get Xcode 14.1 to build only my currently selected scheme/target?
My Xcode project has six different targets/schemes (I've never been clear on the difference, but in any case I have six targets and six schemes), all based on the same sources in different ways.  I just started using Xcode 14.1 (from a substantially older version), and now when I do a build it builds all of my targets/schemes and shows issues for them all on the left:

This is not what I want.  For one thing, since the targets/schemes are all based on the same sources I'm seeing a lot of the same issues repeated over and over.  For another thing, when I'm working on a particular target/scheme I really want to focus on that and not be distracted.  Also, I don't really want my machine to be slowed down by building all those other targets/schemes; I want my build turnaround to be as fast as possible.

So.  How I do get back the old behavior of Xcode that I'm used to, of building just the currently selected scheme and its associated target?  I'm looked in the preferences and "behaviors", and googled, and maybe I'm blind but I can't see any mention of this anywhere.

[ADDENDUM, pursuant to the comments from Matt.  It continues to happen, now with errors rather than warnings, and unrelated to deprecation.  Here's a new screenshot:

I made a change in a header that broke usage in various places in the project.  Now my issues pane is filled with crap from other targets – mostly the SAME crap, repeated for each target.  Particularly annoyingly, the target I have selected and am working on, called slim_multi, doesn't even come first in the issues pane – it's down at the bottom, after all of the other targets I'm NOT working on.  I tried switching to other targets and doing "Clean Build Folder"; that made no difference to the situation.  There must be a fix for this!]


问:
Can DynamoDb streams eventId be used as primary key?
I have a usecase to process dynamodb streams and ingest the data in Redshift for data warehousing and analytics. I want to ensure that there exists only one record per dynamodb update and there are no duplicates. Can I use eventId present in DynamoDb streams record as primary key in Redshift table?

I know dynamodb streams guarantees record is delivered only once but we have fan out design which may not ensure exactly once delivery at the end of flow.

I have looked at Aws docs, it says eventId is global unique identifier for a stream. But, want to understand from anyone who used eventId for such usecase and had success.


问:
Vulkan StorageBuffer versus VertexBuffer
I'm experimenting with Vulkan rendering, and noticed that we can render using StorageBuffer + gl_VertexIndex instead of VertexBuffer. I've seen this in Metal API tutorials.
There are any benefits of using VertexBuffer except missing descriptor sets and ability to set custom vertex layout?
In what scenarios can StorageBuffer be used instead of VertexBuffer?</p>
```<code>#version 450 core

struct Vertex {
    vec3 position;
    vec3 normal;
    vec4 color;
    vec2 texcoord;
};

layout(binding = 0) readonly buffer VertexInput {
    Vertex[] vertices;
};

out gl_PerVertex {
    vec4 gl_Position;
};

layout(location = 0) out struct {
    vec4 color;
    vec2 texcoord;
} vs_out;

void main() {
    vs_out.color = vertices[gl_VertexIndex].color;
    vs_out.texcoord = vertices[gl_VertexIndex].texcoord;

    gl_Position = vec4(vertices[gl_VertexIndex].position, 1);
}
</code>```

Body:
I'm experimenting with Vulkan rendering, and noticed that we can render using StorageBuffer + gl_VertexIndex instead of VertexBuffer. I've seen this in Metal API tutorials.
There are any benefits of using VertexBuffer except missing descriptor sets and ability to set custom vertex layout?
In what scenarios can StorageBuffer be used instead of VertexBuffer?

#version 450 core

struct Vertex {
    vec3 position;
    vec3 normal;
    vec4 color;
    vec2 texcoord;
};

layout(binding = 0) readonly buffer VertexInput {
    Vertex[] vertices;
};

out gl_PerVertex {
    vec4 gl_Position;
};

layout(location = 0) out struct {
    vec4 color;
    vec2 texcoord;
} vs_out;

void main() {
    vs_out.color = vertices[gl_VertexIndex].color;
    vs_out.texcoord = vertices[gl_VertexIndex].texcoord;

    gl_Position = vec4(vertices[gl_VertexIndex].position, 1);
}


问:
Python mysql select loop not returning new data
I have a mysql table described below. There is a separate script updating this table with data constantly.

```<code>+-------------+----------------+------+-----+---------+-------+
| Field       | Type           | Null | Key | Default | Extra |
+-------------+----------------+------+-----+---------+-------+
| size        | varchar(255)   | YES  |     | NULL    |       |
| price       | decimal(20,9)  | YES  |     | NULL    |       |
| value       | decimal(20,9)  | YES  |     | NULL    |       |
| side        | int            | YES  |     | NULL    |       |
| timestamp   | decimal(12,2)  | YES  |     | NULL    |       |
+-------------+----------------+------+-----+---------+-------+
</code>```

The numbers in the value column are all positive, and the side column is either 1 or 0. The timestamp column is a unix timestamp; in python I used round(time(),2)

The code below attempts to check the table in a loop to determine the difference in sums of the value column for side = 1 vs side = 0. However, in each iteration of the loop, when I print the result, the data printed doesn't change. If I run the script through one loop, exit, and run again the data will update correctly.

An example of my select statement is here:

SELECT (SELECT COALESCE(SUM(value),0) FROM myTable WHERE side = 1 AND size = 'sm' AND timestamp > (SELECT MAX(timestamp) FROM myTable WHERE size = 'sm') - 3600) - (SELECT COALESCE(SUM(value),0) FROM myTable WHERE side = 0 AND size = 'sm' AND timestamp > (SELECT MAX(timestamp) FROM myTable WHERE size = 'sm') - 3600);`
```
<p>Here is the code I'm using</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3

import mysql.connector
from time import sleep

if __name__ == "__main__":
    database = mysql.connector.connect(
        host = "localhost",
        user = "sqlUser",
        password = "password",
        database = "myDB"
    )
    myTable: str = "myTable"
    lookBack: int = 3600 #12 hrs in seconds

    cursor = database.cursor()
    sizes: list = [ ['sm',0], ['md',0], ['lg',0] ]

    while True:
        for size in sizes:
            sql = f"SELECT (SELECT COALESCE(SUM(value),0) FROM {myTable} WHERE side = 1 AND size = "
            sql += f"'{size[0]}' AND timestamp > (SELECT MAX(timestamp) FROM {myTable} WHERE size = '{size[0]}') - "
            sql += f"{lookBack}) - (SELECT COALESCE(SUM(value),0) FROM {myTable} WHERE side = 0 AND size = '{size[0]}' "
            sql += f"AND timestamp > (SELECT MAX(timestamp) FROM {myTable} WHERE size = '{size[0]}') - {lookBack})"

            cursor.execute(sql)
            sqlResult = cursor.fetchall()

            for x in sqlResult:print(f"{size[0]} value {lookBack}s:{x[0]}")

        sleep(5) #####
    database.close()
</code>```

I've tried using a different cursor each time with no luck. Any help greatly appreciated :)

Body:
I have a mysql table described below. There is a separate script updating this table with data constantly.

+-------------+----------------+------+-----+---------+-------+
| Field       | Type           | Null | Key | Default | Extra |
+-------------+----------------+------+-----+---------+-------+
| size        | varchar(255)   | YES  |     | NULL    |       |
| price       | decimal(20,9)  | YES  |     | NULL    |       |
| value       | decimal(20,9)  | YES  |     | NULL    |       |
| side        | int            | YES  |     | NULL    |       |
| timestamp   | decimal(12,2)  | YES  |     | NULL    |       |
+-------------+----------------+------+-----+---------+-------+

The numbers in the value column are all positive, and the side column is either 1 or 0. The timestamp column is a unix timestamp; in python I used round(time(),2)

The code below attempts to check the table in a loop to determine the difference in sums of the value column for side = 1 vs side = 0. However, in each iteration of the loop, when I print the result, the data printed doesn't change. If I run the script through one loop, exit, and run again the data will update correctly.

An example of my select statement is here:

SELECT (SELECT COALESCE(SUM(value),0) FROM myTable WHERE side = 1 AND size = 'sm' AND timestamp > (SELECT MAX(timestamp) FROM myTable WHERE size = 'sm') - 3600) - (SELECT COALESCE(SUM(value),0) FROM myTable WHERE side = 0 AND size = 'sm' AND timestamp > (SELECT MAX(timestamp) FROM myTable WHERE size = 'sm') - 3600);`

Here is the code I'm using

#!/usr/bin/env python3

import mysql.connector
from time import sleep

if __name__ == "__main__":
    database = mysql.connector.connect(
        host = "localhost",
        user = "sqlUser",
        password = "password",
        database = "myDB"
    )
    myTable: str = "myTable"
    lookBack: int = 3600 #12 hrs in seconds

    cursor = database.cursor()
    sizes: list = [ ['sm',0], ['md',0], ['lg',0] ]

    while True:
        for size in sizes:
            sql = f"SELECT (SELECT COALESCE(SUM(value),0) FROM {myTable} WHERE side = 1 AND size = "
            sql += f"'{size[0]}' AND timestamp > (SELECT MAX(timestamp) FROM {myTable} WHERE size = '{size[0]}') - "
            sql += f"{lookBack}) - (SELECT COALESCE(SUM(value),0) FROM {myTable} WHERE side = 0 AND size = '{size[0]}' "
            sql += f"AND timestamp > (SELECT MAX(timestamp) FROM {myTable} WHERE size = '{size[0]}') - {lookBack})"

            cursor.execute(sql)
            sqlResult = cursor.fetchall()

            for x in sqlResult:print(f"{size[0]} value {lookBack}s:{x[0]}")

        sleep(5) #####
    database.close()

I've tried using a different cursor each time with no luck. Any help greatly appreciated :)


问:
Crypto module not loading randomUUID() when viewing a local network IP address
I feel like I'm missing something basic here, I've got a React app that I'm trying to use the crypto module in the browser. Specifically I'm trying to use the randomUUID() function, which should be present in Chrome versions > 92. This all works great when I'm viewing my app on localhost, I can import crypto and see the randomUUID() function in the console.

But weirdly when I try to view the same app on my local network IP address (192.168.X.XX), I can't see randomUUID anymore in the console. My app is also failing to get the function. I can see crypto is still importing, but I can't see randomUUID in there, the console only shows  the getRandomValues() function. I also double checked that in both instances I'm running Chrome 108 via navigator.appVersion.match(/.*Chrome\/([0-9\.]+)/)[1]

I also tested this on Safari and can see the behavior replicated there: I can see crypto.randomUUID() on localhost, but not on my local network IP address. Anyone know why this is could be happening?

Localhost:

192.168.X.XX:


问:
Undefined references to math functions during linking
I am compiling a program that uses GLFW, during compilation the linker gives me undefined references to functions originating from the math.h library.

I added the -lm option to my linker, and I still get the same error after recompiling. I'm not sure what I'm doing wrong.

I have tried putting -lm at the end as described in Undefined reference to `sqrt` despite linking to math library, However this does not fix my issue.

I'm using these linker flags in this order.

```<code>-lglfw -lGLEW -lX11 -lXrandr -lXinerama -lXi -lXxf86vm -lXcursor -ldl -lGL -lGLU -lpthread -lm
</code>```

Output:

```<code>gcc -lglfw -lGLEW -lX11 -lXrandr -lXinerama -lXi -lXxf86vm -lXcursor -ldl -lGL -lGLU -lpthread -lm -Ilib/glad/include/glad -Ilib/glfw/include/GLFW -Wall -g -Werror -Wextra  -c -o obj/main.o src/main.c
gcc -lglfw -lGLEW -lX11 -lXrandr -lXinerama -lXi -lXxf86vm -lXcursor -ldl -lGL -lGLU -lpthread -lm -Ilib/glad/include/glad -Ilib/glfw/include/GLFW -Wall -g -Werror -Wextra  -c -o obj/window.o src/window.c
gcc -Wall -g -Werror -Wextra  -o bin/main obj/main.o obj/window.o lib/glad/bin/glad.o lib/glfw/build/src/libglfw3.a
/usr/bin/ld: lib/glfw/build/src/libglfw3.a(monitor.c.o): in function `glfwSetGamma':
monitor.c:(.text+0x1330): undefined reference to `powf'
/usr/bin/ld: lib/glfw/build/src/libglfw3.a(null_monitor.c.o): in function `_glfwGetGammaRampNull':
null_monitor.c:(.text+0x3ea): undefined reference to `powf'
/usr/bin/ld: lib/glfw/build/src/libglfw3.a(x11_monitor.c.o): in function `calculateRefreshRate':
x11_monitor.c:(.text+0xf4): undefined reference to `round'
collect2: error: ld returned 1 exit status
make: *** [Makefile:31: bin/main] Error 1
</code>```

Edit: I have attached my Makefile for further clarification.

```<code>
CC=gcc
CFLAGS=-Wall -g -Werror -Wextra
LDFLAGS=-lglfw -lGLEW -lX11 -lXrandr -lXinerama -lXi -lXxf86vm -lXcursor -ldl -lGL -lGLU -lpthread -lm
# LDFLAGS CONTINUED
LDFLAGS += -Ilib/glad/include/glad -Ilib/glfw/include/GLFW
CCOBJFLAGS=$(CFLAGS) -c

# directories
BIN_PATH=bin
OBJ_PATH=obj
SRC_PATH=src

# source
SRC=$(foreach x, $(SRC_PATH), $(wildcard $(addprefix $(x)/*,.c*)))
OBJ=$(addprefix $(OBJ_PATH)/, $(addsuffix .o, $(notdir $(basename $(SRC)))))
LIBS=lib/glad/bin/glad.o lib/glfw/build/src/libglfw3.a

# specify target
TARGET_NAME=main
TARGET=$(BIN_PATH)/$(TARGET_NAME)

# cleaning rules
CLEAN_LIST=$(TARGET) $(OBJ)

# make section
default: makedir all

$(TARGET): $(OBJ)
    $(CC) $(CFLAGS) -o $@ $(OBJ) $(LIBS)

$(OBJ_PATH)/%.o: $(SRC_PATH)/%.c*
    $(CC) $(LDFLAGS) $(CCOBJFLAGS) -o $@ $<

run: all
    $(TARGET)

libs:
    cd lib/glfw && cmake -S . -B build && cd build/ && make                     # GLFW
    cd lib/glad && $(CC) -o bin/glad.o -Iinclude -c src/glad.c && ar rcs libglad.a bin/glad.o   # GLAD

# phony
.PHONY: makedir
    @mkdir -p $(BIN_PATH) $(OBJ_PATH)

.PHONY: all
all: $(TARGET)

.PHONY: clean
clean:
    @echo CLEAN $(CLEAN_LIST)
    @rm -f $(CLEAN_LIST)

</code>```

Any feedback on the makefile is appreciated.

Body:
I am compiling a program that uses GLFW, during compilation the linker gives me undefined references to functions originating from the math.h library.

I added the -lm option to my linker, and I still get the same error after recompiling. I'm not sure what I'm doing wrong.

I have tried putting -lm at the end as described in Undefined reference to `sqrt` despite linking to math library, However this does not fix my issue.

I'm using these linker flags in this order.

-lglfw -lGLEW -lX11 -lXrandr -lXinerama -lXi -lXxf86vm -lXcursor -ldl -lGL -lGLU -lpthread -lm

Output:

gcc -lglfw -lGLEW -lX11 -lXrandr -lXinerama -lXi -lXxf86vm -lXcursor -ldl -lGL -lGLU -lpthread -lm -Ilib/glad/include/glad -Ilib/glfw/include/GLFW -Wall -g -Werror -Wextra  -c -o obj/main.o src/main.c
gcc -lglfw -lGLEW -lX11 -lXrandr -lXinerama -lXi -lXxf86vm -lXcursor -ldl -lGL -lGLU -lpthread -lm -Ilib/glad/include/glad -Ilib/glfw/include/GLFW -Wall -g -Werror -Wextra  -c -o obj/window.o src/window.c
gcc -Wall -g -Werror -Wextra  -o bin/main obj/main.o obj/window.o lib/glad/bin/glad.o lib/glfw/build/src/libglfw3.a
/usr/bin/ld: lib/glfw/build/src/libglfw3.a(monitor.c.o): in function `glfwSetGamma':
monitor.c:(.text+0x1330): undefined reference to `powf'
/usr/bin/ld: lib/glfw/build/src/libglfw3.a(null_monitor.c.o): in function `_glfwGetGammaRampNull':
null_monitor.c:(.text+0x3ea): undefined reference to `powf'
/usr/bin/ld: lib/glfw/build/src/libglfw3.a(x11_monitor.c.o): in function `calculateRefreshRate':
x11_monitor.c:(.text+0xf4): undefined reference to `round'
collect2: error: ld returned 1 exit status
make: *** [Makefile:31: bin/main] Error 1

Edit: I have attached my Makefile for further clarification.

CC=gcc
CFLAGS=-Wall -g -Werror -Wextra
LDFLAGS=-lglfw -lGLEW -lX11 -lXrandr -lXinerama -lXi -lXxf86vm -lXcursor -ldl -lGL -lGLU -lpthread -lm
# LDFLAGS CONTINUED
LDFLAGS += -Ilib/glad/include/glad -Ilib/glfw/include/GLFW
CCOBJFLAGS=$(CFLAGS) -c

# directories
BIN_PATH=bin
OBJ_PATH=obj
SRC_PATH=src

# source
SRC=$(foreach x, $(SRC_PATH), $(wildcard $(addprefix $(x)/*,.c*)))
OBJ=$(addprefix $(OBJ_PATH)/, $(addsuffix .o, $(notdir $(basename $(SRC)))))
LIBS=lib/glad/bin/glad.o lib/glfw/build/src/libglfw3.a

# specify target
TARGET_NAME=main
TARGET=$(BIN_PATH)/$(TARGET_NAME)

# cleaning rules
CLEAN_LIST=$(TARGET) $(OBJ)

# make section
default: makedir all

$(TARGET): $(OBJ)
    $(CC) $(CFLAGS) -o $@ $(OBJ) $(LIBS)

$(OBJ_PATH)/%.o: $(SRC_PATH)/%.c*
    $(CC) $(LDFLAGS) $(CCOBJFLAGS) -o $@ $<

run: all
    $(TARGET)

libs:
    cd lib/glfw && cmake -S . -B build && cd build/ && make                     # GLFW
    cd lib/glad && $(CC) -o bin/glad.o -Iinclude -c src/glad.c && ar rcs libglad.a bin/glad.o   # GLAD

# phony
.PHONY: makedir
    @mkdir -p $(BIN_PATH) $(OBJ_PATH)

.PHONY: all
all: $(TARGET)

.PHONY: clean
clean:
    @echo CLEAN $(CLEAN_LIST)
    @rm -f $(CLEAN_LIST)

Any feedback on the makefile is appreciated.


问:
How to link to external site in React 18.1.0?
Okay so I hope i'm just being silly or something but my a tags aren't working. My console only shows a few errors for 'GSAP Target Not Found' which hasn't had any effect so far. I'm currently using React 18.1.0, am pretty sure you don't have to use React-Router for external links but if I wrong please tell me how to do external link with it. Any and all advice is awesome.

Footer.jsx

```<code><div id='footer-final-p' className='block'>
<div className='footer-list'>
<a
href='https://www.linkedin.com/'
target='_blank'
rel='noopener noreferrer'>
LinkedIn
</a>
</div>
</div>
</code>```

Footer.css

```<code>.footer-list {
    z-index: 10000;
    display: flex;
    flex-wrap: wrap;
    list-style: none;
    padding-left: 0;
    padding-bottom: 2vh;
    flex: 0 0 calc(100vw/4);
}

#footer-final-p {
    max-width: 80vw;
    font-weight: 300;
    font-size: 1.2vw;
}

a:hover{
    cursor: pointer;
}
</code>```

I tried adjusting some of the z-index values throughout the app but nothing has had an effect.

Body:
Okay so I hope i'm just being silly or something but my a tags aren't working. My console only shows a few errors for 'GSAP Target Not Found' which hasn't had any effect so far. I'm currently using React 18.1.0, am pretty sure you don't have to use React-Router for external links but if I wrong please tell me how to do external link with it. Any and all advice is awesome.

Footer.jsx

LinkedIn

Footer.css

.footer-list {
    z-index: 10000;
    display: flex;
    flex-wrap: wrap;
    list-style: none;
    padding-left: 0;
    padding-bottom: 2vh;
    flex: 0 0 calc(100vw/4);
}

#footer-final-p {
    max-width: 80vw;
    font-weight: 300;
    font-size: 1.2vw;
}

a:hover{
    cursor: pointer;
}

I tried adjusting some of the z-index values throughout the app but nothing has had an effect.


问:
How can you make a chrome extension scroll down to the bottom of a webpage automatically?
I am currently writing code for a chrome extension where it switches to random tabs and performs various actions. I am writing the code in Javascript but I am willing to use python. How can I make the code scroll down to the bottom of the page and back up within a certain time?

Here is the background.js file of the extension:

```<code>
</code>```
```<code>// Set up a timer to perform actions every 5 seconds
setInterval(performActions, 5000);

function performActions() {
  // Get a list of all open tabs in the current window
  chrome.tabs.query({currentWindow: true}, function(tabs) {
    // Select the third tab with a higher probability
    var tab;
    if (Math.random() < 0.8) {
      tab = tabs[2];
    } else {
      tab = tabs[Math.floor(Math.random() * (tabs.length - 1))];
    }

    // Activate the selected tab
    chrome.tabs.update(tab.id, {active: true});

    // Send a message to the selected tab's content script
    chrome.tabs.sendMessage(tab.id, {action: 'scroll'});
  });
}
</code>```
```<code>
</code>```

I tried to use the "window.scrollTo" and it didn't work. I also tried to use the pynput module. I don't know what the issue is.

Body:
I am currently writing code for a chrome extension where it switches to random tabs and performs various actions. I am writing the code in Javascript but I am willing to use python. How can I make the code scroll down to the bottom of the page and back up within a certain time?

Here is the background.js file of the extension:

// Set up a timer to perform actions every 5 seconds
setInterval(performActions, 5000);

function performActions() {
  // Get a list of all open tabs in the current window
  chrome.tabs.query({currentWindow: true}, function(tabs) {
    // Select the third tab with a higher probability
    var tab;
    if (Math.random() < 0.8) {
      tab = tabs[2];
    } else {
      tab = tabs[Math.floor(Math.random() * (tabs.length - 1))];
    }

    // Activate the selected tab
    chrome.tabs.update(tab.id, {active: true});

    // Send a message to the selected tab's content script
    chrome.tabs.sendMessage(tab.id, {action: 'scroll'});
  });
}

I tried to use the "window.scrollTo" and it didn't work. I also tried to use the pynput module. I don't know what the issue is.


问:
why python function is not finding the global variable?
```<code>    def bToDLL(,root):
        # do Code here

        h,p = None, None
        def sol(r):
            global h,p
            if(r == None): return None

            sol(r.left)

            if(p == None): h = r
            else:
                r.left = p
                p.right = r

            p = r

            sol(r.right)

        sol(root)

        return(h)
</code>```

but this is showing this error:

```<code>  File "/home/f03e32e9d366ee3e9a5adb9d71436496.py", line 33, in bToDLL
    sol(root)
  File "/home/f03e32e9d366ee3e9a5adb9d71436496.py", line 22, in sol
    sol(r.left)
  File "/home/f03e32e9d366ee3e9a5adb9d71436496.py", line 24, in sol
    if(p == None): h = r
NameError: name 'p' is not defined
</code>```

i have defined the var p in global scope! ,and have marked it as global inside function too but why it is not finding it ?

Body:
    def bToDLL(,root):
        # do Code here

        h,p = None, None
        def sol(r):
            global h,p
            if(r == None): return None

            sol(r.left)

            if(p == None): h = r
            else:
                r.left = p
                p.right = r

            p = r

            sol(r.right)

        sol(root)

        return(h)

but this is showing this error:

  File "/home/f03e32e9d366ee3e9a5adb9d71436496.py", line 33, in bToDLL
    sol(root)
  File "/home/f03e32e9d366ee3e9a5adb9d71436496.py", line 22, in sol
    sol(r.left)
  File "/home/f03e32e9d366ee3e9a5adb9d71436496.py", line 24, in sol
    if(p == None): h = r
NameError: name 'p' is not defined

i have defined the var p in global scope! ,and have marked it as global inside function too but why it is not finding it ?


问:
http status: 403, code:-1 - https://api.spotify.com/v1/me/: User not registered in the Developer Dashboard
After testing the Flask example on spotipy/app.py.

I noticed after adding my own email, I keep getting User not registered in the Developer Dashboard.

Why could this be the issue? I am using the exact spotify account when I authenticate


问:
my program isnt writing to process memory. how do i debug this? im new to wpm and rpm
`

```<code>#include <iostream>
#include <windows.h>
#include <Tlhelp32.h>

HANDLE hProc = NULL;
DWORD pID;

bool attachProc(char* procName)
{
    PROCESSENTRY32 procEntry32;
    procEntry32.dwSize = sizeof(PROCESSENTRY32);
    auto hProcSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

    if(hProcSnap == INVALID_HANDLE_VALUE)
    {
        std::cout << "FAILED to take snapshot of processes\n";
        return false;
    }

    while(Process32Next(hProcSnap, &procEntry32))
    {
        std::cout << procEntry32.szExeFile << std::endl;
        if (procEntry32.th32ProcessID != 996)
        {

            if (!strcmp(procName, procEntry32.szExeFile))
        {
            std::cout << "found process " << procEntry32.szExeFile << " with process id " << procEntry32.th32ProcessID << std::endl;
            hProc = OpenProcess(PROCESS_ALL_ACCESS,FALSE,procEntry32.th32ProcessID);
            pID = procEntry32.th32ProcessID;

            if (hProc == NULL)
            {
                std::cout << "failed getting handle to process" << std::endl;
            }

            CloseHandle(hProcSnap);
            return true;
        }

        }
    }

    std::cout << "couldnt find " << procName << "in the process snapshot" << std::endl;
    CloseHandle(hProcSnap);
    return false;
}

template <class dataType>
void wpm(dataType valToWrite, DWORD adressToWrite)
{
    WriteProcessMemory(hProc, (PVOID)adressToWrite, &valToWrite, sizeof(dataType), 0);
}

template <class dataType>
dataType rpm(DWORD adressToRead)
{
    dataType rpmBuffer;
    ReadProcessMemory(hProc, (PVOID)adressToRead, &rpmBuffer, sizeof(dataType), 0);
    return rpmBuffer;
}

int main()
{
    DWORD memoryAdress = 0x288469A7A28;
    int value = 1

    attachProc((char*)"dummy.exe");
    while (true)
    {
        wpm<int>(value, memoryAdress);
    }

}
</code>```

`

i think there is a problem in getting the handle but i dont know where or how do i debug this.
is there any different way on how to get a handle? bestsides FindWindow() because this doesnt work either

i was trying to write process memory but id didnt work for some reason the adress should be good i tested it in cheat engine multiple times

Body:
`

#include <iostream>
#include <windows.h>
#include <Tlhelp32.h>

HANDLE hProc = NULL;
DWORD pID;

bool attachProc(char* procName)
{
    PROCESSENTRY32 procEntry32;
    procEntry32.dwSize = sizeof(PROCESSENTRY32);
    auto hProcSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

    if(hProcSnap == INVALID_HANDLE_VALUE)
    {
        std::cout << "FAILED to take snapshot of processes\n";
        return false;
    }

    while(Process32Next(hProcSnap, &procEntry32))
    {
        std::cout << procEntry32.szExeFile << std::endl;
        if (procEntry32.th32ProcessID != 996)
        {

            if (!strcmp(procName, procEntry32.szExeFile))
        {
            std::cout << "found process " << procEntry32.szExeFile << " with process id " << procEntry32.th32ProcessID << std::endl;
            hProc = OpenProcess(PROCESS_ALL_ACCESS,FALSE,procEntry32.th32ProcessID);
            pID = procEntry32.th32ProcessID;

            if (hProc == NULL)
            {
                std::cout << "failed getting handle to process" << std::endl;
            }

            CloseHandle(hProcSnap);
            return true;
        }

        }
    }

    std::cout << "couldnt find " << procName << "in the process snapshot" << std::endl;
    CloseHandle(hProcSnap);
    return false;
}

template <class dataType>
void wpm(dataType valToWrite, DWORD adressToWrite)
{
    WriteProcessMemory(hProc, (PVOID)adressToWrite, &valToWrite, sizeof(dataType), 0);
}

template <class dataType>
dataType rpm(DWORD adressToRead)
{
    dataType rpmBuffer;
    ReadProcessMemory(hProc, (PVOID)adressToRead, &rpmBuffer, sizeof(dataType), 0);
    return rpmBuffer;
}

int main()
{
    DWORD memoryAdress = 0x288469A7A28;
    int value = 1

    attachProc((char*)"dummy.exe");
    while (true)
    {
        wpm<int>(value, memoryAdress);
    }

}

`

i think there is a problem in getting the handle but i dont know where or how do i debug this.
is there any different way on how to get a handle? bestsides FindWindow() because this doesnt work either

i was trying to write process memory but id didnt work for some reason the adress should be good i tested it in cheat engine multiple times


问:
Identify mismatched columns of two hive views
I have two Hive views, hiveView1 and hiveView2

Would like to compare two hive views and find which columns are mismatching.

Step1:

Was able to compare data between two hive views with below command

```<code>select sum(hash(*)) from hiveView1;
select sum(hash(*)) from hiveView2;
</code>```

Step2:
If the data from step1 mismatches, have to identify which columns are mismatching. Any script to identify the mismatched columns

Body:
I have two Hive views, hiveView1 and hiveView2

Would like to compare two hive views and find which columns are mismatching.

Step1:

Was able to compare data between two hive views with below command

select sum(hash(*)) from hiveView1;
select sum(hash(*)) from hiveView2;

Step2:
If the data from step1 mismatches, have to identify which columns are mismatching. Any script to identify the mismatched columns


问:
Pynput Hotkey randomly going off when only the first key is pressed
I've maid a text to speech script and it seems to finally be working well, but for some reason after you use a hotkey and I think specifically ctrl+alt+v, the hotkey will randomly run when your press ctrl. Any idea why this is? Also before you ask, I needed to create a second global hotkeys for the stop and exit functions because they need to run on their own thread to cancel speech, also only ctrl+alt+v can be stopped. Thanks ahead of time!</p>
```<code>import pyttsx3
import pyperclip
import pynput.keyboard as keyboard
import re

def safeStart():
    try:
        e.startLoop(False)
    except RuntimeError:
        return

def safeEnd():
    try:
        e.endLoop()
    except RuntimeError:
        return

def splitText(text):
    t = re.split(r'[.?!,]', text)
    return t

def sayText(text):
    global stop

    stop = False
    t = splitText(text)
    print(t)
    for i in t:
        safeStart()
        e.say(i)
        e.iterate()
        print(i)
        safeEnd()
        if stop:
            stop = False
            break

def speakText(text):
    safeStart()
    e.say(text)
    e.iterate()
    e.endLoop()

def stopSpeak():
    global stop
    stop = True
    print(stop)

e = pyttsx3.init()
e.setProperty("rate", 250)
stop = False

a =  keyboard.GlobalHotKeys({
    "<ctrl>+<alt>+v": lambda: (sayText(pyperclip.paste())),
    "<ctrl>+<alt>+b": lambda: (speakText(pyperclip.paste())),
})
a.start()

with keyboard.GlobalHotKeys({
    "<ctrl>+<alt>+x": stopSpeak,
    "<ctrl>+<alt>+<esc>": exit
}) as h:
    h.join()
</code>```

Body:
I've maid a text to speech script and it seems to finally be working well, but for some reason after you use a hotkey and I think specifically ctrl+alt+v, the hotkey will randomly run when your press ctrl. Any idea why this is? Also before you ask, I needed to create a second global hotkeys for the stop and exit functions because they need to run on their own thread to cancel speech, also only ctrl+alt+v can be stopped. Thanks ahead of time!

import pyttsx3
import pyperclip
import pynput.keyboard as keyboard
import re

def safeStart():
    try:
        e.startLoop(False)
    except RuntimeError:
        return

def safeEnd():
    try:
        e.endLoop()
    except RuntimeError:
        return

def splitText(text):
    t = re.split(r'[.?!,]', text)
    return t

def sayText(text):
    global stop

    stop = False
    t = splitText(text)
    print(t)
    for i in t:
        safeStart()
        e.say(i)
        e.iterate()
        print(i)
        safeEnd()
        if stop:
            stop = False
            break

def speakText(text):
    safeStart()
    e.say(text)
    e.iterate()
    e.endLoop()

def stopSpeak():
    global stop
    stop = True
    print(stop)

e = pyttsx3.init()
e.setProperty("rate", 250)
stop = False

a =  keyboard.GlobalHotKeys({
    "<ctrl>+<alt>+v": lambda: (sayText(pyperclip.paste())),
    "<ctrl>+<alt>+b": lambda: (speakText(pyperclip.paste())),
})
a.start()

with keyboard.GlobalHotKeys({
    "<ctrl>+<alt>+x": stopSpeak,
    "<ctrl>+<alt>+<esc>": exit
}) as h:
    h.join()