问:
why are my params not used unless hard coded for my react twitter embed api?
I'm building a random quote generator and have everything for it except it needs to be able to post to Twitter. I'm using react twitter compact api for this.
I get this error in my console
Could not read source map for https://abs.twimg.com/responsive-web/client-web/main.4756b7fa.js: Unexpected 503 response from https://ton.local.twitter.com/responsive-web-internal/sourcemaps/client-web/main.4756b7fa.js.map: getaddrinfo ENOTFOUND ton.local.twitter.com
for some reason, the Twitter tag only accepts hard-coded and not dynamic values.

url to project:https://github.com/JonathanDaboush/randomQuoteMachine.git

```<code>import React,{useState,  useEffect, useInsertionEffect} from "react";
import { useSelector, useDispatch  } from "react-redux";
import {randomize} from "./actions/Random";
import { TwitterTimelineEmbed, TwitterShareButton, TwitterFollowButton, TwitterHashtagButton, TwitterMentionButton, TwitterTweetEmbed, TwitterMomentShare, TwitterDMButton, TwitterVideoEmbed, TwitterOnAirButton } from 'react-twitter-embed';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
let Quote=()=>{

    let List=[
        {author:"Fishel, Ruth",quote:"Everything that is created begins in the mind"},
        {author:"Dossey, Larry M.D.",quote:"if physical world can affect mind but mind cannot affect physical world, then its the only one-way interaction known in science !!!"},
        {author:"Silva,J. & Miele, P.",quote:"All choice is made in the mind…all acceptance is made by the spirit…There are not billions of minds in this world at all, but only one, and it is in every one of us”"},
        {author:"Jampolsky, Gerold G. M.D.",quote:"Universal Mind -…there is one all uniting, universal Mind, one all-pervading Intelligence…these are no totally separate minds…waves in an ocean – a wave cannot separate itself…bucket of water poured into a pool – affects every other particle of water within the pool, whether it knows it or not"},
        {author:"Anderson, U.S.",quote:"Conceptual habits of the conscious mind = greatest bar to man’s discovery of himself"},
        {author:"Anderson, U.S.",quote:"Subconscious mind does exactly what the conscious mind tells it to do"},
        {author:"Jampolsky, Gerold G. M.D.",quote:"think whatever makes you truly happy to think”"},
        {author:"Ponder, Catherine",quote:"the body feeds on man’s words. Where those words are life-giving, they are health-producing."},
        {author:"Ponder, Catherine",quote:"What you notice, give attention to, talk about, get all worked up over emotionally is what you are inviting into your life, whether you mean to or not."},
        {author:"Price, John R.",quote:"Every thought we think, every feeling we have, every word we speak goes out into the atmosphere to either heal or harm. Let us be healers. Let us be harmless."},
        {author:"Harp, David",quote:"It is not the fear or desire thought that’s the problem – its the inability to control your reaction to that thought that may create a problem.”"},
        {author:"Fishel, Ruth",quote:"the past is stored in your subconscious automatically. In a similar experience, therefore, your subconscious responds and your conscious mind is fooled into thinking that the past is now"},
        {author:"Fishel, Ruth",quote:"…our earliest messages were how we judged ourselves, how we knew if we were okay or loved or worthwhile. They came from outside in, and the more they were repeated, the more strongly we owned them. They became imprinted on our subconscious to be heard over and over again."},
        {author:"Fishel, Ruth",quote:"You act out who you think you are."},
        {author:"Fishel, Ruth",quote:"Whatever we think, we feel What we think in our minds responds in our bodies. When we relive old experiences, our bodies do not know whether they are happening now or I our minds, so our bodies respond as if it were now. Our minds and bodies do not know the difference between real and imagined"},
        {author:"Golas, Thaddeus",quote:"It is your resistance to the negative thought, whether you bring it into consciousness or not, that makes it manifest in your life. Ask: What am I doing on a level of consciousness where this is real?"},
        {author:"Roman, Sanaya. Parker, Duane",quote:"Everytime you think of the future you are creating a possible direction”"},
        {author:"Roman, S.",quote:"Spend time thinking of what you want rather than what you don’t want."},
        {author:"Golas, Thaddeus",quote:"Some people think that “thoughts are things” and that you must avoid negative thoughts or they will happen. If you avoid negative thoughts, they will sooner or later manifest themselves physically. It is your resistance to the negative thought, whether you bring it to consciousness or not, that makes it manifest in your life."},
        {author:"Golas, Thaddeus",quote:"Never pull away suddenly from a negative thought or experience. Stay with it until you are indifferent to it or until it turns beautiful. Look at it, love it, then let it go."},
        {author:"Howard, Vernon",quote:"You need not work at thinking, at trying to find the right attitude toward something that happens to you. The problem arises because you have an attitude, a needless one. Dare to be without an attitude."},
        {author:"Holmes, Ernest ",quote:"That which you decide with the conscious mind and then commit to the action of the Law, in quiet trust, in perfect confidence, is that which will come to pass for you."},
        {author:"Holmes, Ernest",quote:"By thinking you change your environment."},
        {author:"Custer, Dan",quote:"To learn to think is to learn how to live."},
        {author:"Anderson, U.S",quote:"All things and all circumstances must first be created on the mental plane."}
    ];
let [fullQuote,setFq]=useState("");
    let [quote,setQuote]=useState("");
    let [author,setAuthor]=useState("");
    //an stands for account name.
    let [an,setAn]=useState("");
    let [url,setUrl]=useState("https://foundationforwellbeing.org/quotations-for-the-mind/");
    const state = useSelector((state) => state);
    const dispatch = useDispatch();
    let randomObjectGet=()=>{
        let newObject=List[state.number];
        setQuote((quote)=>newObject.quote);
        setAuthor((author)=>newObject.author);
        setFq((fullQuote)=>newObject.quote+" ,"+newObject.author)
    }
    let changeQuote=()=>{
        dispatch(randomize());
        randomObjectGet();

    };
    let changeUserName=(e)=>{
            setAn((an)=>e.target.value);

    }
    useEffect(()=>{
        dispatch(randomize());
        randomObjectGet();
    },[]);
    return(<div>
        <div>{quote}</div>
        <b>-{author}</b>
        <form onSubmit={changeQuote}>
            <input type="submit" value="New Quote!" />
        </form>
        <div>to share; please, enter your account username.</div>
       <label htmlFor="username">userName:</label>
        <input type="text" id="username" onChange={changeUserName} />
        <TwitterShareButton
    url={url}
    options={{ text: fullQuote, via: an }}
  />

    </div>);
}
export default Quote;
</code>```

Body:
I'm building a random quote generator and have everything for it except it needs to be able to post to Twitter. I'm using react twitter compact api for this.
I get this error in my console
Could not read source map for https://abs.twimg.com/responsive-web/client-web/main.4756b7fa.js: Unexpected 503 response from https://ton.local.twitter.com/responsive-web-internal/sourcemaps/client-web/main.4756b7fa.js.map: getaddrinfo ENOTFOUND ton.local.twitter.com
for some reason, the Twitter tag only accepts hard-coded and not dynamic values.

url to project:https://github.com/JonathanDaboush/randomQuoteMachine.git

import React,{useState,  useEffect, useInsertionEffect} from "react";
import { useSelector, useDispatch  } from "react-redux";
import {randomize} from "./actions/Random";
import { TwitterTimelineEmbed, TwitterShareButton, TwitterFollowButton, TwitterHashtagButton, TwitterMentionButton, TwitterTweetEmbed, TwitterMomentShare, TwitterDMButton, TwitterVideoEmbed, TwitterOnAirButton } from 'react-twitter-embed';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
let Quote=()=>{

    let List=[
        {author:"Fishel, Ruth",quote:"Everything that is created begins in the mind"},
        {author:"Dossey, Larry M.D.",quote:"if physical world can affect mind but mind cannot affect physical world, then its the only one-way interaction known in science !!!"},
        {author:"Silva,J. & Miele, P.",quote:"All choice is made in the mind…all acceptance is made by the spirit…There are not billions of minds in this world at all, but only one, and it is in every one of us”"},
        {author:"Jampolsky, Gerold G. M.D.",quote:"Universal Mind -…there is one all uniting, universal Mind, one all-pervading Intelligence…these are no totally separate minds…waves in an ocean – a wave cannot separate itself…bucket of water poured into a pool – affects every other particle of water within the pool, whether it knows it or not"},
        {author:"Anderson, U.S.",quote:"Conceptual habits of the conscious mind = greatest bar to man’s discovery of himself"},
        {author:"Anderson, U.S.",quote:"Subconscious mind does exactly what the conscious mind tells it to do"},
        {author:"Jampolsky, Gerold G. M.D.",quote:"think whatever makes you truly happy to think”"},
        {author:"Ponder, Catherine",quote:"the body feeds on man’s words. Where those words are life-giving, they are health-producing."},
        {author:"Ponder, Catherine",quote:"What you notice, give attention to, talk about, get all worked up over emotionally is what you are inviting into your life, whether you mean to or not."},
        {author:"Price, John R.",quote:"Every thought we think, every feeling we have, every word we speak goes out into the atmosphere to either heal or harm. Let us be healers. Let us be harmless."},
        {author:"Harp, David",quote:"It is not the fear or desire thought that’s the problem – its the inability to control your reaction to that thought that may create a problem.”"},
        {author:"Fishel, Ruth",quote:"the past is stored in your subconscious automatically. In a similar experience, therefore, your subconscious responds and your conscious mind is fooled into thinking that the past is now"},
        {author:"Fishel, Ruth",quote:"…our earliest messages were how we judged ourselves, how we knew if we were okay or loved or worthwhile. They came from outside in, and the more they were repeated, the more strongly we owned them. They became imprinted on our subconscious to be heard over and over again."},
        {author:"Fishel, Ruth",quote:"You act out who you think you are."},
        {author:"Fishel, Ruth",quote:"Whatever we think, we feel What we think in our minds responds in our bodies. When we relive old experiences, our bodies do not know whether they are happening now or I our minds, so our bodies respond as if it were now. Our minds and bodies do not know the difference between real and imagined"},
        {author:"Golas, Thaddeus",quote:"It is your resistance to the negative thought, whether you bring it into consciousness or not, that makes it manifest in your life. Ask: What am I doing on a level of consciousness where this is real?"},
        {author:"Roman, Sanaya. Parker, Duane",quote:"Everytime you think of the future you are creating a possible direction”"},
        {author:"Roman, S.",quote:"Spend time thinking of what you want rather than what you don’t want."},
        {author:"Golas, Thaddeus",quote:"Some people think that “thoughts are things” and that you must avoid negative thoughts or they will happen. If you avoid negative thoughts, they will sooner or later manifest themselves physically. It is your resistance to the negative thought, whether you bring it to consciousness or not, that makes it manifest in your life."},
        {author:"Golas, Thaddeus",quote:"Never pull away suddenly from a negative thought or experience. Stay with it until you are indifferent to it or until it turns beautiful. Look at it, love it, then let it go."},
        {author:"Howard, Vernon",quote:"You need not work at thinking, at trying to find the right attitude toward something that happens to you. The problem arises because you have an attitude, a needless one. Dare to be without an attitude."},
        {author:"Holmes, Ernest ",quote:"That which you decide with the conscious mind and then commit to the action of the Law, in quiet trust, in perfect confidence, is that which will come to pass for you."},
        {author:"Holmes, Ernest",quote:"By thinking you change your environment."},
        {author:"Custer, Dan",quote:"To learn to think is to learn how to live."},
        {author:"Anderson, U.S",quote:"All things and all circumstances must first be created on the mental plane."}
    ];
let [fullQuote,setFq]=useState("");
    let [quote,setQuote]=useState("");
    let [author,setAuthor]=useState("");
    //an stands for account name.
    let [an,setAn]=useState("");
    let [url,setUrl]=useState("https://foundationforwellbeing.org/quotations-for-the-mind/");
    const state = useSelector((state) => state);
    const dispatch = useDispatch();
    let randomObjectGet=()=>{
        let newObject=List[state.number];
        setQuote((quote)=>newObject.quote);
        setAuthor((author)=>newObject.author);
        setFq((fullQuote)=>newObject.quote+" ,"+newObject.author)
    }
    let changeQuote=()=>{
        dispatch(randomize());
        randomObjectGet();

    };
    let changeUserName=(e)=>{
            setAn((an)=>e.target.value);

    }
    useEffect(()=>{
        dispatch(randomize());
        randomObjectGet();
    },[]);
    return(

{quote}

        -{author}
        <form onSubmit={changeQuote}>
            <input type="submit" value="New Quote!" />
        </form>

to share; please, enter your account username.

       userName:
        <input type="text" id="username" onChange={changeUserName} />
        <TwitterShareButton
    url={url}
    options={{ text: fullQuote, via: an }}
  />

);
}
export default Quote;


来源: stackexchange

问:
rotate slices of a circle pygame
I saw an image of a game and i wanted to execute it in pygame, altough im having some trouble with it.

The main idea of the game is to actually have those two circles drawn like this, with the intersection lines.

and if the player click on the red circle for example it would rotate it and "take" a piece of the blue circle:

same if the player rotates the blue circle it would then take a piece of the red circle

I would try and place 4 circles around the red one, shuffle it, and then its a puzzle game that the player need to get them all in the correct places.

ContentLicense: CC BY-SA 4.0

Title: rotate slices of a circle pygame


问:
Junit test cases give InvocationTargetException with Java11 on graviton machines
I have been facing very weird issue where my unit test cases fail on arm graviton aws machines. The same unit test cases pass on intel machines with Java8

I am getting the below errors:

```<code>Exception in thread "main" java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:513)
    at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:525)
FATAL ERROR in native method: processing of -javaagent failed, processJavaStart failed
Caused by: java.lang.RuntimeException: Class java/lang/UnknownError could not be instrumented.
    at org.jacoco.agent.rt.internal_c13123e.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:140)
    at org.jacoco.agent.rt.internal_c13123e.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:101)
    at org.jacoco.agent.rt.internal_c13123e.PreMain.createRuntime(PreMain.java:55)
    at org.jacoco.agent.rt.internal_c13123e.PreMain.premain(PreMain.java:47)
    ... 6 more
Caused by: java.lang.NoSuchFieldException: $jacocoAccess
    at java.base/java.lang.Class.getField(Class.java:1999)
    at org.jacoco.agent.rt.internal_c13123e.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:138)
    ... 9 more
*** java.lang.instrument ASSERTION FAILED ***: "result" with message agent load/premain call failed at ./src/java.instrument/share/native/libinstrument/JPLISAgent.c line: 422
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:513)
    at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:525)
Caused by: java.lang.RuntimeException: Class java/lang/UnknownError could not be instrumented.
    at org.jacoco.agent.rt.internal_c13123e.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:140)
FATAL ERROR in native method: processing of -javaagent failed, processJavaStart failed
    at org.jacoco.agent.rt.internal_c13123e.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:101)
    at org.jacoco.agent.rt.internal_c13123e.PreMain.createRuntime(PreMain.java:55)
    at org.jacoco.agent.rt.internal_c13123e.PreMain.premain(PreMain.java:47)
    ... 6 more
Caused by: java.lang.NoSuchFieldException: $jacocoAccess
    at java.base/java.lang.Class.getField(Class.java:1999)
    at org.jacoco.agent.rt.internal_c13123e.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:138)```

```

Body:
I have been facing very weird issue where my unit test cases fail on arm graviton aws machines. The same unit test cases pass on intel machines with Java8

I am getting the below errors:

Exception in thread "main" java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:513)
    at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:525)
FATAL ERROR in native method: processing of -javaagent failed, processJavaStart failed
Caused by: java.lang.RuntimeException: Class java/lang/UnknownError could not be instrumented.
    at org.jacoco.agent.rt.internal_c13123e.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:140)
    at org.jacoco.agent.rt.internal_c13123e.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:101)
    at org.jacoco.agent.rt.internal_c13123e.PreMain.createRuntime(PreMain.java:55)
    at org.jacoco.agent.rt.internal_c13123e.PreMain.premain(PreMain.java:47)
    ... 6 more
Caused by: java.lang.NoSuchFieldException: $jacocoAccess
    at java.base/java.lang.Class.getField(Class.java:1999)
    at org.jacoco.agent.rt.internal_c13123e.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:138)
    ... 9 more
*** java.lang.instrument ASSERTION FAILED ***: "result" with message agent load/premain call failed at ./src/java.instrument/share/native/libinstrument/JPLISAgent.c line: 422
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:513)
    at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:525)
Caused by: java.lang.RuntimeException: Class java/lang/UnknownError could not be instrumented.
    at org.jacoco.agent.rt.internal_c13123e.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:140)
FATAL ERROR in native method: processing of -javaagent failed, processJavaStart failed
    at org.jacoco.agent.rt.internal_c13123e.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:101)
    at org.jacoco.agent.rt.internal_c13123e.PreMain.createRuntime(PreMain.java:55)
    at org.jacoco.agent.rt.internal_c13123e.PreMain.premain(PreMain.java:47)
    ... 6 more
Caused by: java.lang.NoSuchFieldException: $jacocoAccess
    at java.base/java.lang.Class.getField(Class.java:1999)
    at org.jacoco.agent.rt.internal_c13123e.core.runtime.ModifiedSystemClassRuntime.createFor(ModifiedSystemClassRuntime.java:138)```


问:
UNSAFE_NavigationContext not continuing navigation
I have a MUI dialog box to make sure users don't navigate away with unsaved changes. I would like to continue navigation when user clicks "Discard Changes" button.
The dialog box appears correctly when trying to navigate away, but nothing happens on clicking "Discard changes".

Dialog Box:

import * as React from 'react'
import PropTypes from 'prop-types';
import DialogButton from './DialogButton';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import { useNavigationBlocker } from '../layout/NavigationBlock';

const DiscardChangesDialog = ({ id, showWhen }) => {

  const [discarded, setDiscarded] = React.useState(false);
  const [show, setShow] = React.useState(false);

  useNavigationBlocker(discarded, () => setShow(true), showWhen);

  return (
    <Dialog
      id={id}
      open={show}
    >
      <DialogTitle>Discard changes?</DialogTitle>
      <DialogContent>
        <DialogContentText>You have unsaved changes!</DialogContentText>
      </DialogContent>
      <DialogActions>
        <DialogButton
          onClick={() => setDiscarded(true)}
          autoFocus
        >
          Discard changes
        </DialogButton>
        <DialogButton
          onClick={() => setShow(false)}
        >
          Cancel
        </DialogButton>
      </DialogActions>
    </Dialog>
  );
}

DiscardChangesDialog.propTypes = {
  id: PropTypes.string.isRequired,
  showWhen: PropTypes.bool.isRequired
};

export default DiscardChangesDialog;

```
<p><code>useNavigationBlocker</code> looks like this:</p>
<pre class="lang-js prettyprint-override"><code>import { useCallback, useContext, useEffect } from 'react';
import { UNSAFE_NavigationContext as NavigationContext } from 'react-router-dom';

export const useBlocker = (blocker, blockWhen = true) => {
    const { navigator } = useContext(NavigationContext);

    useEffect(() => {
        if (!blockWhen) return;

        const navigatorBlock = navigator.block((tx) => {

            const autoUnblockingTx = {
                ...tx,
                retry() {
                    navigatorBlock();
                    tx.retry();
                },
            };

            blocker(autoUnblockingTx);
        });

        return navigatorBlock;
    }, [navigator, blocker, blockWhen]);
}

export const useNavigationBlocker = (continuationTriggered, onBlock, blockWhen = true) => {
    const blocker = useCallback(
        (tx) => {
            onBlock();
            if (continuationTriggered)
                tx.retry();
        },
        [continuationTriggered, onBlock]
    );

    useBlocker(blocker, blockWhen);
}
</code>```

Body:
I have a MUI dialog box to make sure users don't navigate away with unsaved changes. I would like to continue navigation when user clicks "Discard Changes" button.
The dialog box appears correctly when trying to navigate away, but nothing happens on clicking "Discard changes".

Dialog Box:

import * as React from 'react'
import PropTypes from 'prop-types';
import DialogButton from './DialogButton';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import { useNavigationBlocker } from '../layout/NavigationBlock';

const DiscardChangesDialog = ({ id, showWhen }) => {

  const [discarded, setDiscarded] = React.useState(false);
  const [show, setShow] = React.useState(false);

  useNavigationBlocker(discarded, () => setShow(true), showWhen);

  return (
    <Dialog
      id={id}
      open={show}
    >
      <DialogTitle>Discard changes?</DialogTitle>
      <DialogContent>
        <DialogContentText>You have unsaved changes!</DialogContentText>
      </DialogContent>
      <DialogActions>
        <DialogButton
          onClick={() => setDiscarded(true)}
          autoFocus
        >
          Discard changes
        </DialogButton>
        <DialogButton
          onClick={() => setShow(false)}
        >
          Cancel
        </DialogButton>
      </DialogActions>
    </Dialog>
  );
}

DiscardChangesDialog.propTypes = {
  id: PropTypes.string.isRequired,
  showWhen: PropTypes.bool.isRequired
};

export default DiscardChangesDialog;

useNavigationBlocker looks like this:

import { useCallback, useContext, useEffect } from 'react';
import { UNSAFE_NavigationContext as NavigationContext } from 'react-router-dom';

export const useBlocker = (blocker, blockWhen = true) => {
    const { navigator } = useContext(NavigationContext);

    useEffect(() => {
        if (!blockWhen) return;

        const navigatorBlock = navigator.block((tx) => {

            const autoUnblockingTx = {
                ...tx,
                retry() {
                    navigatorBlock();
                    tx.retry();
                },
            };

            blocker(autoUnblockingTx);
        });

        return navigatorBlock;
    }, [navigator, blocker, blockWhen]);
}

export const useNavigationBlocker = (continuationTriggered, onBlock, blockWhen = true) => {
    const blocker = useCallback(
        (tx) => {
            onBlock();
            if (continuationTriggered)
                tx.retry();
        },
        [continuationTriggered, onBlock]
    );

    useBlocker(blocker, blockWhen);
}


问:
drag and drop between two list to form parentlist , and to items of parentlist need to add third list angular cdk
Hi iam able to use cdk to drag and drop in between two list and  for sake name it as parentlist and now in to the parentlist items i need to add another list items  using angular 2 cdk? please let me show with an example

drag and drop between two list creates a parentlist

now need to drag and drop third list to parentList individual items

example like to say

first list has Forms with out fields i need to drag that forms to second list whisch will then have array of forms

third list will have fields and i need to drag these fields to the individual forms in the array.
suppose to drop many fields in an individual form  of form array


问:
Why does `Drop::drop` take `&mut self` instead of `self`?
I am aware of a similar question that was once asked, but I am still rather perplexed after reading the accepted answer (to be clear, I do not see why the compiler does not have a special case for Drop::drop, as mentioned in the comments, since it already disallows moving out of an object that implements Drop). So let me please try to reiterate on this.

Suppose we have a struct Foo that owns some resources; say, a thread that has to be joined when the object goes out of scope (this situation can happen if we are writing an asynchronous runtime):

struct Foo {
    t: JoinHandle<()>,
}
```
<p>Since <code>std::ops::Drop::drop</code> takes <code>&mut self</code>, with this definition we cannot really hope to join this thread in <code>drop</code>, because <code>JoinHandle::join</code> takes <code>self</code> by value. Therefore, we have to resort to making this field optional:</p>
<pre class="lang-rust prettyprint-override"><code>struct Foo {
    t: Option<JoinHandle<()>>,
}
</code>```

And then we can go with if let Some(t) = self.t.take() { t.join(); }. But there still seem to be some unanswered questions here:

Is the drop signature hinting us that the drop method may get called several times on some objects, or that drop may not be the last method that is called on an object during its lifetime? If yes, in which scenarios can this happen? Is it correct to write self.t.unwrap() in the example above?

How to achieve similar semantics without introducing the overhead of Option (which may not in all cases get covered by niche optimisation and is anyway rather verbose)?

Body:
I am aware of a similar question that was once asked, but I am still rather perplexed after reading the accepted answer (to be clear, I do not see why the compiler does not have a special case for Drop::drop, as mentioned in the comments, since it already disallows moving out of an object that implements Drop). So let me please try to reiterate on this.

Suppose we have a struct Foo that owns some resources; say, a thread that has to be joined when the object goes out of scope (this situation can happen if we are writing an asynchronous runtime):

struct Foo {
    t: JoinHandle<()>,
}

Since std::ops::Drop::drop takes &mut self, with this definition we cannot really hope to join this thread in drop, because JoinHandle::join takes self by value. Therefore, we have to resort to making this field optional:

struct Foo {
    t: Option<JoinHandle<()>>,
}

And then we can go with if let Some(t) = self.t.take() { t.join(); }. But there still seem to be some unanswered questions here:

Is the drop signature hinting us that the drop method may get called several times on some objects, or that drop may not be the last method that is called on an object during its lifetime? If yes, in which scenarios can this happen? Is it correct to write self.t.unwrap() in the example above?

How to achieve similar semantics without introducing the overhead of Option (which may not in all cases get covered by niche optimisation and is anyway rather verbose)?


问:
Redis sentinel becomes stable after first failover
I have a redis sentinel structure with 3 redis instances and 3 redis-sentinel instances. When I make them up for the first time, slaves constantly changes their master to 127.0.0.1 and then back to real master and then to 127.0.0.1 and so on. When I force the master to be down for 20 sec, another instance becomes master and everything becomes stable. Here are my config. What can cause this and how can I solve this problem? Logs are constantly saying fix-slave-config when sentinels are unstable.

initial master config

```<code>daemonize yes
port 6380
bind 0.0.0.0
supervised systemd
pidfile "/run/redis/redis-sentinel.log"
logfile "/var/log/redis/sentinel.log"
sentinel monitor mymaster 127.0.0.1 6379 2
sentinel auth-pass mymaster ***
sentinel down-after-milliseconds mymaster 4000
sentinel failover-timeout mymaster 2000
sentinel parallel-syncs mymaster 1
sentinel announce-ip IP_OF_CURRENT_MACHINE
</code>```

initial slaves' config

```<code>daemonize yes
port 6380
bind 0.0.0.0
supervised systemd
pidfile "/run/redis/redis-sentinel.log"
logfile "/var/log/redis/sentinel.log"
sentinel monitor mymaster MASTER_IP 6379 2
sentinel auth-pass mymaster ***
sentinel down-after-milliseconds mymaster 4000
sentinel failover-timeout mymaster 2000
sentinel parallel-syncs mymaster 1
sentinel announce-ip IP_OF_CURRENT_MACHINE
</code>```

What I tried:

quorum= 1,2

down-after-milliseconds 4000,10000

failover-timeout 2000,6000

Body:
I have a redis sentinel structure with 3 redis instances and 3 redis-sentinel instances. When I make them up for the first time, slaves constantly changes their master to 127.0.0.1 and then back to real master and then to 127.0.0.1 and so on. When I force the master to be down for 20 sec, another instance becomes master and everything becomes stable. Here are my config. What can cause this and how can I solve this problem? Logs are constantly saying fix-slave-config when sentinels are unstable.

initial master config

daemonize yes
port 6380
bind 0.0.0.0
supervised systemd
pidfile "/run/redis/redis-sentinel.log"
logfile "/var/log/redis/sentinel.log"
sentinel monitor mymaster 127.0.0.1 6379 2
sentinel auth-pass mymaster ***
sentinel down-after-milliseconds mymaster 4000
sentinel failover-timeout mymaster 2000
sentinel parallel-syncs mymaster 1
sentinel announce-ip IP_OF_CURRENT_MACHINE

initial slaves' config

daemonize yes
port 6380
bind 0.0.0.0
supervised systemd
pidfile "/run/redis/redis-sentinel.log"
logfile "/var/log/redis/sentinel.log"
sentinel monitor mymaster MASTER_IP 6379 2
sentinel auth-pass mymaster ***
sentinel down-after-milliseconds mymaster 4000
sentinel failover-timeout mymaster 2000
sentinel parallel-syncs mymaster 1
sentinel announce-ip IP_OF_CURRENT_MACHINE

What I tried:

quorum= 1,2

down-after-milliseconds 4000,10000

failover-timeout 2000,6000


问:
Android QEMU emulator black screen
sometimes my Android QEMU emulator (run on Docker OS Debian), has black screen

my emulatror settings:

/home/user1/Android/Sdk/emulator/emulator \

-writable-system \

-avd emu1 \

-partition-size 1024 \

-cache-size 256 \

-memory 3500 \

-no-audio \

-selinux permissive \

-no-snapshot \

-gpu swiftshader_indirect \

Title: Android QEMU emulator black screen


问:
How can I measure shell latency when the time measuring commands also get stuck?

Some background and motivation

I'm working in a corporate that uses ClearCase for version control. In ClearCase, to work on a "branch" (stream) I have to enter a specific ClearCase shell for that stream.
The issue I've been having is that sometime these ClearCase shells are slow.

Goal

I wanted to write a small script that would allow me to measure and print these performance hiccups. Once it's working I will use it to run other commands or send the information to the appropriate team.

My attempt

I use "time" command to measure how long it would take to run "sleep 0.1" 200 times, which should take exactly 20 seconds, and based on how long it actually took, I do some things.

```<code>
while true;
do
  /usr/bin/time -f "%e" -o saved_timing bash -c "for ((i=1; i<=200; i++)) do sleep 0.1 ; echo hello > /dev/null ; done"
  elapsed_time=$(cat saved_timing)
  elapsed_time=${elapsed_time%.*}
  [ "$elapsed_time" -lt 23 ] && echo -n $elapsed_time || echo -ne "\033[1;31m$elapsed_time\033[0m"
  echo -n " "
  if [ "$elapsed_time" -gt 35 ]
  then
    notify-send "`echo $pwv`"
    exit 0
  fi
done

</code>```

Example output

20 20 20 20 20 20 20 20 20 20 20 20 20 21 20 20 20 20 20 20 20 20 21 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 23 24 25 25 25 25 24 30 25 42

The question

As you can see, it sometimes works, but in fact there are many instances where there's very obvious latency, but when there's finally a print on the screen, it just shows a normal "20".
I assume that this is because the "time" command itself got stuck, and not one of the "sleep" commands.

What can I do to solve this issue?

Note

When I'm outside of the ClearCase shell I do not have these gaps in performance, and maybe I can run two different scripts, one in each shell, and have them communicate somehow. They both have access to my homedir, for instance.
However, I'm not quite sure how to leverage this idea and it it's the best approach.

Cheers.

Body:
Some background and motivation

I'm working in a corporate that uses ClearCase for version control. In ClearCase, to work on a "branch" (stream) I have to enter a specific ClearCase shell for that stream.
The issue I've been having is that sometime these ClearCase shells are slow.

Goal

I wanted to write a small script that would allow me to measure and print these performance hiccups. Once it's working I will use it to run other commands or send the information to the appropriate team.

My attempt

I use "time" command to measure how long it would take to run "sleep 0.1" 200 times, which should take exactly 20 seconds, and based on how long it actually took, I do some things.

while true;
do
  /usr/bin/time -f "%e" -o saved_timing bash -c "for ((i=1; i<=200; i++)) do sleep 0.1 ; echo hello > /dev/null ; done"
  elapsed_time=$(cat saved_timing)
  elapsed_time=${elapsed_time%.*}
  [ "$elapsed_time" -lt 23 ] && echo -n $elapsed_time || echo -ne "\033[1;31m$elapsed_time\033[0m"
  echo -n " "
  if [ "$elapsed_time" -gt 35 ]
  then
    notify-send "`echo $pwv`"
    exit 0
  fi
done

Example output

20 20 20 20 20 20 20 20 20 20 20 20 20 21 20 20 20 20 20 20 20 20 21 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 23 24 25 25 25 25 24 30 25 42

The question

As you can see, it sometimes works, but in fact there are many instances where there's very obvious latency, but when there's finally a print on the screen, it just shows a normal "20".
I assume that this is because the "time" command itself got stuck, and not one of the "sleep" commands.

What can I do to solve this issue?

Note

When I'm outside of the ClearCase shell I do not have these gaps in performance, and maybe I can run two different scripts, one in each shell, and have them communicate somehow. They both have access to my homedir, for instance.
However, I'm not quite sure how to leverage this idea and it it's the best approach.

Cheers.


问:
Why are the results not different when there's code in global?
Code Snippet-1

```<code>setTimeout(() => console.log("setTimeout1"));
setTimeout(() => console.log("setTimeout2"));
setImmediate(() => console.log("setImmediate1"));
setImmediate(() => console.log("setImmediate2"));
</code>```

Code Snippet-2

```<code>setTimeout(() => console.log("setTimeout1"));
setTimeout(() => console.log("setTimeout2"));
setImmediate(() => console.log("setImmediate1"));
setImmediate(() => console.log("setImmediate2"));
console.log('hey');
</code>```

Snippet 1's outputs, when run multiple times:

```<code>> setTimeout1, setTimeout2, setImmediate1, setImmediate2
> setImmediate1, setImmediate2, setTimeout1, setTimeout2
> setTimeout1, setImmediate1, setImmediate2, setTimeout2
</code>```

Snippet 2 always returns in the following order:

```<code>> hey, setTimeout1, setTimeout2, setImmediate1, setImmediate2
</code>```

I read about setImmediate() and setTimeout() and understood that the results might vary, but how does adding a console.log() in Snippet-2 return the same output every time?

Node: v16.18.0

Body:
Code Snippet-1

setTimeout(() => console.log("setTimeout1"));
setTimeout(() => console.log("setTimeout2"));
setImmediate(() => console.log("setImmediate1"));
setImmediate(() => console.log("setImmediate2"));

Code Snippet-2

setTimeout(() => console.log("setTimeout1"));
setTimeout(() => console.log("setTimeout2"));
setImmediate(() => console.log("setImmediate1"));
setImmediate(() => console.log("setImmediate2"));
console.log('hey');

Snippet 1's outputs, when run multiple times:

> setTimeout1, setTimeout2, setImmediate1, setImmediate2
> setImmediate1, setImmediate2, setTimeout1, setTimeout2
> setTimeout1, setImmediate1, setImmediate2, setTimeout2

Snippet 2 always returns in the following order:

> hey, setTimeout1, setTimeout2, setImmediate1, setImmediate2

I read about setImmediate() and setTimeout() and understood that the results might vary, but how does adding a console.log() in Snippet-2 return the same output every time?

Node: v16.18.0


问:
How to sandbox an untrusted code in Dart?
I'm looking for a way to build a secure third-party extension system for a Flutter app.

I know that it's possible to load Dart code at runtime using Isolate.spawnUri(), it will have an isolated memory, but it will still be able to access insecure, native apis, such as dart:io. Is there any way to completely sandbox a third party code, so it can be run securely?

import 'dart:isolate';

void main() async {
  // Load the code to be run in the isolate from a URL
  var uri = Uri.file('path/to/extension.dart');

  // Spawn the isolate and wait for it to complete
  var receivePort = ReceivePort();
  await Isolate.spawnUri(uri, [], receivePort.sendPort); // can you make it secure?
}
```


问:
How to define sources for the HTMLImageElement
Using Image() constructor, I can specify srcset and sizes properties and then await for decode() promise. A browser will select the appropriate image on its own and load it. But this only suitable for .jpg files. I can't be sure that browser is supporting such formats as avif and webp.

So, how can I wait for decoding an image that is represented as <picture> tag, but when it isn't inserted in DOM yet?

<picture>
  <source type="image/avif" srcset="large.avif 1024w, medium.avif 640w, small.avif 320w"/>
  <source type="image/webp" srcset="large.webp 1024w, medium.webp 640w, small.webp 320w"/>

</picture>
```

After the browser has decoded an image, I will hide a loading status and show loaded image immediately. But if I try to guess the behavior of the browser, there is a small chance that the wrong image is selected and the user will see a blank space while correct image is loading.

Body:
Using Image() constructor, I can specify srcset and sizes properties and then await for decode() promise. A browser will select the appropriate image on its own and load it. But this only suitable for .jpg files. I can't be sure that browser is supporting such formats as avif and webp.

So, how can I wait for decoding an image that is represented as <picture> tag, but when it isn't inserted in DOM yet?

<picture>
  <source type="image/avif" srcset="large.avif 1024w, medium.avif 640w, small.avif 320w"/>
  <source type="image/webp" srcset="large.webp 1024w, medium.webp 640w, small.webp 320w"/>

</picture>

After the browser has decoded an image, I will hide a loading status and show loaded image immediately. But if I try to guess the behavior of the browser, there is a small chance that the wrong image is selected and the user will see a blank space while correct image is loading.


问:
State is null when trying to access it in the parent component, but able to pass it down to child component
EDIT: Simplified the code a bit by using two separate states. Adding the channel state to the dependency array of useEffect() does not remove the error but does make the application run in a strange manner: If I try to send messages, I see multiple messages.

EDIT 2: If I use the useRef() hook to store the state, my application works albeit in a strange manner again: the state is one step slower than the actual user input.

I'm trying to build a simple chat application using React.js and Socket.IO where a single user can communicate with multiple users. I have an endpoint from where I fetch all my channel data and store it in a state but I'm not able to access the state (returns null) even if the state is being passed down to a different component as props and that is being rendered correctly the first time. When I click on a channel to select it, the channel list is again reset to null and I get this error:

Uncaught (in promise) TypeError: Cannot read properties of null (reading 'forEach')

I'm trying to implement this by following the tutorial from here. It's outdated, so I'm implementing a newer version of it. But even then, if I use the component class defined in the author's github, it seems to work just fine. I have not worked with component classes before, so I am not sure where I am going wrong.

Main component: Chat.js

```<code>import React, { useEffect, useState } from 'react';
import ChannelList from './ChannelList';
import './chat.css';
import MessagePanel from './MessagePanel';
import { io }  from "socket.io-client";

const SERVER = "http://localhost:8080";

let socket;

function Chat() {

  const [channel, setChannel] = useState(null)
  const [channels, setChannels] = useState(null) //the state where the channels are loaded
  const channelsRef = useRef() //edit 2

  useEffect(() => {
    loadChannels() //the function which loads the channels into the state
    configureSocket()
  }, []) //adding channel to the dependency array results in strange behavior.

  const configureSocket = () => {
    socket = io(SERVER)
    socket.on('connection', () => {
      if(channel) {
        handleChannelSelect(channel.id)
      }
    });

    socket.on('channel', channel => {
      console.log('channel details', channel); //returns the correct channel clicked on
      //let temp_channels = channels; //edit 2
      let temp_channels = channelsRef.current; //edit 2
      console.log('channels inside onchannel', temp_channels); //returns null, does not return null if useRef() is used
      temp_channels.forEach(c => { //I get the above mentioned error at this line, after edit 2 I don't get any error
        if(c.id === channel.id) {
          c.participants = channel.participants
        }
      })
      //setChannels(channels); edit 2
      channelsRef.current = temp_channels // edit 2
    })

    socket.on('message', message => {
      // let temp_channels = channels
      let temp_channels = channelsRef.current //edit 2
      temp_channels.forEach(c => {
        if (c.id === message.channel_id) {
          if (!c.messages) {
            c.messages = [message];
          } else {
            c.messages.push(message);
          }
        }
      })
      // setChannels(channels) edit 2
      channelsRef.current = temp_channels // edit 2
    })
  }

  const handleSendMessage = (channel_id, text) => {
    socket.emit('send-message', { channel_id, text, senderName: socket.id, id: Date.now()})
  }

  const handleChannelSelect = (id) => {
    const channel = channels.find(c => {
      return c.id === id;
    });
    setChannel(channel);
    socket.emit('channel-join', id, ack => {});
  }

  const loadChannels = async () => {
    await fetch('http://localhost:8080/getChannels')
      .then(async response => {
        const data = await response.json()
        console.log('data inside loadchannels', data.channels);
        setChannels(data.channels); //this sets the channels and passes it down to the child component "ChannelList"
        channelsRef.current = data.channels //if setChannels is not used before this, it doesn't work
      })
      console.log('after fetching channels inside loadchannels', channel, channels); //both channel and channels state are null
  }

  return (
    <div className="chat-app">
      <ChannelList channels={channels} onSelectChannel={handleChannelSelect}></ChannelList>
      <MessagePanel onSendMessage={handleSendMessage} channel={channel}/>
    </div>
  );
}

export default Chat;
</code>```

ChannelList.js

```<code>import React from 'react';
import Channel from './Channel';

function ChannelList(props) {
  const handleClick = (id) => {
    props.onSelectChannel(id);
  }

  console.log('inside channellist component', props.channels); //returns the set of channels received from props

  let list = <div className="no-content-message">There are no channels to show</div>;
  if (props.channels && props.channels.map) {
    list = props.channels.map(c =>
      <Channel
        key={c.id}
        id={c.id}
        name={c.name}
        participants={c.participants}
        onClick={handleClick}
      />
    );
  }

  return (
    <div className='channel-list'>
      {list}
    </div>
  );

}

export default ChannelList;
</code>```

Backend index.js:

```<code>const express = require('express');
const app = express();
http = require('http');
const cors = require('cors');
const { Server } = require('socket.io');

app.use(cors());

const server = http.createServer(app);

const STATIC_CHANNELS = [
  {
    name: 'Global chat',
    participants: 0,
    id: 1,
    sockets: []
  },
  {
    name: 'Funny',
    participants: 0,
    id: 2,
    sockets: []
  },
  {
    name: 'Test',
    participants: 0,
    id: 3,
    sockets: []
  },
];

const io = new Server(server, {
  cors: {
    origin: 'http://localhost:3000',
    methods: ['GET', 'POST'],
  },
});

server.listen(8080, () =>
  console.log('Server is running on port 8080')
);

io.on('connection', (socket) => {
  console.log(`User connected ${socket.id}`);

  socket.emit('connected', socket.id);

  socket.on('channel-join', id => {
    console.log('channel join', id);
    STATIC_CHANNELS.forEach(c => {
      if (c.id === id) {
        if (c.sockets.indexOf(socket.id) == (-1)) {
          c.sockets.push(socket.id);
          c.participants++;
          io.emit('channel', c);
        }
      } else {
        let index = c.sockets.indexOf(socket.id);
        if (index != (-1)) {
          c.sockets.splice(index, 1);
          c.participants--;
          io.emit('channel', c);
        }
      }
    });
    return id;
  })

  socket.on('send-message', message => {
    io.emit('message', message);
  })

  socket.on('disconnect', () => {
    STATIC_CHANNELS.forEach(c => {
      let index = c.sockets.indexOf(socket.id);
      if(index != (-1)) {
        c.sockets.splice(index, 1);
        c.participants--;
        io.emit('channel', c);
      }
    })
  })
});

app.get('/getChannels', (req, res) => {
  res.json({
    channels: STATIC_CHANNELS
  })
})
</code>```

Body:
EDIT: Simplified the code a bit by using two separate states. Adding the channel state to the dependency array of useEffect() does not remove the error but does make the application run in a strange manner: If I try to send messages, I see multiple messages.

EDIT 2: If I use the useRef() hook to store the state, my application works albeit in a strange manner again: the state is one step slower than the actual user input.

I'm trying to build a simple chat application using React.js and Socket.IO where a single user can communicate with multiple users. I have an endpoint from where I fetch all my channel data and store it in a state but I'm not able to access the state (returns null) even if the state is being passed down to a different component as props and that is being rendered correctly the first time. When I click on a channel to select it, the channel list is again reset to null and I get this error:

Uncaught (in promise) TypeError: Cannot read properties of null (reading 'forEach')

I'm trying to implement this by following the tutorial from here. It's outdated, so I'm implementing a newer version of it. But even then, if I use the component class defined in the author's github, it seems to work just fine. I have not worked with component classes before, so I am not sure where I am going wrong.

Main component: Chat.js

import React, { useEffect, useState } from 'react';
import ChannelList from './ChannelList';
import './chat.css';
import MessagePanel from './MessagePanel';
import { io }  from "socket.io-client";

const SERVER = "http://localhost:8080";

let socket;

function Chat() {

  const [channel, setChannel] = useState(null)
  const [channels, setChannels] = useState(null) //the state where the channels are loaded
  const channelsRef = useRef() //edit 2

  useEffect(() => {
    loadChannels() //the function which loads the channels into the state
    configureSocket()
  }, []) //adding channel to the dependency array results in strange behavior.

  const configureSocket = () => {
    socket = io(SERVER)
    socket.on('connection', () => {
      if(channel) {
        handleChannelSelect(channel.id)
      }
    });

    socket.on('channel', channel => {
      console.log('channel details', channel); //returns the correct channel clicked on
      //let temp_channels = channels; //edit 2
      let temp_channels = channelsRef.current; //edit 2
      console.log('channels inside onchannel', temp_channels); //returns null, does not return null if useRef() is used
      temp_channels.forEach(c => { //I get the above mentioned error at this line, after edit 2 I don't get any error
        if(c.id === channel.id) {
          c.participants = channel.participants
        }
      })
      //setChannels(channels); edit 2
      channelsRef.current = temp_channels // edit 2
    })

    socket.on('message', message => {
      // let temp_channels = channels
      let temp_channels = channelsRef.current //edit 2
      temp_channels.forEach(c => {
        if (c.id === message.channel_id) {
          if (!c.messages) {
            c.messages = [message];
          } else {
            c.messages.push(message);
          }
        }
      })
      // setChannels(channels) edit 2
      channelsRef.current = temp_channels // edit 2
    })
  }

  const handleSendMessage = (channel_id, text) => {
    socket.emit('send-message', { channel_id, text, senderName: socket.id, id: Date.now()})
  }

  const handleChannelSelect = (id) => {
    const channel = channels.find(c => {
      return c.id === id;
    });
    setChannel(channel);
    socket.emit('channel-join', id, ack => {});
  }

  const loadChannels = async () => {
    await fetch('http://localhost:8080/getChannels')
      .then(async response => {
        const data = await response.json()
        console.log('data inside loadchannels', data.channels);
        setChannels(data.channels); //this sets the channels and passes it down to the child component "ChannelList"
        channelsRef.current = data.channels //if setChannels is not used before this, it doesn't work
      })
      console.log('after fetching channels inside loadchannels', channel, channels); //both channel and channels state are null
  }

  return (

      <ChannelList channels={channels} onSelectChannel={handleChannelSelect}></ChannelList>
      <MessagePanel onSendMessage={handleSendMessage} channel={channel}/>

  );
}

export default Chat;

ChannelList.js

import React from 'react';
import Channel from './Channel';

function ChannelList(props) {
  const handleClick = (id) => {
    props.onSelectChannel(id);
  }

  console.log('inside channellist component', props.channels); //returns the set of channels received from props

  let list =
There are no channels to show
;
  if (props.channels && props.channels.map) {
    list = props.channels.map(c =>
      <Channel
        key={c.id}
        id={c.id}
        name={c.name}
        participants={c.participants}
        onClick={handleClick}
      />
    );
  }

  return (

      {list}

  );

}

export default ChannelList;

Backend index.js:

const express = require('express');
const app = express();
http = require('http');
const cors = require('cors');
const { Server } = require('socket.io');

app.use(cors());

const server = http.createServer(app);

const STATIC_CHANNELS = [
  {
    name: 'Global chat',
    participants: 0,
    id: 1,
    sockets: []
  },
  {
    name: 'Funny',
    participants: 0,
    id: 2,
    sockets: []
  },
  {
    name: 'Test',
    participants: 0,
    id: 3,
    sockets: []
  },
];

const io = new Server(server, {
  cors: {
    origin: 'http://localhost:3000',
    methods: ['GET', 'POST'],
  },
});

server.listen(8080, () =>
  console.log('Server is running on port 8080')
);

io.on('connection', (socket) => {
  console.log(`User connected ${socket.id}`);

  socket.emit('connected', socket.id);

  socket.on('channel-join', id => {
    console.log('channel join', id);
    STATIC_CHANNELS.forEach(c => {
      if (c.id === id) {
        if (c.sockets.indexOf(socket.id) == (-1)) {
          c.sockets.push(socket.id);
          c.participants++;
          io.emit('channel', c);
        }
      } else {
        let index = c.sockets.indexOf(socket.id);
        if (index != (-1)) {
          c.sockets.splice(index, 1);
          c.participants--;
          io.emit('channel', c);
        }
      }
    });
    return id;
  })

  socket.on('send-message', message => {
    io.emit('message', message);
  })

  socket.on('disconnect', () => {
    STATIC_CHANNELS.forEach(c => {
      let index = c.sockets.indexOf(socket.id);
      if(index != (-1)) {
        c.sockets.splice(index, 1);
        c.participants--;
        io.emit('channel', c);
      }
    })
  })
});

app.get('/getChannels', (req, res) => {
  res.json({
    channels: STATIC_CHANNELS
  })
})


问:
Plugin android application is false
For some unknown reason, when I pulled my project from GitHub, the Android Studio told me this:

```<code>"Plugin[id:com.android.application',version'7.3.2',apply:false]was not found in any of the following sources:
</code>```

And in the build file build.gradle it's only this:

I repeat I just only pull my project from GitHub:

Also, I have this exception:

```<code>org.gradle.api.plugins.UnknownPluginException: Plugin [id: 'com.android.application', version: '7.3.2', apply: false] was not found in any of the following sources:

- Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
- Plugin Repositories (could not resolve plugin artifact 'com.android.application:com.android.application.gradle.plugin:7.3.2')
  Searched in the following repositories:
    Gradle Central Plugin Repository
    Google
    MavenRepo
</code>```

I tried to update both android studio versions, but the problem was still there. I tried copying the manifest cause it was incomplete for some reason, and it only created more errors.

Title: Plugin android application is false

Body:
For some unknown reason, when I pulled my project from GitHub, the Android Studio told me this:

"Plugin[id:com.android.application',version'7.3.2',apply:false]was not found in any of the following sources:

And in the build file build.gradle it's only this:

I repeat I just only pull my project from GitHub:

Also, I have this exception:

org.gradle.api.plugins.UnknownPluginException: Plugin [id: 'com.android.application', version: '7.3.2', apply: false] was not found in any of the following sources:

- Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
- Plugin Repositories (could not resolve plugin artifact 'com.android.application:com.android.application.gradle.plugin:7.3.2')
  Searched in the following repositories:
    Gradle Central Plugin Repository
    Google
    MavenRepo

I tried to update both android studio versions, but the problem was still there. I tried copying the manifest cause it was incomplete for some reason, and it only created more errors.


问:
"data is not iterable" when reverse or sort the data using RTK Query
I am trying to use reverse & sort on the data coming from the RTK query. Whenever, i revers, it's showing me the error.

'data is not iterable'

Here's my code.

const {data, error, isLoading} = useGetTransactionsQuery()
const [modalState, setModalState] = useState<boolean>(false)

console.log(data.reverse())
```
<p>Here is my whole code:- <strong>GitHub</strong>.</p>
<p>And also, I tried this. And it didn't work at all.</p>
<pre class="lang-js prettyprint-override"><code>data.reverse()
[...data].reverse()
Array.from(data).reverse();
</code>```

In the case of Array.from(data).reverse();. This error showing.

TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)) at Function.from ()

Body:
I am trying to use reverse & sort on the data coming from the RTK query. Whenever, i revers, it's showing me the error.

'data is not iterable'

Here's my code.

const {data, error, isLoading} = useGetTransactionsQuery()
const [modalState, setModalState] = useState<boolean>(false)

console.log(data.reverse())

Here is my whole code:- GitHub.

And also, I tried this. And it didn't work at all.

data.reverse()
[...data].reverse()
Array.from(data).reverse();

In the case of Array.from(data).reverse();. This error showing.

TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)) at Function.from ()


问:
How to hide any section div inside iframe
I am trying to hide a section using a tag (#masthead) inside the iframe on https://e-hasan.com/blog/

I tried many codes, but they do not work on PHP-based websites only work on a static HTML website.

I tried this code but not working. It's only working on one static HTML page. I would like to hide the header of the website.

```<code><html lang="en">
<head>
  <title>Hide element inside iframe using javascript</title>
</head>
<body>
  <p>Click on the <b>Hide Div</b> button to hide the div element inside the iframe.</p>
  <button onclick="hideDiv()">Hide Div</button>

  <iframe id="iframe-id" src="https://e-hasan.com/blog/" style="height:100%;width:100%">      </iframe>

<script>
function hideDiv() {
  var myIframe = document.getElementById("iframe-id");
  var divElement = myIframe.contentWindow.document.querySelector("#masthead");
  divElement.style.display = "none";
}
</script>
</body>
</html>
</code>```

Body:
I am trying to hide a section using a tag (#masthead) inside the iframe on https://e-hasan.com/blog/

I tried many codes, but they do not work on PHP-based websites only work on a static HTML website.

I tried this code but not working. It's only working on one static HTML page. I would like to hide the header of the website.

  <title>Hide element inside iframe using javascript</title>

Click on the Hide Div button to hide the div element inside the iframe.

  <button onclick="hideDiv()">Hide Div</button>


问:
[Bug]Migrate DLToolkit.FlowListView to Maui
I try to migrate the DLToolkit.Forms.Controls.FlowListView Library to .net 7 Maui(TestProject, to keep using it in our app. Everything works fine but an AbsoluteLayout in Datatemplate dont show list content. I had this xaml:

```<code>    <?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="FlowlistTest.Maui.MainPage"
         xmlns:local="clr-namespace:FlowlistTest.Maui"
          xmlns:flv="clrnamespace:DLToolkit.Maui.Controls.FlowListView;assembly=DLToolkit.Maui.Control s.FlowListView"
         >
    <StackLayout  Padding="10">
    <flv:FlowListView FlowColumnCount="3"
            SeparatorVisibility="Default"
            HasUnevenRows="True"
            Background="Black"
            FlowUseAbsoluteLayoutInternally="True"
            FlowItemTappedCommand="{Binding ItemTappedCommand}"
            FlowItemsSource="{Binding Items}">

        <flv:FlowListView.FlowColumnTemplate>
            <DataTemplate>

                <Frame BackgroundColor="Purple"
                       Margin="5">
                      <Label HorizontalOptions="Fill"
                             VerticalOptions="Fill"
                             TextColor="White"
                             HorizontalTextAlignment="Center"
                             VerticalTextAlignment="Center"
                             Text="{Binding }"/>
                </Frame>

                </DataTemplate>
            </flv:FlowListView.FlowColumnTemplate>
        </flv:FlowListView>

    </StackLayout>

 </ContentPage>
</code>```

And this c# code:

```<code>       void AddViewToLayoutAutoHeightDisabled(View view, int containerCount, int
colNumber)
    {
        double desiredColumnWidth = 1d / _desiredColumnCount;
        Rect bounds = Rect.Zero;

        if (_flowColumnExpand != FlowColumnExpand.None && _desiredColumnCount >
containerCount)
        {
            int diff = _desiredColumnCount - containerCount;
            bool isLastColumn = colNumber == containerCount - 1;

            switch (_flowColumnExpand)
            {
                case FlowColumnExpand.First:

                    if (colNumber == 0)
                    {
                        bounds = new Rect(0d, 0d, desiredColumnWidth +
 (desiredColumnWidth * diff), 1d);
                    }
                    else if (isLastColumn)
                    {
                        bounds = new Rect(1d, 0d, desiredColumnWidth, 1d);
                    }
                    else
                    {
                        bounds = new Rect(desiredColumnWidth * (colNumber + diff) / (1d
- desiredColumnWidth), 0d, desiredColumnWidth, 1d);
                    }

                    break;

                case FlowColumnExpand.Last:

                    if (colNumber == 0)
                    {
                        bounds = new Rect(0d, 0d,
    desiredColumnWidth +
      (desiredColumnWidth * diff), 1d);
                    }
                    else if (isLastColumn)
                    {
                        bounds = new Rect(1d, 0d,
    desiredColumnWidth + (desiredColumnWidth * diff), 1d);
                    }
                    else
                    {
                        bounds = new Rect(desiredColumnWidth * colNumber / (1d - desiredColumnWidth), 0d, desiredColumnWidth, 1d);
                    }

                    break;

                case FlowColumnExpand.Proportional:

                    double propColumnsWidth = 1d / containerCount;
                    if (colNumber == 0)
                    {
                        bounds = new Rect(0d, 0d, propColumnsWidth, 1d);
                    }
                    else if (isLastColumn)
                    {
                        bounds = new Rect(1d, 0d, propColumnsWidth, 1d);
                    }
                    else
                    {
                        bounds = new Rect(propColumnsWidth * colNumber / (1d - propColumnsWidth), 0d, propColumnsWidth, 1d);
                    }

                    break;

                case FlowColumnExpand.ProportionalFirst:

                    int propFMod = _desiredColumnCount % containerCount;
                    double propFSize = desiredColumnWidth * Math.Floor((double)_desiredColumnCount / containerCount);
                    double propFSizeFirst = propFSize + desiredColumnWidth * propFMod;

                    if (colNumber == 0)
                    {
                        bounds = new Rect(0d, 0d, propFSizeFirst, 1d);
                    }
                    else if (isLastColumn)
                    {
                        bounds = new Rect(1d, 0d, propFSize, 1d);
                    }
                    else
                    {
                        bounds = new Rect(((propFSize * colNumber) + (propFSizeFirst - propFSize)) / (1d - propFSize), 0d, propFSize, 1d);
                    }

                    break;

                case FlowColumnExpand.ProportionalLast:

                    int propLMod = _desiredColumnCount % containerCount;
                    double propLSize = desiredColumnWidth * Math.Floor((double)_desiredColumnCount / containerCount);
                    double propLSizeLast = propLSize + desiredColumnWidth * propLMod;

                    if (colNumber == 0)
                    {
                        bounds = new Rect(0d, 0d, propLSize, 1d);
                    }
                    else if (isLastColumn)
                    {
                        bounds = new Rect(1d, 0d, propLSizeLast, 1d);
                    }
                    else
                    {
                        bounds = new Rect((propLSize * colNumber) / (1d - propLSize), 0d, propLSize, 1d);
                    }

                    break;
            }
        }
        else
        {
            if (Math.Abs(1d - desiredColumnWidth) < Epsilon.DoubleValue)
            {
                bounds = new Rect(1d, 0d, desiredColumnWidth, 1d);
            }
            else
            {
                bounds = new Rect(desiredColumnWidth * colNumber / (1d - desiredColumnWidth), 0d, desiredColumnWidth, 1d);
            }
        }

        _rootLayout.SetLayoutBounds(view, bounds);
        _rootLayout.SetLayoutFlags(view, AbsoluteLayoutFlags.All);
        _rootLayout.Children.Add(view);

    }
</code>```

In the old forms library the part:

```<code>     _rootLayout.SetLayoutBounds(view, bounds);
        _rootLayout.SetLayoutFlags(view, AbsoluteLayoutFlags.All);
        _rootLayout.Children.Add(view);
</code>```

was:

```<code>    _rootLayout.Children.Add(view, bounds, AbsoluteLayoutFlags.All);
</code>```

but at Maui the Add Function has no overloads for do it this way, so i use the SetLayoutBounds and Set LayoutFlags functions. The problem is whit this way the List content don#t get shown and i see only an black background, what i do miss here ?

Here is the constructor from FlowListViewInternalCell, this class inherits from ViewCell:

```<code>     public FlowListViewInternalCell(WeakReference<FlowListView> flowListViewRef)
    {
        _flowListViewRef = flowListViewRef;
        flowListViewRef.TryGetTarget(out FlowListView flowListView);
        _useGridAsMainRoot = !flowListView.FlowUseAbsoluteLayoutInternally;

        if (!_useGridAsMainRoot)
        {

            _rootLayout = new AbsoluteLayout()
            {
                Padding = 0d,
                BackgroundColor = flowListView.FlowRowBackgroundColor,

            };

            View = _rootLayout;

        }
        else
        {
            _rootLayoutAuto = new Grid()
            {
                RowSpacing = 0d,
                ColumnSpacing = 0d,
                Padding = 0d,
                BackgroundColor = flowListView.FlowRowBackgroundColor,
            };
            View = _rootLayoutAuto;
        }

        _flowColumnTemplate = flowListView.FlowColumnTemplate;
        _desiredColumnCount = flowListView.FlowDesiredColumnCount;
        _flowColumnExpand = flowListView.FlowColumnExpand;

        View.GestureRecognizers.Clear();
        View.GestureRecognizers.Add(new TapGestureRecognizer());
    }

</code>```

Body:
I try to migrate the DLToolkit.Forms.Controls.FlowListView Library to .net 7 Maui(TestProject, to keep using it in our app. Everything works fine but an AbsoluteLayout in Datatemplate dont show list content. I had this xaml:

    <?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="FlowlistTest.Maui.MainPage"
         xmlns:local="clr-namespace:FlowlistTest.Maui"
          xmlns:flv="clrnamespace:DLToolkit.Maui.Controls.FlowListView;assembly=DLToolkit.Maui.Control s.FlowListView"
         >
    <StackLayout  Padding="10">
    <flv:FlowListView FlowColumnCount="3"
            SeparatorVisibility="Default"
            HasUnevenRows="True"
            Background="Black"
            FlowUseAbsoluteLayoutInternally="True"
            FlowItemTappedCommand="{Binding ItemTappedCommand}"
            FlowItemsSource="{Binding Items}">

        <flv:FlowListView.FlowColumnTemplate>
            <DataTemplate>

                <Frame BackgroundColor="Purple"
                       Margin="5">

                </Frame>

                </DataTemplate>
            </flv:FlowListView.FlowColumnTemplate>
        </flv:FlowListView>

    </StackLayout>

 </ContentPage>

And this c# code:

       void AddViewToLayoutAutoHeightDisabled(View view, int containerCount, int
colNumber)
    {
        double desiredColumnWidth = 1d / _desiredColumnCount;
        Rect bounds = Rect.Zero;

        if (_flowColumnExpand != FlowColumnExpand.None && _desiredColumnCount >
containerCount)
        {
            int diff = _desiredColumnCount - containerCount;
            bool isLastColumn = colNumber == containerCount - 1;

            switch (_flowColumnExpand)
            {
                case FlowColumnExpand.First:

                    if (colNumber == 0)
                    {
                        bounds = new Rect(0d, 0d, desiredColumnWidth +
 (desiredColumnWidth * diff), 1d);
                    }
                    else if (isLastColumn)
                    {
                        bounds = new Rect(1d, 0d, desiredColumnWidth, 1d);
                    }
                    else
                    {
                        bounds = new Rect(desiredColumnWidth * (colNumber + diff) / (1d
- desiredColumnWidth), 0d, desiredColumnWidth, 1d);
                    }

                    break;

                case FlowColumnExpand.Last:

                    if (colNumber == 0)
                    {
                        bounds = new Rect(0d, 0d,
    desiredColumnWidth +
      (desiredColumnWidth * diff), 1d);
                    }
                    else if (isLastColumn)
                    {
                        bounds = new Rect(1d, 0d,
    desiredColumnWidth + (desiredColumnWidth * diff), 1d);
                    }
                    else
                    {
                        bounds = new Rect(desiredColumnWidth * colNumber / (1d - desiredColumnWidth), 0d, desiredColumnWidth, 1d);
                    }

                    break;

                case FlowColumnExpand.Proportional:

                    double propColumnsWidth = 1d / containerCount;
                    if (colNumber == 0)
                    {
                        bounds = new Rect(0d, 0d, propColumnsWidth, 1d);
                    }
                    else if (isLastColumn)
                    {
                        bounds = new Rect(1d, 0d, propColumnsWidth, 1d);
                    }
                    else
                    {
                        bounds = new Rect(propColumnsWidth * colNumber / (1d - propColumnsWidth), 0d, propColumnsWidth, 1d);
                    }

                    break;

                case FlowColumnExpand.ProportionalFirst:

                    int propFMod = _desiredColumnCount % containerCount;
                    double propFSize = desiredColumnWidth * Math.Floor((double)_desiredColumnCount / containerCount);
                    double propFSizeFirst = propFSize + desiredColumnWidth * propFMod;

                    if (colNumber == 0)
                    {
                        bounds = new Rect(0d, 0d, propFSizeFirst, 1d);
                    }
                    else if (isLastColumn)
                    {
                        bounds = new Rect(1d, 0d, propFSize, 1d);
                    }
                    else
                    {
                        bounds = new Rect(((propFSize * colNumber) + (propFSizeFirst - propFSize)) / (1d - propFSize), 0d, propFSize, 1d);
                    }

                    break;

                case FlowColumnExpand.ProportionalLast:

                    int propLMod = _desiredColumnCount % containerCount;
                    double propLSize = desiredColumnWidth * Math.Floor((double)_desiredColumnCount / containerCount);
                    double propLSizeLast = propLSize + desiredColumnWidth * propLMod;

                    if (colNumber == 0)
                    {
                        bounds = new Rect(0d, 0d, propLSize, 1d);
                    }
                    else if (isLastColumn)
                    {
                        bounds = new Rect(1d, 0d, propLSizeLast, 1d);
                    }
                    else
                    {
                        bounds = new Rect((propLSize * colNumber) / (1d - propLSize), 0d, propLSize, 1d);
                    }

                    break;
            }
        }
        else
        {
            if (Math.Abs(1d - desiredColumnWidth) < Epsilon.DoubleValue)
            {
                bounds = new Rect(1d, 0d, desiredColumnWidth, 1d);
            }
            else
            {
                bounds = new Rect(desiredColumnWidth * colNumber / (1d - desiredColumnWidth), 0d, desiredColumnWidth, 1d);
            }
        }

        _rootLayout.SetLayoutBounds(view, bounds);
        _rootLayout.SetLayoutFlags(view, AbsoluteLayoutFlags.All);
        _rootLayout.Children.Add(view);

    }

In the old forms library the part:

     _rootLayout.SetLayoutBounds(view, bounds);
        _rootLayout.SetLayoutFlags(view, AbsoluteLayoutFlags.All);
        _rootLayout.Children.Add(view);

was:

    _rootLayout.Children.Add(view, bounds, AbsoluteLayoutFlags.All);

but at Maui the Add Function has no overloads for do it this way, so i use the SetLayoutBounds and Set LayoutFlags functions. The problem is whit this way the List content don#t get shown and i see only an black background, what i do miss here ?

Here is the constructor from FlowListViewInternalCell, this class inherits from ViewCell:

     public FlowListViewInternalCell(WeakReference<FlowListView> flowListViewRef)
    {
        _flowListViewRef = flowListViewRef;
        flowListViewRef.TryGetTarget(out FlowListView flowListView);
        _useGridAsMainRoot = !flowListView.FlowUseAbsoluteLayoutInternally;

        if (!_useGridAsMainRoot)
        {

            _rootLayout = new AbsoluteLayout()
            {
                Padding = 0d,
                BackgroundColor = flowListView.FlowRowBackgroundColor,

            };

            View = _rootLayout;

        }
        else
        {
            _rootLayoutAuto = new Grid()
            {
                RowSpacing = 0d,
                ColumnSpacing = 0d,
                Padding = 0d,
                BackgroundColor = flowListView.FlowRowBackgroundColor,
            };
            View = _rootLayoutAuto;
        }

        _flowColumnTemplate = flowListView.FlowColumnTemplate;
        _desiredColumnCount = flowListView.FlowDesiredColumnCount;
        _flowColumnExpand = flowListView.FlowColumnExpand;

        View.GestureRecognizers.Clear();
        View.GestureRecognizers.Add(new TapGestureRecognizer());
    }


问:
How to remove white space on array elements
I have a column called 'rest_type' which is data type text[]. inside it are ["Fine Dining", " Cafe", " Bar"] etc. how can i remove the whitespaces in these elements?

```<code>   rest_type
-------------------------------
 {"Quick Bites"}
 {Cafe}
 {Cafe}
 {"Quick Bites"}
 {"Sweet Shop"," Quick Bites"}
</code>```

(5 rows)

Body:
I have a column called 'rest_type' which is data type text[]. inside it are ["Fine Dining", " Cafe", " Bar"] etc. how can i remove the whitespaces in these elements?

   rest_type
-------------------------------
 {"Quick Bites"}
 {Cafe}
 {Cafe}
 {"Quick Bites"}
 {"Sweet Shop"," Quick Bites"}

(5 rows)


问:
Can I optimize the migration process when deploying to aws in a nest.js + prisma environment?
I had a problem while deploying to aws using nest js + prisma, so please help.

Currently, I deploy nest js via EBS (feat. zip file and prisma folder)

However, the problem is that the "prisma generate" command must be specified in git hub actions deploy.yml every time due to npm installation.

As you know, Prisma's official website recommends "prisma deploy" command in a test or master environment.

For this reason, how can I run the deploy command normally without entering the current 'generate command?

This is the prisma db-related configuration code in the deploy.yml file.


问:
Flutter build form controllers using JSON data
I have implemented the flutter forms using the JSON data received from the database but having some issue while returning the widget.i.e not displaying the form fields. can some one help to resolve the issue?

MyApp.dart

```<code>        class MyApp extends StatelessWidget {
          const MyApp({super.key});

          @override
          Widget build(BuildContext context) {
           @override
            void initState() {
            super.initState();

    //Field validations
    String responseData = '{"Data":[{"FieldType":"ALPHANUMERIC","IsMandatory":"TRUE","MaxLength":"15","MinLength":"10","Regex":"","name":"Water Connection Number"}],"Errors":[],"ResponseCode":"0","ResponseMessage":"SUCCESS"}';
    var tagObjsJson = jsonDecode(responseData)['Data'] as List;
    _fieldValidationsData = tagObjsJson.map((tagJson) => FieldValidationsResponse.fromJson(tagJson)).toList();
  }
            return MaterialApp(
              title: 'Welcome to Flutter',
              home: Scaffold(
                appBar: AppBar(
                  title: const Text('Welcome to Flutter'),
                ),
                body: return Container(
                  child: customFieldWidget()
                 )
              ),
            );
          }
        }

      Widget customFieldWidget() {
        var _tempListWidgets = <Widget>[];
        List<Map> _validationList = [];
         _fieldValidationsData?.forEach((element) {
          final textController = new TextEditingController();
          _tempListWidgets.add(Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(height: 14.0),

              Text("Please enter your ${element.name}",
                style: Get.textTheme.button!.copyWith(
                    fontSize: font18
                ),),
              SizedBox(height: 14.0,),
              Container(
                child: TextField(
                  autocorrect: true,
                  controller: textController,
                  maxLength: element.MaxLength == "0" ? 9 : int.tryParse("${element.MaxLength}"),

                  decoration: InputDecoration(
                      hintText: '${element.name}',
                      hintStyle: TextStyle(color: Colors.grey),
                      filled: true
                  ),

                ),
              ),
            ],

          ));

          _validationList.add(element);

        });
          return _tempListWidgets;
        }

        }
</code>```

Body:
I have implemented the flutter forms using the JSON data received from the database but having some issue while returning the widget.i.e not displaying the form fields. can some one help to resolve the issue?

MyApp.dart

        class MyApp extends StatelessWidget {
          const MyApp({super.key});

          @override
          Widget build(BuildContext context) {
           @override
            void initState() {
            super.initState();

    //Field validations
    String responseData = '{"Data":[{"FieldType":"ALPHANUMERIC","IsMandatory":"TRUE","MaxLength":"15","MinLength":"10","Regex":"","name":"Water Connection Number"}],"Errors":[],"ResponseCode":"0","ResponseMessage":"SUCCESS"}';
    var tagObjsJson = jsonDecode(responseData)['Data'] as List;
    _fieldValidationsData = tagObjsJson.map((tagJson) => FieldValidationsResponse.fromJson(tagJson)).toList();
  }
            return MaterialApp(
              title: 'Welcome to Flutter',
              home: Scaffold(
                appBar: AppBar(
                  title: const Text('Welcome to Flutter'),
                ),
                body: return Container(
                  child: customFieldWidget()
                 )
              ),
            );
          }
        }

      Widget customFieldWidget() {
        var _tempListWidgets = <Widget>[];
        List<Map> _validationList = [];
         _fieldValidationsData?.forEach((element) {
          final textController = new TextEditingController();
          _tempListWidgets.add(Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(height: 14.0),

              Text("Please enter your ${element.name}",
                style: Get.textTheme.button!.copyWith(
                    fontSize: font18
                ),),
              SizedBox(height: 14.0,),
              Container(
                child: TextField(
                  autocorrect: true,
                  controller: textController,
                  maxLength: element.MaxLength == "0" ? 9 : int.tryParse("${element.MaxLength}"),

                  decoration: InputDecoration(
                      hintText: '${element.name}',
                      hintStyle: TextStyle(color: Colors.grey),
                      filled: true
                  ),

                ),
              ),
            ],

          ));

          _validationList.add(element);

        });
          return _tempListWidgets;
        }

        }


问:
what is the best solution for nested select input in reactJS?
this is the multi-level select input.. i need this with the best technology.

Actually, I am trying to create nested select input in reactJS,

I found this problem when I was doing my assignment, i tried to solve the problem, and even i had solved the UI design, but can't control this input field properly.
mentionable : react-dropdown-tree-selec i used this library.
but i think it's not the best solution


问:
How to add Spring at "add framework support"?
I want to add Spring at "add framework support".
but, my Intellij doesn't appear Spring at "add framework support".
I'm using the IntelliJ Ultimate edition.

my Injellij info

I've tried "project structure > facets" and tried to delete "spring".
but, there was no Spring in the below image.

I want to do it.

Finally, I'm sorry for my poor English.


问:
error when working with web3dart in flutter
```<code>import 'dart:html';
import 'package:web3dart/web3dart.dart';

import 'package:flutter/material.dart';

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Client? httpClient;
  Web3Client? ethClient;

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
</code>```

when connecting Web3 Client erroneously

error text : Target of URI doesn't exist: 'package:web3dart/web3dart.dart'.
Try creating the file referenced by the URI, or try using a URI for a file that does exist.darturi_does_not_exist

error text : Undefined class 'Web3Client'.
Try changing the name to the name of an existing class, or creating a class with the name 'Web3Client'.dartundefined_class

Body:
import 'dart:html';
import 'package:web3dart/web3dart.dart';

import 'package:flutter/material.dart';

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Client? httpClient;
  Web3Client? ethClient;

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

when connecting Web3 Client erroneously

error text : Target of URI doesn't exist: 'package:web3dart/web3dart.dart'.
Try creating the file referenced by the URI, or try using a URI for a file that does exist.darturi_does_not_exist

error text : Undefined class 'Web3Client'.
Try changing the name to the name of an existing class, or creating a class with the name 'Web3Client'.dartundefined_class


问:
How to Promise.all() in SuiteScript 2.0 (Netsuite)
So the scenario is like this: I have a Suitelet that displays lines, lines are marked with a checkbox by a user and then a "submit" button is clicked. That button calls a Client Script function that goes over the selected lines in a loop and sends https calls to the Suitelet one line at a time to submit the lines (create a custom record and update a Work Order line).

Once all lines are submited a UI message is displayed with success and error messages.

Now I want to make the HTTPS calls asynchronous which I know I can do with https.prmise BUT I can't figure out how to Prmomise.all in SuiteScript 2.0.

Help?


问:
AWS Proxy Cutting off Post Data in non-SSL HTTP Request but not in SSL HTTP request
I have a webserver running on an Amazon Web Server. I programmed the webserver software myself. The webserver primarily uses HTTPS and has been getting hung up somewhere. The server has the option to turn SSL on and off for debugging purposes, and during debugging I found that post data was not getting sent in the HTTP request originating from the client (browser). The browser was sending a whole proper HTTP request containing post data, but my server was not receiving the post data contained in the request. This is only happening when the HTTP request is not over SSL and is a raw plain text HTTP request. HTTPS works perfectly fine and the post data is getting through.

I downloaded an exact copy of the webserver and ran it on my laptop, and found that the post data was being received as normal over non-ssl HTTP and all post related actions were functioning normally over non-ssl HTTP. The only difference is that the proxy all the traffic is going through on AWS to get to my server is appending request parameters to the end of the HTTP request, and the post data is either overwritten, or not being parsed through that process in the proxy.

The reason it works when using HTTPS, is because the proxy server isn't able to append anything to the HTTP request since the SSL originates from the server behind the proxy, and all the proxy sees is an encrypted string.

Does anyone who is familiar with AWS know if there is a way to fix this issue? At this stage, I still don't know why or where the server is getting hung up, but it doesn't seem to happen when not running on the AWS server, and because post data is making it through over SSL, I'm not 100% sure the issue is related because non-SSL http get requests work perfectly fine while the server is hung up, but HTTPS get requests do not.

I didn't share any code because the issue appears to be with the AWS platform. If anyone who has any experience with the AWS platform has any knowledge or help to share, it would be greatly appreciated.

I don't know what to try because it appears to be related to the functionality of the AWS platform.


问:
Default canonical tag for "?" included URL in WordPress
My wordpress website have created so many copy of a single page and post by default for multiple currency system

```<code>How can I set default canonical tag system for sitewide to "?" included URL

Example: https://example.com/page/?c=USD
         https://example.com/page/?c=EUR

Default canonical: https://example.com/page

</code>```

Thank You

Body:
My wordpress website have created so many copy of a single page and post by default for multiple currency system

How can I set default canonical tag system for sitewide to "?" included URL

Example: https://example.com/page/?c=USD
         https://example.com/page/?c=EUR

Default canonical: https://example.com/page

Thank You


问:
Error using ioredis in nodejs - ReplyError: Timeout limit was reached
I'm using ioredis module in nodejs to manage redis client. sometimes when executing search(I'm using Redisearch),  I'm getting this error into my application.

```<code> ReplyError: Timeout limit was reached
     at parseError (/home/robsom/Documents/test_redis/backend/node_modules/redis-parser/lib/parser.js:179:12)
     at parseType (/home/robsom/Documents/test_redis/backend/node_modules/redis-parser/lib/parser.js:302:14) {
   command: {
     name: 'FT.SEARCH',
     args: [
       'idx_contact',
       '(@escaped_name:*99329382*)|(@number:*99329382*)',
       'LIMIT',
       '0',
       '20',
       'SORTBY',
       'escaped_name',
       'ASC'
     ]
   }
 }
</code>```

THIS IS THE METHOD THAT I USE TO CONNECT TO THE REDIS INTO MY APPLICATION

```<code>
const redisConn = async () => {

    if(!process.env.CACHE){
        return null
    }

    try {

        const redis = new Redis();

        const conn = () => new Promise((resolve, reject) => {

            redis.on('error', async (err) => {

                if (err.code === 'ECONNREFUSED') {
                    console.error(`Redis connection error: ${err}.`)
                    await redis.quit()
                }
                else {
                    console.error(`Redis encountered an error: ${err.message}.`)
                }

                reject(err)

            })

            redis.on('connect', () => {

                // console.log('CacheStore - Connection status: connected');
                resolve(redis);

            })

            redis.on('end', () => {
                // console.log('CacheStore - Connection status: disconnected');
            });

            redis.on('reconnecting', () => {
                // console.log('CacheStore - Connection status: reconnecting');
            });
        });

        return await conn();

    } catch (e) {
        console.error(e);
        return Promise.resolve([]);
    }

}
</code>```

My OS is ubuntu 20.04

node version v16.13.1

redis version: Redis server v=6.2.6 sha=00000000:0 malloc=jemalloc-5.1.0 bits=64 build=b7dc414a57056789

ioredis version: "ioredis": "^5.2.3",

Aways when I open the redis conection with   const redis = new Redis(); I'm closing with "await redis.quit()" into my funcion. The aplication has about 20 user with execute some contacts query that has about 90000 registry and a ticket query with has about  200000 tickets. All this registry is saved in type hash in redis

I'm try make a search using ioredis and want get a response without error

Body:
I'm using ioredis module in nodejs to manage redis client. sometimes when executing search(I'm using Redisearch),  I'm getting this error into my application.

 ReplyError: Timeout limit was reached
     at parseError (/home/robsom/Documents/test_redis/backend/node_modules/redis-parser/lib/parser.js:179:12)
     at parseType (/home/robsom/Documents/test_redis/backend/node_modules/redis-parser/lib/parser.js:302:14) {
   command: {
     name: 'FT.SEARCH',
     args: [
       'idx_contact',
       '(@escaped_name:*99329382*)|(@number:*99329382*)',
       'LIMIT',
       '0',
       '20',
       'SORTBY',
       'escaped_name',
       'ASC'
     ]
   }
 }

THIS IS THE METHOD THAT I USE TO CONNECT TO THE REDIS INTO MY APPLICATION

const redisConn = async () => {

    if(!process.env.CACHE){
        return null
    }

    try {

        const redis = new Redis();

        const conn = () => new Promise((resolve, reject) => {

            redis.on('error', async (err) => {

                if (err.code === 'ECONNREFUSED') {
                    console.error(`Redis connection error: ${err}.`)
                    await redis.quit()
                }
                else {
                    console.error(`Redis encountered an error: ${err.message}.`)
                }

                reject(err)

            })

            redis.on('connect', () => {

                // console.log('CacheStore - Connection status: connected');
                resolve(redis);

            })

            redis.on('end', () => {
                // console.log('CacheStore - Connection status: disconnected');
            });

            redis.on('reconnecting', () => {
                // console.log('CacheStore - Connection status: reconnecting');
            });
        });

        return await conn();

    } catch (e) {
        console.error(e);
        return Promise.resolve([]);
    }

}

My OS is ubuntu 20.04

node version v16.13.1

redis version: Redis server v=6.2.6 sha=00000000:0 malloc=jemalloc-5.1.0 bits=64 build=b7dc414a57056789

ioredis version: "ioredis": "^5.2.3",

Aways when I open the redis conection with   const redis = new Redis(); I'm closing with "await redis.quit()" into my funcion. The aplication has about 20 user with execute some contacts query that has about 90000 registry and a ticket query with has about  200000 tickets. All this registry is saved in type hash in redis

I'm try make a search using ioredis and want get a response without error