问:
How to write a custom hook which has multiple async functions inside it so that I can separate logic on the custom hook?
The code for the custom hook, useCast is as follows:

```<code>const useCart = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [cart, setCart] = useState([]);
  const toast = useToast();

  const addToCart = async (categoryId, quantity) => {
    setLoading(true);
    try {
      const res = await ax.post("/cart", { category: categoryId, quantity });
      setCart(res.data?.categories);
    } catch (err) {
      console.log(err);
      setError(err.response?.data);
    }
    setLoading(false);
  };

  const getCartList = async () => {
    setLoading(true);
    try {
      const res = await ax.get("/cart/");
      setCart(res.data);
    } catch (err) {
      console.log(err);
      setError(err.response?.data);
    }
    setLoading(false);
    return cart;
  };

  const emptyCartState = () => {
    setCart([]);
  };

  useEffect(() => {
    if (error)
      toast({
        title: error,
        status: "error",
        isClosable: true,
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [error]);

  return {
    addToCart,
    cart,
    useCartLoading: loading,
    useCartError: error,
    getCartList,
    emptyCartState,
  };
};

export default useCart;
</code>```

And it is being called like this:

```<code>const { user } = useContext(AuthContext);
  const { cartDispatch } = useContext(CartContext);

  const { cart, getCartList, useCartLoading } = useCart();

  // const viewCartList = async () => {
  //   try {
  //     const res = await ax.get("/cart/");
  //     return res.data;
  //   } catch (error) {
  //     console.log(error.response?.data);
  //   }
  // };

  useEffect(() => {
    if (user) {
      const updateCart = async () => {
        const updatedCart = await getCartList();
        console.log(updatedCart);
        // console.log(useCartLoading);
        cartDispatch({ type: "UPDATE_CART", payload: updatedCart });
      };
      updateCart();
    } else {
      cartDispatch({ type: "UPDATE_CART", payload: [] });
    }
  }, [user]);
</code>```

Can anyone please help me out with this? Whenever I use custom hook, it does not work. The commented out ViewCartList works though, so I'm guessing it's the custom hook which has not been implemented correctly. The custom hook returns old data, and does not return the updated data on first call. Like it returns updated data on second call for same request.
How do you implement custom hooks? What I want to achieve is that, I want to separate the logic on the custom hook, and based on what the custom hook returns, I want to update my context values on the page. The functions inside the hook has to be async.

Body:
The code for the custom hook, useCast is as follows:

const useCart = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [cart, setCart] = useState([]);
  const toast = useToast();

  const addToCart = async (categoryId, quantity) => {
    setLoading(true);
    try {
      const res = await ax.post("/cart", { category: categoryId, quantity });
      setCart(res.data?.categories);
    } catch (err) {
      console.log(err);
      setError(err.response?.data);
    }
    setLoading(false);
  };

  const getCartList = async () => {
    setLoading(true);
    try {
      const res = await ax.get("/cart/");
      setCart(res.data);
    } catch (err) {
      console.log(err);
      setError(err.response?.data);
    }
    setLoading(false);
    return cart;
  };

  const emptyCartState = () => {
    setCart([]);
  };

  useEffect(() => {
    if (error)
      toast({
        title: error,
        status: "error",
        isClosable: true,
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [error]);

  return {
    addToCart,
    cart,
    useCartLoading: loading,
    useCartError: error,
    getCartList,
    emptyCartState,
  };
};

export default useCart;

And it is being called like this:

const { user } = useContext(AuthContext);
  const { cartDispatch } = useContext(CartContext);

  const { cart, getCartList, useCartLoading } = useCart();

  // const viewCartList = async () => {
  //   try {
  //     const res = await ax.get("/cart/");
  //     return res.data;
  //   } catch (error) {
  //     console.log(error.response?.data);
  //   }
  // };

  useEffect(() => {
    if (user) {
      const updateCart = async () => {
        const updatedCart = await getCartList();
        console.log(updatedCart);
        // console.log(useCartLoading);
        cartDispatch({ type: "UPDATE_CART", payload: updatedCart });
      };
      updateCart();
    } else {
      cartDispatch({ type: "UPDATE_CART", payload: [] });
    }
  }, [user]);

Can anyone please help me out with this? Whenever I use custom hook, it does not work. The commented out ViewCartList works though, so I'm guessing it's the custom hook which has not been implemented correctly. The custom hook returns old data, and does not return the updated data on first call. Like it returns updated data on second call for same request.
How do you implement custom hooks? What I want to achieve is that, I want to separate the logic on the custom hook, and based on what the custom hook returns, I want to update my context values on the page. The functions inside the hook has to be async.


来源: stackexchange

问:
Sometimes doesn't create object stores in IndexedDb
I completely delete the database named "AdminDatabase" when the user first logs into the website. Then I create the database, object stores and indexes again and make the database connection. However, sometimes (usually on the first login) the database crashes and object stores are not created. I cannot view the database information from the browser (version number etc.). The object stores are rendered correctly when I refresh the page several times. What is the reason of this?

I've used try-catch blocks and onerror() methods but haven't encountered any error messages.

DATABASE CREATED NOT SUCCES SCREENSHOT

DATABASE CREATED SUCCES SCREENSHOT

DATABASE DELETE AND CREATE CODE

```<code>
  //DELETE DATABASE
  var req = indexedDB.deleteDatabase("AdminDatabase");
  req.onsuccess = function () {
      console.log("Deleted database successfully");
  }
  req.onerror = (event) =>{
      console.log("Deleted database error: " + event.target.result);
  }

//CREATE DATABASE
const request = window.indexedDB.open("AdminDatabase", 4);
request.onupgradeneeded = function (event) {
  console.log("onupgradeneeded successfully");

    var db = event.target.result;

    if (event.oldVersion < 1) {
        var objectStore = db.createObjectStore("floors", { keyPath: "id", autoIncrement: true });
    }

    if (event.oldVersion < 2) {
        var objectStore = db.createObjectStore("rooms", { keyPath: "id", autoIncrement: true });
        let index = objectStore.createIndex('floorIndex', ['floorIndex']);

    }

    if (event.oldVersion < 3) {
        var objectStore = db.createObjectStore("components", { keyPath: "id", autoIncrement: true });
        let index = objectStore.createIndex('componentFloorId, componentRoomId', ['componentFloorId', 'componentRoomId']);
        let index2 = objectStore.createIndex('componentFloorId', ['componentFloorId']);

        // let index2 = objectStore.createIndex('roomId', 'roomId', { unique: false});

    }
    if (event.oldVersion < 4) {
        var objectStore = db.createObjectStore("scenarios", { keyPath: "id", autoIncrement: true });
    }

    // objectStore.createIndex("name", "name", { unique: false });

};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I completely delete the database named "AdminDatabase" when the user first logs into the website. Then I create the database, object stores and indexes again and make the database connection. However, sometimes (usually on the first login) the database crashes and object stores are not created. I cannot view the database information from the browser (version number etc.). The object stores are rendered correctly when I refresh the page several times. What is the reason of this?

I've used try-catch blocks and onerror() methods but haven't encountered any error messages.

DATABASE CREATED NOT SUCCES SCREENSHOT

DATABASE CREATED SUCCES SCREENSHOT

DATABASE DELETE AND CREATE CODE

  //DELETE DATABASE
  var req = indexedDB.deleteDatabase("AdminDatabase");
  req.onsuccess = function () {
      console.log("Deleted database successfully");
  }
  req.onerror = (event) =>{
      console.log("Deleted database error: " + event.target.result);
  }

//CREATE DATABASE
const request = window.indexedDB.open("AdminDatabase", 4);
request.onupgradeneeded = function (event) {
  console.log("onupgradeneeded successfully");

    var db = event.target.result;

    if (event.oldVersion < 1) {
        var objectStore = db.createObjectStore("floors", { keyPath: "id", autoIncrement: true });
    }

    if (event.oldVersion < 2) {
        var objectStore = db.createObjectStore("rooms", { keyPath: "id", autoIncrement: true });
        let index = objectStore.createIndex('floorIndex', ['floorIndex']);

    }

    if (event.oldVersion < 3) {
        var objectStore = db.createObjectStore("components", { keyPath: "id", autoIncrement: true });
        let index = objectStore.createIndex('componentFloorId, componentRoomId', ['componentFloorId', 'componentRoomId']);
        let index2 = objectStore.createIndex('componentFloorId', ['componentFloorId']);

        // let index2 = objectStore.createIndex('roomId', 'roomId', { unique: false});

    }
    if (event.oldVersion < 4) {
        var objectStore = db.createObjectStore("scenarios", { keyPath: "id", autoIncrement: true });
    }

    // objectStore.createIndex("name", "name", { unique: false });

};


问:
Add column to dataframe that repeats a value based on how many rows the dataframe has in r
I have a dataframe that I would like to add a new column to. I would like the new column to repeat the character 'apple' for every row in that dataframe.

Example data:

```<code>#Example columns
Label <- c("Blue_001_Series009", "Blue_001_Series009", "Blue_001_Series009", "Blue_001_Series009","Red_001_Series008", "Red_001_Series008","Red_001_Series008","Red_001_Series008","Blue_002_Series009", "Blue_002_Series009","Blue_002_Series009","Blue_002_Series009")
Pred <- c("Pear", "Orange", "Apple", "Peach", "Pear", "Orange", "Apple", "Peach", "Pear", "Orange", "Apple", "Peach")
n <- c(10, 223, 890, 34, 78, 902, 34, 211, 1007,209, 330, 446)

#make example data frame
data <- data.frame(Label, Pred, n)
</code>```

I can do this using

```<code>#Checking how many rows of data there are
dim(data)

#there are 12 rows

#Repeat apple in new column 12 times
data$new_col<-rep("Apple",times=12)
data
</code>```

If I were to feed a new dataframe that has a different amount of rows, is there a way to specify the times = (how many rows are in my dataframe)

E.g. new dataframe with 24 rows

```<code>#Example columns
Label <- rep(c("Blue_001_Series009", "Blue_001_Series009", "Blue_001_Series009", "Blue_001_Series009","Red_001_Series008", "Red_001_Series008","Red_001_Series008","Red_001_Series008","Blue_002_Series009", "Blue_002_Series009","Blue_002_Series009","Blue_002_Series009"), times =2)
Pred <- rep(c("Pear", "Orange", "Apple", "Peach", "Pear", "Orange", "Apple", "Peach", "Pear", "Orange", "Apple", "Peach"), times = 2)
n <- rep(c(10, 223, 890, 34, 78, 902, 34, 211, 1007,209, 330, 446), times = 2)

#make example data frame
data <- data.frame(Label, Pred, n)

#Repeat apple in new column 24 times
data$new_col<-rep("Apple",times=???)
data
</code>```

How do I now automatically let times = 24, without manually typing in 24... So I can automate my script. Thank you!

Body:
I have a dataframe that I would like to add a new column to. I would like the new column to repeat the character 'apple' for every row in that dataframe.

Example data:

#Example columns
Label <- c("Blue_001_Series009", "Blue_001_Series009", "Blue_001_Series009", "Blue_001_Series009","Red_001_Series008", "Red_001_Series008","Red_001_Series008","Red_001_Series008","Blue_002_Series009", "Blue_002_Series009","Blue_002_Series009","Blue_002_Series009")
Pred <- c("Pear", "Orange", "Apple", "Peach", "Pear", "Orange", "Apple", "Peach", "Pear", "Orange", "Apple", "Peach")
n <- c(10, 223, 890, 34, 78, 902, 34, 211, 1007,209, 330, 446)

#make example data frame
data <- data.frame(Label, Pred, n)

I can do this using

#Checking how many rows of data there are
dim(data)

#there are 12 rows

#Repeat apple in new column 12 times
data$new_col<-rep("Apple",times=12)
data

If I were to feed a new dataframe that has a different amount of rows, is there a way to specify the times = (how many rows are in my dataframe)

E.g. new dataframe with 24 rows

#Example columns
Label <- rep(c("Blue_001_Series009", "Blue_001_Series009", "Blue_001_Series009", "Blue_001_Series009","Red_001_Series008", "Red_001_Series008","Red_001_Series008","Red_001_Series008","Blue_002_Series009", "Blue_002_Series009","Blue_002_Series009","Blue_002_Series009"), times =2)
Pred <- rep(c("Pear", "Orange", "Apple", "Peach", "Pear", "Orange", "Apple", "Peach", "Pear", "Orange", "Apple", "Peach"), times = 2)
n <- rep(c(10, 223, 890, 34, 78, 902, 34, 211, 1007,209, 330, 446), times = 2)

#make example data frame
data <- data.frame(Label, Pred, n)

#Repeat apple in new column 24 times
data$new_col<-rep("Apple",times=???)
data

How do I now automatically let times = 24, without manually typing in 24... So I can automate my script. Thank you!


问:
google translate element is not working on mobile view
i used below code to translate my website from the language Eng - Arabic.

```<code><script type="text/javascript" src="//translate.google.com/translate_a/element.js?
cb=googleTranslateElementInit"></script>

<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en' , includedLanguages : 'ar,xx,yy,en',
layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</code>```

its working fine in laptop view.but when i test it on mobile view its not working properly.and also i set a new language translation code in mobile view.and call the same script.

```<code><!-- laptop view-->
<div id="google_translate_element" class="trans" style="padding:0px;"  ></div>

         <!-- mob view-->
          <div id="google_translate_element" style="padding:0px;">
            <div class="skiptranslate goog-te-gadget" dir="ltr" style="">
              <div id=":0.targetLanguage">
                <select class="goog-te-combo" aria-label="Language Translate Widget" style="padding: 5px;
background: azure;
font-size: 15px;
border-radius: 10px;
font-weight: 700 !important;">
                  <option value="">Select Language</option>
                  <option value="ar">Arabic</option>
                </select>
              </div>
            </div>
          </div>
</code>```

when i comment the mobile view code, 2 select box appearing on mobile view and working fine with mobile view and not in laptop view the website link given here


问:
Creating Flash Light with Voice Command JAVA Android Studio
I'm a total noob android studio, I've been doing a little project with the flashLight and with the switch button and create a voice button and say " turn on the flash light " then the light will turn on, same thing as turn it off, I already create the flash light button to turn it on and off, but I do not know how to add the command method to it, I did create the google command, but it doesn't work Please help. Thank You.

```<code>// this is the code I did for the flash light, I create an on/ off switch and the text will change when the light is on or off.

{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                torch(isChecked);

            }
        });
    }

    private void torch(boolean isChecked) {

        try {
            cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);
            cameraID = cameraManager.getCameraIdList()[0];
            cameraManager.setTorchMode(cameraID,isChecked);
            result = isChecked? "ON" : "OFF";
            textView.setText(result);

        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    }
</code>```

I did try the speech recognizer and google command but still doesn't work.

Please help me. Thank you.

Body:
I'm a total noob android studio, I've been doing a little project with the flashLight and with the switch button and create a voice button and say " turn on the flash light " then the light will turn on, same thing as turn it off, I already create the flash light button to turn it on and off, but I do not know how to add the command method to it, I did create the google command, but it doesn't work Please help. Thank You.

// this is the code I did for the flash light, I create an on/ off switch and the text will change when the light is on or off.

{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                torch(isChecked);

            }
        });
    }

    private void torch(boolean isChecked) {

        try {
            cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);
            cameraID = cameraManager.getCameraIdList()[0];
            cameraManager.setTorchMode(cameraID,isChecked);
            result = isChecked? "ON" : "OFF";
            textView.setText(result);

        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    }

I did try the speech recognizer and google command but still doesn't work.

Please help me. Thank you.


问:
Unable to Force Resolve in Unity 2022.1.0b2 with Firebase sdk version 10.3
I am getting this error when I do force resolve for android:

stderr:

FAILURE: Build failed with an exception.

What went wrong:
Could not create an instance of type org.gradle.initialization.DefaultSettings_Decorated.

Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 1s

(I am on Macbook Air 2017)


问:
OpenGL OpenCL interoperability with VBO
I'm using the following callback function for glutDispayFunc

```<code>    void Display(){

    glutSetWindow( subwindow_1 );

    glDisable(GL_TEXTURE_2D);
    glDrawBuffer( GL_BACK );
    glEnable(GL_POINT_SMOOTH);
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
    glShadeModel(GL_SMOOTH);
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity( );
    glDepthMask(GL_FALSE);
    glUseProgram(prog);
    glBindBuffer( GL_ARRAY_BUFFER, hPobj );
    glVertexPointer( 4, GL_FLOAT, 0, (void *)0 );
    glEnableClientState( GL_VERTEX_ARRAY );

    glBindBuffer( GL_ARRAY_BUFFER, hCobj );
    glColorPointer( 4, GL_FLOAT, 0, (void *)0 );
    glEnableClientState( GL_COLOR_ARRAY );

    glDrawArrays( GL_POINTS, 0, NUM_POINTS );
    glDisableClientState( GL_VERTEX_ARRAY );
    glDisableClientState( GL_COLOR_ARRAY );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );

    glutSwapBuffers( );
    glEnd();
    }
</code>```

An OpenCL kernel is used to modify the attributes on GPU. The position and color attributes are bind before glDrawArrays is called. Is there anyway to also pass custom radius (glPointSize) for each vertex?

Title: OpenGL OpenCL interoperability with VBO

Body:
I'm using the following callback function for glutDispayFunc

    void Display(){

    glutSetWindow( subwindow_1 );

    glDisable(GL_TEXTURE_2D);
    glDrawBuffer( GL_BACK );
    glEnable(GL_POINT_SMOOTH);
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
    glShadeModel(GL_SMOOTH);
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity( );
    glDepthMask(GL_FALSE);
    glUseProgram(prog);
    glBindBuffer( GL_ARRAY_BUFFER, hPobj );
    glVertexPointer( 4, GL_FLOAT, 0, (void *)0 );
    glEnableClientState( GL_VERTEX_ARRAY );

    glBindBuffer( GL_ARRAY_BUFFER, hCobj );
    glColorPointer( 4, GL_FLOAT, 0, (void *)0 );
    glEnableClientState( GL_COLOR_ARRAY );

    glDrawArrays( GL_POINTS, 0, NUM_POINTS );
    glDisableClientState( GL_VERTEX_ARRAY );
    glDisableClientState( GL_COLOR_ARRAY );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );

    glutSwapBuffers( );
    glEnd();
    }

An OpenCL kernel is used to modify the attributes on GPU. The position and color attributes are bind before glDrawArrays is called. Is there anyway to also pass custom radius (glPointSize) for each vertex?


问:
convert youtube video id from url
```<code><div class="container">
https://youtu.be/_32C_wVWEF0
</div>
</code>```

div class(video-container) is not created
I want to create a div class (video-container) where I want.
please help fix the code.

Find the link in the text and convert it to the embed code
Please let me know if there is any other way.

```<code><script>
function youtubeParser(url, ...young) {
console.log(url);
const container = `
<div class="video-container" style="width: 100%; height:100%">
<iframe width="560"
height="315"src="https://www.youtube.com/embed/#ID#?rel=0&controls=0"
title="YouTube video player"
frameborder="0" allow="accelerometer; autoplay; clipboard-write;
encrypted-media; gyroscope; picture-in-picture"
allowfullscreen; ></iframe>
</div>`;

return young && young[6].length == 11
? container.replace("#ID#", young[6])
: url;
 }
const content = document.querySelector("body");

const youtubeUrlExp = /(http:|https:)?(\/\/)?(www\.)?
(youtube.com|youtu.be)\/(watch|embed)?(\?v=|\/)?(\S+)?/g;
const wrappedContent = content.innerHTML.replace(youtubeUrlExp,
youtubeParser);

content.innerHTML = wrappedContent;
</script>
</code>```

Title: convert youtube video id from url

Body:
https://youtu.be/_32C_wVWEF0

div class(video-container) is not created
I want to create a div class (video-container) where I want.
please help fix the code.

Find the link in the text and convert it to the embed code
Please let me know if there is any other way.


问:
Why my code is not able to save image details?
I am trying to implement a module where logged in users will upload property details and we can access those detail later on

```<code>// Configuring multer library
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

// new document
const doc = new propertyModel({
    _id: isVerified.userId,
    name: name,
    location: location,
    description: description,
    price: price,
    area: area,
    bedroom: bedroom,
    bathroom: bathroom,
    owner: owner,
    type: type,
    city: city,
    images: images,
    videos: videos
});
// save document
await doc.save();
</code>```

error log :-

```<code>RangeError: offset is out of bounds
    at Buffer.set (<anonymous>)
    at serializeBuffer (C:\Users\siddharth singh\Documents\myalldetails\working\v6\backend\node_modules\bson\lib\parser\serializer.js:255:12)
    at serializeInto (C:\Users\siddharth singh\Documents\myalldetails\working\v6\backend\node_modules\bson\lib\parser\serializer.js:807:25)
    at serializeObject (C:\Users\siddharth singh\Documents\myalldetails\working\v6\backend\node_modules\bson\lib\parser\serializer.js:282:20)
    at serializeInto (C:\Users\siddharth singh\Documents\myalldetails\working\v6\backend\node_modules\bson\lib\parser\serializer.js:607:25)
    at serializeObject (C:\Users\siddharth singh\Documents\myalldetails\working\v6\backend\node_modules\bson\lib\parser\serializer.js:282:20)
    at serializeInto (C:\Users\siddharth singh\Documents\myalldetails\working\v6\backend\node_modules\bson\lib\parser\serializer.js:813:25)
    at serializeObject (C:\Users\siddharth singh\Documents\myalldetails\working\v6\backend\node_modules\bson\lib\parser\serializer.js:282:20)
    at serializeInto (C:\Users\siddharth singh\Documents\myalldetails\working\v6\backend\node_modules\bson\lib\parser\serializer.js:607:25)
    at serializeObject (C:\Users\siddharth singh\Documents\myalldetails\working\v6\backend\node_modules\bson\lib\parser\serializer.js:282:20) ```
```

Body:
I am trying to implement a module where logged in users will upload property details and we can access those detail later on

// Configuring multer library
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

// new document
const doc = new propertyModel({
    _id: isVerified.userId,
    name: name,
    location: location,
    description: description,
    price: price,
    area: area,
    bedroom: bedroom,
    bathroom: bathroom,
    owner: owner,
    type: type,
    city: city,
    images: images,
    videos: videos
});
// save document
await doc.save();

error log :-

RangeError: offset is out of bounds
    at Buffer.set (<anonymous>)
    at serializeBuffer (C:\Users\siddharth singh\Documents\myalldetails\working\v6\backend\node_modules\bson\lib\parser\serializer.js:255:12)
    at serializeInto (C:\Users\siddharth singh\Documents\myalldetails\working\v6\backend\node_modules\bson\lib\parser\serializer.js:807:25)
    at serializeObject (C:\Users\siddharth singh\Documents\myalldetails\working\v6\backend\node_modules\bson\lib\parser\serializer.js:282:20)
    at serializeInto (C:\Users\siddharth singh\Documents\myalldetails\working\v6\backend\node_modules\bson\lib\parser\serializer.js:607:25)
    at serializeObject (C:\Users\siddharth singh\Documents\myalldetails\working\v6\backend\node_modules\bson\lib\parser\serializer.js:282:20)
    at serializeInto (C:\Users\siddharth singh\Documents\myalldetails\working\v6\backend\node_modules\bson\lib\parser\serializer.js:813:25)
    at serializeObject (C:\Users\siddharth singh\Documents\myalldetails\working\v6\backend\node_modules\bson\lib\parser\serializer.js:282:20)
    at serializeInto (C:\Users\siddharth singh\Documents\myalldetails\working\v6\backend\node_modules\bson\lib\parser\serializer.js:607:25)
    at serializeObject (C:\Users\siddharth singh\Documents\myalldetails\working\v6\backend\node_modules\bson\lib\parser\serializer.js:282:20) ```


问:
How to convert '2022-11-02 16:57' to "02.11.22"
It is necessary to transfer the dates from Excel columns to a .pdf report.

Using the xlrd module, the dates are displayed '2022-11-02 16:57'

Question: How to make a convenient and readable view of "02.11.22" from '2022-11-02 16:57'

My code:

```<code>
import xlrd
from reportlab.pdfgen.canvas import Canvas

x = 63
y = 475

# Сбор данных с определенного столбца в Excel.
cells_date = tabl_list.col_slice(0, 1, 30)

# Отображение полученных данных из Excel в отчете .pdf
for cell_date in cells_date:
    canvas.drawString(x, y, cell_date.value)
    y -= 15

</code>```

Даты выводятся в .pdf в таком формате:

I tried using "datetime", but I'm not an experienced programmer yet, so I decided to ask for help here.

Body:
It is necessary to transfer the dates from Excel columns to a .pdf report.

Using the xlrd module, the dates are displayed '2022-11-02 16:57'

Question: How to make a convenient and readable view of "02.11.22" from '2022-11-02 16:57'

My code:

import xlrd
from reportlab.pdfgen.canvas import Canvas

x = 63
y = 475

# Сбор данных с определенного столбца в Excel.
cells_date = tabl_list.col_slice(0, 1, 30)

# Отображение полученных данных из Excel в отчете .pdf
for cell_date in cells_date:
    canvas.drawString(x, y, cell_date.value)
    y -= 15

Даты выводятся в .pdf в таком формате:

I tried using "datetime", but I'm not an experienced programmer yet, so I decided to ask for help here.


问:
Possible to matplotlib's constrained_layout ignore axis tick labels?
I have a reasonably complicated grid of subplots that involves two sets (one on the left and another on the right) of columns plotting a set of quantities for each row, separated by a common legend to label the entries in each row.

Here is a sample of what I want to accomplish

Using matplotlib with constrained_layout = True works 95% perfectly for applying the out optimal sizes & spacing for the columns, down to the tricky case of having the legend run down the middle. The remaining 5% is highlighted in red, where the wordy x-axis tick labels seem to push away the columns: it would be perfect if there was a way to make the layout engine "ignore" the tick labels in determining the spacing.

Methods using other libraries are also appreciated. Thank you in advance.

What I tried:

subplots_adjust

GridSpec

The main difficulty with those attempts:
constrained_layout is incompatible with those settings, so one must sacrifice the optimized legend spacing at the cost of getting the column spacing right, or vice versa.


问:
Rancher RKE failed - metadata.resourceVersion Invalid value
I have K8S cluster with rancher and i run rke to add new nodes.

Running RKE version: v1.2.18

Kubernetes Version: v1.20.15

Since few weeks, the rke process failed with this error:

```<code>time="2022-12-26T01:56:35-05:00" level=info msg="[network] Setting up network plugin: canal"
time="2022-12-26T01:56:35-05:00" level=info msg="[addons] Saving ConfigMap for addon rke-network-plugin to Kubernetes"
time="2022-12-26T01:56:35-05:00" level=info msg="[addons] Successfully saved ConfigMap for addon rke-network-plugin to Kubernetes"
time="2022-12-26T01:56:35-05:00" level=info msg="[addons] Executing deploy job rke-network-plugin"
time="2022-12-26T01:56:35-05:00" level=debug msg="Checking node list for node [10.11.187.184], try #1"
time="2022-12-26T01:56:35-05:00" level=debug msg="[k8s] replacing job rke-network-plugin-deploy-job.. "
time="2022-12-26T01:56:40-05:00" level=debug msg="[k8s] waiting for job rke-network-plugin-deploy-job to complete.."
time="2022-12-26T01:57:40-05:00" level=fatal msg="Failed to get job complete status for job rke-network-plugin-deploy-job in namespace kube-system"
</code>```

Logs of rke-network-plugin-deploy-job:

```<code>Resource: "apiextensions.k8s.io/v1, Resource=customresourcedefinitions", GroupVersionKind: "apiextensions.k8s.io/v1, Kind=CustomResourceDefinition"
Name: "networksets.crd.projectcalico.org", Namespace: ""
for: "/etc/config/rke-network-plugin.yaml": customresourcedefinitions.apiextensions.k8s.io "networksets.crd.projectcalico.org" is invalid: metadata.resourceVersion: Invalid value: 0x0: must be specified for an update
</code>```

CRD yaml:

```<code>apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"apiextensions.k8s.io/v1beta1","kind":"CustomResourceDefinition","metadata":{"annotations":{},"creationTimestamp":"2019-10-31T14:11:28Z","generation":1,"name":"networksets.crd.projectcalico.org","namespace":"","resourceVersion":"197472064","selfLink":"/apis/apiextensions.k8s.io/v1beta1/customresourcedefinitions/networksets.crd.projectcalico.org","uid":"9dfc6e5b-f861-4d35-ae2e-004cd212686e"},"spec":{"conversion":{"strategy":"None"},"group":"crd.projectcalico.org","names":{"kind":"NetworkSet","listKind":"NetworkSetList","plural":"networksets","singular":"networkset"},"preserveUnknownFields":true,"scope":"Namespaced","version":"v1","versions":[{"name":"v1","served":true,"storage":true}]},"status":{"acceptedNames":{"kind":"NetworkSet","listKind":"NetworkSetList","plural":"networksets","singular":"networkset"},"conditions":[{"lastTransitionTime":"2019-10-31T14:11:28Z","message":"no conflicts found","reason":"NoConflicts","status":"True","type":"NamesAccepted"},{"lastTransitionTime":null,"message":"the initial names have been accepted","reason":"InitialNamesAccepted","status":"True","type":"Established"}],"storedVersions":["v1"]}}
  creationTimestamp: "2019-10-31T14:11:28Z"
  generation: 1
  name: networksets.crd.projectcalico.org
  resourceVersion: "1926345484"
  uid: 9dfc6e5b-f861-4d35-ae2e-004cd212686e
spec:
  conversion:
    strategy: None
  group: crd.projectcalico.org
  names:
    kind: NetworkSet
    listKind: NetworkSetList
    plural: networksets
    singular: networkset
  preserveUnknownFields: true
  scope: Namespaced
  versions:
  - name: v1
    served: true
    storage: true
status:
  acceptedNames:
    kind: NetworkSet
    listKind: NetworkSetList
    plural: networksets
    singular: networkset
  conditions:
  - lastTransitionTime: "2019-10-31T14:11:28Z"
    message: no conflicts found
    reason: NoConflicts
    status: "True"
    type: NamesAccepted
  - lastTransitionTime: null
    message: the initial names have been accepted
    reason: InitialNamesAccepted
    status: "True"
    type: Established
  - lastTransitionTime: "2022-06-13T14:07:44Z"
    message: 'spec.preserveUnknownFields: Invalid value: true: must be false'
    reason: Violations
    status: "True"
    type: NonStructuralSchema
  storedVersions:
  - v1

</code>```

Is there any idea how to solve it and what is the root cause of this error?

Body:
I have K8S cluster with rancher and i run rke to add new nodes.

Running RKE version: v1.2.18

Kubernetes Version: v1.20.15

Since few weeks, the rke process failed with this error:

time="2022-12-26T01:56:35-05:00" level=info msg="[network] Setting up network plugin: canal"
time="2022-12-26T01:56:35-05:00" level=info msg="[addons] Saving ConfigMap for addon rke-network-plugin to Kubernetes"
time="2022-12-26T01:56:35-05:00" level=info msg="[addons] Successfully saved ConfigMap for addon rke-network-plugin to Kubernetes"
time="2022-12-26T01:56:35-05:00" level=info msg="[addons] Executing deploy job rke-network-plugin"
time="2022-12-26T01:56:35-05:00" level=debug msg="Checking node list for node [10.11.187.184], try #1"
time="2022-12-26T01:56:35-05:00" level=debug msg="[k8s] replacing job rke-network-plugin-deploy-job.. "
time="2022-12-26T01:56:40-05:00" level=debug msg="[k8s] waiting for job rke-network-plugin-deploy-job to complete.."
time="2022-12-26T01:57:40-05:00" level=fatal msg="Failed to get job complete status for job rke-network-plugin-deploy-job in namespace kube-system"

Logs of rke-network-plugin-deploy-job:

Resource: "apiextensions.k8s.io/v1, Resource=customresourcedefinitions", GroupVersionKind: "apiextensions.k8s.io/v1, Kind=CustomResourceDefinition"
Name: "networksets.crd.projectcalico.org", Namespace: ""
for: "/etc/config/rke-network-plugin.yaml": customresourcedefinitions.apiextensions.k8s.io "networksets.crd.projectcalico.org" is invalid: metadata.resourceVersion: Invalid value: 0x0: must be specified for an update

CRD yaml:

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"apiextensions.k8s.io/v1beta1","kind":"CustomResourceDefinition","metadata":{"annotations":{},"creationTimestamp":"2019-10-31T14:11:28Z","generation":1,"name":"networksets.crd.projectcalico.org","namespace":"","resourceVersion":"197472064","selfLink":"/apis/apiextensions.k8s.io/v1beta1/customresourcedefinitions/networksets.crd.projectcalico.org","uid":"9dfc6e5b-f861-4d35-ae2e-004cd212686e"},"spec":{"conversion":{"strategy":"None"},"group":"crd.projectcalico.org","names":{"kind":"NetworkSet","listKind":"NetworkSetList","plural":"networksets","singular":"networkset"},"preserveUnknownFields":true,"scope":"Namespaced","version":"v1","versions":[{"name":"v1","served":true,"storage":true}]},"status":{"acceptedNames":{"kind":"NetworkSet","listKind":"NetworkSetList","plural":"networksets","singular":"networkset"},"conditions":[{"lastTransitionTime":"2019-10-31T14:11:28Z","message":"no conflicts found","reason":"NoConflicts","status":"True","type":"NamesAccepted"},{"lastTransitionTime":null,"message":"the initial names have been accepted","reason":"InitialNamesAccepted","status":"True","type":"Established"}],"storedVersions":["v1"]}}
  creationTimestamp: "2019-10-31T14:11:28Z"
  generation: 1
  name: networksets.crd.projectcalico.org
  resourceVersion: "1926345484"
  uid: 9dfc6e5b-f861-4d35-ae2e-004cd212686e
spec:
  conversion:
    strategy: None
  group: crd.projectcalico.org
  names:
    kind: NetworkSet
    listKind: NetworkSetList
    plural: networksets
    singular: networkset
  preserveUnknownFields: true
  scope: Namespaced
  versions:
  - name: v1
    served: true
    storage: true
status:
  acceptedNames:
    kind: NetworkSet
    listKind: NetworkSetList
    plural: networksets
    singular: networkset
  conditions:
  - lastTransitionTime: "2019-10-31T14:11:28Z"
    message: no conflicts found
    reason: NoConflicts
    status: "True"
    type: NamesAccepted
  - lastTransitionTime: null
    message: the initial names have been accepted
    reason: InitialNamesAccepted
    status: "True"
    type: Established
  - lastTransitionTime: "2022-06-13T14:07:44Z"
    message: 'spec.preserveUnknownFields: Invalid value: true: must be false'
    reason: Violations
    status: "True"
    type: NonStructuralSchema
  storedVersions:
  - v1

Is there any idea how to solve it and what is the root cause of this error?


问:
Building wolfSSL library in Visual Studio Code for Raspberry Pi Pico
I just downloded wolfSSL library but I dont know how to build it using VSCode. What changes do I have to make in cmake file? Or is it something else? Can someone please guide me.

I tried this instructions for using GCC-ARM:
https://github.com/wolfSSL/wolfssl/tree/master/IDE/GCC-ARM
but it still couldnt compile.

```<code># Toolchain location and prefix
#TOOLCHAIN =
TOOLCHAIN ?=C:/VSARM/armcc/10 2021.10/bin/arm-none-eabi-
</code>```
```<code># Architecture
#ARCHFLAGS ?= -mcpu=cortex-m4 -mthumb -mabi=aapcs -DUSE_WOLF_ARM_STARTUP
ARCHFLAGS = -mcpu=cortex-m0 -mthumb -mabi=aapcs -DUSE_WOLF_ARM_STARTUP
#ARCHFLAGS = -mcpu=cortex-r5 -mthumb -mabi=aapcs
#ARCHFLAGS = -mcpu=cortex-a53 -mthumb -mabi=aapcs
</code>```

p.s. I did my VSCode setup based on shawn haymle's guide for rpi pico.

Body:
I just downloded wolfSSL library but I dont know how to build it using VSCode. What changes do I have to make in cmake file? Or is it something else? Can someone please guide me.

I tried this instructions for using GCC-ARM:
https://github.com/wolfSSL/wolfssl/tree/master/IDE/GCC-ARM
but it still couldnt compile.

# Toolchain location and prefix
#TOOLCHAIN =
TOOLCHAIN ?=C:/VSARM/armcc/10 2021.10/bin/arm-none-eabi-

# Architecture
#ARCHFLAGS ?= -mcpu=cortex-m4 -mthumb -mabi=aapcs -DUSE_WOLF_ARM_STARTUP
ARCHFLAGS = -mcpu=cortex-m0 -mthumb -mabi=aapcs -DUSE_WOLF_ARM_STARTUP
#ARCHFLAGS = -mcpu=cortex-r5 -mthumb -mabi=aapcs
#ARCHFLAGS = -mcpu=cortex-a53 -mthumb -mabi=aapcs

p.s. I did my VSCode setup based on shawn haymle's guide for rpi pico.


问:
How to create route using osm.pbf by road between coordinates in R or Python?
I have *.osm.pbf file but I don't know if it's possible to work with it in R or Python for creating route visualization between two lat-lon points. As an answer, I need to get a map image with a route between them. If the map can be interactive and moveable, that would be great, but a static image will do.

It's important that it's offline. Although yes, it would be easier to use data from google or online osm, but I can't do that.


问:
How do we prevent the .onTapGesture on other views from firing when SwiftUI menu is visible on the screen?
Here is my code:

```<code>/* triggers a full screen view on parent to be able to trap clicks anywhere on the screen and prevent other views .ontap from firing.

This works when the use taps outside, when the user makes a change but does not work when the user selects the already selected menu item. In that case the menu does disappear but I can't toggle the parent's trapping view because .disappear for the menu or the picker doesn't actually fire.
*/
@Binding var menuShowing: Bool

....

Menu {
      Picker("Topic", selection: $selectedTopic) {
        Text("Unassigned")
        .tag(nil as Topic?)

        Divider()

        ForEach(topics, id:\.id) { topic in
            Text(topic.name!)
            .tag(topic as Topic?)
         }
      }
      .onDisappear{
          print("Picker Disappeared") // THIS DOES NOT FIRE IF THE USER SELECTS THE ALREADY SELECTED ITEM
      }
     }
 label: {
         Image(systemName: "circle.grid.3x3.circle")
         .font(.system(size: 26,weight: .ultraLight))
         .foregroundColor(learningSet.topic?.foregroundColor ?? .primary)
         .frame(width:30, height: 30)
        }
        .contentShape(Rectangle())
        .onDisappear{ // THIS DOES NOT FIRE IF THE USER SELECTS THE ALREADY SELECTED ITEM
            print("Menu Disappeared")
        }
        .onTapGesture {
             vm.haptic()
             menuShowing.toggle()
         }

        .onChange(of: selectedTopic, perform: { _ in
            menuShowing = false
            DispatchQueue.main.async {
                if learningSet.topic != selectedTopic{

                    learningSet.lastModifiedOn = .now
                    learningSet.topic?.lastModifiedOn = .now

                    learningSet.topic = selectedTopic
                    if selectedTopic == nil{
                        vm.unassignedExpanded = true
                    } else{
                        selectedTopic?.lastModifiedOn = .now
                        selectedTopic?.expanded = true
                    }
                    _ = vm.save("Changed Topic for set \(learningSet.name ?? "..") to \(String(describing: selectedTopic?.name))")
                    withAnimation(.easeInOut(duration: 0.15)){
                        forceRefresh.toggle()
                    }
                }
            }
        })
</code>```

This correctly shows the menu and if I select an item, the .onchange fires like it should.

Problem is if the user clicks on some other view on the screen while the is active, it fires that views .onTappedGesture.

I tried different combinations of highPriorityGesture and SimultaneousGesture to no avail.

I also tried the approach of adding a full screen view In between the view with the menu and the underlying views and added an onTap to it. That approach works fine with one issue: If the user click on the currency selected item, the .onChange for the picker doesn't fire, the menu disappears but its .onDisappear doesn't fire. So there is no way to know the menu is no longer visible, and hide my full screen view.

Any help would be greatly appreciated.
Thanks.

Body:
Here is my code:

/* triggers a full screen view on parent to be able to trap clicks anywhere on the screen and prevent other views .ontap from firing.

This works when the use taps outside, when the user makes a change but does not work when the user selects the already selected menu item. In that case the menu does disappear but I can't toggle the parent's trapping view because .disappear for the menu or the picker doesn't actually fire.
*/
@Binding var menuShowing: Bool

....

Menu {
      Picker("Topic", selection: $selectedTopic) {
        Text("Unassigned")
        .tag(nil as Topic?)

        Divider()

        ForEach(topics, id:\.id) { topic in
            Text(topic.name!)
            .tag(topic as Topic?)
         }
      }
      .onDisappear{
          print("Picker Disappeared") // THIS DOES NOT FIRE IF THE USER SELECTS THE ALREADY SELECTED ITEM
      }
     }
 label: {
         Image(systemName: "circle.grid.3x3.circle")
         .font(.system(size: 26,weight: .ultraLight))
         .foregroundColor(learningSet.topic?.foregroundColor ?? .primary)
         .frame(width:30, height: 30)
        }
        .contentShape(Rectangle())
        .onDisappear{ // THIS DOES NOT FIRE IF THE USER SELECTS THE ALREADY SELECTED ITEM
            print("Menu Disappeared")
        }
        .onTapGesture {
             vm.haptic()
             menuShowing.toggle()
         }

        .onChange(of: selectedTopic, perform: { _ in
            menuShowing = false
            DispatchQueue.main.async {
                if learningSet.topic != selectedTopic{

                    learningSet.lastModifiedOn = .now
                    learningSet.topic?.lastModifiedOn = .now

                    learningSet.topic = selectedTopic
                    if selectedTopic == nil{
                        vm.unassignedExpanded = true
                    } else{
                        selectedTopic?.lastModifiedOn = .now
                        selectedTopic?.expanded = true
                    }
                    _ = vm.save("Changed Topic for set \(learningSet.name ?? "..") to \(String(describing: selectedTopic?.name))")
                    withAnimation(.easeInOut(duration: 0.15)){
                        forceRefresh.toggle()
                    }
                }
            }
        })

This correctly shows the menu and if I select an item, the .onchange fires like it should.

Problem is if the user clicks on some other view on the screen while the is active, it fires that views .onTappedGesture.

I tried different combinations of highPriorityGesture and SimultaneousGesture to no avail.

I also tried the approach of adding a full screen view In between the view with the menu and the underlying views and added an onTap to it. That approach works fine with one issue: If the user click on the currency selected item, the .onChange for the picker doesn't fire, the menu disappears but its .onDisappear doesn't fire. So there is no way to know the menu is no longer visible, and hide my full screen view.

Any help would be greatly appreciated.
Thanks.


问:
can we have user defined schema for cloud logging GCP and push data to logging bucket
What i am trying to achieve is, currently my apigee logs are stored in log explorer (GCP). I want this logs to be sent to big query -> data studio, which i am doing it with the help of below flow. That works well.

Log explorer -> Pub/sub -> Cloud function -> Big Query -> Data studio.

But i am looking for alternate solution, which is described below.

Log explorer provides an interface for big query directly.
https://cloud.google.com/logging/docs/buckets (Option 4b.)

But when i try to do that, it adds its own field and my entire json is treated as single entry. So in order to get rid of it, what i am thinking is if i can have user defined custom schema in log explorer and that i can enter as input to, big query interface. So the flow is

Log explorer -> Custom schema in log explorer -> Big Query interface -> Data Studio.

Over here big query is just an interface and i am using data from log explorer so i save the storage cost of big query. That is the reason for choosing this approach.

Currently i am trying to find a way of i can create a custom schema in log explorer from my existing entries. But not able to find any way for it. Let me know if that is even possible or not as i am new to GCP log explorer.

Help is appreciated. Thank you.


问:
Joining two mongoose collections with many to many relationship
I have two models which are Product & Category with many to many relationship.

Following are my models

This is the model for Product

```<code>//Product.js
const mongoose = require("mongoose");
const { Schema } = mongoose;
const { ObjectId } = Schema;
const product = {
  name: {
    type: String,
    required: true,
    trim: true,
    minlength: [2, "Too short"],
    maxlength: [32, "Too long"],
    unique: true,
  },
  slug: {
    type: String,
    unique: true,
    lowercase: true,
    index: true,
  },
  category: [
    {
      type: ObjectId,
      ref: "Category",
    },
  ],
  description: {
    type: String,
    maxlength: 200,
  },
  price: {
    type: Number,
    required: true,
    trim: true,
    maxlength: 32,
  },
  shipping: {
    type: String,
    enum: ["Yes", "No"],
  },
  color: [
    {
      type: String,
      enum: ["Black", "Brown", "Silver", "White", "Blue"],
    },
  ],
  sold: {
    type: Number,
    default: 0,
  },
  quantity: {
    type: Number,
  },
  images: [
    {
      public_id: String,
      url: String,
    },
  ],
};
const productSchema = new Schema(product, { timestamps: true });
const Product = mongoose.model("Product", productSchema);
module.exports = Product;
</code>```

This is the model for Category

```<code>//Category.js
const mongoose = require("mongoose");
const { Schema } = mongoose;
const { ObjectId } = Schema;
const category = {
  name: {
    type: String,
    required: true,
    trim: true,
    max: 32,
    unique: true,
  },
  subCategories: [
    {
      type: Schema.Types.ObjectId,
      ref: "Category",
    },
  ],
  parent: {
    type: Schema.Types.ObjectId,
    ref: "Category",
  },
  products: [
    {
      type: ObjectId,
      ref: "Product",
    },
  ],
  slug: {
    type: String,
    required: "URL can't be empty",
    unique: true,
  },
};
const categorySchema = new Schema(category, { timestamps: true });
//Validate the slug to ensure proper url is given
// categorySchema.path("slug").validate((val) => {
//   urlRegex =
//     /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/;
//   return urlRegex.test(val);
// }, "Invalid URL.");
const autoPopulateChildren = function (next) {
  this.populate("subCategories");
  // this.populate("parent");
  next();
};
categorySchema
  .pre("findOne", autoPopulateChildren)
  .pre("findById", autoPopulateChildren)
  .pre("find", autoPopulateChildren);
const Category = mongoose.model("Category", categorySchema);
module.exports = Category;
</code>```

So, product has a foreign keys of category in array of category. Whereas Category has foreign keys of product in array of products. How do you join them ?

I tried this & it doesn't work. It returns empty object

```<code>router.get("/products", [RequireSignIn], async (req, res) => {
  try {
    const products = await Product.find({}).aggregate({
      $lookup: {
        from: "Category",
        localField: "category",
        foreignField: "_id",
        as: "ProductCategories",
      },
    });
    return res.status(200).send(products);

  } catch (error) {
    return res.status(200).send(error);
  }
});
</code>```

Body:
I have two models which are Product & Category with many to many relationship.

Following are my models

This is the model for Product

//Product.js
const mongoose = require("mongoose");
const { Schema } = mongoose;
const { ObjectId } = Schema;
const product = {
  name: {
    type: String,
    required: true,
    trim: true,
    minlength: [2, "Too short"],
    maxlength: [32, "Too long"],
    unique: true,
  },
  slug: {
    type: String,
    unique: true,
    lowercase: true,
    index: true,
  },
  category: [
    {
      type: ObjectId,
      ref: "Category",
    },
  ],
  description: {
    type: String,
    maxlength: 200,
  },
  price: {
    type: Number,
    required: true,
    trim: true,
    maxlength: 32,
  },
  shipping: {
    type: String,
    enum: ["Yes", "No"],
  },
  color: [
    {
      type: String,
      enum: ["Black", "Brown", "Silver", "White", "Blue"],
    },
  ],
  sold: {
    type: Number,
    default: 0,
  },
  quantity: {
    type: Number,
  },
  images: [
    {
      public_id: String,
      url: String,
    },
  ],
};
const productSchema = new Schema(product, { timestamps: true });
const Product = mongoose.model("Product", productSchema);
module.exports = Product;

This is the model for Category

//Category.js
const mongoose = require("mongoose");
const { Schema } = mongoose;
const { ObjectId } = Schema;
const category = {
  name: {
    type: String,
    required: true,
    trim: true,
    max: 32,
    unique: true,
  },
  subCategories: [
    {
      type: Schema.Types.ObjectId,
      ref: "Category",
    },
  ],
  parent: {
    type: Schema.Types.ObjectId,
    ref: "Category",
  },
  products: [
    {
      type: ObjectId,
      ref: "Product",
    },
  ],
  slug: {
    type: String,
    required: "URL can't be empty",
    unique: true,
  },
};
const categorySchema = new Schema(category, { timestamps: true });
//Validate the slug to ensure proper url is given
// categorySchema.path("slug").validate((val) => {
//   urlRegex =
//     /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-/]))?/;
//   return urlRegex.test(val);
// }, "Invalid URL.");
const autoPopulateChildren = function (next) {
  this.populate("subCategories");
  // this.populate("parent");
  next();
};
categorySchema
  .pre("findOne", autoPopulateChildren)
  .pre("findById", autoPopulateChildren)
  .pre("find", autoPopulateChildren);
const Category = mongoose.model("Category", categorySchema);
module.exports = Category;

So, product has a foreign keys of category in array of category. Whereas Category has foreign keys of product in array of products. How do you join them ?

I tried this & it doesn't work. It returns empty object

router.get("/products", [RequireSignIn], async (req, res) => {
  try {
    const products = await Product.find({}).aggregate({
      $lookup: {
        from: "Category",
        localField: "category",
        foreignField: "_id",
        as: "ProductCategories",
      },
    });
    return res.status(200).send(products);

  } catch (error) {
    return res.status(200).send(error);
  }
});


问:
c# Upload File to SharePoint Document Library
My requirement is the following:

I have various bits of network hardware, from which we regularly export configurations (this is done using another c#/.NET app I created, this works really well - the tool logs in via SSH to the various devices and downloads the latest configuration to the local hard disk of the server from which the app runs).

We have various SharePoint online sites (provided via our M365 subscription).

I want to have these configs uploaded to a particular folder, in a particular document library, in a particular SharePoint Online site, basically so that there is an off-site backup of the config files.

I was following the steps in this blog: https://daoudisamir.com/from-c-to-sharepoint-file-upload-using-csom-with-subfolders-structure/.

It looked like it did what I wanted... but when I try to build the code, it tells me that I'm missing references to assemblies etc. I know that this means that I'm missing "using" directives, but I've tried all sorts of variations to reference the various NUGET packages that are instructed to be installed, but I can't get this to work and couldn't see anywhere on the blog itself to email the owner.

Anyone got any ideas... at the moment, my code is more or less a copy/paste of what's on the blog page, but I've included my code here for convenience:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Security;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;

namespace UploadToSharePoint_Net48
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string SiteUrl = "https://You.sharepoint.com/sites/Upload";
            string DocumentLibrary = "UploadLibrary";
            string FileName = @"C:\testupload.pdf";
            string CustomerFolder = "1564_dsfgsst";
            string UserName = "samir.daoudi@******.co.uk";
            string Password = "*****";
            UploadFileToSharePoint(SiteUrl, DocumentLibrary, CustomerFolder, FileName, UserName, Password);
        }

        private static void UploadFileToSharePoint(string SiteUrl, string DocLibrary, string ClientSubFolder, string FileName, string Login, string Password)
        {
            try
            {
                #region ConnectToSharePoint

                var securePassword = new SecureString();
                foreach (char c in Password)
                { securePassword.AppendChar(c); }
                var onlineCredentials = new SP.SharePointOnlineCredentials(Login, securePassword);
                #endregion

                #region Insert the data
                using (SP.ClientContext CContext = new SP.ClientContext(SiteUrl))
                {
                    CContext.Credentials = onlineCredentials;
                    SP.Web web = CContext.Web;
                    SP.FileCreationInformation newFile = new SP.FileCreationInformation();
                    byte[] FileContent = System.IO.File.ReadAllBytes(FileName);
                    newFile.ContentStream = new MemoryStream(FileContent);
                    newFile.Url = Path.GetFileName(FileName);
                    SP.List DocumentLibrary = web.Lists.GetByTitle(DocLibrary);
                    //SP.Folder folder = DocumentLibrary.RootFolder.Folders.GetByUrl(ClientSubFolder);
                    SP.Folder Clientfolder = DocumentLibrary.RootFolder.Folders.Add(ClientSubFolder);
                    Clientfolder.Update();
                    SP.File uploadFile = Clientfolder.Files.Add(newFile);

                    CContext.Load(DocumentLibrary);
                    CContext.Load(uploadFile);
                    CContext.ExecuteQuery();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("The File has been uploaded" + Environment.NewLine + "FileUrl -->" + SiteUrl + "/" + DocLibrary + "/" + ClientSubFolder + "/" + Path.GetFileName(FileName));
                }

                #endregion
            }
            catch (Exception exp)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(exp.Message + Environment.NewLine + exp.StackTrace);
            }
            finally
            {
                Console.ReadLine();
            }
        }
    }
}

</code>```

The errors are with all the references to SP.xxxxx

I can see that there is no definition for anything called "SP", but I'm assuming at this stage that this is in one of the external libraries or whatever is in the NUGETS that are required.

Any help gratefully received.

Thanks

Colin

Body:
My requirement is the following:

I have various bits of network hardware, from which we regularly export configurations (this is done using another c#/.NET app I created, this works really well - the tool logs in via SSH to the various devices and downloads the latest configuration to the local hard disk of the server from which the app runs).

We have various SharePoint online sites (provided via our M365 subscription).

I want to have these configs uploaded to a particular folder, in a particular document library, in a particular SharePoint Online site, basically so that there is an off-site backup of the config files.

I was following the steps in this blog: https://daoudisamir.com/from-c-to-sharepoint-file-upload-using-csom-with-subfolders-structure/.

It looked like it did what I wanted... but when I try to build the code, it tells me that I'm missing references to assemblies etc. I know that this means that I'm missing "using" directives, but I've tried all sorts of variations to reference the various NUGET packages that are instructed to be installed, but I can't get this to work and couldn't see anywhere on the blog itself to email the owner.

Anyone got any ideas... at the moment, my code is more or less a copy/paste of what's on the blog page, but I've included my code here for convenience:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Security;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;

namespace UploadToSharePoint_Net48
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string SiteUrl = "https://You.sharepoint.com/sites/Upload";
            string DocumentLibrary = "UploadLibrary";
            string FileName = @"C:\testupload.pdf";
            string CustomerFolder = "1564_dsfgsst";
            string UserName = "samir.daoudi@******.co.uk";
            string Password = "*****";
            UploadFileToSharePoint(SiteUrl, DocumentLibrary, CustomerFolder, FileName, UserName, Password);
        }

        private static void UploadFileToSharePoint(string SiteUrl, string DocLibrary, string ClientSubFolder, string FileName, string Login, string Password)
        {
            try
            {
                #region ConnectToSharePoint

                var securePassword = new SecureString();
                foreach (char c in Password)
                { securePassword.AppendChar(c); }
                var onlineCredentials = new SP.SharePointOnlineCredentials(Login, securePassword);
                #endregion

                #region Insert the data
                using (SP.ClientContext CContext = new SP.ClientContext(SiteUrl))
                {
                    CContext.Credentials = onlineCredentials;
                    SP.Web web = CContext.Web;
                    SP.FileCreationInformation newFile = new SP.FileCreationInformation();
                    byte[] FileContent = System.IO.File.ReadAllBytes(FileName);
                    newFile.ContentStream = new MemoryStream(FileContent);
                    newFile.Url = Path.GetFileName(FileName);
                    SP.List DocumentLibrary = web.Lists.GetByTitle(DocLibrary);
                    //SP.Folder folder = DocumentLibrary.RootFolder.Folders.GetByUrl(ClientSubFolder);
                    SP.Folder Clientfolder = DocumentLibrary.RootFolder.Folders.Add(ClientSubFolder);
                    Clientfolder.Update();
                    SP.File uploadFile = Clientfolder.Files.Add(newFile);

                    CContext.Load(DocumentLibrary);
                    CContext.Load(uploadFile);
                    CContext.ExecuteQuery();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("The File has been uploaded" + Environment.NewLine + "FileUrl -->" + SiteUrl + "/" + DocLibrary + "/" + ClientSubFolder + "/" + Path.GetFileName(FileName));
                }

                #endregion
            }
            catch (Exception exp)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(exp.Message + Environment.NewLine + exp.StackTrace);
            }
            finally
            {
                Console.ReadLine();
            }
        }
    }
}

The errors are with all the references to SP.xxxxx

I can see that there is no definition for anything called "SP", but I'm assuming at this stage that this is in one of the external libraries or whatever is in the NUGETS that are required.

Any help gratefully received.

Thanks

Colin


问:
Django Docker ElasticBeanstalk fails
I'm new to docker and eb deployment, I want to deploy django with docker on eb

here's what I did so far
created a Dockerfile

```<code># Pull base image
FROM python:3.9.16-slim-buster

# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

RUN apt-get update &&\
    apt-get install -y binutils libproj-dev gdal-bin python-gdal python3-gdal libpq-dev python-dev libcurl4-openssl-dev libssl-dev gcc

# install dependencies
COPY . /code
WORKDIR /code/
RUN pip install -r requirements.txt
# set work directory
WORKDIR /code/app
</code>```

then in docker-compose.yml

```<code>version: '3.7'

services:
    web:
      build: .
      command: python /code/hike/manage.py runserver 0.0.0.0:8000
      ports:
          - 8000:8000
      volumes:
          - .:/code

</code>```

it runs locally, but on deployment it fails and when I get to logs, it says
pg_config is required to build psycopg2 from source.
like it's not using the Dockerfile, I read somewhere I should set Dockerrunder.aws.json but I've no idea what to write in it!

Title: Django Docker ElasticBeanstalk fails

Body:
I'm new to docker and eb deployment, I want to deploy django with docker on eb

here's what I did so far
created a Dockerfile

# Pull base image
FROM python:3.9.16-slim-buster

# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

RUN apt-get update &&\
    apt-get install -y binutils libproj-dev gdal-bin python-gdal python3-gdal libpq-dev python-dev libcurl4-openssl-dev libssl-dev gcc

# install dependencies
COPY . /code
WORKDIR /code/
RUN pip install -r requirements.txt
# set work directory
WORKDIR /code/app

then in docker-compose.yml

version: '3.7'

services:
    web:
      build: .
      command: python /code/hike/manage.py runserver 0.0.0.0:8000
      ports:
          - 8000:8000
      volumes:
          - .:/code

it runs locally, but on deployment it fails and when I get to logs, it says
pg_config is required to build psycopg2 from source.
like it's not using the Dockerfile, I read somewhere I should set Dockerrunder.aws.json but I've no idea what to write in it!


问:
PyCharm terminal freezes when using some modules
PyCharm terminal freezes (or loops) when executing the file and the computer starts to warm up.

Code that doesn't run:

```<code>import time
import requests

start_time = time.time()
print(start_time)
</code>```

Code that works:

```<code>Code that doesn't run:

import time
# import requests

start_time = time.time()
print(start_time)
</code>```

The problem occurs when some libraries are present, for example requests, pycoingecko, pymongo. I assume that these are the libraries that access the Internet.
The problem occurred unexpectedly, the settings in the program did not change.
Everything worked before.
System: Ubuntu.

Body:
PyCharm terminal freezes (or loops) when executing the file and the computer starts to warm up.

Code that doesn't run:

import time
import requests

start_time = time.time()
print(start_time)

Code that works:

Code that doesn't run:

import time
# import requests

start_time = time.time()
print(start_time)

The problem occurs when some libraries are present, for example requests, pycoingecko, pymongo. I assume that these are the libraries that access the Internet.
The problem occurred unexpectedly, the settings in the program did not change.
Everything worked before.
System: Ubuntu.


问:
OpenCV not detecting unknown faces
I recently made a project with opencv, that marks the attendance of a person with facial recognition, but it is not able to detect if a face is unknown or known. It just gives a name for every face. Can anyone help me?

```<code>cap = cv2.VideoCapture(0)
# reading every frame
while True:
    success, img = cap.read()
    # resizing the image to 0.25 of original
    imgS = cv2.resize(img, (0, 0), None, 0.25, 0.25)
    imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)
    # find location of all the faces from our webcam feed [0] is not there so that
    # even if there are more than one faces in the feed
    facesCurrFrame = face_recognition.face_locations(imgS)
    # find encodings of the resized image sending in the small images and The location of
    # all the faces in current frame
    encodesCurrFrame = face_recognition.face_encodings(imgS, facesCurrFrame)
    # one by one it grabs faces from facesCurrFrame list and Encodings From encodesCurrFrame list
    for enc, faceLoc in zip(encodesCurrFrame, facesCurrFrame):
        matches = face_recognition.compare_faces(encodeListKnown, enc)
        # this will return a list which will contain the distance or dis-similarities the image from camera
        # have and the images provided in the training data
        # the lowest value will have our match
        faceDis = face_recognition.face_distance(encodeListKnown, enc)
        # print(faceDis)
        matchIndex = np.argmin(faceDis)
        if matches[matchIndex]:
            name = classNames[matchIndex].upper()
           #print(name)
            y1, x2, y2, x1 = faceLoc
            y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
            cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
            cv2.rectangle(img, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
            cv2.putText(img, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
            markAttendance(name)

</code>```

Above code that captures the webcam footage and extracts the faces and performs the recognition.

I tried the program with some unknown faces but it is still giving me some name for that person.

Title: OpenCV not detecting unknown faces

Body:
I recently made a project with opencv, that marks the attendance of a person with facial recognition, but it is not able to detect if a face is unknown or known. It just gives a name for every face. Can anyone help me?

cap = cv2.VideoCapture(0)
# reading every frame
while True:
    success, img = cap.read()
    # resizing the image to 0.25 of original
    imgS = cv2.resize(img, (0, 0), None, 0.25, 0.25)
    imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)
    # find location of all the faces from our webcam feed [0] is not there so that
    # even if there are more than one faces in the feed
    facesCurrFrame = face_recognition.face_locations(imgS)
    # find encodings of the resized image sending in the small images and The location of
    # all the faces in current frame
    encodesCurrFrame = face_recognition.face_encodings(imgS, facesCurrFrame)
    # one by one it grabs faces from facesCurrFrame list and Encodings From encodesCurrFrame list
    for enc, faceLoc in zip(encodesCurrFrame, facesCurrFrame):
        matches = face_recognition.compare_faces(encodeListKnown, enc)
        # this will return a list which will contain the distance or dis-similarities the image from camera
        # have and the images provided in the training data
        # the lowest value will have our match
        faceDis = face_recognition.face_distance(encodeListKnown, enc)
        # print(faceDis)
        matchIndex = np.argmin(faceDis)
        if matches[matchIndex]:
            name = classNames[matchIndex].upper()
           #print(name)
            y1, x2, y2, x1 = faceLoc
            y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
            cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
            cv2.rectangle(img, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
            cv2.putText(img, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
            markAttendance(name)

Above code that captures the webcam footage and extracts the faces and performs the recognition.

I tried the program with some unknown faces but it is still giving me some name for that person.


问:
advantage of extern-int to int in .h for c language, considering the compiler(gcc)
before, whey I study C, I know it is recommended to use variable declaration in hearder(.h):

```<code>extern int a;
</code>```

nowadays, I study a few of compiler, I know "int a" is weak-type, and "int a = 0;" is strong type, and weak-type could be used for multiple times, my code bellow works well, though "int num" is called multiple times:

```<code>// ==== sub.h ====
int num; // not use "extern int num;"
void change();
</code>```
```<code>// ==== sub.c ====
#include "sub.h"

int num = 1;

void change()
{
    num = 10;
}
</code>```
```<code>// ==== main.c ====
#include <stdio.h>
#include "sub.h"

int main()
{
    printf("before-change: %d\n", num);
    change();
    printf(" after-change: %d\n", num);
}
</code>```

and I run gcc compiler command:

```<code>gcc main.c sub.c -o app.exe
</code>```

the result is

```<code>before-change: 1
 after-change: 10
</code>```

my question is that: what is the advantage of "extern int a;" to "int a;" in c-header. (only in c language, I researched this is an issue in c++)

Body:
before, whey I study C, I know it is recommended to use variable declaration in hearder(.h):

extern int a;

nowadays, I study a few of compiler, I know "int a" is weak-type, and "int a = 0;" is strong type, and weak-type could be used for multiple times, my code bellow works well, though "int num" is called multiple times:

// ==== sub.h ====
int num; // not use "extern int num;"
void change();

// ==== sub.c ====
#include "sub.h"

int num = 1;

void change()
{
    num = 10;
}

// ==== main.c ====
#include <stdio.h>
#include "sub.h"

int main()
{
    printf("before-change: %d\n", num);
    change();
    printf(" after-change: %d\n", num);
}

and I run gcc compiler command:

gcc main.c sub.c -o app.exe

the result is

before-change: 1
 after-change: 10

my question is that: what is the advantage of "extern int a;" to "int a;" in c-header. (only in c language, I researched this is an issue in c++)


问:
Ngx Videogular IONIC 6 Video player issue, Video freezes sound continues playing
I have been plagued by a nasty issue using NGX videogular + Ionic 6 (Angular) on my Android app for more than 2 months now.

In the APP on the device, something really weird happens.

The video plays properly for a few seconds.

After sometime, the video frame freezes completely. The video playing may/not resume. All this while, the audio is playing smoothly. I, initially, was under the impression that the Video was buffering hence the frozen frames. But that cant be so since the audio is streaming smoothly.
BY THE WAY, THIS HAPPENS ON A GIGABIT WIFI CONNECTION AS WELL AS 4G NETWORK

However, when the video is playing, if you scroll the page, the video frames play as long as the scroll continues. The moment that we stop the scroll, the video freezes again. All this while, the audio is playing smoothly.

Click here to view the video

We reviewed the installed plugins

```<code>es6-promise-plugin
cordova-plugin-music-controls2
cordova-plugin-file-transfer
cordova-plugin-device
cordova-plugin-media
cordova-plugin-background-mode
cordova-plugin-ionic-webview
cordova-plugin-x-socialsharing
cordova-plugin-ionic-keyboard
cordova-plugin-appminimize
cordova-plugin-whitelist
cordova-plugin-statusbar
cordova-plugin-inappbrowser
cordova-plugin-androidx-adapter
cordova-plugin-androidx
cordova-plugin-splashscreen
cordova-plugin-firebasex
cordova-plugin-advanced-http
ionic-plugin-deeplinks
cordova-plugin-screen-orientation
cordova-plugin-filepath
cordova-clipboard
cordova-plugin-app-version
cordova-plugin-network-information
cordova-plugin-file
</code>```

Cordova Info output

```<code>Cordova Packages:

    cli: 10.0.0
        common: 4.0.2
        create: 3.0.0
        lib: 10.0.0
            common: 4.0.2
            fetch: 3.0.1
            serve: 4.0.0

Project Installed Platforms:

    android: 11.0.0

Project Installed Plugins:

    com.razorpay.cordova: 0.16.1
    cordova-clipboard: 1.3.0
    cordova-plugin-advanced-http: 3.3.1
    cordova-plugin-androidx-adapter: 1.1.3
    cordova-plugin-androidx: 3.0.0
    cordova-plugin-app-version: 0.1.14
    cordova-plugin-appminimize: 1.0.1
    cordova-plugin-background-mode: 0.7.3
    cordova-plugin-device: 2.0.2
    cordova-plugin-file-transfer: 1.7.1
    cordova-plugin-file: 6.0.2
    cordova-plugin-filepath: 1.6.0
    cordova-plugin-firebasex: 16.0.0
    cordova-plugin-inappbrowser: 5.0.0
    cordova-plugin-ionic-keyboard: 2.2.0
    cordova-plugin-ionic-webview: 5.0.0
    cordova-plugin-media: 5.0.4
    cordova-plugin-music-controls2: 3.0.7
    cordova-plugin-network-information: 3.0.0
    cordova-plugin-screen-orientation: 3.0.2
    cordova-plugin-splashscreen: 5.0.2
    cordova-plugin-statusbar: 2.4.2
    cordova-plugin-whitelist: 1.3.5
    cordova-plugin-x-socialsharing: 6.0.4
    es6-promise-plugin: 4.2.2
    ionic-plugin-deeplinks: 1.0.22

Environment:

    OS: Ubuntu 22.04.1 LTS (linux 5.15.0-56-generic) x64
    Node: v16.15.1
    npm: 8.11.0

</code>```

Click here to view the video

Body:
I have been plagued by a nasty issue using NGX videogular + Ionic 6 (Angular) on my Android app for more than 2 months now.

In the APP on the device, something really weird happens.

The video plays properly for a few seconds.

After sometime, the video frame freezes completely. The video playing may/not resume. All this while, the audio is playing smoothly. I, initially, was under the impression that the Video was buffering hence the frozen frames. But that cant be so since the audio is streaming smoothly.
BY THE WAY, THIS HAPPENS ON A GIGABIT WIFI CONNECTION AS WELL AS 4G NETWORK

However, when the video is playing, if you scroll the page, the video frames play as long as the scroll continues. The moment that we stop the scroll, the video freezes again. All this while, the audio is playing smoothly.

Click here to view the video

We reviewed the installed plugins

es6-promise-plugin
cordova-plugin-music-controls2
cordova-plugin-file-transfer
cordova-plugin-device
cordova-plugin-media
cordova-plugin-background-mode
cordova-plugin-ionic-webview
cordova-plugin-x-socialsharing
cordova-plugin-ionic-keyboard
cordova-plugin-appminimize
cordova-plugin-whitelist
cordova-plugin-statusbar
cordova-plugin-inappbrowser
cordova-plugin-androidx-adapter
cordova-plugin-androidx
cordova-plugin-splashscreen
cordova-plugin-firebasex
cordova-plugin-advanced-http
ionic-plugin-deeplinks
cordova-plugin-screen-orientation
cordova-plugin-filepath
cordova-clipboard
cordova-plugin-app-version
cordova-plugin-network-information
cordova-plugin-file

Cordova Info output

Cordova Packages:

    cli: 10.0.0
        common: 4.0.2
        create: 3.0.0
        lib: 10.0.0
            common: 4.0.2
            fetch: 3.0.1
            serve: 4.0.0

Project Installed Platforms:

    android: 11.0.0

Project Installed Plugins:

    com.razorpay.cordova: 0.16.1
    cordova-clipboard: 1.3.0
    cordova-plugin-advanced-http: 3.3.1
    cordova-plugin-androidx-adapter: 1.1.3
    cordova-plugin-androidx: 3.0.0
    cordova-plugin-app-version: 0.1.14
    cordova-plugin-appminimize: 1.0.1
    cordova-plugin-background-mode: 0.7.3
    cordova-plugin-device: 2.0.2
    cordova-plugin-file-transfer: 1.7.1
    cordova-plugin-file: 6.0.2
    cordova-plugin-filepath: 1.6.0
    cordova-plugin-firebasex: 16.0.0
    cordova-plugin-inappbrowser: 5.0.0
    cordova-plugin-ionic-keyboard: 2.2.0
    cordova-plugin-ionic-webview: 5.0.0
    cordova-plugin-media: 5.0.4
    cordova-plugin-music-controls2: 3.0.7
    cordova-plugin-network-information: 3.0.0
    cordova-plugin-screen-orientation: 3.0.2
    cordova-plugin-splashscreen: 5.0.2
    cordova-plugin-statusbar: 2.4.2
    cordova-plugin-whitelist: 1.3.5
    cordova-plugin-x-socialsharing: 6.0.4
    es6-promise-plugin: 4.2.2
    ionic-plugin-deeplinks: 1.0.22

Environment:

    OS: Ubuntu 22.04.1 LTS (linux 5.15.0-56-generic) x64
    Node: v16.15.1
    npm: 8.11.0

Click here to view the video


问:
How to load Laravel projects Directly after clicking links created in index.html using .htaccess?
I am trying to create a website that contains other laravel projects(different versions) using .htaccess

index.html

```<code><body>
    <ul>
      <li>
        <a href="Projects/Project1/">Project1</a>
      </li>
      <li>
        <a href="Projects/Project2/">Project2</a>
      </li>
      <li>
        <a href="Projects/Project3/">Project3</a>
      </li>
    </ul>
  </body>

</code>```

project1's .env for redirecting to project1

```<code>APP_URL=http://127.0.0.1:8000/AllProjects/Projects/Project1/
</code>```

I have also created .htacess file in every project and the code it contain

```<code><IfModule mod_rewrite.c>
    Options -MultiViews
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ /public/index.php [L]
</IfModule>
</code>```

Now the problem is I cannot see the website I see the directories, and I am doing this for the first time so I have no clue how to do it. Any help would be really appreciated, Thanks

Body:
I am trying to create a website that contains other laravel projects(different versions) using .htaccess

index.html

        Project1

        Project2

        Project3

project1's .env for redirecting to project1

APP_URL=http://127.0.0.1:8000/AllProjects/Projects/Project1/

I have also created .htacess file in every project and the code it contain

<IfModule mod_rewrite.c>
    Options -MultiViews
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ /public/index.php [L]
</IfModule>

Now the problem is I cannot see the website I see the directories, and I am doing this for the first time so I have no clue how to do it. Any help would be really appreciated, Thanks


问:
read row data on button click using python flask
I want to read the patientid in  when the corresponding row button in  is clicked. Using the code i could able to get the patientid of 1st row of the table. I wanted to get the corresponding row's patientid</p>
```<code><table id="mytable" class="styled-table">
    <thead>
    <tr>
        <th>Patientid</th>
        <th>Name</th>
        <th>Path</th>
        <th>Category</th>
        <th>Action</th>
    </tr>
    </thead>
    <tbody>
        {% for row in value %}
            <tr>
                <td><input type="hidden" name="patientid" value="{{row[0]}}"> {{ row[0] }}</td>
                <td>{{row[1]}}</td>
                <td>{{row[2]}}</td>
                <td>{{row[3]}}</td>

                <td><form action="/get" method="POST"><input type="submit" class="button" value="Generate" name="generate"></a> </td>

            </tr>
        {% endfor %}
    </tbody>
</table>
</code>```
```<code>if request.form.get('generate') == 'Generate':
        print('selected')
        print(request.form.get("patientid"))
        a=request.form.get("patientid")
        return render_template('automated.html')
</code>```

Body:
I want to read the patientid in  when the corresponding row button in  is clicked. Using the code i could able to get the patientid of 1st row of the table. I wanted to get the corresponding row's patientid

        Patientid
        Name
        Path
        Category
        Action

        {% for row in value %}

                <input type="hidden" name="patientid" value="{{row[0]}}"> {{ row[0] }}
                {{row[1]}}
                {{row[2]}}
                {{row[3]}}

                <form action="/get" method="POST"><input type="submit" class="button" value="Generate" name="generate">

        {% endfor %}

if request.form.get('generate') == 'Generate':
        print('selected')
        print(request.form.get("patientid"))
        a=request.form.get("patientid")
        return render_template('automated.html')


问:
Contents are not showing on bottom Full screen bottom sheet dialog
I used a bottom sheet dialog in my application I wanted it to be full screen but its contents are not showing on full screen I want those two button at the bottom of the screen</p>
```<code>private fun setupDestinationStationDialog() {
    //Initializing pickup station Dialog Binding
    destinationStationDialogBinding = DialogDestinationStationBinding.inflate(layoutInflater)
    destinationStationDialog.setContentView(destinationStationDialogBinding.root)
    //Sheet behaviour
    val bottomSheetBehavior = BottomSheetBehavior.from( destinationStationDialogBinding.root.parent as View)
    bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
    destinationStationDialogBinding.coordinator.minimumHeight = Resources.getSystem().displayMetrics.heightPixels
    destinationStationDialog.show()
}
</code>```

Body:
I used a bottom sheet dialog in my application I wanted it to be full screen but its contents are not showing on full screen I want those two button at the bottom of the screen

private fun setupDestinationStationDialog() {
    //Initializing pickup station Dialog Binding
    destinationStationDialogBinding = DialogDestinationStationBinding.inflate(layoutInflater)
    destinationStationDialog.setContentView(destinationStationDialogBinding.root)
    //Sheet behaviour
    val bottomSheetBehavior = BottomSheetBehavior.from( destinationStationDialogBinding.root.parent as View)
    bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
    destinationStationDialogBinding.coordinator.minimumHeight = Resources.getSystem().displayMetrics.heightPixels
    destinationStationDialog.show()
}


问:
findContours result causes ValueError: not enough values to unpack (expected 3, got 2)
I'm making python script that can do img to text

but main problem is same pic, same python script

can run successfully on PC python 3.9.12 , Ubuntu 22.04.1

but faced ValueError: not enough values to unpack (expected 3, got 2)

on nvidia TX2 python3 3.6.9 , python 2.7.17 , Ubuntu 18.04.1

and TX2 , I used "python3 my_script.py" to run

```<code>import os
import cv2
import numpy as np
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import pytesseract

image_2x2 = cv2.imread("/home/jetson/Desktop/test_12.26/original_duplicate.png")
x = 0
y = 0
small_w = 250
small_h = 334
new_crop_for_2x2_xy_distance = image_2x2[y:y+small_h, x:x+small_w]
cv2.imwrite(f"/home/jetson/Desktop/test_12.26/2x2_xy_distance.png",new_crop_for_2x2_xy_distance)

gray = cv2.cvtColor(new_crop_for_2x2_xy_distance, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY_INV)
blur = cv2.medianBlur(thresh, 1)
kernel = np.ones((10, 20), np.uint8)
img_dilation = cv2.dilate(blur, kernel, iterations=1)
im2, ctrs, hier = cv2.findContours(img_dilation.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])

xy_list = []
listOfElems = []
listOfDuplicate = []
list_for_duplicate_x_and_y = [ ]

for i, ctr in enumerate(sorted_ctrs):
    # Get bounding box
    x, y, w, h = cv2.boundingRect(ctr)
    roi = new_crop_for_2x2_xy_distance[y:y + h, x:x + w]
    if (h > 50 and w > 50) and h < 200:

        cv2.rectangle(new_crop_for_2x2_xy_distance, (x, y), (x + w, y + h), (255, 255, 255), 1)

        print("= = = = = = = =   ")
        print("左上 右下" )
        print(x , y )            # 左上 (x , y )
        print(x + w , y + h )    # 右下 (x , y ) = (x + w , y + h )

# (x,y)標準化
        for xc in (45,150,255,360,465,570):
            if xc-20 < x < xc+20:
                x = xc + 26
                break
        else:
            x = 0

        for yc in (132, 243,586,357,470):
            if yc-20 < y < yc+20:
                y = yc + 48
                break

        else:
            y = 0

        print("new number" , x , y )

        tem_list_x_and_y = [ ]
        tem_list_for_duplicate_x_and_y = [ ]

        if (x != 0) and (y != 0):
            # cv2.imwrite(f"/home/joy/桌面/optimization_11_10/output_11_10__001/output_y:{y}_x:{x}.png", roi)
            tem_list_x_and_y.append(x)
            tem_list_x_and_y.append(y)

            xy_list.append(tem_list_x_and_y)

print(xy_list)
sorted_xy_list = (sorted(xy_list , key=lambda k: [k[1], k[0]]))
print(sorted_xy_list)

first_xy= sorted_xy_list[0]
second_xy= sorted_xy_list[1]
third_xy= sorted_xy_list[2]
fourth_xy= sorted_xy_list[3]

# each x
first_xy_x = first_xy[0]
second_xy_x = second_xy[0]
third_xy_x = third_xy[0]
fourth_xy_x = fourth_xy[0]

# each y
first_xy_y = first_xy[1]
second_xy_y = second_xy[1]
third_xy_y = third_xy[1]
fourth_xy_y = fourth_xy[1]

x_distance = ((second_xy_x - first_xy_x) + (fourth_xy_x - third_xy_x) )/2
y_distance = ((third_xy_y - first_xy_y) + (fourth_xy_y - second_xy_y) )/2

print(x_distance)
print(y_distance)

predict_xy_list = []
tem_predict_xy_list = [ ]

tem_predict_xy_list.append(first_xy_x)
tem_predict_xy_list.append(first_xy_y)
predict_xy_list.append(tem_predict_xy_list)

last_x = first_xy_x
last_y = first_xy_y

tem_predict_xy_list = [ ]
for y in range(4):
    tem_predict_xy_list = [ ]
    last_y = int(last_y) + int(y_distance)
    tem_predict_xy_list.append(first_xy_x)
    tem_predict_xy_list.append(last_y)
    predict_xy_list.append(tem_predict_xy_list)

for x in range(5):
    tem_predict_xy_list = [ ]
    last_x = int(last_x) + int(x_distance)
    tem_predict_xy_list.append(last_x)
    tem_predict_xy_list.append(first_xy_y)
    predict_xy_list.append(tem_predict_xy_list)

print(predict_xy_list)
print(len(predict_xy_list))
print("= = = = = ")

for x in range(5):
    tem_predict_xy_list = [ ]
    last_x = int(last_x) + int(x_distance)
    last_y = first_xy_y
    for y in range(4):
        tem_predict_xy_list = [ ]
        last_y = int(last_y) + int(y_distance)
        tem_predict_xy_list.append(last_x)
        tem_predict_xy_list.append(last_y)
        predict_xy_list.append(tem_predict_xy_list)

print(predict_xy_list)
print(len(predict_xy_list))

sorted_predict_xy_list = (sorted(predict_xy_list , key=lambda k: [k[1], k[0]]))
print(sorted_predict_xy_list)

sorted_predict_xy_list = [ [71,180], [176,180], [281,180], [386,180], [491,180], [596,180],
[71,291], [176,291], [281,291], [386,291], [491,291], [596,291],
[71,406], [176,406], [281,406], [386,406], [491,406], [596,406],
[71,522], [176,522], [281,522], [386,522], [491,522], [596,522],
[71,637], [176,637], [281,637], [386,637], [491,637], [596,637] ]

image = cv2.imread("/home/jetson/Desktop/test_12.26/original_duplicate.png")
j = 0
while j < len(sorted_predict_xy_list) :
    temp_xy = sorted_predict_xy_list[j]
    x = temp_xy[0]
    y = temp_xy[1]
    small_txt_size_w = 65
    small_txt_size_h = 16
    x2 = int(x) + int(small_txt_size_w)
    y2 = int(y) + int(small_txt_size_h)
    new_crop = image[y:y2, x:x2]

    text = pytesseract.image_to_string(new_crop, lang='eng').strip()
    print("x :" , x  , ",y :",y , ", x+small_txt_size_w", x2 , ", y+small_txt_size_h :" , y2)
    j+=1

    if text not in listOfElems:

        listOfElems.append(text)
        print(text)
        print("= = = = = = = =   ")
        print("  ")
    else:

        print("Duplicate text is here:")
        print(text)
        print("x :" , x , "y :",y)
        tem_list_for_duplicate_x_and_y.append(x)
        tem_list_for_duplicate_x_and_y.append(y)
        list_for_duplicate_x_and_y.append(tem_list_x_and_y)

        print("= = = = = = = =   ")
        print("  ")

                    # print("len for xy_list is : " ,len(xy_list))

                    # aaa_list = (sorted(xy_list , key=lambda k: [k[1], k[0]]))
                    # print(aaa_list)

                    # print("list_for_duplicate_x_and_y is :")

                    # print(list_for_duplicate_x_and_y)

                    # print("listOfElems is :")
                    # print(listOfElems)

    # cd /home/jetson/Desktop/test_12.26

# /home/jetson/Desktop/test_12.26/original_duplicate.png
# python 12_26_img_to_text.py

# python3 12_26_img_to_text.py
</code>```

the error message

```<code>Traceback (most recent call last):
  File "12_26_img_to_text.py", line 26, in <module>
    im2, ctrs, hier = cv2.findContours(img_dilation.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
ValueError: not enough values to unpack (expected 3, got 2)
</code>```

this is my first time using nvidia TX2, but seems instead of normal PC runiing python code/script , that factory production lines more tend to use tx2 and raspberry pi

I thought I made script run on linux pc is fine, should no worry with TX2 cause they are both ubuntu, I'm too naive.

╮(￣▽￣)╭

Body:
I'm making python script that can do img to text

but main problem is same pic, same python script

can run successfully on PC python 3.9.12 , Ubuntu 22.04.1

but faced ValueError: not enough values to unpack (expected 3, got 2)

on nvidia TX2 python3 3.6.9 , python 2.7.17 , Ubuntu 18.04.1

and TX2 , I used "python3 my_script.py" to run

import os
import cv2
import numpy as np
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import pytesseract

image_2x2 = cv2.imread("/home/jetson/Desktop/test_12.26/original_duplicate.png")
x = 0
y = 0
small_w = 250
small_h = 334
new_crop_for_2x2_xy_distance = image_2x2[y:y+small_h, x:x+small_w]
cv2.imwrite(f"/home/jetson/Desktop/test_12.26/2x2_xy_distance.png",new_crop_for_2x2_xy_distance)

gray = cv2.cvtColor(new_crop_for_2x2_xy_distance, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY_INV)
blur = cv2.medianBlur(thresh, 1)
kernel = np.ones((10, 20), np.uint8)
img_dilation = cv2.dilate(blur, kernel, iterations=1)
im2, ctrs, hier = cv2.findContours(img_dilation.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])

xy_list = []
listOfElems = []
listOfDuplicate = []
list_for_duplicate_x_and_y = [ ]

for i, ctr in enumerate(sorted_ctrs):
    # Get bounding box
    x, y, w, h = cv2.boundingRect(ctr)
    roi = new_crop_for_2x2_xy_distance[y:y + h, x:x + w]
    if (h > 50 and w > 50) and h < 200:

        cv2.rectangle(new_crop_for_2x2_xy_distance, (x, y), (x + w, y + h), (255, 255, 255), 1)

        print("= = = = = = = =   ")
        print("左上 右下" )
        print(x , y )            # 左上 (x , y )
        print(x + w , y + h )    # 右下 (x , y ) = (x + w , y + h )

# (x,y)標準化
        for xc in (45,150,255,360,465,570):
            if xc-20 < x < xc+20:
                x = xc + 26
                break
        else:
            x = 0

        for yc in (132, 243,586,357,470):
            if yc-20 < y < yc+20:
                y = yc + 48
                break

        else:
            y = 0

        print("new number" , x , y )

        tem_list_x_and_y = [ ]
        tem_list_for_duplicate_x_and_y = [ ]

        if (x != 0) and (y != 0):
            # cv2.imwrite(f"/home/joy/桌面/optimization_11_10/output_11_10__001/output_y:{y}_x:{x}.png", roi)
            tem_list_x_and_y.append(x)
            tem_list_x_and_y.append(y)

            xy_list.append(tem_list_x_and_y)

print(xy_list)
sorted_xy_list = (sorted(xy_list , key=lambda k: [k[1], k[0]]))
print(sorted_xy_list)

first_xy= sorted_xy_list[0]
second_xy= sorted_xy_list[1]
third_xy= sorted_xy_list[2]
fourth_xy= sorted_xy_list[3]

# each x
first_xy_x = first_xy[0]
second_xy_x = second_xy[0]
third_xy_x = third_xy[0]
fourth_xy_x = fourth_xy[0]

# each y
first_xy_y = first_xy[1]
second_xy_y = second_xy[1]
third_xy_y = third_xy[1]
fourth_xy_y = fourth_xy[1]

x_distance = ((second_xy_x - first_xy_x) + (fourth_xy_x - third_xy_x) )/2
y_distance = ((third_xy_y - first_xy_y) + (fourth_xy_y - second_xy_y) )/2

print(x_distance)
print(y_distance)

predict_xy_list = []
tem_predict_xy_list = [ ]

tem_predict_xy_list.append(first_xy_x)
tem_predict_xy_list.append(first_xy_y)
predict_xy_list.append(tem_predict_xy_list)

last_x = first_xy_x
last_y = first_xy_y

tem_predict_xy_list = [ ]
for y in range(4):
    tem_predict_xy_list = [ ]
    last_y = int(last_y) + int(y_distance)
    tem_predict_xy_list.append(first_xy_x)
    tem_predict_xy_list.append(last_y)
    predict_xy_list.append(tem_predict_xy_list)

for x in range(5):
    tem_predict_xy_list = [ ]
    last_x = int(last_x) + int(x_distance)
    tem_predict_xy_list.append(last_x)
    tem_predict_xy_list.append(first_xy_y)
    predict_xy_list.append(tem_predict_xy_list)

print(predict_xy_list)
print(len(predict_xy_list))
print("= = = = = ")

for x in range(5):
    tem_predict_xy_list = [ ]
    last_x = int(last_x) + int(x_distance)
    last_y = first_xy_y
    for y in range(4):
        tem_predict_xy_list = [ ]
        last_y = int(last_y) + int(y_distance)
        tem_predict_xy_list.append(last_x)
        tem_predict_xy_list.append(last_y)
        predict_xy_list.append(tem_predict_xy_list)

print(predict_xy_list)
print(len(predict_xy_list))

sorted_predict_xy_list = (sorted(predict_xy_list , key=lambda k: [k[1], k[0]]))
print(sorted_predict_xy_list)

sorted_predict_xy_list = [ [71,180], [176,180], [281,180], [386,180], [491,180], [596,180],
[71,291], [176,291], [281,291], [386,291], [491,291], [596,291],
[71,406], [176,406], [281,406], [386,406], [491,406], [596,406],
[71,522], [176,522], [281,522], [386,522], [491,522], [596,522],
[71,637], [176,637], [281,637], [386,637], [491,637], [596,637] ]

image = cv2.imread("/home/jetson/Desktop/test_12.26/original_duplicate.png")
j = 0
while j < len(sorted_predict_xy_list) :
    temp_xy = sorted_predict_xy_list[j]
    x = temp_xy[0]
    y = temp_xy[1]
    small_txt_size_w = 65
    small_txt_size_h = 16
    x2 = int(x) + int(small_txt_size_w)
    y2 = int(y) + int(small_txt_size_h)
    new_crop = image[y:y2, x:x2]

    text = pytesseract.image_to_string(new_crop, lang='eng').strip()
    print("x :" , x  , ",y :",y , ", x+small_txt_size_w", x2 , ", y+small_txt_size_h :" , y2)
    j+=1

    if text not in listOfElems:

        listOfElems.append(text)
        print(text)
        print("= = = = = = = =   ")
        print("  ")
    else:

        print("Duplicate text is here:")
        print(text)
        print("x :" , x , "y :",y)
        tem_list_for_duplicate_x_and_y.append(x)
        tem_list_for_duplicate_x_and_y.append(y)
        list_for_duplicate_x_and_y.append(tem_list_x_and_y)

        print("= = = = = = = =   ")
        print("  ")

                    # print("len for xy_list is : " ,len(xy_list))

                    # aaa_list = (sorted(xy_list , key=lambda k: [k[1], k[0]]))
                    # print(aaa_list)

                    # print("list_for_duplicate_x_and_y is :")

                    # print(list_for_duplicate_x_and_y)

                    # print("listOfElems is :")
                    # print(listOfElems)

    # cd /home/jetson/Desktop/test_12.26

# /home/jetson/Desktop/test_12.26/original_duplicate.png
# python 12_26_img_to_text.py

# python3 12_26_img_to_text.py

the error message

Traceback (most recent call last):
  File "12_26_img_to_text.py", line 26, in <module>
    im2, ctrs, hier = cv2.findContours(img_dilation.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
ValueError: not enough values to unpack (expected 3, got 2)

this is my first time using nvidia TX2, but seems instead of normal PC runiing python code/script , that factory production lines more tend to use tx2 and raspberry pi

I thought I made script run on linux pc is fine, should no worry with TX2 cause they are both ubuntu, I'm too naive.

╮(￣▽￣)╭


问:
Data Flow Task : Error ODBC Source Failed Validation and returned error code 0x80004005
I am trying to migrate data from PostgreSQl to SQL Server, for which I have created a SSIS package in Visual Studio 2019 using OBDC Source (for connecting to PostgreSQL) and OLE DB Destination (to connect SQL Server in Visual Studio).

I was able to successfully establish the connection in both database and transfer the data in visual studio.

To create a SQL Agent job, I tried creating a SSISDB catalog in SQL Server under integration service catalogs and deployed my SSIS package in Visual Studio 2019 (Note: I tried to change Target server version in Visual studio same as SQL server version).

Although the execution happens successfully in Visual Studio but in SQL server when I execute the package in SSMS, it is throwing an error (highlighted in title and in the screenshot).

How to resolve this issue? Any insight on this will be very helpful.

Regards,
PKR

Things I have tried

I tried to check my access to SQL server, the error is happening even after gaining complete admin level access.

I tried to change the target server version in Visual Studio to match with SQL server version yet it didn't help.