问:
where am i going wrong in this javascript code

I fairly new to javascript and can't figure out the problem with this code

const array1 = [1, 2, 3, 4];
array1.map(squareit);
let array2;

function squareit(no) {
  array2.push(no * no);
}
console.log(array2);```

i have feeling my question is silly but still help me pls

this is the error i get
Uncaught ReferenceError: Cannot access 'array2' before initialization

Body:
I fairly new to javascript and can't figure out the problem with this code

const array1 = [1, 2, 3, 4];
array1.map(squareit);
let array2;

function squareit(no) {
  array2.push(no * no);
}
console.log(array2);

i have feeling my question is silly but still help me pls

this is the error i get
Uncaught ReferenceError: Cannot access 'array2' before initialization


来源: stackexchange

问:
Phploy how to upload only 1 file
some short question:

Is there any option to upload only 1 file through phploy, without refresh etc.

My server connection is too slow to make a full refresh, so I just need to upload a file with direction like "resources/js/app/home-page/Pages/Home.jsx".

Please let me know if this is possible or not. Thank you.

ContentLicense: CC BY-SA 4.0

Title: Phploy how to upload only 1 file


问:
ASP.NET Core handle simultaneous requests when caching
So I have an issue when trying to cache on the first request a user sends and then use the cached data in all following requests. A lot of data is fetched on the first request and it's pretty resource heavy so that's why I'm caching it.

The issue is that the user/frontend will on some pages send multiple requests simultaneously. This triggers the resource heavy mechanism to create the cache entry multiple times. Is there some good way to "consolidate" these requests to only trigger the caching logic once?

Currently it works like this:

Name
Time
Triggers recaching logic?

Request 1
00:00
Yes <-- Only this one should fetch the resources to cache

Request 2
00:00
Yes <-- This should wait for cache to be populatd by Request 1

Request 3
00:00
Yes <-- This should wait for cache to be populated by Request 1

Request 4
00:05
No

Request 5
00:15
No

I don't think my actual code is very relevant since I'm more looking for a general concept of this. I've tried looking around for solutions but can't find anything applicable, and I've also attempted to put a dictionary of <cacheKey, cachingTask> that contains the caching tasks while they're being processed but it seems the requests are too close in time for this to work as well.


问:
How read a resource in a @ApplicationScoped Service?
I'm trying to read variables from json.properties and web.xml using the @Resource.In the same time i need to inject the class into another services:
this my class :

```<code>@Named
@ApplicationScoped
public class TestServiceImpl implements ITestService {

@Resource(name = "smsEndpoint")
private String smsEndpoint;

@Resource(name = "smsUsername")
private String smsUsername;

@Resource(name = "smsPassword")
private String smsPassword;

@Override
public void sendSMS(SMS sms) throws IOException {}
}
</code>```

and this an example to inject this class into this service:

```<code> @Inject
 private ITestService smsService;
</code>```

but I can' succeded to read this variable from the files, I got this exception :
Caused by: javax.naming.NameNotFoundException: java:comp/env/smsEndpoint

Any idea which annotation i need to put for my service that can read the ressource and also can be injected?Thanks in advance.

Body:
I'm trying to read variables from json.properties and web.xml using the @Resource.In the same time i need to inject the class into another services:
this my class :

@Named
@ApplicationScoped
public class TestServiceImpl implements ITestService {

@Resource(name = "smsEndpoint")
private String smsEndpoint;

@Resource(name = "smsUsername")
private String smsUsername;

@Resource(name = "smsPassword")
private String smsPassword;

@Override
public void sendSMS(SMS sms) throws IOException {}
}

and this an example to inject this class into this service:

 @Inject
 private ITestService smsService;

but I can' succeded to read this variable from the files, I got this exception :
Caused by: javax.naming.NameNotFoundException: java:comp/env/smsEndpoint

Any idea which annotation i need to put for my service that can read the ressource and also can be injected?Thanks in advance.


问:
Edit functionality with react and firebase
I have been building a react app and have been trying to get the edit functionality to work for awhile but just cant get it right. I have a page where information gets displayed(IncidentReportPage) and another page where the information that gets displayed is input(DashboardForm). When the edit button is clicked on the IncidentReportPage where the information is getting displayed i want to be taken back to the DashboardForm where the previously inputted data should be populated back into the inputs and able to be edited. The save button will also need to be changed to edit the information when clicked rather than submit a whole new instance of the component being created.

This is the code from the IncidentReportPage. I have created an update function already but unable to get it to do what i require.

```<code>import { useEffect, useState } from "react";
import { db } from "./firebase";
import { collection, getDocs, deleteDoc, doc, updateDoc } from "firebase/firestore";
import { useNavigate } from "react-router-dom";

const IncidentReportPage = (props) => {
    const [reports, setReports] = useState([]);
    const usersCollectionRef = collection(db, 'reports');
    const navigate = useNavigate();

    const deleteReport = async (id) => {
        const reportDoc = doc(db, "reports", id);
        await deleteDoc(reportDoc);
      };

    const updateReport = async (id, title, description, patrollerName, location, date, time, dateReport) => {
        const userDoc = doc(db, 'reports', id, title, description, patrollerName, location, date, time, dateReport);
        await updateDoc(userDoc);
        navigate('/Dashboard')
    }

    useEffect(() => {
        const getReports = async () => {
            const reportData = await getDocs(usersCollectionRef);
            setReports(reportData.docs.map((doc) => ({...doc.data(), id: doc.id })));
        };

        getReports();
    },)

    useEffect(() => {
        if (props.funcNav) {
          props.funcNav(true)
        }
      })

 return (
        <main className="flex flex-col bg-zinc-200 min-h-screen">
            <div className="pt-10">
                <h1 className="grid text-4xl place-content-center font-semibold underline underline-offset-8 decoration-1 mb-10">Incident Report's</h1>
            </div>
            {reports.map((report) => {
                return <div
                            className="bg-white p-10 mb-10 ml-[25%] mr-[25%] rounded-lg shadow-xl shadow-gray-500"
                            key={report.id}
                            >
                    {" "}
                <div className="flex justify-between">
                    <h1 className="text-2xl mb-6 font-semibold underline underline-offset-8 decoration-1">{report.title}</h1>
                    <div className="flex items-end pb-4">
                    <h1 className="font-semibold mr-2">Date of report:</h1>
                    <h1>{report.dateReport}</h1>
                    </div>
                </div>
                <p className="mb-10">{report.description}</p>
                <div className="flex justify-between">
                    <div>
                        <div className="flex">
                            <h1 className="font-semibold mr-2">Patroller's name:</h1>
                            <h1>{report.patrollerName}</h1>
                        </div>
                        <div className="flex">
                            <h1 className="font-semibold mr-2">Location:</h1>
                            <h1>{report.location}</h1>
                        </div>
                        <div className="flex">
                            <h1 className="font-semibold mr-2">Date of incident:</h1>
                            <h1>{report.date}</h1>
                        </div>
                        <div className="flex">
                            <h1 className="font-semibold mr-2">Time of incident:</h1>
                            <h1>{report.time}</h1>
                        </div>
                    </div>
                    <div className="flex items-end">
                        <button
                        className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded mr-2 shadow-xl "
                        onClick={updateReport}
                        >
                        Edit
                        </button>
                        <button
                        className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded shadow-xl"
                        onClick={() => {deleteReport(report.id)}}
                        >
                        Delete
                        </button>
                    </div>
                </div>
            </div>
            })}

        </main>
    )
}

export default IncidentReportPage;
</code>```

This is what i have on my DashBoardform.

```import { useState } from "react"
import { db } from "./firebase";
import { collection, addDoc } from "firebase/firestore";
import { storage } from "./firebase";
import { getDownloadURL, ref, uploadBytes } from 'firebase/storage';
import { v4 } from 'uuid';
import { useNavigate } from "react-router-dom";

const DashBoardForm = () => {
  const [newTitle, setNewTitle] =useState();
  const [newPatrollerName, setNewPatrollerName] =useState();
  const [newTime, setNewTime] =useState();
  const [newDate, setNewDate] =useState();
  const [newDateReport, setNewDateReport] =useState();
  const [newLocation, setNewLocation] =useState();
  const [newDescription, setNewDescription] =useState();
  const [imageUpload, setImageUpload] = useState();
  const [newStoryTitle, setNewStoryTitle] = useState();
  const [newStoryContent, setNewStoryContent] = useState();
  const [storyImageUpload, setStoryImageUpload] = useState();
  const navigate = useNavigate();
  const usersCollecctionRef = collection(db, "reports");
  const usersCollecctionRef2 = collection(db, "storys");

const addReport = async (e) => {
    e.preventDefault();
    await addDoc(usersCollecctionRef, { title: newTitle, patrollerName: newPatrollerName, time: newTime, date: newDate, dateReport: newDateReport, location: newLocation, description: newDescription });
    navigate('/IncidentReportPage')
  }

  const addStory = async (e) => {
    e.preventDefault();
    const URL = await uploadStoryImage();
    await addDoc(usersCollecctionRef2, { storyTitle: newStoryTitle, contents: newStoryContent, image: URL });
    navigate('/LandingPage')
  }

  const uploadStoryImage = async (e) => {
    if (storyImageUpload == null) return;
    const storyImageRef = ref(storage, `storyImages/${storyImageUpload.name + v4()}`);
    return uploadBytes(storyImageRef, storyImageUpload).then((uploadResult) => {
      return getDownloadURL(uploadResult.ref).then((downloadURL) => {
        return downloadURL
      })
    })
  };

  const uploadImage = (e) => {
    e.preventDefault();
    if (imageUpload == null) return;

    const imageRef = ref(storage, `galleryImages/${imageUpload.name + v4()}`);
    uploadBytes(imageRef, imageUpload).then(() => {
      navigate('/GalleryPage')
    })
  };

return (
      <>

Add Images to Gallery

                  To add images to gallery page, add file's to input

              <form action="#">

                        Image Input

                            Input files here
                            <input
                              className="form-control
                                block
                                w-full
                                px-3
                                py-1.5
                                text-base
                                font-normal
                                text-gray-700
                                bg-white bg-clip-padding
                                border border-solid border-gray-500
                                rounded
                                transition
                                ease-in-out
                                m-0
                                focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none"
                              type="file"
                              id="formFileMultiple"
                              multiple
                              onChange={(event) => {
                                setImageUpload(event.target.files[0]);
                              }}
                              />

                    <button
                      className="inline-flex justify-center rounded-md border border-transparent bg-gray-800 py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
                      onClick={uploadImage}
                    >
                      Submit
                    </button>

              </form>

Incident Report

To create incident report add information in inputs

              <form action="#">

                          Title

                        <input
                          type="text"
                          name="title"
                          id="title"
                          autoComplete="title"
                          placeholder="Incident Title"
                          className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                          onChange={(event) => {
                            setNewTitle(event.target.value);
                          }}
                        />

                                Patroller's name
                                <input
                                type="text"
                                className="
                                    form-control
                                    block
                                    w-full
                                    px-3
                                    py-1.5
                                    text-base
                                    font-normal
                                    text-gray-700
                                    bg-white bg-clip-padding
                                    border border-solid border-gray-300
                                    rounded
                                    transition
                                    ease-in-out
                                    m-0
                                    focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none
                                "
                                id="PatrollersName"
                                placeholder="Name"
                                onChange={(event) => {
                                  setNewPatrollerName(event.target.value);
                                }}
                                />

                                Time of Incident
                                <input
                                type="number"
                                className="
                                    form-control
                                    block
                                    w-full
                                    px-3
                                    py-1.5
                                    text-base
                                    font-normal
                                    text-gray-700
                                    bg-white bg-clip-padding
                                    border border-solid border-gray-300
                                    rounded
                                    transition
                                    ease-in-out
                                    m-0
                                    focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none
                                "
                                id="time"
                                placeholder="Time"
                                onChange={(event) => {
                                  setNewTime(event.target.value);
                                }}
                                />

                                Date of Incident
                                <input
                                type="Date"
                                className="
                                    form-control
                                    block
                                    w-full
                                    px-3
                                    py-1.5
                                    text-base
                                    font-normal
                                    text-gray-700
                                    bg-white bg-clip-padding
                                    border border-solid border-gray-300
                                    rounded
                                    transition
                                    ease-in-out
                                    m-0
                                    focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none
                                "
                                id="DateOfIncident"
                                onChange={(event) => {
                                  setNewDate(event.target.value);
                                }}
                                />

                                Date of Report
                                <input
                                type="Date"
                                className="
                                    form-control
                                    block
                                    w-full
                                    px-3
                                    py-1.5
                                    text-base
                                    font-normal
                                    text-gray-700
                                    bg-white bg-clip-padding
                                    border border-solid border-gray-300
                                    rounded
                                    transition
                                    ease-in-out
                                    m-0
                                    focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none
                                "
                                id="DateOfReport"
                                onChange={(event) => {
                                  setNewDateReport(event.target.value);
                                }}
                                />

                          Location of Incident

                        <input
                          type="text"
                          name="LocationOfIncident"
                          id="LocationOfIncident"
                          autoComplete="Location-of-incident"
                          placeholder="Location"
                          className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                          onChange={(event) => {
                            setNewLocation(event.target.value);
                          }}
                        />

                            Incident Desciption
                            <textarea
                            type="text"
                            className="
                                form-control
                                block
                                w-full
                                px-3
                                py-1.5
                                text-base
                                font-normal
                                text-gray-700
                                bg-white bg-clip-padding
                                border border-solid border-gray-300
                                rounded
                                transition
                                ease-in-out
                                m-0
                                focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none
                                resize
                            "
                            id="incidentDesciption"
                            rows="10"
                            placeholder="Desciption"
                            onChange={(event) => {
                              setNewDescription(event.target.value);
                            }}
                            ></textarea>

To make the window larger click and drag the bottem right corner

                    <button
                      className="mr-5 inline-flex justify-center rounded-md border border-transparent bg-gray-800 py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
                      onClick={addReport}
                    >
                      Save
                    </button>

              </form>

News Story

To create news storys add information in inputs

              <form action="#">

                          Title

                        <input
                          type="text"
                          name="title"
                          id="title"
                          autoComplete="title"
                          placeholder="Story Title"
                          className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                          onChange={(event) => {
                            setNewStoryTitle(event.target.value);
                          }}
                        />

                              Story Description
                              <textarea
                              type="text"
                              className="
                                  form-control
                                  block
                                  w-full
                                  px-3
                                  py-1.5
                                  text-base
                                  font-normal
                                  text-gray-700
                                  bg-white bg-clip-padding
                                  border border-solid border-gray-300
                                  rounded
                                  transition
                                  ease-in-out
                                  m-0
                                  focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none
                                  resize
                              "
                              id="storyDesciption"
                              rows="10"
                              placeholder="Story Contents"
                              onChange={(event) => {
                                setNewStoryContent(event.target.value);
                              }}
                              ></textarea>

To make the window larger click and drag the bottem right corner

                        Image Input

                          <input
                            className="form-control
                                block
                                w-full
                                px-3
                                py-1.5
                                text-base
                                font-normal
                                text-gray-700
                                bg-white bg-clip-padding
                                border border-solid border-gray-500
                                rounded
                                transition
                                ease-in-out
                                m-0
                                focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none"
                            type="file"
                            id="formFileMultiple"
                            multiple
                            onChange={(event) => {
                              setStoryImageUpload(event.target.files[0]);
                            }}
                          />

Input image here

                    <button
                      className="mr-5 inline-flex justify-center rounded-md border border-transparent bg-gray-800 py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
                      onClick={addStory}
                    >
                      Save
                    </button>

              </form>

      </>
    )
  }

export default DashBoardForm

```

Body:
I have been building a react app and have been trying to get the edit functionality to work for awhile but just cant get it right. I have a page where information gets displayed(IncidentReportPage) and another page where the information that gets displayed is input(DashboardForm). When the edit button is clicked on the IncidentReportPage where the information is getting displayed i want to be taken back to the DashboardForm where the previously inputted data should be populated back into the inputs and able to be edited. The save button will also need to be changed to edit the information when clicked rather than submit a whole new instance of the component being created.

This is the code from the IncidentReportPage. I have created an update function already but unable to get it to do what i require.

import { useEffect, useState } from "react";
import { db } from "./firebase";
import { collection, getDocs, deleteDoc, doc, updateDoc } from "firebase/firestore";
import { useNavigate } from "react-router-dom";

const IncidentReportPage = (props) => {
    const [reports, setReports] = useState([]);
    const usersCollectionRef = collection(db, 'reports');
    const navigate = useNavigate();

    const deleteReport = async (id) => {
        const reportDoc = doc(db, "reports", id);
        await deleteDoc(reportDoc);
      };

    const updateReport = async (id, title, description, patrollerName, location, date, time, dateReport) => {
        const userDoc = doc(db, 'reports', id, title, description, patrollerName, location, date, time, dateReport);
        await updateDoc(userDoc);
        navigate('/Dashboard')
    }

    useEffect(() => {
        const getReports = async () => {
            const reportData = await getDocs(usersCollectionRef);
            setReports(reportData.docs.map((doc) => ({...doc.data(), id: doc.id })));
        };

        getReports();
    },)

    useEffect(() => {
        if (props.funcNav) {
          props.funcNav(true)
        }
      })

 return (

Incident Report's

            {reports.map((report) => {
                return

                    {" "}

{report.title}

Date of report:

{report.dateReport}

{report.description}

Patroller's name:

{report.patrollerName}

Location:

{report.location}

Date of incident:

{report.date}

Time of incident:

{report.time}

                        <button
                        className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded mr-2 shadow-xl "
                        onClick={updateReport}
                        >
                        Edit
                        </button>
                        <button
                        className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded shadow-xl"
                        onClick={() => {deleteReport(report.id)}}
                        >
                        Delete
                        </button>

            })}

    )
}

export default IncidentReportPage;

This is what i have on my DashBoardform.

import { useState } from "react"
import { db } from "./firebase";
import { collection, addDoc } from "firebase/firestore";
import { storage } from "./firebase";
import { getDownloadURL, ref, uploadBytes } from 'firebase/storage';
import { v4 } from 'uuid';
import { useNavigate } from "react-router-dom";

const DashBoardForm = () => {
  const [newTitle, setNewTitle] =useState();
  const [newPatrollerName, setNewPatrollerName] =useState();
  const [newTime, setNewTime] =useState();
  const [newDate, setNewDate] =useState();
  const [newDateReport, setNewDateReport] =useState();
  const [newLocation, setNewLocation] =useState();
  const [newDescription, setNewDescription] =useState();
  const [imageUpload, setImageUpload] = useState();
  const [newStoryTitle, setNewStoryTitle] = useState();
  const [newStoryContent, setNewStoryContent] = useState();
  const [storyImageUpload, setStoryImageUpload] = useState();
  const navigate = useNavigate();
  const usersCollecctionRef = collection(db, "reports");
  const usersCollecctionRef2 = collection(db, "storys");

const addReport = async (e) => {
    e.preventDefault();
    await addDoc(usersCollecctionRef, { title: newTitle, patrollerName: newPatrollerName, time: newTime, date: newDate, dateReport: newDateReport, location: newLocation, description: newDescription });
    navigate('/IncidentReportPage')
  }

  const addStory = async (e) => {
    e.preventDefault();
    const URL = await uploadStoryImage();
    await addDoc(usersCollecctionRef2, { storyTitle: newStoryTitle, contents: newStoryContent, image: URL });
    navigate('/LandingPage')
  }

  const uploadStoryImage = async (e) => {
    if (storyImageUpload == null) return;
    const storyImageRef = ref(storage, `storyImages/${storyImageUpload.name + v4()}`);
    return uploadBytes(storyImageRef, storyImageUpload).then((uploadResult) => {
      return getDownloadURL(uploadResult.ref).then((downloadURL) => {
        return downloadURL
      })
    })
  };

  const uploadImage = (e) => {
    e.preventDefault();
    if (imageUpload == null) return;

    const imageRef = ref(storage, `galleryImages/${imageUpload.name + v4()}`);
    uploadBytes(imageRef, imageUpload).then(() => {
      navigate('/GalleryPage')
    })
  };

return (
      <>

Add Images to Gallery

                  To add images to gallery page, add file's to input

              <form action="#">

                        Image Input

                            Input files here
                            <input
                              className="form-control
                                block
                                w-full
                                px-3
                                py-1.5
                                text-base
                                font-normal
                                text-gray-700
                                bg-white bg-clip-padding
                                border border-solid border-gray-500
                                rounded
                                transition
                                ease-in-out
                                m-0
                                focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none"
                              type="file"
                              id="formFileMultiple"
                              multiple
                              onChange={(event) => {
                                setImageUpload(event.target.files[0]);
                              }}
                              />

                    <button
                      className="inline-flex justify-center rounded-md border border-transparent bg-gray-800 py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
                      onClick={uploadImage}
                    >
                      Submit
                    </button>

              </form>

Incident Report

To create incident report add information in inputs

              <form action="#">

                          Title

                        <input
                          type="text"
                          name="title"
                          id="title"
                          autoComplete="title"
                          placeholder="Incident Title"
                          className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                          onChange={(event) => {
                            setNewTitle(event.target.value);
                          }}
                        />

                                Patroller's name
                                <input
                                type="text"
                                className="
                                    form-control
                                    block
                                    w-full
                                    px-3
                                    py-1.5
                                    text-base
                                    font-normal
                                    text-gray-700
                                    bg-white bg-clip-padding
                                    border border-solid border-gray-300
                                    rounded
                                    transition
                                    ease-in-out
                                    m-0
                                    focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none
                                "
                                id="PatrollersName"
                                placeholder="Name"
                                onChange={(event) => {
                                  setNewPatrollerName(event.target.value);
                                }}
                                />

                                Time of Incident
                                <input
                                type="number"
                                className="
                                    form-control
                                    block
                                    w-full
                                    px-3
                                    py-1.5
                                    text-base
                                    font-normal
                                    text-gray-700
                                    bg-white bg-clip-padding
                                    border border-solid border-gray-300
                                    rounded
                                    transition
                                    ease-in-out
                                    m-0
                                    focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none
                                "
                                id="time"
                                placeholder="Time"
                                onChange={(event) => {
                                  setNewTime(event.target.value);
                                }}
                                />

                                Date of Incident
                                <input
                                type="Date"
                                className="
                                    form-control
                                    block
                                    w-full
                                    px-3
                                    py-1.5
                                    text-base
                                    font-normal
                                    text-gray-700
                                    bg-white bg-clip-padding
                                    border border-solid border-gray-300
                                    rounded
                                    transition
                                    ease-in-out
                                    m-0
                                    focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none
                                "
                                id="DateOfIncident"
                                onChange={(event) => {
                                  setNewDate(event.target.value);
                                }}
                                />

                                Date of Report
                                <input
                                type="Date"
                                className="
                                    form-control
                                    block
                                    w-full
                                    px-3
                                    py-1.5
                                    text-base
                                    font-normal
                                    text-gray-700
                                    bg-white bg-clip-padding
                                    border border-solid border-gray-300
                                    rounded
                                    transition
                                    ease-in-out
                                    m-0
                                    focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none
                                "
                                id="DateOfReport"
                                onChange={(event) => {
                                  setNewDateReport(event.target.value);
                                }}
                                />

                          Location of Incident

                        <input
                          type="text"
                          name="LocationOfIncident"
                          id="LocationOfIncident"
                          autoComplete="Location-of-incident"
                          placeholder="Location"
                          className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                          onChange={(event) => {
                            setNewLocation(event.target.value);
                          }}
                        />

                            Incident Desciption
                            <textarea
                            type="text"
                            className="
                                form-control
                                block
                                w-full
                                px-3
                                py-1.5
                                text-base
                                font-normal
                                text-gray-700
                                bg-white bg-clip-padding
                                border border-solid border-gray-300
                                rounded
                                transition
                                ease-in-out
                                m-0
                                focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none
                                resize
                            "
                            id="incidentDesciption"
                            rows="10"
                            placeholder="Desciption"
                            onChange={(event) => {
                              setNewDescription(event.target.value);
                            }}
                            ></textarea>

To make the window larger click and drag the bottem right corner

                    <button
                      className="mr-5 inline-flex justify-center rounded-md border border-transparent bg-gray-800 py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
                      onClick={addReport}
                    >
                      Save
                    </button>

              </form>

News Story

To create news storys add information in inputs

              <form action="#">

                          Title

                        <input
                          type="text"
                          name="title"
                          id="title"
                          autoComplete="title"
                          placeholder="Story Title"
                          className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                          onChange={(event) => {
                            setNewStoryTitle(event.target.value);
                          }}
                        />

                              Story Description
                              <textarea
                              type="text"
                              className="
                                  form-control
                                  block
                                  w-full
                                  px-3
                                  py-1.5
                                  text-base
                                  font-normal
                                  text-gray-700
                                  bg-white bg-clip-padding
                                  border border-solid border-gray-300
                                  rounded
                                  transition
                                  ease-in-out
                                  m-0
                                  focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none
                                  resize
                              "
                              id="storyDesciption"
                              rows="10"
                              placeholder="Story Contents"
                              onChange={(event) => {
                                setNewStoryContent(event.target.value);
                              }}
                              ></textarea>

To make the window larger click and drag the bottem right corner

                        Image Input

                          <input
                            className="form-control
                                block
                                w-full
                                px-3
                                py-1.5
                                text-base
                                font-normal
                                text-gray-700
                                bg-white bg-clip-padding
                                border border-solid border-gray-500
                                rounded
                                transition
                                ease-in-out
                                m-0
                                focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none"
                            type="file"
                            id="formFileMultiple"
                            multiple
                            onChange={(event) => {
                              setStoryImageUpload(event.target.files[0]);
                            }}
                          />

Input image here

                    <button
                      className="mr-5 inline-flex justify-center rounded-md border border-transparent bg-gray-800 py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
                      onClick={addStory}
                    >
                      Save
                    </button>

              </form>

      </>
    )
  }

export default DashBoardForm


问:
i want to select multiple items
```<code>this is my code

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

  @override
  State<HighestEducation> createState() => _HighestEducationState();
}

class _HighestEducationState extends State<HighestEducation> {
  int selectedPosition = -1;
  late Future<List<Region>> qualification;

  Region? selEdu;
  TextEditingController highestEducation = TextEditingController();

  NetWorkOperations ntop = NetWorkOperations();
  var education = [];
  final List<Region> _selEdu = [];
//List<bool> _checkBoxValues = [];
//bool x = false;

  @override
  void initState() {
    super.initState();

    qualification = ntop.getDropDownList(0, 5);
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
        shrinkWrap: true,
        scrollDirection: Axis.vertical,
        physics: const BouncingScrollPhysics(),
        children: [
          const AppText(
              text: 'HighestEducation', fontSize: 18, color: profileConnect1),
          12.hBox,
          Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: FutureBuilder<List<Region>>(
                  future: qualification,
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      int length = snapshot.data!.length;

                      for (int i = 0; i < length; i++) {
                        Region edu = snapshot.data![i];
                        education.add(edu.value);
                      }

                    return AppTextField(
                          suffixIcon: inputArrowDownIcon,
                          hint: 'M.Com',
                          controller: highestEducation,
                          enabledBorder: true,
                          suffixColor: captionInterest,
                          onTap: () => showOptionPicker(context,
                                  itemBuilder: (_, int index) {
                                if (education.length > 0) {
                                  return Padding(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 20.0),
                                    child: Center(
                                        child: AppText(
                                            fontSize: 15,
                                            text: education[index])),

                                      );
                                } else {
                                  return const Center(
                                    child: CircularProgressIndicator(),
                                  );
                                }
                              }, onDonePressed: (int selectedIndex) {
                                setState(() {
                                  highestEducation.text =
                                      education[selectedIndex];
                                });
                              }, itemCount: education.length));
                    } else if (snapshot.hasError) {
                      return Text('${snapshot.error}');
                    }
                    return const Center(
                      child: CircularProgressIndicator(),
                    );
                  }))
        ]);
  }
}

showOptionPicker code is

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:happy_nikah/ui/components/app_text.dart';
import 'package:happy_nikah/utils/colors.dart';

showOptionPicker(BuildContext context,
    {required Widget Function(BuildContext context, int index) itemBuilder,
    required void Function(int selectedItemIndex) onDonePressed,
    bool isMandatory = false,
    int defaultSelectedIndex = 0,
    required int itemCount}) {
  FixedExtentScrollController scrollController = FixedExtentScrollController(initialItem: defaultSelectedIndex);
  int selectedIndex = defaultSelectedIndex;

  showModalBottomSheet(
      enableDrag: false,
      backgroundColor: Colors.white,
      isScrollControlled: true,
      isDismissible: !isMandatory,
      context: context,
      builder: (context) {
        return Stack(clipBehavior: Clip.antiAlias, children: [
          SizedBox(
            height: 240,
            child: CupertinoPicker.builder(
              scrollController: scrollController,
              childCount: itemCount,
              itemExtent: 48,
              onSelectedItemChanged: (index) {
                selectedIndex = index;
              },
              itemBuilder: itemBuilder,
            ),
          ),
          Container(
            color: Colors.white,
            child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
              if (!isMandatory)
                CupertinoButton(
                    child: const AppText(text: 'Cancel', color: grey),
                    onPressed: () => Navigator.pop(context)),
              const Spacer(),
              CupertinoButton(
                  child: const AppText(text: 'Done', color: blue),
                  onPressed: () {
                    onDonePressed(selectedIndex);
                    Navigator.pop(context);
                  }),
            ]),
          ),
        ]);
      });
}

</code>```

i am new to  flutter and i dont know how to implement multiselection in my code using checkbox,here i am using an api to get data and i name it as "education" and i access the educationlevels from this api, i have to keep future builder and the logic what i used in my code, here i am using apptextfield as a customizes textfield ,   please help me to solve my issue,

Title: i want to select multiple items

Body:
this is my code

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

  @override
  State<HighestEducation> createState() => _HighestEducationState();
}

class _HighestEducationState extends State<HighestEducation> {
  int selectedPosition = -1;
  late Future<List<Region>> qualification;

  Region? selEdu;
  TextEditingController highestEducation = TextEditingController();

  NetWorkOperations ntop = NetWorkOperations();
  var education = [];
  final List<Region> _selEdu = [];
//List<bool> _checkBoxValues = [];
//bool x = false;

  @override
  void initState() {
    super.initState();

    qualification = ntop.getDropDownList(0, 5);
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
        shrinkWrap: true,
        scrollDirection: Axis.vertical,
        physics: const BouncingScrollPhysics(),
        children: [
          const AppText(
              text: 'HighestEducation', fontSize: 18, color: profileConnect1),
          12.hBox,
          Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: FutureBuilder<List<Region>>(
                  future: qualification,
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      int length = snapshot.data!.length;

                      for (int i = 0; i < length; i++) {
                        Region edu = snapshot.data![i];
                        education.add(edu.value);
                      }

                    return AppTextField(
                          suffixIcon: inputArrowDownIcon,
                          hint: 'M.Com',
                          controller: highestEducation,
                          enabledBorder: true,
                          suffixColor: captionInterest,
                          onTap: () => showOptionPicker(context,
                                  itemBuilder: (_, int index) {
                                if (education.length > 0) {
                                  return Padding(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 20.0),
                                    child: Center(
                                        child: AppText(
                                            fontSize: 15,
                                            text: education[index])),

                                      );
                                } else {
                                  return const Center(
                                    child: CircularProgressIndicator(),
                                  );
                                }
                              }, onDonePressed: (int selectedIndex) {
                                setState(() {
                                  highestEducation.text =
                                      education[selectedIndex];
                                });
                              }, itemCount: education.length));
                    } else if (snapshot.hasError) {
                      return Text('${snapshot.error}');
                    }
                    return const Center(
                      child: CircularProgressIndicator(),
                    );
                  }))
        ]);
  }
}

showOptionPicker code is

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:happy_nikah/ui/components/app_text.dart';
import 'package:happy_nikah/utils/colors.dart';

showOptionPicker(BuildContext context,
    {required Widget Function(BuildContext context, int index) itemBuilder,
    required void Function(int selectedItemIndex) onDonePressed,
    bool isMandatory = false,
    int defaultSelectedIndex = 0,
    required int itemCount}) {
  FixedExtentScrollController scrollController = FixedExtentScrollController(initialItem: defaultSelectedIndex);
  int selectedIndex = defaultSelectedIndex;

  showModalBottomSheet(
      enableDrag: false,
      backgroundColor: Colors.white,
      isScrollControlled: true,
      isDismissible: !isMandatory,
      context: context,
      builder: (context) {
        return Stack(clipBehavior: Clip.antiAlias, children: [
          SizedBox(
            height: 240,
            child: CupertinoPicker.builder(
              scrollController: scrollController,
              childCount: itemCount,
              itemExtent: 48,
              onSelectedItemChanged: (index) {
                selectedIndex = index;
              },
              itemBuilder: itemBuilder,
            ),
          ),
          Container(
            color: Colors.white,
            child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
              if (!isMandatory)
                CupertinoButton(
                    child: const AppText(text: 'Cancel', color: grey),
                    onPressed: () => Navigator.pop(context)),
              const Spacer(),
              CupertinoButton(
                  child: const AppText(text: 'Done', color: blue),
                  onPressed: () {
                    onDonePressed(selectedIndex);
                    Navigator.pop(context);
                  }),
            ]),
          ),
        ]);
      });
}

i am new to  flutter and i dont know how to implement multiselection in my code using checkbox,here i am using an api to get data and i name it as "education" and i access the educationlevels from this api, i have to keep future builder and the logic what i used in my code, here i am using apptextfield as a customizes textfield ,   please help me to solve my issue,


问:
Why node-forge package is not serving angular application?
When I try to implement the RSA algorithm in my angular application to encrypt the data using the node-forge npm package, the application does not respond.

I have installed the below packages using the below commands:

```<code>npm i node-forge
npm install @types/node-forge
</code>```

Package.json:

```<code>......
{
  "name": "mavro-customer-portal",
  "version": "0.0.1",
  "description": "Mavro Customer Portal",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "postinstall": "ngcc --properties es2015 browser module main --first-only",
    "start": "ng serve",
    "build": "ng build --prod --aot --build-optimizer --common-chunk --vendor-chunk --optimization --progress",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "prettier": "prettier --write \"{,!(node_modules|dist|build|coverage)/**/}*.{js,jsx,ts,json}\"",
    "pre-commit": "npm run lint && npm run prettier",
    "extract-i18n": "ngx-translate-extract --input ./src --output ./src/assets/i18n/{en,nl,fr,es,it,de}.json --format namespaced-json --sort",
    "prepare": "husky install"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^11.1.0",
    "@angular/cdk": "^11.1.0",
    "@angular/common": "^11.1.0",
    "@angular/compiler": "^11.1.0",
    "@angular/core": "^11.1.0",
    "@angular/forms": "^11.1.0",
    "@angular/localize": "^11.1.0",
    "@angular/platform-browser": "^11.1.0",
    "@angular/platform-browser-dynamic": "^11.1.0",
    "@angular/router": "^11.1.0",
    "@coreui/angular": "~2.11.1",
    "@coreui/coreui": "^2.1.16",
    "@coreui/coreui-plugin-chartjs-custom-tooltips": "^1.3.1",
    "@coreui/icons": "^2.0.0-rc.0",
    "@coreui/icons-angular": "1.0.0-alpha.3",
    "@fortawesome/angular-fontawesome": "^0.8.2",
    "@fortawesome/fontawesome-svg-core": "^1.2.34",
    "@fortawesome/free-brands-svg-icons": "^5.15.2",
    "@fortawesome/free-regular-svg-icons": "^5.15.2",
    "@fortawesome/free-solid-svg-icons": "^5.15.2",
    "@ng-select/ng-select": "^6.1.0",
    "@ngrx/store": "^11.0.1",
    "@ngx-translate/core": "^13.0.0",
    "@ngx-translate/http-loader": "^6.0.0",
    "@rxweb/reactive-form-validators": "^2.1.2",
    "@types/node-forge": "^1.3.1",
    "@uiowa/digit-only": "^2.2.3",
    "ag-grid-angular": "^25.1.0",
    "ag-grid-community": "^25.1.0",
    "bootstrap": "^4.6.0",
    "bs-stepper": "^1.7.0",
    "chart.js": "^2.9.4",
    "classlist.js": "^1.1.20150312",
    "cookieconsent": "^3.1.1",
    "core-js": "^3.8.3",
    "lodash": "^4.17.21",
    "messageformat": "^2.3.0",
    "mock-component": "^5.1.0",
    "moment": "^2.29.1",
    "moment-timezone": "^0.5.33",
    "ng-lazyload-image": "^9.1.0",
    "ng-mocks": "^14.4.0",
    "ngrx-store-localstorage": "^11.0.0",
    "ngx-avatar": "^4.1.0",
    "ngx-bootstrap": "^6.2.0",
    "ngx-cookieconsent": "^2.2.3",
    "ngx-editor": "^9.0.2",
    "ngx-perfect-scrollbar": "^10.1.0",
    "ngx-toastr": "^13.2.1",
    "ngx-translate-cache": "^9.0.2",
    "ngx-translate-messageformat-compiler": "^4.9.0",
    "node-forge": "^1.3.1",
    "primeflex": "^2.0.0",
    "primeicons": "^4.1.0",
    "primeng": "^11.2.3",
    "rxjs": "^6.6.3",
    "simple-line-icons": "^2.5.5",
    "ts-helpers": "^1.1.2",
    "tslib": "^2.0.0",
    "web-animations-js": "^2.3.2",
    "zone.js": "~0.10.3"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.1101.1",
    "@angular/cli": "^11.1.1",
    "@angular/compiler-cli": "^11.1.0",
    "@angular/language-service": "^11.1.0",
    "@biesbjerg/ngx-translate-extract": "^7.0.3",
    "@types/jasmine": "^3.6.3",
    "@types/jasminewd2": "^2.0.8",
    "@types/lodash": "^4.14.182",
    "@types/node": "^14.14.22",
    "codelyzer": "^6.0.0",
    "husky": "^8.0.1",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "^5.2.3",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "^2.2.0",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "prettier": "^2.7.1",
    "protractor": "~7.0.0",
    "ts-node": "^8.10.2",
    "tslint": "~6.1.0",
    "typescript": "~4.0.5"
  },
  "engines": {
    "node": ">= 10.13",
    "npm": "= 6.11.0"
  }
}

</code>```

RSA-helper.service.ts file:

```<code>import { Injectable } from '@angular/core';
import * as Forge from 'node-forge';

@Injectable({
  providedIn: 'root'
})
export class RsaHelperService {

  constructor() { }

  key:string = `  ....  `;

  encryptWithPublicKey(valueToEncrypt: string = "vijay..."): string {
    const rsa = Forge.pki.publicKeyFromPem(this.key);
    console.log(rsa);
    return window.btoa(rsa.encrypt(valueToEncrypt.toString()));
    }
}

</code>```

NOTE::
It does not show any error message even in the console. But the application goes blank.

Body:
When I try to implement the RSA algorithm in my angular application to encrypt the data using the node-forge npm package, the application does not respond.

I have installed the below packages using the below commands:

npm i node-forge
npm install @types/node-forge

Package.json:

......
{
  "name": "mavro-customer-portal",
  "version": "0.0.1",
  "description": "Mavro Customer Portal",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "postinstall": "ngcc --properties es2015 browser module main --first-only",
    "start": "ng serve",
    "build": "ng build --prod --aot --build-optimizer --common-chunk --vendor-chunk --optimization --progress",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "prettier": "prettier --write \"{,!(node_modules|dist|build|coverage)/**/}*.{js,jsx,ts,json}\"",
    "pre-commit": "npm run lint && npm run prettier",
    "extract-i18n": "ngx-translate-extract --input ./src --output ./src/assets/i18n/{en,nl,fr,es,it,de}.json --format namespaced-json --sort",
    "prepare": "husky install"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^11.1.0",
    "@angular/cdk": "^11.1.0",
    "@angular/common": "^11.1.0",
    "@angular/compiler": "^11.1.0",
    "@angular/core": "^11.1.0",
    "@angular/forms": "^11.1.0",
    "@angular/localize": "^11.1.0",
    "@angular/platform-browser": "^11.1.0",
    "@angular/platform-browser-dynamic": "^11.1.0",
    "@angular/router": "^11.1.0",
    "@coreui/angular": "~2.11.1",
    "@coreui/coreui": "^2.1.16",
    "@coreui/coreui-plugin-chartjs-custom-tooltips": "^1.3.1",
    "@coreui/icons": "^2.0.0-rc.0",
    "@coreui/icons-angular": "1.0.0-alpha.3",
    "@fortawesome/angular-fontawesome": "^0.8.2",
    "@fortawesome/fontawesome-svg-core": "^1.2.34",
    "@fortawesome/free-brands-svg-icons": "^5.15.2",
    "@fortawesome/free-regular-svg-icons": "^5.15.2",
    "@fortawesome/free-solid-svg-icons": "^5.15.2",
    "@ng-select/ng-select": "^6.1.0",
    "@ngrx/store": "^11.0.1",
    "@ngx-translate/core": "^13.0.0",
    "@ngx-translate/http-loader": "^6.0.0",
    "@rxweb/reactive-form-validators": "^2.1.2",
    "@types/node-forge": "^1.3.1",
    "@uiowa/digit-only": "^2.2.3",
    "ag-grid-angular": "^25.1.0",
    "ag-grid-community": "^25.1.0",
    "bootstrap": "^4.6.0",
    "bs-stepper": "^1.7.0",
    "chart.js": "^2.9.4",
    "classlist.js": "^1.1.20150312",
    "cookieconsent": "^3.1.1",
    "core-js": "^3.8.3",
    "lodash": "^4.17.21",
    "messageformat": "^2.3.0",
    "mock-component": "^5.1.0",
    "moment": "^2.29.1",
    "moment-timezone": "^0.5.33",
    "ng-lazyload-image": "^9.1.0",
    "ng-mocks": "^14.4.0",
    "ngrx-store-localstorage": "^11.0.0",
    "ngx-avatar": "^4.1.0",
    "ngx-bootstrap": "^6.2.0",
    "ngx-cookieconsent": "^2.2.3",
    "ngx-editor": "^9.0.2",
    "ngx-perfect-scrollbar": "^10.1.0",
    "ngx-toastr": "^13.2.1",
    "ngx-translate-cache": "^9.0.2",
    "ngx-translate-messageformat-compiler": "^4.9.0",
    "node-forge": "^1.3.1",
    "primeflex": "^2.0.0",
    "primeicons": "^4.1.0",
    "primeng": "^11.2.3",
    "rxjs": "^6.6.3",
    "simple-line-icons": "^2.5.5",
    "ts-helpers": "^1.1.2",
    "tslib": "^2.0.0",
    "web-animations-js": "^2.3.2",
    "zone.js": "~0.10.3"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.1101.1",
    "@angular/cli": "^11.1.1",
    "@angular/compiler-cli": "^11.1.0",
    "@angular/language-service": "^11.1.0",
    "@biesbjerg/ngx-translate-extract": "^7.0.3",
    "@types/jasmine": "^3.6.3",
    "@types/jasminewd2": "^2.0.8",
    "@types/lodash": "^4.14.182",
    "@types/node": "^14.14.22",
    "codelyzer": "^6.0.0",
    "husky": "^8.0.1",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "^5.2.3",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "^2.2.0",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "prettier": "^2.7.1",
    "protractor": "~7.0.0",
    "ts-node": "^8.10.2",
    "tslint": "~6.1.0",
    "typescript": "~4.0.5"
  },
  "engines": {
    "node": ">= 10.13",
    "npm": "= 6.11.0"
  }
}

RSA-helper.service.ts file:

import { Injectable } from '@angular/core';
import * as Forge from 'node-forge';

@Injectable({
  providedIn: 'root'
})
export class RsaHelperService {

  constructor() { }

  key:string = `  ....  `;

  encryptWithPublicKey(valueToEncrypt: string = "vijay..."): string {
    const rsa = Forge.pki.publicKeyFromPem(this.key);
    console.log(rsa);
    return window.btoa(rsa.encrypt(valueToEncrypt.toString()));
    }
}

NOTE::
It does not show any error message even in the console. But the application goes blank.


问:
Question: Unity3D 3d models non-uniform scaling
I have to rotate a 3d model (by LookAt) in unity but it has non-uniform scale

So the question is: Can I convert non-uniform scale to 1,1,1 or I need another 3d model?

Image


问:
How to type in netbean's IDE terminal?
I tried a program and after program run when I tried to enter user inputs they are not typing?

I tried to enter user inputs they're not typing

Title: How to type in netbean's IDE terminal?


问:
Automotive app crashes when clicking in searchfield after started typing
I have a problem with the keyboard/softinput in my Android Automotive application. I am using the SearchTemplate, and when I click in the search field after typing some letters, the app crashes. It happens if I click the magnifier-icon, or the text-field, but not the x-button (which empties the field). This only happens if I have started typing some letters in the search field. If the search field is empty and I click it, the only thing that happens is that it is focused.

This is the error message:

```<code>D/InputMethodManager: showSoftInput() view=androidx.car.app.activity.renderer.surface.TemplateSurfaceView{f2a6fbc VFE...... .F...... 0,0-1024,768 #7f0900ae app:id/template_view_surface aid=1073741824} flags=0 reason=SHOW_SOFT_INPUT
E/CarApp.Act: Connection lost
    android.os.DeadObjectException
        at android.os.BinderProxy.transactNative(Native Method)
        at android.os.BinderProxy.transact(BinderProxy.java:571)
        at androidx.car.app.activity.renderer.IRendererCallback$Stub$Proxy.onCreateInputConnection(IRendererCallback.java:297)
        at androidx.car.app.activity.BaseCarAppActivity$2.lambda$registerRendererCallback$1(BaseCarAppActivity.java:178)
        at androidx.car.app.activity.BaseCarAppActivity$2$$ExternalSyntheticLambda6.invoke(Unknown Source:4)
        at androidx.car.app.activity.ServiceDispatcher.fetch(ServiceDispatcher.java:116)
        at androidx.car.app.activity.BaseCarAppActivity$2.lambda$registerRendererCallback$2$androidx-car-app-activity-BaseCarAppActivity$2(BaseCarAppActivity.java:176)
        at androidx.car.app.activity.BaseCarAppActivity$2$$ExternalSyntheticLambda4.onCreateInputConnection(Unknown Source:4)
        at androidx.car.app.activity.renderer.surface.TemplateSurfaceView.onCreateInputConnection(TemplateSurfaceView.java:160)
        at android.view.inputmethod.InputMethodManager.startInputInner(InputMethodManager.java:1928)
        at android.view.inputmethod.InputMethodManager.restartInput(InputMethodManager.java:1858)
        at androidx.car.app.activity.renderer.surface.TemplateSurfaceView.onStartInput(TemplateSurfaceView.java:210)
        at androidx.car.app.activity.BaseCarAppActivity$2.lambda$onStartInput$7$androidx-car-app-activity-BaseCarAppActivity$2(BaseCarAppActivity.java:213)
        at androidx.car.app.activity.BaseCarAppActivity$2$$ExternalSyntheticLambda8.run(Unknown Source:2)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7870)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
E/CarApp.Act: Remote exception (host render service)
    android.os.DeadObjectException
        at android.os.BinderProxy.transactNative(Native Method)
        at android.os.BinderProxy.transact(BinderProxy.java:571)
        at androidx.car.app.activity.renderer.surface.ISurfaceListener$Stub$Proxy.onSurfaceDestroyed(ISurfaceListener.java:181)
        at androidx.car.app.activity.renderer.surface.SurfaceHolderListener.lambda$notifySurfaceDestroyed$2$androidx-car-app-activity-renderer-surface-SurfaceHolderListener(SurfaceHolderListener.java:103)
        at androidx.car.app.activity.renderer.surface.SurfaceHolderListener$$ExternalSyntheticLambda1.invoke(Unknown Source:4)
        at androidx.car.app.activity.ServiceDispatcher.lambda$dispatchNoFail$1(ServiceDispatcher.java:90)
        at androidx.car.app.activity.ServiceDispatcher$$ExternalSyntheticLambda1.invoke(Unknown Source:2)
        at androidx.car.app.activity.ServiceDispatcher.fetchNoFail(ServiceDispatcher.java:153)
        at androidx.car.app.activity.ServiceDispatcher.dispatchNoFail(ServiceDispatcher.java:89)
        at androidx.car.app.activity.renderer.surface.SurfaceHolderListener.notifySurfaceDestroyed(SurfaceHolderListener.java:102)
        at androidx.car.app.activity.renderer.surface.SurfaceHolderListener.surfaceDestroyed(SurfaceHolderListener.java:78)
        at android.view.SurfaceView.notifySurfaceDestroyed(SurfaceView.java:1981)
        at android.view.SurfaceView.updateSurface(SurfaceView.java:1157)
        at android.view.SurfaceView.setVisibility(SurfaceView.java:345)
        at androidx.car.app.activity.BaseCarAppActivity.lambda$onStateChanged$3$androidx-car-app-activity-BaseCarAppActivity(BaseCarAppActivity.java:399)
        at androidx.car.app.activity.BaseCarAppActivity$$ExternalSyntheticLambda3.run(Unknown Source:4)
        at androidx.car.app.utils.ThreadUtils.runOnMain(ThreadUtils.java:39)
        at androidx.car.app.activity.BaseCarAppActivity.onStateChanged(BaseCarAppActivity.java:385)
        at androidx.car.app.activity.BaseCarAppActivity.$r8$lambda$dw3rK9QfgsUWuk2bAICsaK01RZs(Unknown Source:0)
        at androidx.car.app.activity.BaseCarAppActivity$$ExternalSyntheticLambda5.onChanged(Unknown Source:4)
        at androidx.lifecycle.LiveData.considerNotify(LiveData.java:133)
        at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:151)
        at androidx.lifecycle.LiveData.setValue(LiveData.java:309)
        at androidx.lifecycle.MutableLiveData.setValue(MutableLiveData.java:50)
        at androidx.car.app.activity.CarAppViewModel.lambda$onError$0$androidx-car-app-activity-CarAppViewModel(CarAppViewModel.java:185)
        at androidx.car.app.activity.CarAppViewModel$$ExternalSyntheticLambda2.run(Unknown Source:4)
        at androidx.car.app.utils.ThreadUtils.runOnMain(ThreadUtils.java:39)
        at androidx.car.app.activity.CarAppViewModel.onError(CarAppViewModel.java:177)
        at androidx.car.app.activity.ServiceDispatcher.fetch(ServiceDispatcher.java:119)
        at androidx.car.app.activity.BaseCarAppActivity$2.lambda$registerRendererCallback$2$androidx-car-app-activity-BaseCarAppActivity$2(BaseCarAppActivity.java:176)
        at androidx.car.app.activity.BaseCarAppActivity$2$$ExternalSyntheticLambda4.onCreateInputConnection(Unknown Source:4)
        at androidx.car.app.activity.renderer.surface.TemplateSurfaceView.onCreateInputConnection(TemplateSurfaceView.java:160)
        at android.view.inputmethod.InputMethodManager.startInputInner(InputMethodManager.java:1928)
        at android.view.inputmethod.InputMethodManager.restartInput(InputMethodManager.java:1858)
        at androidx.car.app.activity.renderer.surface.TemplateSurfaceView.onStartInput(TemplateSurfaceView.java:210)
        at androidx.car.app.activity.BaseCarAppActivity$2.lambda$onStartInput$7$androidx-car-app-activity-BaseCarAppActivity$2(BaseCarAppActivity.java:213)
        at androidx.car.app.activity.BaseCarAppActivity$2$$ExternalSyntheticLambda8.run(Unknown Source:2)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7870)
E/CarApp.Act:     at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
</code>```
```<code>I/CarApp.Act: Unbinding from ComponentInfo
E/CarApp.Act: InputConnectionListener has not been received yet. Canceling the input
D/InputMethodManager: showSoftInput() view=androidx.car.app.activity.renderer.surface.TemplateSurfaceView{f2a6fbc GFE...... ......I. 0,0-1024,768 #7f0900ae app:id/template_view_surface aid=1073741824} flags=0 reason=SHOW_SOFT_INPUT
W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection
D/EGL_emulation: app_time_stats: avg=73260.20ms min=85.08ms max=219285.45ms count=3
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
</code>```

Code in onGetTemplate() function:

```<code> return SearchTemplate.Builder(
            object : SearchCallback {
                override fun onSearchTextChanged(searchText: String) {
                    if(searchText.isNotEmpty()){
                        searchCompleted()
                        getAddressFromName(searchText)
                        doSearch(searchText)
                    }
                }
                override fun onSearchSubmitted(searchTerm: String) {
                    mIsSearchComplete = true
                    searchCompleted()
                    doSearch(searchTerm)

                }
            })
            .setShowKeyboardByDefault(true)
            .setItemList(mItemList!!)
            .build()
</code>```

doSearch function:

```<code>    fun doSearch(searchText: String) {
        val builder = ItemList.Builder()
        places.clear()

        if (searchText.isEmpty()) {
            mItemList = withNoResults(builder)?.build();
        }
        if (!isInternetConnection) {
            CarToast.makeText(
                carContext,
                "Ingen internett tilgang",
                CarToast.LENGTH_LONG
            )
                .show()
            return
        }

        val destinations = getAddressFromName(searchText)

        if(destinations.isNotEmpty()){
            destinations.forEach{
                val addressLine = it.getAddressLine(0)
                builder.addItem(
                    Row.Builder()
                        .setTitle(addressLine)
                        .setOnClickListener { onClickSearch(it) }
                        .build())
            }
            mItemList = builder.build()
            invalidate()
            return
        }
    }
</code>```

I have tried to remove the body of the onSearchTextChanged and onSearchSubmitted functions, to see if there is anything there that makes the app crash, but the app still crashes.

This is what the app looks like when it happens:

Typing one letter in the searchfield:

Then clicking the search field, and the app crashes:

I have tried to debug the issue and google it, but I can't find anything.

Body:
I have a problem with the keyboard/softinput in my Android Automotive application. I am using the SearchTemplate, and when I click in the search field after typing some letters, the app crashes. It happens if I click the magnifier-icon, or the text-field, but not the x-button (which empties the field). This only happens if I have started typing some letters in the search field. If the search field is empty and I click it, the only thing that happens is that it is focused.

This is the error message:

D/InputMethodManager: showSoftInput() view=androidx.car.app.activity.renderer.surface.TemplateSurfaceView{f2a6fbc VFE...... .F...... 0,0-1024,768 #7f0900ae app:id/template_view_surface aid=1073741824} flags=0 reason=SHOW_SOFT_INPUT
E/CarApp.Act: Connection lost
    android.os.DeadObjectException
        at android.os.BinderProxy.transactNative(Native Method)
        at android.os.BinderProxy.transact(BinderProxy.java:571)
        at androidx.car.app.activity.renderer.IRendererCallback$Stub$Proxy.onCreateInputConnection(IRendererCallback.java:297)
        at androidx.car.app.activity.BaseCarAppActivity$2.lambda$registerRendererCallback$1(BaseCarAppActivity.java:178)
        at androidx.car.app.activity.BaseCarAppActivity$2$$ExternalSyntheticLambda6.invoke(Unknown Source:4)
        at androidx.car.app.activity.ServiceDispatcher.fetch(ServiceDispatcher.java:116)
        at androidx.car.app.activity.BaseCarAppActivity$2.lambda$registerRendererCallback$2$androidx-car-app-activity-BaseCarAppActivity$2(BaseCarAppActivity.java:176)
        at androidx.car.app.activity.BaseCarAppActivity$2$$ExternalSyntheticLambda4.onCreateInputConnection(Unknown Source:4)
        at androidx.car.app.activity.renderer.surface.TemplateSurfaceView.onCreateInputConnection(TemplateSurfaceView.java:160)
        at android.view.inputmethod.InputMethodManager.startInputInner(InputMethodManager.java:1928)
        at android.view.inputmethod.InputMethodManager.restartInput(InputMethodManager.java:1858)
        at androidx.car.app.activity.renderer.surface.TemplateSurfaceView.onStartInput(TemplateSurfaceView.java:210)
        at androidx.car.app.activity.BaseCarAppActivity$2.lambda$onStartInput$7$androidx-car-app-activity-BaseCarAppActivity$2(BaseCarAppActivity.java:213)
        at androidx.car.app.activity.BaseCarAppActivity$2$$ExternalSyntheticLambda8.run(Unknown Source:2)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7870)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
E/CarApp.Act: Remote exception (host render service)
    android.os.DeadObjectException
        at android.os.BinderProxy.transactNative(Native Method)
        at android.os.BinderProxy.transact(BinderProxy.java:571)
        at androidx.car.app.activity.renderer.surface.ISurfaceListener$Stub$Proxy.onSurfaceDestroyed(ISurfaceListener.java:181)
        at androidx.car.app.activity.renderer.surface.SurfaceHolderListener.lambda$notifySurfaceDestroyed$2$androidx-car-app-activity-renderer-surface-SurfaceHolderListener(SurfaceHolderListener.java:103)
        at androidx.car.app.activity.renderer.surface.SurfaceHolderListener$$ExternalSyntheticLambda1.invoke(Unknown Source:4)
        at androidx.car.app.activity.ServiceDispatcher.lambda$dispatchNoFail$1(ServiceDispatcher.java:90)
        at androidx.car.app.activity.ServiceDispatcher$$ExternalSyntheticLambda1.invoke(Unknown Source:2)
        at androidx.car.app.activity.ServiceDispatcher.fetchNoFail(ServiceDispatcher.java:153)
        at androidx.car.app.activity.ServiceDispatcher.dispatchNoFail(ServiceDispatcher.java:89)
        at androidx.car.app.activity.renderer.surface.SurfaceHolderListener.notifySurfaceDestroyed(SurfaceHolderListener.java:102)
        at androidx.car.app.activity.renderer.surface.SurfaceHolderListener.surfaceDestroyed(SurfaceHolderListener.java:78)
        at android.view.SurfaceView.notifySurfaceDestroyed(SurfaceView.java:1981)
        at android.view.SurfaceView.updateSurface(SurfaceView.java:1157)
        at android.view.SurfaceView.setVisibility(SurfaceView.java:345)
        at androidx.car.app.activity.BaseCarAppActivity.lambda$onStateChanged$3$androidx-car-app-activity-BaseCarAppActivity(BaseCarAppActivity.java:399)
        at androidx.car.app.activity.BaseCarAppActivity$$ExternalSyntheticLambda3.run(Unknown Source:4)
        at androidx.car.app.utils.ThreadUtils.runOnMain(ThreadUtils.java:39)
        at androidx.car.app.activity.BaseCarAppActivity.onStateChanged(BaseCarAppActivity.java:385)
        at androidx.car.app.activity.BaseCarAppActivity.$r8$lambda$dw3rK9QfgsUWuk2bAICsaK01RZs(Unknown Source:0)
        at androidx.car.app.activity.BaseCarAppActivity$$ExternalSyntheticLambda5.onChanged(Unknown Source:4)
        at androidx.lifecycle.LiveData.considerNotify(LiveData.java:133)
        at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:151)
        at androidx.lifecycle.LiveData.setValue(LiveData.java:309)
        at androidx.lifecycle.MutableLiveData.setValue(MutableLiveData.java:50)
        at androidx.car.app.activity.CarAppViewModel.lambda$onError$0$androidx-car-app-activity-CarAppViewModel(CarAppViewModel.java:185)
        at androidx.car.app.activity.CarAppViewModel$$ExternalSyntheticLambda2.run(Unknown Source:4)
        at androidx.car.app.utils.ThreadUtils.runOnMain(ThreadUtils.java:39)
        at androidx.car.app.activity.CarAppViewModel.onError(CarAppViewModel.java:177)
        at androidx.car.app.activity.ServiceDispatcher.fetch(ServiceDispatcher.java:119)
        at androidx.car.app.activity.BaseCarAppActivity$2.lambda$registerRendererCallback$2$androidx-car-app-activity-BaseCarAppActivity$2(BaseCarAppActivity.java:176)
        at androidx.car.app.activity.BaseCarAppActivity$2$$ExternalSyntheticLambda4.onCreateInputConnection(Unknown Source:4)
        at androidx.car.app.activity.renderer.surface.TemplateSurfaceView.onCreateInputConnection(TemplateSurfaceView.java:160)
        at android.view.inputmethod.InputMethodManager.startInputInner(InputMethodManager.java:1928)
        at android.view.inputmethod.InputMethodManager.restartInput(InputMethodManager.java:1858)
        at androidx.car.app.activity.renderer.surface.TemplateSurfaceView.onStartInput(TemplateSurfaceView.java:210)
        at androidx.car.app.activity.BaseCarAppActivity$2.lambda$onStartInput$7$androidx-car-app-activity-BaseCarAppActivity$2(BaseCarAppActivity.java:213)
        at androidx.car.app.activity.BaseCarAppActivity$2$$ExternalSyntheticLambda8.run(Unknown Source:2)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7870)
E/CarApp.Act:     at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)

I/CarApp.Act: Unbinding from ComponentInfo
E/CarApp.Act: InputConnectionListener has not been received yet. Canceling the input
D/InputMethodManager: showSoftInput() view=androidx.car.app.activity.renderer.surface.TemplateSurfaceView{f2a6fbc GFE...... ......I. 0,0-1024,768 #7f0900ae app:id/template_view_surface aid=1073741824} flags=0 reason=SHOW_SOFT_INPUT
W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection
D/EGL_emulation: app_time_stats: avg=73260.20ms min=85.08ms max=219285.45ms count=3
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection

Code in onGetTemplate() function:

 return SearchTemplate.Builder(
            object : SearchCallback {
                override fun onSearchTextChanged(searchText: String) {
                    if(searchText.isNotEmpty()){
                        searchCompleted()
                        getAddressFromName(searchText)
                        doSearch(searchText)
                    }
                }
                override fun onSearchSubmitted(searchTerm: String) {
                    mIsSearchComplete = true
                    searchCompleted()
                    doSearch(searchTerm)

                }
            })
            .setShowKeyboardByDefault(true)
            .setItemList(mItemList!!)
            .build()

doSearch function:

    fun doSearch(searchText: String) {
        val builder = ItemList.Builder()
        places.clear()

        if (searchText.isEmpty()) {
            mItemList = withNoResults(builder)?.build();
        }
        if (!isInternetConnection) {
            CarToast.makeText(
                carContext,
                "Ingen internett tilgang",
                CarToast.LENGTH_LONG
            )
                .show()
            return
        }

        val destinations = getAddressFromName(searchText)

        if(destinations.isNotEmpty()){
            destinations.forEach{
                val addressLine = it.getAddressLine(0)
                builder.addItem(
                    Row.Builder()
                        .setTitle(addressLine)
                        .setOnClickListener { onClickSearch(it) }
                        .build())
            }
            mItemList = builder.build()
            invalidate()
            return
        }
    }

I have tried to remove the body of the onSearchTextChanged and onSearchSubmitted functions, to see if there is anything there that makes the app crash, but the app still crashes.

This is what the app looks like when it happens:

Typing one letter in the searchfield:

Then clicking the search field, and the app crashes:

I have tried to debug the issue and google it, but I can't find anything.


问:
Does the order of features matter when predicting from a set of individuals?
Imagine trying to predict the outcome of a match based on the players on each team (3v3). Let's imagine that we have 2 pieces of information about the players: number of points per season and number of games played.

An input could be of the form: [(player_1_team_A_points, player_1_teamA_ngames), ..., (player_4_team_B_points, player_4_team_B_ngames), ..., (player_6_team_B_points, player_6_team_B_ngames)]

Now, does the order of the players in an input matters to predict which team will win?

i.e. does it matter to order players in each team by their points (player_1_team_A has always more points than player_2_team_A for example)?

Thanks


问:
Switch from ADF to React
How do you switch your frontend stack from ADF to React?

Currently, JDeveloper 11g 11.1.2.4.0 and JRE 1.6 are used. There would be a switch from ADF to React as front-end technology while keeping java for backend.

Some features have been already tested/implemented by React within an iframe. I have found many resources about how to migrate react, top to bottom, bottom to top approaches. However, I could not find any similar case study where these 2 technologies (ADF, React) were switched. Here is an excellent case from stripe about how to switch from flow to typescript.

I would like to get similar information, like in the article attached above, regarding switching from ADF to React in order to have a rough guide to follow, this way avoiding pitfalls.

Title: Switch from ADF to React


问:
Django ModelForms using get_or_create
I am using ModelForms to create and render my form, and it is working fine. I however want to use get_or_create method instead of using if form.is_valid(): method but i do not know ho to how to use it with ModelForms.

views.py

```<code>def books(request):
    genres_names = Genre.objects.all()
    if request.method == "POST":
        form = BookFile(request.POST, request.FILES)
        files = request.FILES.getlist("book")
        genres_name = request.POST.get("genres")
        genres, created = Genre.objects.get_or_create(name=genres_name)
        try:
            if form.is_valid():
                genre = form.save(commit=False)
                genre.save()
                if files:
                    for f in files:
                        names = str(f)
                        name = names.strip(".pdf")
                        Books.objects.create(genre=genre, book_title=name, book=f)
                return redirect(index)
        except IntegrityError:
            messages.error(request, "value exist in database")
            return redirect(books)
    else:
        form = BookFile()
    return render(request, "books.html", {"form":form, "genres_names":genres_names})
</code>```

models.py

```<code>class Genre(models.Model):
    genres = models.CharField(max_length=255, default="")

    class Meta:
        verbose_name_plural = "Genre"

    def __str__(self):
        return self.genres

class Books(models.Model):
    """
    This is for models.py
    """
    book_title = models.CharField(max_length=255, default="", primary_key=True)
    book = models.FileField(default="", upload_to="books", validators=[validate_book_extension], verbose_name="books")
    genre = models.ForeignKey(Genre, on_delete=models.CASCADE, default="")

    class Meta:
        verbose_name_plural = "Books"

    def __str__(self):
        return self.book_title
</code>```

forms.py

```<code>class BookInfo(forms.ModelForm):
    class Meta:
        model = Genre
        fields = ["genres",]
        widgets = {
            "genres":forms.TextInput(attrs={"list":"genres"})
        }

class BookFile(BookInfo):
    book = forms.FileField(widget = forms.ClearableFileInput(attrs={"multiple":True}))
    class Meta(BookInfo.Meta):
        fields = BookInfo.Meta.fields + ["book",]
</code>```

my template

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Books</title>
</head>
<body>
    <form action="/books/" method="POST" enctype='multipart/form-data'>
        {% csrf_token %}
        {% if request.user.is_authenticated %}

            <p>
                {{form.book}}
            </p>

            <p>
                {{form.genres}}
                <datalist id="genres">
                    <select name="" id="">
                        {% for name in genres_names %}
                        <option value="{{name.genres}}">{{name.genres}}</option>
                        {% endfor %}
                    </select>
                </datalist>
            </p>

            <p>
                <input type="submit" value="Create">
            </p>

            <div>
                <a href="/signout/"><input type="button" value="SignOut"></a>
            </div>

            <p>
                {{form.errors}}
            </p>

            {% for message in messages %}
                <p>{{ message }}</p>
            {% endfor %}
        {% endif %}
    </form>
</body>
</html>
</code>```

So basically what i want to achieve is for the user to be able to enter rhe genre of the book they want to upload and at the same time whatever a user input will be saved to database so that subsequent entry will have the same option.

Title: Django ModelForms using get_or_create

Body:
I am using ModelForms to create and render my form, and it is working fine. I however want to use get_or_create method instead of using if form.is_valid(): method but i do not know ho to how to use it with ModelForms.

views.py

def books(request):
    genres_names = Genre.objects.all()
    if request.method == "POST":
        form = BookFile(request.POST, request.FILES)
        files = request.FILES.getlist("book")
        genres_name = request.POST.get("genres")
        genres, created = Genre.objects.get_or_create(name=genres_name)
        try:
            if form.is_valid():
                genre = form.save(commit=False)
                genre.save()
                if files:
                    for f in files:
                        names = str(f)
                        name = names.strip(".pdf")
                        Books.objects.create(genre=genre, book_title=name, book=f)
                return redirect(index)
        except IntegrityError:
            messages.error(request, "value exist in database")
            return redirect(books)
    else:
        form = BookFile()
    return render(request, "books.html", {"form":form, "genres_names":genres_names})

models.py

class Genre(models.Model):
    genres = models.CharField(max_length=255, default="")

    class Meta:
        verbose_name_plural = "Genre"

    def __str__(self):
        return self.genres

class Books(models.Model):
    """
    This is for models.py
    """
    book_title = models.CharField(max_length=255, default="", primary_key=True)
    book = models.FileField(default="", upload_to="books", validators=[validate_book_extension], verbose_name="books")
    genre = models.ForeignKey(Genre, on_delete=models.CASCADE, default="")

    class Meta:
        verbose_name_plural = "Books"

    def __str__(self):
        return self.book_title

forms.py

class BookInfo(forms.ModelForm):
    class Meta:
        model = Genre
        fields = ["genres",]
        widgets = {
            "genres":forms.TextInput(attrs={"list":"genres"})
        }

class BookFile(BookInfo):
    book = forms.FileField(widget = forms.ClearableFileInput(attrs={"multiple":True}))
    class Meta(BookInfo.Meta):
        fields = BookInfo.Meta.fields + ["book",]

my template

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Books</title>

    <form action="/books/" method="POST" enctype='multipart/form-data'>
        {% csrf_token %}
        {% if request.user.is_authenticated %}

                {{form.book}}

                {{form.genres}}
                <datalist id="genres">
                    <select name="" id="">
                        {% for name in genres_names %}
                        <option value="{{name.genres}}">{{name.genres}}</option>
                        {% endfor %}
                    </select>
                </datalist>

                <input type="submit" value="Create">

                <input type="button" value="SignOut">

                {{form.errors}}

            {% for message in messages %}

{{ message }}

            {% endfor %}
        {% endif %}
    </form>

So basically what i want to achieve is for the user to be able to enter rhe genre of the book they want to upload and at the same time whatever a user input will be saved to database so that subsequent entry will have the same option.