问:
JSON Parsing Bing Maps Response
I am trying to parse out a Reverse Geo-location using Bing Maps.

http://www.microsoft.com/maps/isdk/ajax/
Find Information > Reverse Find

If you look at the code, when you look up an address, you get this back

```<code>function _f1300044038369() {
    return {
        "d": {
            "__type": "Microsoft.VirtualEarth.Engines.Core.Geocoding.ReverseGeocodeResponse",
            "Results": [{
                "Name": "SW 35th Ave, Tualatin, OR 97062",
                "Type": 0,
                "BestLocation": {
                    "Precision": 0,
                    "Coordinates": {
                        "Latitude": 45.378872752189636,
                        "Longitude": -122.71288096904755
                    }
                },
                "Locations": [{
                    "Precision": 0,
                    "Coordinates": {
                        "Latitude": 45.378872752189636,
                        "Longitude": -122.71288096904755
                    }
                }],
                "BestView": {
                    "NorthEastCorner": {
                        "Latitude": 45.382735469760313,
                        "Longitude": -122.70554921472814
                    },
                    "SouthWestCorner": {
                        "Latitude": 45.37501003461896,
                        "Longitude": -122.72021272336696
                    },
                    "Type": 0,
                    "Center": {
                        "Latitude": 45.378872884129805,
                        "Longitude": -122.71288096904755
                    }
                },
                "Shape": null,
                "Address": {
                    "AddressLine": "SW 35th Ave",
                    "Locality": "Tualatin",
                    "PostalTown": "",
                    "District": "",
                    "AdminDistrict": "OR",
                    "PostalCode": "97062",
                    "CountryRegion": "United States",
                    "FormattedAddress": "SW 35th Ave, Tualatin, OR 97062"
                },
                "CountryRegion": 244,
                "MatchConfidence": 1,
                "MatchCode": 1
            }],
            "ResponseSummary": {
                "Copyright": "Copyright © 2011 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
                "StatusCode": 0,
                "AuthResultCode": 0,
                "ErrorMessage": null,
                "TraceId": "dc1c3b20-6345-484c-9662-4df504d8977e|SN1M001054"
            }
        }
    }.d;
}
if (typeof closeDependency !== 'undefined') {
    closeDependency('1300044038369');
}
</code>```

The code I currently use parses the "Name" into it's sections so that I can use it elsewhere.

```<code>function GetResults(locations) {
    if (locations) {
        for (var i = 0; i < locations.length; i++) {
            s = locations[i].Name;
            //
            var addressSplit = s.split(", ");
            addresscode = addressSplit[0]
            citycode = addressSplit[1]
            statezip = addressSplit[2]
            country = addressSplit[3]
            var statezipSplit = statezip.split(" ");
            statecode = statezipSplit[0];
            zipcode = statezipSplit[1];
            var loc_array = new Array();
            loc_array[0] = addresscode;
            loc_array[1] = citycode;
            loc_array[2] = statecode;
            loc_array[3] = zipcode;
            window.locationArray = loc_array;
        }
    }
</code>```

I want to change the above code to use the section that has the addressline, location, postaltown, etc already.

答:
The only thing you need to do is change your loc_array lines:</p>

```<code>function GetResults(locations) {
    var s, location;
    if (locations) {
        for (var i = 0; i < locations.length; i++) {
            s = locations[i].Name;
            location = locations[i];
            //
            var loc_array = [];
            loc_array[0] = location.Address.AddressLine;
            loc_array[1] = location.Address.Locality;
            loc_array[2] = location.Address.AdminDistrict;
            loc_array[3] = location.Locations.Coordinates.Latitude;
            loc_array[4] = location.Locations.Coordinates.Longitude;
            // ...
            window.locationArray = loc_array;
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: JSON Parsing Bing Maps Response

Body:
I am trying to parse out a Reverse Geo-location using Bing Maps.

http://www.microsoft.com/maps/isdk/ajax/
Find Information > Reverse Find

If you look at the code, when you look up an address, you get this back

function _f1300044038369() {
    return {
        "d": {
            "__type": "Microsoft.VirtualEarth.Engines.Core.Geocoding.ReverseGeocodeResponse",
            "Results": [{
                "Name": "SW 35th Ave, Tualatin, OR 97062",
                "Type": 0,
                "BestLocation": {
                    "Precision": 0,
                    "Coordinates": {
                        "Latitude": 45.378872752189636,
                        "Longitude": -122.71288096904755
                    }
                },
                "Locations": [{
                    "Precision": 0,
                    "Coordinates": {
                        "Latitude": 45.378872752189636,
                        "Longitude": -122.71288096904755
                    }
                }],
                "BestView": {
                    "NorthEastCorner": {
                        "Latitude": 45.382735469760313,
                        "Longitude": -122.70554921472814
                    },
                    "SouthWestCorner": {
                        "Latitude": 45.37501003461896,
                        "Longitude": -122.72021272336696
                    },
                    "Type": 0,
                    "Center": {
                        "Latitude": 45.378872884129805,
                        "Longitude": -122.71288096904755
                    }
                },
                "Shape": null,
                "Address": {
                    "AddressLine": "SW 35th Ave",
                    "Locality": "Tualatin",
                    "PostalTown": "",
                    "District": "",
                    "AdminDistrict": "OR",
                    "PostalCode": "97062",
                    "CountryRegion": "United States",
                    "FormattedAddress": "SW 35th Ave, Tualatin, OR 97062"
                },
                "CountryRegion": 244,
                "MatchConfidence": 1,
                "MatchCode": 1
            }],
            "ResponseSummary": {
                "Copyright": "Copyright © 2011 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
                "StatusCode": 0,
                "AuthResultCode": 0,
                "ErrorMessage": null,
                "TraceId": "dc1c3b20-6345-484c-9662-4df504d8977e|SN1M001054"
            }
        }
    }.d;
}
if (typeof closeDependency !== 'undefined') {
    closeDependency('1300044038369');
}

The code I currently use parses the "Name" into it's sections so that I can use it elsewhere.

function GetResults(locations) {
    if (locations) {
        for (var i = 0; i < locations.length; i++) {
            s = locations[i].Name;
            //
            var addressSplit = s.split(", ");
            addresscode = addressSplit[0]
            citycode = addressSplit[1]
            statezip = addressSplit[2]
            country = addressSplit[3]
            var statezipSplit = statezip.split(" ");
            statecode = statezipSplit[0];
            zipcode = statezipSplit[1];
            var loc_array = new Array();
            loc_array[0] = addresscode;
            loc_array[1] = citycode;
            loc_array[2] = statecode;
            loc_array[3] = zipcode;
            window.locationArray = loc_array;
        }
    }

I want to change the above code to use the section that has the addressline, location, postaltown, etc already.

Body:
The only thing you need to do is change your loc_array lines:

function GetResults(locations) {
    var s, location;
    if (locations) {
        for (var i = 0; i < locations.length; i++) {
            s = locations[i].Name;
            location = locations[i];
            //
            var loc_array = [];
            loc_array[0] = location.Address.AddressLine;
            loc_array[1] = location.Address.Locality;
            loc_array[2] = location.Address.AdminDistrict;
            loc_array[3] = location.Locations.Coordinates.Latitude;
            loc_array[4] = location.Locations.Coordinates.Longitude;
            // ...
            window.locationArray = loc_array;
        }
    }
}


来源: stackexchange

问:
Conditional Formatting based on Another Range
I want to set conditional formatting on a sheet with range A2:D15 using a custom formula that changes the cell background color. I have column F which includes a list of names (F2:F13), and column H which includes what class the name is (G2:G13). I want to compare each row by saying that if the class in G2 = "Paladin" and F2 is not blank, then perform the conditional formatting. I want this to span all 12 rows in F and G, but I cannot pass an array using an if function.

Example sheet: https://docs.google.com/spreadsheets/d/1a32ItT0HpRsov_oG5-CVHVe3HZV9WP-LypkxugsoK0g/edit?usp=sharing

I tried using this formula:

```<code>=if(and(not(isblank(F2)),G2="Paladin"),1)
</code>```

It successfully changes the first result in my range because it happens to be true, but I need it to include the entire array, so I tried using this:

```<code>=if(and(not(isblank(F2:F13)),G2:G13="Paladin"),1)
</code>```

Also played around with this =if(and(F2=A2,G2="Paladin"),1) - same problem I reckon, but more accurate if I could find a way to use arrays.

However, IF function as I understand it cannot evaluate arrays. I tried using $ signs to play around with it, similar to this example I found: https://www.benlcollins.com/formula-examples/array-formula-intro/ - but that is using numerical data and when I use $ it either applies the conditional formatting on the entire row, or entire column, or the entire range of A3:D16.

答:
you will need 4 rules:

```<code>=FILTER(A2, COUNTIF(FILTER(F$2:F,G$2:G="Paladin"), A2))
</code>```

```<code>=FILTER(B2, COUNTIF(FILTER(F$2:F,G$2:G="Paladin"), B2))
</code>```

```<code>=FILTER(C2, COUNTIF(FILTER(F$2:F,G$2:G="Paladin"), C2))
</code>```

```<code>=FILTER(D2, COUNTIF(FILTER(F$2:F,G$2:G="Paladin"), D2))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to set conditional formatting on a sheet with range A2:D15 using a custom formula that changes the cell background color. I have column F which includes a list of names (F2:F13), and column H which includes what class the name is (G2:G13). I want to compare each row by saying that if the class in G2 = "Paladin" and F2 is not blank, then perform the conditional formatting. I want this to span all 12 rows in F and G, but I cannot pass an array using an if function.

Example sheet: https://docs.google.com/spreadsheets/d/1a32ItT0HpRsov_oG5-CVHVe3HZV9WP-LypkxugsoK0g/edit?usp=sharing

I tried using this formula:

=if(and(not(isblank(F2)),G2="Paladin"),1)

It successfully changes the first result in my range because it happens to be true, but I need it to include the entire array, so I tried using this:

=if(and(not(isblank(F2:F13)),G2:G13="Paladin"),1)

Also played around with this =if(and(F2=A2,G2="Paladin"),1) - same problem I reckon, but more accurate if I could find a way to use arrays.

However, IF function as I understand it cannot evaluate arrays. I tried using $ signs to play around with it, similar to this example I found: https://www.benlcollins.com/formula-examples/array-formula-intro/ - but that is using numerical data and when I use $ it either applies the conditional formatting on the entire row, or entire column, or the entire range of A3:D16.

Body:
you will need 4 rules:

=FILTER(A2, COUNTIF(FILTER(F$2:F,G$2:G="Paladin"), A2))

=FILTER(B2, COUNTIF(FILTER(F$2:F,G$2:G="Paladin"), B2))

=FILTER(C2, COUNTIF(FILTER(F$2:F,G$2:G="Paladin"), C2))

=FILTER(D2, COUNTIF(FILTER(F$2:F,G$2:G="Paladin"), D2))


问:
How do you enable newline seperation when writing multiple strings at once in Python 3?
I have an incredibly basic Python 3 program that works fine. All it does is take from user input a string and a number. It then prints the string that number of times.

```<code>program1 = 25
print("[Type anything!]")
while program1 == 25:
        pcmd = input()
        amount = input("How many lines?: ")
        if amount.isnumeric():
            print(pcmd * int(amount))
        elif pcmd or amount == "exit":
            exit()
        else:
            print("Invalid amount")
</code>```

The thing is, whenever I run it and put in a string and amount, it prints all those strings next to each other.

Before, when I had statically defined strings, I could just use '\n' to make a newline. How can I do the same thing in this case?

答:
Change

print(pcmd * int(amount))
```

<p>to</p>

<pre class="lang-py prettyprint-override"><code>print((pcmd +"\n" )* int(amount))
</code>```

Body:
I have an incredibly basic Python 3 program that works fine. All it does is take from user input a string and a number. It then prints the string that number of times.

program1 = 25
print("[Type anything!]")
while program1 == 25:
        pcmd = input()
        amount = input("How many lines?: ")
        if amount.isnumeric():
            print(pcmd * int(amount))
        elif pcmd or amount == "exit":
            exit()
        else:
            print("Invalid amount")

The thing is, whenever I run it and put in a string and amount, it prints all those strings next to each other.

Before, when I had statically defined strings, I could just use '\n' to make a newline. How can I do the same thing in this case?

Body:
Change

print(pcmd * int(amount))

to

print((pcmd +"\n" )* int(amount))


问:
Error: Invalid provider configuration alias
After upgrade to version Terraform v0.12.0 and updating config using "terraform 0.12upgrade"

I get error below for terraform init

the alias are set to variables in main.tf and are passed in from azure or substituted.

There are some problems with the configuration, described below.

The Terraform configuration must be valid before initialization so
  that Terraform can determine which modules and providers need to be
  installed.

Error: Invalid provider configuration alias

An alias must be a valid name. A name must start with a letter and may
  contain only letters, digits, underscores, and dashes.

```<code> `provider "azurerm {
  subscription_id = var.arm_subscription_id
  tenant_id       = var.tenant_id
  alias           = "$${var.myservers_name}"
}`"
</code>```

答:
There are some mistakes that you made in the provider code that you provided. The code should change like below:

```<code>provider "azurerm" {

  version = ">=1.2.0"
  alias = "${var.alias_name}"

  subscription_id = "${var.arm_subscription_id}"
  tenant_id       = "${var.tenant_id}"
}
</code>```

It seems you use the Azure Provider: Authenticating using the Azure CLI. You need to use the code like "${var.var_name}" when you want to quote the variables that set already.

Body:
After upgrade to version Terraform v0.12.0 and updating config using "terraform 0.12upgrade"

I get error below for terraform init

the alias are set to variables in main.tf and are passed in from azure or substituted.

There are some problems with the configuration, described below.

The Terraform configuration must be valid before initialization so
  that Terraform can determine which modules and providers need to be
  installed.

Error: Invalid provider configuration alias

An alias must be a valid name. A name must start with a letter and may
  contain only letters, digits, underscores, and dashes.

 `provider "azurerm {
  subscription_id = var.arm_subscription_id
  tenant_id       = var.tenant_id
  alias           = "$${var.myservers_name}"
}`"

Body:
There are some mistakes that you made in the provider code that you provided. The code should change like below:

provider "azurerm" {

  version = ">=1.2.0"
  alias = "${var.alias_name}"

  subscription_id = "${var.arm_subscription_id}"
  tenant_id       = "${var.tenant_id}"
}

It seems you use the Azure Provider: Authenticating using the Azure CLI. You need to use the code like "${var.var_name}" when you want to quote the variables that set already.


问:
Bottom Overflowed using SingleChildScrollView
```<code>@override
Widget build(BuildContext context) {
return Scaffold(
  backgroundColor: Color(0xff003859),
  appBar: AppBar(
    title: Text(
      "Conversor de moedas 360",
      style: TextStyle(
        color: Color(0xff003859)
      )
    ),
    backgroundColor: Color(0xffffa300),
  ),
  body: FutureBuilder<Map>(
    future: getData(),
    builder: (context, snapshot) {
      switch(snapshot.connectionState){
        case ConnectionState.none:
        case ConnectionState.waiting:
        return Center(
          child: Text(
            "Carregando Dados...",
            style: TextStyle(
              color: Color(0xffffa300),
              fontSize: 25.0
            ),
            textAlign: TextAlign.center,
          )
        );
        default:
        if (snapshot.hasError){
          return Center(
              child: Text(
                "Erro ao carregar dados...",
                style: TextStyle(
                    color: Color(0xffffa300),
                    fontSize: 25.0
                ),
                textAlign: TextAlign.center,
              )
          );
        } else {
          dolar = snapshot.data["results"]["currencies"]["USD"]["buy"];
          euro = snapshot.data["results"]["currencies"]["EUR"]["buy"];
          return Column(
            children: <Widget>[
              Image.asset(
              "images/360Tecnologia.jpg",
                fit: BoxFit.fitWidth,
              ),
              SingleChildScrollView(
                padding: EdgeInsets.all(10.0),
                child: Column(
                  children: <Widget>[
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Reais",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "R\$ "
                      ),
                      style: TextStyle(
                      color: Color(0xffffa300),
                      fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Dólares",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "U\$ "
                      ),
                      style: TextStyle(
                      color: Color(0xffffa300),
                      fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Euros",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "€ "
                      ),
                      style: TextStyle(
                      color: Color(0xffffa300),
                      fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Libra",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "£\$ "
                      ),
                      style: TextStyle(
                        color: Color(0xffffa300),
                        fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Bitcoin",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "BTC "
                      ),
                      style: TextStyle(
                        color: Color(0xffffa300),
                        fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                        decoration: InputDecoration(
                            labelText: "Bitcoin",
                            labelStyle: TextStyle(
                              color: Color(0xffffa300),
                            ),
                            border: OutlineInputBorder(),
                            prefixText: "BTC "
                        ),
                        style: TextStyle(
                            color: Color(0xffffa300),
                            fontSize: 25.0
                        )
                    ),
                  ],
                )
              )
            ],
          );
        }
      }
    }
  )
);
}
}
</code>```

I want to show an image on top below the top bar. The image is fixed.

Below the top bar I have any text field inside the SingleChildScrollView widget, but this not work when I try to scroll the elements.

The text field can't rolling when I roll the screen to up or to down.

The stackoverflow want I type more text because I put many code, but my doubt is explained on text up...

Any help?

答: To address the singleChildScrollView issue, you can wrap that in an Expanded widget and that will solve that problem. Though, you may want to look into using a SliverList for what you're doing if you want the image to be up top and fixed in the app bar.

Body:
@override
Widget build(BuildContext context) {
return Scaffold(
  backgroundColor: Color(0xff003859),
  appBar: AppBar(
    title: Text(
      "Conversor de moedas 360",
      style: TextStyle(
        color: Color(0xff003859)
      )
    ),
    backgroundColor: Color(0xffffa300),
  ),
  body: FutureBuilder<Map>(
    future: getData(),
    builder: (context, snapshot) {
      switch(snapshot.connectionState){
        case ConnectionState.none:
        case ConnectionState.waiting:
        return Center(
          child: Text(
            "Carregando Dados...",
            style: TextStyle(
              color: Color(0xffffa300),
              fontSize: 25.0
            ),
            textAlign: TextAlign.center,
          )
        );
        default:
        if (snapshot.hasError){
          return Center(
              child: Text(
                "Erro ao carregar dados...",
                style: TextStyle(
                    color: Color(0xffffa300),
                    fontSize: 25.0
                ),
                textAlign: TextAlign.center,
              )
          );
        } else {
          dolar = snapshot.data["results"]["currencies"]["USD"]["buy"];
          euro = snapshot.data["results"]["currencies"]["EUR"]["buy"];
          return Column(
            children: <Widget>[
              Image.asset(
              "images/360Tecnologia.jpg",
                fit: BoxFit.fitWidth,
              ),
              SingleChildScrollView(
                padding: EdgeInsets.all(10.0),
                child: Column(
                  children: <Widget>[
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Reais",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "R\$ "
                      ),
                      style: TextStyle(
                      color: Color(0xffffa300),
                      fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Dólares",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "U\$ "
                      ),
                      style: TextStyle(
                      color: Color(0xffffa300),
                      fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Euros",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "€ "
                      ),
                      style: TextStyle(
                      color: Color(0xffffa300),
                      fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Libra",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "£\$ "
                      ),
                      style: TextStyle(
                        color: Color(0xffffa300),
                        fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                      decoration: InputDecoration(
                        labelText: "Bitcoin",
                        labelStyle: TextStyle(
                          color: Color(0xffffa300),
                        ),
                        border: OutlineInputBorder(),
                        prefixText: "BTC "
                      ),
                      style: TextStyle(
                        color: Color(0xffffa300),
                        fontSize: 25.0
                      )
                    ),
                    Divider(),
                    TextField(
                        decoration: InputDecoration(
                            labelText: "Bitcoin",
                            labelStyle: TextStyle(
                              color: Color(0xffffa300),
                            ),
                            border: OutlineInputBorder(),
                            prefixText: "BTC "
                        ),
                        style: TextStyle(
                            color: Color(0xffffa300),
                            fontSize: 25.0
                        )
                    ),
                  ],
                )
              )
            ],
          );
        }
      }
    }
  )
);
}
}

I want to show an image on top below the top bar. The image is fixed.

Below the top bar I have any text field inside the SingleChildScrollView widget, but this not work when I try to scroll the elements.

The text field can't rolling when I roll the screen to up or to down.

The stackoverflow want I type more text because I put many code, but my doubt is explained on text up...

Any help?


问:
Logging from inside a Customized Bad Request Response
I'm capturing model validation errors using the code below and outputting a custom 400 response from the CustomProblemDetails object which works great. My question is, I want to log from within the CustomProblemDetails object but don't see how I can use DI. I've passed in context which gives me access to the services but is this the way to go? If so it appears I can only get access to the ILoggerFactory how do I log using ILoggerFactory?

services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
    .ConfigureApiBehaviorOptions(options =>
    {
        options.InvalidModelStateResponseFactory = context =>
        {
            var problemDetails = new CustomProblemDetails(context)
            {
                Type = "https://contoso.com/probs/modelvalidation",
                Title = "One or more model validation errors occurred.",
                Status = StatusCodes.Status400BadRequest,
                Detail = "See the errors property for details.",
                Instance = context.HttpContext.Request.Path
            };

            return new BadRequestObjectResult(problemDetails)
            {
                ContentTypes = { "application/problem+json" }
            };
        };
    });
```

答:
For logging in InvalidModelStateResponseFactory, you could try code like:

```<code>services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).ConfigureApiBehaviorOptions(options =>
{
    options.InvalidModelStateResponseFactory = context =>
    {
        var loggerFactory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
        var logger = loggerFactory.CreateLogger("Logger From Invalid Model");
        var problemDetails = new CustomProblemDetails(context)
        {
            Type = "https://contoso.com/probs/modelvalidation",
            Title = "One or more model validation errors occurred.",
            Status = StatusCodes.Status400BadRequest,
            Detail = "See the errors property for details.",
            Instance = context.HttpContext.Request.Path
        };
        logger.LogError(JsonConvert.SerializeObject(problemDetails));
        return new BadRequestObjectResult(problemDetails)
        {
            ContentTypes = { "application/problem+json" }
        };
    };
});
</code>```

Body:
For logging in InvalidModelStateResponseFactory, you could try code like:

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).ConfigureApiBehaviorOptions(options =>
{
    options.InvalidModelStateResponseFactory = context =>
    {
        var loggerFactory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
        var logger = loggerFactory.CreateLogger("Logger From Invalid Model");
        var problemDetails = new CustomProblemDetails(context)
        {
            Type = "https://contoso.com/probs/modelvalidation",
            Title = "One or more model validation errors occurred.",
            Status = StatusCodes.Status400BadRequest,
            Detail = "See the errors property for details.",
            Instance = context.HttpContext.Request.Path
        };
        logger.LogError(JsonConvert.SerializeObject(problemDetails));
        return new BadRequestObjectResult(problemDetails)
        {
            ContentTypes = { "application/problem+json" }
        };
    };
});


问:
how to place image on top of uiview drawing (swift5)
My code below places a behind a drawing area. So as you can see in the image below. Anything I draw goes in front of the lines. I want to make so whatever i draw goes behind the lines. All of my code is attached below. The image is in the assets folder as well.

```<code>class ViewController: UIViewController {
    var editBtn = UIButton()
    var canVasView = UIView()
    var path = UIBezierPath()
    var startPoint = CGPoint()
    var touchPoint = CGPoint()

    func addArrowImageToButton(button: UIButton, arrowImage:UIImage = #imageLiteral(resourceName: "graph.png") ) {
        let btnSize:CGFloat = 32
        let imageView = UIImageView(image: arrowImage)
        let btnFrame = button.frame

        button.bringSubviewToFront(imageView)
    }

    override func viewDidAppear(_ animated: Bool) {
        self.addArrowImageToButton(button: editBtn)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        setup()
        draw()
        view.addSubview(editBtn)
        view.addSubview(canVasView)

        editBtn.backgroundColor = UIColor.orange
        canVasView.backgroundColor = UIColor.purple

        editBtn.translatesAutoresizingMaskIntoConstraints = false
        canVasView.translatesAutoresizingMaskIntoConstraints = false

        let myLayer = CALayer()
        let myImage = UIImage(named: "graph.png")?.cgImage
        myLayer.frame = CGRect(x: 40, y: -80, width: 300, height: 300)
        myLayer.contents = myImage
        canVasView.layer.addSublayer(myLayer)

        self.view.addSubview(canVasView)

        NSLayoutConstraint.activate ([
            canVasView.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :175),
            canVasView.topAnchor.constraint(equalTo: view.centerYAnchor, constant : 100),
            canVasView.widthAnchor.constraint(equalToConstant: 350),
            canVasView.heightAnchor.constraint(equalToConstant: 180),

            editBtn.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :175),
            editBtn.topAnchor.constraint(equalTo: view.centerYAnchor, constant : 0),
            editBtn.widthAnchor.constraint(equalToConstant: 350),
            editBtn.heightAnchor.constraint(equalToConstant: 180),
        ])

        editBtn.addTarget(self, action: #selector(didTapEditButton), for: .touchUpInside)
    }

    @objc func didTapEditButton() {
        path.removeAllPoints()
        canVasView.layer.sublayers = nil
        canVasView.setNeedsDisplay()

        self.addArrowImageToButton(button: editBtn)
    }

    func setup(){
        editBtn.layer.cornerRadius = 20
        canVasView.clipsToBounds = true
        canVasView.isMultipleTouchEnabled = false
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        if let point = touch?.location(in: canVasView){
            startPoint = point
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        if let point = touch?.location(in: canVasView){
            touchPoint = point
        }

        path.move(to: startPoint)
        path.addLine(to: touchPoint)
        startPoint = touchPoint
        draw()
    }

    func draw() {
        let strokeLayer = CAShapeLayer()
        strokeLayer.fillColor = nil
        strokeLayer.lineWidth = 5
        strokeLayer.strokeColor = UIColor.blue.cgColor
        strokeLayer.path = path.cgPath
        canVasView.layer.addSublayer(strokeLayer)
        canVasView.setNeedsDisplay()
    }
}
</code>```

答:
To draw behind the lines image you need to add your stroke layer behind it.
To do so, declare myLayer outside of viewDidLoad then change your draw function to:</p>

```<code>func draw() {
    let strokeLayer = CAShapeLayer()
    strokeLayer.fillColor = nil
    strokeLayer.lineWidth = 5
    strokeLayer.strokeColor = UIColor.blue.cgColor
    strokeLayer.path = path.cgPath
    canVasView.layer.insertSublayer(strokeLayer, below: myLayer) //draw behind myLayer
    canVasView.setNeedsDisplay()
}
</code>```

Body:
My code below places a behind a drawing area. So as you can see in the image below. Anything I draw goes in front of the lines. I want to make so whatever i draw goes behind the lines. All of my code is attached below. The image is in the assets folder as well.

class ViewController: UIViewController {
    var editBtn = UIButton()
    var canVasView = UIView()
    var path = UIBezierPath()
    var startPoint = CGPoint()
    var touchPoint = CGPoint()

    func addArrowImageToButton(button: UIButton, arrowImage:UIImage = #imageLiteral(resourceName: "graph.png") ) {
        let btnSize:CGFloat = 32
        let imageView = UIImageView(image: arrowImage)
        let btnFrame = button.frame

        button.bringSubviewToFront(imageView)
    }

    override func viewDidAppear(_ animated: Bool) {
        self.addArrowImageToButton(button: editBtn)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        setup()
        draw()
        view.addSubview(editBtn)
        view.addSubview(canVasView)

        editBtn.backgroundColor = UIColor.orange
        canVasView.backgroundColor = UIColor.purple

        editBtn.translatesAutoresizingMaskIntoConstraints = false
        canVasView.translatesAutoresizingMaskIntoConstraints = false

        let myLayer = CALayer()
        let myImage = UIImage(named: "graph.png")?.cgImage
        myLayer.frame = CGRect(x: 40, y: -80, width: 300, height: 300)
        myLayer.contents = myImage
        canVasView.layer.addSublayer(myLayer)

        self.view.addSubview(canVasView)

        NSLayoutConstraint.activate ([
            canVasView.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :175),
            canVasView.topAnchor.constraint(equalTo: view.centerYAnchor, constant : 100),
            canVasView.widthAnchor.constraint(equalToConstant: 350),
            canVasView.heightAnchor.constraint(equalToConstant: 180),

            editBtn.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :175),
            editBtn.topAnchor.constraint(equalTo: view.centerYAnchor, constant : 0),
            editBtn.widthAnchor.constraint(equalToConstant: 350),
            editBtn.heightAnchor.constraint(equalToConstant: 180),
        ])

        editBtn.addTarget(self, action: #selector(didTapEditButton), for: .touchUpInside)
    }

    @objc func didTapEditButton() {
        path.removeAllPoints()
        canVasView.layer.sublayers = nil
        canVasView.setNeedsDisplay()

        self.addArrowImageToButton(button: editBtn)
    }

    func setup(){
        editBtn.layer.cornerRadius = 20
        canVasView.clipsToBounds = true
        canVasView.isMultipleTouchEnabled = false
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        if let point = touch?.location(in: canVasView){
            startPoint = point
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        if let point = touch?.location(in: canVasView){
            touchPoint = point
        }

        path.move(to: startPoint)
        path.addLine(to: touchPoint)
        startPoint = touchPoint
        draw()
    }

    func draw() {
        let strokeLayer = CAShapeLayer()
        strokeLayer.fillColor = nil
        strokeLayer.lineWidth = 5
        strokeLayer.strokeColor = UIColor.blue.cgColor
        strokeLayer.path = path.cgPath
        canVasView.layer.addSublayer(strokeLayer)
        canVasView.setNeedsDisplay()
    }
}

Body:
To draw behind the lines image you need to add your stroke layer behind it.
To do so, declare myLayer outside of viewDidLoad then change your draw function to:

func draw() {
    let strokeLayer = CAShapeLayer()
    strokeLayer.fillColor = nil
    strokeLayer.lineWidth = 5
    strokeLayer.strokeColor = UIColor.blue.cgColor
    strokeLayer.path = path.cgPath
    canVasView.layer.insertSublayer(strokeLayer, below: myLayer) //draw behind myLayer
    canVasView.setNeedsDisplay()
}


问:
Overlap Components When Using ComponentResizer
I want to make my jTable expandable while floating/overlay when dragging it using ComponentResizer class. I'm using ComponentResizer class from Rob Camick.

Currently as below after dragging the table:

I tried change my layout to null but the result still same.
In my code, I just added to call the ComponentResizer class:

```<code>ComponentResizer cr = new ComponentResizer();
cr.setSnapSize(new Dimension(10, 10));
cr.registerComponent(jScrollPane2);
</code>```

I expect the dragging table will float and overlay the components below it.

答: I solved the problem by put all components in one layered pane and using Border Layout.</p>

Body:
I want to make my jTable expandable while floating/overlay when dragging it using ComponentResizer class. I'm using ComponentResizer class from Rob Camick.

Currently as below after dragging the table:

I tried change my layout to null but the result still same.
In my code, I just added to call the ComponentResizer class:

ComponentResizer cr = new ComponentResizer();
cr.setSnapSize(new Dimension(10, 10));
cr.registerComponent(jScrollPane2);

I expect the dragging table will float and overlay the components below it.


问:
get all data in a mongo collection into a text file using javascript
I have a Mongo collection in this syntax. How do I export each file into a text file including the arrays?

```<code>{
      _id: 1,
      "author": [
        {
          "fname": "Petr",
          "lname": "Kocircurka"
        }
      ],
      "title": "On topological dynamics of Turing machines",
      "journal": "Theor. Comput. Sci.",
      "volume": "174",
      "pages": [
        {
          "FirstNumber": "203",
          "LastNumber": "216"
        }
      ],
      "year": "1997",
      "url": "http://www.sciencedirect.com/science/journal/03043975/"
    }{
      _id: 2,
      "author": [
        {
          "fname": "Aviezri",
          "lname": "Fraenkel"
        },
        {
          "fname": "Jamie",
          "lname": "Simpson"
        }
      ],
      "title": "The exact number of squares in Fibonacci words",
      "journal": "Theor. Comput. Sci.",
      "volume": "218",
      "pages": [
        {
          "FirstNumber": "95",
          "LastNumber": "106"
        }
      ],
      "year": "1999",
      "url": "http://www.sciencedirect.com/science/journal/03043975/"
    }
</code>```

Thanks

答:
If your database is created without using username and password, you can use the following command which will give you json files for each of the collections that you have defined

mongoexport --db databaseName --collection CollectionName --out fileName.json```

ContentLicense: CC BY-SA 3.0

Body:
I have a Mongo collection in this syntax. How do I export each file into a text file including the arrays?

{
      _id: 1,
      "author": [
        {
          "fname": "Petr",
          "lname": "Kocircurka"
        }
      ],
      "title": "On topological dynamics of Turing machines",
      "journal": "Theor. Comput. Sci.",
      "volume": "174",
      "pages": [
        {
          "FirstNumber": "203",
          "LastNumber": "216"
        }
      ],
      "year": "1997",
      "url": "http://www.sciencedirect.com/science/journal/03043975/"
    }{
      _id: 2,
      "author": [
        {
          "fname": "Aviezri",
          "lname": "Fraenkel"
        },
        {
          "fname": "Jamie",
          "lname": "Simpson"
        }
      ],
      "title": "The exact number of squares in Fibonacci words",
      "journal": "Theor. Comput. Sci.",
      "volume": "218",
      "pages": [
        {
          "FirstNumber": "95",
          "LastNumber": "106"
        }
      ],
      "year": "1999",
      "url": "http://www.sciencedirect.com/science/journal/03043975/"
    }

Thanks


问:
IIS10 in Windows-Server-2016(AWS) unable to redirect HTTP request to HTTPS
IIS-10 in windows-server-2016 unable to redirect HTTP request to HTTPS.

I tried almost all configurations that are available over internet but still no success.

Note: My server will get sub-directory url as well and few example as like:

http://abctest.com/subfolder_1

http://abctest.com/subfolder_2

http://abctest.com

etc.

There could be N number of subfolders.), But IIS-10 unable to redirect Http request to Https.

Please find below configuration in IIS-10 GUI and also web.config file:

答:
You could use below URL rewrite rule to redirect URL with the subfolder to https:

```<code><rule name="http to https" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{HTTPS}" pattern="off" />
                </conditions>
                <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" />
            </rule>
</code>```

also, bind the certificate in site binding. if you don't have registered certificate you could bind self-signed certificate.

First, you need to create a self-signed certificate by using below Powershell command:

```<code>New-SelfSignedCertificate -DnsName www.test.com -CertStoreLocation cert:Localmachine\My
</code>```

and bind that certificate with IIS site:

Regards,
Jalpa

Body:
You could use below URL rewrite rule to redirect URL with the subfolder to https:

<rule name="http to https" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{HTTPS}" pattern="off" />
                </conditions>
                <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" />
            </rule>

also, bind the certificate in site binding. if you don't have registered certificate you could bind self-signed certificate.

First, you need to create a self-signed certificate by using below Powershell command:

New-SelfSignedCertificate -DnsName www.test.com -CertStoreLocation cert:Localmachine\My

and bind that certificate with IIS site:

Regards,
Jalpa


问:
How to Sync K8s Service to Consul Cluster which is outside the K8s？
From the consul-k8s document：
The Consul server cluster can run either in or out of a Kubernetes cluster.
The Consul server cluster does not need to be running on the same machine or same platform as the sync process.
The sync process needs to be configured with the address to the Consul cluster as well as any additional access information such as ACL tokens.

The consul cluster I am trying to sync is outside the k8s cluster, based on the document, I must pass the address to consul cluster for sync process.However, the helm chart for installing the sync process didn’t contains any value to configure the consul cluster ip address.

```<code>syncCatalog:

  # True if you want to enable the catalog sync. "-" for default.

  enabled: false

  image: null

  default: true # true will sync by default, otherwise requires annotation

  # toConsul and toK8S control whether syncing is enabled to Consul or K8S

  # as a destination. If both of these are disabled, the sync will do nothing.

  toConsul: true

  toK8S: true

  # k8sPrefix is the service prefix to prepend to services before registering

  # with Kubernetes. For example "consul-" will register all services

  # prepended with "consul-". (Consul -> Kubernetes sync)

  k8sPrefix: null

  # consulPrefix is the service prefix which preprends itself

  # to Kubernetes services registered within Consul

  # For example, "k8s-" will register all services peprended with "k8s-".

  # (Kubernetes -> Consul sync)

  consulPrefix: null

  # k8sTag is an optional tag that is applied to all of the Kubernetes services

  # that are synced into Consul. If nothing is set, defaults to "k8s".

  # (Kubernetes -> Consul sync)

  k8sTag: null

  # syncClusterIPServices syncs services of the ClusterIP type, which may

  # or may not be broadly accessible depending on your Kubernetes cluster.

  # Set this to false to skip syncing ClusterIP services.

  syncClusterIPServices: true

  # nodePortSyncType configures the type of syncing that happens for NodePort

  # services. The valid options are: ExternalOnly, InternalOnly, ExternalFirst.

  # - ExternalOnly will only use a node's ExternalIP address for the sync

  # - InternalOnly use's the node's InternalIP address

  # - ExternalFirst will preferentially use the node's ExternalIP address, but

  #   if it doesn't exist, it will use the node's InternalIP address instead.

  nodePortSyncType: ExternalFirst

  # aclSyncToken refers to a Kubernetes secret that you have created that contains

  # an ACL token for your Consul cluster which allows the sync process the correct

  # permissions. This is only needed if ACLs are enabled on the Consul cluster.

  aclSyncToken:

    secretName: null

    secretKey: null

  # nodeSelector labels for syncCatalog pod assignment, formatted as a muli-line string.

  # ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#nodeselector

  # Example:

  # nodeSelector: |

  #   beta.kubernetes.io/arch: amd64

  nodeSelector: null
</code>```

So How can I set the consul cluster ip address for sync process?

答:
It looks like the sync service runs via the consul agent on the k8s host.

```<code>          env:
            - name: HOST_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.hostIP
</code>```

```<code>          command:
            - consul-k8s sync-catalog \
                  -http-addr=${HOST_IP}:8500
</code>```

That can't be configured directly but helm can configure the agent/client via client.join (yaml src):

If this is null (default), then the clients will attempt to automatically join the server cluster running within Kubernetes. This means that with server.enabled set to true, clients will automatically join that cluster. If server.enabled is not true, then a value must be specified so the clients can join a valid cluster.

This value is passed to the consul agent as the --retry-join option.

```<code>client:
  enabled: true
  join:
  - consul1
  - consul2
  - consul3
syncCatalog:
  enabled: true
</code>```

Body:
From the consul-k8s document：
The Consul server cluster can run either in or out of a Kubernetes cluster.
The Consul server cluster does not need to be running on the same machine or same platform as the sync process.
The sync process needs to be configured with the address to the Consul cluster as well as any additional access information such as ACL tokens.

The consul cluster I am trying to sync is outside the k8s cluster, based on the document, I must pass the address to consul cluster for sync process.However, the helm chart for installing the sync process didn’t contains any value to configure the consul cluster ip address.

syncCatalog:

  # True if you want to enable the catalog sync. "-" for default.

  enabled: false

  image: null

  default: true # true will sync by default, otherwise requires annotation

  # toConsul and toK8S control whether syncing is enabled to Consul or K8S

  # as a destination. If both of these are disabled, the sync will do nothing.

  toConsul: true

  toK8S: true

  # k8sPrefix is the service prefix to prepend to services before registering

  # with Kubernetes. For example "consul-" will register all services

  # prepended with "consul-". (Consul -> Kubernetes sync)

  k8sPrefix: null

  # consulPrefix is the service prefix which preprends itself

  # to Kubernetes services registered within Consul

  # For example, "k8s-" will register all services peprended with "k8s-".

  # (Kubernetes -> Consul sync)

  consulPrefix: null

  # k8sTag is an optional tag that is applied to all of the Kubernetes services

  # that are synced into Consul. If nothing is set, defaults to "k8s".

  # (Kubernetes -> Consul sync)

  k8sTag: null

  # syncClusterIPServices syncs services of the ClusterIP type, which may

  # or may not be broadly accessible depending on your Kubernetes cluster.

  # Set this to false to skip syncing ClusterIP services.

  syncClusterIPServices: true

  # nodePortSyncType configures the type of syncing that happens for NodePort

  # services. The valid options are: ExternalOnly, InternalOnly, ExternalFirst.

  # - ExternalOnly will only use a node's ExternalIP address for the sync

  # - InternalOnly use's the node's InternalIP address

  # - ExternalFirst will preferentially use the node's ExternalIP address, but

  #   if it doesn't exist, it will use the node's InternalIP address instead.

  nodePortSyncType: ExternalFirst

  # aclSyncToken refers to a Kubernetes secret that you have created that contains

  # an ACL token for your Consul cluster which allows the sync process the correct

  # permissions. This is only needed if ACLs are enabled on the Consul cluster.

  aclSyncToken:

    secretName: null

    secretKey: null

  # nodeSelector labels for syncCatalog pod assignment, formatted as a muli-line string.

  # ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#nodeselector

  # Example:

  # nodeSelector: |

  #   beta.kubernetes.io/arch: amd64

  nodeSelector: null

So How can I set the consul cluster ip address for sync process?

Body:
It looks like the sync service runs via the consul agent on the k8s host.

          env:
            - name: HOST_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.hostIP

          command:
            - consul-k8s sync-catalog \
                  -http-addr=${HOST_IP}:8500

That can't be configured directly but helm can configure the agent/client via client.join (yaml src):

If this is null (default), then the clients will attempt to automatically join the server cluster running within Kubernetes. This means that with server.enabled set to true, clients will automatically join that cluster. If server.enabled is not true, then a value must be specified so the clients can join a valid cluster.

This value is passed to the consul agent as the --retry-join option.

client:
  enabled: true
  join:
  - consul1
  - consul2
  - consul3
syncCatalog:
  enabled: true


问:
socket_create vs. fsockopen php
The hosting service that I use currently does not let me use sockets, probably for good reason on their part. They do, however, let me use fsockopen. I was wondering what the difference is, because some scripts that worked with socket_create and even stream_socket_server, do not work with fsockopen. That said, if fsockopen should work, my code is listed below. What it does is it listens on its own ip address for incoming udp packets and reads them.

Thanks

```<code>$sock = fsockopen("udp://x.x.x.x", $port);
while(1)
{
    $buf = fread($sock, 200);
    flush();
    ob_flush();
}
</code>```

答:
fsockopen creates a connection to a host, not a listening socket.

fsockopen($address) ~== socket_connect(socket_create(), $address)

Your hosting provider doesn't want you listening on alternate ports/protocols.

If what you have works, I wouldn't count on it always working as it would be a bug.

OwnerDisplayName: Samuel

Title: socket_create vs. fsockopen php

Body:
The hosting service that I use currently does not let me use sockets, probably for good reason on their part. They do, however, let me use fsockopen. I was wondering what the difference is, because some scripts that worked with socket_create and even stream_socket_server, do not work with fsockopen. That said, if fsockopen should work, my code is listed below. What it does is it listens on its own ip address for incoming udp packets and reads them.

Thanks

$sock = fsockopen("udp://x.x.x.x", $port);
while(1)
{
    $buf = fread($sock, 200);
    flush();
    ob_flush();
}

OwnerDisplayName: Ryan Graham


问:
On Ubuntu an executable created with Pyinstaller doesn't run
I am on ubuntu 16.04. I am trying to make an executable from my python script (fez.py) using pyinstaller using pyinstaller --onefile fez.py.

The executable gets built without any error. I get the two folders dist and build with the .exe file in dist. I get the fez.spec file too.
But when I try to run the executable nothing seems to happen.

My question is:

Is there a problem with the pyinstaller process to create the executable that doesn't get displayed as an error OR is there a problem with my ubuntu that it can't run the executable? Whichever is the reason how to run my executable?

NB: I am well versed with the fact that pyinstaller is OS specific i.e. for an executable to work on ubuntu it should be prepared on ubuntu itself and that is exactly what I have done. I have used the pyinstaller command on ubuntu. This also rules out the fact that I should install wine or something else of that sort as wine is required to execute windows executables on ubuntu. (Files with .exe extension) The executable I am making using pyinstaller on ubuntu specifically builds executables for ubuntu. (In properties they show application\x-executable)

EDIT: To run the executable I had to first change the permission to allow as executable. Then I had to run from the terminal. But is there no way to run it using double clicks.

答: I don't know exactly how to do it... but I believe you can create a .desktop file that sets parameters like terminal = [true/false] and command = "/path/to/executable" or something like that. Then you can double click the .desktop file and it will execute your program. I've never tried this... just read about it a while back. Maybe google .desktop files and see if that leads you anywhere...</p>


问:
C++ How to add vector in a vector? vector.push_back( vector<> )?
I'm creating a 2d vector array of char as a class variable, but I'm having troubles of adding a vector into the vector< vector > array.

I'm running gcc with C++ 11 standard.

I tried using vector< vector<char> > row(size, vector<char> ); but errors will show saying I did not define size and vector<char>. If I define it with int size and vector<char> col it will think it's a new function declaration since I'm putting it as a class variable.

So I use the usual method vector< vector<char> > row; and have a function to add another vector into it. So I use this->row[i].push_back( vector<char> col); but then an error saying error: expected primary-expression before ‘col’ appears. I also tried to use just this->row[i].push_back( vector<char> ); but the error is still there saying error: expected primary-expression before ‘)’. This might be dumb but I have no idea how to add a vector into a vector.

```<code>class Vector2d {
private:
  int size;
  vector< vector<char> > row;
public:
  void make2d();
};

void Vector2d::make2d() {
  for (int i = 0; i < this->size; i++) {
    this->row[i].push_back( vector<char> col );  // compile error here
    for (int j = 0; j < this->size; j++) {
      this->row[i][j];
    }
  }
  cout << "It works!" << endl;
}
</code>```

I expect it to add the vector array into the vector array, and that I can use row[i][j] for the rest of the program. But it gives a compiler error saying error: expected primary-expression before ‘col’ I have no idea what to do.

答:
vector<char> col is not a valid expression. It almost looks like a declaration of a variable (which is not what you need here), except it lacks a semicolon to complete the statement.

Furthermore, you cannot access row[i] until row actually contains at least i elements. row[i].push_back attempts to push a char element into a std::vector<char> that is the ith element of the vector of vectors (except you never created the ith element).

Given that in the following loop you appear to assume that the inserted vector should have size elements, here is how to insert a single vector of size elements into a vector of vectors:

```<code>row.push_back(std::vector<char>(size));
// or more simply
row.emplace_back(size);
</code>```

If you would like to insert an empty vector instead, simply use:

```<code>row.emplace_back();
</code>```

And here is how you can insert all size vectors of size elements in one go so that you can use row[i][j] for all i and j that are less than size:

```<code>row.resize(size, std::vector<char>(size));
</code>```

Body:
I'm creating a 2d vector array of char as a class variable, but I'm having troubles of adding a vector into the vector< vector > array.

I'm running gcc with C++ 11 standard.

I tried using vector< vector<char> > row(size, vector<char> ); but errors will show saying I did not define size and vector<char>. If I define it with int size and vector<char> col it will think it's a new function declaration since I'm putting it as a class variable.

So I use the usual method vector< vector<char> > row; and have a function to add another vector into it. So I use this->row[i].push_back( vector<char> col); but then an error saying error: expected primary-expression before ‘col’ appears. I also tried to use just this->row[i].push_back( vector<char> ); but the error is still there saying error: expected primary-expression before ‘)’. This might be dumb but I have no idea how to add a vector into a vector.

class Vector2d {
private:
  int size;
  vector< vector<char> > row;
public:
  void make2d();
};

void Vector2d::make2d() {
  for (int i = 0; i < this->size; i++) {
    this->row[i].push_back( vector<char> col );  // compile error here
    for (int j = 0; j < this->size; j++) {
      this->row[i][j];
    }
  }
  cout << "It works!" << endl;
}

I expect it to add the vector array into the vector array, and that I can use row[i][j] for the rest of the program. But it gives a compiler error saying error: expected primary-expression before ‘col’ I have no idea what to do.

Body:
vector<char> col is not a valid expression. It almost looks like a declaration of a variable (which is not what you need here), except it lacks a semicolon to complete the statement.

Furthermore, you cannot access row[i] until row actually contains at least i elements. row[i].push_back attempts to push a char element into a std::vector<char> that is the ith element of the vector of vectors (except you never created the ith element).

Given that in the following loop you appear to assume that the inserted vector should have size elements, here is how to insert a single vector of size elements into a vector of vectors:

row.push_back(std::vector<char>(size));
// or more simply
row.emplace_back(size);

If you would like to insert an empty vector instead, simply use:

row.emplace_back();

And here is how you can insert all size vectors of size elements in one go so that you can use row[i][j] for all i and j that are less than size:

row.resize(size, std::vector<char>(size));


问:
Converting Large float64 Matrix into int32 Matrix
I have a large dataset that I need to calculate the euclidean distance matrix for, however, I am limited on RAM and using np.float64 (default) as dtype makes the PC goes out of memory. I would use the squared distance as it is faster and returns an integer anyhow.

using .astype(np.int32) does not solve the issue as it is still created as float64 first.

the dataset itself is int32 but the returned matrix is float64

matrix = pairwise_distances(dataset, metric='euclidean', squared=True)
print(matrix.dtype)
```

```float64
```

How can I cast it directly as an int array?

答:
So the problem is you want to make your data RAM efficient

You can convert your return matrix into int32 (consider loss in the data) or float32 which is better
here's my example code for doing that

```<code>import numpy as np
arr = np.array([[1.0, 4, 5, 12],
    [-5.9, 8, 9.7, 0],
    [-6, 7, 11, 19]])
print(arr.dtype)
arr = arr.astype('float32')
print(arr.dtype)
</code>```

the output were as follows

```<code>float64
float32
</code>```

Body:
I have a large dataset that I need to calculate the euclidean distance matrix for, however, I am limited on RAM and using np.float64 (default) as dtype makes the PC goes out of memory. I would use the squared distance as it is faster and returns an integer anyhow.

using .astype(np.int32) does not solve the issue as it is still created as float64 first.

the dataset itself is int32 but the returned matrix is float64

matrix = pairwise_distances(dataset, metric='euclidean', squared=True)
print(matrix.dtype)

float64

How can I cast it directly as an int array?

Body:
So the problem is you want to make your data RAM efficient

You can convert your return matrix into int32 (consider loss in the data) or float32 which is better
here's my example code for doing that

import numpy as np
arr = np.array([[1.0, 4, 5, 12],
    [-5.9, 8, 9.7, 0],
    [-6, 7, 11, 19]])
print(arr.dtype)
arr = arr.astype('float32')
print(arr.dtype)

the output were as follows

float64
float32


问:
Is there a way to redirect a mobile response webpage to desktop version?
How can I redirect a mobile response webpage with URL m.facebook.com which has parameters included, to a desktop version?

When I tried with User-agent in httpResponse it redirected to the same URL with m as subdomain but in the desktop version.

How to resolve this, or is there an alternative way?

答:
There is no "simple way" to do this since there is no standard API that I am familar with to do this. For your example on the Chrome Mobile Browser, you still load "m.facebook.com"

If you really do want to do this, though you can do a few heuristics:

Try to swap the user agent change and see if you get a response that is "different enough"

You try removing common prefixes such as "m" or "mobile"

You can ship mappings of common sites, i.e: m.facebook.com > facebook.com with your binary

You can screenshot the page, run metrics against it, figure out if it's "mobile" or "desktop" and try to redirect.

But there is no way to ask directly.


问:
add custom property to props.location
Using React and Javacript, is it acceptable to add a custom property to props.location when passing it via props.history.push?  e.g.

```<code>this.props.history.push({
  pathname: '/someurl',
  state: {smallObject: myObject},
  customProperty : myBiggerObject
});
</code>```

And then at the component that loads at /someurl, I can load:
let myBigObj = this.props.location.customProperty;

This appears to work, and I'm asking if it's "okay" to do?  I am concerned that I may be overlooking something within Javascript or React that I am unaware of.

I would pass customProperty within the state property if the object that I was passing was sufficiently small.  It isn't: it exceeds the 640k limit mentioned here, and I get an error indicating that data can not be cloned if I pass myBiggerObject in the state property.

答:
Here is the link for API documentation

```<code>history.push(path, [state])

// Push a new entry onto the history stack.
history.push('/home');

// Push a new entry onto the history stack with a query string
// and some state. Location state does not appear in the URL.
history.push('/home?the=query', { some: 'state' });

// If you prefer, use a single location-like object to specify both
// the URL and state. This is equivalent to the example above.
history.push({
  pathname: '/home',
  search: '?the=query',
  state: { some: 'state' }
});

// Go back to the previous history entry. The following
// two lines are synonymous.
history.go(-1);
history.goBack();
</code>```

Note: Location state is only supported in createBrowserHistory and createMemoryHistory.

Title: add custom property to props.location

Body:
Using React and Javacript, is it acceptable to add a custom property to props.location when passing it via props.history.push?  e.g.

this.props.history.push({
  pathname: '/someurl',
  state: {smallObject: myObject},
  customProperty : myBiggerObject
});

And then at the component that loads at /someurl, I can load:
let myBigObj = this.props.location.customProperty;

This appears to work, and I'm asking if it's "okay" to do?  I am concerned that I may be overlooking something within Javascript or React that I am unaware of.

I would pass customProperty within the state property if the object that I was passing was sufficiently small.  It isn't: it exceeds the 640k limit mentioned here, and I get an error indicating that data can not be cloned if I pass myBiggerObject in the state property.

Body:
Here is the link for API documentation

history.push(path, [state])

// Push a new entry onto the history stack.
history.push('/home');

// Push a new entry onto the history stack with a query string
// and some state. Location state does not appear in the URL.
history.push('/home?the=query', { some: 'state' });

// If you prefer, use a single location-like object to specify both
// the URL and state. This is equivalent to the example above.
history.push({
  pathname: '/home',
  search: '?the=query',
  state: { some: 'state' }
});

// Go back to the previous history entry. The following
// two lines are synonymous.
history.go(-1);
history.goBack();

Note: Location state is only supported in createBrowserHistory and createMemoryHistory.


问:
Export to PDF with Chinese languages
I had a Grid that contain a chinese language. The problem occur when I want to export the data into PDF. It seem appear a weird characters (image below) or something like this . Can anyone help me to solve the issue?

Here I provide a DEMO in dojo

答: As per documentation, https://demos.telerik.com/kendo-ui/grid/pdf-export for unicode support you need to use custom fonts. The code which you shared is in online is not loading. </p>

Title: Export to PDF with Chinese languages


问:
How to apply accessibility in MDHTMLLABEL Link?

not applying the voiceover accessibility on MDHTMLLABEL HTML TEXT link in xamarin iOS

i am doing below code:

```<code>lblSubHeading2.HtmlText = NSBundle.MainBundle.LocalizedString (
                    "EPMRoomParentMessageLine3",
                    null);
</code>```

i am using HTMLTEXT so i am not able to give accessibility on this text or link so give me solution

答:
You have to create bindings to MDHTMLLABEL library, then you can call the method from MDHTMLLABEL in your project.

Here is the document and samples you can refer: Binding Objective-C and walkthrough.

Body:
not applying the voiceover accessibility on MDHTMLLABEL HTML TEXT link in xamarin iOS

i am doing below code:

lblSubHeading2.HtmlText = NSBundle.MainBundle.LocalizedString (
                    "EPMRoomParentMessageLine3",
                    null);

i am using HTMLTEXT so i am not able to give accessibility on this text or link so give me solution


问:
BLE is not detecting in Chrome browser
I am trying to connect my Android application with web via Bluetooth. But Chrome browser is not detecting my Bluetooth enabled smartphone. I am using Google-FIDO2-Android API.

I am working on Chrome Browser 74.0.3729.157 (64-bit), Nexus Phone, MacBook Pro (Mojave-10.14.5).

How can I proceed on this?

答:
Open Chrome

Go to chrome://flags/

search by Web Authentication API BLE support

Change to Enabled

This helps you to enable bluetooth communication for Webauthn. They said this flag will be enabled by default in the future. Let's see.

If it doesn't work, it should be your authenticator problem. And you should figure out where is the error and post here to get help.

Title: BLE is not detecting in Chrome browser


问:
How can I get the yesterday's data and show it to my form today?
The idea is that I have this 'Present' form that is a textbox one that the user can input the data.

Now, I want to show yesterday's data(readonly) for comparing the result yesterday vs the result today.

Ex:
Attendance: (yesterday- readonly textbox)

```<code>Andy Shrob
Paula Guinto
Mylene Miles
</code>```

Attendance (TODAY)

```<code>Paula Guinto
Mylene Miles
</code>```

How can I get yesterday and show it so I can see who's present yesterday and who's present today? I'm coding PHP and Javascript

I was thinking of this:

```<code>mysql_query("Select prestoday, presyesterday
FROM attendance
WHERE ???)
</code>```

All ideas are welcome. ;) Whether it be PHP code or Javascript or MYSQL Query

TABLE STRUCTURE:
mysql_select_db("csdcon", $con);

$sql="INSERT INTO attendance (prestoday, presyesterday, userdateinp, yesterdate)
                            VALUES
('$_POST[prestoday]','$_POST[presyesterday]','$_POST[userdateinp]','$_POST[yesterdate]')";

答:
```<code>mysql_query("Select prestoday, presyesterday
FROM attendance
WHERE DATE(`datetimefield`) = DATE(DATE_SUB(NOW(), INTERVAL 1 DAY))
</code>```

Body:
The idea is that I have this 'Present' form that is a textbox one that the user can input the data.

Now, I want to show yesterday's data(readonly) for comparing the result yesterday vs the result today.

Ex:
Attendance: (yesterday- readonly textbox)

Andy Shrob
Paula Guinto
Mylene Miles

Attendance (TODAY)

Paula Guinto
Mylene Miles

How can I get yesterday and show it so I can see who's present yesterday and who's present today? I'm coding PHP and Javascript

I was thinking of this:

mysql_query("Select prestoday, presyesterday
FROM attendance
WHERE ???)

All ideas are welcome. ;) Whether it be PHP code or Javascript or MYSQL Query

TABLE STRUCTURE:
mysql_select_db("csdcon", $con);

$sql="INSERT INTO attendance (prestoday, presyesterday, userdateinp, yesterdate)
                            VALUES
('$_POST[prestoday]','$_POST[presyesterday]','$_POST[userdateinp]','$_POST[yesterdate]')";


问:
Worker node-status on a Ray EC2 cluster: update-failed
I now have a Ray cluster working on EC2 (Ubuntu 16.04) with a c4.8xlarge master node and one identical worker.  I wanted to check whether multi-threading was being used, so I ran tests to time increasing numbers (n) of the same 9-second task.  Since the instance has 18 CPUs, I expected to see the job taking about 9s for up to n<=35 (assuming one CPU for the cluster management) and then either a fault, or an increase to about 18 sec when switching to 36 vCPUs per node.

Instead, the cluster handled up to only 14 tasks in parallel and then the execution time jumped to 40s and continued to increase for increasing n. When I tried a c4xlarge master (4 CPUs), the times were directly proportional to n, i.e. they were running serially. So I surmise that the master actually requires 4 CPUs for the system, and that the worker node is not being used at all. However, if I add a second worker, the times for n>14 are about 40s less that without it. I also tried a value for target_utilization_factor less than 1.0, but that made no difference.

There were no reported errors, but I did notice that the ray-node-status for the worker in the EC2 Instances console was "update-failed". Is this significant? Can anyone enlighten me about this behaviour?

答: The cluster did not appear to be using the workers, so the trace is showing only 18 actual cpus dealing with the task.  The monitor (ray exec ray_conf.yaml  'tail -n 100 -f /tmp/ray/session_<em>/logs/monitor</em>') identified that the "update-failed" is significant in that the setup commands, called by the ray updater.py, were failing on the worker nodes. Specifically, it was the attempt to install the C build-essential compiler package on them that, presumably, exceeded the worker memory allocation. I was only doing this in order to suppress a "setproctitle" installation warning - which I now understand can be safely ignored anyway. </p>

Body: The cluster did not appear to be using the workers, so the trace is showing only 18 actual cpus dealing with the task.  The monitor (ray exec ray_conf.yaml  'tail -n 100 -f /tmp/ray/session_/logs/monitor') identified that the "update-failed" is significant in that the setup commands, called by the ray updater.py, were failing on the worker nodes. Specifically, it was the attempt to install the C build-essential compiler package on them that, presumably, exceeded the worker memory allocation. I was only doing this in order to suppress a "setproctitle" installation warning - which I now understand can be safely ignored anyway.


问:
Create new columns based on other's columns value
I'm trying to do some feature engineering for a pandas data frame.

Say I have this:

```<code>Data frame 1:
X |  date     | is_holiday
a |  1/4/2018 | 0
a |  1/5/2018 | 0
a |  1/6/2018 | 1
a |  1/7/2018 | 0
a |  1/8/2018 | 0
...
b |  1/1/2018 | 1
</code>```

I'd like to have an additional indicator for some dates, to indicate if the date is before 1 and 2 days from a holiday, and also 1 and 2 days after.

```<code>Data frame 1:
X |  date     | is_holiday | one_day_before_hol | ... | one_day_after_hol
a |  1/4/2018 | 0          | 0                  | ... | 0
a |  1/5/2018 | 0          | 1                  | ... | 0
a |  1/6/2018 | 1          | 0                  | ... | 0
a |  1/7/2018 | 0          | 0                  | ... | 1
a |  1/8/2018 | 0          | 0                  | ... | 0
...
b |  1/1/2018 | 1          | 0                  | ... | 0
</code>```

Is there any efficient way to do it? I believe I can do it using for statements, but since I'm new to python, I'd like to see if there is an elegant way to do it. Dates might not be adjacent or continuos (i.e. for some of the X columns, a specific date might not be present)

Thank you so much!

答:
You could shift:

```<code>import pandas as pd
df = pd.DataFrame([1,0,0,1,1,0], columns=['day'])
d.head()

   day
0   1
1   0
2   0
3   1
4   1

df['Once Day Before'] = d['day'].shift(-1)
df['One Day After'] = df['day'].shift(1)
df['Two Days before'] = df['day'].shift(-2)

df.head()

day Holiday   One Day Before    One Day After   Two Days before
0     1            0.0               NaN              0.0
1     0            0.0               1.0              1.0
2     0            1.0               0.0              1.0
3     1            1.0               0.0              0.0
4     1            0.0               1.0              NaN
5     0            NaN               1.0              NaN
</code>```

This would move the is_holiday up or down and to a new column. You will have to deal with the NaN's though.

Body:
I'm trying to do some feature engineering for a pandas data frame.

Say I have this:

Data frame 1:
X |  date     | is_holiday
a |  1/4/2018 | 0
a |  1/5/2018 | 0
a |  1/6/2018 | 1
a |  1/7/2018 | 0
a |  1/8/2018 | 0
...
b |  1/1/2018 | 1

I'd like to have an additional indicator for some dates, to indicate if the date is before 1 and 2 days from a holiday, and also 1 and 2 days after.

Data frame 1:
X |  date     | is_holiday | one_day_before_hol | ... | one_day_after_hol
a |  1/4/2018 | 0          | 0                  | ... | 0
a |  1/5/2018 | 0          | 1                  | ... | 0
a |  1/6/2018 | 1          | 0                  | ... | 0
a |  1/7/2018 | 0          | 0                  | ... | 1
a |  1/8/2018 | 0          | 0                  | ... | 0
...
b |  1/1/2018 | 1          | 0                  | ... | 0

Is there any efficient way to do it? I believe I can do it using for statements, but since I'm new to python, I'd like to see if there is an elegant way to do it. Dates might not be adjacent or continuos (i.e. for some of the X columns, a specific date might not be present)

Thank you so much!

Body:
You could shift:

import pandas as pd
df = pd.DataFrame([1,0,0,1,1,0], columns=['day'])
d.head()

   day
0   1
1   0
2   0
3   1
4   1

df['Once Day Before'] = d['day'].shift(-1)
df['One Day After'] = df['day'].shift(1)
df['Two Days before'] = df['day'].shift(-2)

df.head()

day Holiday   One Day Before    One Day After   Two Days before
0     1            0.0               NaN              0.0
1     0            0.0               1.0              1.0
2     0            1.0               0.0              1.0
3     1            1.0               0.0              0.0
4     1            0.0               1.0              NaN
5     0            NaN               1.0              NaN

This would move the is_holiday up or down and to a new column. You will have to deal with the NaN's though.


问:
Can I manually run a C# class containing a Main() method from a project that is not a console application project?
I am pretty new in .NET\C# (I came from Java) and I have the following doubt.

In my solution I have a project that should be a SharePoint job, something like this in my solution explorer:

I know that this project is deployed as a SharePoint job and it works fine.

Now I have the need to manually perform a specific operation that is in some way related to this job. So my idea was to create this MigrateAttachments class into this project and put a Main() method here, then perform only this class as a script:

```<code>namespace XXXMigrationJob
{
    class MigrateAttachments
    {
        static void Main(string[] args)
        {

            Debug.Print("MigrateAttachments Main() START");

            Debug.Print("MigrateAttachments Main() END");
        }
    }
}
</code>```

But it seems to me that I can't perform this Main() method as a standalone method and that the only way to do it is to create a brand new Console Application project that will contain this class.

is it true or am I missing something and I can manually run this MigrateAttachements Main() method also into my XXXMigrationJob project?

答:
No you can't really just execute that.  It will be in a DLL not an exe. You'll need to bootstrap it somehow.

I would refactor the reusable code into a class library.  Then create a console app as you mentioned.  Reference the reusable class library and call it.

However if you don't want to create a console app, then the link NineBerry put in discusses calling .net code with PowerShell and Reflection.

Body:
I am pretty new in .NET\C# (I came from Java) and I have the following doubt.

In my solution I have a project that should be a SharePoint job, something like this in my solution explorer:

I know that this project is deployed as a SharePoint job and it works fine.

Now I have the need to manually perform a specific operation that is in some way related to this job. So my idea was to create this MigrateAttachments class into this project and put a Main() method here, then perform only this class as a script:

namespace XXXMigrationJob
{
    class MigrateAttachments
    {
        static void Main(string[] args)
        {

            Debug.Print("MigrateAttachments Main() START");

            Debug.Print("MigrateAttachments Main() END");
        }
    }
}

But it seems to me that I can't perform this Main() method as a standalone method and that the only way to do it is to create a brand new Console Application project that will contain this class.

is it true or am I missing something and I can manually run this MigrateAttachements Main() method also into my XXXMigrationJob project?


问:
Assist me in finding the error: invalid method declaration; return type required
This is my last homework for my java class and I have been trying to run this through a compiler but I don't understand whats wrong with the code.

I tried using void after reading about how that would fix the return type issue but that just made it worse, maybe I was putting void in the wrong place.

```<code>public class Exercise09_01 {
    private double width = 1;
    private double height = 1;

    public Rectangle() {
    }

    public Rectangle(double newWidth, double newHeight) {
        width = newWidth;
        height = newHeight;
    }

    public double getArea() {
        return width * height;
    }

    public double getPerimeter() {
        return 2 * (width + height);
    }

    public static void main(String[] args) {
        Rectangle rectangle1 = new Rectangle(4, 40);
        System.out.println("The area of a 4.0 x 40.0 Rectangle is " +
        rectangle1.getArea());
        System.out.println("The perimeter of a 4.0 x 40.0 Rectangle is " +
        rectangle1.getPerimeter());
        Rectangle rectangle2 = new Rectangle(3.5, 35.9);
        System.out.println("The area of a 3.5 x 35.9 Rectangle is " +
        rectangle2.getArea());
        System.out.println("The perimeter of a 3.5 x 35.9 Rectangle is " +
        rectangle2.getPerimeter());
    }
}
</code>```

This is my last homework for this class I just want this over with any help is appreciated.

答:
```<code>public Rectangle() {
}
</code>```

This is a method as far as Java is concerned. And all methods have to have  a return type.

```<code>public Rectangle(double newWidth, double newHeight) {
width = newWidth;
  height = newHeight;
  }
</code>```

The same here.

You don't need the 1st one really unless you really need to be able to make one without those values set.

You can just rename them, but you probably just want to rename the class Rectangle

Body:
This is my last homework for my java class and I have been trying to run this through a compiler but I don't understand whats wrong with the code.

I tried using void after reading about how that would fix the return type issue but that just made it worse, maybe I was putting void in the wrong place.

public class Exercise09_01 {
    private double width = 1;
    private double height = 1;

    public Rectangle() {
    }

    public Rectangle(double newWidth, double newHeight) {
        width = newWidth;
        height = newHeight;
    }

    public double getArea() {
        return width * height;
    }

    public double getPerimeter() {
        return 2 * (width + height);
    }

    public static void main(String[] args) {
        Rectangle rectangle1 = new Rectangle(4, 40);
        System.out.println("The area of a 4.0 x 40.0 Rectangle is " +
        rectangle1.getArea());
        System.out.println("The perimeter of a 4.0 x 40.0 Rectangle is " +
        rectangle1.getPerimeter());
        Rectangle rectangle2 = new Rectangle(3.5, 35.9);
        System.out.println("The area of a 3.5 x 35.9 Rectangle is " +
        rectangle2.getArea());
        System.out.println("The perimeter of a 3.5 x 35.9 Rectangle is " +
        rectangle2.getPerimeter());
    }
}

This is my last homework for this class I just want this over with any help is appreciated.

Body:
public Rectangle() {
}

This is a method as far as Java is concerned. And all methods have to have  a return type.

public Rectangle(double newWidth, double newHeight) {
width = newWidth;
  height = newHeight;
  }

The same here.

You don't need the 1st one really unless you really need to be able to make one without those values set.

You can just rename them, but you probably just want to rename the class Rectangle


问:
Get integer value from malformed query string
I'm looking for an way to parse a substring using PHP, and have come across preg_match however I can't seem to work out the rule that I need.

I am parsing a web page and need to grab a numeric value from the string, the string is like this

```<code>producturl.php?id=736375493?=tm
</code>```

I need to be able to obtain this part of the string:

736375493

答:
Unfortunately, you have a malformed url query string, so a regex technique is most appropriate.  See what I mean.

There is no need for capture groups.  Just match id= then forget those characters with \K, then isolate the following one or more digital characters.

Code (Demo)

```<code>$str = 'producturl.php?id=736375493?=tm';
echo preg_match('~id=\K\d+~', $str, $out) ? $out[0] : 'no match';
</code>```

Output:

```<code>736375493
</code>```

For completeness, there 8s another way to scan the formatted string and explicitly return an int-typed value. (Demo)

```<code>var_dump(
    sscanf($str, '%*[^?]?id=%d')[0]
);
</code>```

The %*[^?] means: greedily match one or more non-question mark characters, but do not capture the substring.  The remainder of the format parameter matches the literal sequence ?id=, then greedily captures one or more numbers.  The returned value will be cast as an integer because of the %d placeholder.

Body:
I'm looking for an way to parse a substring using PHP, and have come across preg_match however I can't seem to work out the rule that I need.

I am parsing a web page and need to grab a numeric value from the string, the string is like this

producturl.php?id=736375493?=tm

I need to be able to obtain this part of the string:

736375493

Body:
Unfortunately, you have a malformed url query string, so a regex technique is most appropriate.  See what I mean.

There is no need for capture groups.  Just match id= then forget those characters with \K, then isolate the following one or more digital characters.

Code (Demo)

$str = 'producturl.php?id=736375493?=tm';
echo preg_match('~id=\K\d+~', $str, $out) ? $out[0] : 'no match';

Output:

736375493

For completeness, there 8s another way to scan the formatted string and explicitly return an int-typed value. (Demo)

var_dump(
    sscanf($str, '%*[^?]?id=%d')[0]
);

The %*[^?] means: greedily match one or more non-question mark characters, but do not capture the substring.  The remainder of the format parameter matches the literal sequence ?id=, then greedily captures one or more numbers.  The returned value will be cast as an integer because of the %d placeholder.


问:
Dynamically Creating Pages On Button Click
I am using Ionic 4 to create an app. So far, I have a floating action button, when you click it you can add a new item to a list (starts empty) that is displayed on screen. Each item has name and a button.

I want it so that whenever a button is pressed on the item, it goes to a page for that specific item.

I do not have the faintest idea how to do this so, this leaves me with a few questions:

1) Should I have one page premade and dynamically change the contents of it based on item button clicked OR whenever item is created, dynamically create a page unique to that item?

2) Based on the last question, what is the best way to accomplish it?

答:
your idea is what angular solves or why we call it SPA in the first place.

you need first to check Routing in Angular and try to learn and apply to it and you will find what you are looking for - specifically in routing params -.

Check these links for more information:

https://www.youtube.com/watch?v=Ba2QIjUwi9E

https://angular.io/guide/router

https://www.smashingmagazine.com/2018/11/a-complete-guide-to-routing-in-angular/


问:
Non-compressed, non-minimal grammar for programming language C
Programming languages are defined via a grammar, e.g. Java is defined in the JLS, see here

This is a minimal, "compressed" grammar, no construct is used twice: the result are - for me - unuseful grammar descriptions like MethodDeclaratorRest which is appended to the MethodOrFieldDecl as you can see here, I'd call it the "minimal,compressed approach"

```MethodOrFieldDecl:
        Type Identifier MethodOrFieldRest

MethodOrFieldRest:
        VariableDeclaratorRest
        MethodDeclaratorRest

MethodDeclaratorRest:
        FormalParameters {[]} [throws QualifiedIdentifierList] ( MethodBody |   ; )```

This is in general ok, but I'd like to have a grammar like the following where all the necessary information of the type MethodDeclaration are listed, I'd call it the "top-down-approach":

```MethodDeclaration:
   [ Javadoc ] { ExtendedModifier }
          [  ]
        ( Type | void ) Identifier (
        [ FormalParameter
             { , FormalParameter } ] ) {[ ] }
        [ throws TypeName { , TypeName } ] ( Block | ; )```

Searching for a "top-down grammar approach I found the website of Pete Jinks, using the "minimal,compressed approach": here

Now, I'd like to have a grammar definition of the programming language C using the "top-down-approach".

答: "The C Programming Language" by Kernighan and Ritchie 2e (pub. Prentice-Hall) has an (E)BNF grammar in it... there may also be a version accessible online.</p>

Body:
Programming languages are defined via a grammar, e.g. Java is defined in the JLS, see here

This is a minimal, "compressed" grammar, no construct is used twice: the result are - for me - unuseful grammar descriptions like MethodDeclaratorRest which is appended to the MethodOrFieldDecl as you can see here, I'd call it the "minimal,compressed approach"

MethodOrFieldDecl:
        Type Identifier MethodOrFieldRest

MethodOrFieldRest:
        VariableDeclaratorRest
        MethodDeclaratorRest

MethodDeclaratorRest:
        FormalParameters {[]} [throws QualifiedIdentifierList] ( MethodBody |   ; )

This is in general ok, but I'd like to have a grammar like the following where all the necessary information of the type MethodDeclaration are listed, I'd call it the "top-down-approach":

MethodDeclaration:
   [ Javadoc ] { ExtendedModifier }
          [  ]
        ( Type | void ) Identifier (
        [ FormalParameter
             { , FormalParameter } ] ) {[ ] }
        [ throws TypeName { , TypeName } ] ( Block | ; )

Searching for a "top-down grammar approach I found the website of Pete Jinks, using the "minimal,compressed approach": here

Now, I'd like to have a grammar definition of the programming language C using the "top-down-approach".