问:
i want to create courses and add them to cloud datastore but steel got this error
logger.ts:115 [2023-01-03T18:53:23.362Z]  @firebase/firestore: Firestore (9.15.0): Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=failed-precondition]: The Cloud Firestore API is not available for Firestore in Datastore Mode database projects/react-platform-v2/databases/(default).

This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.

here is the add form :

```<code>import React from 'react'
import { useState } from "react";
import { toast } from "react-toastify";
import {
  getStorage,
  ref,
  uploadBytesResumable,
  getDownloadURL,
} from "firebase/storage";
import { getAuth } from "firebase/auth";
import { v4 as uuidv4 } from "uuid";
import { addDoc, collection, serverTimestamp } from "firebase/firestore";
import { db } from "../../../Firebase/firebase";
import { useNavigate } from "react-router-dom";

function AddCourseForm() {
    const navigate = useNavigate();
  const auth = getAuth();
  const [formData, setFormData] = useState({
    title: "",
    description: "",
    images: {},
  });
  const {
    title,
    description,
    images,
  } = formData;
  function onChange(e) {
    let boolean = null;
    if (e.target.value === "true") {
      boolean = true;
    }
    if (e.target.value === "false") {
      boolean = false;
    }
    // Files
    if (e.target.files) {
      setFormData((prevState) => ({
        ...prevState,
        images: e.target.files,
      }));
    }
    // Text/Boolean/Number
    if (!e.target.files) {
      setFormData((prevState) => ({
        ...prevState,
        [e.target.id]: boolean ?? e.target.value,
      }));
    }
  }
  async function onSubmit(e) {
    e.preventDefault();

    if (images.length > 2) {
      toast.error("maximum 2 images are allowed");
      return;
    }

    async function storeImage(image) {
      return new Promise((resolve, reject) => {
        const storage = getStorage();
        const filename = `${auth.currentUser.uid}-${image.name}-${uuidv4()}`;
        const storageRef = ref(storage, filename);
        const uploadTask = uploadBytesResumable(storageRef, image);
        uploadTask.on(
          "state_changed",
          (snapshot) => {
            // Observe state change events such as progress, pause, and resume
            // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
            const progress =
              (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            console.log("Upload is " + progress + "% done");
            switch (snapshot.state) {
              case "paused":
                console.log("Upload is paused");
                break;
              case "running":
                console.log("Upload is running");
                break;
            }
          },
          (error) => {
            // Handle unsuccessful uploads
            reject(error);
          },
          () => {
            // Handle successful uploads on complete
            // For instance, get the download URL: https://firebasestorage.googleapis.com/...
            getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
              resolve(downloadURL);
            });
          }
        );
      });
    }

    const imgUrls = await Promise.all(
      [...images].map((image) => storeImage(image))
    ).catch((error) => {
      toast.error("Images not uploaded");
      return;
    });

    const formDataCopy = {
      ...formData,
      imgUrls,
      timestamp: serverTimestamp(),
      userRef: auth.currentUser.uid,
    };
    delete formDataCopy.images;
    const docRef = await addDoc(collection(db, "courses"), formDataCopy);
    toast.success("course created");
    navigate(`/category/${docRef.id}`);
  }

    return (
        <main className="max-w-md px-2 mx-auto">
            <h1 className="text-3xl text-center mt-6 font-bold">Create a course</h1>
            <form onSubmit={onSubmit}>
                <p className="text-lg mt-6 font-semibold">Sell / Rent</p>
                <div className="flex">

                </div>
                <p className="text-lg mt-6 font-semibold">title</p>
                <input
                    type="text"
                    id="title"
                    value={title}
                    onChange={onChange}
                    placeholder="title"
                    maxLength="32"
                    minLength="10"
                    required
                    className="w-full px-4 py-2 text-xl text-gray-700 bg-white border border-gray-300 rounded transition duration-150 ease-in-out focus:text-gray-700 focus:bg-white focus:border-slate-600 mb-6"
                />

                <p className="text-lg font-semibold">Description</p>
                <textarea
                    type="text"
                    id="description"
                    value={description}
                    onChange={onChange}
                    placeholder="Description"
                    required
                    className="w-full px-4 py-2 text-xl text-gray-700 bg-white border border-gray-300 rounded transition duration-150 ease-in-out focus:text-gray-700 focus:bg-white focus:border-slate-600 mb-6"
                />

                <div className="mb-6">
                    <p className="text-lg font-semibold">Images</p>
                    <p className="text-gray-600">
                        The first image will be the cover (max 6)
                    </p>
                    <input
                        type="file"
                        id="images"
                        onChange={onChange}
                        accept=".jpg,.png,.jpeg"
                        multiple
                        required
                        className="w-full px-3 py-1.5 text-gray-700 bg-white border border-gray-300 rounded transition duration-150 ease-in-out focus:bg-white focus:border-slate-600"
                    />
                </div>
                <button
                    type="submit"
                    className="mb-6 w-full px-7 py-3 bg-blue-600 text-white font-medium text-sm uppercase rounded shadow-md hover:bg-blue-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg active:bg-blue-800 active:shadow-lg transition duration-150 ease-in-out"
                >
                    Create course
                </button>
            </form>
        </main>
    )
}

export default AddCourseForm
</code>```

and this is the display code :

```<code>const auth = getAuth();
const navigate = useNavigate();
const [changeDetail, setChangeDetail] = useState(false);
const [courses, setCourses] = useState([]);
  //
  useEffect(() => {
    async function fetchUserCourses() {
      const courseRef = collection(db, "courses");
      const q = query(
        courseRef,
        where("userRef", "==", auth.currentUser.uid),
        orderBy("timestamp", "desc")
      );
      const querySnap = await getDocs(q);
      let courses = [];
      querySnap.forEach((doc) => {
        return courses.push({
          id: doc.id,
          data: doc.data(),
        });
      });
      setCourses(courses);
    }
    fetchUserCourses();
  }, [courses]);

</code>```
```<code><ul className="sm:grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5">
              {courses.map((course) => (
                <>
                <h1>{course.id}</h1>
                <p>{course.data}</p>
                </>

              ))}
            </ul>
</code>```

Body:
logger.ts:115 [2023-01-03T18:53:23.362Z]  @firebase/firestore: Firestore (9.15.0): Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=failed-precondition]: The Cloud Firestore API is not available for Firestore in Datastore Mode database projects/react-platform-v2/databases/(default).

This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.

here is the add form :

import React from 'react'
import { useState } from "react";
import { toast } from "react-toastify";
import {
  getStorage,
  ref,
  uploadBytesResumable,
  getDownloadURL,
} from "firebase/storage";
import { getAuth } from "firebase/auth";
import { v4 as uuidv4 } from "uuid";
import { addDoc, collection, serverTimestamp } from "firebase/firestore";
import { db } from "../../../Firebase/firebase";
import { useNavigate } from "react-router-dom";

function AddCourseForm() {
    const navigate = useNavigate();
  const auth = getAuth();
  const [formData, setFormData] = useState({
    title: "",
    description: "",
    images: {},
  });
  const {
    title,
    description,
    images,
  } = formData;
  function onChange(e) {
    let boolean = null;
    if (e.target.value === "true") {
      boolean = true;
    }
    if (e.target.value === "false") {
      boolean = false;
    }
    // Files
    if (e.target.files) {
      setFormData((prevState) => ({
        ...prevState,
        images: e.target.files,
      }));
    }
    // Text/Boolean/Number
    if (!e.target.files) {
      setFormData((prevState) => ({
        ...prevState,
        [e.target.id]: boolean ?? e.target.value,
      }));
    }
  }
  async function onSubmit(e) {
    e.preventDefault();

    if (images.length > 2) {
      toast.error("maximum 2 images are allowed");
      return;
    }

    async function storeImage(image) {
      return new Promise((resolve, reject) => {
        const storage = getStorage();
        const filename = `${auth.currentUser.uid}-${image.name}-${uuidv4()}`;
        const storageRef = ref(storage, filename);
        const uploadTask = uploadBytesResumable(storageRef, image);
        uploadTask.on(
          "state_changed",
          (snapshot) => {
            // Observe state change events such as progress, pause, and resume
            // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
            const progress =
              (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            console.log("Upload is " + progress + "% done");
            switch (snapshot.state) {
              case "paused":
                console.log("Upload is paused");
                break;
              case "running":
                console.log("Upload is running");
                break;
            }
          },
          (error) => {
            // Handle unsuccessful uploads
            reject(error);
          },
          () => {
            // Handle successful uploads on complete
            // For instance, get the download URL: https://firebasestorage.googleapis.com/...
            getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
              resolve(downloadURL);
            });
          }
        );
      });
    }

    const imgUrls = await Promise.all(
      [...images].map((image) => storeImage(image))
    ).catch((error) => {
      toast.error("Images not uploaded");
      return;
    });

    const formDataCopy = {
      ...formData,
      imgUrls,
      timestamp: serverTimestamp(),
      userRef: auth.currentUser.uid,
    };
    delete formDataCopy.images;
    const docRef = await addDoc(collection(db, "courses"), formDataCopy);
    toast.success("course created");
    navigate(`/category/${docRef.id}`);
  }

    return (

Create a course

            <form onSubmit={onSubmit}>

Sell / Rent

title

                <input
                    type="text"
                    id="title"
                    value={title}
                    onChange={onChange}
                    placeholder="title"
                    maxLength="32"
                    minLength="10"
                    required
                    className="w-full px-4 py-2 text-xl text-gray-700 bg-white border border-gray-300 rounded transition duration-150 ease-in-out focus:text-gray-700 focus:bg-white focus:border-slate-600 mb-6"
                />

Description

                <textarea
                    type="text"
                    id="description"
                    value={description}
                    onChange={onChange}
                    placeholder="Description"
                    required
                    className="w-full px-4 py-2 text-xl text-gray-700 bg-white border border-gray-300 rounded transition duration-150 ease-in-out focus:text-gray-700 focus:bg-white focus:border-slate-600 mb-6"
                />

Images

                        The first image will be the cover (max 6)

                    <input
                        type="file"
                        id="images"
                        onChange={onChange}
                        accept=".jpg,.png,.jpeg"
                        multiple
                        required
                        className="w-full px-3 py-1.5 text-gray-700 bg-white border border-gray-300 rounded transition duration-150 ease-in-out focus:bg-white focus:border-slate-600"
                    />

                <button
                    type="submit"
                    className="mb-6 w-full px-7 py-3 bg-blue-600 text-white font-medium text-sm uppercase rounded shadow-md hover:bg-blue-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg active:bg-blue-800 active:shadow-lg transition duration-150 ease-in-out"
                >
                    Create course
                </button>
            </form>

    )
}

export default AddCourseForm

and this is the display code :

const auth = getAuth();
const navigate = useNavigate();
const [changeDetail, setChangeDetail] = useState(false);
const [courses, setCourses] = useState([]);
  //
  useEffect(() => {
    async function fetchUserCourses() {
      const courseRef = collection(db, "courses");
      const q = query(
        courseRef,
        where("userRef", "==", auth.currentUser.uid),
        orderBy("timestamp", "desc")
      );
      const querySnap = await getDocs(q);
      let courses = [];
      querySnap.forEach((doc) => {
        return courses.push({
          id: doc.id,
          data: doc.data(),
        });
      });
      setCourses(courses);
    }
    fetchUserCourses();
  }, [courses]);

              {courses.map((course) => (
                <>

{course.id}

{course.data}

                </>

              ))}


来源: stackexchange

问:
How to retrive telegram poll answers?
I basically created a page in wordpress where i can build polls, then I hit publish and it sends the poll to my telegram group.

This is the function I wrote and works:

```<code>function post_to_telegram( $new_status, $old_status, $post ) {
  if( $new_status == 'publish' && $old_status != 'publish' && $post->post_type == 'post') {
    $apiToken = "XXX";
    $options =  array("Devendra","noneofthese","Sourabh") ;
    $data = [      'chat_id' => 'XXX',   'question' => 'TEST ?',  'options' => json_encode($options) ];
    $response = file_get_contents("https://api.telegram.org/bot$apiToken/sendPoll?" .http_build_query($data) );
    }
  }
add_action( 'transition_post_status', 'post_to_telegram', 10, 3 );
</code>```

Thing is now I need to read the answers, the documentation has "update" and "Poll answers" https://core.telegram.org/bots/api#update - https://core.telegram.org/bots/api#pollanswer

But I'm very new to this and I'm not sure how to retrieve them and display results using php.

ContentLicense: CC BY-SA 4.0

Title: How to retrive telegram poll answers?

Body:
I basically created a page in wordpress where i can build polls, then I hit publish and it sends the poll to my telegram group.

This is the function I wrote and works:

function post_to_telegram( $new_status, $old_status, $post ) {
  if( $new_status == 'publish' && $old_status != 'publish' && $post->post_type == 'post') {
    $apiToken = "XXX";
    $options =  array("Devendra","noneofthese","Sourabh") ;
    $data = [      'chat_id' => 'XXX',   'question' => 'TEST ?',  'options' => json_encode($options) ];
    $response = file_get_contents("https://api.telegram.org/bot$apiToken/sendPoll?" .http_build_query($data) );
    }
  }
add_action( 'transition_post_status', 'post_to_telegram', 10, 3 );

Thing is now I need to read the answers, the documentation has "update" and "Poll answers" https://core.telegram.org/bots/api#update - https://core.telegram.org/bots/api#pollanswer

But I'm very new to this and I'm not sure how to retrieve them and display results using php.


问:
Konva with stage draggable passing mouse events to layers
using konva's library I'm trying to be able to drag the whole stage only with the middle click which i've solutioned using:

```<code>this.stage = new Konva.Stage({
 container: canvasElement.id,
 width: this.initialWidth,
 height: this.initialHeight,
 scaleX: this.initialScale,
 scaleY: this.initialScale,
 draggable: true
});

let lastX = this.stage.position().x;
let lastY = this.stage.position().y;
this.stage.on('dragmove', (e) => {
 if (e.evt.buttons === 1) {
  this.stage.x(lastX);
  this.stage.y(lastY);
 } else {
  lastX = this.stage.position().x;
  lastY = this.stage.position().y;
 }
});
</code>```

And now i wish to use the different mouse events on a specific layer in that stage while left click (which triggers the drag from the stage).

mouseover

mousedown

mouseup

mouseleave

mouseenter

contextmenu

But while the canvas is in dragging mode (even tho I've restricted the movement), it won't pass any event to childs.

Example of layer event handler:

```<code>this.layerGrid.on('mouseover', (e) => {
 const coords = new Coords(e.target.attrs.coords.x, e.target.attrs.coords.y);
 this.onMouseOver(coords);
});
</code>```

I've tried to search for a way to only configure the draggable to be triggered only by middle click and ignore right click, without success, only found my actual way of restricting the movements directly.

I've also found a way handling manually the dragging with onmousemove and changing the stage position, but is there really no simple way using the builtin draggable for my case?

Body:
using konva's library I'm trying to be able to drag the whole stage only with the middle click which i've solutioned using:

this.stage = new Konva.Stage({
 container: canvasElement.id,
 width: this.initialWidth,
 height: this.initialHeight,
 scaleX: this.initialScale,
 scaleY: this.initialScale,
 draggable: true
});

let lastX = this.stage.position().x;
let lastY = this.stage.position().y;
this.stage.on('dragmove', (e) => {
 if (e.evt.buttons === 1) {
  this.stage.x(lastX);
  this.stage.y(lastY);
 } else {
  lastX = this.stage.position().x;
  lastY = this.stage.position().y;
 }
});

And now i wish to use the different mouse events on a specific layer in that stage while left click (which triggers the drag from the stage).

mouseover

mousedown

mouseup

mouseleave

mouseenter

contextmenu

But while the canvas is in dragging mode (even tho I've restricted the movement), it won't pass any event to childs.

Example of layer event handler:

this.layerGrid.on('mouseover', (e) => {
 const coords = new Coords(e.target.attrs.coords.x, e.target.attrs.coords.y);
 this.onMouseOver(coords);
});

I've tried to search for a way to only configure the draggable to be triggered only by middle click and ignore right click, without success, only found my actual way of restricting the movements directly.

I've also found a way handling manually the dragging with onmousemove and changing the stage position, but is there really no simple way using the builtin draggable for my case?


问:
Every time it is retuning null this tag is not retuning the data courses = soup.find_all("li", {'class': 'ais-InfiniteHits-item'})
I am not getting the details of the courses

```<code>from selenium.webdriver.common.action_chains import ActionChains
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By

def find_courses(source):
    soup = BeautifulSoup(source, 'html.parser')
    if soup is None:
        print("Page not found")
    else:
        courses = soup.find_all("li", {'class': 'ais-InfiniteHits-item'})
        print(courses)
        for course in courses:
            try:
                course_title = course.h2.get_text()
                course_rating = course.find('span', {'class': 'ratings-text'}).get_text()
                print(f"Course Title: \t {course_title}")
                print(f"Course Rating: \t {course_rating}")
                print('\n' + '|' + ('<' * 3) + ('-' * 7) + ' New Course ' + ('-' * 7) + ('>' * 3) + '|' + '\n')
            except:
                print("Something went wrong when printing the courses")

url = "https://in.coursera.org/search?query=free&index=prod_all_launched_products_term_optimization"
driver = webdriver.Chrome()
driver.get(url)
driver.implicitly_wait(80)
for i in range(10):
    element = driver.find_element("xpath",'//button[@aria-label = "Next Page"]')
    ActionChains(driver).move_to_element(element).perform()
    find_courses(driver.page_source)
    ActionChains(driver).click().perform()
    driver.implicitly_wait(80)
driver.quit()

</code>```

Every time it is retuning null  this tag is not retuning the data courses = soup.find_all("li", {'class': 'ais-InfiniteHits-item'})

Body:
I am not getting the details of the courses

from selenium.webdriver.common.action_chains import ActionChains
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By

def find_courses(source):
    soup = BeautifulSoup(source, 'html.parser')
    if soup is None:
        print("Page not found")
    else:
        courses = soup.find_all("li", {'class': 'ais-InfiniteHits-item'})
        print(courses)
        for course in courses:
            try:
                course_title = course.h2.get_text()
                course_rating = course.find('span', {'class': 'ratings-text'}).get_text()
                print(f"Course Title: \t {course_title}")
                print(f"Course Rating: \t {course_rating}")
                print('\n' + '|' + ('<' * 3) + ('-' * 7) + ' New Course ' + ('-' * 7) + ('>' * 3) + '|' + '\n')
            except:
                print("Something went wrong when printing the courses")

url = "https://in.coursera.org/search?query=free&index=prod_all_launched_products_term_optimization"
driver = webdriver.Chrome()
driver.get(url)
driver.implicitly_wait(80)
for i in range(10):
    element = driver.find_element("xpath",'//button[@aria-label = "Next Page"]')
    ActionChains(driver).move_to_element(element).perform()
    find_courses(driver.page_source)
    ActionChains(driver).click().perform()
    driver.implicitly_wait(80)
driver.quit()

Every time it is retuning null  this tag is not retuning the data courses = soup.find_all("li", {'class': 'ais-InfiniteHits-item'})


问:
Script not executing in Thymeleaf template, getting 'Error OK'
Hi I am using Thymeleaf and spring boot, view is displayed but the script tag is not executing it gives me ERROR OK on console, I am new to this, can some one help

This is my Thymeleaf template (HTML)

```<code><!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<!-- jQuery Cdn import -->
<script   src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>

</head>
<body>
    <header>Report Scheduling</header>
    <h1>Welcome</h1>
    <p th:text="${queryData}"></p>
    <a class="waves-effect waves-light btn">button</a>
    <script th:inline="javascript">
        console.log("Script Executed");
    </script>
</body>
</html>
</code>```

This is my controller

```<code>@Controller
@RequestMapping("analyticsdashboard/neoApi")
public class RSChartsController {
    @Autowired
    CatalogService catalogService;

    private static final Logger logger = LoggerFactory.getLogger(RSChartsController.class);

    @GetMapping("/RSChartsController")
    public String RSChartsController(Model model, HttpServletRequest req, HttpServletResponse res) throws SQLException
    {
        Object queryData =catalogService.reportChartDetails();

        model.addAttribute("queryData",queryData);
        return "RSChartsTemplate";
    }
}
</code>```

Every time i hit "RSChartsController" api from frontend the html content shows but script is not executing, I am not understanding what mistake I am doing

showing me following error
enter image description here

& preview
enter image description here

can somebody help me in understanding why my script is not executing, it should show me output in console as "Script Executed"

Thanks

Body:
Hi I am using Thymeleaf and spring boot, view is displayed but the script tag is not executing it gives me ERROR OK on console, I am new to this, can some one help

This is my Thymeleaf template (HTML)

<!DOCTYPE html>

    Report Scheduling

Welcome

    button

This is my controller

@Controller
@RequestMapping("analyticsdashboard/neoApi")
public class RSChartsController {
    @Autowired
    CatalogService catalogService;

    private static final Logger logger = LoggerFactory.getLogger(RSChartsController.class);

    @GetMapping("/RSChartsController")
    public String RSChartsController(Model model, HttpServletRequest req, HttpServletResponse res) throws SQLException
    {
        Object queryData =catalogService.reportChartDetails();

        model.addAttribute("queryData",queryData);
        return "RSChartsTemplate";
    }
}

Every time i hit "RSChartsController" api from frontend the html content shows but script is not executing, I am not understanding what mistake I am doing

showing me following error
enter image description here

& preview
enter image description here

can somebody help me in understanding why my script is not executing, it should show me output in console as "Script Executed"

Thanks


问:
Test PreparedStatement values are not null when passed to the jdbcTemplate.batchUpdate("sql", new BatchPreparedStatementSetter()))
I have code which reads from json files and adds values to a list of pojos, this list is then used to batch insert into sql table. I am trying to write a unit test in Java to check wheather the values of a list of Pojos are null when when creating a Prepared statement as this uses setString and setLong which will throw NPE if value is null.

Pojo Class

```<code>public class Customer{
Long: id;
String Name;
}
</code>```

Dao Class

```<code>public class CustomerDao{
@Autowired
JdbcTemplate jdbcTemplate;

public int[] batchInsert(List<Customer> customers) {

return this.jdbcTemplate.batchUpdate("INSERT into CUSTOMER_TBL (ID, NAME) values (?,?)", new BatchPreparedStatementSetter(){
public void setValues(PreparedStatement ps, int i) throws SQLException {

ps.setLong(1, customers.get(i).getId());
ps.setString(2, customers.get(i).getName());
}
public int getBatchSize(){ return customers.size();}
})

}

}
</code>```

Service class

In this class I am creating a List of Customers and populating the values of name and id from json  then calling the batchInsert method of Dao class with that List.

```<code>public class CustomerService(){

@Autowired
JdbcTemplate jdbcTemplate;

@Autowired
CustomerDao customerDao;

List<Customer> customerList = new LinkedList<>();

// populating list
...

// calling batchInsert with list of Custoemrs

customerDao.batchInsert(customerList)

}

</code>```

Now I want to write a unit test to verify that  the values of name and id in customerList are not null when setting the values of prepared statement in CustomerDao class.

```<code> ps.setLong(1, customers.get(i).getId());
ps.setString(2, customers.get(i).getName());
</code>```

I have tried something like code below but the setValues method is not being called in the DaoClass due to jdbcTemplate null pointer. Is there a better way to test this kind of functionality?

```<code>public class DaoTest {
    @Mock
    private JdbcTemplate jdbcTemplate;

    @InjectMocks
    private CustomerDao dao;

    @Test
    public void testBatchInsert() {

        Customer customer = new Customer();
customer.setId(1L);
customer.setName(null);
        List<Customer> customerList = new LinkedList<>();
customerList.add(customer);

        PreparedStatement ps = mock(PreparedStatement.class);

        int[] result = dao.batchInsert(customerList);

         assertEquals(0, result.length)

    }
}
</code>```

Thanks in advance

Body:
I have code which reads from json files and adds values to a list of pojos, this list is then used to batch insert into sql table. I am trying to write a unit test in Java to check wheather the values of a list of Pojos are null when when creating a Prepared statement as this uses setString and setLong which will throw NPE if value is null.

Pojo Class

public class Customer{
Long: id;
String Name;
}

Dao Class

public class CustomerDao{
@Autowired
JdbcTemplate jdbcTemplate;

public int[] batchInsert(List<Customer> customers) {

return this.jdbcTemplate.batchUpdate("INSERT into CUSTOMER_TBL (ID, NAME) values (?,?)", new BatchPreparedStatementSetter(){
public void setValues(PreparedStatement ps, int i) throws SQLException {

ps.setLong(1, customers.get(i).getId());
ps.setString(2, customers.get(i).getName());
}
public int getBatchSize(){ return customers.size();}
})

}

}

Service class

In this class I am creating a List of Customers and populating the values of name and id from json  then calling the batchInsert method of Dao class with that List.

public class CustomerService(){

@Autowired
JdbcTemplate jdbcTemplate;

@Autowired
CustomerDao customerDao;

List<Customer> customerList = new LinkedList<>();

// populating list
...

// calling batchInsert with list of Custoemrs

customerDao.batchInsert(customerList)

}

Now I want to write a unit test to verify that  the values of name and id in customerList are not null when setting the values of prepared statement in CustomerDao class.

 ps.setLong(1, customers.get(i).getId());
ps.setString(2, customers.get(i).getName());

I have tried something like code below but the setValues method is not being called in the DaoClass due to jdbcTemplate null pointer. Is there a better way to test this kind of functionality?

public class DaoTest {
    @Mock
    private JdbcTemplate jdbcTemplate;

    @InjectMocks
    private CustomerDao dao;

    @Test
    public void testBatchInsert() {

        Customer customer = new Customer();
customer.setId(1L);
customer.setName(null);
        List<Customer> customerList = new LinkedList<>();
customerList.add(customer);

        PreparedStatement ps = mock(PreparedStatement.class);

        int[] result = dao.batchInsert(customerList);

         assertEquals(0, result.length)

    }
}

Thanks in advance


问:
How can I get this Javascript to correctly decorate button hyperlinks on my page? Relevant: Google's Cross-Domain Measurement, Unbounce Landing Pages
I have some landing pages built in a service called Unbounce. These landing pages contain buttons going to my sign-up page. The landing pages and sign-up page are in different domains, so I use Google's Cross Domain Measurement to track activity between them.

Unbounced has a behavior in their landing pages where clicks are first directed to an unseen sub-directory and then re-directed to the destination (sign-up page). This behavior causes Google's CDM to not decorate the link, and therefore I am not able to adequately track traffic that goes through my landing pages.

note: by "not decorated," I mean an "_gl" parameter isn't showing up in the link.

Visiting the provided hyperlink to my landing page, there's two buttons: "Get Started for FREE" and "Start Your 60-day FREE Trial", at the top and bottom of the page respectively. The top button is subject to the issue I described and the resulting link is not decorated when clicked. The bottom button is not subject to this behavior and produces the desired result when clicked.

I have managed to find examples of people trying to solve similar problems with forms, but it does not work the same for buttons. I'm not sure how to modify this to get it working in my case though. Any help here is appreciated.

```<code><script>
  $('.lp-pom-button, .lp-pom-text a, .lp-pom-image a').click(function(event) {
    var parentClass = $(this).parent().attr('class');

    var isFormRedirect =
      parentClass === 'lp-element lp-pom-form' &&
      window.module.lp.form.data.confirmAction === 'url' &&
      lp.jQuery('form').valid() === true;

    if (isFormRedirect) {
      ga(function(tracker) {
        var linker = new window.gaplugins.Linker(tracker);
        window.module.lp.form.data.confirmData = linker.decorate(window.module.lp.form.data.confirmData);
      });
    } else {
      ga('linker:decorate', this);
    }
  });
</script>
</code>```


问:
How does Laravel turn this code into a link?
Consider this block of code from a Laravel blade file:

{{ $item->name }}

{!! Str::limit($item->desccription, 120) !!}

  @if($item->type == 'lot')

{{ $item->info ? "Current Bid: $".number_format($item->info, 2) : 'No bids yet' }}

{{ \Carbon\Carbon::parse($item->start)->setTimezone($_COOKIE['timezone'])->format('n/j/y g:ia T') }} - {{ \Carbon\Carbon::parse($item->end)->setTimezone($_COOKIE['timezone'])->format('n/j/y g:ia T') }}

  @else

{{ $item->info }} Lot{{ $item->info > 1 ? "s" : '' }}

{{ \Carbon\Carbon::parse($item->start)->setTimezone($_COOKIE['timezone'])->format('n/j/y T') }} - {{ \Carbon\Carbon::parse($item->end)->setTimezone($_COOKIE['timezone'])->format('n/j/y T') }}

  @endif
  search_url }}" title="">
    View: {{ $item->search_title }}

```

Somehow or other, this renders in a browser as a block of text that is all included in a link tag, and "$item->search_url" becomes the link url. But the link is wrong - it just points back to the page this text is appearing on.  I need to figure out where "search-url" is assigned its value, so I can fix it.  But I am entirely new to Laravel, and I can't figure out where or how "search-url" is getting assigned a value.  I've searched the entire system with Visual Code, and that name doesn't appear anywhere else.  It's not a variable, it's not a property name, it's not a database field name.

Where is that variable getting assigned?

Body:
Consider this block of code from a Laravel blade file:

{{ $item->name }}

{!! Str::limit($item->desccription, 120) !!}

  @if($item->type == 'lot')

{{ $item->info ? "Current Bid: $".number_format($item->info, 2) : 'No bids yet' }}

{{ \Carbon\Carbon::parse($item->start)->setTimezone($_COOKIE['timezone'])->format('n/j/y g:ia T') }} - {{ \Carbon\Carbon::parse($item->end)->setTimezone($_COOKIE['timezone'])->format('n/j/y g:ia T') }}

  @else

{{ $item->info }} Lot{{ $item->info > 1 ? "s" : '' }}

{{ \Carbon\Carbon::parse($item->start)->setTimezone($_COOKIE['timezone'])->format('n/j/y T') }} - {{ \Carbon\Carbon::parse($item->end)->setTimezone($_COOKIE['timezone'])->format('n/j/y T') }}

  @endif
  search_url }}" title="">
    View: {{ $item->search_title }}

Somehow or other, this renders in a browser as a block of text that is all included in a link tag, and "$item->search_url" becomes the link url. But the link is wrong - it just points back to the page this text is appearing on.  I need to figure out where "search-url" is assigned its value, so I can fix it.  But I am entirely new to Laravel, and I can't figure out where or how "search-url" is getting assigned a value.  I've searched the entire system with Visual Code, and that name doesn't appear anywhere else.  It's not a variable, it's not a property name, it's not a database field name.

Where is that variable getting assigned?


问:
Can I test the sent email in the register view with "mailoutbox" parameter in pytest_django?
I have a register view that sends an activation email and I want to test sending emails with "mailoutbox" parameter in pytest_django.

This is the register view:

for EmailMessage I used mail_templated and send

```<code>from django.http import HttpResponseRedirect
from django.shortcuts import redirect, render
from django.urls import reverse_lazy
from django.views.generic.edit import FormView
from django.contrib.auth import get_user_model

from rest_framework_simplejwt.tokens import RefreshToken

from mail_templated import EmailMessage
from decouple import config

from .utils import EmailThread
from .forms import UserCreationModelForm

User = get_user_model()

class AccountsRegisterFormView(FormView):
    """
    A view for displaying a register form and rendering a template response.
    """

    form_class = UserCreationModelForm
    template_name = 'accounts/register.html'
    success_url = reverse_lazy('task:list')

    def get_token_for_user(self, user):
        refresh = RefreshToken.for_user(user)
        return str(refresh.access_token)

    def form_valid(self, form):
        """
        If the form is valid, redirect to the supplied URL
        :param form: registration form
        :return: if form valid register user.
        """
        user_obj = form.save()
        if user_obj is not None:
            email = user_obj.email
            username = user_obj.username
            token = self.get_token_for_user(user_obj)

            domain = 'http://127.0.0.1:8000/'
            url = 'accounts/activation/confirm/'

            activation_email = EmailMessage(
                'email/activation_account.tpl',
                {
                    'user': username,
                    'token': f'{domain}{url}{token}/',
                },
                'sender@example.com',
                [email]
            )
            EmailThread(activation_email).start()
            return HttpResponseRedirect(
                reverse_lazy('accounts:activation_send')
            )

        return super(AccountsRegisterFormView, self).form_valid(form)

</code>```

I used EmailMessage from mail_templated package.

and this is the test:

```<code>
@pytest.mark.django_db
class TestAccountsViews:

    def test_accounts_views(self, client, mailoutbox):
        url = reverse('accounts:register')
        data = {
            'email': 'test_register@test.com',
            'username': 'test_username_register',
            'password1': 'password2register',
            'password2': 'password2register',
        }
        response = client.post(path=url, data=data)
        assert response.status_code == 302
        assert len(mailoutbox) == 1
        email = mailoutbox[0]
        assert email.subject == 'Email Verification'

</code>```

and this is what I received:

```<code>======================================= FAILURES ========================================
_________________________ TestAccountsViews.test_accounts_views _________________________

self = <app.accounts.tests.TestAccountsViews object at 0x7f7856be1ed0>
client = <django.test.client.Client object at 0x7f785660f010>
mailoutbox = [<mail_templated.message.EmailMessage object at 0x7f7855d90310>]

    def test_accounts_views(self, client, mailoutbox):
        url = reverse('accounts:register')
        data = {
            'email': 'test_register@test.com',
            'username': 'test_username_register',
            'password1': 'password2register',
            'password2': 'password2register',
        }
        response = client.post(path=url, data=data)
        assert response.status_code == 302
>       assert len(mailoutbox) == 1
E       assert 0 == 1
E        +  where 0 = len([])

accounts/tests.py:67: AssertionError

</code>```

Body:
I have a register view that sends an activation email and I want to test sending emails with "mailoutbox" parameter in pytest_django.

This is the register view:

for EmailMessage I used mail_templated and send

from django.http import HttpResponseRedirect
from django.shortcuts import redirect, render
from django.urls import reverse_lazy
from django.views.generic.edit import FormView
from django.contrib.auth import get_user_model

from rest_framework_simplejwt.tokens import RefreshToken

from mail_templated import EmailMessage
from decouple import config

from .utils import EmailThread
from .forms import UserCreationModelForm

User = get_user_model()

class AccountsRegisterFormView(FormView):
    """
    A view for displaying a register form and rendering a template response.
    """

    form_class = UserCreationModelForm
    template_name = 'accounts/register.html'
    success_url = reverse_lazy('task:list')

    def get_token_for_user(self, user):
        refresh = RefreshToken.for_user(user)
        return str(refresh.access_token)

    def form_valid(self, form):
        """
        If the form is valid, redirect to the supplied URL
        :param form: registration form
        :return: if form valid register user.
        """
        user_obj = form.save()
        if user_obj is not None:
            email = user_obj.email
            username = user_obj.username
            token = self.get_token_for_user(user_obj)

            domain = 'http://127.0.0.1:8000/'
            url = 'accounts/activation/confirm/'

            activation_email = EmailMessage(
                'email/activation_account.tpl',
                {
                    'user': username,
                    'token': f'{domain}{url}{token}/',
                },
                'sender@example.com',
                [email]
            )
            EmailThread(activation_email).start()
            return HttpResponseRedirect(
                reverse_lazy('accounts:activation_send')
            )

        return super(AccountsRegisterFormView, self).form_valid(form)

I used EmailMessage from mail_templated package.

and this is the test:

@pytest.mark.django_db
class TestAccountsViews:

    def test_accounts_views(self, client, mailoutbox):
        url = reverse('accounts:register')
        data = {
            'email': 'test_register@test.com',
            'username': 'test_username_register',
            'password1': 'password2register',
            'password2': 'password2register',
        }
        response = client.post(path=url, data=data)
        assert response.status_code == 302
        assert len(mailoutbox) == 1
        email = mailoutbox[0]
        assert email.subject == 'Email Verification'

and this is what I received:

======================================= FAILURES ========================================
_________________________ TestAccountsViews.test_accounts_views _________________________

self = <app.accounts.tests.TestAccountsViews object at 0x7f7856be1ed0>
client = <django.test.client.Client object at 0x7f785660f010>
mailoutbox = [<mail_templated.message.EmailMessage object at 0x7f7855d90310>]

    def test_accounts_views(self, client, mailoutbox):
        url = reverse('accounts:register')
        data = {
            'email': 'test_register@test.com',
            'username': 'test_username_register',
            'password1': 'password2register',
            'password2': 'password2register',
        }
        response = client.post(path=url, data=data)
        assert response.status_code == 302
>       assert len(mailoutbox) == 1
E       assert 0 == 1
E        +  where 0 = len([])

accounts/tests.py:67: AssertionError


问:
Inserting and deleting rows in excel with node.js cause problems
I have a node.js file whose function is to insert and delete columns in an excel file,Im working with the 'xslx' module.

Both insert and delete rows have their own function, so when I call one without calling the other, everything works fine, but if I call them at the same time they don't work as they should, the rows are repeated and not added as they should.

This is the data I want to put in the excel sheet :

```<code>    let datos = [
    {
        "Dato 1" : 1,
        "Dato 2" : 2,
        "Dato 3" : 3
    },
    {
        "Dato 1" : 4,
        "Dato 2" : 5,
        "Dato 3" : 6
    },
    {
        "Dato 1" : 7,
        "Dato 2" : 8,
        "Dato 3" : 9
    }
 ]
</code>```

When I only call the function to put data, this happens Works fine it pull all the data in the correct way:

```<code>    function caller() {

        // console.log('Deleting previous data...')
        // deleteAllExcelRows(woorksheet)
        // console.log('Data eliminated\n')

        console.log("Put new data...\n");
        for (let i = 0; i < datos.length; i++) {

            putDataExcel(woorksheet,datos,i);
        }

    }
caller()
</code>```

When I only call the function to delete the data also works fine,deletes all the data except the headers:

```<code>    function caller() {

        console.log('Deleting previous data...')
        deleteAllExcelRows(woorksheet)
        console.log('Data eliminated\n')

        // console.log("Put new data...\n");
        // for (let i = 0; i < datos.length; i++) {

        //     putDataExcel(woorksheet,datos,i);
        // }

    }
caller()
</code>```

Now if I called both something very weird happens, the last elements of the data is repeated:

```<code>function caller() {

    console.log('Deleting previous data...')
    deleteAllExcelRows(woorksheet)
    console.log('Data eliminated\n')

    console.log("Put new data...\n");
    for (let i = 0; i < datos.length; i++) {

        putDataExcel(woorksheet,datos,i);
    }

}

caller()
</code>```

INCORRECT RESULT :

Desire result :

Complete code :

```<code>const xlsx = require("xlsx");

const FILENAME = "C:\\Users\\harol\\Documents\\prueba-excel.xlsx"

let wb = xlsx.readFile(FILENAME);
let woorksheet = wb.Sheets[wb.SheetNames[0]];

let datos = [
    {
        "Dato 1" : 1,
        "Dato 2" : 2,
        "Dato 3" : 3
    },
    {
        "Dato 1" : 4,
        "Dato 2" : 5,
        "Dato 3" : 6
    },
    {
        "Dato 1" : 7,
        "Dato 2" : 8,
        "Dato 3" : 9
    }
]

function putDataExcel(ws,data,i) {

    let hoja = xlsx.utils.sheet_to_json(ws);
    console.log(xlsx.utils.decode_range(ws["!ref"]))

    hoja.push(data[i]);
    xlsx.utils.sheet_add_json(ws, hoja);
    xlsx.writeFile(wb, FILENAME);
}

function ec(row, column) {
  return xlsx.utils.encode_cell({ r: row, c: column });
}

function deleteExcelRow(ws, row_index) {

    let hoja = xlsx.utils.sheet_to_json(ws);
    console.log(xlsx.utils.decode_range(ws["!ref"]))

    let range = xlsx.utils.decode_range(ws["!ref"]);
    for (var R = row_index; R < range.e.r; ++R) {
        for (var C = range.s.c; C <= range.e.c; ++C) {
        ws[ec(R, C)] = ws[ec(R + 1, C)];
    }
  }
  range.e.r--;
  ws["!ref"] = xlsx.utils.encode_range(range.s, range.e);
  xlsx.writeFile(wb, FILENAME);
  console.log(xlsx.utils.decode_range(ws["!ref"]))
  console.log("\n")
}

function deleteAllExcelRows(ws)
{

    let numeroFilas = parseInt(xlsx.utils.decode_range(ws['!ref']).e.r)

    for(let i = 1;i<=numeroFilas;i++)
    {
        deleteExcelRow(ws,i);
        console.log("Dato " + i + "Eliminado ")
    }

}

function caller() {

    console.log('Deleting previous data...')
    deleteAllExcelRows(woorksheet)
    console.log('Data eliminated\n')

    console.log("Put new data...\n");
    for (let i = 0; i < datos.length; i++) {

        putDataExcel(woorksheet,datos,i);
    }

}

caller()
</code>```

Why this happens and how I can solve it ?

Body:
I have a node.js file whose function is to insert and delete columns in an excel file,Im working with the 'xslx' module.

Both insert and delete rows have their own function, so when I call one without calling the other, everything works fine, but if I call them at the same time they don't work as they should, the rows are repeated and not added as they should.

This is the data I want to put in the excel sheet :

    let datos = [
    {
        "Dato 1" : 1,
        "Dato 2" : 2,
        "Dato 3" : 3
    },
    {
        "Dato 1" : 4,
        "Dato 2" : 5,
        "Dato 3" : 6
    },
    {
        "Dato 1" : 7,
        "Dato 2" : 8,
        "Dato 3" : 9
    }
 ]

When I only call the function to put data, this happens Works fine it pull all the data in the correct way:

    function caller() {

        // console.log('Deleting previous data...')
        // deleteAllExcelRows(woorksheet)
        // console.log('Data eliminated\n')

        console.log("Put new data...\n");
        for (let i = 0; i < datos.length; i++) {

            putDataExcel(woorksheet,datos,i);
        }

    }
caller()

When I only call the function to delete the data also works fine,deletes all the data except the headers:

    function caller() {

        console.log('Deleting previous data...')
        deleteAllExcelRows(woorksheet)
        console.log('Data eliminated\n')

        // console.log("Put new data...\n");
        // for (let i = 0; i < datos.length; i++) {

        //     putDataExcel(woorksheet,datos,i);
        // }

    }
caller()

Now if I called both something very weird happens, the last elements of the data is repeated:

function caller() {

    console.log('Deleting previous data...')
    deleteAllExcelRows(woorksheet)
    console.log('Data eliminated\n')

    console.log("Put new data...\n");
    for (let i = 0; i < datos.length; i++) {

        putDataExcel(woorksheet,datos,i);
    }

}

caller()

INCORRECT RESULT :

Desire result :

Complete code :

const xlsx = require("xlsx");

const FILENAME = "C:\\Users\\harol\\Documents\\prueba-excel.xlsx"

let wb = xlsx.readFile(FILENAME);
let woorksheet = wb.Sheets[wb.SheetNames[0]];

let datos = [
    {
        "Dato 1" : 1,
        "Dato 2" : 2,
        "Dato 3" : 3
    },
    {
        "Dato 1" : 4,
        "Dato 2" : 5,
        "Dato 3" : 6
    },
    {
        "Dato 1" : 7,
        "Dato 2" : 8,
        "Dato 3" : 9
    }
]

function putDataExcel(ws,data,i) {

    let hoja = xlsx.utils.sheet_to_json(ws);
    console.log(xlsx.utils.decode_range(ws["!ref"]))

    hoja.push(data[i]);
    xlsx.utils.sheet_add_json(ws, hoja);
    xlsx.writeFile(wb, FILENAME);
}

function ec(row, column) {
  return xlsx.utils.encode_cell({ r: row, c: column });
}

function deleteExcelRow(ws, row_index) {

    let hoja = xlsx.utils.sheet_to_json(ws);
    console.log(xlsx.utils.decode_range(ws["!ref"]))

    let range = xlsx.utils.decode_range(ws["!ref"]);
    for (var R = row_index; R < range.e.r; ++R) {
        for (var C = range.s.c; C <= range.e.c; ++C) {
        ws[ec(R, C)] = ws[ec(R + 1, C)];
    }
  }
  range.e.r--;
  ws["!ref"] = xlsx.utils.encode_range(range.s, range.e);
  xlsx.writeFile(wb, FILENAME);
  console.log(xlsx.utils.decode_range(ws["!ref"]))
  console.log("\n")
}

function deleteAllExcelRows(ws)
{

    let numeroFilas = parseInt(xlsx.utils.decode_range(ws['!ref']).e.r)

    for(let i = 1;i<=numeroFilas;i++)
    {
        deleteExcelRow(ws,i);
        console.log("Dato " + i + "Eliminado ")
    }

}

function caller() {

    console.log('Deleting previous data...')
    deleteAllExcelRows(woorksheet)
    console.log('Data eliminated\n')

    console.log("Put new data...\n");
    for (let i = 0; i < datos.length; i++) {

        putDataExcel(woorksheet,datos,i);
    }

}

caller()

Why this happens and how I can solve it ?


问:
hello first of all I'm not very expert in solidity, I would like to understand what I have to correct in this contract
```<code>//SPDX-License-Identifier: MIT

pragma solidity 0.8.17;

import "./DappCNO.sol";

contract DappCNOSale {

    address admin;
    DappCNO public tokenContract;
    uint256 public tokenPrice;
    uint256 public tokenSold;

    event Sell(address _buyer, uint256 _amount);

    function DappCNOSaleF(DappCNO _tokenContract, uint256 _tokePrice) public {
        admin = msg.sender;
        tokenContract = _tokenContract;
        tokenPrice = _tokePrice;
    }

    function multiply(uint x, uint y ) internal pure returns ( uint z ) {
        require(y == 0 || (z = x * y ) / y == x);
    }

    function buyTokens(uint256 _numberOfTokens) public  payable {
        require(msg.value == multiply(_numberOfTokens, tokenPrice));
        require(tokenContract.balanceOf(address(this)) >= _numberOfTokens);
        require(tokenContract.transfer(msg.sender, _numberOfTokens));

        tokenSold += _numberOfTokens;

        Sell(msg.sender, _numberOfTokens);
    }

    function endSale() public {
        require(msg.sender == admin);
        require(tokenContract.transfer(admin, tokenContract.balanceOf(address(this))));

        // UPDATE: Let's not destroy the contract here
        // Just transfer the balance to the admin
        admin.transfer(address(this).balance);
    }
}
</code>```

here where it gives me the error---->     admin.transfer
error says: send and transfer are only availabe for objects

of type "address payable", not "address" .
where should i  correct?

```<code></code>```

Body:
//SPDX-License-Identifier: MIT

pragma solidity 0.8.17;

import "./DappCNO.sol";

contract DappCNOSale {

    address admin;
    DappCNO public tokenContract;
    uint256 public tokenPrice;
    uint256 public tokenSold;

    event Sell(address _buyer, uint256 _amount);

    function DappCNOSaleF(DappCNO _tokenContract, uint256 _tokePrice) public {
        admin = msg.sender;
        tokenContract = _tokenContract;
        tokenPrice = _tokePrice;
    }

    function multiply(uint x, uint y ) internal pure returns ( uint z ) {
        require(y == 0 || (z = x * y ) / y == x);
    }

    function buyTokens(uint256 _numberOfTokens) public  payable {
        require(msg.value == multiply(_numberOfTokens, tokenPrice));
        require(tokenContract.balanceOf(address(this)) >= _numberOfTokens);
        require(tokenContract.transfer(msg.sender, _numberOfTokens));

        tokenSold += _numberOfTokens;

        Sell(msg.sender, _numberOfTokens);
    }

    function endSale() public {
        require(msg.sender == admin);
        require(tokenContract.transfer(admin, tokenContract.balanceOf(address(this))));

        // UPDATE: Let's not destroy the contract here
        // Just transfer the balance to the admin
        admin.transfer(address(this).balance);
    }
}

here where it gives me the error---->     admin.transfer
error says: send and transfer are only availabe for objects

of type "address payable", not "address" .
where should i  correct?


问:
Flutter - drawer doesn't pop out when performing logout
I have an app that presents an AuthScreen and then works with subsequent screens based on the Auth provider class result.

In fact, in the main.dart file I present different pages based on the provider class Auth.
If the user performs the login (and he is Supplier), he will be directed to SupplierOverviewScreen, where he can see all his events.

If he clicks on an event, he will be directed to the EditEventScreen class, where he can modify the event.

Both SupplierOverviewScreen and EditEventScreen use the same drawer (SupplierDrawer), which allows to perform the logout operation.

When peforming a logout, Auth info will be deleted and so the main.dart file (consuming Auth provider class) will present againt the AuthScreen page.

If I'm on the SupplierOverviewScreen and I open the drawer to logout, everything works.

The problem is that if I'm on the EditEventScreen and I try to logout, The screen remains stuck and the drawer doesn't pop out.

I see that under the hood everything works, and the main.dart file returns the AuthScreen exactly as it does in SupplierOverviewScreen  (where it works), but nothing changes on the screen.
If I return to previous screen, it doesn't direct me to SupplierOverview screen, but to AuthScreen.

I've found two possible hacks, but I'm not satisfied with them:

Remove drawer from EditEventScreen

Change the drawer such that after the logout it performs  Navigator.pushReplacementNamed(context, "/"); It works, but since main.dart file consumes Auth provider class, I have that the home is called twice (one when Auth provider class notify listeners and one when drawer calls Navigator.pushReplacementNamed(context, "/")

Do you have any idea to suggest? Thanks a lot

This is the main.dart file:

```<code>Future<void> main() async {
  await dotenv.load(fileName: Environment.fileName);
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    //Init state operations
  }

  void _configureAmplify() async {
    // Amplify initial configurations
  }

  List<Event> _mockEvents() {
    // mocked list of event objects
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => Auth()),
        ChangeNotifierProxyProvider<Auth, Supplier>(
          create: (ctx) => Supplier(userId: null, username: null),
          update: (ctx, authData, previous) => Supplier(
              userId: authData.getUserId, username: previous?.username),
        ),
        ChangeNotifierProxyProvider<Auth, SupplierEvents>(
          create: (ctx) => SupplierEvents(
              userId: null,
              events:
                  _mockEvents()),
          update: (ctx, authData, previous) => SupplierEvents(
              userId: authData.getUserId, events: previous?.events ?? []),
        ),
      ],
      child: Consumer<Auth>(
        builder: (context, authData, child) => MaterialApp(
            title: 'Apperò',
            theme: ThemeData(
              colorScheme: Theme.of(context).colorScheme.copyWith(),
            ),
            home: !authData.isAuth()
                ? FutureBuilder(
                    future: authData.tryAutoLogin(),
                    builder: (ctx, authResultSnapshot) {
                      print(authResultSnapshot.connectionState.name);
                      if (authResultSnapshot.connectionState ==
                          ConnectionState.waiting) {
                        return LoadingScreen();
                      } else
                        return AuthScreen();
                    })
                : (authData.getUserType == UserType.supplier
                    ? SupplierOverviewScreen()
                    : CustomerOverviewScreen()),
            routes: {
              SupplierOverviewScreen.ROUTE_NAME: (ctx) =>
                  SupplierOverviewScreen(),
              CustomerOverviewScreen.ROUTE_NAME: (ctx) =>
                  CustomerOverviewScreen(),
              EditEventScreen.ROUTE_NAME: (ctx) => EditEventScreen(),
            }),
      ),
    );
  }
}
</code>```

This is the SupplierOverviewScreen  class:

```<code>class SupplierOverviewScreen extends StatefulWidget {
  static const String ROUTE_NAME = '/supplier-overview-screen';

  const SupplierOverviewScreen({Key? key}) : super(key: key);

  @override
  State<SupplierOverviewScreen> createState() => _SupplierOverviewScreenState();
}

class _SupplierOverviewScreenState extends State<SupplierOverviewScreen> {
  late Future _obtainedInfo;

  Future<void> _fetchInfo() async {
    await Provider.of<Supplier>(context, listen: false).fetchSupplierByUserId();
    await Provider.of<SupplierEvents>(context, listen: false)
        .fetchEventsByUserId();
  }

  @override
  void initState() {
    _obtainedInfo = _fetchInfo();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
        appBar: AppBar(title: Text('Your page'), actions: []),
        drawer: SupplierDrawer(),
        body: FutureBuilder(
          future: _obtainedInfo,
          builder: (context, snapshot) => snapshot.connectionState ==
                  ConnectionState.waiting
              ? const Center(
                  child: CircularProgressIndicator(),
                )
              : RefreshIndicator(
                  onRefresh: () => _fetchInfo(),
                  child: Column(
                    children: [
                      Consumer<Supplier>(
                        builder: (context, supplierData, _) => Padding(
                          padding: EdgeInsets.all(8),
                          child: Text('Hello ${supplierData.username}'),
                        ),
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      Consumer<SupplierEvents>(
                        builder: (context, supplierEventsData, _) => Expanded(
                          child: ListView.builder(
                            scrollDirection: Axis.vertical,
                            itemCount: supplierEventsData.events.length,
                            itemBuilder: (context, index) => Column(children: [
                              SupplierEventsItem(
                                event: supplierEventsData.events[index],
                              ),
                              const Divider(),
                            ]),
                          ),
                        ),
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      Padding(
                        padding: EdgeInsets.all(8),
                        child: Text('Bottom element'),
                      ),
                    ],
                  ),
                ),
        ),
        floatingActionButton: FloatingActionButton(
          child: const Text('Add Event', textAlign: TextAlign.center,),
          onPressed: () {
            Navigator.of(context)
                .pushNamed(EditEventScreen.ROUTE_NAME);
          },
        ));
  }
}
</code>```

This is the EditEventScreen class:

```<code>class EditEventScreen extends StatefulWidget {
  static const String ROUTE_NAME = '/edit-event-screen';
  const EditEventScreen({Key? key}) : super(key: key);

  @override
  State<EditEventScreen> createState() => _EditEventScreenState();
}

class _EditEventScreenState extends State<EditEventScreen> {
  late Future _obtainedInfo;
  Event? inputEvent;
  var _isLoading = false;

  var _form = GlobalKey<FormState>();
  var _titleFocusNode = FocusNode();
  var _descriptionFocusNode = FocusNode();

  Map<String, dynamic?> _initialValuesMap = {
    //....
  };

  Event event = Event(// ...);

  @override
  void didChangeDependencies() {
    _obtainedInfo = _fetchInfo();
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    // ...
  }

  Future<void> _fetchInfo() async {
    try {
      var eventId = ModalRoute.of(context)!.settings.arguments as int?;
      print('eventId: $eventId');
      if (eventId != null) {
        inputEvent = await Provider.of<SupplierEvents>(context, listen: false)
            .findById(eventId);
        _initFormFields();
      }
    } catch (error) {
      print(error);
    }
  }

  void _initFormFields() {
    // init form fields logic
  }

  Future<void> _saveForm() async {
    //Form saving logic
  }

  @override
  Widget build(BuildContext context) {
    print('Building EditEventScreen');
    return Scaffold(
      appBar: AppBar(title: Text('Manage event'), actions: [
        IconButton(
            onPressed: () {
              _saveForm();
            },
            icon: Icon(Icons.check))
      ]),
      drawer: SupplierDrawer(),
      body: FutureBuilder(
        future: _obtainedInfo,
        builder: (context, snapshot) => snapshot.connectionState ==
                ConnectionState.waiting
            ? const Center(
                child: CircularProgressIndicator(),
              )
            : _isLoading
                ? const Center(
                    child: CircularProgressIndicator(),
                  )
                : Padding(
                    padding: EdgeInsets.all(16),
                    child: Form(
                      key: _form,
                      child: SingleChildScrollView(
                        child: Column(
                          children: [
                            // TextFormFields ...
                          ],
                        ),
                      ),
                    ),
                  ),
      ),
    );
  }
}
</code>```

This is the drawer class:

```<code>class SupplierDrawer extends StatelessWidget {
  Future<void> logout(BuildContext context) async {
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Logout'),
          content: Container(
            alignment: Alignment.center,
            height: 300,
            width: 300,
            child: Column(
              children: const [
                Text('Logging out...'),
                Center(
                  child: CircularProgressIndicator(),
                )
              ],
            ),
          ),
        );
      },
    );
    await Provider.of<Auth>(context, listen: false).signOutCurrentUser(false);
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: Column(
        children: [
          AppBar(
            title: Text('Your options'),
            automaticallyImplyLeading: false,
          ),
          Divider(),
          ListTile(
            leading: Icon(Icons.logout),
            title: Text('Logout'),
            onTap: () async {
              await logout(context);
            },
          ),
        ],
      ),
    );
  }
}
</code>```

Body:
I have an app that presents an AuthScreen and then works with subsequent screens based on the Auth provider class result.

In fact, in the main.dart file I present different pages based on the provider class Auth.
If the user performs the login (and he is Supplier), he will be directed to SupplierOverviewScreen, where he can see all his events.

If he clicks on an event, he will be directed to the EditEventScreen class, where he can modify the event.

Both SupplierOverviewScreen and EditEventScreen use the same drawer (SupplierDrawer), which allows to perform the logout operation.

When peforming a logout, Auth info will be deleted and so the main.dart file (consuming Auth provider class) will present againt the AuthScreen page.

If I'm on the SupplierOverviewScreen and I open the drawer to logout, everything works.

The problem is that if I'm on the EditEventScreen and I try to logout, The screen remains stuck and the drawer doesn't pop out.

I see that under the hood everything works, and the main.dart file returns the AuthScreen exactly as it does in SupplierOverviewScreen  (where it works), but nothing changes on the screen.
If I return to previous screen, it doesn't direct me to SupplierOverview screen, but to AuthScreen.

I've found two possible hacks, but I'm not satisfied with them:

Remove drawer from EditEventScreen

Change the drawer such that after the logout it performs  Navigator.pushReplacementNamed(context, "/"); It works, but since main.dart file consumes Auth provider class, I have that the home is called twice (one when Auth provider class notify listeners and one when drawer calls Navigator.pushReplacementNamed(context, "/")

Do you have any idea to suggest? Thanks a lot

This is the main.dart file:

Future<void> main() async {
  await dotenv.load(fileName: Environment.fileName);
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    //Init state operations
  }

  void _configureAmplify() async {
    // Amplify initial configurations
  }

  List<Event> _mockEvents() {
    // mocked list of event objects
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => Auth()),
        ChangeNotifierProxyProvider<Auth, Supplier>(
          create: (ctx) => Supplier(userId: null, username: null),
          update: (ctx, authData, previous) => Supplier(
              userId: authData.getUserId, username: previous?.username),
        ),
        ChangeNotifierProxyProvider<Auth, SupplierEvents>(
          create: (ctx) => SupplierEvents(
              userId: null,
              events:
                  _mockEvents()),
          update: (ctx, authData, previous) => SupplierEvents(
              userId: authData.getUserId, events: previous?.events ?? []),
        ),
      ],
      child: Consumer<Auth>(
        builder: (context, authData, child) => MaterialApp(
            title: 'Apperò',
            theme: ThemeData(
              colorScheme: Theme.of(context).colorScheme.copyWith(),
            ),
            home: !authData.isAuth()
                ? FutureBuilder(
                    future: authData.tryAutoLogin(),
                    builder: (ctx, authResultSnapshot) {
                      print(authResultSnapshot.connectionState.name);
                      if (authResultSnapshot.connectionState ==
                          ConnectionState.waiting) {
                        return LoadingScreen();
                      } else
                        return AuthScreen();
                    })
                : (authData.getUserType == UserType.supplier
                    ? SupplierOverviewScreen()
                    : CustomerOverviewScreen()),
            routes: {
              SupplierOverviewScreen.ROUTE_NAME: (ctx) =>
                  SupplierOverviewScreen(),
              CustomerOverviewScreen.ROUTE_NAME: (ctx) =>
                  CustomerOverviewScreen(),
              EditEventScreen.ROUTE_NAME: (ctx) => EditEventScreen(),
            }),
      ),
    );
  }
}

This is the SupplierOverviewScreen  class:

class SupplierOverviewScreen extends StatefulWidget {
  static const String ROUTE_NAME = '/supplier-overview-screen';

  const SupplierOverviewScreen({Key? key}) : super(key: key);

  @override
  State<SupplierOverviewScreen> createState() => _SupplierOverviewScreenState();
}

class _SupplierOverviewScreenState extends State<SupplierOverviewScreen> {
  late Future _obtainedInfo;

  Future<void> _fetchInfo() async {
    await Provider.of<Supplier>(context, listen: false).fetchSupplierByUserId();
    await Provider.of<SupplierEvents>(context, listen: false)
        .fetchEventsByUserId();
  }

  @override
  void initState() {
    _obtainedInfo = _fetchInfo();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
        appBar: AppBar(title: Text('Your page'), actions: []),
        drawer: SupplierDrawer(),
        body: FutureBuilder(
          future: _obtainedInfo,
          builder: (context, snapshot) => snapshot.connectionState ==
                  ConnectionState.waiting
              ? const Center(
                  child: CircularProgressIndicator(),
                )
              : RefreshIndicator(
                  onRefresh: () => _fetchInfo(),
                  child: Column(
                    children: [
                      Consumer<Supplier>(
                        builder: (context, supplierData, _) => Padding(
                          padding: EdgeInsets.all(8),
                          child: Text('Hello ${supplierData.username}'),
                        ),
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      Consumer<SupplierEvents>(
                        builder: (context, supplierEventsData, _) => Expanded(
                          child: ListView.builder(
                            scrollDirection: Axis.vertical,
                            itemCount: supplierEventsData.events.length,
                            itemBuilder: (context, index) => Column(children: [
                              SupplierEventsItem(
                                event: supplierEventsData.events[index],
                              ),
                              const Divider(),
                            ]),
                          ),
                        ),
                      ),
                      const SizedBox(
                        height: 10,
                      ),
                      Padding(
                        padding: EdgeInsets.all(8),
                        child: Text('Bottom element'),
                      ),
                    ],
                  ),
                ),
        ),
        floatingActionButton: FloatingActionButton(
          child: const Text('Add Event', textAlign: TextAlign.center,),
          onPressed: () {
            Navigator.of(context)
                .pushNamed(EditEventScreen.ROUTE_NAME);
          },
        ));
  }
}

This is the EditEventScreen class:

class EditEventScreen extends StatefulWidget {
  static const String ROUTE_NAME = '/edit-event-screen';
  const EditEventScreen({Key? key}) : super(key: key);

  @override
  State<EditEventScreen> createState() => _EditEventScreenState();
}

class _EditEventScreenState extends State<EditEventScreen> {
  late Future _obtainedInfo;
  Event? inputEvent;
  var _isLoading = false;

  var _form = GlobalKey<FormState>();
  var _titleFocusNode = FocusNode();
  var _descriptionFocusNode = FocusNode();

  Map<String, dynamic?> _initialValuesMap = {
    //....
  };

  Event event = Event(// ...);

  @override
  void didChangeDependencies() {
    _obtainedInfo = _fetchInfo();
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    // ...
  }

  Future<void> _fetchInfo() async {
    try {
      var eventId = ModalRoute.of(context)!.settings.arguments as int?;
      print('eventId: $eventId');
      if (eventId != null) {
        inputEvent = await Provider.of<SupplierEvents>(context, listen: false)
            .findById(eventId);
        _initFormFields();
      }
    } catch (error) {
      print(error);
    }
  }

  void _initFormFields() {
    // init form fields logic
  }

  Future<void> _saveForm() async {
    //Form saving logic
  }

  @override
  Widget build(BuildContext context) {
    print('Building EditEventScreen');
    return Scaffold(
      appBar: AppBar(title: Text('Manage event'), actions: [
        IconButton(
            onPressed: () {
              _saveForm();
            },
            icon: Icon(Icons.check))
      ]),
      drawer: SupplierDrawer(),
      body: FutureBuilder(
        future: _obtainedInfo,
        builder: (context, snapshot) => snapshot.connectionState ==
                ConnectionState.waiting
            ? const Center(
                child: CircularProgressIndicator(),
              )
            : _isLoading
                ? const Center(
                    child: CircularProgressIndicator(),
                  )
                : Padding(
                    padding: EdgeInsets.all(16),
                    child: Form(
                      key: _form,
                      child: SingleChildScrollView(
                        child: Column(
                          children: [
                            // TextFormFields ...
                          ],
                        ),
                      ),
                    ),
                  ),
      ),
    );
  }
}

This is the drawer class:

class SupplierDrawer extends StatelessWidget {
  Future<void> logout(BuildContext context) async {
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Logout'),
          content: Container(
            alignment: Alignment.center,
            height: 300,
            width: 300,
            child: Column(
              children: const [
                Text('Logging out...'),
                Center(
                  child: CircularProgressIndicator(),
                )
              ],
            ),
          ),
        );
      },
    );
    await Provider.of<Auth>(context, listen: false).signOutCurrentUser(false);
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: Column(
        children: [
          AppBar(
            title: Text('Your options'),
            automaticallyImplyLeading: false,
          ),
          Divider(),
          ListTile(
            leading: Icon(Icons.logout),
            title: Text('Logout'),
            onTap: () async {
              await logout(context);
            },
          ),
        ],
      ),
    );
  }
}


问:
I can't resize Mat-calendar , remain always big
I create one MatDialog, with inline Mat-Calendar, but I can't resize the calendar, the Dialog  I'm able to resize by putting the width and heigth, but tha table of days remain like this picture, so big!.

```<code><mat-card class="">
  <div class="flex justify-around items-center">
    <button mat-button (click)="today()">Today</button>
    <button mat-flat-button (click)="clearSelected()"[color]="'accent'">Clear</button>
    <button mat-flat-button (click)="select($event)" [color]="'primary'">Select</button>
  </div>
  <mat-calendar
    [dateClass]="dateClass()"
    #picker panelClass="endDate"
    [(selected)]="selectedDate"
    (selectedChange)="onSelect($event)">
  </mat-calendar>
</code>```

```<code>.example-header {
    display: flex;
    align-items: center;
    padding: 0.5em;
}
::ng-deep.md-datepicker-input-container {
    width: 200px;
}
</code>```

for open the dialog I use this code:

```<code>this._matDialog.open(DialogDueDateTableDialog, {
                // width: '300px',
                // height: 'h-full',
                // autoFocus: false,
                // maxHeight: '90vh', //you can adjust the value as per your view
                data: {
                    content:this.activatedRow,
                    column: column.name,
                    row:    row,
                    allData: this.rowData
                }
            })
            .afterClosed()
            .pipe(
                tap(() => this.activatedRow = null)
            );
</code>```

if I try to enable the width (width: '300px') the final resul is the second image
Ho can resize correctly?
like the image 3?

Body:
I create one MatDialog, with inline Mat-Calendar, but I can't resize the calendar, the Dialog  I'm able to resize by putting the width and heigth, but tha table of days remain like this picture, so big!.

<mat-card class="">

    <button mat-button (click)="today()">Today</button>
    <button mat-flat-button (click)="clearSelected()"[color]="'accent'">Clear</button>
    <button mat-flat-button (click)="select($event)" [color]="'primary'">Select</button>

  <mat-calendar
    [dateClass]="dateClass()"
    #picker panelClass="endDate"
    [(selected)]="selectedDate"
    (selectedChange)="onSelect($event)">
  </mat-calendar>

.example-header {
    display: flex;
    align-items: center;
    padding: 0.5em;
}
::ng-deep.md-datepicker-input-container {
    width: 200px;
}

for open the dialog I use this code:

this._matDialog.open(DialogDueDateTableDialog, {
                // width: '300px',
                // height: 'h-full',
                // autoFocus: false,
                // maxHeight: '90vh', //you can adjust the value as per your view
                data: {
                    content:this.activatedRow,
                    column: column.name,
                    row:    row,
                    allData: this.rowData
                }
            })
            .afterClosed()
            .pipe(
                tap(() => this.activatedRow = null)
            );

if I try to enable the width (width: '300px') the final resul is the second image
Ho can resize correctly?
like the image 3?


问:
PBI R Script Visual: Error in UseMethod("rename") : no applicable method for 'rename' applied to an object of class "function"
Super R noob here trying to get away with some copy/paste from Google. Any help to eliminate this error is appreciated.

here is my code:

```<code>library(bupaR)
library(dplyr)

data %>%
    # rename timestamp variables appropriately
   dplyr::rename(start = Starttime,
         complete = Endtime) %>%
    # convert timestamps to
    convert_timestamps(columns = c("start", "complete"), format = ymd_hms) %>%
    activitylog(case_id = "Shipasitem",
                activity_id = "OperationDescription",
                timestamps = c("start", "complete"))
</code>```

and here is the error:

Error in UseMethod("rename") :
no applicable method for 'rename' applied to an object of class "function"
Calls: %>% ... convert_timestamps -> stopifnot -> %in% ->
Execution halted

i've tried calling all sorts of different libraries with no luck.

Body:
Super R noob here trying to get away with some copy/paste from Google. Any help to eliminate this error is appreciated.

here is my code:

library(bupaR)
library(dplyr)

data %>%
    # rename timestamp variables appropriately
   dplyr::rename(start = Starttime,
         complete = Endtime) %>%
    # convert timestamps to
    convert_timestamps(columns = c("start", "complete"), format = ymd_hms) %>%
    activitylog(case_id = "Shipasitem",
                activity_id = "OperationDescription",
                timestamps = c("start", "complete"))

and here is the error:

Error in UseMethod("rename") :
no applicable method for 'rename' applied to an object of class "function"
Calls: %>% ... convert_timestamps -> stopifnot -> %in% ->
Execution halted

i've tried calling all sorts of different libraries with no luck.


问:
Convert SQL Server uniqueidentifier to MongoDB bindata uuid
We can convert MongoDB bindata uuid to SQL Server uniqueidentifier by this query:

```<code>select cast(0x14e52693004d004caf19c169251a497c as uniqueidentifier)
</code>```

outputs

```<code>9326E514-4D00-4C00-AF19-C169251A497C
</code>```

convert mongodb bindata uuid to sql server uniqueidentifier

Can we convert SQL Server uniqueidentifier to MongoDB bindata uuid?

Body:
We can convert MongoDB bindata uuid to SQL Server uniqueidentifier by this query:

select cast(0x14e52693004d004caf19c169251a497c as uniqueidentifier)

outputs

9326E514-4D00-4C00-AF19-C169251A497C

convert mongodb bindata uuid to sql server uniqueidentifier

Can we convert SQL Server uniqueidentifier to MongoDB bindata uuid?


问:
Spring Controller: how to get the query parameters and urlencoded body separately
I have a POST controller to handle a simple HTML user sign up form that has fields for 'username', 'password' and so on. This is sent as application/x-www-form-urlencoded. The controller also takes a few parameters from the request URI, like the client id, redirect uri and it might have a username query parameter which is used to prefill the 'username' input when rendering the page.

In my controller, I use a model to read the request body called UserSignUpFormModel it's a simple POJO with setters and getters for the form fields 'username', 'password', 'email'.

However, when the form is submitted with also a username query parameter, then the username value is added twice to the 'username' field in UserSignUpFormModel.

When performing this POST request:

```<code>POST localhost/sign-up?client_id=abc&redirect_uri=xyz&username=bar

-- Request body:
username=foo&password=some_password&...
</code>```

then calling userSignUpFormModel.getUsername() returns "foo,bar" instead of just "foo" from the request body.

This is my controller:

@PostController
public String performSignUp(UserSignUpFormModel user) {
     // username = "foo,bar" but should just be "foo" from the input field
     String username = user.getUsername();
     // ...controller logic
}
```
<p>And this is my model:</p>
<pre class="lang-java prettyprint-override"><code>@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserSignUpFormModel {

    private String email;

    private String username;

    private String password;

    private String passwordConfirmation;

    private Boolean hasAcceptedTerms;

}
</code>```

How can I get the query parameters and body values separately?

Body:
I have a POST controller to handle a simple HTML user sign up form that has fields for 'username', 'password' and so on. This is sent as application/x-www-form-urlencoded. The controller also takes a few parameters from the request URI, like the client id, redirect uri and it might have a username query parameter which is used to prefill the 'username' input when rendering the page.

In my controller, I use a model to read the request body called UserSignUpFormModel it's a simple POJO with setters and getters for the form fields 'username', 'password', 'email'.

However, when the form is submitted with also a username query parameter, then the username value is added twice to the 'username' field in UserSignUpFormModel.

When performing this POST request:

POST localhost/sign-up?client_id=abc&redirect_uri=xyz&username=bar

-- Request body:
username=foo&password=some_password&...

then calling userSignUpFormModel.getUsername() returns "foo,bar" instead of just "foo" from the request body.

This is my controller:

@PostController
public String performSignUp(UserSignUpFormModel user) {
     // username = "foo,bar" but should just be "foo" from the input field
     String username = user.getUsername();
     // ...controller logic
}

And this is my model:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserSignUpFormModel {

    private String email;

    private String username;

    private String password;

    private String passwordConfirmation;

    private Boolean hasAcceptedTerms;

}

How can I get the query parameters and body values separately?


问:
How do I add 32 bit libraries to Code::Blocks using GNU GCC in Win 10
Currently using GNU GCC 64 bit with Code::Blocks as the IDE. When adding the -M32 checkbox to compile, it can't find libraries. I know the problem. They are installed (I have found the paths in explorer), but how do I enable the ability to switch between 32 bit and 64 bit libraries? I need to provide programs to 32 bit XP systems also. I am just a hobby user, so easier explanation is better.</p>