问:
ASP.NET Core app does not use setting from the appsettings.json, after trying to publish to Azure
My app when executed locally does not read ConnectionString from the appsettings.json.
I had configured "Connected Services" in VS2019 for my ASP.NET Core 3.1 app. Where the SQL DB connection got a wrong DB name (probably got autogenerated). I then have deleted this configuration and ignored it from my profile.
But now when I'm trying to execute this app locally - it is still trying to use DB from that config.

Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot open
database "aspnet-53bc9b9d-9d6a-45d4-1122-2a2761773502" requested by
the login. The login failed.

1. Is there a place it is got cached at or where I need to remove it
manually from?

2. Also why it does not read from my appsettings.json?

appsettings.json:

```<code>**{
  "Serilog": {
    "Using": [
      "Serilog.Sinks.Console",
      "Serilog.Sinks.File",
      "Serilog.Sinks.Seq",
      "Serilog.Sinks.Loggly"
    ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Debug",
        "System": "Debug"
      }
    },
    "Enrich": [
      "FromLogContext",
      "WithMachineName",
      "WithProcessId",
      "WithThreadId"
    ],
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": {
          "path": "C:\\ODATA\\Logs\\log.json"
        },
        "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
      }
    ],
    "Properties": {
      "Application": "ODataTestApp"
    }
  },
  "ConnectionStrings": {
    "Database": "Data Source=*MyDBConnectionString*"
  },
  "AllowedHosts": "*",
  "ApplicationInsights": {
    "ConnectionString": "InstrumentationKey=*my-key*/"
  }
}**
</code>```

P.S. I added those Connected Services as part of the Publish to Azure steps. I have tried to Publish my app to Azure, but it failed (for different reasons).

答:
In local when we debug the application, it will read the configuration from appsettings.dev.json file.

Automatically set appsettings.json for dev and release environments in asp.net core?

When we deploy the application to azure. By default, it will read the appsettings.json file.

But if we have configure the connection string in azure portal, it will overwrite the connection string.

The settings in the azure portal take precedence over the configuration in the appsettings.json file in the project file.

Body:
My app when executed locally does not read ConnectionString from the appsettings.json.
I had configured "Connected Services" in VS2019 for my ASP.NET Core 3.1 app. Where the SQL DB connection got a wrong DB name (probably got autogenerated). I then have deleted this configuration and ignored it from my profile.
But now when I'm trying to execute this app locally - it is still trying to use DB from that config.

Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot open
database "aspnet-53bc9b9d-9d6a-45d4-1122-2a2761773502" requested by
the login. The login failed.

1. Is there a place it is got cached at or where I need to remove it
manually from?

2. Also why it does not read from my appsettings.json?

appsettings.json:

**{
  "Serilog": {
    "Using": [
      "Serilog.Sinks.Console",
      "Serilog.Sinks.File",
      "Serilog.Sinks.Seq",
      "Serilog.Sinks.Loggly"
    ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Debug",
        "System": "Debug"
      }
    },
    "Enrich": [
      "FromLogContext",
      "WithMachineName",
      "WithProcessId",
      "WithThreadId"
    ],
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": {
          "path": "C:\\ODATA\\Logs\\log.json"
        },
        "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
      }
    ],
    "Properties": {
      "Application": "ODataTestApp"
    }
  },
  "ConnectionStrings": {
    "Database": "Data Source=*MyDBConnectionString*"
  },
  "AllowedHosts": "*",
  "ApplicationInsights": {
    "ConnectionString": "InstrumentationKey=*my-key*/"
  }
}**

P.S. I added those Connected Services as part of the Publish to Azure steps. I have tried to Publish my app to Azure, but it failed (for different reasons).


来源: stackexchange

问:
Groupby 2 columns and find .min of multiple other columns (python pandas)
My data frame looks like this:

```<code>|Months   |  Places | Sales_X |   Sales_Y |  Sales_Z |
|----------------------------------------------------|
|**month1 |  Place1 | 10000   |   12000   |  13000   |
|month1   |  Place2 |  300    |     200   |   1000   |
|month1   |  Place3 |  350    |    1000   |  1200**  |
|month2   |  Place2 |  1400   |    12300  |  14000   |
|month2   |  Place3 |  9000   |    8500   |    150   |
|month2   |  Place1 |  90     |    4000   |   3000   |
|month3   |  Place2 |  12350  |    8590   |   4000   |
|month3   |  Place1 | 4500    |    7020   |   8800   |
|month3   |  Place3 |  351    |    6500   |   4567   |
</code>```

I need to find the highest number from the three sales columns by month and show the name of the place with the highest number.

I have been trying to solve it by using pandas.DataFrame.idxmax and groupby but it does not seem to work.

I created a new df with the highest number/row which may help

```<code>|Months  |  Places  |  Highest_sales|
|-----------------------------------|
|**month1|   Place1 |    10000      |
|month1  |   Place2 |      200      |
|month1  |   Place3 |      350**    |
|        |          |               |
|**month2|   Place2 |     1400      |
|month2  |   Place3 |      150      |
|month2  |   Place1 |      90**     |
|        |          |               |
|**month3|  Place2  |     4000      |
|month3  |  Place1  |     4500      |
|month3  |   Place3 |     351**     |
|-----------------------------------|
</code>```

Now I just need the highest number/ month and the name of the place. When using groupby on two columns and getting the min of the Lowest_sales, the result

```<code>df.groupby(['Months', 'Places'])['Highest_sales'].max()
</code>```

when I run this

```<code>Months  Places        Highest Sales

1       Place1          1549.0
        Place2          2214.0
        Place3          2074.0
                    ...
12      Place1          1500.0
        Place2          8090.0
        Place3          2074.0
</code>```

the format I am looking for would be

```<code>|**Months|Places                    |Highest Sales**|
|--------|--------------------------|---------------|
|Month1  |Place(*of highest sales*) |100000         |
|Month2  |Place(*of highest sales*) |900000         |
|Month3  |Place(*of highest sales*) |3232000        |
|Month4  |Place(*of highest sales*) |1300833        |
|....    |                          |               |
|Month12 |Place(*of highest sales*) |               |
-----------------------------------------------------

12 rows and 3 columns
</code>```

答:
Use DataFrame.filter for Sales columns, create Highest column adn then aggregate DataFrameGroupBy.idxmax only for Months and select rows and columns by list in DataFrame.loc:

```<code>#columns with substring Sales
df1 = df.filter(like='Sales')
#or all columns from third position
#df1 = df.iloc[: 2:]

df['Highest'] = df1.min(axis=1)
df = df.loc[df.groupby('Months')['Highest'].idxmax(), ['Months','Places','Highest']]

print (df)
   Months  Places  Highest
0  month1  Place1    10000
3  month2  Place2     1400
7  month3  Place1     4500
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My data frame looks like this:

|Months   |  Places | Sales_X |   Sales_Y |  Sales_Z |
|----------------------------------------------------|
|**month1 |  Place1 | 10000   |   12000   |  13000   |
|month1   |  Place2 |  300    |     200   |   1000   |
|month1   |  Place3 |  350    |    1000   |  1200**  |
|month2   |  Place2 |  1400   |    12300  |  14000   |
|month2   |  Place3 |  9000   |    8500   |    150   |
|month2   |  Place1 |  90     |    4000   |   3000   |
|month3   |  Place2 |  12350  |    8590   |   4000   |
|month3   |  Place1 | 4500    |    7020   |   8800   |
|month3   |  Place3 |  351    |    6500   |   4567   |

I need to find the highest number from the three sales columns by month and show the name of the place with the highest number.

I have been trying to solve it by using pandas.DataFrame.idxmax and groupby but it does not seem to work.

I created a new df with the highest number/row which may help

|Months  |  Places  |  Highest_sales|
|-----------------------------------|
|**month1|   Place1 |    10000      |
|month1  |   Place2 |      200      |
|month1  |   Place3 |      350**    |
|        |          |               |
|**month2|   Place2 |     1400      |
|month2  |   Place3 |      150      |
|month2  |   Place1 |      90**     |
|        |          |               |
|**month3|  Place2  |     4000      |
|month3  |  Place1  |     4500      |
|month3  |   Place3 |     351**     |
|-----------------------------------|

Now I just need the highest number/ month and the name of the place. When using groupby on two columns and getting the min of the Lowest_sales, the result

df.groupby(['Months', 'Places'])['Highest_sales'].max()

when I run this

Months  Places        Highest Sales

1       Place1          1549.0
        Place2          2214.0
        Place3          2074.0
                    ...
12      Place1          1500.0
        Place2          8090.0
        Place3          2074.0

the format I am looking for would be

|**Months|Places                    |Highest Sales**|
|--------|--------------------------|---------------|
|Month1  |Place(*of highest sales*) |100000         |
|Month2  |Place(*of highest sales*) |900000         |
|Month3  |Place(*of highest sales*) |3232000        |
|Month4  |Place(*of highest sales*) |1300833        |
|....    |                          |               |
|Month12 |Place(*of highest sales*) |               |
-----------------------------------------------------

12 rows and 3 columns

Body:
Use DataFrame.filter for Sales columns, create Highest column adn then aggregate DataFrameGroupBy.idxmax only for Months and select rows and columns by list in DataFrame.loc:

#columns with substring Sales
df1 = df.filter(like='Sales')
#or all columns from third position
#df1 = df.iloc[: 2:]

df['Highest'] = df1.min(axis=1)
df = df.loc[df.groupby('Months')['Highest'].idxmax(), ['Months','Places','Highest']]

print (df)
   Months  Places  Highest
0  month1  Place1    10000
3  month2  Place2     1400
7  month3  Place1     4500


问:
How to parse a url from a String in android?
I want to parse the url from a String in android. The example String is

```<code>"This is a new message. The content of the message is in 'http://www.example.com/asd/abc' "
</code>```

I want to parse the url http://www.example.com/asd/abc from the String without using the subString method.

答:
I use this in Kotlin</p>
```<code>fun findAllUrls(text: String): List<String> {
    return Regex(Patterns.WEB_URL.pattern()).findAll(text).map {
        it.value
    }.toList()
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to parse the url from a String in android. The example String is

"This is a new message. The content of the message is in 'http://www.example.com/asd/abc' "

I want to parse the url http://www.example.com/asd/abc from the String without using the subString method.

Body:
I use this in Kotlin

fun findAllUrls(text: String): List<String> {
    return Regex(Patterns.WEB_URL.pattern()).findAll(text).map {
        it.value
    }.toList()
}


问:
`%_` and detecting unwanted named arguments to a method
As I understand, a named argument to a method goes to %_ if not found in the signature (not sure why!). To detect this, I do

```<code>die "Extra args passed" if %_;
</code>```

for the methods I remember to do and that are worth doing. Is there a way to automate this for example with some decorator kind of thing? Or I miss and %_ is actually a very useful thing in object oriented Raku programming?

答:
Is there a way to automate this for example with some decorator kind of thing?

I'm not aware of a way of doing that currently.

I once developed a method trait to remove the implicit *%_ from the signature of a method.  In the hopes I could simplify dispatching on multi methods that take many different (combinations) of named arguments.

It did not end well.  I don't recall exactly why anymore, but I decided to postpone trying to do that until after the RakuAST branch has landed.

Body:
As I understand, a named argument to a method goes to %_ if not found in the signature (not sure why!). To detect this, I do

die "Extra args passed" if %_;

for the methods I remember to do and that are worth doing. Is there a way to automate this for example with some decorator kind of thing? Or I miss and %_ is actually a very useful thing in object oriented Raku programming?


问:
Problem with "this" in JS
Consider the following code:

```<code>    var table = function () {

        return {
            _init: function (tableId) {
                this.tableId = tableId;
                this.table = $("#" + tableId);
            },

            removeStripes: function() {
                this.table.find(".alt").removeClass("alt");
            },

            addStripes: function () {
                this.table.find("tbody tr:even").addClass("alt");
            },

            resetStripes: function() {
                this.removeStripes();
                this.addStripes();
            },

            sort: function (options) {
                this.table.tablesorter(options);
                this.table.bind("sortEnd", this.resetStripes);
            },

        }

    }

var newTable = new table();
newTable._init("tableId");
var options = {};
newTable.sort(options);
</code>```

The browser says this.removeStripes called by this.resetStripes, on one of the last lines) is not a function. I guess there is some error with this, but I can't figure out where it is. Any idea, anyone?

答:
Try this:

```<code>var table = function () {
        var that = this;
        return {
            _init: function (tableId) {
                that.tableId = tableId;
                that.table = $("#" + tableId);
            },

            removeStripes: function() {
                that.table.find(".alt").removeClass("alt");
            },

            addStripes: function () {
                that.table.find("tbody tr:even").addClass("alt");
            },

            resetStripes: function() {
                that.removeStripes();
                that.addStripes();
            },

            sort: function (options) {
                that.table.tablesorter(options);
                that.table.bind("sortEnd", that.resetStripes);
            },

        }

    }

var newTable = new table();
newTable._init("tableId");
var options = {};
newTable.sort(options);
</code>```

Its a common pattern in JavaScript to save the this into another variable so you can reference it in deeper nested functions. As javascript this always refers to either the global object or the this object that was passed to the function through .call or .apply it's rather unreliable to use at times..

Title: Problem with "this" in JS

Body:
Consider the following code:

    var table = function () {

        return {
            _init: function (tableId) {
                this.tableId = tableId;
                this.table = $("#" + tableId);
            },

            removeStripes: function() {
                this.table.find(".alt").removeClass("alt");
            },

            addStripes: function () {
                this.table.find("tbody tr:even").addClass("alt");
            },

            resetStripes: function() {
                this.removeStripes();
                this.addStripes();
            },

            sort: function (options) {
                this.table.tablesorter(options);
                this.table.bind("sortEnd", this.resetStripes);
            },

        }

    }

var newTable = new table();
newTable._init("tableId");
var options = {};
newTable.sort(options);

The browser says this.removeStripes called by this.resetStripes, on one of the last lines) is not a function. I guess there is some error with this, but I can't figure out where it is. Any idea, anyone?

Body:
Try this:

var table = function () {
        var that = this;
        return {
            _init: function (tableId) {
                that.tableId = tableId;
                that.table = $("#" + tableId);
            },

            removeStripes: function() {
                that.table.find(".alt").removeClass("alt");
            },

            addStripes: function () {
                that.table.find("tbody tr:even").addClass("alt");
            },

            resetStripes: function() {
                that.removeStripes();
                that.addStripes();
            },

            sort: function (options) {
                that.table.tablesorter(options);
                that.table.bind("sortEnd", that.resetStripes);
            },

        }

    }

var newTable = new table();
newTable._init("tableId");
var options = {};
newTable.sort(options);

Its a common pattern in JavaScript to save the this into another variable so you can reference it in deeper nested functions. As javascript this always refers to either the global object or the this object that was passed to the function through .call or .apply it's rather unreliable to use at times..


问:
Format SQL in a string (in python or any language)
Is there a cli tool that can be used to format SQL code inside strings in a given .py file? Example:

```<code>import foo

query = """SELECT please, format, me

FROM    i-am-an-unformatted-query

"""

some_client.query(query)

</code>```

could for example yield

```<code>import foo

query = """
SELECT
    please,
    format,
    me
FROM i-am-an-unformatted-query"""

some_client.query(query)
</code>```

ie, formatting would only occur inside the query string.

Does such a tool exist? The once I've looked at only format standalone files. I would prefer not having discussions about SQL formatting with my colleagues but align around a tool, much like we do with for example black for python formatting.

答:
I mean I probably didn't get your question right but, if you're referring to formatting the query i.e : changing it based upon a request or variable you could simply use:

```<code>print( """
SELECT {},
   format, me
FROM i-am-an-unformatted-query""",format(please))
</code>```

and the print could be placed in a function that takes the please as an argument.

Body:
Is there a cli tool that can be used to format SQL code inside strings in a given .py file? Example:

import foo

query = """SELECT please, format, me

FROM    i-am-an-unformatted-query

"""

some_client.query(query)

could for example yield

import foo

query = """
SELECT
    please,
    format,
    me
FROM i-am-an-unformatted-query"""

some_client.query(query)

ie, formatting would only occur inside the query string.

Does such a tool exist? The once I've looked at only format standalone files. I would prefer not having discussions about SQL formatting with my colleagues but align around a tool, much like we do with for example black for python formatting.

Body:
I mean I probably didn't get your question right but, if you're referring to formatting the query i.e : changing it based upon a request or variable you could simply use:

print( """
SELECT {},
   format, me
FROM i-am-an-unformatted-query""",format(please))

and the print could be placed in a function that takes the please as an argument.


问:
Why I cannot set my java program with expected memory size?
I limit my java program with -Xmx2g -Xmn1280m -Xms2g -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=152m -XX:SurvivorRatio=8 -XX:+UseConcMarkSweepGC.

And then, I use top to show memory uesage, which shows:

```<code>Tasks: 139 total,   1 running, 138 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.5 us,  0.9 sy,  0.2 ni, 98.4 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  7896536 total,  2724188 free,  1870168 used,  3302180 buff/cache
KiB Swap:        0 total,        0 free,        0 used.  5756128 avail Mem

   PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
 69518 service   20   0 4089960   1.5g  16916 S   1.3 19.3   3:03.27 java
</code>```

The real memory uesage is 1.5g.

But I have already set the jvm heap size.

Why this happened?
Thank you very much.

答: The maximum java heap size is set with -Xmx. In your question you set it twice to 2GB and 1.5GB < 2GB. The JVM behaves as told.

Body:
I limit my java program with -Xmx2g -Xmn1280m -Xms2g -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=152m -XX:SurvivorRatio=8 -XX:+UseConcMarkSweepGC.

And then, I use top to show memory uesage, which shows:

Tasks: 139 total,   1 running, 138 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.5 us,  0.9 sy,  0.2 ni, 98.4 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  7896536 total,  2724188 free,  1870168 used,  3302180 buff/cache
KiB Swap:        0 total,        0 free,        0 used.  5756128 avail Mem

   PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
 69518 service   20   0 4089960   1.5g  16916 S   1.3 19.3   3:03.27 java

The real memory uesage is 1.5g.

But I have already set the jvm heap size.

Why this happened?
Thank you very much.


问:
How can I resolve omp_get_wtime undefined in C?
I have a program in C with an OpenMP library. I am trying to measure the execution time for a loop to add numbers except that I am getting an error that the reference the function omp_get_wtime() is undefined while I have the library file included in the header section of my code file...

Why am I getting this error and how can I resolve it?

```<code>#include <omp.h>
#include <stdlib.h>
#include <string.h>

int main(){
    // Number of threads to use
    int no_threads = 3;

    // Mark the execution go mark
    double start = omp_get_wtime();

    // Parallelize the loop
    #pragma omp parallel num_threads(no_threads)

    for(int i=0; i<1000; i++){
        printf("%d", i);
    }

    double end_time = omp_get_wtime();
    printf("%f", end_time - start);
}
</code>```

I tried to compile even before I started using the #pragma directive and got the error that the omp function is undefined and the function in the file.

答:
You should build an OMP program with a flag.

gcc -fopenmp test.c
```

Body:
I have a program in C with an OpenMP library. I am trying to measure the execution time for a loop to add numbers except that I am getting an error that the reference the function omp_get_wtime() is undefined while I have the library file included in the header section of my code file...

Why am I getting this error and how can I resolve it?

#include <omp.h>
#include <stdlib.h>
#include <string.h>

int main(){
    // Number of threads to use
    int no_threads = 3;

    // Mark the execution go mark
    double start = omp_get_wtime();

    // Parallelize the loop
    #pragma omp parallel num_threads(no_threads)

    for(int i=0; i<1000; i++){
        printf("%d", i);
    }

    double end_time = omp_get_wtime();
    printf("%f", end_time - start);
}

I tried to compile even before I started using the #pragma directive and got the error that the omp function is undefined and the function in the file.


问:
How to put a Wrap widget in a Column widget in Flutter
What I want:
image

```<code>child: IntrinsicWidth(
  child: Column(
    children: [
      Stack(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: const [
              Red(),
              Green(),
            ],
          ),
          const Align(
            child: Yellow(),
          ),
        ],
      ),
      const Blue(),
      const PurpleWrap(),
    ],
  ),
),
</code>```

What I got:
image

How can I achieve what I want?

Also can I achieve it without using IntrinsicWidth/Stack?

答: their is problem in the Blue(), inside the blue, you should just make the width: double.infinity; and what else problem you got ?</p>

Body:
What I want:
image

child: IntrinsicWidth(
  child: Column(
    children: [
      Stack(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: const [
              Red(),
              Green(),
            ],
          ),
          const Align(
            child: Yellow(),
          ),
        ],
      ),
      const Blue(),
      const PurpleWrap(),
    ],
  ),
),

What I got:
image

How can I achieve what I want?

Also can I achieve it without using IntrinsicWidth/Stack?


问:
Create Custom policy in Azure API Management
I want to validate custom claims which are part of JWT token. Token has custom user claims, application claims and other details.

For user claims, I want to have custom policy/block like

<validate-logintype> {validation logic in this block} </validation-logintype>

For application claims, custom policy like

<request-from> {validation logic} </request-from>

Include the above blocks in actual API policy

User API:

```<code>    <policy>
       <inbound>
          <validate-logintype>
          <base />
       </inbound>
    </policy>
</code>```

Can someone please help how this can be implemented.

答:
something like this?</p>
```<code><policies>
<inbound>
    <base />
    <set-header id="apim-generated-policy" name="Ocp-Apim-Subscription-Key" exists-action="delete" />
    <validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
        <openid-config url="https://login.microsoftonline.com/<yourtenant>/.well-known/openid-configuration" />
        <audiences>
            <audience>{{claim1}}</audience>
        </audiences>
    </validate-jwt>
</inbound>
</code>```

Body:
I want to validate custom claims which are part of JWT token. Token has custom user claims, application claims and other details.

For user claims, I want to have custom policy/block like

<validate-logintype> {validation logic in this block} </validation-logintype>

For application claims, custom policy like

<request-from> {validation logic} </request-from>

Include the above blocks in actual API policy

User API:

    <policy>
       <inbound>
          <validate-logintype>
          <base />
       </inbound>
    </policy>

Can someone please help how this can be implemented.

Body:
something like this?

<policies>
<inbound>
    <base />
    <set-header id="apim-generated-policy" name="Ocp-Apim-Subscription-Key" exists-action="delete" />
    <validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
        <openid-config url="https://login.microsoftonline.com/<yourtenant>/.well-known/openid-configuration" />
        <audiences>
            <audience>{{claim1}}</audience>
        </audiences>
    </validate-jwt>
</inbound>


问:
Bitbucket/Github: permission denied public key
when I am trying to clone a rails app repo I have got permission to, I am getting this issue.

```<code>Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

Even after adding public key by generating one, I am unable to solve this.

Although I am able to clone using he https method but after making changes, the same error comes while I try to push the code.

Please suggest an answer for this.

答:
When attempting to clone, push, or pull over SSH with Git, you may receive one of these messages if Bitbucket couldn't authenticate with the keys that your SSH agent offered.

Here are the most common reasons why you may see these messages:

You used sudo when attempting the connection

You shouldn't use sudo when cloning, pushing, or pulling because the ssh-agent runs on the user level, not the root level.

Your public key isn't loaded into Bitbucket

To check if your public key is loaded into Bitbucket, do the following:

From Bitbucket, choose Personal settings from your avatar in the lower left.
The Account settings page displays.

Click SSH keys.
The SSH keys page shows a list of any existing keys.

If you don't have any keys listed, you can follow our Set up an SSH key documentation to set one up.

Your key isn't loaded into your SSH agent

If your SSH agent doesn't know to offer Bitbucket a key, the connection fails. You may run into this issue if you've recently restarted your system.

You can refer to this Article for more informations:
https://support.atlassian.com/bitbucket-cloud/docs/troubleshoot-ssh-issues/

Body:
when I am trying to clone a rails app repo I have got permission to, I am getting this issue.

Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Even after adding public key by generating one, I am unable to solve this.

Although I am able to clone using he https method but after making changes, the same error comes while I try to push the code.

Please suggest an answer for this.


问:
In JavaFX, Is there a best practice or framework for creating program help files?
I've been experimenting with using HTML as a structure for generating a help information area for a desktop program that I've finished writing and that seems to work ok, though I don't really like the way it is turning out and I began to wonder if perhaps there might be a better way to go about it. Perhaps a library that makes generating and linking content within Java a little easier in that context or some other means that I'm not aware of.

I did some Googling on the topic but found nothing specifically in reference to help menu / content creation.

Does anyone know of any libraries out there that would make it easier to create help info for end users?

Or, is there a "best practice" for doing this or any other method to that end?

Thank you,

Mike

答:
What does Idea do?

Intellij is large java app that has decent help documentation. You could look and see how they did that, if that is something you wish to emulate. I think it is mostly good quality writing and organization rather than tool support, though I guess they use decent tooling too.

I did a quick check to see how idea create their doc. They write in markdown format. Here is the markdown style guide they use for creating the document, in generated html form and in markdown authoring form. A repository of docs used for one of their products is their open source sdk docs. The SDK docs project is an Idea project, so I guess they just use Idea for authoring.  If it seems to be something that would help you, you could try cloning the project and generating documentation from it or contacting the project contributors for more info.

As far as tying the help content into your app, either you can display it in situ using a WebView or link to it externally using HostServices.  You could study the help system used within Idea to see how they generally do that, e.g. help menus used, key commands responded to, icons used to link to the help system, etc.

Generally, the way it works is:

The document is written in markdown then processed and rendered to html.

The html documents have copious anchors throughout.

The help menu items link to the anchors directly.

Help menus and shortcut keys follow platform specific conventions and differ between Windows and Mac.

There is a single ? icon in dialogs which appears in a consistent place and it links to an anchor in the html for context sensitive help in the dialog.

The documentation itself is hosted on a website so it can be accessed independently of the application.

The app launches an external browser to view the help rather than using something like a WebView to show the help internally.

Additionally, Idea will use tooltips which show up on hover.  Tooltips aren't used for every control or UI element, only certain ones.  If there is a keyboard accelerator which can be used to trigger the control action, then there is a tooltip for it, and in the tooltip it lets you know what the keyboard shortcut to trigger it is.

The rendered HTML to which the app is linked is hosted at the jetbrains website.

Linking to HTML help

You could:

Link to your own hosted website, OR

Link to html files packaged with your app.

Both could be rendered by either WebView or a browser showing a document using HostServices, using the file: protocol to access html files packaged with your app or https: protocol for files hosted on your web server.

What does SceneBuilder do?

For a pure JavaFX application, SceneBuilder is quite large and complex.  It has no reliance on internal help at all, just a single help menu item, accessible via an F1 shortcut.  The help links to a website authored and hosted by Oracle (using the standard tool Oracle use for authoring most Java platform docs, which is likely a commercial tool).  It is not as nicely integrated and context sensitive as the Idea example but it does demonstrate a simple approach to documenting an app via an external website.


问:
html_table_parser not working in command prompt but working in python jupyter notebooks
I am running a batch file which runs my python code through the command prompt. However, when running the code it gives me the following error:

```<code> from html_table_parser import HTMLTableParser
 ModuleNotFoundError: No module named 'html_table_parser'
</code>```

However, when running my code through Jupyter-notebooks its works just fine. Is it because it isn't properly downloaded. My python.exe is found in Anaconda.

My code is the following

```<code>import urllib.request
from pprint import pprint
from html_table_parser import HTMLTableParser
import datetime
# pretty-print python data structures
from pprint import pprint
# for parsing all the tables present  on the website

# for converting the parsed data in a
# pandas dataframe
import pandas as pd
from bs4 import BeautifulSoup

 # Opens a website and read its
 # binary contents (HTTP Response Body)
  def url_get_contents(url):

   # Opens a website and read its
  # binary contents (HTTP Response Body)

  #making request to the website
  req = urllib.request.Request(url=url)
   f = urllib.request.urlopen(req)

   #reading contents of the website
   return f.read()
    xhtml = url_get_contents("https://en.wikipedia.org/wiki/Searching").decode('utf-8')

  # Defining the HTMLTableParser object
  p = HTMLTableParser()

 content = urllib.request.urlopen("https://en.wikipedia.org/wiki/Searching")
  read_content = content.read()
</code>```

答:
```<code>pip install html-table-parser-python3
</code>```

I have solved it by installing the above package.

Body:
I am running a batch file which runs my python code through the command prompt. However, when running the code it gives me the following error:

 from html_table_parser import HTMLTableParser
 ModuleNotFoundError: No module named 'html_table_parser'

However, when running my code through Jupyter-notebooks its works just fine. Is it because it isn't properly downloaded. My python.exe is found in Anaconda.

My code is the following

import urllib.request
from pprint import pprint
from html_table_parser import HTMLTableParser
import datetime
# pretty-print python data structures
from pprint import pprint
# for parsing all the tables present  on the website

# for converting the parsed data in a
# pandas dataframe
import pandas as pd
from bs4 import BeautifulSoup

 # Opens a website and read its
 # binary contents (HTTP Response Body)
  def url_get_contents(url):

   # Opens a website and read its
  # binary contents (HTTP Response Body)

  #making request to the website
  req = urllib.request.Request(url=url)
   f = urllib.request.urlopen(req)

   #reading contents of the website
   return f.read()
    xhtml = url_get_contents("https://en.wikipedia.org/wiki/Searching").decode('utf-8')

  # Defining the HTMLTableParser object
  p = HTMLTableParser()

 content = urllib.request.urlopen("https://en.wikipedia.org/wiki/Searching")
  read_content = content.read()

Body:
pip install html-table-parser-python3

I have solved it by installing the above package.


问:
How to get and set Textfield value in flutter
Sample Data

data

```<code>data1
data2
data3
    data_detail
    data_detail1
        score - > textfield
</code>```

tabel data, how do i do set or get data on scrore, i use textfield.
is it possible to use controller?

Structure Example

Listview.builder(
    itemCount : anything.length
    itemBuilder:(context, index){

    Listview.Builder(
    itemCount : anything[data][index][data_detail].length
    itemBuilder:(context, index2){

        Textfield (
        controller : ??
        )

        }
    )
}
)```

with a structure like that I'm quite confused about the use of controllers in textfields, is it possible to use a list controller with such a structure?

答:
because of the position data as in the question, here I use OnChange

Textfield(
onChanged: (text) {
   your_data/varibale.position = text
}
```

thus there is no need to create a list in the controller to retrieve the value from the textfield

Body:
Sample Data

data

data1
data2
data3
    data_detail
    data_detail1
        score - > textfield

tabel data, how do i do set or get data on scrore, i use textfield.
is it possible to use controller?

Structure Example

Listview.builder(
    itemCount : anything.length
    itemBuilder:(context, index){

    Listview.Builder(
    itemCount : anything[data][index][data_detail].length
    itemBuilder:(context, index2){

        Textfield (
        controller : ??
        )

        }
    )
}
)

with a structure like that I'm quite confused about the use of controllers in textfields, is it possible to use a list controller with such a structure?

Body:
because of the position data as in the question, here I use OnChange

Textfield(
onChanged: (text) {
   your_data/varibale.position = text
}

thus there is no need to create a list in the controller to retrieve the value from the textfield


问:
Python matplotlib not saving charts files
I have historic data on my stock holdings in a database. The object here is to create two charts and save each to png files. I read the data from the db into a pandas dataframe to build the charts. The code runs cleanly - no errors. I see the charts when I run it in Spyder, but nothing is saved. Here is a brief summary of what I'm doing:

```<code>fig1, ax1 = plt.subplots()
... some code
df['Price'].plot(ax=ax1, title=title1)
plt.savefig(figName1, bbox_inches='tight')
fig2, ax2 = plt.subplots()
... some code
df['% Price'].plot(ax=ax2, title=title2)
df['% S&P'].plot(ax=ax2)
plt.savefig(figName2, bbox_inches='tight')
</code>```

Is there something wrong with this approach? Thanks.

答:
I think the problem is that when you call DataFrame.plot() it returns a numpy array of matplotlib.axes.Axes objects. Try to use get_figure() like this:

```<code>fig1 = df['Price'].plot(ax=ax1, title=title1).get_figure()
fig1.savefig(figName1, bbox_inches='tight')
</code>```

Or in one line:

```<code>df['Price'].plot(ax=ax1, title=title1).get_figure().savefig(figName1, bbox_inches='tight')
</code>```

Body:
I have historic data on my stock holdings in a database. The object here is to create two charts and save each to png files. I read the data from the db into a pandas dataframe to build the charts. The code runs cleanly - no errors. I see the charts when I run it in Spyder, but nothing is saved. Here is a brief summary of what I'm doing:

fig1, ax1 = plt.subplots()
... some code
df['Price'].plot(ax=ax1, title=title1)
plt.savefig(figName1, bbox_inches='tight')
fig2, ax2 = plt.subplots()
... some code
df['% Price'].plot(ax=ax2, title=title2)
df['% S&P'].plot(ax=ax2)
plt.savefig(figName2, bbox_inches='tight')

Is there something wrong with this approach? Thanks.

Body:
I think the problem is that when you call DataFrame.plot() it returns a numpy array of matplotlib.axes.Axes objects. Try to use get_figure() like this:

fig1 = df['Price'].plot(ax=ax1, title=title1).get_figure()
fig1.savefig(figName1, bbox_inches='tight')

Or in one line:

df['Price'].plot(ax=ax1, title=title1).get_figure().savefig(figName1, bbox_inches='tight')


问:
How to filter tags to be included/excluded in a clocktable
I'd like to set up a clocktable where I can specify what tags to include and exclude. </p>

<p>I've tried the below. I've tried with and without double quotes, using + and &, and using :match as well as :tags, nothing seems to work. From the manual it seems that :match should do exactly what I want, but it just includes everything no matter what I do. </p>

```<code>#+TAGS: { billable(a) notes(o) travel(b) }
#+BEGIN: clocktable :scope file :tags +"billable"+"notes"-"travel"
#+CAPTION: Clock summary at [2019-09-20 Fri 21:49]
| Headline     | Time   |
|--------------+--------|
| *Total time* | *1:00* |
|--------------+--------|
| Session      | 1:00   |
#+END:
* Session   :billable:
:LOGBOOK:
CLOCK: [2019-09-19 Thu 17:30]--[2019-09-19 Thu 18:30] =>  1:00
:END:
* Notes    :notes:
:LOGBOOK:
CLOCK: [2019-09-19 Thu 18:30]--[2019-09-19 Thu 18:45] =>  0:15
:END:
* Travel   :travel:
:LOGBOOK:
CLOCK: [2019-09-19 Thu 18:45]--[2019-09-19 Thu 18:55] =>  0:10
:END:
</code>```

答:
Since org-mode version 9.2, the :tags argument adds a column with tags when set to t. The argument :match has the old functionality that matches specific tags.

From the changelog,

The :match (renamed from :tags) option allows to limit clock entries to those matching a todo-tags matcher.

The old :tags option can be set to t to display a headline's tags in a dedicated column.

Body:
I'd like to set up a clocktable where I can specify what tags to include and exclude.

I've tried the below. I've tried with and without double quotes, using + and &, and using :match as well as :tags, nothing seems to work. From the manual it seems that :match should do exactly what I want, but it just includes everything no matter what I do.

#+TAGS: { billable(a) notes(o) travel(b) }
#+BEGIN: clocktable :scope file :tags +"billable"+"notes"-"travel"
#+CAPTION: Clock summary at [2019-09-20 Fri 21:49]
| Headline     | Time   |
|--------------+--------|
| *Total time* | *1:00* |
|--------------+--------|
| Session      | 1:00   |
#+END:
* Session   :billable:
:LOGBOOK:
CLOCK: [2019-09-19 Thu 17:30]--[2019-09-19 Thu 18:30] =>  1:00
:END:
* Notes    :notes:
:LOGBOOK:
CLOCK: [2019-09-19 Thu 18:30]--[2019-09-19 Thu 18:45] =>  0:15
:END:
* Travel   :travel:
:LOGBOOK:
CLOCK: [2019-09-19 Thu 18:45]--[2019-09-19 Thu 18:55] =>  0:10
:END:


问:
Why the openssl output differs for SHA512 Digest
C:\WINDOWS\system32>echo -n "Password" | openssl sha512
(stdin)= 90bf10f0985a74a1be02f5704c3473dbcd9b2d4dd0968169b58f75ba60174efb42117478694a3219cee0cee93f8e04743c2b17445bcdf921857e44604b2a764f

C:\WINDOWS\system32>echo "Password" | openssl dgst -sha512
(stdin)= 1b0f2ea6c7d600da96a57281a87f382ab3d9cd04d5a00e895689ae5431d43787e92392fa35f9bbeae9ace0f96e2e7b10fa762db8b690ccced419c04c10ffc694

Body:
C:\WINDOWS\system32>echo -n "Password" | openssl dgst -sha512
(stdin)= 90bf10f0985a74a1be02f5704c3473dbcd9b2d4dd0968169b58f75ba60174efb42117478694a3219cee0cee93f8e04743c2b17445bcdf921857e44604b2a764f

C:\WINDOWS\system32>echo -n "Password" | openssl sha512
(stdin)= 90bf10f0985a74a1be02f5704c3473dbcd9b2d4dd0968169b58f75ba60174efb42117478694a3219cee0cee93f8e04743c2b17445bcdf921857e44604b2a764f

C:\WINDOWS\system32>


问:
Perform a call to a function that will print character
The vga_puts function should print out characters one by one. To do so, it should perform calls to the vga_putc() function that will actually print each character.

```<code>void vga_putc(char c) {

  switch (c) {
  case VGA_TAB:

    vga_set_c(0x20);
    vga_incrementpos();
    vga_set_c(0x20);
    vga_incrementpos();
    vga_set_c(0x20);
    vga_incrementpos();
    vga_set_c(0x20);
    vga_incrementpos();

    break;

  case VGA_RETURN:

    pos_x = 0;

    break;

  case VGA_NEWLINE:

    pos_x = 0;
    pos_y++;

    break;

  case VGA_BACKSPACE:

    if (pos_x == 0) {
      vga_set_xy(79, pos_y--);
    }
    else if (pos_x != 0 && pos_y != 0) {
      pos_x--;
    }
    else if (pos_y == 0) {
      vga_set_xy(pos_x, pos_y);
      break;
    }
  }

  void vga_puts(char* s) {

  }

</code>```

I understand that vga_puts(char *s) has a pointer to character s however I dont understand how to call vga_putc(char c) in order to print it to the screen. I tend to overthink things and I feel like its fairly simple.

答:
It is fairly simple.

You probably just want this:

```<code>void vga_puts(char* s) {
  char c;
  while (c = *s++)  // repeat until c is 0
    vga_putc(c);
}
...
int main(void)
{
  vga_puts("Hello\r\nWorld!");
}
</code>```

This should print this:

Hello
World!
```
<p>But there are also a problems in <code>vga_putc</code>: you don't handle the case where <code>c</code> is just a normal character that should be printed, and the final <code>}</code> is missing.</p>
<p>The end of <code>vga_putc</code> should look like this:</p>
```    ...
    case VGA_BACKSPACE:

      if (pos_x == 0) {
        vga_set_xy(79, pos_y--);
      }
      else if (pos_x != 0 && pos_y != 0) {
        pos_x--;
      }
      else if (pos_y == 0) {
        vga_set_xy(pos_x, pos_y);
        break;
     }

    default:   // handle all other cases, IOW prints the characters

      vga_set_c(c);
      vga_incrementpos();
    }
  }
}   // this '}' was missing
```

Body:
The vga_puts function should print out characters one by one. To do so, it should perform calls to the vga_putc() function that will actually print each character.

void vga_putc(char c) {

  switch (c) {
  case VGA_TAB:

    vga_set_c(0x20);
    vga_incrementpos();
    vga_set_c(0x20);
    vga_incrementpos();
    vga_set_c(0x20);
    vga_incrementpos();
    vga_set_c(0x20);
    vga_incrementpos();

    break;

  case VGA_RETURN:

    pos_x = 0;

    break;

  case VGA_NEWLINE:

    pos_x = 0;
    pos_y++;

    break;

  case VGA_BACKSPACE:

    if (pos_x == 0) {
      vga_set_xy(79, pos_y--);
    }
    else if (pos_x != 0 && pos_y != 0) {
      pos_x--;
    }
    else if (pos_y == 0) {
      vga_set_xy(pos_x, pos_y);
      break;
    }
  }

  void vga_puts(char* s) {

  }

I understand that vga_puts(char *s) has a pointer to character s however I dont understand how to call vga_putc(char c) in order to print it to the screen. I tend to overthink things and I feel like its fairly simple.

Body:
It is fairly simple.

You probably just want this:

void vga_puts(char* s) {
  char c;
  while (c = *s++)  // repeat until c is 0
    vga_putc(c);
}
...
int main(void)
{
  vga_puts("Hello\r\nWorld!");
}

This should print this:

Hello
World!

But there are also a problems in vga_putc: you don't handle the case where c is just a normal character that should be printed, and the final } is missing.

The end of vga_putc should look like this:

    ...
    case VGA_BACKSPACE:

      if (pos_x == 0) {
        vga_set_xy(79, pos_y--);
      }
      else if (pos_x != 0 && pos_y != 0) {
        pos_x--;
      }
      else if (pos_y == 0) {
        vga_set_xy(pos_x, pos_y);
        break;
     }

    default:   // handle all other cases, IOW prints the characters

      vga_set_c(c);
      vga_incrementpos();
    }
  }
}   // this '}' was missing


问:
Reactjs, re-render same components, but different return data
A little hard to explain, but please bear with me.

I have this function Component. The function Component code is almost the same, but how can i simplify my function MyComponent with the return value are different to each pages?

Below is my code and to better understand here is the complete sandbox code https://codesandbox.io/.

```<code>import { React, useState, useEffect } from "react";

function MyComponent() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);
  useEffect(() => {
    fetch(
      "https://api.unsplash.com/search/photos?query=nature?orientation=landscape&client_id=ddIh7_ebg4KwNHzNLf3ePCZb6yIPREJ5jxG3dYgoj6U"
    )
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result.results);
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      );
  }, []);

  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    return (
      <div style={{ textAlign: "left" }}>
        This return has to be dynamic. See the function Home and About below.
      </div>
    );
  }
}

export default MyComponent;
</code>```

Here is my Home and About pages.

```<code>function Home() {
  const [items, setItems] = useState([]);
  return (
    <div>
      <h2>Home</h2>
      <ul>
        {items.map((item) => (
          <li key={item.id}>{item.user.last_name}</li>
        ))}
      </ul>
    </div>
  );
}

function About() {
  const [items, setItems] = useState([]);
  return (
    <div>
      <h2>About</h2>
      <ul>
        {items.map((item) => (
          <li key={item.id}>{item.user.first_name}</li>
        ))}
      </ul>
    </div>
  );
}
</code>```

MyComponent doesn't appear to be rendered in my codesandbox, thats why im asking how can achieve my questions.

答:
The issue is that you've no centralized source of truth. Each of MyComponent, Home, and About each have their own items state. The question you are asking is how to get the items that MyComponent fetched passed to the other two.

The solution is to Lift State Up. Move all the fetching and rendering logic from MyComponent into App. Pass the items state down to both Home and About.

App

```<code>export default function App() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);

  useEffect(() => {
    fetch(
      "https://api.unsplash.com/search/photos?query=nature?orientation=landscape&client_id=ddIh7_ebg4KwNHzNLf3ePCZb6yIPREJ5jxG3dYgoj6U"
    )
      .then((res) => res.json())
      .then((result) => {
        setItems(result.results);
      })
      .catch((error) => {
        setError(error);
      })
      .finally(() => {
        setIsLoaded(true);
      });
  }, []);

  return (
    <BrowserRouter>
      {<Layout />}
      <main>
        {error ? (
          <div>Error: {error.message}</div>
        ) : !isLoaded ? (
          <div>Loading...</div>
        ) : (
          <React.Suspense fallback={<h6>Loading...</h6>}>
            <Routes>
              <Route path="/" element={<Home items={items} />} />
              <Route path="/about" element={<About items={items} />} />
            </Routes>
          </React.Suspense>
        )}
      </main>
    </BrowserRouter>
  );
}
</code>```

Home

```<code>function Home({ items }) {
  return (
    <div>
      <h2>Home</h2>
      <ul>
        {items.map((item) => (
          <li key={item.id}>{item.user.last_name}</li>
        ))}
      </ul>
    </div>
  );
}
</code>```

About

```<code>function About({ items }) {
  return (
    <div>
      <h2>About</h2>
      <ul>
        {items.map((item) => (
          <li key={item.id}>{item.user.first_name}</li>
        ))}
      </ul>
    </div>
  );
}
</code>```

Body:
A little hard to explain, but please bear with me.

I have this function Component. The function Component code is almost the same, but how can i simplify my function MyComponent with the return value are different to each pages?

Below is my code and to better understand here is the complete sandbox code https://codesandbox.io/.

import { React, useState, useEffect } from "react";

function MyComponent() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);
  useEffect(() => {
    fetch(
      "https://api.unsplash.com/search/photos?query=nature?orientation=landscape&client_id=ddIh7_ebg4KwNHzNLf3ePCZb6yIPREJ5jxG3dYgoj6U"
    )
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result.results);
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      );
  }, []);

  if (error) {
    return
Error: {error.message}
;
  } else if (!isLoaded) {
    return
Loading...
;
  } else {
    return (

        This return has to be dynamic. See the function Home and About below.

    );
  }
}

export default MyComponent;

Here is my Home and About pages.

function Home() {
  const [items, setItems] = useState([]);
  return (

Home

        {items.map((item) => (

{item.user.last_name}

        ))}

  );
}

function About() {
  const [items, setItems] = useState([]);
  return (

About

        {items.map((item) => (

{item.user.first_name}

        ))}

  );
}

MyComponent doesn't appear to be rendered in my codesandbox, thats why im asking how can achieve my questions.

Body:
The issue is that you've no centralized source of truth. Each of MyComponent, Home, and About each have their own items state. The question you are asking is how to get the items that MyComponent fetched passed to the other two.

The solution is to Lift State Up. Move all the fetching and rendering logic from MyComponent into App. Pass the items state down to both Home and About.

App

export default function App() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);

  useEffect(() => {
    fetch(
      "https://api.unsplash.com/search/photos?query=nature?orientation=landscape&client_id=ddIh7_ebg4KwNHzNLf3ePCZb6yIPREJ5jxG3dYgoj6U"
    )
      .then((res) => res.json())
      .then((result) => {
        setItems(result.results);
      })
      .catch((error) => {
        setError(error);
      })
      .finally(() => {
        setIsLoaded(true);
      });
  }, []);

  return (
    <BrowserRouter>
      {<Layout />}
      <main>
        {error ? (
          <div>Error: {error.message}</div>
        ) : !isLoaded ? (
          <div>Loading...</div>
        ) : (
          <React.Suspense fallback={<h6>Loading...</h6>}>
            <Routes>
              <Route path="/" element={<Home items={items} />} />
              <Route path="/about" element={<About items={items} />} />
            </Routes>
          </React.Suspense>
        )}
      </main>
    </BrowserRouter>
  );
}

Home

function Home({ items }) {
  return (
    <div>
      <h2>Home</h2>
      <ul>
        {items.map((item) => (
          <li key={item.id}>{item.user.last_name}</li>
        ))}
      </ul>
    </div>
  );
}

About

function About({ items }) {
  return (
    <div>
      <h2>About</h2>
      <ul>
        {items.map((item) => (
          <li key={item.id}>{item.user.first_name}</li>
        ))}
      </ul>
    </div>
  );
}


问:
Routablepage of the BlogPage/category
I fail to display the routable index page for categories/given category.

My code uses:
-BlogCategory(model)

-BlogPageBlogCategory (page) an intemediary structure that links to:

-PostPage(page)

I can pass the code to the post_page template, but when I click on a specific category link I get:

```<code>Reverse for 'post_by_category' with arguments '('',)' not found. 1 pattern(s) tried: ['category/(?P<category>[-\\w]+)/$']
</code>```

In the following post @gasman wrote: "the routablepageurl tag has received an empty string". I couldn't find the 'empty' string/missing link.

I assume it's related to the route of my 'def post_by_category'. Any input that would help me deepen my learning woulg be great.

NB - in case it helps, when I run this procedure without the intemeiary page all's fine. I can display the BlogPage/given_category once I click on the category in the PostPage.

Here's my code:

Models

class BlogPage(RoutablePageMixin, Page):
...

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        context["posts"] = posts
        return context

    def get_posts(self):
        return PostPage.objects.descendant_of(self).live().order_by("-post_date")

@route(r'^category/(?P<category>[-\w]+)/$')
    def post_by_category(self, request, category, *args, **kwargs):
        self.posts =  self.get_posts().filter(categories__blog_category__slug=category)
        context["categories"] = BlogCategory.objects.all()
        return self.render(request)

class PostPage(MetadataPageMixin, Page):
...
    content_panels = Page.content_panels + [
...
    InlinePanel("categories", label="category"),
...

def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        return context

class PostPageBlogCategory(models.Model):
    page = ParentalKey(
        "blog.PostPage", on_delete=models.CASCADE, related_name="categories"
    )
    blog_category = models.ForeignKey(
        "blog.BlogCategory", on_delete=models.CASCADE, related_name="post_pages"
    )

    panels = [
        SnippetChooserPanel("blog_category"),
    ]

    class Meta:
        unique_together = ("page", "blog_category")

@register_snippet
class BlogCategory(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(unique=True, max_length=80)

    panels = [
        FieldPanel('name'),
        FieldPanel("slug"),
    ]

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'categories'```
</div>
</div>
</p>
<p>The post_page.html:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{% extends "base.html" %}
{% load wagtailroutablepage_tags %}

...
{% for category in page.categories.all %}
    <li>

            {{ blog_category.name }}

    </li>
    {% empty %}
        No categories yet'
{% endfor %}

...</code>```

答:
After debugging and testing, I didn't find any blank categories, (which doesn't mean there were none, but that I didn't find or deleted them Unintentionally).
I case it could help, what worked for me was adding the category_type at the beginning of my varaiable:

{{ category.blog_category.name }} rather than {{ blog_category.name }}

        {% for category in page.categories.all %}

        {{ category.blog_category.name }}

         {% empty %}
         No categories yet'
        {% endfor %}```

Title: Routablepage of the BlogPage/category

Body:
I fail to display the routable index page for categories/given category.

My code uses:
-BlogCategory(model)

-BlogPageBlogCategory (page) an intemediary structure that links to:

-PostPage(page)

I can pass the code to the post_page template, but when I click on a specific category link I get:

Reverse for 'post_by_category' with arguments '('',)' not found. 1 pattern(s) tried: ['category/(?P<category>[-\\w]+)/$']

In the following post @gasman wrote: "the routablepageurl tag has received an empty string". I couldn't find the 'empty' string/missing link.

I assume it's related to the route of my 'def post_by_category'. Any input that would help me deepen my learning woulg be great.

NB - in case it helps, when I run this procedure without the intemeiary page all's fine. I can display the BlogPage/given_category once I click on the category in the PostPage.

Here's my code:

Models

class BlogPage(RoutablePageMixin, Page):
...

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        context["posts"] = posts
        return context

    def get_posts(self):
        return PostPage.objects.descendant_of(self).live().order_by("-post_date")

@route(r'^category/(?P<category>[-\w]+)/$')
    def post_by_category(self, request, category, *args, **kwargs):
        self.posts =  self.get_posts().filter(categories__blog_category__slug=category)
        context["categories"] = BlogCategory.objects.all()
        return self.render(request)

class PostPage(MetadataPageMixin, Page):
...
    content_panels = Page.content_panels + [
...
    InlinePanel("categories", label="category"),
...

def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        return context

class PostPageBlogCategory(models.Model):
    page = ParentalKey(
        "blog.PostPage", on_delete=models.CASCADE, related_name="categories"
    )
    blog_category = models.ForeignKey(
        "blog.BlogCategory", on_delete=models.CASCADE, related_name="post_pages"
    )

    panels = [
        SnippetChooserPanel("blog_category"),
    ]

    class Meta:
        unique_together = ("page", "blog_category")

@register_snippet
class BlogCategory(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(unique=True, max_length=80)

    panels = [
        FieldPanel('name'),
        FieldPanel("slug"),
    ]

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'categories'

The post_page.html:

{% extends "base.html" %}
{% load wagtailroutablepage_tags %}

...
{% for category in page.categories.all %}

            {{ blog_category.name }}

    {% empty %}
        No categories yet'
{% endfor %}

...

Body:
After debugging and testing, I didn't find any blank categories, (which doesn't mean there were none, but that I didn't find or deleted them Unintentionally).
I case it could help, what worked for me was adding the category_type at the beginning of my varaiable:

{{ category.blog_category.name }} rather than {{ blog_category.name }}

        {% for category in page.categories.all %}

        <a href="{% routablepageurl article_index_page "post_by_category" category.blog_category.slug %}" class="link-primary text-decoration-none">
        {{ category.blog_category.name }}
        </a>

         {% empty %}
         No categories yet'
        {% endfor %}


问:
Flutter PIN Verification Countdown
I made a pin verification with countdown using the timer_count_down package. What I'm trying to do is when the countdown is finished, it shows a text saying "Resend PIN" to resend the PIN to email and starts the countdown again.

Here is my Login.dart code snippet when I enter my email address it sends a PIN code to my email :

```<code>...
Form(
            key: _formKey,
            child: TextFormField(
              cursorColor: Color(0xFF2481CF),
              autofocus: true,
              validator: (value) {
                if (value == null || value.isEmpty || !EmailValidator.validate(value.trim())) {
                  return 'Email is not valid!';
                }
                return null;
              },
              controller: _controller,
              decoration: InputDecoration(
                  enabledBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Color(0xFF2481CF)),
                  ),
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Color(0xFF2481CF)),
                  ),
                  labelText: 'Enter your email :',
                  labelStyle: TextStyle(
                    color: Color(0xFF2481CF)
                  )
                ),
              style: TextStyle(
                fontSize: 19.0,
                height: 1.3,
              ),
            ),
          ),
...

floatingActionButton: FloatingActionButton(
      // onPressed: _submit,
      onPressed: () {
        if (_formKey.currentState!.validate()) {
          showDialog<String>(
            context: context,
            builder: (BuildContext context) => AlertDialog(
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  SizedBox(height: 20,),
                  Text('PIN code will be sent to'),
                  SizedBox(height: 10,),
                  Text(_controller.text,
                  style: TextStyle(
                    fontWeight: FontWeight.bold
                  ),),
                  SizedBox(
                    height: 30,
                  ),
                  Text('Is this OK or would you like to edit the email address?'),
                ],
              ),
              actions: <Widget>[
                TextButton(
                  onPressed: () => Navigator.pop(context, 'Cancel'),
                  child: const Text('Edit',
                    style: TextStyle(
                        color: Color(0xFF2481CF)
                    ),),
                ),
                TextButton(
                  onPressed: () {
                    //kirim email

                    sendEmail(_controller.text.trim());

                    Navigator.of(context).push(
                      MaterialPageRoute(builder: (context) =>  PinVerification(_controller.text.trim())),
                    );
                  },
                  child: const Text('Verify',
                    style: TextStyle(
                        color: Color(0xFF2481CF)
                    ),),
                ),
              ],
            ),
          );
        };
      },
      child: const Icon(Icons.send),
    ),
</code>```

And for the PinVerification.dart :

```<code>Widget onlySelectedBorderPinPut() {
    final BoxDecoration pinPutDecoration = BoxDecoration(
      color: const Color.fromRGBO(235, 236, 237, 1),
      borderRadius: BorderRadius.circular(5.0),
    );
    return Form(
      key: _formKey,
      child: Column(
        children: [
          SizedBox(
            height: 50,
          ),
          Text(
            'Enter 6 digit code we sent to your email.',
            textAlign: TextAlign.center,
            style: TextStyle(color: Colors.grey),
          ),
          SizedBox(
            height: 30,
          ),
          GestureDetector(
            onLongPress: () {
              print(_formKey.currentState?.validate());
            },
            child: PinPut(
              validator: (s) {
                if (s != null && s.contains('1')) return null;
                return 'NOT VALID';
              },
              useNativeKeyboard: true,
              autovalidateMode: AutovalidateMode.always,
              withCursor: true,
              fieldsCount: 6,
              fieldsAlignment: MainAxisAlignment.spaceAround,
              textStyle: const TextStyle(fontSize: 25.0, color: Colors.black),
              eachFieldMargin: EdgeInsets.all(0),
              eachFieldWidth: 45.0,
              eachFieldHeight: 55.0,
              onSubmit: (String pin) => postRequest(pin),
              focusNode: _pinPutFocusNode,
              controller: _pinPutController,
              submittedFieldDecoration: pinPutDecoration,
              selectedFieldDecoration: pinPutDecoration.copyWith(
                color: Colors.white,
                border: Border.all(
                  width: 2,
                  color: const Color.fromRGBO(160, 215, 220, 1),
                ),
              ),
              followingFieldDecoration: pinPutDecoration,
              pinAnimationType: PinAnimationType.scale,
            ),
          ),
          SizedBox(
            height: 20,
          ),
          Countdown(
            seconds: 20,
            build: (_, double time) =>
                RichText(
                  text: TextSpan(
                    text: 'Send PIN again in ',
                    style: TextStyle(
                      color: Theme.of(context).inputDecorationTheme.labelStyle?.color
                    ),
                    children: <TextSpan>[
                      TextSpan(
                        text: time.toString(),
                      style: TextStyle(
                        color: Color(0xFF2481CF),
                        fontWeight: FontWeight.bold
                      )),
                      TextSpan(text: ' sec',
                      style: TextStyle(
                        color: Theme.of(context).inputDecorationTheme.labelStyle?.color
                      ))
                    ]
                  ),
                ),
            onFinished: () {

            },
          ),
        ],
      ),
    );
  }
</code>```

This is the screenshot for my PinVerification.dart:

Any solutions?

答:
Created custom timer It worked for me

```<code> late Timer _timer;
 int _start = 60;

 void startTimer() {
const oneSec = const Duration(seconds: 1);
_timer = new Timer.periodic(
  oneSec,
  (Timer timer) {
    if (_start == 0) {
      setState(() {
        timer.cancel();
      });
    } else {
      setState(() {
        _start--;
      });
    }
  },
);
}

    @override
  void initState() {
    super.initState();

    startTimer();

  }

    @override
  void dispose() {
    super.dispose();
    _timer.cancel();
    errorController!.close();
  }
</code>```

And inside widget check condition as follows:

```<code> _start != 0
              ? Row(
                  // mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Text(
                      "Resend Code in",
                      style: TextStyle(
                          color: Colors.white.withOpacity(0.5),
                          fontWeight: FontWeight.bold,
                          fontSize: 16),
                    ),
                    const SizedBox(width: 10),
                    Text(
                      _start.toString(),
                      style: TextStyle(
                          color: MyTheme.yellow,
                          fontWeight: FontWeight.bold,
                          fontSize: 20),
                    ),
                  ],
                )
              : YourWidget() // your widget here
</code>```

When the Resend Otp is clikced reset the timer is as follows:

```<code>setState(() {
                                _start = 60;
                                startTimer();
                              });
</code>```

Title: Flutter PIN Verification Countdown

Body:
I made a pin verification with countdown using the timer_count_down package. What I'm trying to do is when the countdown is finished, it shows a text saying "Resend PIN" to resend the PIN to email and starts the countdown again.

Here is my Login.dart code snippet when I enter my email address it sends a PIN code to my email :

...
Form(
            key: _formKey,
            child: TextFormField(
              cursorColor: Color(0xFF2481CF),
              autofocus: true,
              validator: (value) {
                if (value == null || value.isEmpty || !EmailValidator.validate(value.trim())) {
                  return 'Email is not valid!';
                }
                return null;
              },
              controller: _controller,
              decoration: InputDecoration(
                  enabledBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Color(0xFF2481CF)),
                  ),
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Color(0xFF2481CF)),
                  ),
                  labelText: 'Enter your email :',
                  labelStyle: TextStyle(
                    color: Color(0xFF2481CF)
                  )
                ),
              style: TextStyle(
                fontSize: 19.0,
                height: 1.3,
              ),
            ),
          ),
...

floatingActionButton: FloatingActionButton(
      // onPressed: _submit,
      onPressed: () {
        if (_formKey.currentState!.validate()) {
          showDialog<String>(
            context: context,
            builder: (BuildContext context) => AlertDialog(
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  SizedBox(height: 20,),
                  Text('PIN code will be sent to'),
                  SizedBox(height: 10,),
                  Text(_controller.text,
                  style: TextStyle(
                    fontWeight: FontWeight.bold
                  ),),
                  SizedBox(
                    height: 30,
                  ),
                  Text('Is this OK or would you like to edit the email address?'),
                ],
              ),
              actions: <Widget>[
                TextButton(
                  onPressed: () => Navigator.pop(context, 'Cancel'),
                  child: const Text('Edit',
                    style: TextStyle(
                        color: Color(0xFF2481CF)
                    ),),
                ),
                TextButton(
                  onPressed: () {
                    //kirim email

                    sendEmail(_controller.text.trim());

                    Navigator.of(context).push(
                      MaterialPageRoute(builder: (context) =>  PinVerification(_controller.text.trim())),
                    );
                  },
                  child: const Text('Verify',
                    style: TextStyle(
                        color: Color(0xFF2481CF)
                    ),),
                ),
              ],
            ),
          );
        };
      },
      child: const Icon(Icons.send),
    ),

And for the PinVerification.dart :

Widget onlySelectedBorderPinPut() {
    final BoxDecoration pinPutDecoration = BoxDecoration(
      color: const Color.fromRGBO(235, 236, 237, 1),
      borderRadius: BorderRadius.circular(5.0),
    );
    return Form(
      key: _formKey,
      child: Column(
        children: [
          SizedBox(
            height: 50,
          ),
          Text(
            'Enter 6 digit code we sent to your email.',
            textAlign: TextAlign.center,
            style: TextStyle(color: Colors.grey),
          ),
          SizedBox(
            height: 30,
          ),
          GestureDetector(
            onLongPress: () {
              print(_formKey.currentState?.validate());
            },
            child: PinPut(
              validator: (s) {
                if (s != null && s.contains('1')) return null;
                return 'NOT VALID';
              },
              useNativeKeyboard: true,
              autovalidateMode: AutovalidateMode.always,
              withCursor: true,
              fieldsCount: 6,
              fieldsAlignment: MainAxisAlignment.spaceAround,
              textStyle: const TextStyle(fontSize: 25.0, color: Colors.black),
              eachFieldMargin: EdgeInsets.all(0),
              eachFieldWidth: 45.0,
              eachFieldHeight: 55.0,
              onSubmit: (String pin) => postRequest(pin),
              focusNode: _pinPutFocusNode,
              controller: _pinPutController,
              submittedFieldDecoration: pinPutDecoration,
              selectedFieldDecoration: pinPutDecoration.copyWith(
                color: Colors.white,
                border: Border.all(
                  width: 2,
                  color: const Color.fromRGBO(160, 215, 220, 1),
                ),
              ),
              followingFieldDecoration: pinPutDecoration,
              pinAnimationType: PinAnimationType.scale,
            ),
          ),
          SizedBox(
            height: 20,
          ),
          Countdown(
            seconds: 20,
            build: (_, double time) =>
                RichText(
                  text: TextSpan(
                    text: 'Send PIN again in ',
                    style: TextStyle(
                      color: Theme.of(context).inputDecorationTheme.labelStyle?.color
                    ),
                    children: <TextSpan>[
                      TextSpan(
                        text: time.toString(),
                      style: TextStyle(
                        color: Color(0xFF2481CF),
                        fontWeight: FontWeight.bold
                      )),
                      TextSpan(text: ' sec',
                      style: TextStyle(
                        color: Theme.of(context).inputDecorationTheme.labelStyle?.color
                      ))
                    ]
                  ),
                ),
            onFinished: () {

            },
          ),
        ],
      ),
    );
  }

This is the screenshot for my PinVerification.dart:

Any solutions?

Body:
Created custom timer It worked for me

 late Timer _timer;
 int _start = 60;

 void startTimer() {
const oneSec = const Duration(seconds: 1);
_timer = new Timer.periodic(
  oneSec,
  (Timer timer) {
    if (_start == 0) {
      setState(() {
        timer.cancel();
      });
    } else {
      setState(() {
        _start--;
      });
    }
  },
);
}

    @override
  void initState() {
    super.initState();

    startTimer();

  }

    @override
  void dispose() {
    super.dispose();
    _timer.cancel();
    errorController!.close();
  }

And inside widget check condition as follows:

 _start != 0
              ? Row(
                  // mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Text(
                      "Resend Code in",
                      style: TextStyle(
                          color: Colors.white.withOpacity(0.5),
                          fontWeight: FontWeight.bold,
                          fontSize: 16),
                    ),
                    const SizedBox(width: 10),
                    Text(
                      _start.toString(),
                      style: TextStyle(
                          color: MyTheme.yellow,
                          fontWeight: FontWeight.bold,
                          fontSize: 20),
                    ),
                  ],
                )
              : YourWidget() // your widget here

When the Resend Otp is clikced reset the timer is as follows:

setState(() {
                                _start = 60;
                                startTimer();
                              });


问:
Run two Angular 2+ project on same server (local server)
Can Any body can help me?
I have two angular 6 project.Completely two different project.
One project is use for Website Front View(landing pages like etc)…
Second project is used for Backend view (Admin panel).
Can I run together these two project and can naviagate from one project component to other project component?
Help please.</p>

答: we can`t run two angular(2+) projects on same port number in local machine</p>


问:
Beautify html output
I was wondering whether there is class or something similar which I can include into my PHP pages to beautify the HTML output.

Such as putting new lines in after tags and correctly indenting so that my source code isn't only one line, I know that to the browser it doesn't matter but I wish to do this.

I have heard of http://www.php.net/manual/en/book.tidy.php but am not clear on what it does and how to implement it, i.e. I don't understand what the manual says about it.

答:
HTML purifier or HTML tidy seems to be the way to go for this, combined with this set of functions: http://www.php.net/manual/en/ref.outcontrol.php

http://htmlpurifier.org/
http://tidy.sourceforge.net/

Title: Beautify html output


问:
Trying to exit MySQL server, it shows an syntax error when I try to run exit or \q
I was importing a CSV file in MySQL when I got a -secure-file-priv error, I searched here and it said I need to set the global variable for local-infile system. I ran that command and it worked. The next step was to quit the server. I tried with exit, \q, \quit, \exit, \quit and more possible variations, but all of them shows the '1064: Syntax Error'. I tried all of this with adding ; as well, but it still showed the error. What's the issue here?

I followed the answers to this question. (I could've added a comment on the answer and asked the author but I just joined the website today so I don't have enough reputation to comment yet and also am new to MySQL so I am putting this as a question here. I tried searching the internet a lot but couldn't find an answer.)

答:
```<code> exit, \q, \quit, \exit, \quit
</code>```

Above commands only exit MySQL command prompt.

To stop mysql server, under the mysql install location(such as C:\Program Files\MySQL\MySQL Server 8.0), execute below command:

```<code>mysqladmin -u root -p shutdown
Enter password: ********
</code>```

Body:
 exit, \q, \quit, \exit, \quit

Above commands only exit MySQL command prompt.

To stop mysql server, under the mysql install location(such as C:\Program Files\MySQL\MySQL Server 8.0), execute below command:

mysqladmin -u root -p shutdown
Enter password: ********


问:
Excel add hyperlink to another table in excel
I am trying to add a hyperlink from one sheet to a named table on another sheet. I know that if I name the range then I can use the hyperlink, but ideally, I would like to keep it as just a table.

I have a table on SHEET 2 named MySpa - I would like to have a link from SHEET 1 to that table.

I tried this - =HYPERLINK(MySpa, "Link to MySpa Table") but when I click on the link in the cell it doesn't seem to do anything. How can I link from one sheet to a table on another sheet?

答:
If the table is named and is in the same sheet, prepend a hash (#) and wrap in double quotes as shown below:

```<code>=HYPERLINK("#TableName", "Click to view")
</code>```

If the table is in another sheet, prepend the sheet name as shown:

```<code>=HYPERLINK("#SheetName!TableName", "Click to view")
</code>```

The trick is in wrapping the reference in double quotation marks and including the hash sign.

Body:
If the table is named and is in the same sheet, prepend a hash (#) and wrap in double quotes as shown below:

=HYPERLINK("#TableName", "Click to view")

If the table is in another sheet, prepend the sheet name as shown:

=HYPERLINK("#SheetName!TableName", "Click to view")

The trick is in wrapping the reference in double quotation marks and including the hash sign.


问:
ArrayList with search terms check a .txt file for duplicates
I am supposed to revise my actually finished code again, because it is too long. The idea was, or was suggested to me, to write search terms in an ArrayList and then run this over a .txt file, which is then stored in an ArrayList. Duplicates are to be read over and not read in.

```<code>    boolean allegefunden = false;
    BufferedReader reader;
    String zeile = null;

    ArrayList<String> arr = new ArrayList<String>();
    try {
        reader = new BufferedReader(new FileReader("C:\\Dev\\lesenUndSchreibenInput.txt"));
        zeile = reader.readLine();

        while (zeile != null) {
            if (zeile.contains((CharSequence) suchbegriffe)) {
                arr.add(zeile);
                allegefunden = true;

            } else if (allegefunden == true && zeile.contains((CharSequence) suchbegriffe)) {

            } else
                arr.add(zeile);
</code>```

However, the normal contains method does not work.

答:
I'm not sure I understand fully what you're trying to do, but to replace the contains method, you could build a regexp at the beginning of the search:

```<code>private static Pattern reFromWords(List<String> searchWords) {
    String s = searchWords.stream()
            .map(Pattern::quote)
            .collect(Collectors.joining("|"));
    return Pattern.compile(s);
}
</code>```

Searching in a file would then look like this:

```<code>    Pattern regexp = reFromWords(suchbegriffe);
    try (Reader fileReader = new FileReader("yourfile.txt");
            BufferedReader reader = new BufferedReader(fileReader)) {
        String line = reader.readLine();
        while (line != null) {
            Matcher matcher = regexp.matcher(line);
            if (matcher.find()) {
                String foundWord = matcher.group();
                System.out.println("Found " + foundWord + " in line: " + line);
            }
            line = reader.readLine();
        }
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
</code>```

Body:
I am supposed to revise my actually finished code again, because it is too long. The idea was, or was suggested to me, to write search terms in an ArrayList and then run this over a .txt file, which is then stored in an ArrayList. Duplicates are to be read over and not read in.

    boolean allegefunden = false;
    BufferedReader reader;
    String zeile = null;

    ArrayList<String> arr = new ArrayList<String>();
    try {
        reader = new BufferedReader(new FileReader("C:\\Dev\\lesenUndSchreibenInput.txt"));
        zeile = reader.readLine();

        while (zeile != null) {
            if (zeile.contains((CharSequence) suchbegriffe)) {
                arr.add(zeile);
                allegefunden = true;

            } else if (allegefunden == true && zeile.contains((CharSequence) suchbegriffe)) {

            } else
                arr.add(zeile);

However, the normal contains method does not work.

Body:
I'm not sure I understand fully what you're trying to do, but to replace the contains method, you could build a regexp at the beginning of the search:

private static Pattern reFromWords(List<String> searchWords) {
    String s = searchWords.stream()
            .map(Pattern::quote)
            .collect(Collectors.joining("|"));
    return Pattern.compile(s);
}

Searching in a file would then look like this:

    Pattern regexp = reFromWords(suchbegriffe);
    try (Reader fileReader = new FileReader("yourfile.txt");
            BufferedReader reader = new BufferedReader(fileReader)) {
        String line = reader.readLine();
        while (line != null) {
            Matcher matcher = regexp.matcher(line);
            if (matcher.find()) {
                String foundWord = matcher.group();
                System.out.println("Found " + foundWord + " in line: " + line);
            }
            line = reader.readLine();
        }
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }


问:
ASP.NET MVC passing strongly typed data to master page

Duplicate

Passing data to Master Page in ASP.NET MVC

Should an ASP.NET masterpage get its data from the view ?

I have been following this method for passing common data to the site.master. However, this does require specific casting of the ViewData and I don't like using string identifiers everywhere. Is this the best way to do it or is there another way?

http://www.asp.net/learn/MVC/tutorial-13-cs.aspx

Thanks

答:
You could create a base class that all your models inherit from:

```<code>class MasterModel {
     // common info, used in master page.
}

class Page1Model : MasterModel {
     // page 1 model
}
</code>```

Then your master page would inherit from ViewMasterPage<MasterModel> and your Page1.aspx would inherit from ViewPage<Page1Model> and set Site.master as its master page.

OwnerDisplayName: MVC User

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Craig Stuntz

Body:
You could create a base class that all your models inherit from:

class MasterModel {
     // common info, used in master page.
}

class Page1Model : MasterModel {
     // page 1 model
}

Then your master page would inherit from ViewMasterPage<MasterModel> and your Page1.aspx would inherit from ViewPage<Page1Model> and set Site.master as its master page.

OwnerDisplayName: Mehrdad


问:
Woocommerce How can i have a price per page text appear in my ink single product pages?
I'm working in WooCommerce and I want to display a custom field at single product page that contains the result of the attribute "Pages" term, which is always going to be an integer, divided by the  product price.
This way i will have a price per page value appear in ink and toners product pages.

At the moment i'm doing it with a custom field and i manually input the price in the attribute
but I want to do it automatically.
The function i use to display the attribute is this.How do i call the price in the function and where do i do the pages/price?

Thanks for your help.

```<code>function isa_woo_get_one_pa(){

// Edit below with the title of the attribute you wish to display

global $product;
$attributes = $product->get_attributes();

if ( ! $attributes ) {
    return;
}

$out = '';

foreach ( $attributes as $attribute ) {
    $name = $attribute->get_name();
    if ( $attribute->is_taxonomy() ) {

        // if this is desired att, get value and label
        if ( $name == 'pa_pages') {

            $terms = wp_get_post_terms( $product->get_id(), $name, 'all' );
            // get the taxonomy
            $tax = $terms[0]->taxonomy;
            // get the tax object
            $tax_object = get_taxonomy( $tax );
            // get tax label
            if ( isset ( $tax_object->labels->singular_name ) ) {
                $tax_label = $tax_object->labels->singular_name;
            } elseif ( isset( $tax_object->label ) ) {
                $tax_label = $tax_object->label;
                $tax_label = ($tax_label);

            }

            foreach ( $terms as $term ) {

                $out .= $tax_label . ': ';
                $out .= $term->name . '<br />';

            }

        }

    }

}

echo $out;
</code>```

}
add_action('woocommerce_single_product_summary', 'isa_woo_get_one_pa');

答:
If it's a custom field and not an attribute you need to get it with get_post_meta():
https://developer.wordpress.org/reference/functions/get_post_meta/

The hook you use will depend on your theme and where you want to display your calculation, I recommend using guide as start:
https://www.businessbloomer.com/woocommerce-visual-hook-guide-single-product-page/

Body:
I'm working in WooCommerce and I want to display a custom field at single product page that contains the result of the attribute "Pages" term, which is always going to be an integer, divided by the  product price.
This way i will have a price per page value appear in ink and toners product pages.

At the moment i'm doing it with a custom field and i manually input the price in the attribute
but I want to do it automatically.
The function i use to display the attribute is this.How do i call the price in the function and where do i do the pages/price?

Thanks for your help.

function isa_woo_get_one_pa(){

// Edit below with the title of the attribute you wish to display

global $product;
$attributes = $product->get_attributes();

if ( ! $attributes ) {
    return;
}

$out = '';

foreach ( $attributes as $attribute ) {
    $name = $attribute->get_name();
    if ( $attribute->is_taxonomy() ) {

        // if this is desired att, get value and label
        if ( $name == 'pa_pages') {

            $terms = wp_get_post_terms( $product->get_id(), $name, 'all' );
            // get the taxonomy
            $tax = $terms[0]->taxonomy;
            // get the tax object
            $tax_object = get_taxonomy( $tax );
            // get tax label
            if ( isset ( $tax_object->labels->singular_name ) ) {
                $tax_label = $tax_object->labels->singular_name;
            } elseif ( isset( $tax_object->label ) ) {
                $tax_label = $tax_object->label;
                $tax_label = ($tax_label);

            }

            foreach ( $terms as $term ) {

                $out .= $tax_label . ': ';
                $out .= $term->name . '
';

            }

        }

    }

}

echo $out;

}
add_action('woocommerce_single_product_summary', 'isa_woo_get_one_pa');


问:
How to account for all whitespace (spaces, tabs, new lines) in regexp_substr() method?
I have the following code snippet in SQL to select the next piece of text after ABC DEF that's of variable length:

SELECT trim('ABC DEF ' FROM regexp_substr(my_field, 'ABC DEF ([^ ]+)')) FROM my_table

Sample Data:

```<code>'{random text here}           ABC DEF          {my_variable_length_keyword} {random text here}'
</code>```

Expected Output:
{my_variable_length_keyword}

While this works, it only accounts for cases where there is one space after ABC DEF. How would I deal with cases where there are tabs, new lines, or multiple spaces before the next word?

I've tried:

SELECT trim('ABC DEF ' FROM regexp_substr(my_field, 'ABC DEF\s+([^ ]+)')) FROM my_table

But this doesn't yield any result.

Can someone please help me out with this? Thank you!

答:
You do not need to use any lookarounds, nor do you need to trim the prefix matched with the regex, since with REGEXP_SUBSTR you can specify a capturing group and extract just its contents.

SELECT regexp_substr(my_field, 'ABC\\s+DEF\\s+(\\S+)', 1, 1, 'e') FROM my_table
```

This is the regex demo.

Details:

ABC\s+DEF\s+(\S+) - ABC, one or more whitespaces, DEF, one or more whitespaces (this text is just matched) and then one or more non-whitespace chars are captured into Group 1 (note you need to double escape backslashes as the single backslash is used to form string escape sequences, and to introduce a literal \ it needs doubling)

1 - start searching from the first char in the string

1 - tells the regex engine to extract the first occurrence of the pattern

'e' - enables extraction of the subexpression (aka capturing group value) from the resulting match.

Body:
I have the following code snippet in SQL to select the next piece of text after ABC DEF that's of variable length:

SELECT trim('ABC DEF ' FROM regexp_substr(my_field, 'ABC DEF ([^ ]+)')) FROM my_table

Sample Data:

'{random text here}           ABC DEF          {my_variable_length_keyword} {random text here}'

Expected Output:
{my_variable_length_keyword}

While this works, it only accounts for cases where there is one space after ABC DEF. How would I deal with cases where there are tabs, new lines, or multiple spaces before the next word?

I've tried:

SELECT trim('ABC DEF ' FROM regexp_substr(my_field, 'ABC DEF\s+([^ ]+)')) FROM my_table

But this doesn't yield any result.

Can someone please help me out with this? Thank you!

Body:
You do not need to use any lookarounds, nor do you need to trim the prefix matched with the regex, since with REGEXP_SUBSTR you can specify a capturing group and extract just its contents.

SELECT regexp_substr(my_field, 'ABC\\s+DEF\\s+(\\S+)', 1, 1, 'e') FROM my_table

This is the regex demo.

Details:

ABC\s+DEF\s+(\S+) - ABC, one or more whitespaces, DEF, one or more whitespaces (this text is just matched) and then one or more non-whitespace chars are captured into Group 1 (note you need to double escape backslashes as the single backslash is used to form string escape sequences, and to introduce a literal \ it needs doubling)

1 - start searching from the first char in the string

1 - tells the regex engine to extract the first occurrence of the pattern

'e' - enables extraction of the subexpression (aka capturing group value) from the resulting match.