问:
How to move some hook in separate file ? React hook
I want to separate my function with hook because i have a lot of in one file....

example of code:

```<code>  const collectOrganisationUnitNode = useCallback((treeData) => {
       // someLogic
  }, []);

  const handleCancelClick = useCallback(() => {
     .../some logic
  }, [hideModal, selected, multiselect, tree]);
</code>```

I want to remove from index.js and set to another file then just import and using inside index.js

is that possible ?

答:
You could make a custom hook that returns these functions.

const customHook = () => {
  const collectOrganisationUnitNode = useCallback((treeData) => {
    // someLogic
  }, []);

  const handleCancelClick = useCallback(() => {
    //some logic
  }, [hideModal, selected, multiselect, tree]);
  return {
    collectOrganisationUnitNode,
    handleCancelClick
  }
};
```
<p>Then used like so inside your component</p>
<pre class="lang-js prettyprint-override"><code>  const { collectOrganisationUnitNode, handleCancelClick } = customHook();

</code>```

Body:
I want to separate my function with hook because i have a lot of in one file....

example of code:

  const collectOrganisationUnitNode = useCallback((treeData) => {
       // someLogic
  }, []);

  const handleCancelClick = useCallback(() => {
     .../some logic
  }, [hideModal, selected, multiselect, tree]);

I want to remove from index.js and set to another file then just import and using inside index.js

is that possible ?

Body:
You could make a custom hook that returns these functions.

const customHook = () => {
  const collectOrganisationUnitNode = useCallback((treeData) => {
    // someLogic
  }, []);

  const handleCancelClick = useCallback(() => {
    //some logic
  }, [hideModal, selected, multiselect, tree]);
  return {
    collectOrganisationUnitNode,
    handleCancelClick
  }
};

Then used like so inside your component

  const { collectOrganisationUnitNode, handleCancelClick } = customHook();


来源: stackexchange

问:
Java swing jtextarea on a tab does not fill out the tab, cannot get it to fill even with scrollbar added
So I'm using the Oracle tabbed example to create a Java swing application to help retrieve quick data from an internal database for a very small company and I'm very new at Java (decent scripting, though). My problem is that retrieved data from the database goes outside tab boundariesenter image description here. From reading a question, I learned I should use a textarea, so I modified to use a text area but then I could not scroll. I fixed the scroll, but now the data is just in a small window on the tab. I can enlarge the tab, I have my scrolls, but I cannot fill out the text area.

This is the gridlayout from the documentation example:
super(new GridLayout(8, 40));

This is the pane that displays the information where inv is an array list defined as follows:
ArrayList<String> inv = new ArrayList<String>();

The data is pulled into the pane with the following code (note that the dimension does not change the text area, in fact, I do not believe this has any effect on the code at all so it is commented out during my testing:

```<code>    JComponent panel2 = makeTextPanel(inv.toString());
    //panel2.setPreferredSize(new Dimension(100, 50));
    tabbedPane.addTab("Customers", null, panel2,
            "Displays Customer Details");
    tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
    } catch (SQLException sqlException) {
        System.out.println(sqlException);
    }
</code>```

This is the code for the panel using scroll tab, text area, etc. which is a modified version of the copied code:

```<code>    //Add the tabbed pane to this panel.
    add(tabbedPane);

    //The following line enables to use scrolling tabs.
    tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
}

protected JComponent makeTextPanel(String text) {
    JPanel panel = new JPanel(false);
    JTextArea filler = new JTextArea(text, 100, 50);
    JScrollPane scroll = new JScrollPane (filler,
        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    //filler.setHorizontalAlignment(JTextArea.CENTER);
    panel.setLayout(new GridLayout(1, 1));
    //panel.add(filler);
    panel.add(scroll);
    return panel;
}
</code>```

The tabbed pane is then displayed using the original code which I did not make any changes:

```<code>private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("TabbedPane");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Add content to the window.
    frame.add(new TabbedPane(), BorderLayout.CENTER);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}
</code>```

The question is, how can I get the text area to fill out the pane instead of just being 1/4 the size (regardless of how I resize the window either in the code or the GUI? The documentation doesn't seem to offer me much (based on searches) that work as I am already setting the scrollbar in the textarea like the documentation specifies. I tried setLineWrap(true) like another question but that was of no help either. See the image for an example of the issue I'm having. Any thoughts?

答:
I'd use a BorderLayout to control the layout of the JScrollPane so it can automatically fill the available space.

You can control the JTextArea's visible size via it's rows and columns properties

```<code>import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                // Replace this with your text retrieval process
                List<String> text = new ArrayList<String>(128);
                try (BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/resources/StarWarANewHope.txt")))) {
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        text.add(line);
                    }
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }

                // Use this to format the results for the text area
                StringJoiner joiner = new StringJoiner("\n");
                for (String line : text) {
                    joiner.add(line);
                }

                JTabbedPane tabbedPane = new JTabbedPane();
                tabbedPane.addTab("Customers", null, new TestPane(joiner.toString()), "Displays customer details");

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(tabbedPane);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane(String text) {
            JTextArea filler = new JTextArea(text, 25, 25);
            filler.setWrapStyleWord(true);
            filler.setLineWrap(true);
            JScrollPane scroll = new JScrollPane(filler);
            //filler.setHorizontalAlignment(JTextArea.CENTER);
            setLayout(new BorderLayout());
            //panel.add(filler);
            add(scroll);
        }
    }

}
</code>```

If you continue to have issues, consider providing a minimal reproducible example, it takes out the guess work and generally results in better answers for more details

ContentLicense: CC BY-SA 4.0

Body:
So I'm using the Oracle tabbed example to create a Java swing application to help retrieve quick data from an internal database for a very small company and I'm very new at Java (decent scripting, though). My problem is that retrieved data from the database goes outside tab boundariesenter image description here. From reading a question, I learned I should use a textarea, so I modified to use a text area but then I could not scroll. I fixed the scroll, but now the data is just in a small window on the tab. I can enlarge the tab, I have my scrolls, but I cannot fill out the text area.

This is the gridlayout from the documentation example:
super(new GridLayout(8, 40));

This is the pane that displays the information where inv is an array list defined as follows:
ArrayList<String> inv = new ArrayList<String>();

The data is pulled into the pane with the following code (note that the dimension does not change the text area, in fact, I do not believe this has any effect on the code at all so it is commented out during my testing:

    JComponent panel2 = makeTextPanel(inv.toString());
    //panel2.setPreferredSize(new Dimension(100, 50));
    tabbedPane.addTab("Customers", null, panel2,
            "Displays Customer Details");
    tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
    } catch (SQLException sqlException) {
        System.out.println(sqlException);
    }

This is the code for the panel using scroll tab, text area, etc. which is a modified version of the copied code:

    //Add the tabbed pane to this panel.
    add(tabbedPane);

    //The following line enables to use scrolling tabs.
    tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
}

protected JComponent makeTextPanel(String text) {
    JPanel panel = new JPanel(false);
    JTextArea filler = new JTextArea(text, 100, 50);
    JScrollPane scroll = new JScrollPane (filler,
        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    //filler.setHorizontalAlignment(JTextArea.CENTER);
    panel.setLayout(new GridLayout(1, 1));
    //panel.add(filler);
    panel.add(scroll);
    return panel;
}

The tabbed pane is then displayed using the original code which I did not make any changes:

private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("TabbedPane");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Add content to the window.
    frame.add(new TabbedPane(), BorderLayout.CENTER);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

The question is, how can I get the text area to fill out the pane instead of just being 1/4 the size (regardless of how I resize the window either in the code or the GUI? The documentation doesn't seem to offer me much (based on searches) that work as I am already setting the scrollbar in the textarea like the documentation specifies. I tried setLineWrap(true) like another question but that was of no help either. See the image for an example of the issue I'm having. Any thoughts?

Body:
I'd use a BorderLayout to control the layout of the JScrollPane so it can automatically fill the available space.

You can control the JTextArea's visible size via it's rows and columns properties

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                // Replace this with your text retrieval process
                List<String> text = new ArrayList<String>(128);
                try (BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/resources/StarWarANewHope.txt")))) {
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        text.add(line);
                    }
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }

                // Use this to format the results for the text area
                StringJoiner joiner = new StringJoiner("\n");
                for (String line : text) {
                    joiner.add(line);
                }

                JTabbedPane tabbedPane = new JTabbedPane();
                tabbedPane.addTab("Customers", null, new TestPane(joiner.toString()), "Displays customer details");

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(tabbedPane);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane(String text) {
            JTextArea filler = new JTextArea(text, 25, 25);
            filler.setWrapStyleWord(true);
            filler.setLineWrap(true);
            JScrollPane scroll = new JScrollPane(filler);
            //filler.setHorizontalAlignment(JTextArea.CENTER);
            setLayout(new BorderLayout());
            //panel.add(filler);
            add(scroll);
        }
    }

}

If you continue to have issues, consider providing a minimal reproducible example, it takes out the guess work and generally results in better answers for more details


问:
I get Error parsing JSON: SyntaxError: Unexpected token u in JSON at position 0 when i try to parse a string from a JSON
```<code>fs.readFile('./horoscopy.json', 'utf8', (err, data) => {
    if (err) {
      console.log('File read failed:', err);
      return;
    }
    try {
        const horoscopeJson = JSON.parse(data);
        console.log(horoscopeJson.horo.aries.today);
      } catch (err) {
        console.log('Error parsing JSON:', err);
      }
  });
</code>```

This is my code

```<code>"aries": [
            {
                "yesterday": [
                    "\nСегодня вы вновь обретете несколько ослабшую в последнее время уверенность в себе. Ситуация начнет меняться, причем , как ни странно, в лучшую сторону.\n"
                ],
                "today": [
                    "\nПостарайтесь сегодня не вмешиваться ни в чьи дела. Не разобравшись в тонкостях дела, вы можете натворить чего-то не того, действуя из лучших побуждений.\n"
                ],
                "tomorrow": [
                    "\nНе тратьте сегодня свое и чужое время на всевозможные словесные изыски. Информация должна исходить от вас в четкой и понятной форме, в противном случае возможны малоприятные накладки.\n"
                ],
                "tomorrow02": [
                    "\nПрежде чем покупать то, что вы давно хотели купить, постарайтесь приложить некоторые усилия к тому, чтобы попытаться заплатить не больше, чем эта вещь реально стоит.\n"
                ]
            }
        ],
</code>```

This is the json object I try to parse
Please help, I found similar problems but none of the solutions there helped
TIA

答:
Try to update a line where you parse with this one:

```<code>const horoscopeJson = JSON.parse(`{${data}}`);
</code>```

In fact, your file foes not conform to JSON format, that's the problem, curly brackets are missing.

Body:
fs.readFile('./horoscopy.json', 'utf8', (err, data) => {
    if (err) {
      console.log('File read failed:', err);
      return;
    }
    try {
        const horoscopeJson = JSON.parse(data);
        console.log(horoscopeJson.horo.aries.today);
      } catch (err) {
        console.log('Error parsing JSON:', err);
      }
  });

This is my code

"aries": [
            {
                "yesterday": [
                    "\nСегодня вы вновь обретете несколько ослабшую в последнее время уверенность в себе. Ситуация начнет меняться, причем , как ни странно, в лучшую сторону.\n"
                ],
                "today": [
                    "\nПостарайтесь сегодня не вмешиваться ни в чьи дела. Не разобравшись в тонкостях дела, вы можете натворить чего-то не того, действуя из лучших побуждений.\n"
                ],
                "tomorrow": [
                    "\nНе тратьте сегодня свое и чужое время на всевозможные словесные изыски. Информация должна исходить от вас в четкой и понятной форме, в противном случае возможны малоприятные накладки.\n"
                ],
                "tomorrow02": [
                    "\nПрежде чем покупать то, что вы давно хотели купить, постарайтесь приложить некоторые усилия к тому, чтобы попытаться заплатить не больше, чем эта вещь реально стоит.\n"
                ]
            }
        ],

This is the json object I try to parse
Please help, I found similar problems but none of the solutions there helped
TIA

Body:
Try to update a line where you parse with this one:

const horoscopeJson = JSON.parse(`{${data}}`);

In fact, your file foes not conform to JSON format, that's the problem, curly brackets are missing.


问:
How can I make a previously incremented set of numbers appear below the current numbers in a new line?
I wrote a javascript that increases a set of numbers every second, where every increased set writes on a new line separated by a horizontal rule. E.g;

20220215155

20220215156

20220215157

20220215158 etc...

```<code>var i = 20220215155;
    function increment(){
     i++;
        document.getElementById('period').innerHTML += i + "<br />" + "<hr />" ;
    }
    setInterval('increment()', 1000);
</code>```

But I want every current set of the numbers to always be in the first line, whereby a previously increased set goes below the currently increased set... E.g;

20220215159

20220215158

20220215157

20220215156

20220215155

Please how do I go about this?

答:
Like this?

<button id="start">Start Incrementing</button>
<button id="stop">Stop Incrementing</button>

```

Body:
I wrote a javascript that increases a set of numbers every second, where every increased set writes on a new line separated by a horizontal rule. E.g;

20220215155

20220215156

20220215157

20220215158 etc...

var i = 20220215155;
    function increment(){
     i++;
        document.getElementById('period').innerHTML += i + "
" + "
" ;
    }
    setInterval('increment()', 1000);

But I want every current set of the numbers to always be in the first line, whereby a previously increased set goes below the currently increased set... E.g;

20220215159

20220215158

20220215157

20220215156

20220215155

Please how do I go about this?

Body:
Like this?

<button id="start">Start Incrementing</button>
<button id="stop">Stop Incrementing</button>
<div id="main"></div>

<script>
    const main = document.querySelector('#main');
    const startBtn = document.querySelector('#start');
    const stopBtn = document.querySelector('#stop');
    let i = 0;
    let interval = null;

    const createElem = () => {
        const div = document.createElement('p');
        div.className = 'inc-elem';
        const h1 = document.createElement('h1');
        h1.innerText = i;
        const hr = document.createElement('hr');

        div.appendChild(h1);
        div.appendChild(hr);
        return div;
    };

    window.addEventListener('DOMContentLoaded', () => {
        const startingDiv = createElem();
        main.prepend(startingDiv);
    });

    const increment = () => {
        i++;
        const newDiv = createElem();
        main.prepend(newDiv);
    };

    startBtn.addEventListener('click', () => (interval = setInterval(increment, 1000)));
    stopBtn.addEventListener('click', () => clearInterval(interval));
</script>


问:
How to create appointment exception from recurring series?
How to create appointment exception from recurring series using the EWS API?  I checked all documentation, and could not find that information.

```<code>Appointment occurrence = Appointment.BindToOccurrence(service, new ItemId(sRecurringMasterId), 3)
</code>```

It is for already existed exception, but how to create one and connect to the recurrent master?

答:
It is for already existed exception, but how to create one and connect to the recurrent master?

You don't create exceptions directly, all you need to do is bind to the Occurrence then modify the occurrence see https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-update-a-recurring-series-by-using-ews. If you modify the date or any other properties when you update the occurrence it will create an exception for you. Basically the way it work is this modifies the Master instance in some case the exception will be a hidden attachment on the underlying master item in others case (depending on what properties you change) it will just modify the recurrence blob https://learn.microsoft.com/en-us/office/client-developer/outlook/mapi/how-to-read-and-parse-a-recurrence-pattern.

You can't link another appointment you create as an exception because of the above reason its just a standalone appointment (or store item).

Body:
How to create appointment exception from recurring series using the EWS API?  I checked all documentation, and could not find that information.

Appointment occurrence = Appointment.BindToOccurrence(service, new ItemId(sRecurringMasterId), 3)

It is for already existed exception, but how to create one and connect to the recurrent master?


问:
Remove punctuation from beginning and end of words in a string
I have a string and I want to remove any - ,( ,) ,& ,$ ,# ,! ,[ ,] ,{ ,} ," ,' from the beginning or end of the word. If it is between the words just ignore those.

Here is an example:

```<code>var $string = "Hello I am a string, and I am called Jack-Tack!. My -mom is Darlean.";
</code>```

I want the above text to be like this after a regex:

```<code>console.log("Hello I am a string and I am called Jack-Tack My mom is Darlean");
</code>```

答:
Here's one I just created. It could probably be simplified, but it works.</p>

```<code>"Hello I am a string, and I am called Jack-Tack!. My -mom is Darlean."
.replace(/(?:[\(\)\-&$#!\[\]{}\"\',\.]+(?:\s|$)|(?:^|\s)[\(\)\-&$#!\[\]{}\"\',\.]+)/g, ' ')
.trim();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a string and I want to remove any - ,( ,) ,& ,$ ,# ,! ,[ ,] ,{ ,} ," ,' from the beginning or end of the word. If it is between the words just ignore those.

Here is an example:

var $string = "Hello I am a string, and I am called Jack-Tack!. My -mom is Darlean.";

I want the above text to be like this after a regex:

console.log("Hello I am a string and I am called Jack-Tack My mom is Darlean");

Body:
Here's one I just created. It could probably be simplified, but it works.

"Hello I am a string, and I am called Jack-Tack!. My -mom is Darlean."
.replace(/(?:[\(\)\-&$#!\[\]{}\"\',\.]+(?:\s|$)|(?:^|\s)[\(\)\-&$#!\[\]{}\"\',\.]+)/g, ' ')
.trim();


问:
Function to test variable in Postgres insert

I have a trigger rule on a table insert

I wish to insert value in another table following that insert

The insert only happen in a specific condition

Current code (that work)

```<code>CREATE OR REPLACE FUNCTION "public"."raw_data_insert"()
  RETURNS "pg_catalog"."trigger" AS $BODY$
    DECLARE v_TitleId JSON;
    DECLARE v_EventName JSON;
    DECLARE v_EntityId JSON;
    DECLARE v_ItemId JSON;

   BEGIN
     v_TitleId = new.data::json->'TitleId';
     v_EventName = new.data::json->'EventName';
     v_EntityId = new.data::json->'EntityId';
     v_ItemId = new.data::json->'ItemId';

     INSERT INTO player_inventory_item_added(titleid, playerid, itemid, timestamp, expiration) VALUES (v_TitleId, v_EntityId, v_ItemId, new.ts, NULL);
   RETURN NEW;

   END;

$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
</code>```

What I would love to do:

```<code>CREATE OR REPLACE FUNCTION "public"."raw_data_insert"()
  RETURNS "pg_catalog"."trigger" AS $BODY$
    DECLARE v_TitleId JSON;
    DECLARE v_EventName JSON;
    DECLARE v_EntityId JSON;
    DECLARE v_ItemId JSON;

   BEGIN
     v_TitleId = new.data::json->'TitleId';
     v_EventName = new.data::json->'EventName';
     v_EntityId = new.data::json->'EntityId';
     v_ItemId = new.data::json->'ItemId';

     IF v_EventName = "player_inventory_item_added" then

     INSERT INTO player_inventory_item_added(titleid, playerid, itemid, timestamp, expiration) VALUES (v_TitleId, v_EntityId, v_ItemId, new.ts, NULL);
   RETURN NEW;

    end if;

   END;

$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
</code>```

My condition trigger a server error. The code without condition work fine.

I also noticed that all my json value return the value + "". For example, when I insert v_EventName in my table, I get "player_inventory_item_added" instead of player_inventory_item_added.

Sorry for the 'noob' question, I did try every combination I could find in the documentation. IS, ==, etc.. I even tested basic int value condition,  nothing work.

Thanks for your help! :)

答: You need to use '"player_inventory_item_added"' - a postgres constant literal (apostrophes) of a json value, specifically a json string literal (quotes). Quotes alone make it an escaped postgres identifier (name of an entity such as variable / column / table etc), but nothing with the name player_inventory_item_added exists in the scope of that function.

Body:
I have a trigger rule on a table insert

I wish to insert value in another table following that insert

The insert only happen in a specific condition

Current code (that work)

CREATE OR REPLACE FUNCTION "public"."raw_data_insert"()
  RETURNS "pg_catalog"."trigger" AS $BODY$
    DECLARE v_TitleId JSON;
    DECLARE v_EventName JSON;
    DECLARE v_EntityId JSON;
    DECLARE v_ItemId JSON;

   BEGIN
     v_TitleId = new.data::json->'TitleId';
     v_EventName = new.data::json->'EventName';
     v_EntityId = new.data::json->'EntityId';
     v_ItemId = new.data::json->'ItemId';

     INSERT INTO player_inventory_item_added(titleid, playerid, itemid, timestamp, expiration) VALUES (v_TitleId, v_EntityId, v_ItemId, new.ts, NULL);
   RETURN NEW;

   END;

$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100

What I would love to do:

CREATE OR REPLACE FUNCTION "public"."raw_data_insert"()
  RETURNS "pg_catalog"."trigger" AS $BODY$
    DECLARE v_TitleId JSON;
    DECLARE v_EventName JSON;
    DECLARE v_EntityId JSON;
    DECLARE v_ItemId JSON;

   BEGIN
     v_TitleId = new.data::json->'TitleId';
     v_EventName = new.data::json->'EventName';
     v_EntityId = new.data::json->'EntityId';
     v_ItemId = new.data::json->'ItemId';

     IF v_EventName = "player_inventory_item_added" then

     INSERT INTO player_inventory_item_added(titleid, playerid, itemid, timestamp, expiration) VALUES (v_TitleId, v_EntityId, v_ItemId, new.ts, NULL);
   RETURN NEW;

    end if;

   END;

$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100

My condition trigger a server error. The code without condition work fine.

I also noticed that all my json value return the value + "". For example, when I insert v_EventName in my table, I get "player_inventory_item_added" instead of player_inventory_item_added.

Sorry for the 'noob' question, I did try every combination I could find in the documentation. IS, ==, etc.. I even tested basic int value condition,  nothing work.

Thanks for your help! :)


问:
Seaborn distplot: fit distribution with some fixed parameres
I want to fit some distribution, say gamma, to a given data array x, and plot the corresponding density function. I can make this easily via seaborn.distplot and scipy.stats:

```<code>sns.distplot(x, fit = stats.gamma)
</code>```

However, let's say that I want some parameters of this distribution to remain fixed, for example loc. When I'm using fit function from scipy.stats with fixed loc, I write it as

```<code>stats.gamma.fit(x, floc = 0)
</code>```

Is there a way to pass loc=0 to fit in distplot function and achieve the same result?

答:
This is a good question.
To find the Gamma distribution approximation of a given data set, you can use liklihood function. This is the link for the formulation. https://en.wikipedia.org/wiki/Gamma_distribution
Here I have generated some random numbers based on a given gamma parameters. Then I have used the data and maximum liklihood to find the parameters of the distribution.</p>
```<code>import numpy as np
from scipy.special import psi
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.optimize import fsolve

# Generating Random variable based on Gamma dist:

shape, scale = 3., 5.  #
s = np.random.gamma(shape, scale, 1000)

plt.hist(s, 50, density=True)

# Solving Liklihood:
Log_s=np.log(s)
Mean_s=np.mean(s)
Size_s=np.size(s)

k=fsolve(lambda k: np.log(k)-psi(k)-np.log(Mean_s)+(1/Size_s)*np.sum(Log_s),.1)
theta=Mean_s/k

sns.distplot(np.random.gamma(k, theta, 1000), hist=False, label='Gamma')

plt.show()
</code>```

Body:
I want to fit some distribution, say gamma, to a given data array x, and plot the corresponding density function. I can make this easily via seaborn.distplot and scipy.stats:

sns.distplot(x, fit = stats.gamma)

However, let's say that I want some parameters of this distribution to remain fixed, for example loc. When I'm using fit function from scipy.stats with fixed loc, I write it as

stats.gamma.fit(x, floc = 0)

Is there a way to pass loc=0 to fit in distplot function and achieve the same result?

Body:
This is a good question.
To find the Gamma distribution approximation of a given data set, you can use liklihood function. This is the link for the formulation. https://en.wikipedia.org/wiki/Gamma_distribution
Here I have generated some random numbers based on a given gamma parameters. Then I have used the data and maximum liklihood to find the parameters of the distribution.

import numpy as np
from scipy.special import psi
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.optimize import fsolve

# Generating Random variable based on Gamma dist:

shape, scale = 3., 5.  #
s = np.random.gamma(shape, scale, 1000)

plt.hist(s, 50, density=True)

# Solving Liklihood:
Log_s=np.log(s)
Mean_s=np.mean(s)
Size_s=np.size(s)

k=fsolve(lambda k: np.log(k)-psi(k)-np.log(Mean_s)+(1/Size_s)*np.sum(Log_s),.1)
theta=Mean_s/k

sns.distplot(np.random.gamma(k, theta, 1000), hist=False, label='Gamma')

plt.show()


问:
Align two flex items vertically independent of each other
Inside the container are two elements "Title" and "Signature". Their vertical position will be taken from the given parameters and added to the mustache template, i.e. can be anything, for example:

title and caption top/center/bottom;

title at the top, caption at the center;

title centered, caption bottom;

title at the top, caption at the bottom, etc.

If I do it through the lines, then the captions either stick to the headings (when they are on the same vertical) or the indentation is visible along the width of the heading content. If I do through the columns - nothing happens at all. Can anyone suggest to align several elements vertically, but so that they do not stick together and do not run into each other?

.item {
  display: flex;
  align-items: flex-start;
  border: 5px solid yellow;
  background-color: #bbb;
  height: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="item">
     <div class="title" style="align-self: flex-start;">Title lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum</div>
     <div class="caption" style="align-self: center;">Caption caption caption</div>
  </div>

    <div class="item">
     <div class="title" style="align-self: center;">Title lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum</div>
     <br>
     <div class="caption" style="align-self: center;">Caption caption caption</div>
  </div>

      <div class="item">
     <div class="title" style="align-self: center;">Title lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum</div>
     <br>
     <div class="caption" style="align-self: flex-end;">Caption caption caption</div>
  </div></code>```

UPD: Added an image of how it should look like in the end

答:
You can make use of justify-self and align-self for variant 2 and 3. Everything else is basic flexbox and grid which you can learn here and here.

*{
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
body{
  display: flex;
  flex-wrap: wrap;
  margin: 1rem;
  gap: 1rem;
}
.variant{
  padding: 1rem;
  background-color: #6D6A89;
  height: 25rem;
  width: 250px;
  color: #fff;
}

.var1{
  display: flex;
  flex-direction: column;
  align-items: center;
}

.var2{
  display: grid;
}
.var2>*{
  justify-self: center;
}

.var3{
  display: grid;
}

.var3>*{
  align-self: end;
  justify-self: center;
}

.var4{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="variant var1">
    <h1>Title top</h1>
    <div class="caption">caption top</div>
  </div>
  <div class="variant var2">
    <h1>Title top</h1>
    <div class="caption">caption center</div>
  </div>
  <div class="variant var3">
    <h1>Title center</h1>
    <div class="caption">caption bottom</div>
  </div>
  <div class="variant var4">
    <h1>Title top</h1>
    <div class="caption">caption bottom</div>
  </div>
</body></code>```

More on flexbox here.

Body:
Inside the container are two elements "Title" and "Signature". Their vertical position will be taken from the given parameters and added to the mustache template, i.e. can be anything, for example:

title and caption top/center/bottom;

title at the top, caption at the center;

title centered, caption bottom;

title at the top, caption at the bottom, etc.

If I do it through the lines, then the captions either stick to the headings (when they are on the same vertical) or the indentation is visible along the width of the heading content. If I do through the columns - nothing happens at all. Can anyone suggest to align several elements vertically, but so that they do not stick together and do not run into each other?

.item {
  display: flex;
  align-items: flex-start;
  border: 5px solid yellow;
  background-color: #bbb;
  height: 200px;
}

Title lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum

Caption caption caption

Title lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum

Caption caption caption

Title lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum

Caption caption caption

UPD: Added an image of how it should look like in the end

Body:
You can make use of justify-self and align-self for variant 2 and 3. Everything else is basic flexbox and grid which you can learn here and here.

*{
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
body{
  display: flex;
  flex-wrap: wrap;
  margin: 1rem;
  gap: 1rem;
}
.variant{
  padding: 1rem;
  background-color: #6D6A89;
  height: 25rem;
  width: 250px;
  color: #fff;
}

.var1{
  display: flex;
  flex-direction: column;
  align-items: center;
}

.var2{
  display: grid;
}
.var2>*{
  justify-self: center;
}

.var3{
  display: grid;
}

.var3>*{
  align-self: end;
  justify-self: center;
}

.var4{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}

<body>
  <div class="variant var1">
    <h1>Title top</h1>
    <div class="caption">caption top</div>
  </div>
  <div class="variant var2">
    <h1>Title top</h1>
    <div class="caption">caption center</div>
  </div>
  <div class="variant var3">
    <h1>Title center</h1>
    <div class="caption">caption bottom</div>
  </div>
  <div class="variant var4">
    <h1>Title top</h1>
    <div class="caption">caption bottom</div>
  </div>
</body>

More on flexbox here.


问:
Get Excel tab colors to Treview node color - wrong colors displayed
I'm trying to get the tab colors of excel sheets to treeview nodes.backColor, but i'm not getting the correct colors and i'm not sure way (red is blue, blue is orange...). Please let me know what i'm doing wrong.

```<code>Sub sheets_loadToTreeView()
        Dim WB As Excel.Workbook = Globals.ThisAddIn.Application.ActiveWorkbook
        Dim SH As Excel.Worksheet
        Dim dSHeets As New Dictionary(Of String, String), dKey, tabColor
        Dim dColors As New Dictionary(Of String, Color)
        Dim mainNode As TreeNode, colorNode As TreeNode, shNode As TreeNode, MyNode1() As TreeNode
        Dim colorname As String

        For Each SH In WB.Worksheets
            tabColor = color_integerToColor(SH.Tab.Color)
            dSHeets.Add(SH.Name.ToString(), SH.Tab.Color)
            If Not dColors.ContainsKey(SH.Tab.Color) Then
                dColors.Add(SH.Tab.Color, tabColor)
            End If
        Next

        With Me.TreeView1
            .CheckBoxes = True
            .Nodes.Clear()

            mainNode = .Nodes.Add("sheets", "Sheets")

            For Each dKey In dColors.Keys
                colorName = "------------------"
                colorNode = mainNode.Nodes.Add(dKey, colorName)
                colorNode.Tag = "color"
                colorNode.BackColor = dColors(dKey)
                colorNode.ForeColor = dColors(dKey)
            Next

            For Each dKey In dSHeets.Keys
                MyNode1 = Me.TreeView1.Nodes.Find(dSHeets(dKey), True)

                If UBound(MyNode1) >= 0 Then
                    shNode = MyNode1(0).Nodes.Add(dKey, dKey)
                    shNode.Tag = "sheet"
                End If
            Next
            .ExpandAll()
            'MyNode.FirstNode.EnsureVisible()
        End With
    End Sub

    Public Function color_toInteger(ByVal C As Color) As Integer
        Return C.ToArgb
    End Function

    Public Function color_integerToColor(ByVal colorValue As Integer) As Color
        Return Color.FromArgb(colorValue)
    End Function
</code>```

答:
Thanks @jimi, I did have my variable type set incorrectly, but that was not the problem.
The problem was that Red and Blue were indeed reversed, so I needed the break down the color into RGB and then reverser the Blue and Red position.</p>
```<code>    Public Function color_integerToColor(ByVal colorValue As Integer) As Color
        'Return Color.FromArgb(colorValue,)

        'SOURCE: https://social.technet.microsoft.com/wiki/contents/articles/17432.vb-net-how-to-convert-a-32-bit-integer-into-a-color.aspx

        Dim Bytes As Byte() = BitConverter.GetBytes(colorValue)
        Dim Alpha As Byte = Bytes(3)
        Dim Red As Byte = Bytes(0)   '2
        Dim Green As Byte = Bytes(1)
        Dim Blue As Byte = Bytes(2)  '0
        Return Color.FromArgb(Alpha, Red, Green, Blue)
    End Function
</code>```

Body:
I'm trying to get the tab colors of excel sheets to treeview nodes.backColor, but i'm not getting the correct colors and i'm not sure way (red is blue, blue is orange...). Please let me know what i'm doing wrong.

Sub sheets_loadToTreeView()
        Dim WB As Excel.Workbook = Globals.ThisAddIn.Application.ActiveWorkbook
        Dim SH As Excel.Worksheet
        Dim dSHeets As New Dictionary(Of String, String), dKey, tabColor
        Dim dColors As New Dictionary(Of String, Color)
        Dim mainNode As TreeNode, colorNode As TreeNode, shNode As TreeNode, MyNode1() As TreeNode
        Dim colorname As String

        For Each SH In WB.Worksheets
            tabColor = color_integerToColor(SH.Tab.Color)
            dSHeets.Add(SH.Name.ToString(), SH.Tab.Color)
            If Not dColors.ContainsKey(SH.Tab.Color) Then
                dColors.Add(SH.Tab.Color, tabColor)
            End If
        Next

        With Me.TreeView1
            .CheckBoxes = True
            .Nodes.Clear()

            mainNode = .Nodes.Add("sheets", "Sheets")

            For Each dKey In dColors.Keys
                colorName = "------------------"
                colorNode = mainNode.Nodes.Add(dKey, colorName)
                colorNode.Tag = "color"
                colorNode.BackColor = dColors(dKey)
                colorNode.ForeColor = dColors(dKey)
            Next

            For Each dKey In dSHeets.Keys
                MyNode1 = Me.TreeView1.Nodes.Find(dSHeets(dKey), True)

                If UBound(MyNode1) >= 0 Then
                    shNode = MyNode1(0).Nodes.Add(dKey, dKey)
                    shNode.Tag = "sheet"
                End If
            Next
            .ExpandAll()
            'MyNode.FirstNode.EnsureVisible()
        End With
    End Sub

    Public Function color_toInteger(ByVal C As Color) As Integer
        Return C.ToArgb
    End Function

    Public Function color_integerToColor(ByVal colorValue As Integer) As Color
        Return Color.FromArgb(colorValue)
    End Function

Body:
Thanks @jimi, I did have my variable type set incorrectly, but that was not the problem.
The problem was that Red and Blue were indeed reversed, so I needed the break down the color into RGB and then reverser the Blue and Red position.

    Public Function color_integerToColor(ByVal colorValue As Integer) As Color
        'Return Color.FromArgb(colorValue,)

        'SOURCE: https://social.technet.microsoft.com/wiki/contents/articles/17432.vb-net-how-to-convert-a-32-bit-integer-into-a-color.aspx

        Dim Bytes As Byte() = BitConverter.GetBytes(colorValue)
        Dim Alpha As Byte = Bytes(3)
        Dim Red As Byte = Bytes(0)   '2
        Dim Green As Byte = Bytes(1)
        Dim Blue As Byte = Bytes(2)  '0
        Return Color.FromArgb(Alpha, Red, Green, Blue)
    End Function


问:
ModelState IsValid returns False Using ASP.NET Core 5 MVC Identity with UserName
I'm trying to accomplish login functionality using UserName instead of Email to Login.

I'm using Bootstrap Modal dialog for loging in users with jquery and ajax for error handling.

The UserName is not an email address so ModelState IsValid always returns false. If I hard code an email address in the javascrip file then all works.

Is there anyway around this issue. Any help would be much appreciated.

```<code>    <div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
  <div class="modal-header">
    <h5 class="modal-title" id="exampleModalLabel">Login</h5>
    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
  </div>
  <div class="modal-body">
    <form id="UserLoginForm" asp-controller="UserAuth" asp-action="login">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <input type="hidden" asp-for="LoginInValid" />
        <div class="form-group row mb-3">
            <label asp-for="UserName" class="col-md-4 col-form-label"></label>
            <div class="col-md-8">
                <input asp-for="UserName" placeholder="User Name" class="form-control" />
                <span asp-validation-for="UserName" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group row mb-3">
            <label asp-for="Password" class="col-md-4 col-form-label"></label>
            <div class="col-md-8">
                <input asp-for="Password" placeholder="Password" class="form-control" />
                <span asp-validation-for="Password" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group-row">
            <div class="col-md-8 offset-md-4">
                <div class="form-check">
                    <input asp-for="RememberMe" class="form-check-input" />
                    <label asp-for="RememberMe" class="col-md-4" col-form-label"></label>
                </div>
            </div>
        </div>
    </form>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
    <button type="button" id="login" name="login" class="btn btn-primary">Login</button>
  </div>
</div>
</code>```

```<code> [AllowAnonymous]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginModel loginModel)
    {
        loginModel.LoginInValid = "true";

        if (ModelState.IsValid)
        {
            var result = await _signInManager.PasswordSignInAsync(loginModel.UserName, loginModel.Password, loginModel.RememberMe, lockoutOnFailure: false);

            if (result.Succeeded)
            {
                loginModel.LoginInValid = "";
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt");
            }
        }
        return PartialView("_UserLoginPartial", loginModel);
    }
</code>```

Error handling is not displayed

```<code>(function () {
    var userloginButton = $("#UserLoginModal button[name='login']").click(onUserLoginClick);

    function onUserLoginClick() {

        var url = "UserAuth/Login";

        var antiForgeryToken = $("#UserLoginModal input[name='__RequestVerificationToken']").val();

        var username = $("#UserLoginModal input[name = 'UserName']").val();
        var email = "mydomain.com"
        /*var email = $("#UserLoginModal input[name = 'Email']").val();*/
        var password = $("#UserLoginModal input[name = 'Password']").val();
        var rememberMe = $("#UserLoginModal input[name = 'RememberMe']").prop('checked');

        var userInput = {
            __RequestVerificationToken: antiForgeryToken,
            UserName: username,
            Email: email,
            Password: password,
            RememeberMe: rememberMe
        };
    }
});
</code>```

LoginModel

```<code>public class LoginModel
{
    [Required]
    [Display(Name = "User Name")]
    [StringLength(25, MinimumLength = 2)]
    public string UserName { get; set; }

    [Required]
    [StringLength(100, MinimumLength = 2)]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [StringLength (100, MinimumLength = 2)]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    public bool RememberMe { get; set; }

    public string LoginInValid { get; set; }
}
</code>```

答:
LoginModel has UserName, Email, and Password all marked as "Required", so ModelState will not be valid unless all are provided.

You'll need to either provide values for each of these (I don't see any Email input in your HTML markup) or remove the [Required] annotation from the LoginModel properties you don't want to provide.

Body:
I'm trying to accomplish login functionality using UserName instead of Email to Login.

I'm using Bootstrap Modal dialog for loging in users with jquery and ajax for error handling.

The UserName is not an email address so ModelState IsValid always returns false. If I hard code an email address in the javascrip file then all works.

Is there anyway around this issue. Any help would be much appreciated.

Login

    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

    <form id="UserLoginForm" asp-controller="UserAuth" asp-action="login">

        <input type="hidden" asp-for="LoginInValid" />

                <input asp-for="UserName" placeholder="User Name" class="form-control" />

                <input asp-for="Password" placeholder="Password" class="form-control" />

                    <input asp-for="RememberMe" class="form-check-input" />

    </form>

    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
    <button type="button" id="login" name="login" class="btn btn-primary">Login</button>

 [AllowAnonymous]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginModel loginModel)
    {
        loginModel.LoginInValid = "true";

        if (ModelState.IsValid)
        {
            var result = await _signInManager.PasswordSignInAsync(loginModel.UserName, loginModel.Password, loginModel.RememberMe, lockoutOnFailure: false);

            if (result.Succeeded)
            {
                loginModel.LoginInValid = "";
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt");
            }
        }
        return PartialView("_UserLoginPartial", loginModel);
    }

Error handling is not displayed

(function () {
    var userloginButton = $("#UserLoginModal button[name='login']").click(onUserLoginClick);

    function onUserLoginClick() {

        var url = "UserAuth/Login";

        var antiForgeryToken = $("#UserLoginModal input[name='__RequestVerificationToken']").val();

        var username = $("#UserLoginModal input[name = 'UserName']").val();
        var email = "mydomain.com"
        /*var email = $("#UserLoginModal input[name = 'Email']").val();*/
        var password = $("#UserLoginModal input[name = 'Password']").val();
        var rememberMe = $("#UserLoginModal input[name = 'RememberMe']").prop('checked');

        var userInput = {
            __RequestVerificationToken: antiForgeryToken,
            UserName: username,
            Email: email,
            Password: password,
            RememeberMe: rememberMe
        };
    }
});

LoginModel

public class LoginModel
{
    [Required]
    [Display(Name = "User Name")]
    [StringLength(25, MinimumLength = 2)]
    public string UserName { get; set; }

    [Required]
    [StringLength(100, MinimumLength = 2)]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [StringLength (100, MinimumLength = 2)]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    public bool RememberMe { get; set; }

    public string LoginInValid { get; set; }
}


问:
How to retrieve UUID value in Java/JPA for Oracle database?
I am using Oracle database and have to define a UUID column. I followed other posts and created the table using regex pattern for primary key:

```<code>CREATE TABLE TEST_UUID (
    ID_UUID VARCHAR(255)
    DEFAULT REGEXP_REPLACE(RAWTOHEX(SYS_GUID()), '([A-F0-9]{8})([A-F0-9]{4})([A-F0-9]{4})([A-F0-9]{4})([A-F0-9]{12})', '\1-\2-\3-\4-\5'),
    NAME VARCHAR2(40)  NOT NULL
);
</code>```

In my entity class I have to define the ID_UUID column of type UUID (cannot define it as String). The entity class looks like this:

```<code>import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "test_uuid")
public class TestUuid {

    @Id
    @Column(name = "id_uuid")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID idUuid;

    @Column(name = "name")
    private String name;

    /**
     * @return the idUuid
     */
    public UUID getIdUuid() {
        return idUuid;
    }

    /**
     * @param idUuid the idUuid to set
     */
    public void setIdUuid(UUID idUuid) {
        this.idUuid = idUuid;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

}
</code>```

When I retrieve the table values I don't get the same value for ID_UUID whats stored in the database because of UUID data type (if I change it to a String I am able to pull the correct value). My limitation is to use the UUID type as I am migrating from Postgre to Oracle database and cannot change my entity class. Is it possible to retrieve the correct value using UUID data type?

答:
You need to define custom type that stores and retrieves UUID type as VARCHAR.

See Hibernate UUID type implementation.

https://github.com/hibernate/hibernate-orm/blob/main/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/UUIDJavaType.java

In case if you have Hibernate 5 or higher you can use it.

Create own user type

```<code>public class UUIDType extends AbstractSingleColumnStandardBasicType<UUID> {

    public static final UUIDType INSTANCE = new UUIDType();
    public static final String NAME = "UUIDType";

    public UUIDType() {
        super(VarcharTypeDescriptor.INSTANCE, UUIDTypeDescriptor.INSTANCE);
    }

    @Override
    public String getName() {
        return NAME;
    }
}
</code>```

Implement a UUIDTypeDescriptor for storing and retrieving UUID as VARCHAR

```<code>public class UUIDTypeDescriptor extends AbstractTypeDescriptor<UUID> {

    public static final UUIDTypeDescriptor INSTANCE = new UUIDTypeDescriptor();

    public UUIDTypeDescriptor() {
        super(UUID.class, ImmutableMutabilityPlan.INSTANCE);
    }

    @Override
    public String toString(UUID uuid) {
        return uuid.toString();
    }

    @Override
    public UUID fromString(String s) {
        return UUID.fromString(s);
    }

    @Override
    public <T> T unwrap(UUID uuid, Class<T> type, WrapperOptions wrapperOptions) {
        if (uuid == null) return null;

        if (String.class.isAssignableFrom(type)) {
            return (T) uuid.toString();
        }

        throw unknownUnwrap(type);
    }

    @Override
    public <T> UUID wrap(T value, WrapperOptions wrapperOptions) {
        if (value == null)
            return null;

        if(value instanceof String) {
            return UUID.fromString((String) value);
        }

        throw unknownWrap(value.getClass());
    }
}
</code>```

Apply custom type to your entity

Specific for entity:

```<code>@TypeDef(name = UUIDType.NAME,
         typeClass = UUIDType.class,
         defaultForType = UUID.class)
@Entity
@Table(name = "test_uuid")
public class TestUUID {

}
</code>```

or on package lavel in package-info.java file:

```<code>@TypeDef(
    name = UUIDType.NAME,
    typeClass = UUIDType.class,
    defaultForType = UUID.class
)
package com.model;
</code>```

Body:
I am using Oracle database and have to define a UUID column. I followed other posts and created the table using regex pattern for primary key:

CREATE TABLE TEST_UUID (
    ID_UUID VARCHAR(255)
    DEFAULT REGEXP_REPLACE(RAWTOHEX(SYS_GUID()), '([A-F0-9]{8})([A-F0-9]{4})([A-F0-9]{4})([A-F0-9]{4})([A-F0-9]{12})', '\1-\2-\3-\4-\5'),
    NAME VARCHAR2(40)  NOT NULL
);

In my entity class I have to define the ID_UUID column of type UUID (cannot define it as String). The entity class looks like this:

import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "test_uuid")
public class TestUuid {

    @Id
    @Column(name = "id_uuid")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID idUuid;

    @Column(name = "name")
    private String name;

    /**
     * @return the idUuid
     */
    public UUID getIdUuid() {
        return idUuid;
    }

    /**
     * @param idUuid the idUuid to set
     */
    public void setIdUuid(UUID idUuid) {
        this.idUuid = idUuid;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

}

When I retrieve the table values I don't get the same value for ID_UUID whats stored in the database because of UUID data type (if I change it to a String I am able to pull the correct value). My limitation is to use the UUID type as I am migrating from Postgre to Oracle database and cannot change my entity class. Is it possible to retrieve the correct value using UUID data type?

Body:
You need to define custom type that stores and retrieves UUID type as VARCHAR.

See Hibernate UUID type implementation.

https://github.com/hibernate/hibernate-orm/blob/main/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/UUIDJavaType.java

In case if you have Hibernate 5 or higher you can use it.

Create own user type

public class UUIDType extends AbstractSingleColumnStandardBasicType<UUID> {

    public static final UUIDType INSTANCE = new UUIDType();
    public static final String NAME = "UUIDType";

    public UUIDType() {
        super(VarcharTypeDescriptor.INSTANCE, UUIDTypeDescriptor.INSTANCE);
    }

    @Override
    public String getName() {
        return NAME;
    }
}

Implement a UUIDTypeDescriptor for storing and retrieving UUID as VARCHAR

public class UUIDTypeDescriptor extends AbstractTypeDescriptor<UUID> {

    public static final UUIDTypeDescriptor INSTANCE = new UUIDTypeDescriptor();

    public UUIDTypeDescriptor() {
        super(UUID.class, ImmutableMutabilityPlan.INSTANCE);
    }

    @Override
    public String toString(UUID uuid) {
        return uuid.toString();
    }

    @Override
    public UUID fromString(String s) {
        return UUID.fromString(s);
    }

    @Override
    public <T> T unwrap(UUID uuid, Class<T> type, WrapperOptions wrapperOptions) {
        if (uuid == null) return null;

        if (String.class.isAssignableFrom(type)) {
            return (T) uuid.toString();
        }

        throw unknownUnwrap(type);
    }

    @Override
    public <T> UUID wrap(T value, WrapperOptions wrapperOptions) {
        if (value == null)
            return null;

        if(value instanceof String) {
            return UUID.fromString((String) value);
        }

        throw unknownWrap(value.getClass());
    }
}

Apply custom type to your entity

Specific for entity:

@TypeDef(name = UUIDType.NAME,
         typeClass = UUIDType.class,
         defaultForType = UUID.class)
@Entity
@Table(name = "test_uuid")
public class TestUUID {

}

or on package lavel in package-info.java file:

@TypeDef(
    name = UUIDType.NAME,
    typeClass = UUIDType.class,
    defaultForType = UUID.class
)
package com.model;


问:
React/Jest Select element onChange values not updating
I have the following code to test the value of the Select element after changing:

```<code>it("changes value after selecting another field", () => {
  doSetupWork();
  let field = screen.getByLabelText("MySelectField");
  expect(field).toHaveValue("");

  fireEvent.change(field, { target: { value: "1" } });

  // Insert one of two options from below
});
</code>```

However, when I insert the following at the bottom, it does not work:

```<code>field = screen.getByLabelText("MySelectField");
expect(field).toHaveValue("1");
</code>```

and gives the following error message:

```<code>Expected the element to have value: 1
Received:
</code>```

But, when I wrap it in a setTimeout with just 1ms delay, it does work:

```<code>setTimeout(() => {
  field = screen.getByLabelText("MySelectField");
  expect(field).toHaveValue("1");
}, 1);
</code>```

It feels like there should be a more elegant way of writing this without setTimeout. Any advice?

答:
You could try using waitFor instead of setTimeout:

```<code>import {waitFor} from '@testing-library/react'

...

await waitFor(() => screen.getByLabelText("MySelectField").toHaveValue("1"))
</code>```

Body:
I have the following code to test the value of the Select element after changing:

it("changes value after selecting another field", () => {
  doSetupWork();
  let field = screen.getByLabelText("MySelectField");
  expect(field).toHaveValue("");

  fireEvent.change(field, { target: { value: "1" } });

  // Insert one of two options from below
});

However, when I insert the following at the bottom, it does not work:

field = screen.getByLabelText("MySelectField");
expect(field).toHaveValue("1");

and gives the following error message:

Expected the element to have value: 1
Received:

But, when I wrap it in a setTimeout with just 1ms delay, it does work:

setTimeout(() => {
  field = screen.getByLabelText("MySelectField");
  expect(field).toHaveValue("1");
}, 1);

It feels like there should be a more elegant way of writing this without setTimeout. Any advice?

Body:
You could try using waitFor instead of setTimeout:

import {waitFor} from '@testing-library/react'

...

await waitFor(() => screen.getByLabelText("MySelectField").toHaveValue("1"))


问:
XPath expression to fetch price field in this markup
I have the following markup:

```<code><div class="D(ib) Mend(20px)">
   <fin-streamer class="Fw(b) Fz(36px) Mb(-4px) D(ib)" data-symbol="TSLA" data-test="qsp-price" data-field="regularMarketPrice" data-trend="none" data-pricehint="2" value="860" active="">860.00</fin-streamer>
   <fin-streamer class="Fw(500) Pstart(8px) Fz(24px)" data-symbol="TSLA" data-test="qsp-price-change" data-field="regularMarketChange" data-trend="txt" data-pricehint="2" value="-44.549988" active=""><span class="C($negativeColor)">-44.55</span></fin-streamer>
   <fin-streamer class="Fw(500) Pstart(8px) Fz(24px)" data-symbol="TSLA" data-field="regularMarketChangePercent" data-trend="txt" data-pricehint="2" data-template="({fmt})" value="-0.049250998" active=""><span class="C($negativeColor)">(-4.93%)</span></fin-streamer>
   <fin-streamer class="D(n)" data-symbol="TSLA" changeev="regularTimeChange" data-field="regularMarketTime" data-trend="none" value="" active="true"></fin-streamer>
   <fin-streamer class="D(n)" data-symbol="TSLA" changeev="marketState" data-field="marketState" data-trend="none" value="" active="true"></fin-streamer>
   <div id="quote-market-notice" class="C($tertiaryColor) D(b) Fz(12px) Fw(n) Mstart(0)--mobpsm Mt(6px)--mobpsm Whs(n)"><span>At close: February 11 04:00PM EST</span></div>
</div>
</code>```

I am trying to get to the price value, which is the first value in the <fin-streamer> element tag.

I am able to select the parent div, using this selector:

['//div[@class="D(ib) Mend(20px)"]

However, once selected, it is not clear how to select the non standard tag element <fin-streamer> and on to the price field.

How do I extract the price field?

答:
If I understand you correctly, this expression

```<code>//div[@class="D(ib) Mend(20px)"]/fin-streamer[@data-test="qsp-price"]/text()
</code>```

should output

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

Body:
I have the following markup:

   <fin-streamer class="Fw(b) Fz(36px) Mb(-4px) D(ib)" data-symbol="TSLA" data-test="qsp-price" data-field="regularMarketPrice" data-trend="none" data-pricehint="2" value="860" active="">860.00</fin-streamer>
   <fin-streamer class="Fw(500) Pstart(8px) Fz(24px)" data-symbol="TSLA" data-test="qsp-price-change" data-field="regularMarketChange" data-trend="txt" data-pricehint="2" value="-44.549988" active="">-44.55</fin-streamer>
   <fin-streamer class="Fw(500) Pstart(8px) Fz(24px)" data-symbol="TSLA" data-field="regularMarketChangePercent" data-trend="txt" data-pricehint="2" data-template="({fmt})" value="-0.049250998" active="">(-4.93%)</fin-streamer>
   <fin-streamer class="D(n)" data-symbol="TSLA" changeev="regularTimeChange" data-field="regularMarketTime" data-trend="none" value="" active="true"></fin-streamer>
   <fin-streamer class="D(n)" data-symbol="TSLA" changeev="marketState" data-field="marketState" data-trend="none" value="" active="true"></fin-streamer>

At close: February 11 04:00PM EST

I am trying to get to the price value, which is the first value in the <fin-streamer> element tag.

I am able to select the parent div, using this selector:

['//div[@class="D(ib) Mend(20px)"]

However, once selected, it is not clear how to select the non standard tag element <fin-streamer> and on to the price field.

How do I extract the price field?

Body:
If I understand you correctly, this expression

//div[@class="D(ib) Mend(20px)"]/fin-streamer[@data-test="qsp-price"]/text()

should output

860.00


问:
loading pdf using react-pdf
I am trying to display pdf using react-pdf in create-react-app application.
I followed the instructions but the pdf is not displayed.

```<code>import { makeStyles, Box, Grid } from "@material-ui/core";
import React, { useState } from "react";
import Header from "./header";
import contractPdf from "../../sample.pdf";
import { Document, Page } from "react-pdf";

const useStyles = makeStyles((theme) => ({
  root: {
    padding: "32px 24px 14px 24px",
  },
  pdfArea: {
    borderRight: "1px solid #DDDDDD",
    height: "calc(100vh - 195px)",
  },
}));

const BasicComponent = (props) => {
  const classes = useStyles();
  const [numPages, setNumPages] = useState(null);
  const [pageNumber, setPageNumber] = useState(1);

  function onDocumentLoadSuccess({ numPages: nextNumPages }) {
    setNumPages(nextNumPages);
  }

  return (
    <Box className={classes.root}>
      <Header />
      <Grid container>
        <Grid item xs={8}>
          <Box className={classes.pdfArea}>
            <Document
              file={contractPdf}
              onLoadSuccess={onDocumentLoadSuccess}
              options={options}
            >
              <Page pageNumber={1} />
            </Document>
          </Box>
        </Grid>
        <Grid item xs={4}>
          <Box className={classes.inputArea}>User input</Box>
        </Grid>
      </Grid>
    </Box>
  );
};

export default BasicComponent;
</code>```

I checked the debug in development mode and it shows Uncaught SyntaxError: Unexpected token '<' in pdf.worker.js

Can anyone help me?
I appreciate your help. Thank you

答:
I wasted so much time that I decided to write an answer to this question to help anybody in my situation avoid the waste of time. The instructions as described in the github site for react-pdf do not work with react 17.02 CRA 5 and Webpack 5.6.6 regarding the pdf.worker.js worker.

As the site indicates without giving a clear solution,

```<code>import { Document, Page } from 'react-pdf/dist/esm/entry.webpack5';
</code>```

creates a heap out of memory error during compilation that is not fixed even by allocating 8 gigabytes of memory.

Using the standard instructions doesn't work either, creating an error that is dependent of the last web directory that was used in your react-router routes. This creates a weird bug, because sometimes it works and sometimes it doesn't.

The standard instructions say:

that you should add:

```<code>import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.min.js';
</code>```

when using the .min file, instead of the regular .js file, that gave me the idea of adding the following:

```<code>import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.js';
</code>```

But it didn't work either. To make it work I had to do the following:

copy pdf.worker.js and pdf.worker.js.map from pdfjs-dist/legacy/build to public directory (it also works if you copy from the build - not legacy directory)

and,

add to my code the following:

import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.js';

Yes, the '/' did it. Otherwise it'd go back to load my index.html from my /public directory.

Title: loading pdf using react-pdf

Body:
I am trying to display pdf using react-pdf in create-react-app application.
I followed the instructions but the pdf is not displayed.

import { makeStyles, Box, Grid } from "@material-ui/core";
import React, { useState } from "react";
import Header from "./header";
import contractPdf from "../../sample.pdf";
import { Document, Page } from "react-pdf";

const useStyles = makeStyles((theme) => ({
  root: {
    padding: "32px 24px 14px 24px",
  },
  pdfArea: {
    borderRight: "1px solid #DDDDDD",
    height: "calc(100vh - 195px)",
  },
}));

const BasicComponent = (props) => {
  const classes = useStyles();
  const [numPages, setNumPages] = useState(null);
  const [pageNumber, setPageNumber] = useState(1);

  function onDocumentLoadSuccess({ numPages: nextNumPages }) {
    setNumPages(nextNumPages);
  }

  return (
    <Box className={classes.root}>

      <Grid container>
        <Grid item xs={8}>
          <Box className={classes.pdfArea}>
            <Document
              file={contractPdf}
              onLoadSuccess={onDocumentLoadSuccess}
              options={options}
            >
              <Page pageNumber={1} />
            </Document>
          </Box>
        </Grid>
        <Grid item xs={4}>
          <Box className={classes.inputArea}>User input</Box>
        </Grid>
      </Grid>
    </Box>
  );
};

export default BasicComponent;

I checked the debug in development mode and it shows Uncaught SyntaxError: Unexpected token '<' in pdf.worker.js

Can anyone help me?
I appreciate your help. Thank you

Body:
I wasted so much time that I decided to write an answer to this question to help anybody in my situation avoid the waste of time. The instructions as described in the github site for react-pdf do not work with react 17.02 CRA 5 and Webpack 5.6.6 regarding the pdf.worker.js worker.

As the site indicates without giving a clear solution,

import { Document, Page } from 'react-pdf/dist/esm/entry.webpack5';

creates a heap out of memory error during compilation that is not fixed even by allocating 8 gigabytes of memory.

Using the standard instructions doesn't work either, creating an error that is dependent of the last web directory that was used in your react-router routes. This creates a weird bug, because sometimes it works and sometimes it doesn't.

The standard instructions say:

that you should add:

import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.min.js';

when using the .min file, instead of the regular .js file, that gave me the idea of adding the following:

import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.js';

But it didn't work either. To make it work I had to do the following:

copy pdf.worker.js and pdf.worker.js.map from pdfjs-dist/legacy/build to public directory (it also works if you copy from the build - not legacy directory)

and,

add to my code the following:

import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.js';

Yes, the '/' did it. Otherwise it'd go back to load my index.html from my /public directory.


问:
Is there any way I can print multiple elements each of an array twice on separate lines?
My code so far prints the whole array twice but I want to print each array element twice such that "Daudu" appears twice side by side etc and others like that on separate lines.</p>
```<code>let Smart = ["Daudu", "Emma", "Skodo", "John", "Jones", "Mike", "Sierra", "Oscar", "Alpha", "Bravo"];
console.log(Smart.join('\r\n'));
console.log(Smart.join('\r\n'));

</code>```

答:
Like that?

let Smart = ["Daudu", "Emma", "Skodo", "John", "Jones", "Mike", "Sierra", "Oscar", "Alpha", "Bravo"];
Smart.forEach(element => console.log(element, element));```

Body:
My code so far prints the whole array twice but I want to print each array element twice such that "Daudu" appears twice side by side etc and others like that on separate lines.

let Smart = ["Daudu", "Emma", "Skodo", "John", "Jones", "Mike", "Sierra", "Oscar", "Alpha", "Bravo"];
console.log(Smart.join('\r\n'));
console.log(Smart.join('\r\n'));


答:
What you're seeing is that it takes a finite amount of time for your app to react (excuse the pun) to the change that has occurred - specifically, it needs to re-render.

And yes, there is a nicer way - the waitFor function from testing-library/react:

```<code>import { screen, waitFor } from '@testing-library/react';

...

  it("changes value after selecting another field", async () => {

    ...

    fireEvent.change(field, { target: { value: "1" } });

    await waitFor(async () => {
      field = screen.getByLabelText("MySelectField");
      expect(field).toHaveValue("1");
    });
  }
</code>```

Note that the entire test body (i.e. after the test's name) has to be declared async in order to be able to await the new waitFor block.

Title: React/Jest Select element onChange values not updating

Body:
What you're seeing is that it takes a finite amount of time for your app to react (excuse the pun) to the change that has occurred - specifically, it needs to re-render.

And yes, there is a nicer way - the waitFor function from testing-library/react:

import { screen, waitFor } from '@testing-library/react';

...

  it("changes value after selecting another field", async () => {

    ...

    fireEvent.change(field, { target: { value: "1" } });

    await waitFor(async () => {
      field = screen.getByLabelText("MySelectField");
      expect(field).toHaveValue("1");
    });
  }

Note that the entire test body (i.e. after the test's name) has to be declared async in order to be able to await the new waitFor block.