问:
Reconnect to PostgreSQL database with R's pool package
I have an API built with R plumber that connects to a PostgreSQL database using RPostgreSQL and pool (although this would also apply if I was using a Shiny app):

# create the connection pool
pool <- dbPool(
  drv = PostgreSQL(),
  host = Sys.getenv("DB_HOST"),
  port = 5432,
  dbname = "db",
  user = Sys.getenv("DB_USER"),
  password = Sys.getenv("DB_PASSWORD")
)

# start the API
pr <- plumb("plumber.R")

# on stop, close the pool
pr$registerHooks(
  list("exit" = function() { poolClose(pool) })
)
```

<p>I want to import new data every day. The easiest way is to create a new database and promote it to production:</p>

<pre class="lang-sql prettyprint-override"><code>CREATE DATABASE db_new;
-- create the tables
-- bulk-insert the data
SELECT pg_terminate_backend (pid) FROM pg_stat_activity WHERE datname = 'db';
DROP DATABASE db;
ALTER DATABASE db_new RENAME TO db;
</code>```

This is fast and minimizes downtime. The problem is that pool then loses is connection to the database and doesn't automatically attempt to reconnect:

```<code>> tbl(pool, "users")
Error in postgresqlExecStatement(conn, statement, ...) :
  RS-DBI driver: (could not Retrieve the result : FATAL:  terminating connection due to administrator command
server closed the connection unexpectedly
    This probably means the server terminated abnormally
    before or while processing the request.
)
</code>```

Even if I wasn't replacing the database every day, DB servers occasionally restart and that will also cause my app to break. Reconnection doesn't seem to be a feature of pool, RPostgreSQL, nor DBI. Does anyone know a way to deal with this problem?

答:
I recently encountered a similar issue due to MySQL connections being closed when the instance's wait_timeout was exceeded. I came across your post on RStudio Community, and was inspired by your solution. In case you are still making use of it, and are in search of a solution that avoids the extra query while wrapping the actual functions you use, here is a reprex demonstrating something I came up with, along with an example proving it works:

library(dplyr, warn.conflicts = FALSE)
library(pool)
library(RMariaDB)

generate_safe_query <- function(pool) {
  function(db_function, ...) {
    tryCatch({
      db_function(pool, ...)
    }, error = function(e) {
      if (grepl("Lost connection to MySQL server during query", e$message)) {
        # Preserve `validationInterval` so that it can be restored
        validation_interval <- pool$validationInterval
        # Trigger destruction of dead connection
        pool$validationInterval <- 0
        refreshed_connection <- poolCheckout(pool)
        poolReturn(refreshed_connection)
        # Restore original `validationInterval`
        pool$validationInterval <- validation_interval
        # Execute the query with the new connection
        db_function(pool, ...)
      } else {
        # Unexpected error
        stop(e)
      }
    })
  }
}

mysql_pool <- dbPool(MariaDB(),
                     host = "127.0.0.1",
                     username = "root",
                     password = "",
                     dbname = "test")

safe_query <- generate_safe_query(mysql_pool)

# Works
safe_query(tbl, "notes")
#> # Source:   table<notes> [?? x 2]
#> # Database: mysql 8.0.15 [root@127.0.0.1:/test]
#>      id note
#>   <int> <chr>
#> 1     1 NOTE1

# Set the `wait_timeout` to 5 seconds for this session
invisible(safe_query(dbExecute, "SET SESSION wait_timeout = 5"))

# Wait longer than `wait_timeout` to trigger a disconnect
Sys.sleep(6)

# Still works; warning will appear notifying that connection was
# destroyed and replaced with a new one
safe_query(tbl, "notes")
#> Warning: It wasn't possible to activate and/or validate the object. Trying
#> again with a new object.
#> # Source:   table<notes> [?? x 2]
#> # Database: mysql 8.0.15 [root@127.0.0.1:/test]
#>      id note
#>   <int> <chr>
#> 1     1 NOTE1

safe_query(poolClose)
# Or, equivalently:
# poolClose(mysql_pool)
```

Created on 2019-05-30 by the reprex package (v0.3.0)

The function returned by generate_safe_query will work with any database query function (e.g. dbExecute, dbGetQuery, etc.). Obviously, you'll want to update the error message it matches to suit your needs.

I have also opened my own Community topic on an option I think should be included in dbPool that would alleviate the need for such workarounds.

Body:
I have an API built with R plumber that connects to a PostgreSQL database using RPostgreSQL and pool (although this would also apply if I was using a Shiny app):

# create the connection pool
pool <- dbPool(
  drv = PostgreSQL(),
  host = Sys.getenv("DB_HOST"),
  port = 5432,
  dbname = "db",
  user = Sys.getenv("DB_USER"),
  password = Sys.getenv("DB_PASSWORD")
)

# start the API
pr <- plumb("plumber.R")

# on stop, close the pool
pr$registerHooks(
  list("exit" = function() { poolClose(pool) })
)

I want to import new data every day. The easiest way is to create a new database and promote it to production:

CREATE DATABASE db_new;
-- create the tables
-- bulk-insert the data
SELECT pg_terminate_backend (pid) FROM pg_stat_activity WHERE datname = 'db';
DROP DATABASE db;
ALTER DATABASE db_new RENAME TO db;

This is fast and minimizes downtime. The problem is that pool then loses is connection to the database and doesn't automatically attempt to reconnect:

> tbl(pool, "users")
Error in postgresqlExecStatement(conn, statement, ...) :
  RS-DBI driver: (could not Retrieve the result : FATAL:  terminating connection due to administrator command
server closed the connection unexpectedly
    This probably means the server terminated abnormally
    before or while processing the request.
)

Even if I wasn't replacing the database every day, DB servers occasionally restart and that will also cause my app to break. Reconnection doesn't seem to be a feature of pool, RPostgreSQL, nor DBI. Does anyone know a way to deal with this problem?

Body:
I recently encountered a similar issue due to MySQL connections being closed when the instance's wait_timeout was exceeded. I came across your post on RStudio Community, and was inspired by your solution. In case you are still making use of it, and are in search of a solution that avoids the extra query while wrapping the actual functions you use, here is a reprex demonstrating something I came up with, along with an example proving it works:

library(dplyr, warn.conflicts = FALSE)
library(pool)
library(RMariaDB)

generate_safe_query <- function(pool) {
  function(db_function, ...) {
    tryCatch({
      db_function(pool, ...)
    }, error = function(e) {
      if (grepl("Lost connection to MySQL server during query", e$message)) {
        # Preserve `validationInterval` so that it can be restored
        validation_interval <- pool$validationInterval
        # Trigger destruction of dead connection
        pool$validationInterval <- 0
        refreshed_connection <- poolCheckout(pool)
        poolReturn(refreshed_connection)
        # Restore original `validationInterval`
        pool$validationInterval <- validation_interval
        # Execute the query with the new connection
        db_function(pool, ...)
      } else {
        # Unexpected error
        stop(e)
      }
    })
  }
}

mysql_pool <- dbPool(MariaDB(),
                     host = "127.0.0.1",
                     username = "root",
                     password = "",
                     dbname = "test")

safe_query <- generate_safe_query(mysql_pool)

# Works
safe_query(tbl, "notes")
#> # Source:   table<notes> [?? x 2]
#> # Database: mysql 8.0.15 [root@127.0.0.1:/test]
#>      id note
#>   <int> <chr>
#> 1     1 NOTE1

# Set the `wait_timeout` to 5 seconds for this session
invisible(safe_query(dbExecute, "SET SESSION wait_timeout = 5"))

# Wait longer than `wait_timeout` to trigger a disconnect
Sys.sleep(6)

# Still works; warning will appear notifying that connection was
# destroyed and replaced with a new one
safe_query(tbl, "notes")
#> Warning: It wasn't possible to activate and/or validate the object. Trying
#> again with a new object.
#> # Source:   table<notes> [?? x 2]
#> # Database: mysql 8.0.15 [root@127.0.0.1:/test]
#>      id note
#>   <int> <chr>
#> 1     1 NOTE1

safe_query(poolClose)
# Or, equivalently:
# poolClose(mysql_pool)

Created on 2019-05-30 by the reprex package (v0.3.0)

The function returned by generate_safe_query will work with any database query function (e.g. dbExecute, dbGetQuery, etc.). Obviously, you'll want to update the error message it matches to suit your needs.

I have also opened my own Community topic on an option I think should be included in dbPool that would alleviate the need for such workarounds.


来源: stackexchange

问:
Javascript error when html passed in JSON packet
I am going mad trying to resolve this issue. I have implemented a Coldfusion Ajax-like File Upload that uploads a file using a hidden frame and then grabs the contents returned by the frame. It is based on this article: http://www.bennadel.com/blog/1244-ColdFusion-jQuery-And-AJAX-File-Upload-Demo.htm

So, everything is working great, EXCEPT when I send back HTML in the data. So, if you look in the code below, I have provided the action page that streams data back to the hidden frame. The first line works, the second line with html does not.

```<code>    <!--- Create the return HTML. Remember, we are going to be treating the BODY of the returned document as if it were a JSON string. --->
    <cfsavecontent variable="strHTML">

        <cfset var sResponse = {} />
        <!--- THIS WORKS --->
        <cfset sResponse = {SUCCESS = true, ERRORS = [], DATA = "Hello World", RETURNID=""} />
        <!--- THIS DOES NOT WORK --->
        <cfset sResponse = {SUCCESS = true, ERRORS = [], DATA = #HtmlEditFormat('<div>Hello World</div>')#", RETURNID=""} />

        <cfoutput>
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
            <html>
            <head></head>
            <body>#SerializeJSON( sResponse )#</body>
            </html>
        </cfoutput>
    </cfsavecontent>

<!--- Create binary response data. --->
<cfset binResponse = ToBinary( ToBase64( strHTML ) ) />

<!--- Tell the client how much data to expect. --->
<cfheader name="content-length" value="#ArrayLen( binResponse )#" />

<!--- Stream the "plain text" back to the client .--->
<cfcontent type="text/html" variable="#binResponse#" />
</code>```

The javascript for doing all of this is below. The line that it errors on when HTML is passed back is:

// Assuming that our return data is in JSON format, evaluate the body html to get our return data.
var objData = eval( "(" + jBody.html() + ")" );

```<code>//ShareForm Photo Upload Form Process (simulated Ajax)
$(document).ready(function() {
    // Attach an event to the submit method. Instead of submitting the actual form to the primary page, we are going to be submitting the form to a hidden iFrame that we dynamically create.
    $( "#frmShareForm" ).submit(
        function( objEvent ){
            var jThis = $( this );
            var photoUploadAction = $("#photoUploadAction").val();

            // Create a unique name for our iFrame. We can do this by using the tick count from the date.
            var strName = ("uploader" + (new Date()).getTime());

            // Create an iFrame with the given name that does not point to any page - we can use the address "about:blank" to get this to happen.
            var jFrame = $( "<iframe name=\"" + strName + "\" src=\"about:blank\" />" );

            // We now have an iFrame that is not attached to the document. Before we attach it, let's make sure it will not be seen.
            jFrame.css( "display", "none" );

            // Since we submitting the form to the iFrame, we will want to be able to get back data from the form submission.
            // To do this, we will have to set up an event listener for the LOAD event of the iFrame.
            jFrame.load(
                function( objEvent ){
                    // Get a reference to the body tag of the loaded iFrame. We are doing to assume that this element will contain our return data in JSON format.
                    var objUploadBody = window.frames[ strName ].document.getElementsByTagName( "body" )[ 0 ];

                    // Get a jQuery object of the body so that we can have better access to it.
                    var jBody = $( objUploadBody );

                    // Assuming that our return data is in JSON format, evaluate the body html to get our return data.
                    var objData = eval( "(" + jBody.html() + ")" );
                    alert(objData);

                    // A JSON-format struct is returned that will be used to do callback functionality
                    SharePhotoAjaxResponseHandler(objData);

                    // Remove the iFrame from the document. Because FireFox has some issues with "Infinite thinking", let's put a small delay on the frame removal.
                    setTimeout
                    (
                        function()
                        {
                            jFrame.remove();
                        }, 100
                    );
                }
            );

            // Attach to body.
            $( "body:first" ).append( jFrame );

            // Now that our iFrame it totally in place, hook up the frame to post to the iFrame.
            jThis
                .attr( "action",  photoUploadAction)
                .attr( "method", "post" )
                .attr( "enctype", "multipart/form-data" )
                .attr( "encoding", "multipart/form-data" )
                .attr( "target", strName );
    });
});
</code>```

The javascript error I get is usually something like:
"unterminated regular expression literal"

I have also tried removing the SerialiseJson on the CFM page, and the eval in the javascript, which both result in other js errors. I have also tried removing the surrounding html as well as change .html() to .text(), remove the eval() and combinations of all of them. No luck.

Please can someone tell me what the problem is. I know I can't be far off as it works without html.

Thanks

UPDATE: I ran the JSON output that Coldfusion generates through the JSON validator and it failed, due to (from what I can see) the double quotation marks:

```<code>{""RETURNID"":"""",""DATA"":""<div>Hello World<\/div>"",""SUCCESS"":true,""ERRORS"":[]}
</code>```

Now I really don't know why Coldfusion is doing double quotations?? Anyone have any ideas?

答:
The javascript error I get is usually
  something like: "unterminated regular
  expression literal"

Check your JSON. You can run it though JSONLint to see if it's valid or not. It probably isn't, based on your error message.

ContentLicense: CC BY-SA 3.0

Body:
I am going mad trying to resolve this issue. I have implemented a Coldfusion Ajax-like File Upload that uploads a file using a hidden frame and then grabs the contents returned by the frame. It is based on this article: http://www.bennadel.com/blog/1244-ColdFusion-jQuery-And-AJAX-File-Upload-Demo.htm

So, everything is working great, EXCEPT when I send back HTML in the data. So, if you look in the code below, I have provided the action page that streams data back to the hidden frame. The first line works, the second line with html does not.

    <cfsavecontent variable="strHTML">

        <cfset var sResponse = {} />

        <cfset sResponse = {SUCCESS = true, ERRORS = [], DATA = "Hello World", RETURNID=""} />

        <cfset sResponse = {SUCCESS = true, ERRORS = [], DATA = #HtmlEditFormat('
Hello World
')#", RETURNID=""} />

        <cfoutput>
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

            #SerializeJSON( sResponse )#

        </cfoutput>
    </cfsavecontent>

<cfset binResponse = ToBinary( ToBase64( strHTML ) ) />

<cfheader name="content-length" value="#ArrayLen( binResponse )#" />

<cfcontent type="text/html" variable="#binResponse#" />

The javascript for doing all of this is below. The line that it errors on when HTML is passed back is:

// Assuming that our return data is in JSON format, evaluate the body html to get our return data.
var objData = eval( "(" + jBody.html() + ")" );

//ShareForm Photo Upload Form Process (simulated Ajax)
$(document).ready(function() {
    // Attach an event to the submit method. Instead of submitting the actual form to the primary page, we are going to be submitting the form to a hidden iFrame that we dynamically create.
    $( "#frmShareForm" ).submit(
        function( objEvent ){
            var jThis = $( this );
            var photoUploadAction = $("#photoUploadAction").val();

            // Create a unique name for our iFrame. We can do this by using the tick count from the date.
            var strName = ("uploader" + (new Date()).getTime());

            // Create an iFrame with the given name that does not point to any page - we can use the address "about:blank" to get this to happen.
            var jFrame = $( "" );

            // We now have an iFrame that is not attached to the document. Before we attach it, let's make sure it will not be seen.
            jFrame.css( "display", "none" );

            // Since we submitting the form to the iFrame, we will want to be able to get back data from the form submission.
            // To do this, we will have to set up an event listener for the LOAD event of the iFrame.
            jFrame.load(
                function( objEvent ){
                    // Get a reference to the body tag of the loaded iFrame. We are doing to assume that this element will contain our return data in JSON format.
                    var objUploadBody = window.frames[ strName ].document.getElementsByTagName( "body" )[ 0 ];

                    // Get a jQuery object of the body so that we can have better access to it.
                    var jBody = $( objUploadBody );

                    // Assuming that our return data is in JSON format, evaluate the body html to get our return data.
                    var objData = eval( "(" + jBody.html() + ")" );
                    alert(objData);

                    // A JSON-format struct is returned that will be used to do callback functionality
                    SharePhotoAjaxResponseHandler(objData);

                    // Remove the iFrame from the document. Because FireFox has some issues with "Infinite thinking", let's put a small delay on the frame removal.
                    setTimeout
                    (
                        function()
                        {
                            jFrame.remove();
                        }, 100
                    );
                }
            );

            // Attach to body.
            $( "body:first" ).append( jFrame );

            // Now that our iFrame it totally in place, hook up the frame to post to the iFrame.
            jThis
                .attr( "action",  photoUploadAction)
                .attr( "method", "post" )
                .attr( "enctype", "multipart/form-data" )
                .attr( "encoding", "multipart/form-data" )
                .attr( "target", strName );
    });
});

The javascript error I get is usually something like:
"unterminated regular expression literal"

I have also tried removing the SerialiseJson on the CFM page, and the eval in the javascript, which both result in other js errors. I have also tried removing the surrounding html as well as change .html() to .text(), remove the eval() and combinations of all of them. No luck.

Please can someone tell me what the problem is. I know I can't be far off as it works without html.

Thanks

UPDATE: I ran the JSON output that Coldfusion generates through the JSON validator and it failed, due to (from what I can see) the double quotation marks:

{""RETURNID"":"""",""DATA"":""
Hello World<\/div>"",""SUCCESS"":true,""ERRORS"":[]}

Now I really don't know why Coldfusion is doing double quotations?? Anyone have any ideas?


问:
How do you remove a vertex from a polygon with multiple paths?
In googlemaps api, when editing a polygon with multiple paths, removeAT eliminates the wrong vertex

For simple polygons, the removeAT will remove the correct vertex, but for multiple path polygons, it seems to remove only the vertex number from the first path.

Given this definition of a polygon for multiple paths:

```<code>var blockpolygon = newgoogle.maps.Polygon({
paths: [blockcoords0,blockcoords1,blockcoords2,blockcoords3,blockcoords4,blockcoords5]
});
</code>```

where the paths are previously defined, for example:

```<code>var blockcoords4 = [{lat:51.799693211411,lng:-114.12380330669},{lat:51.799109509173,lng:-114.12273800578},{lat:51.799558197929,lng:-114.1223323167},{lat:51.799684004911,lng:-114.12232429316},{lat:51.799876802912,lng:-114.12248608283},{lat:51.800102904916,lng:-114.12290678386},{lat:51.800133809341,lng:-114.12306439938},{lat:51.800077007986,lng:-114.12331471639},{lat: 51.799693211411, lng: -114.12380330669}];
</code>```

and the polygon is set as editable

When this event fires:

```<code>blockpolygon.addListener("rightclick", function(event)
{
this.getPath().removeAt(event.vertex);
}
</code>```

The vertex from the first path on the list is removed, which is not the vertex that was "clicked"

Is there any way to remove the vertex from the correct path?

If I could identify which path and have the removeAT pointed to the correct path, that would make my day.

答:
the hint from geocodezip was enough.  Here's the solution:</p>

```<code>blockpolygon.addListener("rightclick", function(event)
    {
    for (i=0; i<this.getPaths().getLength(); i++)
        {
        for (j=0; j< this.getPaths().getAt(i).getLength(); j++)
            {
            var distance = google.maps.geometry.spherical.computeDistanceBetween(event.latLng, this.getPaths().getAt(i).getAt(j));
            if (distance==0) this.getPaths().getAt(i).removeAt(j);
            }
        }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In googlemaps api, when editing a polygon with multiple paths, removeAT eliminates the wrong vertex

For simple polygons, the removeAT will remove the correct vertex, but for multiple path polygons, it seems to remove only the vertex number from the first path.

Given this definition of a polygon for multiple paths:

var blockpolygon = newgoogle.maps.Polygon({
paths: [blockcoords0,blockcoords1,blockcoords2,blockcoords3,blockcoords4,blockcoords5]
});

where the paths are previously defined, for example:

var blockcoords4 = [{lat:51.799693211411,lng:-114.12380330669},{lat:51.799109509173,lng:-114.12273800578},{lat:51.799558197929,lng:-114.1223323167},{lat:51.799684004911,lng:-114.12232429316},{lat:51.799876802912,lng:-114.12248608283},{lat:51.800102904916,lng:-114.12290678386},{lat:51.800133809341,lng:-114.12306439938},{lat:51.800077007986,lng:-114.12331471639},{lat: 51.799693211411, lng: -114.12380330669}];

and the polygon is set as editable

When this event fires:

blockpolygon.addListener("rightclick", function(event)
{
this.getPath().removeAt(event.vertex);
}

The vertex from the first path on the list is removed, which is not the vertex that was "clicked"

Is there any way to remove the vertex from the correct path?

If I could identify which path and have the removeAT pointed to the correct path, that would make my day.

Body:
the hint from geocodezip was enough.  Here's the solution:

blockpolygon.addListener("rightclick", function(event)
    {
    for (i=0; i<this.getPaths().getLength(); i++)
        {
        for (j=0; j< this.getPaths().getAt(i).getLength(); j++)
            {
            var distance = google.maps.geometry.spherical.computeDistanceBetween(event.latLng, this.getPaths().getAt(i).getAt(j));
            if (distance==0) this.getPaths().getAt(i).removeAt(j);
            }
        }
}


问:
Apply style to element with empty next sibling using Sass
Is it possible to style an element based on whether or not its next sibling is empty.

Hide me when submenu is empty

```

<p>Let's assume that I want to hide <code><LI class="label"></code> when <code><UL class="submenu"></code> is empty.  Is this possible with CSS/Sass?  </p>

<p>I've tried several variations of the example below, but haven't had any luck.</p>

<pre class="lang-css prettyprint-override"><code>    ul {
        > li {
            ~ ul:empty {
                display: none;
            }
        }
    }
</code>```

I'd prefer to stick with a CSS solution if possible.

答:
The first, major problem your markup has is that it's invalid.

The only valid children of
 elements are
s. Therefore, in order to be valid, your inner
 has to be inside the
. It can't be an immediate child of another
.

But, even assuming a valid markup:

Hide me when submenu is empty

```

<p>... what you're trying to do is not possible using CSS alone, because the CSS parser never goes backwards (or upwards, for that matter).</p>

<p>If you can't do it with CSS alone you can't do it with SCSS alone, because SCSS is CSS syntactic sugar.</p>

<hr>

<p>Here's how a JavaScript solution would look like:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const uls = document.querySelectorAll('ul');
[...uls].forEach((ul) => {
  const emptyChildUls = ul.querySelectorAll('ul:empty');
  [...emptyChildUls].forEach((emptyUl) => {
    emptyUl.parentElement.classList.add('hasEmptyList');
  })
});</code>```

ul li.hasEmptyList {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Hide me when submenu is empty
    <ul></ul>
  </li>
</ul></code>```

Obviously, you can change the applied classname to whatever you want. I chose to add a class rather than perform direct changes to the DOM elements so that you could still retain a level of control via CSS.

The above script has to run after you finished adding
s to your page. If you add them after you ran the script, they won't have the class applied (you need to run the script again so they do).

Body:
Is it possible to style an element based on whether or not its next sibling is empty.

Hide me when submenu is empty

Let's assume that I want to hide
 when
 is empty.  Is this possible with CSS/Sass?

I've tried several variations of the example below, but haven't had any luck.

    ul {
        > li {
            ~ ul:empty {
                display: none;
            }
        }
    }

I'd prefer to stick with a CSS solution if possible.

Body:
The first, major problem your markup has is that it's invalid.

The only valid children of <ul> elements are <li>s. Therefore, in order to be valid, your inner <ul> has to be inside the <li>. It can't be an immediate child of another <ul>.

But, even assuming a valid markup:

<ul class="menu">
  <li class="label">Hide me when submenu is empty
    <ul class="submenu"></ul>
  </li>
</ul>

... what you're trying to do is not possible using CSS alone, because the CSS parser never goes backwards (or upwards, for that matter).

If you can't do it with CSS alone you can't do it with SCSS alone, because SCSS is CSS syntactic sugar.

Here's how a JavaScript solution would look like:

const uls = document.querySelectorAll('ul');
[...uls].forEach((ul) => {
  const emptyChildUls = ul.querySelectorAll('ul:empty');
  [...emptyChildUls].forEach((emptyUl) => {
    emptyUl.parentElement.classList.add('hasEmptyList');
  })
});

ul li.hasEmptyList {
  display: none;
}

<ul>
  <li>Hide me when submenu is empty
    <ul></ul>
  </li>
</ul>

Obviously, you can change the applied classname to whatever you want. I chose to add a class rather than perform direct changes to the DOM elements so that you could still retain a level of control via CSS.

The above script has to run after you finished adding <ul>s to your page. If you add them after you ran the script, they won't have the class applied (you need to run the script again so they do).


问:
Console Says Internal Server Errror?
My Console Browser Says Internal Server Error but my connection and path on file is already ok what should i do ??

Ill try to json decode my array form database in sql column but still cant find my target data

```<code>//GET PATIENT LIST TABLE
function get_bereavement_risk_list_table(){
    $arr = array();
    $g = 'SELECT bvpoc_mrno,bvpoc_no,bvpoc_dateassesed,bvpoc_entered,bvpoc_risklevel,bvpoc_formdata,bvpoc_lastupdate,
    patient_mrno,patient_lastname,patient_middlename,patient_firstname
    FROM bereavement_poc a LEFT JOIN tblpatients b ON a.bvpoc_mrno = b.patient_mrno';
    $r = $this->connect()->prepare($g);
    $r->execute();
    if($r->rowCount()>0){
        while($rr = $r->fetch()){
           $riskarr = json_decode($rr['bvpoc_formdata']);
           $risklname = $riskarr[0];
           $riskfname = $riskarr[1];

           $risk['lname']  = $risklname;
           $risk['fname'] = $riskfname;

           array_push($arr,$risk);
        }
        echo json_encode($arr);
    }
}
</code>```

POST https://bdhospice.com/pages/reports/bereavement_letter/bereavement_risk_report/bereavement_risk.class.php 500 (Internal Server Error)

答:
By going to the link you provided, browser catches the 404 error, not the 500.
By the way, try using a different browser or cleaning your browsers cache, cookies (associated with the site you're getting the error on).
500 error is server-side error, meaning the problem probably isn't with your connection but instead with the website's server, maybe it crashed or something, try refreshing it.</p>

Title: Console Says Internal Server Errror?

Body:
My Console Browser Says Internal Server Error but my connection and path on file is already ok what should i do ??

Ill try to json decode my array form database in sql column but still cant find my target data

//GET PATIENT LIST TABLE
function get_bereavement_risk_list_table(){
    $arr = array();
    $g = 'SELECT bvpoc_mrno,bvpoc_no,bvpoc_dateassesed,bvpoc_entered,bvpoc_risklevel,bvpoc_formdata,bvpoc_lastupdate,
    patient_mrno,patient_lastname,patient_middlename,patient_firstname
    FROM bereavement_poc a LEFT JOIN tblpatients b ON a.bvpoc_mrno = b.patient_mrno';
    $r = $this->connect()->prepare($g);
    $r->execute();
    if($r->rowCount()>0){
        while($rr = $r->fetch()){
           $riskarr = json_decode($rr['bvpoc_formdata']);
           $risklname = $riskarr[0];
           $riskfname = $riskarr[1];

           $risk['lname']  = $risklname;
           $risk['fname'] = $riskfname;

           array_push($arr,$risk);
        }
        echo json_encode($arr);
    }
}

POST https://bdhospice.com/pages/reports/bereavement_letter/bereavement_risk_report/bereavement_risk.class.php 500 (Internal Server Error)


问:
Python Processing: How to call multiple of the same class
I am a noob at Python and I am having trouble with this problem. I am trying to create a raindrop scene with the 'drop' class. Right now, the code only calls one drop at a time. How can I call multiple drops at once?

Here is my code:

```<code>import random
class drop():
    def __init__(self):
        # where the drop starts
        self.x = random.randint(20,480)
        self.y = 0
        #how fast the drop falls
        self.yspeed = 5

    def fall(self):
        self.y = self.y+self.yspeed

    def show(self):
        # color of drop
        stroke(1,1,1)
        fill(1,1,1)
        strokeWeight(1)
        line(self.x,self.y,self.x,self.y+10)

def setup():
    size(500,500)
    global d
    d = drop()

def draw():
    background(255,255,255)
    d.fall()
    d.show()
</code>```

答:
You can create as many instances of a class as you want. For example the following code creates two drops.

```<code>d1 = drop()
d2 = drop()
</code>```

You can also create a list of drops like this -

```<code>drops = []
drops.append(drop())
drops.append(drop())
drops[0].fall()
drops[1].show()
</code>```

Body:
I am a noob at Python and I am having trouble with this problem. I am trying to create a raindrop scene with the 'drop' class. Right now, the code only calls one drop at a time. How can I call multiple drops at once?

Here is my code:

import random
class drop():
    def __init__(self):
        # where the drop starts
        self.x = random.randint(20,480)
        self.y = 0
        #how fast the drop falls
        self.yspeed = 5

    def fall(self):
        self.y = self.y+self.yspeed

    def show(self):
        # color of drop
        stroke(1,1,1)
        fill(1,1,1)
        strokeWeight(1)
        line(self.x,self.y,self.x,self.y+10)

def setup():
    size(500,500)
    global d
    d = drop()

def draw():
    background(255,255,255)
    d.fall()
    d.show()

Body:
You can create as many instances of a class as you want. For example the following code creates two drops.

d1 = drop()
d2 = drop()

You can also create a list of drops like this -

drops = []
drops.append(drop())
drops.append(drop())
drops[0].fall()
drops[1].show()


问:
Java - wrapper classes and hashCode()
is there any difference b/w value returned by Integer's hashCode() and intValue()? Can hashcode be negative?

答:
No, there's no difference, and thus yes, it can be negative or zero.

From the Javadoc:

Returns:  a hash code value for this object, equal to the primitive int value represented by this Integer object.

Title: Java - wrapper classes and hashCode()


问:
When compressing text files with DEFLATE how much data is required before a decrease in size is possible?
The degree of compression achieved by any compression algorithm is obviously dependent on the data provided.  However, there is also clearly some overhead added purely by virtue of having compressed data.

I'm working on a process where I am compressing data that can be of various types but where I know much of the data will be very small though it will also frequently be large enough to benefit from some level of compression.  While I can probably just experimentally determine some minimum before compression is applied that will work well enough I am curious if there's a clear point where this is definitely not worth it.

Running some tests using zip, I compressed a series of files with 10, 100, and 1000 bytes respectively of random data and the alphabet repeated.  For example here is the content of the 100 byte alphabet file:

```abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqr```

I was fairly surprised to find that the zipped version of the file was 219 bytes, despite the level of redundancy.  For comparison the 100 byte file with random data became 272 bytes.

However, the 1000 byte alphabet file compressed all the way down to 227 bytes, while the random file increased to 1174.

Is there a clear minimum file size where even the most redundant files will not benefit from this type of compression?

答:
Something between 250 and 500 bytes would be a decent threshold depending on the level of redundancy and assuming the time spent compressing the data is negligible.

I got to this by realizing that fully redundant data (every byte the same) would likely result in the greatest level of compression.

Re-running the same tests with data read from /dev/zero, I found that the compressed file length was not really that variable:

```
Uncompressed | Compressed | Percent Size
-------------+------------+-------------
100 bytes    | 178 bytes  | 178%
200 bytes    | 178 bytes  |  89%
300 bytes    | 179 bytes  |  60%
400 bytes    | 180 bytes  |  45%
500 bytes    | 180 bytes  |  36%
  ...
1000 bytes   | 185 bytes  |  19%
```

This makes a decent case for the answer being technically 178 bytes (I tested this case and got 178 bytes).

However, I think the alphabet test is probably a bit closer to a practical best case of redundancy (without knowing much about how DEFLATE looks for redundancy).

Using various files in the same format as in the question, I found the following:

```
Uncompressed | Compressed | Percent Size
-------------+------------+-------------
100 bytes    | 212 bytes  | 212%
200 bytes    | 212 bytes  | 106%
300 bytes    | 214 bytes  |  71%
400 bytes    | 214 bytes  |  54%
500 bytes    | 214 bytes  |  43%
  ...
1000 bytes   | 221 bytes  |  22%
```

And unsurprisingly 212 seems to be a fixed point for this type of file.

Lastly, I decided to try a more direct approach with lorem ipsum text and eventually found that 414 bytes was the fixed point there.

Based on all of this, I would assume something between 250 and 500 would be a reasonable lower limit for skipping compression for general text that may or may not have some level of redundancy on average.  One may even want to go higher if benchmarking reveals the time the compression takes isn't worth the minor benefit in space.

Body:
The degree of compression achieved by any compression algorithm is obviously dependent on the data provided.  However, there is also clearly some overhead added purely by virtue of having compressed data.

I'm working on a process where I am compressing data that can be of various types but where I know much of the data will be very small though it will also frequently be large enough to benefit from some level of compression.  While I can probably just experimentally determine some minimum before compression is applied that will work well enough I am curious if there's a clear point where this is definitely not worth it.

Running some tests using zip, I compressed a series of files with 10, 100, and 1000 bytes respectively of random data and the alphabet repeated.  For example here is the content of the 100 byte alphabet file:

abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqr

I was fairly surprised to find that the zipped version of the file was 219 bytes, despite the level of redundancy.  For comparison the 100 byte file with random data became 272 bytes.

However, the 1000 byte alphabet file compressed all the way down to 227 bytes, while the random file increased to 1174.

Is there a clear minimum file size where even the most redundant files will not benefit from this type of compression?

Body:
Something between 250 and 500 bytes would be a decent threshold depending on the level of redundancy and assuming the time spent compressing the data is negligible.

I got to this by realizing that fully redundant data (every byte the same) would likely result in the greatest level of compression.

Re-running the same tests with data read from /dev/zero, I found that the compressed file length was not really that variable:

Uncompressed | Compressed | Percent Size
-------------+------------+-------------
100 bytes    | 178 bytes  | 178%
200 bytes    | 178 bytes  |  89%
300 bytes    | 179 bytes  |  60%
400 bytes    | 180 bytes  |  45%
500 bytes    | 180 bytes  |  36%
  ...
1000 bytes   | 185 bytes  |  19%

This makes a decent case for the answer being technically 178 bytes (I tested this case and got 178 bytes).

However, I think the alphabet test is probably a bit closer to a practical best case of redundancy (without knowing much about how DEFLATE looks for redundancy).

Using various files in the same format as in the question, I found the following:

Uncompressed | Compressed | Percent Size
-------------+------------+-------------
100 bytes    | 212 bytes  | 212%
200 bytes    | 212 bytes  | 106%
300 bytes    | 214 bytes  |  71%
400 bytes    | 214 bytes  |  54%
500 bytes    | 214 bytes  |  43%
  ...
1000 bytes   | 221 bytes  |  22%

And unsurprisingly 212 seems to be a fixed point for this type of file.

Lastly, I decided to try a more direct approach with lorem ipsum text and eventually found that 414 bytes was the fixed point there.

Based on all of this, I would assume something between 250 and 500 would be a reasonable lower limit for skipping compression for general text that may or may not have some level of redundancy on average.  One may even want to go higher if benchmarking reveals the time the compression takes isn't worth the minor benefit in space.


问:
Excel VBA to Word Unselect a Selected text
I'm writing an Excel VBA code that transfers data to a Word document. I'm using the command Application.Selection.Find and Application.Selection.InsertAfter in order to fill in the blanks in the Word document.

The problem is that after I select one item I can't select another one.

I would like to be able to unselect an item so that I could freely select another using the same command. How?

答:
Alternatively can use this. This will send the cursor to the end of the Word document.

Selection.EndKey Unit:=wdStory

[SOURCE: https://software-solutions-online.com/word-vba-move-cursor-to-end-of-document/]


问:
Where is the variable "code" in SKError defined?
I am seeing examples of code using SKError "code" property or variable.
I cannot seem to define any definition for this property.
How is xcode / Swift able to access this property?
I am using SwiftyStoreKit with this issue.
Thanks

Tried looking in the documentation for SKError, nothing there.
Tried debugging in xcode, live, cannot understand from xcode where is this thing coming from.

```<code>    SwiftyStoreKit.purchaseProduct("X", quantity: 1, atomically: true) { result in
        switch result {
        case .success(let purchase):
            print("Purchase Success: \(purchase.productId)")
            let defaults = UserDefaults.standard
            defaults.set(true, forKey: "Y")
        case .error(let error):
            switch error.code {
            case .unknown: self.Alert("Z")
</code>```

Just want to know how xcode can access this property.

答:
It may help to realize that SKError conforms to Error, which is bridged to NSError. If you look at the NSError docs you'll see that it has a code property which is an Int. Therefore SKError has this too.

In the Objective-C world, from which all this comes ultimately, the possible NSInteger values of an SKError's code are listed in an Objective-C enum:

```<code>typedef NS_ENUM(NSInteger,SKErrorCode) {
    SKErrorUnknown,
    SKErrorClientInvalid,
    SKErrorPaymentCancelled,
    // ...
}
</code>```

That is imported into Swift as a Swift enum with an Int raw value, of type SKError.Code:

```<code>public struct SKError {
    public enum Code : Int {
        case unknown
        case clientInvalid
        case paymentCancelled
        // ...
    }
}
</code>```

Thus as a convenience the names .clientInvalid and so forth can be used in comparison with an SKError's code.

Body:
I am seeing examples of code using SKError "code" property or variable.
I cannot seem to define any definition for this property.
How is xcode / Swift able to access this property?
I am using SwiftyStoreKit with this issue.
Thanks

Tried looking in the documentation for SKError, nothing there.
Tried debugging in xcode, live, cannot understand from xcode where is this thing coming from.

    SwiftyStoreKit.purchaseProduct("X", quantity: 1, atomically: true) { result in
        switch result {
        case .success(let purchase):
            print("Purchase Success: \(purchase.productId)")
            let defaults = UserDefaults.standard
            defaults.set(true, forKey: "Y")
        case .error(let error):
            switch error.code {
            case .unknown: self.Alert("Z")

Just want to know how xcode can access this property.

Body:
It may help to realize that SKError conforms to Error, which is bridged to NSError. If you look at the NSError docs you'll see that it has a code property which is an Int. Therefore SKError has this too.

In the Objective-C world, from which all this comes ultimately, the possible NSInteger values of an SKError's code are listed in an Objective-C enum:

typedef NS_ENUM(NSInteger,SKErrorCode) {
    SKErrorUnknown,
    SKErrorClientInvalid,
    SKErrorPaymentCancelled,
    // ...
}

That is imported into Swift as a Swift enum with an Int raw value, of type SKError.Code:

public struct SKError {
    public enum Code : Int {
        case unknown
        case clientInvalid
        case paymentCancelled
        // ...
    }
}

Thus as a convenience the names .clientInvalid and so forth can be used in comparison with an SKError's code.


问:
Copy cell values from one excel workbooks sheet to another when a cell value matches in the same row
I have two excels workbooks, let's say, wb01 and wb02. Suppose they have only one sheet, sh01 and sh02 respectively.

I need to synchronize sheets (sh01 and sh02) by copying the cell values (name and surname columns) from sh01 to sh02 when "Id" column match.

Example

sh01 in wb01

```<code>Id | name     | surname  | Dept
10 | John     | McCoy    | Logistics
21 | Liam     | Alloy    | Administration
40 | Peter    | Gregor   | Finance
42 | Albert   | Kein     | Business
50 | Kelly    | Braxton  | Logistics
60 | Isabella | O'Neill  | Finance
</code>```

sh02 in wb02

```<code>Id | name   | surname   | ext.
10 | David  | McCoy     | 1004
23 | Bren   | Summer    | 1230
40 | George | Brown     | 2400
42 | Astrid | Anderson  | 3312
50 | Kelly  | Braxton   | 1139
51 | Evelyn | Connor    | 4532
</code>```

I do not need to copy these cell values from sh02 to sh01, only from sh01 to sh02.
Also if "Id" cell value exists on wb01 but not in sh2, cell values name and surname should be copied to sh02 as a new row and the rest of fields must be kept empty/blank in sh02.

Taken into account above two sheets, after copying process, sh02 must be as below:

```<code>Id | name     | surname   | ext.
10 | John     | McCoy     | 1004
21 | Liam     | Alloy     |
23 | Bren     | Summer    | 1230
40 | Peter    | Gregor    | 2400
42 | Albert   | Kein      | 3312
50 | Kelly    | Braxton   | 1139
51 | Evelyn   | Connor    | 4532
60 | Isabella | O'Neill   |
</code>```

This copy process should be done on demand, I mean, when user clicks a button from sh02 in wb02. On button click, a macro in sh02 will be executed to start the copying process from sh01 to sh02.

答:
You've literally not provided any code that you've attempted to use to do this, more people would gladly help if you would have at least attempted to code it...
Nonetheless, you did not provide your sheet names, here is some code you can put to the test.  </p>

```<code>Sub CopyValue

Dim Wb1 As Workbook, wb2 As Workbook, lastrow As Long, lastrow2 As Long, counter As Integer

counter = 0
Set wb1 = Workbooks("wb01")
Set wb2 = Workbooks("wb02")
lastrow = wb1.Range("A" & .Rows.Count).End(xlUp).Row
lastrow2 = wb2.Range("A" & .Rows.Count).End(xlUp).Row

For x = 2 To lastrow
    For y = 2 To lastrow2
    If wb1.Sheets("abc").Cells(x,1).Value = wb2.Sheets("def").Cells(y,1).Value Then
        wb2.Sheets("def").Cells(y,2).Value =    wb1.Sheets("abc").Cells(x,2).Value
        wb2.Sheets("def").Cells(y,3).Value =    wb1.Sheets("abc").Cells(x,3).Value
    Else
        counter= counter +1
        wb2.Sheets("def").Cells(lastrow+counter,1).Value = wb1.sheets("abc").Cells(x,1).Value
        wb2.Sheets("def").Cells(lastrow+counter,2).Value = wb1.sheets("abc").Cells(x,2).Value
        wb2.Sheets("def").Cells(lastrow+counter,3).Value = wb1.sheets("abc").Cells(x,3).Value
    End If
Next y
Next x
End Sub
</code>```

Body:
I have two excels workbooks, let's say, wb01 and wb02. Suppose they have only one sheet, sh01 and sh02 respectively.

I need to synchronize sheets (sh01 and sh02) by copying the cell values (name and surname columns) from sh01 to sh02 when "Id" column match.

Example

sh01 in wb01

Id | name     | surname  | Dept
10 | John     | McCoy    | Logistics
21 | Liam     | Alloy    | Administration
40 | Peter    | Gregor   | Finance
42 | Albert   | Kein     | Business
50 | Kelly    | Braxton  | Logistics
60 | Isabella | O'Neill  | Finance

sh02 in wb02

Id | name   | surname   | ext.
10 | David  | McCoy     | 1004
23 | Bren   | Summer    | 1230
40 | George | Brown     | 2400
42 | Astrid | Anderson  | 3312
50 | Kelly  | Braxton   | 1139
51 | Evelyn | Connor    | 4532

I do not need to copy these cell values from sh02 to sh01, only from sh01 to sh02.
Also if "Id" cell value exists on wb01 but not in sh2, cell values name and surname should be copied to sh02 as a new row and the rest of fields must be kept empty/blank in sh02.

Taken into account above two sheets, after copying process, sh02 must be as below:

Id | name     | surname   | ext.
10 | John     | McCoy     | 1004
21 | Liam     | Alloy     |
23 | Bren     | Summer    | 1230
40 | Peter    | Gregor    | 2400
42 | Albert   | Kein      | 3312
50 | Kelly    | Braxton   | 1139
51 | Evelyn   | Connor    | 4532
60 | Isabella | O'Neill   |

This copy process should be done on demand, I mean, when user clicks a button from sh02 in wb02. On button click, a macro in sh02 will be executed to start the copying process from sh01 to sh02.

Body:
You've literally not provided any code that you've attempted to use to do this, more people would gladly help if you would have at least attempted to code it...
Nonetheless, you did not provide your sheet names, here is some code you can put to the test.

Sub CopyValue

Dim Wb1 As Workbook, wb2 As Workbook, lastrow As Long, lastrow2 As Long, counter As Integer

counter = 0
Set wb1 = Workbooks("wb01")
Set wb2 = Workbooks("wb02")
lastrow = wb1.Range("A" & .Rows.Count).End(xlUp).Row
lastrow2 = wb2.Range("A" & .Rows.Count).End(xlUp).Row

For x = 2 To lastrow
    For y = 2 To lastrow2
    If wb1.Sheets("abc").Cells(x,1).Value = wb2.Sheets("def").Cells(y,1).Value Then
        wb2.Sheets("def").Cells(y,2).Value =    wb1.Sheets("abc").Cells(x,2).Value
        wb2.Sheets("def").Cells(y,3).Value =    wb1.Sheets("abc").Cells(x,3).Value
    Else
        counter= counter +1
        wb2.Sheets("def").Cells(lastrow+counter,1).Value = wb1.sheets("abc").Cells(x,1).Value
        wb2.Sheets("def").Cells(lastrow+counter,2).Value = wb1.sheets("abc").Cells(x,2).Value
        wb2.Sheets("def").Cells(lastrow+counter,3).Value = wb1.sheets("abc").Cells(x,3).Value
    End If
Next y
Next x
End Sub


问:
How to have a radio checked on page load
I have a donation page using Liquid Shopify. I CANNOT change name="donation[amount_option]" (I do not have access to that file) so I need code that allows this to stay.

I want to have $250 automatically checked on load

My code

document.querySelector('input[name="donation[amount_option]"][value=250]').checked = true;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="radio-inline donation-v2-amounts padbottommore">
  <span>
    <input id="donation_amount_25" type="radio" name="donation[amount_option]" class="donation_amount_option" value="25">
    <label for="donation_amount_25" class="radio">$25</label>
  </span>

  <span>
    <input id="donation_amount_250" type="radio" name="donation[amount_option]" class="donation_amount_option" value="250">
    <label for="donation_amount_250" class="radio">$250</label>
  </span>

  <span>
    <input id="donation_amount_1000" type="radio" name="donation[amount_option]" class="donation_amount_option" value="1000">
    <label for="donation_amount_1000" class="radio">$1,000</label>
  </span>
</div></code>```

答:
Just add the "checked" keyword to the end of the input.</p>

```<code><input id="donation_amount_250" type="radio" name="donation[amount_option]" class="donation_amount_option" value="250" checked>
</code>```

Body:
I have a donation page using Liquid Shopify. I CANNOT change name="donation[amount_option]" (I do not have access to that file) so I need code that allows this to stay.

I want to have $250 automatically checked on load

My code

document.querySelector('input[name="donation[amount_option]"][value=250]').checked = true;

    <input id="donation_amount_25" type="radio" name="donation[amount_option]" class="donation_amount_option" value="25">
    $25

    <input id="donation_amount_250" type="radio" name="donation[amount_option]" class="donation_amount_option" value="250">
    $250

    <input id="donation_amount_1000" type="radio" name="donation[amount_option]" class="donation_amount_option" value="1000">
    $1,000

Body:
Just add the "checked" keyword to the end of the input.

<input id="donation_amount_250" type="radio" name="donation[amount_option]" class="donation_amount_option" value="250" checked>


问:
Modifying a data structure while iterating over it
What happens when you add elements to a data structure such as a vector while
iterating over it. Can I not do this?

I tried this and it breaks:

```<code>int main() {
    vector<int> x = { 1, 2, 3 };

    int j = 0;
    for (auto it = x.begin(); it != x.end(); ++it) {
        x.push_back(j);
        j++;
        cout << j << " .. ";
    }
}
</code>```

答:
It's a bad idea in general, because if the vector is resized, the iterator will become invalid (it's wrapping a pointer into the vector's memory).

It's also not clear what your code is really trying to do.  If the iterator somehow didn't become invalid (suppose it was implemented as an index), I'd expect you to have an infinite loop there - the end would never be reached because you're always adding elements.

Assuming you want to loop over the original elements, and add one for each, one solution would be to add the new elements to a second vector, and then concatenate that at the end:

```<code>vector<int> temp;

// ...

// Inside loop, do this:
temp.push_back(j);

// ...

// After loop, do this to insert all new elements onto end of x
x.insert(x.end(), temp.begin(), temp.end());
</code>```

Body:
What happens when you add elements to a data structure such as a vector while
iterating over it. Can I not do this?

I tried this and it breaks:

int main() {
    vector<int> x = { 1, 2, 3 };

    int j = 0;
    for (auto it = x.begin(); it != x.end(); ++it) {
        x.push_back(j);
        j++;
        cout << j << " .. ";
    }
}

Body:
It's a bad idea in general, because if the vector is resized, the iterator will become invalid (it's wrapping a pointer into the vector's memory).

It's also not clear what your code is really trying to do.  If the iterator somehow didn't become invalid (suppose it was implemented as an index), I'd expect you to have an infinite loop there - the end would never be reached because you're always adding elements.

Assuming you want to loop over the original elements, and add one for each, one solution would be to add the new elements to a second vector, and then concatenate that at the end:

vector<int> temp;

// ...

// Inside loop, do this:
temp.push_back(j);

// ...

// After loop, do this to insert all new elements onto end of x
x.insert(x.end(), temp.begin(), temp.end());


答:
I'm a bit rusty with Python, But I would suggest changing draw to accept an array of elements.

So for example, in setup and can generate an array of droplets by doing:

def setup():
  size(500,500) #Idk what this does, I assume its another function somewhere else in your code
  droplets = [] #The array of droplets we want to render
  for x in range(6): #6 is the number of droplets we want.
    droplets.append(drop())

#Pass droplets into draw.
def draw(entities):
  background(255,255,255) #Again, IDK what this does but its in your code. I assume it is another function somewhere.
  for droplet in entities: #Goes through ALL the droplets in the list you passed.
    droplet.fall() #Calls these methods on every droplet in the array.
    droplet.show()
```

This is untested, but from here you would somehow pass the droplets array into draw and BOOM you have a bunch of droplets being rendered every draw cycle. I would suggest NOT using global variables. Its just bad practice. You should have another function somewhere that runs all of this, I assume on a time for the draw cycle.

Title: Python Processing: How to call multiple of the same class

Body:
I'm a bit rusty with Python, But I would suggest changing draw to accept an array of elements.

So for example, in setup and can generate an array of droplets by doing:

def setup():
  size(500,500) #Idk what this does, I assume its another function somewhere else in your code
  droplets = [] #The array of droplets we want to render
  for x in range(6): #6 is the number of droplets we want.
    droplets.append(drop())

#Pass droplets into draw.
def draw(entities):
  background(255,255,255) #Again, IDK what this does but its in your code. I assume it is another function somewhere.
  for droplet in entities: #Goes through ALL the droplets in the list you passed.
    droplet.fall() #Calls these methods on every droplet in the array.
    droplet.show()

This is untested, but from here you would somehow pass the droplets array into draw and BOOM you have a bunch of droplets being rendered every draw cycle. I would suggest NOT using global variables. Its just bad practice. You should have another function somewhere that runs all of this, I assume on a time for the draw cycle.


问:
Spring - Thymeleaf: Exception processing template
I'm following the a book Spring in Action 5th ed., but I believe that is presents a bug.

This is the GitHub of the book. I'm arrived on chap 3 tacos-jdbc
source of code

When submit my order a sudden error appears:

and in this way on the terminal:

2019-05-25 16:58:18.164 ERROR 11777 --- [nio-8080-exec-7] org.thymeleaf.TemplateEngine             :
    [THYMELEAF][http-nio-8080-exec-7] Exception processing template
    "orderForm": An error happened during template parsing (template:
    "class path resource [templates/orderForm.html]")

org.thymeleaf.exceptions.TemplateInputException: An error happened
  during template parsing (template: "class path resource
  [templates/orderForm.html]")

OrderController:

```<code>@Controller
@RequestMapping("/orders")
@SessionAttributes("order")
public class OrderController {

    private OrderRepository orderRepo;

    public OrderController(OrderRepository orderRepo) {
        this.orderRepo = orderRepo;
    }

    @GetMapping("/current")
    public String orderForm() {
        return "orderForm";
    }

    @PostMapping
    public String processOrder(@Valid Order order, Errors errors,
                               SessionStatus sessionStatus) {
        if (errors.hasErrors()) {
            return "orderForm";
        }

        orderRepo.save(order);
        sessionStatus.setComplete();

        return "redirect:/";
    }

}
</code>```

and orderForm:

<!DOCTYPE html>

    <title>Taco Cloud</title>
    <link rel="stylesheet" th:href="@{/styles.css}" />

<form method="POST" th:action="@{/orders}" th:object="${order}">

Order your taco creations!

    Design another taco

        Please correct the problems below and resubmit.

Deliver my taco masterpieces to...

    Name:
    <input type="text" th:field="*{name}"/>

    Street address:
    <input type="text" th:field="*{street}"/>

    City:
    <input type="text" th:field="*{city}"/>

    State:
    <input type="text" th:field="*{state}"/>

    Zip code:
    <input type="text" th:field="*{zip}"/>

    Credit Card #:
    <input type="text" th:field="*{ccNumber}"/>
    CC Num Error

    Expiration:
    <input type="text" th:field="*{ccExpiration}"/>

    CVV:
    <input type="text" th:field="*{ccCVV}"/>

    <input type="submit" value="Submit order"/>
</form>

```

答:
I fixed with this code adding delivery prefix:

```<code>    <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Taco Cloud</title>
    <link rel="stylesheet" th:href="@{/styles.css}" />
</head>

<body>

<form method="POST" th:action="@{/orders}" th:object="${order}">
    <h1>Order your taco creations!</h1>

    <img th:src="@{/images/TacoCloud.png}"/>

    <h3>Your tacos in this order:</h3>
    <a th:href="@{/design}" id="another">Design another taco</a><br/>
    <ul>
        <li th:each="taco : ${order.tacos}"><span th:text="${taco.name}">taco name</span></li>
    </ul>

    <div th:if="${#fields.hasErrors()}">
        <span class="validationError">
        Please correct the problems below and resubmit.
        </span>
    </div>

    <h3>Deliver my taco masterpieces to...</h3>
    <label for="deliveryName">Name: </label>
    <input type="text" th:field="*{deliveryName}"/>
    <span class="validationError"
          th:if="${#fields.hasErrors('deliveryName')}"
          th:errors="*{deliveryName}">Name Error</span>
    <br/>

    <label for="deliveryStreet">Street address: </label>
    <input type="text" th:field="*{deliveryStreet}"/>
    <span class="validationError"
          th:if="${#fields.hasErrors('deliveryStreet')}"
          th:errors="*{deliveryStreet}">Street Error</span>
    <br/>

    <label for="deliveryCity">City: </label>
    <input type="text" th:field="*{deliveryCity}"/>
    <span class="validationError"
          th:if="${#fields.hasErrors('deliveryCity')}"
          th:errors="*{deliveryCity}">City Error</span>
    <br/>

    <label for="deliveryState">State: </label>
    <input type="text" th:field="*{deliveryState}"/>
    <span class="validationError"
          th:if="${#fields.hasErrors('deliveryState')}"
          th:errors="*{deliveryState}">State Error</span>
    <br/>

    <label for="deliveryZip">Zip code: </label>
    <input type="text" th:field="*{deliveryZip}"/>
    <span class="validationError"
          th:if="${#fields.hasErrors('deliveryZip')}"
          th:errors="*{deliveryZip}">Zip Error</span>
    <br/>

    <h3>Here's how I'll pay...</h3>
    <label for="ccNumber">Credit Card #: </label>
    <input type="text" th:field="*{ccNumber}"/>
    <span class="validationError"
          th:if="${#fields.hasErrors('ccNumber')}"
          th:errors="*{ccNumber}">CC Num Error</span>
    <br/>

    <label for="ccExpiration">Expiration: </label>
    <input type="text" th:field="*{ccExpiration}"/>
    <span class="validationError"
          th:if="${#fields.hasErrors('ccExpiration')}"
          th:errors="*{ccExpiration}">CC Num Error</span>
    <br/>

    <label for="ccCVV">CVV: </label>
    <input type="text" th:field="*{ccCVV}"/>
    <span class="validationError"
          th:if="${#fields.hasErrors('ccCVV')}"
          th:errors="*{ccCVV}">CC Num Error</span>
    <br/>

    <input type="submit" value="Submit order"/>
</form>

</body>
</html>
</code>```

Body:
I'm following the a book Spring in Action 5th ed., but I believe that is presents a bug.

This is the GitHub of the book. I'm arrived on chap 3 tacos-jdbc
source of code

When submit my order a sudden error appears:

and in this way on the terminal:

2019-05-25 16:58:18.164 ERROR 11777 --- [nio-8080-exec-7] org.thymeleaf.TemplateEngine             :
    [THYMELEAF][http-nio-8080-exec-7] Exception processing template
    "orderForm": An error happened during template parsing (template:
    "class path resource [templates/orderForm.html]")

org.thymeleaf.exceptions.TemplateInputException: An error happened
  during template parsing (template: "class path resource
  [templates/orderForm.html]")

OrderController:

@Controller
@RequestMapping("/orders")
@SessionAttributes("order")
public class OrderController {

    private OrderRepository orderRepo;

    public OrderController(OrderRepository orderRepo) {
        this.orderRepo = orderRepo;
    }

    @GetMapping("/current")
    public String orderForm() {
        return "orderForm";
    }

    @PostMapping
    public String processOrder(@Valid Order order, Errors errors,
                               SessionStatus sessionStatus) {
        if (errors.hasErrors()) {
            return "orderForm";
        }

        orderRepo.save(order);
        sessionStatus.setComplete();

        return "redirect:/";
    }

}

and orderForm:

<!DOCTYPE html>

    <title>Taco Cloud</title>
    <link rel="stylesheet" th:href="@{/styles.css}" />

<form method="POST" th:action="@{/orders}" th:object="${order}">

Order your taco creations!

    Design another taco

        Please correct the problems below and resubmit.

Deliver my taco masterpieces to...

    Name:
    <input type="text" th:field="*{name}"/>

    Street address:
    <input type="text" th:field="*{street}"/>

    City:
    <input type="text" th:field="*{city}"/>

    State:
    <input type="text" th:field="*{state}"/>

    Zip code:
    <input type="text" th:field="*{zip}"/>

    Credit Card #:
    <input type="text" th:field="*{ccNumber}"/>
    CC Num Error

    Expiration:
    <input type="text" th:field="*{ccExpiration}"/>

    CVV:
    <input type="text" th:field="*{ccCVV}"/>

    <input type="submit" value="Submit order"/>
</form>

Body:
I fixed with this code adding delivery prefix:

    <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Taco Cloud</title>
    <link rel="stylesheet" th:href="@{/styles.css}" />
</head>

<body>

<form method="POST" th:action="@{/orders}" th:object="${order}">
    <h1>Order your taco creations!</h1>

    <img th:src="@{/images/TacoCloud.png}"/>

    <h3>Your tacos in this order:</h3>
    <a th:href="@{/design}" id="another">Design another taco</a><br/>
    <ul>
        <li th:each="taco : ${order.tacos}"><span th:text="${taco.name}">taco name</span></li>
    </ul>

    <div th:if="${#fields.hasErrors()}">
        <span class="validationError">
        Please correct the problems below and resubmit.
        </span>
    </div>

    <h3>Deliver my taco masterpieces to...</h3>
    <label for="deliveryName">Name: </label>
    <input type="text" th:field="*{deliveryName}"/>
    <span class="validationError"
          th:if="${#fields.hasErrors('deliveryName')}"
          th:errors="*{deliveryName}">Name Error</span>
    <br/>

    <label for="deliveryStreet">Street address: </label>
    <input type="text" th:field="*{deliveryStreet}"/>
    <span class="validationError"
          th:if="${#fields.hasErrors('deliveryStreet')}"
          th:errors="*{deliveryStreet}">Street Error</span>
    <br/>

    <label for="deliveryCity">City: </label>
    <input type="text" th:field="*{deliveryCity}"/>
    <span class="validationError"
          th:if="${#fields.hasErrors('deliveryCity')}"
          th:errors="*{deliveryCity}">City Error</span>
    <br/>

    <label for="deliveryState">State: </label>
    <input type="text" th:field="*{deliveryState}"/>
    <span class="validationError"
          th:if="${#fields.hasErrors('deliveryState')}"
          th:errors="*{deliveryState}">State Error</span>
    <br/>

    <label for="deliveryZip">Zip code: </label>
    <input type="text" th:field="*{deliveryZip}"/>
    <span class="validationError"
          th:if="${#fields.hasErrors('deliveryZip')}"
          th:errors="*{deliveryZip}">Zip Error</span>
    <br/>

    <h3>Here's how I'll pay...</h3>
    <label for="ccNumber">Credit Card #: </label>
    <input type="text" th:field="*{ccNumber}"/>
    <span class="validationError"
          th:if="${#fields.hasErrors('ccNumber')}"
          th:errors="*{ccNumber}">CC Num Error</span>
    <br/>

    <label for="ccExpiration">Expiration: </label>
    <input type="text" th:field="*{ccExpiration}"/>
    <span class="validationError"
          th:if="${#fields.hasErrors('ccExpiration')}"
          th:errors="*{ccExpiration}">CC Num Error</span>
    <br/>

    <label for="ccCVV">CVV: </label>
    <input type="text" th:field="*{ccCVV}"/>
    <span class="validationError"
          th:if="${#fields.hasErrors('ccCVV')}"
          th:errors="*{ccCVV}">CC Num Error</span>
    <br/>

    <input type="submit" value="Submit order"/>
</form>

</body>
</html>


问:
Kotlin float/int indirect comparison
For a project I am trying to implement a Bit class, that does all the usual stuff a bit should do.

The constructor should be able to take any Number and set the Bit's internal state to 0 if the given value is 0, else set it to 1.

All works for integer inputs but when I get to float... apparently 0.0 is not equal to 0.

```<code>class Bit(value: Number) {
    var value: Int = (value != 0).toInt() // I implemented Bool-to-Int myself
}
</code>```

Now the problem:

```<code>println(Bit(0).value)   // Prints 0
println(Bit(0f).value)  // Prints 1
</code>```

I thought this was some kind of approximation error, but when I tried print(0f != 0) I got Operator '!=' cannot be applied to 'Float' and 'Int'. However it had no issue comparing the numbers trough the constructor.

I feel there is some hidden type-casting magic I'm not aware of here so my question is basically "why is this not behaving as intended and what would be an elegant way to make it behave as intended?"

答:
I can't tell you exactly why it's not behaving as you expect, but I can give you an easy fix!

The Number interface isn't as powerful as you might like, but the main thing it does give you is a way to convert its value to any of the standard numeric types.  You can use that like this:

```<code>class Bit(value: Number) {
    var value = if (value.toDouble() == 0.0) 0 else 1
}
</code>```

This will work for all Number implementations: Byte, Double, Float, Int, Long, Short, AtomicInteger, AtomicLong, BigDecimal, Striped64, and any others you write or import.

(Whatever you do, I suggest you also override value's setter, to make sure that it only ever holds 0 or 1.)

Title: Kotlin float/int indirect comparison

Body:
For a project I am trying to implement a Bit class, that does all the usual stuff a bit should do.

The constructor should be able to take any Number and set the Bit's internal state to 0 if the given value is 0, else set it to 1.

All works for integer inputs but when I get to float... apparently 0.0 is not equal to 0.

class Bit(value: Number) {
    var value: Int = (value != 0).toInt() // I implemented Bool-to-Int myself
}

Now the problem:

println(Bit(0).value)   // Prints 0
println(Bit(0f).value)  // Prints 1

I thought this was some kind of approximation error, but when I tried print(0f != 0) I got Operator '!=' cannot be applied to 'Float' and 'Int'. However it had no issue comparing the numbers trough the constructor.

I feel there is some hidden type-casting magic I'm not aware of here so my question is basically "why is this not behaving as intended and what would be an elegant way to make it behave as intended?"

Body:
I can't tell you exactly why it's not behaving as you expect, but I can give you an easy fix!

The Number interface isn't as powerful as you might like, but the main thing it does give you is a way to convert its value to any of the standard numeric types.  You can use that like this:

class Bit(value: Number) {
    var value = if (value.toDouble() == 0.0) 0 else 1
}

This will work for all Number implementations: Byte, Double, Float, Int, Long, Short, AtomicInteger, AtomicLong, BigDecimal, Striped64, and any others you write or import.

(Whatever you do, I suggest you also override value's setter, to make sure that it only ever holds 0 or 1.)


问:
Make single colored regions in image smooth in MATLAB
I have written some algorithms for an image but the output has some differences from my ground truth which you can see in image below:

I don't want to make it exactly like the 2nd image but since my images is kinda simple I think there are some filters to at least remove those white curves inside the circles.

Can you suggest me any?

Thanks

答:
You can try using morphological operations like imclose

You need to play with it, to get the desired result.

I used imbinarize to convert from uint8 to black/white.

```<code>I = imread('https://i.stack.imgur.com/r8XO7.png'); %Read image directly from URL.
R = I(:,:,1);G = I(:,:,2);B = I(:,:,3);
R = imbinarize(255 - R);G = imbinarize(255 - G);B = imbinarize(255 - B); %Convert to binary (use 255-R to inverse polarity because background is white).
SE = strel('disk', 15);
R = imclose(R, SE); %Close opreation.
G = imclose(G, SE);
B = imclose(B, SE);
J = im2uint8(cat(3, ~R, ~G, ~B)); %Use ~R to invert to original polarity.
figure;imshow(J);
</code>```

Almost...

[It's weird that image is reversed up/down].

Body:
You can try using morphological operations like imclose

You need to play with it, to get the desired result.

I used imbinarize to convert from uint8 to black/white.

I = imread('https://i.stack.imgur.com/r8XO7.png'); %Read image directly from URL.
R = I(:,:,1);G = I(:,:,2);B = I(:,:,3);
R = imbinarize(255 - R);G = imbinarize(255 - G);B = imbinarize(255 - B); %Convert to binary (use 255-R to inverse polarity because background is white).
SE = strel('disk', 15);
R = imclose(R, SE); %Close opreation.
G = imclose(G, SE);
B = imclose(B, SE);
J = im2uint8(cat(3, ~R, ~G, ~B)); %Use ~R to invert to original polarity.
figure;imshow(J);

Almost...

[It's weird that image is reversed up/down].


答:
```<code>$(document).ready(function(){
    $('#donation_amount_250').prop('checked',true);
});
</code>```

Title: How to have a radio checked on page load


问:
Lotus notes email in multiple folders
Is it possible to place an email into multiple lotus notes folders without creating a copy of the email? Essitiantly, I am looking for a way to create a shortcut to the same email in a different folder. For example, I have many emails relating to expenses. I would like to place the email in a folder I created called 'Airport Expenses', as well as in a folder I created called 'Business Travel DD/MM/YYYY', without duplicating the physical storage of the file. </p>

答: Placing an email into multiple folders, in Notes, does not create a copy of the email - it simply adds a reference to the email to each folder. (Deleting the email will delete the one and only copy of the email, and remove references from all folders).  </p>

Title: Lotus notes email in multiple folders


问:
Using reduce to delete even numbers in an object
I'm given an array of numbers. I have created an object named counts, whose keys are the numbers and values the amount of times those numbers appear in the array. Can't work out how to use reduce to delete the even counts of the numbers.

```<code>A =  [ 20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5 ]

n =  5

function findOdd(A) {

  let counts = {};

  for (let i = 0; i < A.length; i++) {
    let num = A[i];
    counts[num] = counts[num] ? counts[num] + 1 : 1;
  }

//counts -> { '1': 2, '2': 2, '3': 2, '4': 2, '5': 3, '20': 2, '-1': 2, '-2': 2 }

  const answer = Object.keys(counts).reduce((object, key) => {
    if (key % 2 !== 0) {
      object[key] = counts[key];
    }
    return object;
  }, {})

  return answer;
</code>```

Must return the key of the odd count.

SOLUTION:

```<code>function findOdd(A) {
  const counts = {};
  for (let i = 0; i < A.length; i++) {
    let num = A[i];
    counts[num] = counts[num] ? counts[num] + 1 : 1;
  }
  Object.keys(counts).forEach(key => {
    if(counts[key] % 2 === 0) {
    delete counts[key];
    }
  });
  return Number(Object.keys(counts));
}
</code>```

答:
I know there are already great answers but as the question said "using reduce" I thought it'd be fun to try doing this using only reduce:

```<code>const findOdd = arr => arr.reduce((acc, d, i, list) => {
    if (!acc[d]) {
        acc[d] = 0;
    }

    acc[d]++;

    if (i === list.length - 1) {
        return Object.keys(acc)
            .reduce((subAcc, key) => ({
                ...subAcc,
                ...(acc[key] % 2 === 0 ? {} : {
                    [key]: acc[key]
                })
            }), {})
    }
    return acc;
}, {})
</code>```

Body:
I'm given an array of numbers. I have created an object named counts, whose keys are the numbers and values the amount of times those numbers appear in the array. Can't work out how to use reduce to delete the even counts of the numbers.

A =  [ 20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5 ]

n =  5

function findOdd(A) {

  let counts = {};

  for (let i = 0; i  { '1': 2, '2': 2, '3': 2, '4': 2, '5': 3, '20': 2, '-1': 2, '-2': 2 }

  const answer = Object.keys(counts).reduce((object, key) => {
    if (key % 2 !== 0) {
      object[key] = counts[key];
    }
    return object;
  }, {})

  return answer;

Must return the key of the odd count.

SOLUTION:

function findOdd(A) {
  const counts = {};
  for (let i = 0; i  {
    if(counts[key] % 2 === 0) {
    delete counts[key];
    }
  });
  return Number(Object.keys(counts));
}

Body:
I know there are already great answers but as the question said "using reduce" I thought it'd be fun to try doing this using only reduce:

const findOdd = arr => arr.reduce((acc, d, i, list) => {
    if (!acc[d]) {
        acc[d] = 0;
    }

    acc[d]++;

    if (i === list.length - 1) {
        return Object.keys(acc)
            .reduce((subAcc, key) => ({
                ...subAcc,
                ...(acc[key] % 2 === 0 ? {} : {
                    [key]: acc[key]
                })
            }), {})
    }
    return acc;
}, {})


问:
How do I tell Gradle to use specific JDK version?
I can't figure out to get this working.

Scenario:

I have an application built with gradle

The application uses JavaFX

What I want

Use a variable (defined per developer machine) which points to an installation of a JDK which will be used for building the whole application / tests / ...

I thought about having the gradle.properties file, defining the variable. Something like

```<code>JAVA_HOME_FOR_MY_PROJECT=<path to my desired JDK>
</code>```

What I don't want

point JAVA_HOME to the desired JDK

I could live with many suggestions:

a solution that defines a system environment variable which I'm able to check in my build.gradle script

a variable defined in gradle.properties

overriding the JAVA_HOME variable only for the build context (something like use JAVA_HOME=<my special JDK path defined somewhere else defined>)

something else I didn't think about

Question:

How to wire a variable (how ever defined, as variable in the gradle.properties, system environment variable, ...) to the build process?

I have more than one JDK7 available and need to point to a special version (minimum JDK_u version).

Any answer is appreciated and I'm thankful for every hint to the right direction.

答:
If you just want to set it once to run a specific command:</p>

```<code>JAVA_HOME=/usr/lib/jvm/java-11-oracle/ gw build
</code>```

Body:
I can't figure out to get this working.

Scenario:

I have an application built with gradle

The application uses JavaFX

What I want

Use a variable (defined per developer machine) which points to an installation of a JDK which will be used for building the whole application / tests / ...

I thought about having the gradle.properties file, defining the variable. Something like

JAVA_HOME_FOR_MY_PROJECT=<path to my desired JDK>

What I don't want

point JAVA_HOME to the desired JDK

I could live with many suggestions:

a solution that defines a system environment variable which I'm able to check in my build.gradle script

a variable defined in gradle.properties

overriding the JAVA_HOME variable only for the build context (something like use JAVA_HOME=<my special JDK path defined somewhere else defined>)

something else I didn't think about

Question:

How to wire a variable (how ever defined, as variable in the gradle.properties, system environment variable, ...) to the build process?

I have more than one JDK7 available and need to point to a special version (minimum JDK_u version).

Any answer is appreciated and I'm thankful for every hint to the right direction.

Body:
If you just want to set it once to run a specific command:

JAVA_HOME=/usr/lib/jvm/java-11-oracle/ gw build


问:
Issues with function output using if/else if
I am (new to c++) trying to create a power function manually and came across the issue where if the power inputted is negative, the result is always being printed out as 0. I suspect that one of the variables might not be declared properly, can you help please</p>

```<code>#include <iostream>

using namespace std;

int power;
float result = 1, base;

int firs();
void pow(int base, int power);

int main()
{
    firs();
    pow(base, power);

    return 0;
}

int firs()
{
    cout << "Enter a base input: ";
    cin >> base;

    cout << "Enter a power input: ";
    cin >> power;

    return base, power;
}

void pow(int base, int power)
{
    cout << "With a given base of " << base << " and a given power of " << power << endl;

    if (power > 0)
    {
        for (int i = 0; i < power; i++)
        {
            result = result*base;
        }

    cout << "The final answer is: " << result;

    }
    else if (power < 0)
    {
        for (int i = 0; i > power; i--)
        {
            result = result*(1/base);
        }

    cout << "The final answer is: " << result;
    }
    else
    {
        cout << "The final answer is: " << 1;
    }
}
</code>```

答:
The problem lies in the following code section:

```<code>    else if (power < 0)
    {
        for (int i = 0; i > power; i--)
        {
            result = result*(1/base);
        }
    }
</code>```

When (1/base) is calculated, because both 1 and base are int, the result will also be casted into int, which is 0 (if base is greater than 1). You can avoid this by either defining base as float, using 1.0 instead of 1, or using explicit type casting:

```<code>    else if (power < 0)
    {
        for (int i = 0; i > power; i--)
        {
            result = result*(1/(float) base);
        }
    }
</code>```

Also, return base, power only returns power.

Body:
I am (new to c++) trying to create a power function manually and came across the issue where if the power inputted is negative, the result is always being printed out as 0. I suspect that one of the variables might not be declared properly, can you help please

#include <iostream>

using namespace std;

int power;
float result = 1, base;

int firs();
void pow(int base, int power);

int main()
{
    firs();
    pow(base, power);

    return 0;
}

int firs()
{
    cout << "Enter a base input: ";
    cin >> base;

    cout << "Enter a power input: ";
    cin >> power;

    return base, power;
}

void pow(int base, int power)
{
    cout << "With a given base of " << base << " and a given power of " << power << endl;

    if (power > 0)
    {
        for (int i = 0; i < power; i++)
        {
            result = result*base;
        }

    cout << "The final answer is: " << result;

    }
    else if (power < 0)
    {
        for (int i = 0; i > power; i--)
        {
            result = result*(1/base);
        }

    cout << "The final answer is: " << result;
    }
    else
    {
        cout << "The final answer is: " << 1;
    }
}

Body:
The problem lies in the following code section:

    else if (power < 0)
    {
        for (int i = 0; i > power; i--)
        {
            result = result*(1/base);
        }
    }

When (1/base) is calculated, because both 1 and base are int, the result will also be casted into int, which is 0 (if base is greater than 1). You can avoid this by either defining base as float, using 1.0 instead of 1, or using explicit type casting:

    else if (power < 0)
    {
        for (int i = 0; i > power; i--)
        {
            result = result*(1/(float) base);
        }
    }

Also, return base, power only returns power.


问:
ASP.Net and log4Net - Compatible Framework error on adding of Dll
I cannot add log4Net as a reference to my new .Net project.  I've researched this, and all the answers say to change the Target framework from ".Net Framework 4 (Client Profile)" to ".Net Framework 4" or some variation.

Well, my project is already ".Net Framework 4".  And I don't even have the Client Profile type in my target framework drop down.

To be clear, I DO have this option on other projects, but just not on the last one that I made.  I can't remember if I made this a new "Project" or "Website" -- I'm assuming I chose "Project" when I made it.

When I try to add log4net, I get this error:

```<code>"log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" is incompatible with .NET Framework 4

In order to add it you should to change the project's target to a compatible framework first.
</code>```

Yes, even that incorrect grammar is from the message "you should to change"

I'm missing something fundamental, but for the life of me I can't tell between my projects what is different about this one.

答:
Log4net unfortunately is only officially supported for the.Net versions below, but the note below says it should work fine on backward compatible framework versions.  I've had it work on .Net 3.5, but not 4.0 yet.

Microsoft .NET Framework 1.0 (1.0.3705)

Microsoft .NET Framework
1.1 (1.1.4322)

Microsoft .NET Framework 2.0 (2.0.50727)

Microsoft
.NET Compact Framework 1.0

Mono 1.0

Mono 2.0

Microsoft Shared Source CLI
   1.0
CLI 1.0

Compatible Note: Due to the .NET frameworks support for
   backward compatibility log4net will
   run on future versions of the
   runtimes listed above.

Body:
I cannot add log4Net as a reference to my new .Net project.  I've researched this, and all the answers say to change the Target framework from ".Net Framework 4 (Client Profile)" to ".Net Framework 4" or some variation.

Well, my project is already ".Net Framework 4".  And I don't even have the Client Profile type in my target framework drop down.

To be clear, I DO have this option on other projects, but just not on the last one that I made.  I can't remember if I made this a new "Project" or "Website" -- I'm assuming I chose "Project" when I made it.

When I try to add log4net, I get this error:

"log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" is incompatible with .NET Framework 4

In order to add it you should to change the project's target to a compatible framework first.

Yes, even that incorrect grammar is from the message "you should to change"

I'm missing something fundamental, but for the life of me I can't tell between my projects what is different about this one.


问:
How to use Bottom Navigation with Navigation Drawer
I am trying to add navigation drawer with bottom navigation view. I have full screen activities for all bottom navigation view fragments. And I have app icon top left side. I want to open navigation drawer when user click on that icon. So How can I implement that?

I tried with DrawerLayout. But it includes the toolbar. And I tried to open new Activities on click of item of Navigation drawer but it gives IllegleStateException.

答:
I shared the following code below. You have to put the hamburger menu icon for Nav Drawer in the toolbar and a NavigationView inside the DrawerLayout which has a child (ListView, RecyclerView, ExpandableListView etc.) to be filled programmatically or you can just set static items in the NavigationView by setting the menu in NavigationView. Hope that helps. Do ask if you have any more queries.</p>

```<code><androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorActivityBackground"
        android:descendantFocusability="beforeDescendants"
        android:focusableInTouchMode="true"
        android:layoutDirection="locale"
        android:orientation="vertical"
        android:textDirection="locale">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/topbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/colorPrimary"
                app:contentInsetEnd="0dp"
                app:contentInsetLeft="0dp"
                app:contentInsetRight="0dp"
                app:contentInsetStart="0dp"/>
        </RelativeLayout>
    </FrameLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        android:maxWidth="320dp">

        <ExpandableListView
            android:id="@+id/navList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:animateLayoutChanges="true"
            android:background="@color/white"
            android:groupIndicator="@null" />

    </com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>
</code>```

Body:
I shared the following code below. You have to put the hamburger menu icon for Nav Drawer in the toolbar and a NavigationView inside the DrawerLayout which has a child (ListView, RecyclerView, ExpandableListView etc.) to be filled programmatically or you can just set static items in the NavigationView by setting the menu in NavigationView. Hope that helps. Do ask if you have any more queries.

<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorActivityBackground"
        android:descendantFocusability="beforeDescendants"
        android:focusableInTouchMode="true"
        android:layoutDirection="locale"
        android:orientation="vertical"
        android:textDirection="locale">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/topbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/colorPrimary"
                app:contentInsetEnd="0dp"
                app:contentInsetLeft="0dp"
                app:contentInsetRight="0dp"
                app:contentInsetStart="0dp"/>
        </RelativeLayout>
    </FrameLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        android:maxWidth="320dp">

        <ExpandableListView
            android:id="@+id/navList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:animateLayoutChanges="true"
            android:background="@color/white"
            android:groupIndicator="@null" />

    </com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>


问:
How to pull while deployment in ansible
I am using Ansible for configuration management and the following task to clone a Git repo:

```<code># Example git checkout from Ansible Playbooks
- git: repo=git://foosball.example.org/path/to/repo.git
       dest=/srv/checkout
       version=release-0.22
</code>```

This clones the repo with the particular version.

Does it do a git pull when run again if the repo already exists? Or does it simply clone the repo all the time? How to do a git pull in Ansible if the repo already exists and how can we run a specific command if the repo exists and same if the repo is cloned for the first time?

答:
This works for me using a shell command:

```<code>- hosts: myserver
  become: yes
  tasks:
  - name: pull changes
    shell: chdir=/path/whereis/myrepo git pull https://mygituser:mypassword@bitbucket.org/company/myrepo.git master
</code>```

i had to specify the remote url using user and password because it hangs with simple "git pull".

Title: How to pull while deployment in ansible

Body:
I am using Ansible for configuration management and the following task to clone a Git repo:

# Example git checkout from Ansible Playbooks
- git: repo=git://foosball.example.org/path/to/repo.git
       dest=/srv/checkout
       version=release-0.22

This clones the repo with the particular version.

Does it do a git pull when run again if the repo already exists? Or does it simply clone the repo all the time? How to do a git pull in Ansible if the repo already exists and how can we run a specific command if the repo exists and same if the repo is cloned for the first time?

Body:
This works for me using a shell command:

- hosts: myserver
  become: yes
  tasks:
  - name: pull changes
    shell: chdir=/path/whereis/myrepo git pull https://mygituser:mypassword@bitbucket.org/company/myrepo.git master

i had to specify the remote url using user and password because it hangs with simple "git pull".


问:
How can you select value based on three horizontal and vertical criteria?
I'm trying to organize the data from a colleague by putting it all in one tab, rather than having a separate tab for each week. What I currently have is this, for each week we are tracking.

I would like to organize it as follows to make the analysis part easier:

Is there a function that can grab the data from the original tab to put it in the above-mentioned format?

I've tried using SUMPRODUCT, but it returns duplicate values after the first correct value.

```<code>=SUMPRODUCT(('Week of 11th March'!$B$2:$B$19=$E$1)*('Week of 11th March'!$A$2:$A$19=$B4)*('Week of 11th March'!$C$1:$N$1=$C4)*('Week of 11th March'!$C$2:$C$19))
</code>```

Any help would be greatly appreciated.

答:
delete everything and paste this into A2 cell:

```<code>=ARRAYFORMULA({SPLIT(TRANSPOSE(SPLIT(TEXTJOIN( , 1, "♠"&TEXT(
 FILTER('Week of 18th March'!A3:A20, 'Week of 18th March'!B3:B20="Female"),
 "m/d/yyyy")&"♦"&TEXT('Week of 18th March'!C1:M1, "h:mm am/pm")&"♦"&
 QUERY('Week of 18th March'!A3:M20,
 "select C,D,E,F,G,H,I,J,K,L,M where B='Female'", 0)), "♠")), "♦"),
 INDEX(SPLIT(TRANSPOSE(SPLIT(TEXTJOIN( , 1, "♠"&TEXT(
 FILTER('Week of 18th March'!A3:A20, 'Week of 18th March'!B3:B20="Male"),
 "m/d/yyyy")&"♦"&TEXT('Week of 18th March'!C1:M1, "h:mm am/pm")&"♦"&
 QUERY('Week of 18th March'!A3:M20,
 "select C,D,E,F,G,H,I,J,K,L,M where B='Male'", 0)), "♠")), "♦"), , 3),
 INDEX(SPLIT(TRANSPOSE(SPLIT(TEXTJOIN( , 1, "♠"&TEXT(
 FILTER('Week of 18th March'!A3:A20, 'Week of 18th March'!B3:B20="Total"),
 "m/d/yyyy")&"♦"&TEXT('Week of 18th March'!C1:M1, "h:mm am/pm")&"♦"&
 QUERY('Week of 18th March'!A3:M20,
 "select C,D,E,F,G,H,I,J,K,L,M where B='Total'", 0)), "♠")), "♦"), , 3)})
</code>```

Body:
I'm trying to organize the data from a colleague by putting it all in one tab, rather than having a separate tab for each week. What I currently have is this, for each week we are tracking.

I would like to organize it as follows to make the analysis part easier:

Is there a function that can grab the data from the original tab to put it in the above-mentioned format?

I've tried using SUMPRODUCT, but it returns duplicate values after the first correct value.

=SUMPRODUCT(('Week of 11th March'!$B$2:$B$19=$E$1)*('Week of 11th March'!$A$2:$A$19=$B4)*('Week of 11th March'!$C$1:$N$1=$C4)*('Week of 11th March'!$C$2:$C$19))

Any help would be greatly appreciated.

Body:
delete everything and paste this into A2 cell:

=ARRAYFORMULA({SPLIT(TRANSPOSE(SPLIT(TEXTJOIN( , 1, "♠"&TEXT(
 FILTER('Week of 18th March'!A3:A20, 'Week of 18th March'!B3:B20="Female"),
 "m/d/yyyy")&"♦"&TEXT('Week of 18th March'!C1:M1, "h:mm am/pm")&"♦"&
 QUERY('Week of 18th March'!A3:M20,
 "select C,D,E,F,G,H,I,J,K,L,M where B='Female'", 0)), "♠")), "♦"),
 INDEX(SPLIT(TRANSPOSE(SPLIT(TEXTJOIN( , 1, "♠"&TEXT(
 FILTER('Week of 18th March'!A3:A20, 'Week of 18th March'!B3:B20="Male"),
 "m/d/yyyy")&"♦"&TEXT('Week of 18th March'!C1:M1, "h:mm am/pm")&"♦"&
 QUERY('Week of 18th March'!A3:M20,
 "select C,D,E,F,G,H,I,J,K,L,M where B='Male'", 0)), "♠")), "♦"), , 3),
 INDEX(SPLIT(TRANSPOSE(SPLIT(TEXTJOIN( , 1, "♠"&TEXT(
 FILTER('Week of 18th March'!A3:A20, 'Week of 18th March'!B3:B20="Total"),
 "m/d/yyyy")&"♦"&TEXT('Week of 18th March'!C1:M1, "h:mm am/pm")&"♦"&
 QUERY('Week of 18th March'!A3:M20,
 "select C,D,E,F,G,H,I,J,K,L,M where B='Total'", 0)), "♠")), "♦"), , 3)})