问:
SQL Parameter as DBNull.Value is not working
I'm loading a select box list with a distinct list of values from our database table on CompanyName.

If the value in the column is NULL, I am adding '-- NULL --'

If the value in the column is empty or white space, I'm adding '-- EMPTY / WHITE SPACE --'

Otherwise, it will be the value in the column.

When I am trying to update the parameter to the property value DBNull.value is not working.

Here is my SQL statement:

```<code>SELECT Column1
      ,Column2
      ,[CreatedBy]
      ,RestOfColumns...
  FROM [dbo].[CompanyTable]
  where CompanyName = @DataVisParam
</code>```

Here is my code:

```<code>        public DataTable GetDataVisQueryParameterizedResults(string query, string parameterizedSelectedValue, string connectionString)
        {
            DataTable dt = new DataTable();

            using (SqlConnection conn = new SqlConnection(ConnectionUtilities.GetWebConfigConnectionString(connectionString)))
            {
                conn.Open();

                using (SqlDataAdapter sda = new SqlDataAdapter(query, conn))
                {
                    sda.SelectCommand.Parameters.Clear();
                    sda.SelectCommand.CommandType = CommandType.Text;
                    SqlParameter param = sda.SelectCommand.Parameters.Add(SharedUtilities.DataVisParameterPlaceholder(), SqlDbType.NVarChar);

                    /*if (parameterizedSelectedValue == SharedUtilities.DataVisParamSelectBoxValueIsNull())
                    {
                        param.Value = DBNull.Value;
                    }
                    else*/
                    if (parameterizedSelectedValue == SharedUtilities.DataVisParamValueSelectBoxIsEmptyOrWhiteSpace())
                    {
                        param.Value = string.Empty;
                    }
                    else
                    {
                        param.Value = parameterizedSelectedValue;
                    }

                    sda.Fill(dt);
                }
            }

            return dt;
        }
</code>```
```<code>        /// <summary>
        /// Data Vis parameterized query placeholder.
        /// </summary>
        /// <returns>Data vis parameterized placeholder text that will be used in the data vis query</returns>
        public static string DataVisParameterPlaceholder()
        {
            return "@DataVisParam";
        }

        /// <summary>
        /// Data vis parameter value is null.
        /// </summary>
        /// <returns>Parameter value for null on the select box</returns>
        public static string DataVisParamSelectBoxValueIsNull()
        {
            return "-- NULL --";
        }

        /// <summary>
        /// Data vis parameter value is empty or white space.
        /// </summary>
        /// <returns>Parameter value for empty or white space on the select box</returns>
        public static string DataVisParamValueSelectBoxIsEmptyOrWhiteSpace()
        {
            return "-- EMPTY / WHITE SPACE --";
        }
</code>```

I've tried DBNull.Value and not even setting it, but always 0 records are return for NULL. If I do the empty or white space, it works and 2 records are returned. Everything else is working fine.

Thoughts?

Main Question: Is there a way to NOT have to change the query from = @DataVisParam to IS NULL ?. I really do not want to have to change the query because then I have to make sure they put the text in perfect. I was hoping I could use the sda.SelectCommand.Parameters.Add() to check for NULL, but that appears it is not possible.

I've tried DBNull.Value in the commented out part of my code where this line is: param.Value = DBNull.Value; is set. It should enter this If statement.

Update: Yes, I know in SQL that you usually check IS Null for thanks in SSMS. Do I need to change my actual query from = @dataVisParam to Is Null? If I need to do that, doesn't that mess up the issue with SQL injection?

Update 2:

Appears I just need to replace the text = @DataVisParam with IS NULL when -- NULL -- is selected in the select box

答:
After discussing with a co-worker, since we are replacing the query to IS NULL from = @DataVisParam and we are NOT using user selection / input, then we can accept the fact that there is not a possibility of a security risk.

The one downside to this, is the user that inputs the query must make sure they put the parameter correctly so that we can match it and replace it with IS NULL

```<code>        public DataTable GetDataVisQueryParameterizedResults(string query, string parameterizedSelectedValue, string connectionString)
        {
            DataTable dt = new DataTable();

            using (SqlConnection conn = new SqlConnection(ConnectionUtilities.GetWebConfigConnectionString(connectionString)))
            {
                conn.Open();

                // update the query with IS NULL to check on null values
                if (parameterizedSelectedValue == SharedUtilities.DataVisParamSelectBoxValueIsNull())
                {
                    // replace the param with IS NULL -> replace for one space or two spaces (if there is a typo mistake with updating the query etc.)
#pragma warning disable CA1307 // Specify StringComparison
                    query = query.Replace("= @DataVisParam", "IS NULL").Replace("=  @DataVisParam", "IS NULL");
#pragma warning restore CA1307 // Specify StringComparison
                }

                using (SqlDataAdapter sda = new SqlDataAdapter(query, conn))
                {
                    // the parameterizedSelectedValue is not Null, query by the parameter and query will not be changed.
                    if (parameterizedSelectedValue != SharedUtilities.DataVisParamSelectBoxValueIsNull())
                    {
                        sda.SelectCommand.Parameters.Clear();
                        sda.SelectCommand.CommandType = CommandType.Text;
                        SqlParameter param = sda.SelectCommand.Parameters.Add(SharedUtilities.DataVisParameterPlaceholder(), SqlDbType.NVarChar);

                        if (parameterizedSelectedValue == SharedUtilities.DataVisParamValueSelectBoxIsEmptyOrWhiteSpace())
                        {
                            param.Value = string.Empty;
                        }
                        else
                        {
                            param.Value = parameterizedSelectedValue;
                        }
                    }

                    sda.Fill(dt);
                }
            }

            return dt;
        }
</code>```

Body:
I'm loading a select box list with a distinct list of values from our database table on CompanyName.

If the value in the column is NULL, I am adding '-- NULL --'

If the value in the column is empty or white space, I'm adding '-- EMPTY / WHITE SPACE --'

Otherwise, it will be the value in the column.

When I am trying to update the parameter to the property value DBNull.value is not working.

Here is my SQL statement:

SELECT Column1
      ,Column2
      ,[CreatedBy]
      ,RestOfColumns...
  FROM [dbo].[CompanyTable]
  where CompanyName = @DataVisParam

Here is my code:

        public DataTable GetDataVisQueryParameterizedResults(string query, string parameterizedSelectedValue, string connectionString)
        {
            DataTable dt = new DataTable();

            using (SqlConnection conn = new SqlConnection(ConnectionUtilities.GetWebConfigConnectionString(connectionString)))
            {
                conn.Open();

                using (SqlDataAdapter sda = new SqlDataAdapter(query, conn))
                {
                    sda.SelectCommand.Parameters.Clear();
                    sda.SelectCommand.CommandType = CommandType.Text;
                    SqlParameter param = sda.SelectCommand.Parameters.Add(SharedUtilities.DataVisParameterPlaceholder(), SqlDbType.NVarChar);

                    /*if (parameterizedSelectedValue == SharedUtilities.DataVisParamSelectBoxValueIsNull())
                    {
                        param.Value = DBNull.Value;
                    }
                    else*/
                    if (parameterizedSelectedValue == SharedUtilities.DataVisParamValueSelectBoxIsEmptyOrWhiteSpace())
                    {
                        param.Value = string.Empty;
                    }
                    else
                    {
                        param.Value = parameterizedSelectedValue;
                    }

                    sda.Fill(dt);
                }
            }

            return dt;
        }

        ///
        /// Data Vis parameterized query placeholder.
        ///
        /// <returns>Data vis parameterized placeholder text that will be used in the data vis query</returns>
        public static string DataVisParameterPlaceholder()
        {
            return "@DataVisParam";
        }

        ///
        /// Data vis parameter value is null.
        ///
        /// <returns>Parameter value for null on the select box</returns>
        public static string DataVisParamSelectBoxValueIsNull()
        {
            return "-- NULL --";
        }

        ///
        /// Data vis parameter value is empty or white space.
        ///
        /// <returns>Parameter value for empty or white space on the select box</returns>
        public static string DataVisParamValueSelectBoxIsEmptyOrWhiteSpace()
        {
            return "-- EMPTY / WHITE SPACE --";
        }

I've tried DBNull.Value and not even setting it, but always 0 records are return for NULL. If I do the empty or white space, it works and 2 records are returned. Everything else is working fine.

Thoughts?

Main Question: Is there a way to NOT have to change the query from = @DataVisParam to IS NULL ?. I really do not want to have to change the query because then I have to make sure they put the text in perfect. I was hoping I could use the sda.SelectCommand.Parameters.Add() to check for NULL, but that appears it is not possible.

I've tried DBNull.Value in the commented out part of my code where this line is: param.Value = DBNull.Value; is set. It should enter this If statement.

Update: Yes, I know in SQL that you usually check IS Null for thanks in SSMS. Do I need to change my actual query from = @dataVisParam to Is Null? If I need to do that, doesn't that mess up the issue with SQL injection?

Update 2:

Appears I just need to replace the text = @DataVisParam with IS NULL when -- NULL -- is selected in the select box

Body:
After discussing with a co-worker, since we are replacing the query to IS NULL from = @DataVisParam and we are NOT using user selection / input, then we can accept the fact that there is not a possibility of a security risk.

The one downside to this, is the user that inputs the query must make sure they put the parameter correctly so that we can match it and replace it with IS NULL

        public DataTable GetDataVisQueryParameterizedResults(string query, string parameterizedSelectedValue, string connectionString)
        {
            DataTable dt = new DataTable();

            using (SqlConnection conn = new SqlConnection(ConnectionUtilities.GetWebConfigConnectionString(connectionString)))
            {
                conn.Open();

                // update the query with IS NULL to check on null values
                if (parameterizedSelectedValue == SharedUtilities.DataVisParamSelectBoxValueIsNull())
                {
                    // replace the param with IS NULL -> replace for one space or two spaces (if there is a typo mistake with updating the query etc.)
#pragma warning disable CA1307 // Specify StringComparison
                    query = query.Replace("= @DataVisParam", "IS NULL").Replace("=  @DataVisParam", "IS NULL");
#pragma warning restore CA1307 // Specify StringComparison
                }

                using (SqlDataAdapter sda = new SqlDataAdapter(query, conn))
                {
                    // the parameterizedSelectedValue is not Null, query by the parameter and query will not be changed.
                    if (parameterizedSelectedValue != SharedUtilities.DataVisParamSelectBoxValueIsNull())
                    {
                        sda.SelectCommand.Parameters.Clear();
                        sda.SelectCommand.CommandType = CommandType.Text;
                        SqlParameter param = sda.SelectCommand.Parameters.Add(SharedUtilities.DataVisParameterPlaceholder(), SqlDbType.NVarChar);

                        if (parameterizedSelectedValue == SharedUtilities.DataVisParamValueSelectBoxIsEmptyOrWhiteSpace())
                        {
                            param.Value = string.Empty;
                        }
                        else
                        {
                            param.Value = parameterizedSelectedValue;
                        }
                    }

                    sda.Fill(dt);
                }
            }

            return dt;
        }


来源: stackexchange

问:
How to disable proxy settings for System Idle Process?
I'm using a proxy software named V2rayN and I found there are lots of error in it:

```<code>2022/02/10 10:35:25 tcp:127.0.0.1:11012 rejected  proxy/socks: unknown Socks version: 67
</code>```

I used "netstat -ano" to find the process:

```<code>TCP    127.0.0.1:10808        127.0.0.1:11012        TIME_WAIT       0
</code>```

Then I opened the task manager, find that the process PID: 0 is belongs to "System Idle Process", and I have no issue on another windows PC. Any idea on this? Is there any way to disable proxy settings for "System Idle Process"?

答:
The issue was resolved by using command which provided by Microsoft Community/ Answers:

```<code>netsh winsock reset
netsh winhttp reset proxy
netsh int ip reset
ipconfig /release
ipconfig /renew
ipconfig /flushdns
ipconfig /registerdns
</code>```

After the commands finished then restart the computer, the issue gone.

ContentLicense: CC BY-SA 4.0

Body:
I'm using a proxy software named V2rayN and I found there are lots of error in it:

2022/02/10 10:35:25 tcp:127.0.0.1:11012 rejected  proxy/socks: unknown Socks version: 67

I used "netstat -ano" to find the process:

TCP    127.0.0.1:10808        127.0.0.1:11012        TIME_WAIT       0

Then I opened the task manager, find that the process PID: 0 is belongs to "System Idle Process", and I have no issue on another windows PC. Any idea on this? Is there any way to disable proxy settings for "System Idle Process"?

Body:
The issue was resolved by using command which provided by Microsoft Community/ Answers:

netsh winsock reset
netsh winhttp reset proxy
netsh int ip reset
ipconfig /release
ipconfig /renew
ipconfig /flushdns
ipconfig /registerdns

After the commands finished then restart the computer, the issue gone.


问:
Tracking metrics using StatsD (via etsy) and Graphite, graphite graph doesn't seem to be graphing all the data
We have a metric that we increment every time a user performs a certain action on our website, but the graphs don't seem to be accurate.

So going off this hunch, we invested the updates.log of carbon and discovered that the action had happened over 4 thousand times today(using grep and wc), but according the Integral result of the graph it returned only 220ish.

What could be the cause of this?  Data is being reported to statsd using the statsd php library, and calling statsd::increment('metric'); and as stated above, the log confirms that 4,000+ updates to this key happened today.

We are using:

graphite 0.9.6 with statsD (etsy)

答:
After some research through the documentation, and some conversations with others, I've found the problem - and the solution.

The way the whisper file format is designed, it expect you (or your application) to publish updates no faster than the minimum interval in your storage-schemas.conf file.  This file is used to configure how much data retention you have at different time interval resolutions.

My storage-schemas.conf file was set with a minimum retention time of 1 minute.  The default StatsD daemon (from etsy) is designed to update to carbon (the graphite daemon) every 10 seconds.  The reason this is a problem is: over a 60 second period StatsD reports 6 times, each write overwrites the last one (in that 60 second interval, because you're updating faster than once per minute).  This produces really weird results on your graph because the last 10 seconds in a minute could be completely dead and report a 0 for the activity during that period, which results in completely nuking all of the data you had written for that minute.

To fix this, I had to re-configure my storage-schemas.conf file to store data at a maximum resolution of 10 seconds, so every update from StatsD would be saved in the whisper database without being overwritten.

Etsy published the storage-schemas.conf configuration that they were using for their installation of carbon, which looks like this:

```<code>[stats]
priority = 110
pattern = ^stats\..*
retentions = 10:2160,60:10080,600:262974
</code>```

This has a 10 second minimum retention time, and stores 6 hours worth of them.  However, due to my next problem, I extended the retention periods significantly.

As I let this data collect for a few days, I noticed that it still looked off (and was under reporting).  This was due to 2 problems.

StatsD (older versions) only reported an average number of events per second for each 10 second reporting period.  This means, if you incremented a key 100 times in 1 second and 0 times for the next 9 seconds, at the end of the 10th second statsD would report 10 to graphite, instead of 100.  (100/10 = 10).  This failed to report the total number of events for a 10 second period (obviously).

Newer versions of statsD fix this problem, as they introduced the stats_counts bucket, which logs the total # of events per metric for each 10 second period (so instead of reporting 10 in the previous example, it reports 100).

After I upgraded StatsD, I noticed that the last 6 hours of data looked great, but as I looked beyond the last 6 hours - things looked weird, and the next reason is why:

As graphite stores data, it moves data from high precision retention to lower precision retention.  This means, using the etsy storage-schemas.conf example, after 6 hours of 10 second precision, data was moved to 60 second (1 minute) precision.  In order to move 6 data points from 10s to 60s precision, graphite does an average of the 6 data points.  So it'd take the total value of the oldest 6 data points, and divide it by 6.  This gives an average # of events per 10 seconds for that 60 second period (and not the total # of events, which is what we care about specifically).

This is just how graphite is designed, and for some cases it might be useful, but in our case, it's not what we wanted.  To "fix" this problem, I increased our 10 second precision retention time to 60 days.  Beyond 60 days, I store the minutely and 10-minutely precisions, but they're essentially there for no reason, as that data isn't as useful to us.

I hope this helps someone, I know it annoyed me for a few days - and I know there isn't a huge community of people that are using this stack of software for this purpose, so it took a bit of research to really figure out what was going on and how to get a result that I wanted.

ContentLicense: CC BY-SA 3.0

Body:
After some research through the documentation, and some conversations with others, I've found the problem - and the solution.

The way the whisper file format is designed, it expect you (or your application) to publish updates no faster than the minimum interval in your storage-schemas.conf file.  This file is used to configure how much data retention you have at different time interval resolutions.

My storage-schemas.conf file was set with a minimum retention time of 1 minute.  The default StatsD daemon (from etsy) is designed to update to carbon (the graphite daemon) every 10 seconds.  The reason this is a problem is: over a 60 second period StatsD reports 6 times, each write overwrites the last one (in that 60 second interval, because you're updating faster than once per minute).  This produces really weird results on your graph because the last 10 seconds in a minute could be completely dead and report a 0 for the activity during that period, which results in completely nuking all of the data you had written for that minute.

To fix this, I had to re-configure my storage-schemas.conf file to store data at a maximum resolution of 10 seconds, so every update from StatsD would be saved in the whisper database without being overwritten.

Etsy published the storage-schemas.conf configuration that they were using for their installation of carbon, which looks like this:

[stats]
priority = 110
pattern = ^stats\..*
retentions = 10:2160,60:10080,600:262974

This has a 10 second minimum retention time, and stores 6 hours worth of them.  However, due to my next problem, I extended the retention periods significantly.

As I let this data collect for a few days, I noticed that it still looked off (and was under reporting).  This was due to 2 problems.

StatsD (older versions) only reported an average number of events per second for each 10 second reporting period.  This means, if you incremented a key 100 times in 1 second and 0 times for the next 9 seconds, at the end of the 10th second statsD would report 10 to graphite, instead of 100.  (100/10 = 10).  This failed to report the total number of events for a 10 second period (obviously).

Newer versions of statsD fix this problem, as they introduced the stats_counts bucket, which logs the total # of events per metric for each 10 second period (so instead of reporting 10 in the previous example, it reports 100).

After I upgraded StatsD, I noticed that the last 6 hours of data looked great, but as I looked beyond the last 6 hours - things looked weird, and the next reason is why:

As graphite stores data, it moves data from high precision retention to lower precision retention.  This means, using the etsy storage-schemas.conf example, after 6 hours of 10 second precision, data was moved to 60 second (1 minute) precision.  In order to move 6 data points from 10s to 60s precision, graphite does an average of the 6 data points.  So it'd take the total value of the oldest 6 data points, and divide it by 6.  This gives an average # of events per 10 seconds for that 60 second period (and not the total # of events, which is what we care about specifically).

This is just how graphite is designed, and for some cases it might be useful, but in our case, it's not what we wanted.  To "fix" this problem, I increased our 10 second precision retention time to 60 days.  Beyond 60 days, I store the minutely and 10-minutely precisions, but they're essentially there for no reason, as that data isn't as useful to us.

I hope this helps someone, I know it annoyed me for a few days - and I know there isn't a huge community of people that are using this stack of software for this purpose, so it took a bit of research to really figure out what was going on and how to get a result that I wanted.


问:
How to display images using props in react?
I'm new to React and I am following a tutorial. Right now I have the following code:

index.js:

```<code>import ReactDOM from "react-dom"
import App from "./App"

ReactDOM.render(
    <App />,
    document.getElementById("root")
)
</code>```

App.js:

```<code>import Contact from "./components/Contact"
export default function App() {
    return (
        <div className="contacts">
            <Contact
                img="../images/mr-whiskerson.png"
                name="Mr. Whiskerson"
                phone="(111) 111-1111"
                email="mr.whiskaz@catnap.meow"
            />
    )
}
</code>```

Contact.js:

```<code>import React from "react"
import ReactDOM from "react-dom"

export default function Contact(props) {
return (
        < div className="contact-card" >
            <img src={props.img} />
            <h3>{props.name}</h3>
            <div className="info-group">
                <img src="../images/phone-icon.png" />
                <p>{props.phone}</p>
            </div>
            <div className="info-group">
                <img src="../images/mail-icon.png" />
                <p>{props.email}</p>
            </div>
        </div >
    )
}
</code>```

All the files above are structured like this:

My problem is that I can't seem to display the images:

This is exactly how the tutorial has it, and I know the image directory is correct since if I hard code the directory for 'mr-whiskerson.png' on Contact component like this

..the image is displayed

So my question is, is there something I am missing? Do I need to use special syntax to display images that is not used to display paragraphs? I am honestly confused and I would really appreciate those who could help me understand. Thank you.

答:
If you pass a path to component as a string, your component receive that relative path, but relative to parent component. It won't work.

You should import path to image in import section in App.js:

```<code>import Contact from "./components/Contact"
import yourImage from "../images/mr-whiskerson.png";

export default function App() {
    return (
        <div className="contacts">
            <Contact
                img={yourImage}
                name="Mr. Whiskerson"
                phone="(111) 111-1111"
                email="mr.whiskaz@catnap.meow"
            />
    )
}
</code>```

in such a case your path will be passed in another components correctly as a pointer (in the level where it is should exist).

Leave Contact.js file as it is, it should work.

Body:
I'm new to React and I am following a tutorial. Right now I have the following code:

index.js:

import ReactDOM from "react-dom"
import App from "./App"

ReactDOM.render(
    <App />,
    document.getElementById("root")
)

App.js:

import Contact from "./components/Contact"
export default function App() {
    return (

            <Contact
                img="../images/mr-whiskerson.png"
                name="Mr. Whiskerson"
                phone="(111) 111-1111"
                email="mr.whiskaz@catnap.meow"
            />
    )
}

Contact.js:

import React from "react"
import ReactDOM from "react-dom"

export default function Contact(props) {
return (

{props.name}

{props.phone}

{props.email}

    )
}

All the files above are structured like this:

My problem is that I can't seem to display the images:

This is exactly how the tutorial has it, and I know the image directory is correct since if I hard code the directory for 'mr-whiskerson.png' on Contact component like this

..the image is displayed

So my question is, is there something I am missing? Do I need to use special syntax to display images that is not used to display paragraphs? I am honestly confused and I would really appreciate those who could help me understand. Thank you.

Body:
If you pass a path to component as a string, your component receive that relative path, but relative to parent component. It won't work.

You should import path to image in import section in App.js:

import Contact from "./components/Contact"
import yourImage from "../images/mr-whiskerson.png";

export default function App() {
    return (
        <div className="contacts">
            <Contact
                img={yourImage}
                name="Mr. Whiskerson"
                phone="(111) 111-1111"
                email="mr.whiskaz@catnap.meow"
            />
    )
}

in such a case your path will be passed in another components correctly as a pointer (in the level where it is should exist).

Leave Contact.js file as it is, it should work.


问:
Why does win.setPosition('center') move the window to top-left?
I have this code which I execute after toggling fullscreen back from fullscreen to windowed mode:

```<code>win.setPosition('center');
</code>```

The window consistently appears in top-left part of the screen -- not the middle.

The manual claims at http://docs.nwjs.io/en/latest/References/Window/#winsetpositionposition :

position {String} the position of the window. There are three valid positions: null or center or mouse
Move window to specified position. Currently only center is supported on all platforms, which will put window in the middle of the screen.

I tried "center" both quoted and unquoted, and even "centre" in case it was a typo in the manual.

For the record, the "mouse" value (which I don't want/need) also doesn't work; it seems to put the window in a random or semi-random place, far away from the cursor.

Windows 10. nwjs-v0.61.0-win-x64.

答:
Make sure you are creating the win variable like below:

```

You can use nw.Screen.screens to see dimensions of all the monitors if you wanted to move it to a different location.

https://nwjs.readthedocs.io/en/latest/References/Screen#screenscreens

https://nwjs.readthedocs.io/en/latest/References/Window/#winmovetox-y

https://nwjs.readthedocs.io/en/latest/References/Window/#winsetpositionposition

Body:
I have this code which I execute after toggling fullscreen back from fullscreen to windowed mode:

win.setPosition('center');

The window consistently appears in top-left part of the screen -- not the middle.

The manual claims at http://docs.nwjs.io/en/latest/References/Window/#winsetpositionposition :

position {String} the position of the window. There are three valid positions: null or center or mouse
Move window to specified position. Currently only center is supported on all platforms, which will put window in the middle of the screen.

I tried "center" both quoted and unquoted, and even "centre" in case it was a typo in the manual.

For the record, the "mouse" value (which I don't want/need) also doesn't work; it seems to put the window in a random or semi-random place, far away from the cursor.

Windows 10. nwjs-v0.61.0-win-x64.

Body:
Make sure you are creating the win variable like below:

<script>
const win = nw.Window.get();

// Move window to top left of screen
win.moveTo(0, 0);

// Move window to middle of screen
win.setPosition('center');

// Manually move window to middle of screen
const screen = nw.Screens.screen[0].bounds;
const x = Math.floor((screen.width - win.width) / 2);
const y = Math.floor((screen.height - win.height) / 2);
win.moveTo(x, y);
</script>

You can use nw.Screen.screens to see dimensions of all the monitors if you wanted to move it to a different location.

https://nwjs.readthedocs.io/en/latest/References/Screen#screenscreens

https://nwjs.readthedocs.io/en/latest/References/Window/#winmovetox-y

https://nwjs.readthedocs.io/en/latest/References/Window/#winsetpositionposition


问:
Check if a row exists in Azure Storage Table using the Azure.Data.Tables.TableClient
I'm using Azure.Data.Tables.TableClient (also looked at Azure.Data.Tables.TableServiceClient).

I want to check if a record exists in the Azure Table given a specific Partition Key and Row Key. Calling the TableClient.GetEntity<T> throws an exception if it gets 404 from the server rather than returning null.

I've searched on SO and there is one solution available but it uses the older CloudTable.

I've tried looking at the TableServiceClient options but so far haven't had any success finding a good solution that doesnt require catching the exception.

答:
You can probably use Query and specify your query as PartitionKey eq 'partition-key-value' and RowKey eq 'row-key-value'.

If the entity does not exist, you will receive an empty array back instead of error. If the entity exists, you will receive an array with just 1 entity.


问:
Why is export from index.tsx file undefined? (React + Typescript)
I have a simple Context Provider that I want to export as a npm package.

I created my npm package using create-react-library.

I have created an index.tsx file that will be accessible when importing this npm package from another project;
I am importing the Context Provider to this index.tsx, then exporting it.

When I try and run a test with the ContextProvider imported from index.tsx, the imported object is undefined (even though I can navigate to it in VS Code). However, when I import it directly from the source, it works fine. I will need to have it working from the index.tsx file in order to access it through the npm package.

Can anyone explain to me what I'm missing here?

src/index.tsx

import ErrorHandler from './contexts/ErrorHandlerContextProvider'

export { ErrorHandler }

// export { default as ErrorHandler } from './contexts/ErrorHandlerContextProvider' //<-- no luck

```
<p>src/index.test.tsx</p>
<pre class="lang-js prettyprint-override"><code>// import ErrorHandler from './contexts/ErrorHandlerContextProvider' // <-- this import works
import { ErrorHandler } from '.'

describe('ErrorHandlerContextProvider', () => {
  it('is truthy', () => {
    expect(ErrorHandler.ErrorHandlerContextProvider).toBeTruthy()
  })
})

</code>```

src/contexts/ErrorHandlerContextProvider.tsx

import React, { createContext, FC, useContext } from 'react'
import PropTypes from 'prop-types'

type errorHandlerContextType = {
  handleError: (error: Error, info: string) => Promise<void>
}

const ErrorHandlerContext = createContext<errorHandlerContextType | null>(null)

const useErrorHandlerContextProvider = () => {
  return useContext(ErrorHandlerContext)
}

const ErrorHandlerContextProvider: FC = ({ children }) => {

  const handleError = (error: Error, info: string): Promise<void> => {
    console.log('error', error)
    console.log('info', info)

    return Promise.reject(error)
  }

  return (
    <ErrorHandlerContext.Provider value={{ handleError }}>
      {children}
    </ErrorHandlerContext.Provider>
  )
}

ErrorHandlerContextProvider.propTypes = {
  children: PropTypes.node.isRequired
}

export default { ErrorHandlerContextProvider, useErrorHandlerContextProvider }

```
<p>/tsconfig.json</p>
<pre class="lang-json prettyprint-override"><code>{
  "compilerOptions": {
    "outDir": "dist",
    "module": "esnext",
    "lib": ["dom", "esnext"],
    "moduleResolution": "node",
    "jsx": "react",
    "sourceMap": true,
    "declaration": true,
    "esModuleInterop": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "allowSyntheticDefaultImports": true
  },
  "include": ["src"],
  "exclude": ["node_modules", "dist", "example"]
}

</code>```

npm run test

FAIL  src/index.test.tsx
● ErrorHandlerContextProvider › is truthy

```<code>TypeError: Cannot read property 'ErrorHandlerContextProvider' of undefined

  4 | describe('ErrorHandlerContextProvider', () => {
  5 |   it('is truthy', () => {
> 6 |     expect(ErrorHandler.ErrorHandlerContextProvider).toBeTruthy()
    |                         ^
  7 |   })
  8 | })
  9 |

  at Object.<anonymous> (src/index.test.tsx:6:25)
</code>```

答:
This seems really suspicious:

```<code>// src/index.test.tsx

// works
// import ErrorHandler from './contexts/ErrorHandlerContextProvider'

// does not work
import { ErrorHandler } from '.'
</code>```

Since the disabled import works, we know that the impl file's default export is working. But your index has no default export (which seems like bad manners for npm, but you do you). This tells me that either the test file is importing the impl wrongly, or the barrel file is. (I think it is unlikely that the index is exporting the impl wrongly.)

All your other imports, exports, and declarations seem correct on casual inspection.

So here is a grab-bag of ideas:

Try using the actual filename instead of just from '.'

The barrel has no React in it, so try renaming index.tsx to index.ts

Confirm that your test setup uses the same settings as the app code when it comes to default file extensions & default filenames

If none of those does it, try using your basic error-trapping skills to pinpoint the first broken link in the chain.

Add console.log("ErrorHandler", ErrorHandler) to your index after the import, then run the tests again and look for that log statement to confirm that the imported thing looks like you'd expect.

Try the same thing inside the test file, to examine what is imported from the barrel file.

The goal is to figure out at which step of the import chain things go awry.

Also: ES6 destructuring is not the same thing as ES6 named imports/exports, and you can't mix-and-match. So, I believe this code should not work:

// file1.js
export default { property: 'value' }

// file2.js
import { property } from './file1' // should fail
```

The reason is that file1 does not have named exports, it has only a default export, and the import statement in file2 is not permitted to destructure that object while importing it. The code in file2 should be read as: "import named export 'property' from file1" -- which will not work because file1 has no named exports.

In all honesty, I don't see a violation of this here, but it's something to keep in mind.

One final thought: don't organize your tests like this.

The test file for ErrorHandlerContextProvider should live in the same folder as the impl of the provider (or in a nested __tests folder, according to your preference). The proper job of that test suite is to test the actual impl of the provider.

If you even bother with an index.test.tsx, the proper job of that suite is just to prove that the public API of your npm module has the right shape. It has no business testing the actual functionality.

I would make this change even if it's not necessary to fix the problem. But, I'd hold off on making the change until after you have figured out precisely what the underlying problem is (and fixed it).

Body:
I have a simple Context Provider that I want to export as a npm package.

I created my npm package using create-react-library.

I have created an index.tsx file that will be accessible when importing this npm package from another project;
I am importing the Context Provider to this index.tsx, then exporting it.

When I try and run a test with the ContextProvider imported from index.tsx, the imported object is undefined (even though I can navigate to it in VS Code). However, when I import it directly from the source, it works fine. I will need to have it working from the index.tsx file in order to access it through the npm package.

Can anyone explain to me what I'm missing here?

src/index.tsx

import ErrorHandler from './contexts/ErrorHandlerContextProvider'

export { ErrorHandler }

// export { default as ErrorHandler } from './contexts/ErrorHandlerContextProvider' //<-- no luck

src/index.test.tsx

// import ErrorHandler from './contexts/ErrorHandlerContextProvider' // <-- this import works
import { ErrorHandler } from '.'

describe('ErrorHandlerContextProvider', () => {
  it('is truthy', () => {
    expect(ErrorHandler.ErrorHandlerContextProvider).toBeTruthy()
  })
})

src/contexts/ErrorHandlerContextProvider.tsx

import React, { createContext, FC, useContext } from 'react'
import PropTypes from 'prop-types'

type errorHandlerContextType = {
  handleError: (error: Error, info: string) => Promise<void>
}

const ErrorHandlerContext = createContext<errorHandlerContextType | null>(null)

const useErrorHandlerContextProvider = () => {
  return useContext(ErrorHandlerContext)
}

const ErrorHandlerContextProvider: FC = ({ children }) => {

  const handleError = (error: Error, info: string): Promise<void> => {
    console.log('error', error)
    console.log('info', info)

    return Promise.reject(error)
  }

  return (
    <ErrorHandlerContext.Provider value={{ handleError }}>
      {children}
    </ErrorHandlerContext.Provider>
  )
}

ErrorHandlerContextProvider.propTypes = {
  children: PropTypes.node.isRequired
}

export default { ErrorHandlerContextProvider, useErrorHandlerContextProvider }

/tsconfig.json

{
  "compilerOptions": {
    "outDir": "dist",
    "module": "esnext",
    "lib": ["dom", "esnext"],
    "moduleResolution": "node",
    "jsx": "react",
    "sourceMap": true,
    "declaration": true,
    "esModuleInterop": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "allowSyntheticDefaultImports": true
  },
  "include": ["src"],
  "exclude": ["node_modules", "dist", "example"]
}

npm run test

FAIL  src/index.test.tsx
● ErrorHandlerContextProvider › is truthy

TypeError: Cannot read property 'ErrorHandlerContextProvider' of undefined

  4 | describe('ErrorHandlerContextProvider', () => {
  5 |   it('is truthy', () => {
> 6 |     expect(ErrorHandler.ErrorHandlerContextProvider).toBeTruthy()
    |                         ^
  7 |   })
  8 | })
  9 |

  at Object.<anonymous> (src/index.test.tsx:6:25)

Body:
This seems really suspicious:

// src/index.test.tsx

// works
// import ErrorHandler from './contexts/ErrorHandlerContextProvider'

// does not work
import { ErrorHandler } from '.'

Since the disabled import works, we know that the impl file's default export is working. But your index has no default export (which seems like bad manners for npm, but you do you). This tells me that either the test file is importing the impl wrongly, or the barrel file is. (I think it is unlikely that the index is exporting the impl wrongly.)

All your other imports, exports, and declarations seem correct on casual inspection.

So here is a grab-bag of ideas:

Try using the actual filename instead of just from '.'

The barrel has no React in it, so try renaming index.tsx to index.ts

Confirm that your test setup uses the same settings as the app code when it comes to default file extensions & default filenames

If none of those does it, try using your basic error-trapping skills to pinpoint the first broken link in the chain.

Add console.log("ErrorHandler", ErrorHandler) to your index after the import, then run the tests again and look for that log statement to confirm that the imported thing looks like you'd expect.

Try the same thing inside the test file, to examine what is imported from the barrel file.

The goal is to figure out at which step of the import chain things go awry.

Also: ES6 destructuring is not the same thing as ES6 named imports/exports, and you can't mix-and-match. So, I believe this code should not work:

// file1.js
export default { property: 'value' }

// file2.js
import { property } from './file1' // should fail

The reason is that file1 does not have named exports, it has only a default export, and the import statement in file2 is not permitted to destructure that object while importing it. The code in file2 should be read as: "import named export 'property' from file1" -- which will not work because file1 has no named exports.

In all honesty, I don't see a violation of this here, but it's something to keep in mind.

One final thought: don't organize your tests like this.

The test file for ErrorHandlerContextProvider should live in the same folder as the impl of the provider (or in a nested __tests folder, according to your preference). The proper job of that test suite is to test the actual impl of the provider.

If you even bother with an index.test.tsx, the proper job of that suite is just to prove that the public API of your npm module has the right shape. It has no business testing the actual functionality.

I would make this change even if it's not necessary to fix the problem. But, I'd hold off on making the change until after you have figured out precisely what the underlying problem is (and fixed it).


问:
Move a forum from a directory to a subdomain
I'd like to move my old forum to a subdomain, but It doesn't work...

My forum is IPB 3.2 (invision power board), and at that point i've created my subdomain (not using CPanel, DNS propagated), and followed their instructions.

My homepage works fine and the new links are OK, but when I try to view a topic i get an error 500.

For example, when i try to view this page :
http://forum.domain.com/my-topic-t1.html

I got an error, and here is what's in my error log:

```<code>//my-topic-t1.html HTTP/1.1" 500 403 "http://forum.domain.com/
</code>```

I guess it's a mod rewrite problem, but i can't figure out what's wrong.

Here is my .htaccess file (located in my /forum/ folder)

```<code>RewriteBase /forum/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /forum/index.php [L]
</code>```

I've been told it may be an issue with the rewrite rule and the way the sub-domain is configured/being served. But how to put an exception in for the sub-domain ?

I'm on a shared server running Apache2.

Thanks !

答:
Because subdomain already points into /forum/ folder, you need to remove that part from the rewrite rule target (as well as get rid of the RewriteBase).

Try this line instead:

```<code>RewriteRule . /index.php [L]
</code>```

Body:
I'd like to move my old forum to a subdomain, but It doesn't work...

My forum is IPB 3.2 (invision power board), and at that point i've created my subdomain (not using CPanel, DNS propagated), and followed their instructions.

My homepage works fine and the new links are OK, but when I try to view a topic i get an error 500.

For example, when i try to view this page :
http://forum.domain.com/my-topic-t1.html

I got an error, and here is what's in my error log:

//my-topic-t1.html HTTP/1.1" 500 403 "http://forum.domain.com/

I guess it's a mod rewrite problem, but i can't figure out what's wrong.

Here is my .htaccess file (located in my /forum/ folder)

RewriteBase /forum/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /forum/index.php [L]

I've been told it may be an issue with the rewrite rule and the way the sub-domain is configured/being served. But how to put an exception in for the sub-domain ?

I'm on a shared server running Apache2.

Thanks !

Body:
Because subdomain already points into /forum/ folder, you need to remove that part from the rewrite rule target (as well as get rid of the RewriteBase).

Try this line instead:

RewriteRule . /index.php [L]


问:
Nodejs: how can I wait for pipe and createWriteStream to finish before executing next lines?
I'm new to Nodejs.  I am saving a zip file from S3 bucket to EC2 instance which is hosting the nodejs service, and then I am decompressing the zip file locally in the file system in EC2:

```<code>
  const s3Item = await S3.getFile(objectBucket, objectKey);
  let stream = s3Item.Body.pipe(fs.createWriteStream(sourceFilePath, { mode: 0o777 }));
  stream.on('finish', () => {
    logger.info(` pipe done `);
  });

  logger.info(`start decompressing...`);
  await decompressArchive(sourceFilePath, targetDirectory_decompressed);

  ... a lot of code...

</code>```

However, start decompressing... is always printed before pipe done is printed.

How can I make these two steps synchronous such that we wait until pipe done, and then start to decompress?

I want to use async/await , since I simply cannot put all the rest of the code in the stream.on('finish', () => {}); block, since there are too much code and they all rely on the stream being finished.

I have searched for related answers (there are many of them), but I still cannot get it working.

答:
Well, streams are event driven.  You can put the code you want to run after the stream is done inside the finish event handler:

```<code>  const s3Item = await S3.getFile(objectBucket, objectKey);
  let stream = s3Item.Body.pipe(fs.createWriteStream(sourceFilePath, { mode: 0o777 }));
  stream.on('finish', async () => {
    logger.info(` pipe done `);
    logger.info(`start decompressing...`);
    await decompressArchive(sourceFilePath, targetDirectory_decompressed);
  });
</code>```

Or, you can wrap the finish event in a promise and await that:

```<code>  const s3Item = await S3.getFile(objectBucket, objectKey);
  let stream = s3Item.Body.pipe(fs.createWriteStream(sourceFilePath, { mode: 0o777 }));

  await new Promise((resolve, reject) => {
    stream.on('finish', () => {
      logger.info(` pipe done `);
      resolve();
    }).on('error', err => {
      reject(err);
    });
  });

  logger.info(`start decompressing...`);
  await decompressArchive(sourceFilePath, targetDirectory_decompressed);
</code>```

FYI, recent versions of nodejs have a once() function in the events module that makes this a bit easier:

```<code>  const { once } = require('events');

  const s3Item = await S3.getFile(objectBucket, objectKey);
  let stream = s3Item.Body.pipe(fs.createWriteStream(sourceFilePath, { mode: 0o777 }));

  await once(stream, 'finish');
  logger.info(` pipe done `);

  logger.info(`start decompressing...`);
  await decompressArchive(sourceFilePath, targetDirectory_decompressed);
</code>```

Or, you can use a promisified version of pipeline() instead of .pipe().  Lots of ways to do this.

Body:
I'm new to Nodejs.  I am saving a zip file from S3 bucket to EC2 instance which is hosting the nodejs service, and then I am decompressing the zip file locally in the file system in EC2:

  const s3Item = await S3.getFile(objectBucket, objectKey);
  let stream = s3Item.Body.pipe(fs.createWriteStream(sourceFilePath, { mode: 0o777 }));
  stream.on('finish', () => {
    logger.info(` pipe done `);
  });

  logger.info(`start decompressing...`);
  await decompressArchive(sourceFilePath, targetDirectory_decompressed);

  ... a lot of code...

However, start decompressing... is always printed before pipe done is printed.

How can I make these two steps synchronous such that we wait until pipe done, and then start to decompress?

I want to use async/await , since I simply cannot put all the rest of the code in the stream.on('finish', () => {}); block, since there are too much code and they all rely on the stream being finished.

I have searched for related answers (there are many of them), but I still cannot get it working.

Body:
Well, streams are event driven.  You can put the code you want to run after the stream is done inside the finish event handler:

  const s3Item = await S3.getFile(objectBucket, objectKey);
  let stream = s3Item.Body.pipe(fs.createWriteStream(sourceFilePath, { mode: 0o777 }));
  stream.on('finish', async () => {
    logger.info(` pipe done `);
    logger.info(`start decompressing...`);
    await decompressArchive(sourceFilePath, targetDirectory_decompressed);
  });

Or, you can wrap the finish event in a promise and await that:

  const s3Item = await S3.getFile(objectBucket, objectKey);
  let stream = s3Item.Body.pipe(fs.createWriteStream(sourceFilePath, { mode: 0o777 }));

  await new Promise((resolve, reject) => {
    stream.on('finish', () => {
      logger.info(` pipe done `);
      resolve();
    }).on('error', err => {
      reject(err);
    });
  });

  logger.info(`start decompressing...`);
  await decompressArchive(sourceFilePath, targetDirectory_decompressed);

FYI, recent versions of nodejs have a once() function in the events module that makes this a bit easier:

  const { once } = require('events');

  const s3Item = await S3.getFile(objectBucket, objectKey);
  let stream = s3Item.Body.pipe(fs.createWriteStream(sourceFilePath, { mode: 0o777 }));

  await once(stream, 'finish');
  logger.info(` pipe done `);

  logger.info(`start decompressing...`);
  await decompressArchive(sourceFilePath, targetDirectory_decompressed);

Or, you can use a promisified version of pipeline() instead of .pipe().  Lots of ways to do this.


问:
Creating a method that merges 2 arrays into one sorted array in ascending order in Java
For part of an assignment, I have to create a method that merges 2 arrays into one sorted array in ascending order. I have most of it done, but I am getting a bug that replaces the last element in the array with 0. Has anyone ever run into this problem and know a solution? Heres my code:

```<code>     public static OrderedArray merge(OrderedArray src1, OrderedArray src2) {

         int numLength1 = src1.array.length;
         int numLength2 = src2.array.length;

         //combined array lengths
         int myLength = (numLength1 + numLength2);
        // System.out.println(myLength);
         OrderedArray mergedArr = new OrderedArray(myLength);

         //new array
         long[] merged = new long[myLength];

         //loop to sort array
         int i = 0;
         int j = 0;
         int k = 0;
         while (k < src1.array.length + src2.array.length - 1) {
             if(src1.array[i] < src2.array[j]) {
                 merged[k] = src1.array[i];
             i++;
             }
             else {
                merged[k] = src2.array[j];
             j++;

             }
            k++;

         }

         //loop to print result
         for(int x = 0; x < myLength; x++) {
             System.out.println(merged[x]);
         }
         return mergedArr;
     }

    public static void main(String[] args) {
        int maxSize = 100; // array size
//      OrderedArray arr; // reference to array
        OrderedArray src1 = new OrderedArray(4);
        OrderedArray src2 = new OrderedArray(5);

//      arr = new OrderedArray(maxSize); // create the array

        src1.insert(1);  //insert src1
        src1.insert(17);
        src1.insert(42);
        src1.insert(55);

        src2.insert(8); //insert src2
        src2.insert(13);
        src2.insert(21);
        src2.insert(32);
        src2.insert(69);

        OrderedArray myArray = merge(src1, src2);

</code>```

This is my expected output:

```<code>1
8
13
17
21
32
42
55
69
</code>```

and this is my current output:

```<code>1
8
13
17
21
32
42
55
0
</code>```

答:
To answer your main question, the length of your target array is src1.array.length + src2.array.length, so your loop condition should be one of:

while (k < src1.array.length + src2.array.length) {

while (k <= src1.array.length + src2.array.length - 1) {

Otherwise, you will never set a value for the last element, where k == src1.array.length + src2.array.length - 1.

But depending on how comprehensively you test the code, you may then find you have a bigger problem: ArrayIndexOutOfBoundsException. Before trying to use any array index, such as src1.array[i], you need to be sure it is valid. This condition:

```<code>if(src1.array[i] < src2.array[j]) {
</code>```

does not verify that i is a valid index of src1.array or that j is a valid index of src2.array. When one array has been fully consumed, checking this condition will cause your program to fail. You can see this with input arrays like { 1, 2 } & { 1 }.

This revision of the code does the proper bounds checks:

```<code>if (i >= src1.array.length) {
    // src1 is fully consumed
    merged[k] = src2.array[j];
    j++;
} else if (j >= src2.array.length || src1.array[i] < src2.array[j]) {
    // src2 is fully consumed OR src1's next is less than src2's next
    merged[k] = src1.array[i];
    i++;
} else {
    merged[k] = src2.array[j];
    j++;
}
</code>```

Note that we do not need to check j in the first condition because i >= src1.array.length implies that j is a safe value, due to your loop's condition and the math of how you are incrementing those variables:

k == i + j due to parity between k's incrementing and i & j's mutually exclusive incrementing

k < src1.array.length + src2.array.length due to the loop condition

Therefore i + j < src1.array.length + src2.array.length

If both i >= src1.array.length and j >= src2.array.length then i + j >= src1.array.length + src2.array.length, violating the facts above.

A couple other points and things to think about:

Be consistent with how you refer to data. If you have variables, use them. Either use numLength1 & numLength2 or use src1.length & src2.length. Either use myLength or use src1.array.length + src2.array.length.

Should a merge method really output its own results, or should the code that called the method (main) handle all the input & output?

Is the OrderedArray class safe to trust as "ordered", and is it doing its job properly, if you can directly access its internal data like src1.array and make modifications to the array?

Body:
For part of an assignment, I have to create a method that merges 2 arrays into one sorted array in ascending order. I have most of it done, but I am getting a bug that replaces the last element in the array with 0. Has anyone ever run into this problem and know a solution? Heres my code:

     public static OrderedArray merge(OrderedArray src1, OrderedArray src2) {

         int numLength1 = src1.array.length;
         int numLength2 = src2.array.length;

         //combined array lengths
         int myLength = (numLength1 + numLength2);
        // System.out.println(myLength);
         OrderedArray mergedArr = new OrderedArray(myLength);

         //new array
         long[] merged = new long[myLength];

         //loop to sort array
         int i = 0;
         int j = 0;
         int k = 0;
         while (k < src1.array.length + src2.array.length - 1) {
             if(src1.array[i] < src2.array[j]) {
                 merged[k] = src1.array[i];
             i++;
             }
             else {
                merged[k] = src2.array[j];
             j++;

             }
            k++;

         }

         //loop to print result
         for(int x = 0; x < myLength; x++) {
             System.out.println(merged[x]);
         }
         return mergedArr;
     }

    public static void main(String[] args) {
        int maxSize = 100; // array size
//      OrderedArray arr; // reference to array
        OrderedArray src1 = new OrderedArray(4);
        OrderedArray src2 = new OrderedArray(5);

//      arr = new OrderedArray(maxSize); // create the array

        src1.insert(1);  //insert src1
        src1.insert(17);
        src1.insert(42);
        src1.insert(55);

        src2.insert(8); //insert src2
        src2.insert(13);
        src2.insert(21);
        src2.insert(32);
        src2.insert(69);

        OrderedArray myArray = merge(src1, src2);

This is my expected output:

1
8
13
17
21
32
42
55
69

and this is my current output:

1
8
13
17
21
32
42
55
0

Body:
To answer your main question, the length of your target array is src1.array.length + src2.array.length, so your loop condition should be one of:

while (k < src1.array.length + src2.array.length) {

while (k <= src1.array.length + src2.array.length - 1) {

Otherwise, you will never set a value for the last element, where k == src1.array.length + src2.array.length - 1.

But depending on how comprehensively you test the code, you may then find you have a bigger problem: ArrayIndexOutOfBoundsException. Before trying to use any array index, such as src1.array[i], you need to be sure it is valid. This condition:

if(src1.array[i] < src2.array[j]) {

does not verify that i is a valid index of src1.array or that j is a valid index of src2.array. When one array has been fully consumed, checking this condition will cause your program to fail. You can see this with input arrays like { 1, 2 } & { 1 }.

This revision of the code does the proper bounds checks:

if (i >= src1.array.length) {
    // src1 is fully consumed
    merged[k] = src2.array[j];
    j++;
} else if (j >= src2.array.length || src1.array[i] < src2.array[j]) {
    // src2 is fully consumed OR src1's next is less than src2's next
    merged[k] = src1.array[i];
    i++;
} else {
    merged[k] = src2.array[j];
    j++;
}

Note that we do not need to check j in the first condition because i >= src1.array.length implies that j is a safe value, due to your loop's condition and the math of how you are incrementing those variables:

k == i + j due to parity between k's incrementing and i & j's mutually exclusive incrementing

k < src1.array.length + src2.array.length due to the loop condition

Therefore i + j < src1.array.length + src2.array.length

If both i >= src1.array.length and j >= src2.array.length then i + j >= src1.array.length + src2.array.length, violating the facts above.

A couple other points and things to think about:

Be consistent with how you refer to data. If you have variables, use them. Either use numLength1 & numLength2 or use src1.length & src2.length. Either use myLength or use src1.array.length + src2.array.length.

Should a merge method really output its own results, or should the code that called the method (main) handle all the input & output?

Is the OrderedArray class safe to trust as "ordered", and is it doing its job properly, if you can directly access its internal data like src1.array and make modifications to the array?


问:
Convert these nested functions from arrow to old style and what happens with variables
I'm trying to find items from one list that are not in items in a second list. Almost by dumb luck I got it to work, but only with arrow functions. For me normal functions are easier to read so I tried converting it and the result isn't what I expect.

data:

```<code>const arr1 = [
    {
        "key": 1,
        "val": "one"
    },
    {
        "key": 2,
        "val": "two"
    },
    {
        "key": 3,
        "val": "three"
    }
]

const arr2 = [
    {
        "key": 3,
        "val": "three"
    },
    {
        "key": 4,
        "val": "four"
    },
    {
        "key": 1,
        "val": "one"
    }
]
</code>```

version 1

```<code>arr1.filter((element) => arr2.findIndex((innerElement) => element.key === innerElement.key) === -1);
// produces object with key 2
</code>```

version 2

```<code>arr1.filter(function(element) {
    return arr2.findIndex(function(innerElement) {
      element.key === innerElement.key === -1
    })
}) // produces all three objects in arr1
</code>```

To make the correct one more terse I removed extra parentheses and it still works:

```<code>arr1.filter(element => arr2.findIndex(innerElement => element.key === innerElement.key) === -1);
</code>```

I'm missing a key aspect here. I get that each item in arr1 is passed to a function and that inner function in turn passes its result to another function and the expression has access to both sets of arguments and gets executed. But I think I have the wrong mental model about the order or something.

Can someone explain what is happening in each step and how to think about it?  And how do I make it into a normal function?

I'll be dealing with a lot of nested structures and I feel this is a weak area that I'd like to get better in.

Thank you

答:
You need to return the value of the comparison. And the === -1 test must be with the result of findIndex(), not inside its callback.

```<code>arr1.filter(function(element) {
    return arr2.findIndex(function(innerElement) {
      return element.key === innerElement.key;
    }) === -1;
});
</code>```

This can be simplified with the some() method.

```<code>arr1.filter(function(element) {
  return !arr2.some(function(innerElement) {
    return element.key === innerElement.key
  })
})
</code>```

Body:
I'm trying to find items from one list that are not in items in a second list. Almost by dumb luck I got it to work, but only with arrow functions. For me normal functions are easier to read so I tried converting it and the result isn't what I expect.

data:

const arr1 = [
    {
        "key": 1,
        "val": "one"
    },
    {
        "key": 2,
        "val": "two"
    },
    {
        "key": 3,
        "val": "three"
    }
]

const arr2 = [
    {
        "key": 3,
        "val": "three"
    },
    {
        "key": 4,
        "val": "four"
    },
    {
        "key": 1,
        "val": "one"
    }
]

version 1

arr1.filter((element) => arr2.findIndex((innerElement) => element.key === innerElement.key) === -1);
// produces object with key 2

version 2

arr1.filter(function(element) {
    return arr2.findIndex(function(innerElement) {
      element.key === innerElement.key === -1
    })
}) // produces all three objects in arr1

To make the correct one more terse I removed extra parentheses and it still works:

arr1.filter(element => arr2.findIndex(innerElement => element.key === innerElement.key) === -1);

I'm missing a key aspect here. I get that each item in arr1 is passed to a function and that inner function in turn passes its result to another function and the expression has access to both sets of arguments and gets executed. But I think I have the wrong mental model about the order or something.

Can someone explain what is happening in each step and how to think about it?  And how do I make it into a normal function?

I'll be dealing with a lot of nested structures and I feel this is a weak area that I'd like to get better in.

Thank you

Body:
You need to return the value of the comparison. And the === -1 test must be with the result of findIndex(), not inside its callback.

arr1.filter(function(element) {
    return arr2.findIndex(function(innerElement) {
      return element.key === innerElement.key;
    }) === -1;
});

This can be simplified with the some() method.

arr1.filter(function(element) {
  return !arr2.some(function(innerElement) {
    return element.key === innerElement.key
  })
})


问:
Ember - Loading an URL dynamically for button
New to ember, I wonder what is the best way to go about this:

```<code>component.js
import Component from '@ember/component';
import { inject as service } from '@ember/service';

export default Component.extend({
  ajax: service(),

  url: '',

  async fetchUrl() {
    try {
      let result = await this.ajax.request(
        `api/urlgenerator`
      );
      this.url = result.link;
    } catch (err) {
      this.errorHandler.handle(err);
    }
  },

  init() {
    this._super(...arguments);
    this.fetchUrl();
  },
});

</code>```

and my template

```<code>{{#card/banner}}
  <Banner
    @text="Template Button"
    @action={{hash
      text="Enable Launcher"
      onAction=(track-action
        (route-action "openUrl" this.url)
      )
    }}
  />
{{/card/banner}}

</code>```

openUrl is simple a global method responsible for opening an external URL

--

Not too sure if this is the right way to go about it, right now it is not working, since maybe due to ember component lifecycle, the variable gets rendered with the initial value only (empty '')

However, If I hardcode the url for example, it works fine.

Can someone give me some advice on it?

答: In case it helps someone, I used this approach The Guide to Promises in Computed Properties</p>

Body:
New to ember, I wonder what is the best way to go about this:

component.js
import Component from '@ember/component';
import { inject as service } from '@ember/service';

export default Component.extend({
  ajax: service(),

  url: '',

  async fetchUrl() {
    try {
      let result = await this.ajax.request(
        `api/urlgenerator`
      );
      this.url = result.link;
    } catch (err) {
      this.errorHandler.handle(err);
    }
  },

  init() {
    this._super(...arguments);
    this.fetchUrl();
  },
});

and my template

{{#card/banner}}
  <Banner
    @text="Template Button"
    @action={{hash
      text="Enable Launcher"
      onAction=(track-action
        (route-action "openUrl" this.url)
      )
    }}
  />
{{/card/banner}}

openUrl is simple a global method responsible for opening an external URL

--

Not too sure if this is the right way to go about it, right now it is not working, since maybe due to ember component lifecycle, the variable gets rendered with the initial value only (empty '')

However, If I hardcode the url for example, it works fine.

Can someone give me some advice on it?


问:
How to trigger Azure function with flutter
I created an azure function in c # and set up an HTTP trigger. I'm interested in how to call this function from the flutter application. I don't need to transfer any special data because everything is already in the link I use to call the function.I’ve created a simplified view of the function to demonstrate what I want.

https://functionapp220220124204147.azurewebsites.net/api/Quercus?status=Off

When it calls this function all it needs to do is change the value of the variable from on to off

I know this is not the correct way to make a function and I should not have such variables, but this is just a simplified version

答:
Here is a workaround given by Vikash Kumar in the Medium article regarding How to call Azure Functions API through Flutter App Code:

Created Wordle Website which has a list of legit words and allows you to input a word only from that list where we validate if an input word is a legit English word.

First, he created the Azure Cosmos DB > container in it > added a few dates, word pairs like:

Created the Azure Functions which has input binding with the Cosmos DB and gets a list of stored words on every request.

This functionality is broken into 3 segments:

Validate the input word (not null, same length, convert to uppercase both)

Check if both words are the same

Status of each letter in the input word.

The deployed function app API will be in this format: https://wordle-api.azurewebsites.net/api/CheckWord?word=

Also created the flutter in the composition of the word_field component which creates an input widget that accepts a 5 letter word in 5 boxes (1 each) which is similar to the OTP field.

And the home component builds a scaffold and puts together a page to accept 6 attempts for words.

The _checkWord handler calls the wordle-api, gets the color code, and updates the components accordingly.

Calling the Function API in the above handler and writing the code about response status and the user-defined message to the response.

var uri = Uri.https('wordle-api.azurewebsites.net', '/api/CheckWord', params);

For Complete Code, Please refer this article.


问:
Gemfire start pulse error - Running desktop applications is not supported on Linux
I have installed GemFire 9.0.3 in a UNIX "Red Hat Enterprise Linux Server release 6.6 (Santiago)" environment.

I am unable to start the pulse here. Please help, with other alternatives! ( Reference - http://gemfire90.docs.pivotal.io/gemfire/getting_started/15_minute_quickstart_gfsh.html)

[bin]# ./gfsh
    _________________________     __
   / _____/ ______/ ______/ /____/ /
  / /  / /_  /_____  / _____  /
 / /__/ / ____/  _____/ / /    / /
/______/_/      /______//    //

9.0.3

Monitor and Manage Pivotal GemFire

gfsh>start pulse
Running desktop applications is not supported on Linux.

答: You could also use Gemfire GUI (open source at https://github.com/ldom22/GGGUI)</p>


问:
Windows Phone 7, IsolatedStorageSettings "Remove()" not working, a bug?
I'm using IsolatedStorageSettings class in my Windows Phone 7 project as a key-value store to remember user preferences and login credentials in my app.

The problem is, when I invoke Remove(string) method with the key and then I use Save() method to persist changes. Remove() method returns true, that means value is deleted. But when I try to get the value next time, I see that it is still there and not deleted.

Here's the code I use for deletion:

```<code>if (isolatedStore.Contains(key))
{
    isolatedStore[key] = null;
}

bool del = isolatedStore.Remove(key);
isolatedStore.Save();
</code>```

Here's how I get isolatedStorage instance:

```<code>private IsolatedStorageSettings isolatedStore =
     IsolatedStorageSettings.ApplicationSettings;
</code>```

Where do you think the problem is?

答:
I found this block in the following link.  I haven't tried to remove a key the way you're doing, though.  http://social.msdn.microsoft.com/Forums/en/windowsphone7series/thread/17514c94-1f59-47b4-bb78-99694bfbb6b2</p>

```<code>public static void DeleteObject(string key)
{
  IsolatedStorageSettings.ApplicationSettings.Remove(key);
}
</code>```

Body:
I'm using IsolatedStorageSettings class in my Windows Phone 7 project as a key-value store to remember user preferences and login credentials in my app.

The problem is, when I invoke Remove(string) method with the key and then I use Save() method to persist changes. Remove() method returns true, that means value is deleted. But when I try to get the value next time, I see that it is still there and not deleted.

Here's the code I use for deletion:

if (isolatedStore.Contains(key))
{
    isolatedStore[key] = null;
}

bool del = isolatedStore.Remove(key);
isolatedStore.Save();

Here's how I get isolatedStorage instance:

private IsolatedStorageSettings isolatedStore =
     IsolatedStorageSettings.ApplicationSettings;

Where do you think the problem is?

Body:
I found this block in the following link.  I haven't tried to remove a key the way you're doing, though.  http://social.msdn.microsoft.com/Forums/en/windowsphone7series/thread/17514c94-1f59-47b4-bb78-99694bfbb6b2

public static void DeleteObject(string key)
{
  IsolatedStorageSettings.ApplicationSettings.Remove(key);
}


问:
IntelliJ won't recognize some imports from gradle project
I am working on a Gradle project in IntelliJ and some packages are not recognized by IntelliJ. When I go to Project Structure -> Modules -> <my module> -> Dependencies, the jar file that contains these packages is there. (I've examined the jar file with jar tfv <file> to make sure that the classes in question are in the file.)

The classes in question are in red and when hovering over them, I get errors like "Cannot resolve symbol 'somepackagename'" or "Cannot resolve symbol 'SomeClassName'".

However, the gradle project compiles just fine from the command line.

I've tried all the existing suggestions I could find, but so far none have helped. Primarily, I've already tried:

Deleting the .idea folder and re-importing

Reimporting the project from the root build.gradle file

Clicking on the "Refresh all gradle projects" button

Upgrading IntelliJ

Clicking on "Invalidate Caches and Restart"

What can I do to get IntelliJ to recognize the packages in these jar files?

答:
The issue still occurs on IntelliJ IDEA 2021.3.2 (Community Edition). Invalidate Caches/Restart did not work, this solved it:

Delete the .idea folder

Close and open the project


问:
I am trying to remove items from an array of objects used as projectiles for players or enemies to shoot in games made with JavaScript
I am practicing with making players and enemies for 2d games using vanilla JavaScript and HTML Canvas. The only problem I have is that I am trying to remove the projectiles from the playerProjectiles array when the projectile goes off of the screen. This is so that the game doesn't have to keep track of a bunch of projectiles that are not even on the screen, so the game will run smoother. I have tried sifting through the array using .forEach and splicing the current projectile that it is looping through as long as that projectile is off the screen. However, using this method, if there are multiple projectiles on the screen and one of them goes off of the screen, the entire array gets spliced and all of the projectiles are removed. What am I doing wrong here? Also, would it be better to put the code for the different mechanics of the projectiles in a different function? Etc. moving the projectiles up when they are shot out, actually drawing them to the screen, splicing them from the array when they go off the screen.

function populatePlayerProjectilesArray() {
    playerProjectiles.forEach(projectile => {
        projectile.draw();
        projectile.y -= pdy;
        if(projectile.y <= 0 - projectile.rad) {
            playerProjectiles.splice(projectile)
        }
    })
}```

答:
Array.prototype.splice()

Examples:

```<code>splice(start)
splice(start, deleteCount)
</code>```

deleteCount Optional An integer indicating the number of elements in the array to remove from start. If deleteCount is omitted [...], then all the elements from start to the end of the array will be deleted.

I think you want to change your splice statement to:

```<code>playerProjectiles.splice(projectile, 1)
</code>```

Body:
Array.prototype.splice()

Examples:

splice(start)
splice(start, deleteCount)

deleteCount Optional An integer indicating the number of elements in the array to remove from start. If deleteCount is omitted [...], then all the elements from start to the end of the array will be deleted.

I think you want to change your splice statement to:

playerProjectiles.splice(projectile, 1)


问:
How to selectively clone a git repository
I am new to Git. I want to clone a large remote repository lets say xyzcodebase. The structure of repo is like I have src folders for different functional areas as shown below.

```<code>xyzcodebase
|
|__ Func area 1
|
|__ Func area 2
</code>```

I work on Functional area 2 hence while cloning I don't want code from Functional area 1 (large size)  which will save lots of my time. So that after cloning I will have only Functional area 2 source code on my local repository.

Is there a way to accomplish such selective cloning of git repository?

Thanks in advance for your help

答:
No, there is no way to only clone one directory. Git stores history as changes to whole repository instead of storing only subtrees as SVN.

If your project contains multiple functionalities, then maybe it would be better to split it into some sub-projects, with different repositories, and then include other repositories as submodules in master project. But it depends how your project is organized.

Body:
I am new to Git. I want to clone a large remote repository lets say xyzcodebase. The structure of repo is like I have src folders for different functional areas as shown below.

xyzcodebase
|
|__ Func area 1
|
|__ Func area 2

I work on Functional area 2 hence while cloning I don't want code from Functional area 1 (large size)  which will save lots of my time. So that after cloning I will have only Functional area 2 source code on my local repository.

Is there a way to accomplish such selective cloning of git repository?

Thanks in advance for your help


问:
How do I make writeFileSync not overwrite previous data
This line of code overwrites all previous data.
Is there are way, or another function that allows me to add the data on a new line?</p>
```<code>fs.writeFileSync(path.resolve(__dirname, 'quotes.json'), JSON.stringify(quotey));
</code>```

答:
fs.appendFileSync() will append your new content to the file.  Documentation here.

To make it a line boundary, just make sure you also add the appropriate \n to the data you are appending so it will be separated from the next one that is appended (this assumes previous content also ends in a \n.

```<code>fs.appendFileSync(path.resolve(__dirname, 'quotes.json'), JSON.stringify(quotey) + "\n");
</code>```

Body:
This line of code overwrites all previous data.
Is there are way, or another function that allows me to add the data on a new line?

fs.writeFileSync(path.resolve(__dirname, 'quotes.json'), JSON.stringify(quotey));

Body:
fs.appendFileSync() will append your new content to the file.  Documentation here.

To make it a line boundary, just make sure you also add the appropriate \n to the data you are appending so it will be separated from the next one that is appended (this assumes previous content also ends in a \n.

fs.appendFileSync(path.resolve(__dirname, 'quotes.json'), JSON.stringify(quotey) + "\n");


问:
Flutter - Upload csv file
I would like to upload csv file in Flutter. I am using FileUploadInputElement for file browsing. The problem I issue is how to convert the data to csv format.

This is currently the code I am using:

```<code>class _GenesTableTabState extends State<GenesTableTab> {
  Uint8List uploadedCsv;
  String option1Text;

  _startFilePicker() async {
    InputElement uploadInput = FileUploadInputElement();
    uploadInput.click();

    uploadInput.onChange.listen((e) {
      // read file content as dataURL
      final files = uploadInput.files;
      if (files.length == 1) {
        final file = files[0];
        FileReader reader = FileReader();

        reader.onLoadEnd.listen((e) {
          setState(() {
            uploadedCsv = Base64Decoder()
                .convert(reader.result.toString().split(",").last);
          });
        });

        reader.onError.listen((fileEvent) {
          setState(() {
            option1Text = "Some Error occured while reading the file";
          });
        });

        reader.readAsDataUrl(file);
      }
    });
  }
</code>```

I don't know how to handle uploadedCsv field after the decoding.

答:
Here's how I handled it</p>
```<code>Uint8List uploadedCsv = new Uint8List(0);
String option1Text = "";

 if (kIsWeb)
{
  print('registering as web file picker');
    startWebFilePicker();
}

//....

 startWebFilePicker() async {
    html.FileUploadInputElement uploadInput = html.FileUploadInputElement();
    uploadInput.click();

          uploadInput.onChange.listen((e) {
        // read file content as dataURL
        final files = uploadInput.files;
        if (files!.length == 1) {
          final file = files[0];
          html.FileReader reader = html.FileReader();

          reader.onLoadEnd.listen((e) {
            setState(() async {
              uploadedCsv = Base64Decoder()
                  .convert(reader.result.toString().split(",").last);

              final fields = CsvToListConverter().convert(utf8.decode(uploadedCsv));
                print(fields);
                setState(() {
                  itemData=fields;
                });

              print('uploadedCSV is now ' + utf8.decode(uploadedCsv)); // utf8.decode returns the UInt8List to readable csv
            });
          });

          reader.onError.listen((fileEvent) {
            setState(() {
              option1Text = "Some Error occured while reading the file";
            });
          });

          reader.readAsDataUrl(file);

        }
      });

  }
</code>```

Title: Flutter - Upload csv file

Body:
I would like to upload csv file in Flutter. I am using FileUploadInputElement for file browsing. The problem I issue is how to convert the data to csv format.

This is currently the code I am using:

class _GenesTableTabState extends State<GenesTableTab> {
  Uint8List uploadedCsv;
  String option1Text;

  _startFilePicker() async {
    InputElement uploadInput = FileUploadInputElement();
    uploadInput.click();

    uploadInput.onChange.listen((e) {
      // read file content as dataURL
      final files = uploadInput.files;
      if (files.length == 1) {
        final file = files[0];
        FileReader reader = FileReader();

        reader.onLoadEnd.listen((e) {
          setState(() {
            uploadedCsv = Base64Decoder()
                .convert(reader.result.toString().split(",").last);
          });
        });

        reader.onError.listen((fileEvent) {
          setState(() {
            option1Text = "Some Error occured while reading the file";
          });
        });

        reader.readAsDataUrl(file);
      }
    });
  }

I don't know how to handle uploadedCsv field after the decoding.

Body:
Here's how I handled it

Uint8List uploadedCsv = new Uint8List(0);
String option1Text = "";

 if (kIsWeb)
{
  print('registering as web file picker');
    startWebFilePicker();
}

//....

 startWebFilePicker() async {
    html.FileUploadInputElement uploadInput = html.FileUploadInputElement();
    uploadInput.click();

          uploadInput.onChange.listen((e) {
        // read file content as dataURL
        final files = uploadInput.files;
        if (files!.length == 1) {
          final file = files[0];
          html.FileReader reader = html.FileReader();

          reader.onLoadEnd.listen((e) {
            setState(() async {
              uploadedCsv = Base64Decoder()
                  .convert(reader.result.toString().split(",").last);

              final fields = CsvToListConverter().convert(utf8.decode(uploadedCsv));
                print(fields);
                setState(() {
                  itemData=fields;
                });

              print('uploadedCSV is now ' + utf8.decode(uploadedCsv)); // utf8.decode returns the UInt8List to readable csv
            });
          });

          reader.onError.listen((fileEvent) {
            setState(() {
              option1Text = "Some Error occured while reading the file";
            });
          });

          reader.readAsDataUrl(file);

        }
      });

  }


问:
Can we get "agent status report" and "agent performance report" through historical metrics using APIs in Amazon Connect?
I hope everyone is doing great.
I am working on Amazon Connect reporting APIs. The basic need to post this question is that I want to get agent performance and agent status report through historical metrics using APIs. I am trying to find an API that will give me agent status from midnight that is only possible through historical metrics.
I don't want to use Streams APIs. If anyone has any solution kindly respond to me, it would be very helpful for me. Thanks.</p>

答: The current reporting API only provides one function for retrieving historical data, GetMetricData, and that function is only able to return queue or channel statistics. Agent specific data is only available via agent event stream and console-based reports at this time. So, unfortunately, there is no way to do what your describing with an API in Amazon Connect right now.</p>


问:
I am changing the state of the REACT component from another component but no refresh
I need a light to see what is missing?.
I am changing the state of the Users REACT component when I add a user to the backend.
The user added with no issues.
And I send the state of the User element in  and I change the state when "onSubmit:" happened
but the Users REACT component didn't reload .
What is wrong with this approach?</p>
```<code>import { v4 as uuidv4 } from 'uuid';
import React, { useState, useEffect }  from 'react';
import { useFormik } from 'formik';
function unique_id() {
    return uuidv4()
}
var PlayersBackend='/players';
const validate = values => {
    const errors = {};
    if (values.firstName === 0 || values.firstName.replace(/^\s+|\s+$/gm, '').length === 0) {
        errors.firstName = 'Required';
    } else if (values.firstName.length === 0) {
        errors.firstName = 'The message must be no empty';
    }

    if (values.lastName === 0 || values.lastName.replace(/^\s+|\s+$/gm, '').length === 0) {
        errors.lastName = 'Required';
    } else if (values.lastName.length === 0) {

        errors.lastName = 'The message must be no empty';
    }
    return errors;
};
const addPlayer = async (firstName, lastName) => {
    await fetch(PlayersBackend, {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            "Content-Type":"application/json",
        },
        body: JSON.stringify({ firstName, lastName })
    })

};

const AddPlayerForm=(compUsersState) =>{
    const formik = useFormik(
        {initialValues:{firstName: '',lastName: '',},
            validate,
            onSubmit: (values,{resetForm}) =>
        {  addPlayer(values.firstName,values.lastName).then();
            resetForm();
            console.log(compUsersState.compUsersState)
            compUsersState.compUsersState(p => p+1);

        },
    });
    return (
        <form onSubmit={formik.handleSubmit}>
            <label htmlFor="firstName">First Name</label>
            <input
                id="firstName"
                name="firstName"
                type="text"
                onChange={formik.handleChange}
                value={formik.values.firstName}
            />
            <label htmlFor="lastName">Last Name</label>
            <input
                id="lastName"
                name="lastName"
                type="text"
                onChange={formik.handleChange}
                value={formik.values.lastName}
            />

            <button type="submit">Add user</button>
        </form>
    );
};

export const Users = () => {

    const [error, setError] = useState(null);
    const [isLoaded, setIsLoaded] = useState(false);
    const [users, setPlayers] = useState([]);
    const [,compUsersState] = useState(0);
    useEffect(() => {
        fetch(PlayersBackend).then(response => response.json()).then((data) => { setIsLoaded(true);setPlayers(data);}, (error) => {setIsLoaded(true);setError(error);})},[])
    if (error) {
        return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
        return <div>Loading...</div>;
    } else {

        if (typeof (users._embedded) !== 'undefined')
        {
            return (

                <ul>
                    <AddPlayerForm compUsersState={compUsersState}/>
                    {users._embedded.players.map(player => (
                        <li className="d-flex justify-content-start" key={unique_id()}>
                            {player.firstName} {player.lastName}
                        </li>
                    ))}

                </ul>
            );

        }
        else return  (<ul> </ul> )

    }

}
</code>```

答:
It might be due to useEffect it only executes once when the component is loaded
adding users to useEffect dependency might help</p>
```<code> useEffect(() => {
    fetch(PlayersBackend)
      .then((response) => response.json())
      .then(
        (data) => {
          setIsLoaded(true);
          setPlayers(data);
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      );
  }, [users,users.length]);
</code>```

Body:
I need a light to see what is missing?.
I am changing the state of the Users REACT component when I add a user to the backend.
The user added with no issues.
And I send the state of the User element in  and I change the state when "onSubmit:" happened
but the Users REACT component didn't reload .
What is wrong with this approach?

import { v4 as uuidv4 } from 'uuid';
import React, { useState, useEffect }  from 'react';
import { useFormik } from 'formik';
function unique_id() {
    return uuidv4()
}
var PlayersBackend='/players';
const validate = values => {
    const errors = {};
    if (values.firstName === 0 || values.firstName.replace(/^\s+|\s+$/gm, '').length === 0) {
        errors.firstName = 'Required';
    } else if (values.firstName.length === 0) {
        errors.firstName = 'The message must be no empty';
    }

    if (values.lastName === 0 || values.lastName.replace(/^\s+|\s+$/gm, '').length === 0) {
        errors.lastName = 'Required';
    } else if (values.lastName.length === 0) {

        errors.lastName = 'The message must be no empty';
    }
    return errors;
};
const addPlayer = async (firstName, lastName) => {
    await fetch(PlayersBackend, {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            "Content-Type":"application/json",
        },
        body: JSON.stringify({ firstName, lastName })
    })

};

const AddPlayerForm=(compUsersState) =>{
    const formik = useFormik(
        {initialValues:{firstName: '',lastName: '',},
            validate,
            onSubmit: (values,{resetForm}) =>
        {  addPlayer(values.firstName,values.lastName).then();
            resetForm();
            console.log(compUsersState.compUsersState)
            compUsersState.compUsersState(p => p+1);

        },
    });
    return (
        <form onSubmit={formik.handleSubmit}>
            First Name
            <input
                id="firstName"
                name="firstName"
                type="text"
                onChange={formik.handleChange}
                value={formik.values.firstName}
            />
            Last Name
            <input
                id="lastName"
                name="lastName"
                type="text"
                onChange={formik.handleChange}
                value={formik.values.lastName}
            />

            <button type="submit">Add user</button>
        </form>
    );
};

export const Users = () => {

    const [error, setError] = useState(null);
    const [isLoaded, setIsLoaded] = useState(false);
    const [users, setPlayers] = useState([]);
    const [,compUsersState] = useState(0);
    useEffect(() => {
        fetch(PlayersBackend).then(response => response.json()).then((data) => { setIsLoaded(true);setPlayers(data);}, (error) => {setIsLoaded(true);setError(error);})},[])
    if (error) {
        return
Error: {error.message}
;
    } else if (!isLoaded) {
        return
Loading...
;
    } else {

        if (typeof (users._embedded) !== 'undefined')
        {
            return (

                    <AddPlayerForm compUsersState={compUsersState}/>
                    {users._embedded.players.map(player => (

                            {player.firstName} {player.lastName}

                    ))}

            );

        }
        else return  (

 )

    }

}

Body:
It might be due to useEffect it only executes once when the component is loaded
adding users to useEffect dependency might help

 useEffect(() => {
    fetch(PlayersBackend)
      .then((response) => response.json())
      .then(
        (data) => {
          setIsLoaded(true);
          setPlayers(data);
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      );
  }, [users,users.length]);


问:
Adding constructor to third party class/struct definition
A third party library has structs defined as

```<code>typedef struct _Example
{
  int member;
} Example;
</code>```

As a side question, just out of interest, why that definition? Why not struct Example { ... }?

Anyhow, I want to serialize the information with boost::serialization, and for that need a constructor. Is it safe to just change my version of the 3rd party header file by adding a constructor to the struct definition? Or alternatively, to just copy that definition to my own code base, rename it, add a constructor, and reinterpret_cast to it?

I assume it would be because as I understand functions and constructors shouldn't change the underlying byte layout of the class/struct, is this correct?

Thanks

答:
It's better to derive from that struct and define all the constructors you need. Modifying third-party libraries and copy-pasting definitions is not a good idea.

typedef struct pattern comes from C. In [older?] C, struct _Something does not allow you to use _Something as a type:

```<code>//_Something x;//not allowed
struct _Something x; //ok
</code>```

With typedef, one can define variables in natural Something x way, without that struct burden.

Body:
A third party library has structs defined as

typedef struct _Example
{
  int member;
} Example;

As a side question, just out of interest, why that definition? Why not struct Example { ... }?

Anyhow, I want to serialize the information with boost::serialization, and for that need a constructor. Is it safe to just change my version of the 3rd party header file by adding a constructor to the struct definition? Or alternatively, to just copy that definition to my own code base, rename it, add a constructor, and reinterpret_cast to it?

I assume it would be because as I understand functions and constructors shouldn't change the underlying byte layout of the class/struct, is this correct?

Thanks

Body:
It's better to derive from that struct and define all the constructors you need. Modifying third-party libraries and copy-pasting definitions is not a good idea.

typedef struct pattern comes from C. In [older?] C, struct _Something does not allow you to use _Something as a type:

//_Something x;//not allowed
struct _Something x; //ok

With typedef, one can define variables in natural Something x way, without that struct burden.


问:
Can you simplify Else If?
Currently working on a project from school. And they want us to take a users input and display their grades.

Now I am just being curious here, but is there any way to make this more simple? I feel like this could easily get out of hand.

My first thought was instead of creating each grade as a variable. You could make it an array. Could you then create some sort of loop that will check instead of creating an if else?

Sorry if this isn't possible. Just very curious about how i could improve on this.

```<code>> Grades = [
    '9',
    '8',
    '7',
    '6',
    '5',
    '4',
    '3',
    '2',
    '1',
    'U'
]

Component_1 = int(input("Enter your Component 1 mark here: "))
if Component_1 <= 9:
    print(f"You got the grade {Grades[9]} ")
elif Component_1 <= 17:
    print(f"You got the grade {Grades[8]}")
elif Component_1 <= 25:
    print(f"You got the grade {Grades[7]}")
elif Component_1 <= 34:
    print(f"You got the grade {Grades[6]}")
</code>```

The task I was originally asked to do:

答:
We can even solve  this by using dictionary too, similar to tuples provided by @Barmar

Here Grades is a dictionary which will store baseline scores and grades.
looping on dictionary we can fetch its key:value.
comparing input with key, based on if condition show the grade if it is neither < or > it will check on another value because it is in a loop, once matched it will break.

if user enters more than range for eg 1000 they will get to see out of range marks message

Note : further baseline scores and grades needs to be added in Grades dictionary

```<code>Grades={
     9:'U',
     17:'1'
}
Component_1 = int(input("Enter your Component 1 mark here: "))
count = 0
for key, values in Grades.items():
     if Component_1 <= key:
          count = count + 1
          print(f"You got:{values}")
          break
if count == 0 :
     print('you entered out of range marks')
</code>```

Title: Can you simplify Else If?

Body:
Currently working on a project from school. And they want us to take a users input and display their grades.

Now I am just being curious here, but is there any way to make this more simple? I feel like this could easily get out of hand.

My first thought was instead of creating each grade as a variable. You could make it an array. Could you then create some sort of loop that will check instead of creating an if else?

Sorry if this isn't possible. Just very curious about how i could improve on this.

> Grades = [
    '9',
    '8',
    '7',
    '6',
    '5',
    '4',
    '3',
    '2',
    '1',
    'U'
]

Component_1 = int(input("Enter your Component 1 mark here: "))
if Component_1 <= 9:
    print(f"You got the grade {Grades[9]} ")
elif Component_1 <= 17:
    print(f"You got the grade {Grades[8]}")
elif Component_1 <= 25:
    print(f"You got the grade {Grades[7]}")
elif Component_1 <= 34:
    print(f"You got the grade {Grades[6]}")

The task I was originally asked to do:

Body:
We can even solve  this by using dictionary too, similar to tuples provided by @Barmar

Here Grades is a dictionary which will store baseline scores and grades.
looping on dictionary we can fetch its key:value.
comparing input with key, based on if condition show the grade if it is neither < or > it will check on another value because it is in a loop, once matched it will break.

if user enters more than range for eg 1000 they will get to see out of range marks message

Note : further baseline scores and grades needs to be added in Grades dictionary

Grades={
     9:'U',
     17:'1'
}
Component_1 = int(input("Enter your Component 1 mark here: "))
count = 0
for key, values in Grades.items():
     if Component_1 <= key:
          count = count + 1
          print(f"You got:{values}")
          break
if count == 0 :
     print('you entered out of range marks')