问:
onscroll section reveal animation in gsap
I have three sections on my site,
I want to reveal sections one by one by scrolling. Now the issue is that when I trigger animation with section 2 it's fine for the first two sections while when I trigger animation with section result is not expected what I want. please check my code and correct me on what I have done wrong

```<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>Document</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.3/gsap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.3/ScrollTrigger.min.js"></script>
  </head>
  <body>
    <div class="upper-container">
      <span>(OUR AWARDS)</span>
      <h1>
        NOT FOR OUR EGOS, BUT BECAUSE AWARDS ARE A MEASURE OF CREATIVITY,
        ORIGINALITY AND QUALITY. AIMING FOR AWARDS PUSHES US TO THINK DEEPER, GO
        FURTHER AND HAVE MEANINGFUL CONVERSATIONS ABOUT WHAT CREATIVITY IS.
      </h1>
    </div>
    <div class="section2">
      <div class="upper-container2-left">
        <h1>OUR AWARDS 1</h1>
        <p>
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
          voluptates, quod, quia, voluptate quae voluptatem quas quibusdam
          accusantium quidem voluptatum quos. Quisquam, quae. Quisquam, quae.
          Quisquam, quae. Quisquam, quae.
        </p>
        <button>SEE ALL AWARDS</button>
      </div>
      <div class="upper-container2-right">
        <div class="upper-container2-right-top">
          <div class="upper-container2-right-top-left">
            <h1>OUR AWARDS</h1>
            <p>
              Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
              voluptates, quod, quia, voluptate quae voluptatem quas quibusdam
              accusantium quidem voluptatum quos. Quisquam, quae. Quisquam,
              quae. Quisquam, quae. Quisquam, quae.
            </p>
            <button>SEE ALL AWARDS</button>
          </div>
          <div class="upper-container2-right-top-right">
            <h1>OUR AWARDS</h1>
            <p>
              Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
              voluptates, quod, quia, voluptate quae voluptatem quas quibusdam
              accusantium quidem voluptatum quos. Quisquam, quae. Quisquam,
              quae. Quisquam, quae. Quisquam, quae.
            </p>
            <button>SEE ALL AWARDS</button>
          </div>
        </div>
        <div class="upper-container2-right-bottom">
          <div class="upper-container2-right-bottom-left">
            <h1>OUR AWARDS</h1>
            <p>
              Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
              voluptates, quod, quia, voluptate quae voluptatem quas quibusdam
              accusantium quidem voluptatum quos. Quisquam, quae. Quisquam,
              quae. Quisquam, quae
            </p>
          </div>
        </div>
      </div>
    </div>

    <div class="section3">
      <div class="upper-container2-left">
        <h1>OUR AWARDS</h1>
        <p>
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
          voluptates, quod, quia, voluptate quae voluptatem quas quibusdam
          accusantium quidem voluptatum quos. Quisquam, quae. Quisquam, quae.
          Quisquam, quae. Quisquam, quae.
        </p>
        <button>SEE ALL AWARDS</button>
      </div>
      <div class="upper-container2-right">
        <div class="upper-container2-right-top">
          <div class="upper-container2-right-top-left">
            <h1>OUR AWARDS</h1>
            <p>
              Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
              voluptates, quod, quia, voluptate quae voluptatem quas quibusdam
              accusantium quidem voluptatum quos. Quisquam, quae. Quisquam,
              quae. Quisquam, quae. Quisquam, quae.
            </p>
            <button>SEE ALL AWARDS</button>
          </div>
          <div class="upper-container2-right-top-right">
            <h1>OUR AWARDS</h1>
            <p>
              Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
              voluptates, quod, quia, voluptate quae voluptatem quas quibusdam
              accusantium quidem voluptatum quos. Quisquam, quae. Quisquam,
              quae. Quisquam, quae. Quisquam, quae.
            </p>
            <button>SEE ALL AWARDS</button>
          </div>
        </div>
        <div class="upper-container2-right-bottom">
          <div class="upper-container2-right-bottom-left">
            <h1>OUR AWARDS</h1>
            <p>
              Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
              voluptates, quod, quia, voluptate quae voluptatem quas quibusdam
              accusantium quidem voluptatum quos. Quisquam, quae. Quisquam,
              quae. Quisquam, quae
            </p>
          </div>
        </div>
      </div>
    </div>

    <script src="/script.js"></script>
  </body>
</html>
</code>```
```<code>gsap.registerPlugin(ScrollTrigger);
gsap
  .timeline({
    scrollTrigger: {
      trigger: ".section2",
      pin: true,
      start: "top top",
      end: "+=300%",
      scrub: 1,
    },
    defaults: {
      ease: "none",
    },
  })
  .to(
    document.body,
    {
      delay: 0.2,
      backgroundColor: "#f0f0f0",
    },
    "start"
  )

  // upper container
  .to(
    ".upper-container ",
    {
      scale: 0,
    },
    "start"
  )
  .to(
    ".upper-container",
    {
      opacity: 0,
    },
    "start"
  )

  // section2
  .to(
    ".section2",
    {
      scale: 1,
      top: 0,
    },
    "start"
  )
  .to(
    ".section2",
    {
      opacity: 1,
    },
    "start"
  )
  // section3
  .to(
    ".section3",
    {
      scale: 1,
      top: 0,
    },
    "start"
  )
  .to(
    ".section3",
    {
      opacity: 1,
    },
    "start"
  );
</code>```
```<code>body {
  margin: 0;
  padding: 0;
  font-family: "Open Sans", sans-serif;
  background: #f1bdbd;
  box-sizing: border-box;
  overflow-x: hidden;
}
* {
  padding: 0;
  margin: 0;
}
/* ::-webkit-scrollbar {
  display: none;
} */
.upper-container {
  height: 100vh;
  position: fixed;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  background-color: royalblue;
  /* background-image: url("./visiontabsbg.png"); */
}
.upper-container span,
.upper-container h1 {
  padding: 10px 50px;
  color: #fff;
}

.section2 {
  background-color: rgb(146, 118, 118);
  position: relative;
  height: 100vh;
  width: 100%;
  transform: scale(0);
  opacity: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.section3 {
  background-color: rgb(197, 71, 71);
  position: relative;
  height: 100vh;
  width: 100%;
  transform: scale(0);
  opacity: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
</code>```

Body:
I have three sections on my site,
I want to reveal sections one by one by scrolling. Now the issue is that when I trigger animation with section 2 it's fine for the first two sections while when I trigger animation with section result is not expected what I want. please check my code and correct me on what I have done wrong

<!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>Document</title>
    <link rel="stylesheet" href="style.css" />

      (OUR AWARDS)

        NOT FOR OUR EGOS, BUT BECAUSE AWARDS ARE A MEASURE OF CREATIVITY,
        ORIGINALITY AND QUALITY. AIMING FOR AWARDS PUSHES US TO THINK DEEPER, GO
        FURTHER AND HAVE MEANINGFUL CONVERSATIONS ABOUT WHAT CREATIVITY IS.

OUR AWARDS 1

          Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
          voluptates, quod, quia, voluptate quae voluptatem quas quibusdam
          accusantium quidem voluptatum quos. Quisquam, quae. Quisquam, quae.
          Quisquam, quae. Quisquam, quae.

        <button>SEE ALL AWARDS</button>

OUR AWARDS

              Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
              voluptates, quod, quia, voluptate quae voluptatem quas quibusdam
              accusantium quidem voluptatum quos. Quisquam, quae. Quisquam,
              quae. Quisquam, quae. Quisquam, quae.

            <button>SEE ALL AWARDS</button>

OUR AWARDS

              Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
              voluptates, quod, quia, voluptate quae voluptatem quas quibusdam
              accusantium quidem voluptatum quos. Quisquam, quae. Quisquam,
              quae. Quisquam, quae. Quisquam, quae.

            <button>SEE ALL AWARDS</button>

OUR AWARDS

              Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
              voluptates, quod, quia, voluptate quae voluptatem quas quibusdam
              accusantium quidem voluptatum quos. Quisquam, quae. Quisquam,
              quae. Quisquam, quae

OUR AWARDS

          Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
          voluptates, quod, quia, voluptate quae voluptatem quas quibusdam
          accusantium quidem voluptatum quos. Quisquam, quae. Quisquam, quae.
          Quisquam, quae. Quisquam, quae.

        <button>SEE ALL AWARDS</button>

OUR AWARDS

              Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
              voluptates, quod, quia, voluptate quae voluptatem quas quibusdam
              accusantium quidem voluptatum quos. Quisquam, quae. Quisquam,
              quae. Quisquam, quae. Quisquam, quae.

            <button>SEE ALL AWARDS</button>

OUR AWARDS

              Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
              voluptates, quod, quia, voluptate quae voluptatem quas quibusdam
              accusantium quidem voluptatum quos. Quisquam, quae. Quisquam,
              quae. Quisquam, quae. Quisquam, quae.

            <button>SEE ALL AWARDS</button>

OUR AWARDS

              Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
              voluptates, quod, quia, voluptate quae voluptatem quas quibusdam
              accusantium quidem voluptatum quos. Quisquam, quae. Quisquam,
              quae. Quisquam, quae

gsap.registerPlugin(ScrollTrigger);
gsap
  .timeline({
    scrollTrigger: {
      trigger: ".section2",
      pin: true,
      start: "top top",
      end: "+=300%",
      scrub: 1,
    },
    defaults: {
      ease: "none",
    },
  })
  .to(
    document.body,
    {
      delay: 0.2,
      backgroundColor: "#f0f0f0",
    },
    "start"
  )

  // upper container
  .to(
    ".upper-container ",
    {
      scale: 0,
    },
    "start"
  )
  .to(
    ".upper-container",
    {
      opacity: 0,
    },
    "start"
  )

  // section2
  .to(
    ".section2",
    {
      scale: 1,
      top: 0,
    },
    "start"
  )
  .to(
    ".section2",
    {
      opacity: 1,
    },
    "start"
  )
  // section3
  .to(
    ".section3",
    {
      scale: 1,
      top: 0,
    },
    "start"
  )
  .to(
    ".section3",
    {
      opacity: 1,
    },
    "start"
  );

body {
  margin: 0;
  padding: 0;
  font-family: "Open Sans", sans-serif;
  background: #f1bdbd;
  box-sizing: border-box;
  overflow-x: hidden;
}
* {
  padding: 0;
  margin: 0;
}
/* ::-webkit-scrollbar {
  display: none;
} */
.upper-container {
  height: 100vh;
  position: fixed;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  background-color: royalblue;
  /* background-image: url("./visiontabsbg.png"); */
}
.upper-container span,
.upper-container h1 {
  padding: 10px 50px;
  color: #fff;
}

.section2 {
  background-color: rgb(146, 118, 118);
  position: relative;
  height: 100vh;
  width: 100%;
  transform: scale(0);
  opacity: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.section3 {
  background-color: rgb(197, 71, 71);
  position: relative;
  height: 100vh;
  width: 100%;
  transform: scale(0);
  opacity: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}


来源: stackexchange

问:
How to direct a link to a random page without negatively impacting search engine status?
I have a link in the main menu of a website I'm working on that allows the user to go to a random page on the website. The link redirects the user to a script I'll call "random.php" that queries the database then does a 303 redirect to a randomly selected page (using the header function).

I've never needed to do something like this before, and I'm not sure if having a menu link that leads to a 303 redirect will have a negative impact on the search engines indexing the website. I have my site loaded in Ahrefs which gives a warning that every page has a link to a redirect, but Google Search Console doesn't mention it as an issue.

Nonetheless I'm concerned the 303 redirect might be a bad approach. Would appreciate any thoughts on how to better go about the random page link without any potential search engine issues - or is this solution ok?

ContentLicense: CC BY-SA 4.0


问:
How to update value from long running isolate in dart?
I am trying to update long running(while true) isolate. the idea is call update everywhere on main or update that value on future.

```<code>void main() async {
  final ReceivePort p = ReceivePort();
  var events = StreamQueue<dynamic>(p);
  SendPort sendPort = await events.next;
  await Isolate.spawn(longTask, p.sendPort);
  sendPort.send(30);

  Future.delayed(Duration(seconds: 10), (() {
    sendPort.send(10);
  }));
  Future.delayed(Duration(seconds: 50), (() {
    sendPort.send(30);
  }));
}

Future<void> longTask(SendPort p) async {
  final commandPort = ReceivePort();
  p.send(commandPort.sendPort);

  //###############################################
  // the idea is this loop will call function each second
  while (true) {
    // how to get value 30 20 10  ?
    // here
    sleep(const Duration(seconds: 1));
  }
}
</code>```

I cannot using await for because loop must running without stop

```<code> await for (var d in commandPort) {
    print(d);
 }
</code>```

Body:
I am trying to update long running(while true) isolate. the idea is call update everywhere on main or update that value on future.

void main() async {
  final ReceivePort p = ReceivePort();
  var events = StreamQueue<dynamic>(p);
  SendPort sendPort = await events.next;
  await Isolate.spawn(longTask, p.sendPort);
  sendPort.send(30);

  Future.delayed(Duration(seconds: 10), (() {
    sendPort.send(10);
  }));
  Future.delayed(Duration(seconds: 50), (() {
    sendPort.send(30);
  }));
}

Future<void> longTask(SendPort p) async {
  final commandPort = ReceivePort();
  p.send(commandPort.sendPort);

  //###############################################
  // the idea is this loop will call function each second
  while (true) {
    // how to get value 30 20 10  ?
    // here
    sleep(const Duration(seconds: 1));
  }
}

I cannot using await for because loop must running without stop

 await for (var d in commandPort) {
    print(d);
 }


问:
VOSK in Python on Mac not getting/reading microphone input
I am trying to use VOSK to transcribe voice input from my M1 MacBook Air  microphone and the program runs fine, it just gets no input from the microphone. I found that if I use the larger English voice model with a '''exception_on_overflow = False''' it sometimes, after 20 seconds or so, hears the word "the" and prints it.

```<code>from vosk import Model, KaldiRecognizer
import pyaudio

model = Model(r'/Users/myname/Desktop/AVIS/vosk-model-small-en-us-0.15')
#vosk-model-en-us-0.22-lgraph

recognizer = KaldiRecognizer(model, 16000)

cap = pyaudio.PyAudio()
stream = cap.open(format = pyaudio.paInt16, channels = 1, rate = 16000, input = True, frames_per_buffer = 8192)
stream.start_stream()

while True:

    data = stream.read(4096)#, exception_on_overflow = False)

    if recognizer.AcceptWaveform(data):
        print(recognizer.Result())
</code>```

I hand copied this code from several different video tutorials on getting started with VOSK.

Originally I was using the larger VOSK English speech model but I would get an error OSError: [Errno -9981] Input overflowed. But as soon as I changed the model to the smaller English model, in an attempt to get it to recognize anything, it was gone.

I tried changing the format of pyaudio from paInt16 to paFloat32 (32 bit float as said in the Mac Audio Midi Setup) but that didn't do anything either.

Body:
I am trying to use VOSK to transcribe voice input from my M1 MacBook Air  microphone and the program runs fine, it just gets no input from the microphone. I found that if I use the larger English voice model with a '''exception_on_overflow = False''' it sometimes, after 20 seconds or so, hears the word "the" and prints it.

from vosk import Model, KaldiRecognizer
import pyaudio

model = Model(r'/Users/myname/Desktop/AVIS/vosk-model-small-en-us-0.15')
#vosk-model-en-us-0.22-lgraph

recognizer = KaldiRecognizer(model, 16000)

cap = pyaudio.PyAudio()
stream = cap.open(format = pyaudio.paInt16, channels = 1, rate = 16000, input = True, frames_per_buffer = 8192)
stream.start_stream()

while True:

    data = stream.read(4096)#, exception_on_overflow = False)

    if recognizer.AcceptWaveform(data):
        print(recognizer.Result())

I hand copied this code from several different video tutorials on getting started with VOSK.

Originally I was using the larger VOSK English speech model but I would get an error OSError: [Errno -9981] Input overflowed. But as soon as I changed the model to the smaller English model, in an attempt to get it to recognize anything, it was gone.

I tried changing the format of pyaudio from paInt16 to paFloat32 (32 bit float as said in the Mac Audio Midi Setup) but that didn't do anything either.


问:
Component not rendering update UI after state change by using useReducer hook and context api
My ProductList Component which is used to show filtered products

```<code>const ProductsList = () => {
    const { cate } = useParams();
    const { getFilterProducts, all_products, filter_products } = useFilterContext();
    const [loading, setLoading] = useState(true);
    useEffect(() => {
        getFilterProducts(`${API}/category/${cate}`).then(() => {
            setLoading(false);
        });
    }, [cate]);
    return (
        <div className="mx-2 mt-2 mb-16 md:mb-0 grid grid-cols-1 md:grid-cols-12">
            <div className="md:h-9 w-full md:col-span-2">
                <FilterSection cat={cate} />
            </div>
            <div className="md:col-span-10 ">
                <ProductListDetails products={filter_products} />
            </div>
        </div>
    );
};
</code>```

My FilterSection Component which has the sorting buttons to sort the products displayed using filter_products

```<code>const FilterSection = ({ cat }) => {
    const { updateFilterValue, clearFilters, all_products, sortProductsValue } = useFilterContext();

    return (
        <>
            <div className="md:hidden flex items-center gap-1 mt-1 mb-1">
                <div>Sort</div>
                <button
                    className="px-2 text-sm border-2 ml-3 rounded-sm"
                    name="sort"
                    value="lowest"
                    onClick={sortProductsValue}
                >
                    Lowest
                </button>
                <button
                    className="px-2 text-sm border-2 rounded-sm"
                    name="sort"
                    value="highest"
                    onClick={sortProductsValue}
                >
                    Highest
                </button>
            </div>
        </>
    );
};
</code>```

My FilterContext

```<code>const initialState = {
    loading: true,
    error: null,
    filter_products: [],
    all_products: [],
    sort: "",
    filters: {
        query: "",
        rating: null,
        brand: "all",
        discount: 0,
        price: 0,
        minPrice: 0,
        maxPrice: 0,
    },
};
const FilterProvider = ({ children }) => {
    const [state, dispatch] = useReducer(reducer, initialState);

    const getFilterProducts = async (url) => {
        dispatch({ type: "FILTERS_LOADING" });
        try {
            const res = await fetch(url);
            const data = await res.json();
            if (!res.ok) {
                var error = new Error("Error" + res.status + res.statusText);
                throw error;
            }
            dispatch({ type: "LOAD_FILTER_PRODUCTS", payload: data.products });
        } catch (err) {
            dispatch({ type: "FILTERS_ERROR", payload: err.message });
        }
    };

    const sortProductsValue = (e) => {
        dispatch({ type: "GET_SORT_VALUE", payload: e.target.value });
    };

    useEffect(() => {
        dispatch({ type: "SORT_PRODUCTS" });
        dispatch({ type: "APPLY_FILTERS" });
    }, [state.filters, state.sort]);
    return (
        <FilterContext.Provider
            value={{
                ...state,
                getFilterProducts,
                updateFilterValue,
                updateFormValue,
                clearFilters,
                sortProductsValue,
            }}
        >
            {children}
        </FilterContext.Provider>
    );
};

const useFilterContext = () => {
    return useContext(FilterContext);
};

</code>```

My FilterReducer

```<code>const FilterReducer = (state, { type, payload }) => {
    switch (type) {
        case "LOAD_FILTER_PRODUCTS":
            //console.log(payload);
            const allPrice = payload.map((x) => x.price);
            const maxPrice = Math.max(...allPrice);
            return {
                ...state,
                all_products: [...payload],
                filter_products: [...payload],
                sort_products: [...payload],
                loading: false,
                maxPrice,
            };

        case "GET_SORT_VALUE":
            return {
                ...state,
                sort: payload,
            };

        case "SORT_PRODUCTS":
            const { filter_products, sort } = state;
            let temp = [...filter_products];

            //console.log(filter_products);
            const sortProducts = (a, b) => {
                if (sort === "lowest") {
                    return a.price - b.price;
                }
                if (sort === "highest") {
                    return b.price - a.price;
                }
            };

            let filtered = temp.sort(sortProducts);
            console.log(filtered); //here I am getting the products in sorted order
            return {
                ...state,
                filter_products: filtered, //here I am assigning the sorted array to
                                           // filtered_products and using     filtered_products to display in ProductList Component
            };

        default:
            return state;
    }
};
</code>```

I created sortProductsValue function in my filterContext and using this function in filtersection component. When I click on one of the sort button which is either lowest or highest, it calls the function and on function call "GET_SORT_VALUE" action is dispathed with the payload which sets the sort value in state. When state changes, I am using useEffect to automatically dispatch "SORT_PRODUCTS" when the value of **state.sort **changes and store the sorted products in filter_products.

My problem is when I click on the sorting button, it dispatches the action and sorts the products, but it does not updates the state of filter_products which is used to display the products in productList component.

Body:
My ProductList Component which is used to show filtered products

const ProductsList = () => {
    const { cate } = useParams();
    const { getFilterProducts, all_products, filter_products } = useFilterContext();
    const [loading, setLoading] = useState(true);
    useEffect(() => {
        getFilterProducts(`${API}/category/${cate}`).then(() => {
            setLoading(false);
        });
    }, [cate]);
    return (

                <FilterSection cat={cate} />

                <ProductListDetails products={filter_products} />

    );
};

My FilterSection Component which has the sorting buttons to sort the products displayed using filter_products

const FilterSection = ({ cat }) => {
    const { updateFilterValue, clearFilters, all_products, sortProductsValue } = useFilterContext();

    return (
        <>

Sort

                <button
                    className="px-2 text-sm border-2 ml-3 rounded-sm"
                    name="sort"
                    value="lowest"
                    onClick={sortProductsValue}
                >
                    Lowest
                </button>
                <button
                    className="px-2 text-sm border-2 rounded-sm"
                    name="sort"
                    value="highest"
                    onClick={sortProductsValue}
                >
                    Highest
                </button>

        </>
    );
};

My FilterContext

const initialState = {
    loading: true,
    error: null,
    filter_products: [],
    all_products: [],
    sort: "",
    filters: {
        query: "",
        rating: null,
        brand: "all",
        discount: 0,
        price: 0,
        minPrice: 0,
        maxPrice: 0,
    },
};
const FilterProvider = ({ children }) => {
    const [state, dispatch] = useReducer(reducer, initialState);

    const getFilterProducts = async (url) => {
        dispatch({ type: "FILTERS_LOADING" });
        try {
            const res = await fetch(url);
            const data = await res.json();
            if (!res.ok) {
                var error = new Error("Error" + res.status + res.statusText);
                throw error;
            }
            dispatch({ type: "LOAD_FILTER_PRODUCTS", payload: data.products });
        } catch (err) {
            dispatch({ type: "FILTERS_ERROR", payload: err.message });
        }
    };

    const sortProductsValue = (e) => {
        dispatch({ type: "GET_SORT_VALUE", payload: e.target.value });
    };

    useEffect(() => {
        dispatch({ type: "SORT_PRODUCTS" });
        dispatch({ type: "APPLY_FILTERS" });
    }, [state.filters, state.sort]);
    return (
        <FilterContext.Provider
            value={{
                ...state,
                getFilterProducts,
                updateFilterValue,
                updateFormValue,
                clearFilters,
                sortProductsValue,
            }}
        >
            {children}
        </FilterContext.Provider>
    );
};

const useFilterContext = () => {
    return useContext(FilterContext);
};

My FilterReducer

const FilterReducer = (state, { type, payload }) => {
    switch (type) {
        case "LOAD_FILTER_PRODUCTS":
            //console.log(payload);
            const allPrice = payload.map((x) => x.price);
            const maxPrice = Math.max(...allPrice);
            return {
                ...state,
                all_products: [...payload],
                filter_products: [...payload],
                sort_products: [...payload],
                loading: false,
                maxPrice,
            };

        case "GET_SORT_VALUE":
            return {
                ...state,
                sort: payload,
            };

        case "SORT_PRODUCTS":
            const { filter_products, sort } = state;
            let temp = [...filter_products];

            //console.log(filter_products);
            const sortProducts = (a, b) => {
                if (sort === "lowest") {
                    return a.price - b.price;
                }
                if (sort === "highest") {
                    return b.price - a.price;
                }
            };

            let filtered = temp.sort(sortProducts);
            console.log(filtered); //here I am getting the products in sorted order
            return {
                ...state,
                filter_products: filtered, //here I am assigning the sorted array to
                                           // filtered_products and using     filtered_products to display in ProductList Component
            };

        default:
            return state;
    }
};

I created sortProductsValue function in my filterContext and using this function in filtersection component. When I click on one of the sort button which is either lowest or highest, it calls the function and on function call "GET_SORT_VALUE" action is dispathed with the payload which sets the sort value in state. When state changes, I am using useEffect to automatically dispatch "SORT_PRODUCTS" when the value of **state.sort **changes and store the sorted products in filter_products.

My problem is when I click on the sorting button, it dispatches the action and sorts the products, but it does not updates the state of filter_products which is used to display the products in productList component.


问:
ValueError: all the input array dimensions for the concatenation axis must match exactly when using ColumnTransformer
I'm trying to apply transformations as part of sklearn pipeline for my categorical and numeric features, using both inbuilt and custom Transformers, but when I use the ColumnTransformer to combine the outputs I get above error.

this is the Pipeline that I'm trying to build:

```<code>from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler

numeric_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='median')),
    ('scaler', StandardScaler())
])

categorical_transformer = Pipeline(steps=[
    ('word2vec', W2VTransformer())
])

preprocessor = ColumnTransformer(
    transformers=[

        ('cat', categorical_transformer, categorical_features),
        ('num', numeric_transformer, numeric_features),
    ])
</code>```

The W2VTransformer takes in a column of sentences and averages the word2Vec output to give a (row_size,n_dim) output which  looks like this:

```<code>from gensim.models.word2vec import Word2Vec
from gensim.models.doc2vec import Doc2Vec
from sklearn.base import BaseEstimator, TransformerMixin
import nltk
nltk.download('punkt')
import numpy as np
from scipy import sparse

class W2VTransformer(BaseEstimator, TransformerMixin):

    def __init__(self, n_dim = 10, n_context = 2):
        self.n_dim = n_dim
        self.n_context = n_context

    def fit(self, X,y=0):
        nlp = [nltk.word_tokenize(i) for i in X]
        self.model = Word2Vec(nlp, vector_size = self.n_dim,
                              window = self.n_context,
                              min_count = 1, sample = 1e-3, workers = 4, seed=42)
        return self

    def transform(self, X):

        nlp = [nltk.word_tokenize(i) for i in X]
        return np.array([self.model.wv[i].mean(axis=0) for i in nlp])
</code>```

When I run it, I get the following error:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_3879/2379153661.py in <module>
----> 1 preprocessor.fit_transform(X)

/opt/conda/lib/python3.7/site-packages/sklearn/compose/_column_transformer.py in fit_transform(self, X, y)
    538         self._validate_output(Xs)
    539
--> 540         return self._hstack(list(Xs))
    541
    542     def transform(self, X):

/opt/conda/lib/python3.7/site-packages/sklearn/compose/_column_transformer.py in _hstack(self, Xs)
    621         else:
    622             Xs = [f.toarray() if sparse.issparse(f) else f for f in Xs]
--> 623             return np.hstack(Xs)
    624
    625

<__array_function__ internals> in hstack(*args, **kwargs)

/opt/conda/lib/python3.7/site-packages/numpy/core/shape_base.py in hstack(tup)
    343         return _nx.concatenate(arrs, 0)
    344     else:
--> 345         return _nx.concatenate(arrs, 1)
    346
    347

<__array_function__ internals> in concatenate(*args, **kwargs)

ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 1 and the array at index 1 has size 37
</code>```

I saw the code fails at the return np.hstack(Xs) line, so I tried to replicate it:

```<code>numeric_transformer.fit(X[numeric_features])
numeric_transformer.transform(X[numeric_features]).shape
</code>```

(37, 24)

```<code>categorical_transformer.fit(X['sentence_col'])
categorical_transformer.transform(X['sentence_col']).shape
</code>```

(37, 10)

and then combined the two as is done in the library:

```<code>from scipy import sparse

Xs = [f.toarray() if sparse.issparse(f) else f for f in [categorical_transformer.transform(X['sentence_col']),
                                                         numeric_transformer.transform(X[numeric_features])]]

np.hstack(Xs).shape
</code>```

(37, 34)

looks like the code should work fine, but it's not. What am I doing wrong?

Body:
I'm trying to apply transformations as part of sklearn pipeline for my categorical and numeric features, using both inbuilt and custom Transformers, but when I use the ColumnTransformer to combine the outputs I get above error.

this is the Pipeline that I'm trying to build:

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler

numeric_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='median')),
    ('scaler', StandardScaler())
])

categorical_transformer = Pipeline(steps=[
    ('word2vec', W2VTransformer())
])

preprocessor = ColumnTransformer(
    transformers=[

        ('cat', categorical_transformer, categorical_features),
        ('num', numeric_transformer, numeric_features),
    ])

The W2VTransformer takes in a column of sentences and averages the word2Vec output to give a (row_size,n_dim) output which  looks like this:

from gensim.models.word2vec import Word2Vec
from gensim.models.doc2vec import Doc2Vec
from sklearn.base import BaseEstimator, TransformerMixin
import nltk
nltk.download('punkt')
import numpy as np
from scipy import sparse

class W2VTransformer(BaseEstimator, TransformerMixin):

    def __init__(self, n_dim = 10, n_context = 2):
        self.n_dim = n_dim
        self.n_context = n_context

    def fit(self, X,y=0):
        nlp = [nltk.word_tokenize(i) for i in X]
        self.model = Word2Vec(nlp, vector_size = self.n_dim,
                              window = self.n_context,
                              min_count = 1, sample = 1e-3, workers = 4, seed=42)
        return self

    def transform(self, X):

        nlp = [nltk.word_tokenize(i) for i in X]
        return np.array([self.model.wv[i].mean(axis=0) for i in nlp])

When I run it, I get the following error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_3879/2379153661.py in <module>
----> 1 preprocessor.fit_transform(X)

/opt/conda/lib/python3.7/site-packages/sklearn/compose/_column_transformer.py in fit_transform(self, X, y)
    538         self._validate_output(Xs)
    539
--> 540         return self._hstack(list(Xs))
    541
    542     def transform(self, X):

/opt/conda/lib/python3.7/site-packages/sklearn/compose/_column_transformer.py in _hstack(self, Xs)
    621         else:
    622             Xs = [f.toarray() if sparse.issparse(f) else f for f in Xs]
--> 623             return np.hstack(Xs)
    624
    625

<__array_function__ internals> in hstack(*args, **kwargs)

/opt/conda/lib/python3.7/site-packages/numpy/core/shape_base.py in hstack(tup)
    343         return _nx.concatenate(arrs, 0)
    344     else:
--> 345         return _nx.concatenate(arrs, 1)
    346
    347

<__array_function__ internals> in concatenate(*args, **kwargs)

ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 1 and the array at index 1 has size 37

I saw the code fails at the return np.hstack(Xs) line, so I tried to replicate it:

numeric_transformer.fit(X[numeric_features])
numeric_transformer.transform(X[numeric_features]).shape

(37, 24)

categorical_transformer.fit(X['sentence_col'])
categorical_transformer.transform(X['sentence_col']).shape

(37, 10)

and then combined the two as is done in the library:

from scipy import sparse

Xs = [f.toarray() if sparse.issparse(f) else f for f in [categorical_transformer.transform(X['sentence_col']),
                                                         numeric_transformer.transform(X[numeric_features])]]

np.hstack(Xs).shape

(37, 34)

looks like the code should work fine, but it's not. What am I doing wrong?


问:
TanStack Query: Pagination on last page and last item if deleted and invalidate and go back to previous page
I am using TanStack Query and I have a list of items with pagination configuration as currentPage: 1 and PageSize as 10.

When i got to currentPage:4 I only have 1 item and if delete it and invalidate cache it runs the api with ?page=4 and goes into error as there are no items on page 4 anymore.

If there are no items or if its the last element of last page I would like to redirect to ?page=3. Or if you could let me know the idea sceanrio.

In my users.tsx

```<code>const {
    status: userStatus,
    data: userData,
    isPreviousData,
  } = useQuery({
    enabled: role_id != '',
    queryKey: ['userlist', currentPage],
    queryFn: () =>
      userService.searchUsers(user_id, role_id, currentPage, pageSize),
    keepPreviousData: true,
    refetchOnWindowFocus: false,
    onSuccess: (response) => {
      setPageInfo(response.data.pageInfo)
    },
  })

// handling manually
const handleUserClose = (text: string) => {
        if (text) {
          setCurrentPage(parseInt(text))
        }
        setUserShow(false)
      }
</code>```

I run this query for my pagination.

On delete I have a modal on bin icon click.

delete modal.tsx

```<code>const {
    status,
    error: deleteError,
    mutate,
    isLoading,
  } = useMutation({
    mutationFn: () => userService.deleteUser(props.userId, props.orgId),
    onSuccess: () => {
      toast.success('User deleted successfully!')

      if (props.pageInfo.itemsOnPage === 1 && props.pageInfo.pageCurrent > 1) {
        //queryClient.invalidateQueries(["stafflist"]) //tried this
        //queryClient.refetchQueries(["stafflist", 1]) // tried this

        props.handleUserClose(`${props.pageInfo.pageCurrent - 1}`) // currently handeling
        manually.

      } else {
        props.handleUserClose()
        queryClient.invalidateQueries(['stafflist'])
      }
    },
    onError: (error: any) => {
      toast.error(error?.response?.data?.detail)
      setError(error?.response?.data?.detail)
    },
  })
</code>```

I tried using multiple methods like queryClient.invalidateQueries and queryClient.refetchQueries it goes to page 3 but doesn't updated the UI. Not sure what I am doing wrong.

Body:
I am using TanStack Query and I have a list of items with pagination configuration as currentPage: 1 and PageSize as 10.

When i got to currentPage:4 I only have 1 item and if delete it and invalidate cache it runs the api with ?page=4 and goes into error as there are no items on page 4 anymore.

If there are no items or if its the last element of last page I would like to redirect to ?page=3. Or if you could let me know the idea sceanrio.

In my users.tsx

const {
    status: userStatus,
    data: userData,
    isPreviousData,
  } = useQuery({
    enabled: role_id != '',
    queryKey: ['userlist', currentPage],
    queryFn: () =>
      userService.searchUsers(user_id, role_id, currentPage, pageSize),
    keepPreviousData: true,
    refetchOnWindowFocus: false,
    onSuccess: (response) => {
      setPageInfo(response.data.pageInfo)
    },
  })

// handling manually
const handleUserClose = (text: string) => {
        if (text) {
          setCurrentPage(parseInt(text))
        }
        setUserShow(false)
      }

I run this query for my pagination.

On delete I have a modal on bin icon click.

delete modal.tsx

const {
    status,
    error: deleteError,
    mutate,
    isLoading,
  } = useMutation({
    mutationFn: () => userService.deleteUser(props.userId, props.orgId),
    onSuccess: () => {
      toast.success('User deleted successfully!')

      if (props.pageInfo.itemsOnPage === 1 && props.pageInfo.pageCurrent > 1) {
        //queryClient.invalidateQueries(["stafflist"]) //tried this
        //queryClient.refetchQueries(["stafflist", 1]) // tried this

        props.handleUserClose(`${props.pageInfo.pageCurrent - 1}`) // currently handeling
        manually.

      } else {
        props.handleUserClose()
        queryClient.invalidateQueries(['stafflist'])
      }
    },
    onError: (error: any) => {
      toast.error(error?.response?.data?.detail)
      setError(error?.response?.data?.detail)
    },
  })

I tried using multiple methods like queryClient.invalidateQueries and queryClient.refetchQueries it goes to page 3 but doesn't updated the UI. Not sure what I am doing wrong.


问:
How to iterate throught an input type="file" name='Image[]' multiple
hii guys this is vineet i am new to php and there is a situation where need to receive a value of input type="file" in a array but i unable to get the data as it give me error showing undefined array key

```<code> html code

<input type="file" class="inputImage"  name="CrewImage[]" accept="image/png , image/jpg , image/jpeg" required>

 phpcode

 <?php
      $crewImage=$_POST['CrewImage'];
    ?>
</code>```

I want to access the individual value of this so that i can save this value in the database

i have tried this

```<code>for($i=0;$i< count($crewImage);$i++){

        $MovieCastImage=addslashes(file_get_contents($_FILES[ $_POST['CrewImage['.$i.']']]['tmp_name']));
       echo $MovieCastImage;

    }
</code>```

but this also gives the error Undefined array key

Body:
hii guys this is vineet i am new to php and there is a situation where need to receive a value of input type="file" in a array but i unable to get the data as it give me error showing undefined array key

 html code

<input type="file" class="inputImage"  name="CrewImage[]" accept="image/png , image/jpg , image/jpeg" required>

 phpcode

 <?php
      $crewImage=$_POST['CrewImage'];
    ?>

I want to access the individual value of this so that i can save this value in the database

i have tried this

for($i=0;$i< count($crewImage);$i++){

        $MovieCastImage=addslashes(file_get_contents($_FILES[ $_POST['CrewImage['.$i.']']]['tmp_name']));
       echo $MovieCastImage;

    }

but this also gives the error Undefined array key


问:
How to make visible false of legend series item in highcharts
Trying to make visible false of legend series items on legendItemClick event in highcharts, But not working. How to do it?

Below is my code.

```<code>  series: {
  events: {
    legendItemClick: function(e) {
      const series = this;
      const chart = series.chart;
      const hasChangedOpacity = series.hasChangedOpacity;

      if(this.name == 'Movie1' || this.name == 'Movie2'){
         chart.series[2].visible = false;
         chart.series[3].visible = false;
      }

      if(this.name == 'Game1' || this.name == 'Game2'){
         chart.series[0].visible = false;
         chart.series[1].visible = false;
      }

    }
     }
      },
       series: [{
    name: 'Movie1',
    data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4],
    visible:true
  }, {
    name: 'Movie2',
    data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5,106.6, 92.3],
    visible:true
  }, {
    name: 'Game1',
    data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3,51.2],
    visible:true
  }, {
    name: 'Game2',
    data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8,51.1],
    visible:true
  }]
</code>```

https://www.highcharts.com/demo/column-basic

Demo: https://jsfiddle.net/zny6c9d3/2/

Body:
Trying to make visible false of legend series items on legendItemClick event in highcharts, But not working. How to do it?

Below is my code.

  series: {
  events: {
    legendItemClick: function(e) {
      const series = this;
      const chart = series.chart;
      const hasChangedOpacity = series.hasChangedOpacity;

      if(this.name == 'Movie1' || this.name == 'Movie2'){
         chart.series[2].visible = false;
         chart.series[3].visible = false;
      }

      if(this.name == 'Game1' || this.name == 'Game2'){
         chart.series[0].visible = false;
         chart.series[1].visible = false;
      }

    }
     }
      },
       series: [{
    name: 'Movie1',
    data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4],
    visible:true
  }, {
    name: 'Movie2',
    data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5,106.6, 92.3],
    visible:true
  }, {
    name: 'Game1',
    data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3,51.2],
    visible:true
  }, {
    name: 'Game2',
    data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8,51.1],
    visible:true
  }]

https://www.highcharts.com/demo/column-basic

Demo: https://jsfiddle.net/zny6c9d3/2/


问:
Why do I receive the TypeError: "int" is not subscriptable error all of a sudden? It worked before I included a chi-square test in Kaggle notebook
I am trying to code a visualization in a Kaggle notebook. It involves graphing variables from a .csv file in distribution plots. I keep receiving the TypeError: "int" is not subscriptable.

```<code>fig, ax = plt.subplots(2,2, figsize=(12,12))
sns.histplot(df['Satisfaction'], kde=True, ax = ax[0,0])
plt.ylabel("Count")
sns.histplot(df['Performance_evaluation'], kde=True, ax = ax[0,1])
sns.histplot(df['Monthly_hours'], kde=True, ax = ax[1,0])
</code>```

TypeError: 'int object is not subscriptable (referring to line 2)

I've tried to look up articles on the error but not quite understanding what the issue is. I am new to Python.

Turns out, I defined df as degrees of freedom in my chi square test. Once I fixed that, there were no issues. Thanks for the help!

Body:
I am trying to code a visualization in a Kaggle notebook. It involves graphing variables from a .csv file in distribution plots. I keep receiving the TypeError: "int" is not subscriptable.

fig, ax = plt.subplots(2,2, figsize=(12,12))
sns.histplot(df['Satisfaction'], kde=True, ax = ax[0,0])
plt.ylabel("Count")
sns.histplot(df['Performance_evaluation'], kde=True, ax = ax[0,1])
sns.histplot(df['Monthly_hours'], kde=True, ax = ax[1,0])

TypeError: 'int object is not subscriptable (referring to line 2)

I've tried to look up articles on the error but not quite understanding what the issue is. I am new to Python.

Turns out, I defined df as degrees of freedom in my chi square test. Once I fixed that, there were no issues. Thanks for the help!


问:
How to Show Video player notification in flutter
i made application which play audio and video files.

for playing audio i used => just_audio: ^0.9.28 and for audio notification user => audio_service: ^0.18.7

but my main issue is with the video player. to play videos I use  chewie: ^1.3.5
and video_player: ^2.4.7

and now when I play audio it will show a notification and I can control audio from there but while playing video it not showing any notification.

I want to show the controller on notification for video too.

Does anyone have any idea how can i achieve this? Thank you so much in advance for your time and effort.

```<code>1) First image audio controller.
2) Second image audio is playing.
3) third image both video is playing but the notification not showing in Android or in IOS.
</code>```

Body:
i made application which play audio and video files.

for playing audio i used => just_audio: ^0.9.28 and for audio notification user => audio_service: ^0.18.7

but my main issue is with the video player. to play videos I use  chewie: ^1.3.5
and video_player: ^2.4.7

and now when I play audio it will show a notification and I can control audio from there but while playing video it not showing any notification.

I want to show the controller on notification for video too.

Does anyone have any idea how can i achieve this? Thank you so much in advance for your time and effort.

1) First image audio controller.
2) Second image audio is playing.
3) third image both video is playing but the notification not showing in Android or in IOS.


问:
Explain HTML img src urls
I'm building a scraper to grab some Yugioh card images from the official Konami card database. The HTML surrounding card images is as such:

The base url is: https://www.db.yugioh-card.com

However, if I visit: https://www.db.yugioh-card.com/yugiohdb/get_image.action?type=1&osplang=1&cid=17991&ciid=1&;enc=_eYdjsTOl-_0X1rcfo6YwA, I get no image. It seems that this type of url is related to a Java framework, but regardless, I should be able to access the images since they are obvioulsy rendering client side, no? Forgive me, I haven't encountered this when scraping before.

Could anyone shed some light on these types of urls, and if possible, how to access the image directly?

Thanks,

Title: Explain HTML img src urls


问:
How to iterate over multiple sheets and insert new columns in multiple workbooks in python
I am trying to  iterate over multiple sheets and insert new columns in multiple workbooks in python, here is my code:

file_list is the list of all workbooks that each have multiple sheets , and I am trying to insert new columns in each sheet of every workbook.
when I run the code, it gives me this error: "ValueError: Invalid file path or buffer object type: <class 'collections.OrderedDict'>"
The error occurs in the second loop for sheets.
Any help will be appreciated.

```<code>  for i, file in enumerate(file_list):
   print(i, file)
   wb = pd.ExcelFile(file)

  print(wb.sheet_names)
sheets = pd.read_excel(workbook, None)

   for sheet in wb.sheet:

        file1 = pd.read_excel(file_list[i], sheet)
        file1.insert(loc=2, column ='group_number', value = (file1.groupby(['p_key']).ngroup() + 1000) + group_number)
        file1.insert(loc=3, column ='batch_number', value = file1['group_number'].apply(lambda x: round_down(x, 1000)))
        file1.insert(loc=8, column = "primary_owner_2", value = file1["primary_owner"])
        wb.save("batched_"+ file_list[i][6:])
       # file1.to_excel(writer, sheet_name = sheet, index = False)
        group_number = group_number + len(file1.groupby(by = "p_key"))

   print(group_number)
</code>```

I am expecting the second loop of the code works but it doesnt.

Body:
I am trying to  iterate over multiple sheets and insert new columns in multiple workbooks in python, here is my code:

file_list is the list of all workbooks that each have multiple sheets , and I am trying to insert new columns in each sheet of every workbook.
when I run the code, it gives me this error: "ValueError: Invalid file path or buffer object type: <class 'collections.OrderedDict'>"
The error occurs in the second loop for sheets.
Any help will be appreciated.

  for i, file in enumerate(file_list):
   print(i, file)
   wb = pd.ExcelFile(file)

  print(wb.sheet_names)
sheets = pd.read_excel(workbook, None)

   for sheet in wb.sheet:

        file1 = pd.read_excel(file_list[i], sheet)
        file1.insert(loc=2, column ='group_number', value = (file1.groupby(['p_key']).ngroup() + 1000) + group_number)
        file1.insert(loc=3, column ='batch_number', value = file1['group_number'].apply(lambda x: round_down(x, 1000)))
        file1.insert(loc=8, column = "primary_owner_2", value = file1["primary_owner"])
        wb.save("batched_"+ file_list[i][6:])
       # file1.to_excel(writer, sheet_name = sheet, index = False)
        group_number = group_number + len(file1.groupby(by = "p_key"))

   print(group_number)

I am expecting the second loop of the code works but it doesnt.


问:
JavaFX Text Area Append Causes Two Errors
I am writing a program that checks prices and if it increases past a set amount then lets the user know by putting into a JavaFX text area line by line with a time stamp, appendText() spits out 2 errors. The error codes don't point to anything specific which is causing me to go in circles.

Most of the code works and if I use System.out.print() instead the code runs perfectly, but if I use txtContent.appendText() then at a random time in the first five minutes I will get one of the following errors.

```<code>Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Cannot read the array length because "this.lines" is null
    at javafx.graphics@19/com.sun.javafx.text.PrismTextLayout.layout(PrismTextLayout.java:1222)
    at javafx.graphics@19/com.sun.javafx.text.PrismTextLayout.ensureLayout(PrismTextLayout.java:223)
    at javafx.graphics@19/com.sun.javafx.text.PrismTextLayout.getBounds(PrismTextLayout.java:246)
    at javafx.graphics@19/javafx.scene.text.Text.getLogicalBounds(Text.java:432)
    at javafx.graphics@19/javafx.scene.text.Text.doComputeGeomBounds(Text.java:1187)
    at javafx.graphics@19/javafx.scene.text.Text$1.doComputeGeomBounds(Text.java:149)
    at javafx.graphics@19/com.sun.javafx.scene.shape.TextHelper.computeGeomBoundsImpl(TextHelper.java:90)
    at javafx.graphics@19/com.sun.javafx.scene.NodeHelper.computeGeomBounds(NodeHelper.java:117)
    at javafx.graphics@19/javafx.scene.Node.updateGeomBounds(Node.java:3825)
    at javafx.graphics@19/javafx.scene.Node.getGeomBounds(Node.java:3787)
    at javafx.graphics@19/javafx.scene.Node.getLocalBounds(Node.java:3735)
    at javafx.graphics@19/javafx.scene.Node$MiscProperties$3.computeBounds(Node.java:6825)
    at javafx.graphics@19/javafx.scene.Node$LazyBoundsProperty.get(Node.java:9840)
    at javafx.graphics@19/javafx.scene.Node$LazyBoundsProperty.get(Node.java:9810)
    at javafx.graphics@19/javafx.scene.Node.getBoundsInLocal(Node.java:3415)
    at javafx.controls@19/javafx.scene.control.skin.TextAreaSkin$ContentView.layoutChildren(TextAreaSkin.java:1324)
    at javafx.graphics@19/javafx.scene.Parent.layout(Parent.java:1207)
    at javafx.graphics@19/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@19/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@19/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@19/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@19/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@19/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@19/javafx.scene.Scene.doLayoutPass(Scene.java:592)
    at javafx.graphics@19/javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2512)
    at javafx.graphics@19/com.sun.javafx.tk.Toolkit.lambda$runPulse$2(Toolkit.java:407)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at javafx.graphics@19/com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:406)
    at javafx.graphics@19/com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:436)
    at javafx.graphics@19/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:575)
    at javafx.graphics@19/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:555)
    at javafx.graphics@19/com.sun.javafx.tk.quantum.QuantumToolkit.pulseFromQueue(QuantumToolkit.java:548)
    at javafx.graphics@19/com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$11(QuantumToolkit.java:352)
    at javafx.graphics@19/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics@19/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics@19/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
    at java.base/java.lang.Thread.run(Thread.java:1589)

</code>```
```<code>Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException: Index -1 out of bounds for length 2
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:100)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:106)
    at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:302)
    at java.base/java.util.Objects.checkIndex(Objects.java:385)
    at java.base/java.util.ArrayList.get(ArrayList.java:427)
    at javafx.base@19/com.sun.javafx.collections.ObservableListWrapper.get(ObservableListWrapper.java:89)
    at javafx.base@19/com.sun.javafx.collections.VetoableListDecorator.get(VetoableListDecorator.java:305)
    at javafx.graphics@19/javafx.scene.Parent.updateCachedBounds(Parent.java:1704)
    at javafx.graphics@19/javafx.scene.Parent.recomputeBounds(Parent.java:1648)
    at javafx.graphics@19/javafx.scene.Parent.doComputeGeomBounds(Parent.java:1501)
    at javafx.graphics@19/javafx.scene.Parent$1.doComputeGeomBounds(Parent.java:115)
    at javafx.graphics@19/com.sun.javafx.scene.ParentHelper.computeGeomBoundsImpl(ParentHelper.java:84)
    at javafx.graphics@19/com.sun.javafx.scene.layout.RegionHelper.superComputeGeomBoundsImpl(RegionHelper.java:78)
    at javafx.graphics@19/com.sun.javafx.scene.layout.RegionHelper.superComputeGeomBounds(RegionHelper.java:62)
    at javafx.graphics@19/javafx.scene.layout.Region.doComputeGeomBounds(Region.java:3355)
    at javafx.graphics@19/javafx.scene.layout.Region$1.doComputeGeomBounds(Region.java:168)
    at javafx.graphics@19/com.sun.javafx.scene.layout.RegionHelper.computeGeomBoundsImpl(RegionHelper.java:89)
    at javafx.graphics@19/com.sun.javafx.scene.NodeHelper.computeGeomBounds(NodeHelper.java:117)
    at javafx.graphics@19/javafx.scene.Node.updateGeomBounds(Node.java:3825)
    at javafx.graphics@19/javafx.scene.Node.getGeomBounds(Node.java:3787)
    at javafx.graphics@19/javafx.scene.Node.getLocalBounds(Node.java:3735)
    at javafx.graphics@19/javafx.scene.Node.intersectsBounds(Node.java:5270)
    at javafx.graphics@19/javafx.scene.Node$1.intersectsBounds(Node.java:559)
    at javafx.graphics@19/com.sun.javafx.scene.NodeHelper.intersectsBounds(NodeHelper.java:264)
    at javafx.graphics@19/javafx.scene.layout.Region.doPickNodeLocal(Region.java:3224)
    at javafx.graphics@19/javafx.scene.layout.Region$1.doPickNodeLocal(Region.java:184)
    at javafx.graphics@19/com.sun.javafx.scene.layout.RegionHelper.pickNodeLocalImpl(RegionHelper.java:104)
    at javafx.graphics@19/com.sun.javafx.scene.NodeHelper.pickNodeLocal(NodeHelper.java:130)
    at javafx.graphics@19/javafx.scene.Node.pickNode(Node.java:5180)
    at javafx.graphics@19/javafx.scene.Scene$MouseHandler.pickNode(Scene.java:4037)
    at javafx.graphics@19/javafx.scene.Scene.pick(Scene.java:2067)
    at javafx.graphics@19/javafx.scene.Scene$MouseHandler.process(Scene.java:3847)
    at javafx.graphics@19/javafx.scene.Scene.processMouseEvent(Scene.java:1887)
    at javafx.graphics@19/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2620)
    at javafx.graphics@19/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:411)
    at javafx.graphics@19/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:301)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at javafx.graphics@19/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:450)
    at javafx.graphics@19/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:424)
    at javafx.graphics@19/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:449)
    at javafx.graphics@19/com.sun.glass.ui.View.handleMouseEvent(View.java:551)
    at javafx.graphics@19/com.sun.glass.ui.View.notifyMouse(View.java:937)
    at javafx.graphics@19/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics@19/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
    at java.base/java.lang.Thread.run(Thread.java:1589)
</code>```

Normally when I get errors like this I will follow errors to the part that I wrote something incorrect or made some mistake with my work. But these don't point to anything in particular other than my runLoop which is pretty simple.

```<code>try
        {
            Database.deleteLastRow();
            Database.updateRows();

            JSONAccess.createNewRow();

            if(increaseCounter)
            {
                rowCounter++;
            }

            if(rowCounter >= Main.calculatedRows)
            {
                if(testLine)
                {
                    System.out.println("Starting");
                    testLine = false;
                }
                increaseCounter = false;
                MainGUI.txtContent.appendText("\n New Section");
                Database.compareValues();
            }
        }
        catch (Exception e)
        {
            MainGUI.btnStart.setDisable(false);
            MainGUI.btnStop.setDisable(true);
            System.out.println("Test to see if something goes wrong");
        }
</code>```
```<code>public static void compareValues() throws Exception
    {
        Class.forName("org.hsqldb.jdbc.JDBCDriver");

        for (String tableName : symbolsList)
        {
            String compareSql = "SELECT * FROM tbl_" + tableName + " ORDER BY id";
            prepStatement = connection.prepareStatement(compareSql);

            ResultSet rs = prepStatement.executeQuery();
            int rowNum = 1;
            while (rs.next())
            {
                if (rowNum == 1)
                {
                    dblNew = rs.getDouble("val");
                }
                if (rowNum == Main.calculatedRows)
                {
                    dblOld = rs.getDouble("val");
                }
                rowNum = Main.calculatedRows;
            }
            mathsCompare(tableName, dblNew, dblOld);
        }
    }

    public static void mathsCompare(String tableName1, double dblNew1, double dblOld1) throws Exception
    {
        if(dblNew1>dblOld1)
        {
            double dblChange = ((dblNew1-dblOld1)/dblOld1)*100;

            if(dblChange >= Main.dblPercentage)
            {
                MainGUI.txtContent.appendText("\n" + tableName1);
                System.out.print("\n" + tableName1);
            }
        }
    }
</code>```

If I have both System.out.println and MainGUI.txtContent.appendText enabled then the console gets an extra set of values out before the error comes out but thats when I get stumped

Any help appreciated.

Body:
I am writing a program that checks prices and if it increases past a set amount then lets the user know by putting into a JavaFX text area line by line with a time stamp, appendText() spits out 2 errors. The error codes don't point to anything specific which is causing me to go in circles.

Most of the code works and if I use System.out.print() instead the code runs perfectly, but if I use txtContent.appendText() then at a random time in the first five minutes I will get one of the following errors.

Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Cannot read the array length because "this.lines" is null
    at javafx.graphics@19/com.sun.javafx.text.PrismTextLayout.layout(PrismTextLayout.java:1222)
    at javafx.graphics@19/com.sun.javafx.text.PrismTextLayout.ensureLayout(PrismTextLayout.java:223)
    at javafx.graphics@19/com.sun.javafx.text.PrismTextLayout.getBounds(PrismTextLayout.java:246)
    at javafx.graphics@19/javafx.scene.text.Text.getLogicalBounds(Text.java:432)
    at javafx.graphics@19/javafx.scene.text.Text.doComputeGeomBounds(Text.java:1187)
    at javafx.graphics@19/javafx.scene.text.Text$1.doComputeGeomBounds(Text.java:149)
    at javafx.graphics@19/com.sun.javafx.scene.shape.TextHelper.computeGeomBoundsImpl(TextHelper.java:90)
    at javafx.graphics@19/com.sun.javafx.scene.NodeHelper.computeGeomBounds(NodeHelper.java:117)
    at javafx.graphics@19/javafx.scene.Node.updateGeomBounds(Node.java:3825)
    at javafx.graphics@19/javafx.scene.Node.getGeomBounds(Node.java:3787)
    at javafx.graphics@19/javafx.scene.Node.getLocalBounds(Node.java:3735)
    at javafx.graphics@19/javafx.scene.Node$MiscProperties$3.computeBounds(Node.java:6825)
    at javafx.graphics@19/javafx.scene.Node$LazyBoundsProperty.get(Node.java:9840)
    at javafx.graphics@19/javafx.scene.Node$LazyBoundsProperty.get(Node.java:9810)
    at javafx.graphics@19/javafx.scene.Node.getBoundsInLocal(Node.java:3415)
    at javafx.controls@19/javafx.scene.control.skin.TextAreaSkin$ContentView.layoutChildren(TextAreaSkin.java:1324)
    at javafx.graphics@19/javafx.scene.Parent.layout(Parent.java:1207)
    at javafx.graphics@19/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@19/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@19/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@19/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@19/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@19/javafx.scene.Parent.layout(Parent.java:1214)
    at javafx.graphics@19/javafx.scene.Scene.doLayoutPass(Scene.java:592)
    at javafx.graphics@19/javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2512)
    at javafx.graphics@19/com.sun.javafx.tk.Toolkit.lambda$runPulse$2(Toolkit.java:407)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at javafx.graphics@19/com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:406)
    at javafx.graphics@19/com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:436)
    at javafx.graphics@19/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:575)
    at javafx.graphics@19/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:555)
    at javafx.graphics@19/com.sun.javafx.tk.quantum.QuantumToolkit.pulseFromQueue(QuantumToolkit.java:548)
    at javafx.graphics@19/com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$11(QuantumToolkit.java:352)
    at javafx.graphics@19/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics@19/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics@19/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
    at java.base/java.lang.Thread.run(Thread.java:1589)

Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException: Index -1 out of bounds for length 2
    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:100)
    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:106)
    at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:302)
    at java.base/java.util.Objects.checkIndex(Objects.java:385)
    at java.base/java.util.ArrayList.get(ArrayList.java:427)
    at javafx.base@19/com.sun.javafx.collections.ObservableListWrapper.get(ObservableListWrapper.java:89)
    at javafx.base@19/com.sun.javafx.collections.VetoableListDecorator.get(VetoableListDecorator.java:305)
    at javafx.graphics@19/javafx.scene.Parent.updateCachedBounds(Parent.java:1704)
    at javafx.graphics@19/javafx.scene.Parent.recomputeBounds(Parent.java:1648)
    at javafx.graphics@19/javafx.scene.Parent.doComputeGeomBounds(Parent.java:1501)
    at javafx.graphics@19/javafx.scene.Parent$1.doComputeGeomBounds(Parent.java:115)
    at javafx.graphics@19/com.sun.javafx.scene.ParentHelper.computeGeomBoundsImpl(ParentHelper.java:84)
    at javafx.graphics@19/com.sun.javafx.scene.layout.RegionHelper.superComputeGeomBoundsImpl(RegionHelper.java:78)
    at javafx.graphics@19/com.sun.javafx.scene.layout.RegionHelper.superComputeGeomBounds(RegionHelper.java:62)
    at javafx.graphics@19/javafx.scene.layout.Region.doComputeGeomBounds(Region.java:3355)
    at javafx.graphics@19/javafx.scene.layout.Region$1.doComputeGeomBounds(Region.java:168)
    at javafx.graphics@19/com.sun.javafx.scene.layout.RegionHelper.computeGeomBoundsImpl(RegionHelper.java:89)
    at javafx.graphics@19/com.sun.javafx.scene.NodeHelper.computeGeomBounds(NodeHelper.java:117)
    at javafx.graphics@19/javafx.scene.Node.updateGeomBounds(Node.java:3825)
    at javafx.graphics@19/javafx.scene.Node.getGeomBounds(Node.java:3787)
    at javafx.graphics@19/javafx.scene.Node.getLocalBounds(Node.java:3735)
    at javafx.graphics@19/javafx.scene.Node.intersectsBounds(Node.java:5270)
    at javafx.graphics@19/javafx.scene.Node$1.intersectsBounds(Node.java:559)
    at javafx.graphics@19/com.sun.javafx.scene.NodeHelper.intersectsBounds(NodeHelper.java:264)
    at javafx.graphics@19/javafx.scene.layout.Region.doPickNodeLocal(Region.java:3224)
    at javafx.graphics@19/javafx.scene.layout.Region$1.doPickNodeLocal(Region.java:184)
    at javafx.graphics@19/com.sun.javafx.scene.layout.RegionHelper.pickNodeLocalImpl(RegionHelper.java:104)
    at javafx.graphics@19/com.sun.javafx.scene.NodeHelper.pickNodeLocal(NodeHelper.java:130)
    at javafx.graphics@19/javafx.scene.Node.pickNode(Node.java:5180)
    at javafx.graphics@19/javafx.scene.Scene$MouseHandler.pickNode(Scene.java:4037)
    at javafx.graphics@19/javafx.scene.Scene.pick(Scene.java:2067)
    at javafx.graphics@19/javafx.scene.Scene$MouseHandler.process(Scene.java:3847)
    at javafx.graphics@19/javafx.scene.Scene.processMouseEvent(Scene.java:1887)
    at javafx.graphics@19/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2620)
    at javafx.graphics@19/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:411)
    at javafx.graphics@19/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:301)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at javafx.graphics@19/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:450)
    at javafx.graphics@19/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:424)
    at javafx.graphics@19/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:449)
    at javafx.graphics@19/com.sun.glass.ui.View.handleMouseEvent(View.java:551)
    at javafx.graphics@19/com.sun.glass.ui.View.notifyMouse(View.java:937)
    at javafx.graphics@19/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics@19/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
    at java.base/java.lang.Thread.run(Thread.java:1589)

Normally when I get errors like this I will follow errors to the part that I wrote something incorrect or made some mistake with my work. But these don't point to anything in particular other than my runLoop which is pretty simple.

try
        {
            Database.deleteLastRow();
            Database.updateRows();

            JSONAccess.createNewRow();

            if(increaseCounter)
            {
                rowCounter++;
            }

            if(rowCounter >= Main.calculatedRows)
            {
                if(testLine)
                {
                    System.out.println("Starting");
                    testLine = false;
                }
                increaseCounter = false;
                MainGUI.txtContent.appendText("\n New Section");
                Database.compareValues();
            }
        }
        catch (Exception e)
        {
            MainGUI.btnStart.setDisable(false);
            MainGUI.btnStop.setDisable(true);
            System.out.println("Test to see if something goes wrong");
        }

public static void compareValues() throws Exception
    {
        Class.forName("org.hsqldb.jdbc.JDBCDriver");

        for (String tableName : symbolsList)
        {
            String compareSql = "SELECT * FROM tbl_" + tableName + " ORDER BY id";
            prepStatement = connection.prepareStatement(compareSql);

            ResultSet rs = prepStatement.executeQuery();
            int rowNum = 1;
            while (rs.next())
            {
                if (rowNum == 1)
                {
                    dblNew = rs.getDouble("val");
                }
                if (rowNum == Main.calculatedRows)
                {
                    dblOld = rs.getDouble("val");
                }
                rowNum = Main.calculatedRows;
            }
            mathsCompare(tableName, dblNew, dblOld);
        }
    }

    public static void mathsCompare(String tableName1, double dblNew1, double dblOld1) throws Exception
    {
        if(dblNew1>dblOld1)
        {
            double dblChange = ((dblNew1-dblOld1)/dblOld1)*100;

            if(dblChange >= Main.dblPercentage)
            {
                MainGUI.txtContent.appendText("\n" + tableName1);
                System.out.print("\n" + tableName1);
            }
        }
    }

If I have both System.out.println and MainGUI.txtContent.appendText enabled then the console gets an extra set of values out before the error comes out but thats when I get stumped

Any help appreciated.


问:
AWS Cognito Admin create user API throws AliasExistsException but also creates the user
I am using AWS SDK (Java) for user creation in Cognito via Admin create/signup API documented here
The docs say that the method throws AliasExistException if a user creation is attempted using an email that already exists with another user.

To my surprise, the exception is thrown but at the same time, the user is created in Cognito as well and the new user overrides the email-verified flag for the existing user.

This cannot be the intended behavior. What is the purpose of an exception if the user is anyways created? How can we stop the creation of such users? Am I missing anything?

P.S: I am sending ForceAliasCreation as False


问:
Trying to implement AdSense in Flutter Web - TagError: adsbygoogle.push() error: No slot size for availableWidth=0
I have a Flutter app that uses AdMob but that doesn't work for web. As suggested by some solutions, I am trying to use an IFrame to display an AdSense ad. I have almost the same code as one example that worked for others, but for me, it does not show the ad and I get an error TagError: adsbygoogle.push() error: No slot size for availableWidth=0. Is there a better way to go about this? If not, what part of my code is causing the error?

adview.html:

```<code><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-<replace>"
        crossorigin="anonymous"></script>
<!-- Web Flutter Globe -->
<ins class="adsbygoogle"
     style="display:inline-block;width:320px;height:80px"
     data-ad-client="ca-pub-<replace>"
     data-ad-slot="<replace>"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</code>```

adview.dart:

```<code>import 'mobile_implementation.dart'
if (dart.library.html) 'web_implementation.dart'
as package;
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';

class AdsenseWeb extends StatelessWidget {
  const AdsenseWeb({super.key, required this.height, required this.width});

  final double height;
  final double width;

  @override
  Widget build(BuildContext context) {
    return kIsWeb
        ? package.AdsenseWeb.adsenseAdsView(width, height)
        : const SizedBox();
  }
}
</code>```

web_implementation.dart:

```<code>import 'dart:html';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';

class AdsenseWeb {

  static Widget adsenseAdsView(double width, double height) {
    // ignore: undefined_prefixed_name
    ui.platformViewRegistry.registerViewFactory(
        'adViewType',
            (int viewID) => IFrameElement()
          ..width = '$width'
          ..height = '$height'
          ..src = 'adview.html'
          ..style.border = 'none');

    return SizedBox(
      height: height,
      width: width,
      child: const HtmlElementView(
        viewType: 'adViewType',
      ),
    );
  }
}
</code>```

mobile_implementation.dart:

```<code>import 'package:flutter/material.dart';

class AdsenseWeb {
  static Widget adsenseAdsView(double width, double height) {
    return const SizedBox();
  }
}
</code>```

Body:
I have a Flutter app that uses AdMob but that doesn't work for web. As suggested by some solutions, I am trying to use an IFrame to display an AdSense ad. I have almost the same code as one example that worked for others, but for me, it does not show the ad and I get an error TagError: adsbygoogle.push() error: No slot size for availableWidth=0. Is there a better way to go about this? If not, what part of my code is causing the error?

adview.html:

<ins class="adsbygoogle"
     style="display:inline-block;width:320px;height:80px"
     data-ad-client="ca-pub-<replace>"
     data-ad-slot="<replace>"
     data-ad-format="auto"
     data-full-width-responsive="true">

adview.dart:

import 'mobile_implementation.dart'
if (dart.library.html) 'web_implementation.dart'
as package;
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';

class AdsenseWeb extends StatelessWidget {
  const AdsenseWeb({super.key, required this.height, required this.width});

  final double height;
  final double width;

  @override
  Widget build(BuildContext context) {
    return kIsWeb
        ? package.AdsenseWeb.adsenseAdsView(width, height)
        : const SizedBox();
  }
}

web_implementation.dart:

import 'dart:html';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';

class AdsenseWeb {

  static Widget adsenseAdsView(double width, double height) {
    // ignore: undefined_prefixed_name
    ui.platformViewRegistry.registerViewFactory(
        'adViewType',
            (int viewID) => IFrameElement()
          ..width = '$width'
          ..height = '$height'
          ..src = 'adview.html'
          ..style.border = 'none');

    return SizedBox(
      height: height,
      width: width,
      child: const HtmlElementView(
        viewType: 'adViewType',
      ),
    );
  }
}

mobile_implementation.dart:

import 'package:flutter/material.dart';

class AdsenseWeb {
  static Widget adsenseAdsView(double width, double height) {
    return const SizedBox();
  }
}


问:
Upgraded PHP & Symfony, now getting "Call to a member function render() on null" using Twig
I recently upgraded PHP from 7.4 to 8.2 and with that, I've upgraded Symfony, Twig to the current versions. (Twig 3.5) Unfortunately that has now broken my application. I've managed to fix everything up till now but I'm stuck with the Template and and it's function to render pages using Twig.

The error is:

```<code>Fatal error:  Uncaught Error: Call to a member function render() on null in /var/www/html/website/lib/Template.php:79
</code>```

```<code>Stack trace:
#0 /var/www/html/website/lib/Handler.php(44): MyProject\Template::render()
#1 /var/www/html/website/lib/Handler.php(61): MyProject\Handler::error()
#2 [internal function]: MyProject\Handler::exception()
#3 {main}
  thrown in /var/www/html/website/lib/Template.php on line 79<
</code>```

This is on the initial index page to the website. The code in question is:

```<code>    public static function render($template, $args = [], $returnOutput = false)
    {
        $arg['user'] = Auth::user();
        $output = self::$twig->render($template . '.twig', $args);

        if (getenv('STAGE') == 'dev') {
            $output = self::$purifierExtension->getLog() . $output;
        }

        if ($returnOutput) {
            return $output;
        } else {
            echo $output;
        }
    }

</code>```

The page that is calling this function is this one:

```<code>    MyProject\Template::header('MyProject', true);

    $user = MyProject\Auth::user();
    $args = [
        'error' => false,
        'redirect' => isset($_GET['redirect']) && $_GET['redirect'] ? $_GET['redirect'] : 'main.php',
        'username' => ''
    ];

    if (!$user && isset($_POST['username'])) {
        MyProject\Form::validateCsrf('login');

        $username = $_POST['username'];
        $passwrd = $_POST['password'];

        // query for matching user/password
        try {
            $MyProjectuserid = MyProject\Auth::login($username, $passwrd);
        } catch (UnauthorizedHttpException $ex) {
            $args['error'] = 'Could not login. Please try again.';
            $args['username'] = $username;
        }
    }

    if (MyProject\Auth::user()) {
        MyProject\Alert::redirect($args['redirect']);
    }

    MyProject\Template::render('index', $args);

    MyProject\Template::footer();

</code>```

I have checked file permissions, I have removed and reinstalled the packages using Composer, and I have commented out various lines, leaving just this line as the culprit:

```<code>    $output = self::$twig->render($template . '.twig', $args);
</code>```

Any suggestions or help you can offer will be most gratefully received!

Additional info:

Thanks for your comment. I confess I have inherited this site and am not familiar with Symfony/Twig (I'm more of a dba person). The only initialisation I can find are these:
in Template.php

```<code>    private static $twig;
        self::$twig = new Twig_Environment($loader);
        self::$twig->addFunction($fn);
        self::$twig->addExtension(self::$purifierExtension);
        self::$twig->addExtension(self::$answerTypeExt);
    $output = self::$twig->render($template . '.twig', $args);
        return self::$twig;
</code>```

and in Handler.php

```<code>    public static function init()
    {
        $loader = new Twig_Loader_Filesystem('templates');
        self::$twig = new Twig_Environment($loader);
</code>```

This site used to work until a recent PHP/Symfony stack upgrade. So is this something in the logic used to be acceptable but isn't any more?

Bootstrap.php loads various files:

```<code>require('vendor/autoload.php');
use Symfony\Component\Dotenv\Dotenv;
$dotenv = new Dotenv();
$dotenv->load(DIR.'/../.env');
MyProject\Handler::init();
MyProject\DB::init();
MyProject\Auth::init();
MyProject\Template::init();
MyProject\Form::init();
</code>```

Body:
I recently upgraded PHP from 7.4 to 8.2 and with that, I've upgraded Symfony, Twig to the current versions. (Twig 3.5) Unfortunately that has now broken my application. I've managed to fix everything up till now but I'm stuck with the Template and and it's function to render pages using Twig.

The error is:

Fatal error:  Uncaught Error: Call to a member function render() on null in /var/www/html/website/lib/Template.php:79

Stack trace:
#0 /var/www/html/website/lib/Handler.php(44): MyProject\Template::render()
#1 /var/www/html/website/lib/Handler.php(61): MyProject\Handler::error()
#2 [internal function]: MyProject\Handler::exception()
#3 {main}
  thrown in /var/www/html/website/lib/Template.php on line 79<

This is on the initial index page to the website. The code in question is:

    public static function render($template, $args = [], $returnOutput = false)
    {
        $arg['user'] = Auth::user();
        $output = self::$twig->render($template . '.twig', $args);

        if (getenv('STAGE') == 'dev') {
            $output = self::$purifierExtension->getLog() . $output;
        }

        if ($returnOutput) {
            return $output;
        } else {
            echo $output;
        }
    }

The page that is calling this function is this one:

    MyProject\Template::header('MyProject', true);

    $user = MyProject\Auth::user();
    $args = [
        'error' => false,
        'redirect' => isset($_GET['redirect']) && $_GET['redirect'] ? $_GET['redirect'] : 'main.php',
        'username' => ''
    ];

    if (!$user && isset($_POST['username'])) {
        MyProject\Form::validateCsrf('login');

        $username = $_POST['username'];
        $passwrd = $_POST['password'];

        // query for matching user/password
        try {
            $MyProjectuserid = MyProject\Auth::login($username, $passwrd);
        } catch (UnauthorizedHttpException $ex) {
            $args['error'] = 'Could not login. Please try again.';
            $args['username'] = $username;
        }
    }

    if (MyProject\Auth::user()) {
        MyProject\Alert::redirect($args['redirect']);
    }

    MyProject\Template::render('index', $args);

    MyProject\Template::footer();

I have checked file permissions, I have removed and reinstalled the packages using Composer, and I have commented out various lines, leaving just this line as the culprit:

    $output = self::$twig->render($template . '.twig', $args);

Any suggestions or help you can offer will be most gratefully received!

Additional info:

Thanks for your comment. I confess I have inherited this site and am not familiar with Symfony/Twig (I'm more of a dba person). The only initialisation I can find are these:
in Template.php

    private static $twig;
        self::$twig = new Twig_Environment($loader);
        self::$twig->addFunction($fn);
        self::$twig->addExtension(self::$purifierExtension);
        self::$twig->addExtension(self::$answerTypeExt);
    $output = self::$twig->render($template . '.twig', $args);
        return self::$twig;

and in Handler.php

    public static function init()
    {
        $loader = new Twig_Loader_Filesystem('templates');
        self::$twig = new Twig_Environment($loader);

This site used to work until a recent PHP/Symfony stack upgrade. So is this something in the logic used to be acceptable but isn't any more?

Bootstrap.php loads various files:

require('vendor/autoload.php');
use Symfony\Component\Dotenv\Dotenv;
$dotenv = new Dotenv();
$dotenv->load(DIR.'/../.env');
MyProject\Handler::init();
MyProject\DB::init();
MyProject\Auth::init();
MyProject\Template::init();
MyProject\Form::init();


问:
Flex connector integration with postgreSql
How can I integrate flex connector with postgreSql? Is that possible and if so, what will be the whole procedure to do it?

Basically we want to integrate arksite with postgreSql and postgreSql doesn't have its own connector for integration purposes.

So is there any alternate way to integrate postgresql with arksite to get the desired database logs on the esm of arksite

I haven't tried anything yet, because there is nothing available on internet about that.


问:
add a custome domain to firebase hosting
i am tring to a dd acustome domain and change the email verification to it through firebase and I add the new server and show to me it is connected but when I try to open my website I found this error


问:
Method ReflectionParameter::getClass() is deprecated, even after downgrading php version to 7.4
I am having difficulty with Method ReflectionParameter::getClass() is deprecated, as suggested by many other posts, I downgraded the php version to 7.4, which didn't help. I am new to the php, so might not understand

downgraded php to 7.4.33


问:
Create Athena table with Json
I have done a lab question that requires me to find a string of text from logs which I have done so by the long way (excel) instead of the intelligent way (having data populated nicely on the table in Athena). I have multiple files within an S3 folder that has json format like this...

{"Records":[{"eventVersion":"1.05","userIdentity":{"type":"AssumedRole","principalId":"ARXXXXXXXXXXXXXXXXXFVEC:AWSConfig-Describe","arn":"arn:aws:sts::2CCCCCCCCC8:assumed-role/AWSServiceRoleForConfig/AWSConfig-Describe","accountId":"2CCCCCCCCC8","accessKeyId":"ASXXXXXXXXXXXXXXXQVL","sessionContext":{"sessionIssuer":{"type":"Role","principalId":"ARXXXXXXXXXXXXXXXXXFVEC","arn":"arn:aws:iam::2CCCCCCCCC8:role/aws-service-role/config.amazonaws.com/AWSServiceRoleForConfig","accountId":"2CCCCCCCCC8","userName":"AWSServiceRoleForConfig"},"attributes":{"creationDate":"2019-09-03T07:40:00Z","mfaAuthenticated":"false"}},"invokedBy":"AWS Internal"},"eventTime":"2019-09-03T07:40:00Z","eventSource":"s3.amazonaws.com","eventName":"HeadBucket","awsRegion":"us-west-2","sourceIPAddress":"172.18.87.252","userAgent":"[AWSConfig]","requestParameters":{"bucketName":"service_logs_10l51wolgib72","Host":"s3.us-west-2.amazonaws.com"},"responseElements":null,"additionalEventData":{"SignatureVersion":"SigV4","CipherSuite":"ECDHE-RSA-AES128-SHA","bytesTransferredIn":0.0,"AuthenticationMethod":"AuthHeader","x-amz-id-2":"JYEwSk6jEv2rB/MjwluNXcnKxRSo72GCOz8WP9OYXDFI2FxS1T81K7excoDuo36rJIQz9MWYKEE=","bytesTransferredOut":0.0},"requestID":"E224F90BD7370007","eventID":"77d7ea03-b8a2-4b50-8f81-b8217eacf008","readOnly":true,"resources":[{"type":"AWS::S3::Object","ARNPrefix":"arn:aws:s3:::service_logs_10l51wolgib72/"},{"accountId":"2CCCCCCCCC8","type":"AWS::S3::Bucket","ARN":"arn:aws:s3:::service_logs_10l51wolgib72"}],"eventType":"AwsApiCall","recipientAccountId":"2CCCCCCCCC8","vpcEndpointId":"vpce-3c0ee766"},{"eventVersion":"1.05","userIdentity":{"type":"AssumedRole","principalId":"ARXXXXXXXXXXXXXXXXXFVEC:AWSConfig-Describe","arn":"arn:aws:sts::2CCCCCCCCC8:assumed-role/AWSServiceRoleForConfig/AWSConfig-Describe","accountId":"2CCCCCCCCC8","accessKeyId":"ASXXXXXXXXXXXXXXXQVL","sessionContext":{"sessionIssuer":{"type":"Role","principalId":"ARXXXXXXXXXXXXXXXXXFVEC","arn":"arn:aws:iam::2CCCCCCCCC8:role/aws-service-role/config.amazonaws.com/AWSServiceRoleForConfig","accountId":"2CCCCCCCCC8","userName":"AWSServiceRoleForConfig"},"attributes":{"creationDate":"2019-09-03T07:40:00Z","mfaAuthenticated":"false"}},"invokedBy":"AWS Internal"},"eventTime":"2019-09-03T07:40:00Z","eventSource":"s3.amazonaws.com","eventName":"HeadBucket","awsRegion":"us-west-2","sourceIPAddress":"172.18.87.252","userAgent":"[AWSConfig]","requestParameters":{"bucketName":"service_logs_10l51wolgib72","Host":"s3.us-west-2.amazonaws.com"},"responseElements":null,"additionalEventData":{"SignatureVersion":"SigV4","CipherSuite":"ECDHE-RSA-AES128-SHA","bytesTransferredIn":0.0,"AuthenticationMethod":"AuthHeader","x-amz-id-2":"JYEwSk6jEv2rB/MjwluNXcnKxRSo72GCOz8WP9OYXDFI2FxS1T81K7excoDuo36rJIQz9MWYKEE=","bytesTransferredOut":0.0},"requestID":"E224F90BD7370020","eventID":"77d7ea03-b8a2-4b50-8f81-b8217eacf021","readOnly":true,"resources":[{"type":"AWS::S3::Object","ARNPrefix":"arn:aws:s3:::service_logs_10l51wolgib72/"},{"accountId":"2CCCCCCCCC8","type":"AWS::S3::Bucket","ARN":"arn:aws:s3:::service_logs_10l51wolgib72"}],"eventType":"AwsApiCall","recipientAccountId":"2CCCCCCCCC8","vpcEndpointId":"vpce-3c0ee766"},{"eventVersion":"1.05","userIdentity":{"type":"AssumedRole","principalId":"ARXXXXXXXXXXXXXXXXXFVEC:AWSConfig-Describe","arn":"arn:aws:sts::2CCCCCCCCC8:assumed-role/AWSServiceRoleForConfig/AWSConfig-Describe","accountId":"2CCCCCCCCC8","accessKeyId":"ASXXXXXXXXXXXXXXXQVL","sessionContext":{"sessionIssuer":{"type":"Role","principalId":"ARXXXXXXXXXXXXXXXXXFVEC","arn":"arn:aws:iam::2CCCCCCCCC8:role/aws-service-role/config.amazonaws.com/AWSServiceRoleForConfig","accountId":"2CCCCCCCCC8","userName":"AWSServiceRoleForConfig"},"attributes":{"creationDate":"2019-09-03T07:40:00Z","mfaAuthenticated":"false"}},"invokedBy":"AWS Internal"},"eventTime":"2019-09-03T07:40:00Z","eventSource":"s3.amazonaws.com","eventName":"HeadBucket","awsRegion":"us-west-2","sourceIPAddress":"172.18.87.252","userAgent":"[AWSConfig]","requestParameters":{"bucketName":"service_logs_10l51wolgib72","Host":"s3.us-west-2.amazonaws.com"},"responseElements":null,"additionalEventData":{"SignatureVersion":"SigV4","CipherSuite":"ECDHE-RSA-AES128-SHA","bytesTransferredIn":0.0,"AuthenticationMethod":"AuthHeader","x-amz-id-2":"JYEwSk6jEv2rB/MjwluNXcnKxRSo72GCOz8WP9OYXDFI2FxS1T81K7excoDuo36rJIQz9MWYKEE=","bytesTransferredOut":0.0},"requestID":"E224F90BD7370033","eventID":"77d7ea03-b8a2-4b50-8f81-b8217eacf034","readOnly":true,"resources":[{"type":"AWS::S3::Object","ARNPrefix":"arn:aws:s3:::service_logs_10l51wolgib72/"},{"accountId":"2CCCCCCCCC8","type":"AWS::S3::Bucket","ARN":"arn:aws:s3:::service_logs_10l51wolgib72"}],"eventType":"AwsApiCall","recipientAccountId":"2CCCCCCCCC8","vpcEndpointId":"vpce-3c0ee766"}]}
```
<p>I am importing them (the whole dir with the files sharing same format) into Athena using this code from online reference but no matter how I adjust, I still get the table with single column...</p>
<pre class="lang-sql prettyprint-override"><code>CREATE EXTERNAL TABLE IF NOT EXISTS `default`.testjson4 (
 Records struct<eventVersion:string,
             userIdentity:string,
             eventTime:string,
             eventSource:string>)

ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
WITH SERDEPROPERTIES (
  'ignore.malformed.json' = 'FALSE',
  'dots.in.keys' = 'FALSE',
  'case.insensitive' = 'TRUE',
  'mapping' = 'TRUE'
)
STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION 's3://******************/CloudTrail/us-east-1/****/'
TBLPROPERTIES ('classification' = 'json');
</code>```

Would like to get help on how to do this correctly, thank you!

Title: Create Athena table with Json

Body:
I have done a lab question that requires me to find a string of text from logs which I have done so by the long way (excel) instead of the intelligent way (having data populated nicely on the table in Athena). I have multiple files within an S3 folder that has json format like this...

{"Records":[{"eventVersion":"1.05","userIdentity":{"type":"AssumedRole","principalId":"ARXXXXXXXXXXXXXXXXXFVEC:AWSConfig-Describe","arn":"arn:aws:sts::2CCCCCCCCC8:assumed-role/AWSServiceRoleForConfig/AWSConfig-Describe","accountId":"2CCCCCCCCC8","accessKeyId":"ASXXXXXXXXXXXXXXXQVL","sessionContext":{"sessionIssuer":{"type":"Role","principalId":"ARXXXXXXXXXXXXXXXXXFVEC","arn":"arn:aws:iam::2CCCCCCCCC8:role/aws-service-role/config.amazonaws.com/AWSServiceRoleForConfig","accountId":"2CCCCCCCCC8","userName":"AWSServiceRoleForConfig"},"attributes":{"creationDate":"2019-09-03T07:40:00Z","mfaAuthenticated":"false"}},"invokedBy":"AWS Internal"},"eventTime":"2019-09-03T07:40:00Z","eventSource":"s3.amazonaws.com","eventName":"HeadBucket","awsRegion":"us-west-2","sourceIPAddress":"172.18.87.252","userAgent":"[AWSConfig]","requestParameters":{"bucketName":"service_logs_10l51wolgib72","Host":"s3.us-west-2.amazonaws.com"},"responseElements":null,"additionalEventData":{"SignatureVersion":"SigV4","CipherSuite":"ECDHE-RSA-AES128-SHA","bytesTransferredIn":0.0,"AuthenticationMethod":"AuthHeader","x-amz-id-2":"JYEwSk6jEv2rB/MjwluNXcnKxRSo72GCOz8WP9OYXDFI2FxS1T81K7excoDuo36rJIQz9MWYKEE=","bytesTransferredOut":0.0},"requestID":"E224F90BD7370007","eventID":"77d7ea03-b8a2-4b50-8f81-b8217eacf008","readOnly":true,"resources":[{"type":"AWS::S3::Object","ARNPrefix":"arn:aws:s3:::service_logs_10l51wolgib72/"},{"accountId":"2CCCCCCCCC8","type":"AWS::S3::Bucket","ARN":"arn:aws:s3:::service_logs_10l51wolgib72"}],"eventType":"AwsApiCall","recipientAccountId":"2CCCCCCCCC8","vpcEndpointId":"vpce-3c0ee766"},{"eventVersion":"1.05","userIdentity":{"type":"AssumedRole","principalId":"ARXXXXXXXXXXXXXXXXXFVEC:AWSConfig-Describe","arn":"arn:aws:sts::2CCCCCCCCC8:assumed-role/AWSServiceRoleForConfig/AWSConfig-Describe","accountId":"2CCCCCCCCC8","accessKeyId":"ASXXXXXXXXXXXXXXXQVL","sessionContext":{"sessionIssuer":{"type":"Role","principalId":"ARXXXXXXXXXXXXXXXXXFVEC","arn":"arn:aws:iam::2CCCCCCCCC8:role/aws-service-role/config.amazonaws.com/AWSServiceRoleForConfig","accountId":"2CCCCCCCCC8","userName":"AWSServiceRoleForConfig"},"attributes":{"creationDate":"2019-09-03T07:40:00Z","mfaAuthenticated":"false"}},"invokedBy":"AWS Internal"},"eventTime":"2019-09-03T07:40:00Z","eventSource":"s3.amazonaws.com","eventName":"HeadBucket","awsRegion":"us-west-2","sourceIPAddress":"172.18.87.252","userAgent":"[AWSConfig]","requestParameters":{"bucketName":"service_logs_10l51wolgib72","Host":"s3.us-west-2.amazonaws.com"},"responseElements":null,"additionalEventData":{"SignatureVersion":"SigV4","CipherSuite":"ECDHE-RSA-AES128-SHA","bytesTransferredIn":0.0,"AuthenticationMethod":"AuthHeader","x-amz-id-2":"JYEwSk6jEv2rB/MjwluNXcnKxRSo72GCOz8WP9OYXDFI2FxS1T81K7excoDuo36rJIQz9MWYKEE=","bytesTransferredOut":0.0},"requestID":"E224F90BD7370020","eventID":"77d7ea03-b8a2-4b50-8f81-b8217eacf021","readOnly":true,"resources":[{"type":"AWS::S3::Object","ARNPrefix":"arn:aws:s3:::service_logs_10l51wolgib72/"},{"accountId":"2CCCCCCCCC8","type":"AWS::S3::Bucket","ARN":"arn:aws:s3:::service_logs_10l51wolgib72"}],"eventType":"AwsApiCall","recipientAccountId":"2CCCCCCCCC8","vpcEndpointId":"vpce-3c0ee766"},{"eventVersion":"1.05","userIdentity":{"type":"AssumedRole","principalId":"ARXXXXXXXXXXXXXXXXXFVEC:AWSConfig-Describe","arn":"arn:aws:sts::2CCCCCCCCC8:assumed-role/AWSServiceRoleForConfig/AWSConfig-Describe","accountId":"2CCCCCCCCC8","accessKeyId":"ASXXXXXXXXXXXXXXXQVL","sessionContext":{"sessionIssuer":{"type":"Role","principalId":"ARXXXXXXXXXXXXXXXXXFVEC","arn":"arn:aws:iam::2CCCCCCCCC8:role/aws-service-role/config.amazonaws.com/AWSServiceRoleForConfig","accountId":"2CCCCCCCCC8","userName":"AWSServiceRoleForConfig"},"attributes":{"creationDate":"2019-09-03T07:40:00Z","mfaAuthenticated":"false"}},"invokedBy":"AWS Internal"},"eventTime":"2019-09-03T07:40:00Z","eventSource":"s3.amazonaws.com","eventName":"HeadBucket","awsRegion":"us-west-2","sourceIPAddress":"172.18.87.252","userAgent":"[AWSConfig]","requestParameters":{"bucketName":"service_logs_10l51wolgib72","Host":"s3.us-west-2.amazonaws.com"},"responseElements":null,"additionalEventData":{"SignatureVersion":"SigV4","CipherSuite":"ECDHE-RSA-AES128-SHA","bytesTransferredIn":0.0,"AuthenticationMethod":"AuthHeader","x-amz-id-2":"JYEwSk6jEv2rB/MjwluNXcnKxRSo72GCOz8WP9OYXDFI2FxS1T81K7excoDuo36rJIQz9MWYKEE=","bytesTransferredOut":0.0},"requestID":"E224F90BD7370033","eventID":"77d7ea03-b8a2-4b50-8f81-b8217eacf034","readOnly":true,"resources":[{"type":"AWS::S3::Object","ARNPrefix":"arn:aws:s3:::service_logs_10l51wolgib72/"},{"accountId":"2CCCCCCCCC8","type":"AWS::S3::Bucket","ARN":"arn:aws:s3:::service_logs_10l51wolgib72"}],"eventType":"AwsApiCall","recipientAccountId":"2CCCCCCCCC8","vpcEndpointId":"vpce-3c0ee766"}]}

I am importing them (the whole dir with the files sharing same format) into Athena using this code from online reference but no matter how I adjust, I still get the table with single column...

CREATE EXTERNAL TABLE IF NOT EXISTS `default`.testjson4 (
 Records struct<eventVersion:string,
             userIdentity:string,
             eventTime:string,
             eventSource:string>)

ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
WITH SERDEPROPERTIES (
  'ignore.malformed.json' = 'FALSE',
  'dots.in.keys' = 'FALSE',
  'case.insensitive' = 'TRUE',
  'mapping' = 'TRUE'
)
STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION 's3://******************/CloudTrail/us-east-1/****/'
TBLPROPERTIES ('classification' = 'json');

Would like to get help on how to do this correctly, thank you!