问:
How to create a preloader within a html select box using JQuery?
I have a select box with id Provice, whenever a Province is selected within this select box, the city select box populates with the cities within the selected provinces. Now that works, what I need to know is how to add a pre-loader in the city select box while it loads the appropriate cities using JQuery

My code looks as below

```<code> $('#Province').change(function() {
          $("#cities").load('cities.php');
        });
</code>```

答:
just add a preloader on the begginning and hide it in the callback :</p>

```<code>$('#Province').change(function() {
      $("#loading").html("<img src='images/preload.gif' />");
      $("#cities").load('cities.php', function() {
         $("#loading").hide();
      });
    });
</code>```

Body:
I have a select box with id Provice, whenever a Province is selected within this select box, the city select box populates with the cities within the selected provinces. Now that works, what I need to know is how to add a pre-loader in the city select box while it loads the appropriate cities using JQuery

My code looks as below

 $('#Province').change(function() {
          $("#cities").load('cities.php');
        });

Body:
just add a preloader on the begginning and hide it in the callback :

$('#Province').change(function() {
      $("#loading").html("<img src='images/preload.gif' />");
      $("#cities").load('cities.php', function() {
         $("#loading").hide();
      });
    });


来源: stackexchange

问:
Flink and Cassandra Connection Issue
Has anyone faced any issue with Connecting to Cassandra from a Flink Job when the Connection is made outside the Flink's DataStreams normally?

```<code>    Session session = clusterBuilder.getCluster().connect();
    ResultSet resultSet = session.execute(resultStatement.getQuery());
</code>```

I am not facing this in Locale but in a dev environment. In local connection it is working fine. Even with same clusterbuilder settings when I am keeping this piece of code inside a DataStream processElement, The Connection is getting Established in Dev.

I am getting a programInvocation error in main and I can not see the whole error because of Flink 1.7's limitation. In dashboard you do not get the whole exception trace to see in Flink 1.7. The Job is not getting submitted.

Anybody has any clue on this or faced anything similar like this?

答:
The most probably cause (I'm not Flink expert, but I have seen this problem with Spark) is that Session object is not Serializable, and couldn't be sent to executors/workers.

To workaround this, usually there is an API with explicit open/close calls that allow to initialize non-serializable classes.  As I see, Flink has a notion of Asynchronous I/O for External Data Access, that could be potentially used for accessing Cassandra.

ContentLicense: CC BY-SA 4.0

Title: Flink and Cassandra Connection Issue

Body:
Has anyone faced any issue with Connecting to Cassandra from a Flink Job when the Connection is made outside the Flink's DataStreams normally?

    Session session = clusterBuilder.getCluster().connect();
    ResultSet resultSet = session.execute(resultStatement.getQuery());

I am not facing this in Locale but in a dev environment. In local connection it is working fine. Even with same clusterbuilder settings when I am keeping this piece of code inside a DataStream processElement, The Connection is getting Established in Dev.

I am getting a programInvocation error in main and I can not see the whole error because of Flink 1.7's limitation. In dashboard you do not get the whole exception trace to see in Flink 1.7. The Job is not getting submitted.

Anybody has any clue on this or faced anything similar like this?


问:
Get total count for table row?
I Have an if Statement in  the function is to make  Row Red... if $ced (which is date value coming from MySQL) is lesser than the current time the code is given below: what I am looking for is how can I get total number of rows like 20,30 or whatever the value is and echo

```<code><tr <?php if(($ced <= time())): ?> style="color:red;" <?php endif; ?>>
 <td><?php  echo $students_rollno_class;?></td>
 <td><?php  echo $students_admission_no;?> </td>
 <td><?php  echo $students_firstname;?></td>
 <td><?php  echo $students_contact;?></td>
 <td><?php  echo $students_reference_no;?></td>
 <td><?php  echo date('d/m/Y', strtotime($students_date));?></td>
 <td><?php  echo $newformat;?></td>
</code>```

what I tried is

```<code>if(($ced <= time())){
$totalCount=$totalCount+1 ;}
</code>```

the problem is its giving me a row numbers like 1,1,1,1,2,2,2,2,4,4,4,4 but i am looking for is single total count like 20

I have a box where I want to show total count the code is given below

```<code><div class="info-box-content">
<span class="info-box-text"><?php echo "Course Ended"; ?></span>
<span class="info-box-number"><?php echo $totalCount; ?></span>
 </div>
</code>```

image for reference as the rows are changing to red and i want to show total count in the box

Loop i Created but with this its giving me value of 384 as per picture i have only 188 students

```<code><?php
if(($ced <= time())){
$totalCount=$totalCount+1 ; ?>
 <tr <?php if(($ced <= time())): ?> style="color:red;" <?php endif; ?>>
 <td><?php  echo $students_rollno_class;?></td>
    <td><?php  echo $students_admission_no;?> </td>
      <td><?php  echo $students_firstname;?></td>
       <td><?php  echo $students_contact;?></td>
        <td><?php  echo $students_reference_no;?></td>
         <td><?php  echo date('d/m/Y', strtotime($students_date));?></td>
          <td><?php  echo date('d/m/Y', $ced);?></td>
             </tr><?php }}?>
                       <?php  echo $totalCount;?>
</code>```

and making all rows red

答:
In order for $totalCount++ to do what you're looking for, it needs to be within some kind of a loop.

You also don't want to echo $totalCount++, you want to echo your variable $totalCount. This is what contains your total count. The ++ is what increments your value stored in $totalCount.

Can you please share the remainder of your code so we can see how you are trying to accomplish this?

Title: Get total count for table row?

Body:
I Have an if Statement in  the function is to make  Row Red... if $ced (which is date value coming from MySQL) is lesser than the current time the code is given below: what I am looking for is how can I get total number of rows like 20,30 or whatever the value is and echo

<tr <?php if(($ced <= time())): ?> style="color:red;" <?php endif; ?>>
 <?php  echo $students_rollno_class;?>
 <?php  echo $students_admission_no;?>
 <?php  echo $students_firstname;?>
 <?php  echo $students_contact;?>
 <?php  echo $students_reference_no;?>
 <?php  echo date('d/m/Y', strtotime($students_date));?>
 <?php  echo $newformat;?>

what I tried is

if(($ced <= time())){
$totalCount=$totalCount+1 ;}

the problem is its giving me a row numbers like 1,1,1,1,2,2,2,2,4,4,4,4 but i am looking for is single total count like 20

I have a box where I want to show total count the code is given below

<?php echo "Course Ended"; ?>
<?php echo $totalCount; ?>

image for reference as the rows are changing to red and i want to show total count in the box

Loop i Created but with this its giving me value of 384 as per picture i have only 188 students

<?php
if(($ced <= time())){
$totalCount=$totalCount+1 ; ?>
 <tr <?php if(($ced <= time())): ?> style="color:red;" <?php endif; ?>>
 <?php  echo $students_rollno_class;?>
    <?php  echo $students_admission_no;?>
      <?php  echo $students_firstname;?>
       <?php  echo $students_contact;?>
        <?php  echo $students_reference_no;?>
         <?php  echo date('d/m/Y', strtotime($students_date));?>
          <?php  echo date('d/m/Y', $ced);?>

<?php }}?>
                       <?php  echo $totalCount;?>

and making all rows red


问:
Calculating average of list from certain point in list?
I have a question, I know that it is possible to calculate the average of a list but is it possible to calculate average but from a certain point?

For example:

```<code>def Average(lst):
    return sum(lst) / len(lst)

list = [2, 8, 6, 7, 3, 2, 1]
average = Average(lst)
</code>```

Printing average of the list:

```<code>print("Average of the list =", round(average, 2))
</code>```

Output:
    Average of the list = 4.14

Say we want to keep the first 3 values and average the rest to have only 4 values in the list

So my new list is:

```<code>list = [2, 8, 6, 7, 3, 2, 1]
new_list = [2, 8, 6, 12.25]
</code>```

Edit 1

Thank you all for your answers. I have another question, say, I don't know the length of my list and I just want 4 elements in my new list. How could I tackle this?

Body:
I have a question, I know that it is possible to calculate the average of a list but is it possible to calculate average but from a certain point?

For example:

def Average(lst):
    return sum(lst) / len(lst)

list = [2, 8, 6, 7, 3, 2, 1]
average = Average(lst)

Printing average of the list:

print("Average of the list =", round(average, 2))

Output:
    Average of the list = 4.14

Say we want to keep the first 3 values and average the rest to have only 4 values in the list

So my new list is:

list = [2, 8, 6, 7, 3, 2, 1]
new_list = [2, 8, 6, 12.25]

Edit 1

Thank you all for your answers. I have another question, say, I don't know the length of my list and I just want 4 elements in my new list. How could I tackle this?

Body:
You can do it like this

l=[2, 8, 6, 7, 3, 2, 1]
pt=3
l=l[:pt]+[sum(l[pt:])/len(l[pt:])]

output:

[2, 8, 6, 3.25]


问:
Basic maths for animation
Assuming I have a form and paint an oval on it. I then want to take a control (such as a picturebox) and (while keeping the top left corner of the control exactly on the line) I want to move the control pixel by pixel following the drawn oval.

Basically I want to calculate the Top/Left point for each position/pixel in my oval. I know its a basic formula but cant for the life of me remember what its called or how its accomplished.

Anyone care to help?

答:
```<code>double step=1.0; //  how fast do you want it to move

double halfWidth=100.0; //  width of the ellipse divided by 2
double halfHeight=50.0; //  height of the ellipse divided by 2

for (double angle=0; angle<360; angle+=step)
{
    int x=(int)halfWidth * Math.Cos(angle/180*Math.PI);
    int y=(int)halfHeight * Math.Sin(angle/180*Math.PI);
    pictureBox.TopLeft=new Point(x,y);
}
</code>```

EDIT:

Now, if you are about to ask why isn't it moving if you write it like that - you'll have to add message loop processing to it, in form of:

```<code>Application.DoEvents();
</code>```

which you will place inside the loop.

ContentLicense: CC BY-SA 3.0

Title: Basic maths for animation

Body:
double step=1.0; //  how fast do you want it to move

double halfWidth=100.0; //  width of the ellipse divided by 2
double halfHeight=50.0; //  height of the ellipse divided by 2

for (double angle=0; angle<360; angle+=step)
{
    int x=(int)halfWidth * Math.Cos(angle/180*Math.PI);
    int y=(int)halfHeight * Math.Sin(angle/180*Math.PI);
    pictureBox.TopLeft=new Point(x,y);
}

EDIT:

Now, if you are about to ask why isn't it moving if you write it like that - you'll have to add message loop processing to it, in form of:

Application.DoEvents();

which you will place inside the loop.


问:
Is connectionPoolSetting for single mongos instance or the whole cluster?
I am a server-side developer, working on a project which uses a mongo cluster as persistent database.

I have a question for https://mongodb.github.io/mongo-java-driver/3.8/javadoc/com/mongodb/connection/ConnectionPoolSettings.html

It said to a MongoDB server
But what if I have a connectionString like following one

```<code>mongodb://user:pwd@mongos1:port,mongos3:port,mongos3:port,mongos4:port,mongos5:port,mongos6:port/admin?readPreference=secondaryPreferred
</code>```

A mongodb sharded cluster which has 6 mongos instance.

Question:
Is the connectionPoolSetting related to one mongos server? or related to all mongos servers?

E.g. if we have maxSize = 10 in this setting, does it mean single client has max connection pool = 10 for single mongos server (max pool = 60 for my 6 mongos cluster)? Or max connection pool = 10 for the whole cluster no matter how many mongos server we have?

答:
Mongo Client

com.mongodb.client.MongoClient interface:

A client-side representation of a MongoDB cluster. Instances can represent either a standalone MongoDB instance, a replica set, or a sharded cluster. Instance of this class are responsible for maintaining an up-to-date state of the cluster, and possibly cache resources related to this, including background threads for monitoring, and connection pools.

MongoClient object is used to get access to the database, using the getDatebase() method and work with collections and documents in it.

From the documentation:

The MongoClient instance represents a pool of connections to the
  database; you will only need one instance of class MongoClient even
  with multiple threads.

IMPORTANT
  Typically you only create one MongoClient instance for a
  given MongoDB deployment (e.g. standalone, replica set, or a sharded
  cluster) and use it across your application. However, if you do create
  multiple instances:

All resource usage limits (e.g. max connections, etc.) apply per
  MongoClient instance.

    To dispose of an instance, call MongoClient.close() to clean up resources.

The following code creates a MongoDB client connection object with connection pooling to connect to a MongoDB instance.

```<code>MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("test");
</code>```

MongoClients.create() static method creates a connection object specified by the default host (localhost) and port (27017). You can explicitly specify other settings with the MongoClientSettings which specifies various settings to control the behavior of a MongoClient.

```<code>MongoClient mongoClient = MongoClients.create(MongoClientSettings settings)
</code>```

Connection Pool Settings:

The ConnectionPoolSettings object specifies all settings that relate to the pool of connections to a MongoDB server. The application creates this connection pool when the client object is created. This creating of connection pool is driver specific.

ConnectionPoolSettings.Builder is a builder for ConnectionPoolSettings has methods to specify the connection pool properties. E.g., maxSize(int maxSize): The maximum number of connections allowed. Default is 100. Other methods include, minSize, maxConnectionIdleTime, etc.

Code to instantiate a MongoClient with connection pool settings:

```<code>MongoClientSettings settings = MongoClientSettings.builder()
                                   .applyToConnectionPoolSettings(builder ->
                                       builder.maxSize(20).minSize(10)
                                    .build();
MongoClient mongoClient = MongoClients.create(settings);
//...
// Verify the connection pool settings max size as
settings.getConnectionPoolSettings().getMaxSize()
</code>```

Question: Is the connectionPoolSetting related to one mongos server?
  or related to all mongos servers?

A client or application connects to the sharded cluster (includes all its shards) via the mongos router. The client program specifies the URL connection string and other options for the connection. In a sharded cluster, a client may connect thru a set of mongoss or a single mongos, or multiple clients can connect thru a single mongos, etc.,; it depends upon your application architecture.

If you are connecting via a single mongos, you can specify the mongos's host, port, user/password, etc., in the connection string. If it is a multiple mongos's, then multiple host/port values. Irrespective of the number of mongos's, the client program connects to the cluster via only one mongos.

The connection pool setting is for one mongos router only, as an application connects to one mongos irrespective of the number of mongoss specified in the connection string.

Body:
I am a server-side developer, working on a project which uses a mongo cluster as persistent database.

I have a question for https://mongodb.github.io/mongo-java-driver/3.8/javadoc/com/mongodb/connection/ConnectionPoolSettings.html

It said to a MongoDB server
But what if I have a connectionString like following one

mongodb://user:pwd@mongos1:port,mongos3:port,mongos3:port,mongos4:port,mongos5:port,mongos6:port/admin?readPreference=secondaryPreferred

A mongodb sharded cluster which has 6 mongos instance.

Question:
Is the connectionPoolSetting related to one mongos server? or related to all mongos servers?

E.g. if we have maxSize = 10 in this setting, does it mean single client has max connection pool = 10 for single mongos server (max pool = 60 for my 6 mongos cluster)? Or max connection pool = 10 for the whole cluster no matter how many mongos server we have?

Body:
Mongo Client

com.mongodb.client.MongoClient interface:

A client-side representation of a MongoDB cluster. Instances can represent either a standalone MongoDB instance, a replica set, or a sharded cluster. Instance of this class are responsible for maintaining an up-to-date state of the cluster, and possibly cache resources related to this, including background threads for monitoring, and connection pools.

MongoClient object is used to get access to the database, using the getDatebase() method and work with collections and documents in it.

From the documentation:

The MongoClient instance represents a pool of connections to the
  database; you will only need one instance of class MongoClient even
  with multiple threads.

IMPORTANT
  Typically you only create one MongoClient instance for a
  given MongoDB deployment (e.g. standalone, replica set, or a sharded
  cluster) and use it across your application. However, if you do create
  multiple instances:

All resource usage limits (e.g. max connections, etc.) apply per
  MongoClient instance.

    To dispose of an instance, call MongoClient.close() to clean up resources.

The following code creates a MongoDB client connection object with connection pooling to connect to a MongoDB instance.

MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("test");

MongoClients.create() static method creates a connection object specified by the default host (localhost) and port (27017). You can explicitly specify other settings with the MongoClientSettings which specifies various settings to control the behavior of a MongoClient.

MongoClient mongoClient = MongoClients.create(MongoClientSettings settings)

Connection Pool Settings:

The ConnectionPoolSettings object specifies all settings that relate to the pool of connections to a MongoDB server. The application creates this connection pool when the client object is created. This creating of connection pool is driver specific.

ConnectionPoolSettings.Builder is a builder for ConnectionPoolSettings has methods to specify the connection pool properties. E.g., maxSize(int maxSize): The maximum number of connections allowed. Default is 100. Other methods include, minSize, maxConnectionIdleTime, etc.

Code to instantiate a MongoClient with connection pool settings:

MongoClientSettings settings = MongoClientSettings.builder()
                                   .applyToConnectionPoolSettings(builder ->
                                       builder.maxSize(20).minSize(10)
                                    .build();
MongoClient mongoClient = MongoClients.create(settings);
//...
// Verify the connection pool settings max size as
settings.getConnectionPoolSettings().getMaxSize()

Question: Is the connectionPoolSetting related to one mongos server?
  or related to all mongos servers?

A client or application connects to the sharded cluster (includes all its shards) via the mongos router. The client program specifies the URL connection string and other options for the connection. In a sharded cluster, a client may connect thru a set of mongoss or a single mongos, or multiple clients can connect thru a single mongos, etc.,; it depends upon your application architecture.

If you are connecting via a single mongos, you can specify the mongos's host, port, user/password, etc., in the connection string. If it is a multiple mongos's, then multiple host/port values. Irrespective of the number of mongos's, the client program connects to the cluster via only one mongos.

The connection pool setting is for one mongos router only, as an application connects to one mongos irrespective of the number of mongoss specified in the connection string.


问:
Element is not clickable at point . Other element would receive the click:
I'm trying to click a button on top of the page.I'm using CSS selector and it works perfectly fine when I run it in my local eclipse.But when I try to run it on Jenkins server on my local machine it fails, saying element not clickable.
When I saw the screenshot of failed test on Jenkins I see that the header is overlapping the button that I want to click.
I have tried almost everything using XPath,CSS,move to element,move mouse.
But still can't fix it, Someone please help.

I'm tring to click on add buttoun

```<code>org.openqa.selenium.WebDriverException: Element is not clickable at point (775.25, 10.166671752929688). Other element would receive the click: <div class="globalHeader-UtilTop"></div>
Command duration or timeout: 69 milliseconds
Build info: version: '2.53.0', revision: '35ae25b1534ae328c771e0856c93e187490ca824', time: '2016-03-15 10:43:46'
System info: host', ip: '', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_80'

<div class="Componet-intels**strong text**-Container">
<div class="Componet-intels-Container-Header">
<div class="Componet-intels-Container-Content">
<div class="Componet-intels-Container-Content-Row">
<span class="Componet-intels-Item"> Item # </span>
<span class="Componet-intels-Text-Item">
<span class="Componet-intels-Lable-Quantity"> Qty: </span>
<span class="Componet-intels-Text-Quantity">
<span class="Componet-intels-Button">
**<input class="Componet-intelsButtonIcon" type="button" value="Add">**
</span>
</div>
</code>```

答:
I got this error while using Robot Framework and Chrome browser for Salesforce automation ,
It got solved when I used key press event (Press Keys  ${locator}  RETURN) instead of 'Click Element' or 'Click Button' keyword.</p>

Body:
I'm trying to click a button on top of the page.I'm using CSS selector and it works perfectly fine when I run it in my local eclipse.But when I try to run it on Jenkins server on my local machine it fails, saying element not clickable.
When I saw the screenshot of failed test on Jenkins I see that the header is overlapping the button that I want to click.
I have tried almost everything using XPath,CSS,move to element,move mouse.
But still can't fix it, Someone please help.

I'm tring to click on add buttoun

org.openqa.selenium.WebDriverException: Element is not clickable at point (775.25, 10.166671752929688). Other element would receive the click:

Command duration or timeout: 69 milliseconds
Build info: version: '2.53.0', revision: '35ae25b1534ae328c771e0856c93e187490ca824', time: '2016-03-15 10:43:46'
System info: host', ip: '', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_80'

 Item #

 Qty:

**<input class="Componet-intelsButtonIcon" type="button" value="Add">**


问:
Unable to target button to separate behaviour using :not()
I have a HTML5 application which has a table (ID is #myTable in the remainder of this question). The table is populated by an ajax request.

Following the ajax response a single row of the table looks like this:

```<code><tr>
    <td>ID 001</td>
    <td>Foo</td>
    <td>Bar</td>
    <td>Baz</td>
    <td><a href="/fge?id=001" class="btn-fge">Find group entries</a></td>
</tr>
</code>```

The anchor in the last column isn't present on every row. It only appears for certain rows. If the anchor doesn't appear an empty row is rendered: 	.

Prior to this anchor being added I'd written a function which toggles expanding/collapsing each row. Upon expansion an additional ajax request was made to present further data. The behaviour was such that the user could click anywhere inside the row.

```<code>$('#myTable tbody').on('click', 'td', function (e) {
    var tr = $(this).closest('tr');

    // Code to expand/collapse tr
    // ...

    // Ajax request for additional row data
    // ...
}
</code>```

This all worked without any problems.

However, I want to segregate the behaviour such that the code above doesn't fire if the user has clicked the anchor. Conversely if they click anywhere inside the row other than the anchor it should fire.

I've read Check if clicked element doesn't have a specific class and attempted to target .btn-fge using a :not() condition as follows.

```<code>$('#myTable tbody').on('click', 'td:not(.btn-fge)', function (e) {

}
</code>```

This doesn't work (although I believe this might be because .btn-fge isn't a class on the  but rather an anchor inside it?). The collapsing/expanding row behaviour still fires followed by the browser redirecting to the href value. In the example given the behaviour is:

Click .btn-fge.

The row is expanded (or if it was already expanded it is collapsed).

The browser follows the href on .btn-fge so in this case redirects to /fge?id=001.

I want (1) followed by (3) to occur, but not (2) when clicking .btn-fge.

I've tried logging console.log($(this)); followed by e.preventDefault(). It doesn't matter whereabouts inside the row I click - whether it's on the button or not - it gives the same output as follows.

How can I target this such that the button behaviour is different to clicking other places inside the row?

I'm using jquery version 3.2.1 and would prefer a jquery solution but a vanilla JavaScript one would also be acceptable.

Edit - I've made a fiddle here https://jsfiddle.net/adrq0nhz/ and if you click anywhere inside the table it will console log "this is still firing" which is effectively the issue of the anchor having no separate behavior. Note: the .btn-fge class is on the anchor, not the , and this cannot be changed.

答:
The existing answers all suggest checking this in the event handler, which, IMO, is in the wrong place.

The row-click event handler should only need to handle row click events, not that it shouldn't handle some other event.

This paradigm could get very messy very quickly with additional buttons/inputs/selects - better not to get into the handler in the first place.

You can stop the row getting the click with e.stopPropagation() - this allows you to still click in the same cell around the button, eg:

$("table tr td").click(() => console.log("row click"));
$(".btn-fge").click((e) => e.stopPropagation());```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  border-collapse: collapse;
}

table, th, td {
  border: 1px solid black;
  padding:2px;
}</code>```

    ID 001
    Foo
    Bar
    Baz
    Find group entriesclick here also works

```
</div>
</div>
</p>

<p>Updated fiddle: https://jsfiddle.net/8ahn6dc1/</p>

<hr>

<p>An alternative is to not add click to the button cell.  It's noted that you don't want to change the HTML, but you can still "change" the HTML via js, example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(".btn-fge").closest("td").addClass("noclick");
$("table tr td:not(.noclick)").click(() => console.log("row click"));</code>```

table {
  border-collapse: collapse;
}

table, th, td {
  border: 1px solid black;
  padding:2px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
    <td>ID 001</td>
    <td>Foo</td>
    <td>Bar</td>
    <td>Baz</td>
    <td>Find group entriesclick here does nothing</td>
</tr>
</table></code>```

Body:
I have a HTML5 application which has a table (ID is #myTable in the remainder of this question). The table is populated by an ajax request.

Following the ajax response a single row of the table looks like this:

    ID 001
    Foo
    Bar
    Baz
    Find group entries

The anchor in the last column isn't present on every row. It only appears for certain rows. If the anchor doesn't appear an empty row is rendered: 	.

Prior to this anchor being added I'd written a function which toggles expanding/collapsing each row. Upon expansion an additional ajax request was made to present further data. The behaviour was such that the user could click anywhere inside the row.

$('#myTable tbody').on('click', 'td', function (e) {
    var tr = $(this).closest('tr');

    // Code to expand/collapse tr
    // ...

    // Ajax request for additional row data
    // ...
}

This all worked without any problems.

However, I want to segregate the behaviour such that the code above doesn't fire if the user has clicked the anchor. Conversely if they click anywhere inside the row other than the anchor it should fire.

I've read Check if clicked element doesn't have a specific class and attempted to target .btn-fge using a :not() condition as follows.

$('#myTable tbody').on('click', 'td:not(.btn-fge)', function (e) {

}

This doesn't work (although I believe this might be because .btn-fge isn't a class on the  but rather an anchor inside it?). The collapsing/expanding row behaviour still fires followed by the browser redirecting to the href value. In the example given the behaviour is:

Click .btn-fge.

The row is expanded (or if it was already expanded it is collapsed).

The browser follows the href on .btn-fge so in this case redirects to /fge?id=001.

I want (1) followed by (3) to occur, but not (2) when clicking .btn-fge.

I've tried logging console.log($(this)); followed by e.preventDefault(). It doesn't matter whereabouts inside the row I click - whether it's on the button or not - it gives the same output as follows.

How can I target this such that the button behaviour is different to clicking other places inside the row?

I'm using jquery version 3.2.1 and would prefer a jquery solution but a vanilla JavaScript one would also be acceptable.

Edit - I've made a fiddle here https://jsfiddle.net/adrq0nhz/ and if you click anywhere inside the table it will console log "this is still firing" which is effectively the issue of the anchor having no separate behavior. Note: the .btn-fge class is on the anchor, not the , and this cannot be changed.

Body:
The existing answers all suggest checking this in the event handler, which, IMO, is in the wrong place.

The row-click event handler should only need to handle row click events, not that it shouldn't handle some other event.

This paradigm could get very messy very quickly with additional buttons/inputs/selects - better not to get into the handler in the first place.

You can stop the row getting the click with e.stopPropagation() - this allows you to still click in the same cell around the button, eg:

$("table tr td").click(() => console.log("row click"));
$(".btn-fge").click((e) => e.stopPropagation());

table {
  border-collapse: collapse;
}

table, th, td {
  border: 1px solid black;
  padding:2px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
    <td>ID 001</td>
    <td>Foo</td>
    <td>Bar</td>
    <td>Baz</td>
    <td><a href="#" class="btn-fge">Find group entries</a>click here also works</td>
</tr>
</table>

Updated fiddle: https://jsfiddle.net/8ahn6dc1/

An alternative is to not add click to the button cell.  It's noted that you don't want to change the HTML, but you can still "change" the HTML via js, example:

$(".btn-fge").closest("td").addClass("noclick");
$("table tr td:not(.noclick)").click(() => console.log("row click"));

table {
  border-collapse: collapse;
}

table, th, td {
  border: 1px solid black;
  padding:2px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
    <td>ID 001</td>
    <td>Foo</td>
    <td>Bar</td>
    <td>Baz</td>
    <td><a href="#" class="btn-fge">Find group entries</a>click here does nothing</td>
</tr>
</table>


问:
Spring Data and Native Query with pagination
In a web project, using latest spring-data (1.10.2) with a MySQL 5.6 database, I'm trying to use a native query with pagination but I'm experiencing an org.springframework.data.jpa.repository.query.InvalidJpaQueryMethodException at startup.

UPDATE: 20180306 This issue is now fixed in Spring 2.0.4 For those still interested or stuck with older versions check the related answers and comments for workarounds.

According to Example 50 at Using @Query from spring-data documentation this is possible specifying the query itself and a countQuery, like this:

```<code>public interface UserRepository extends JpaRepository<User, Long> {
  @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1",
    countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
    nativeQuery = true)
  Page<User> findByLastname(String lastname, Pageable pageable);
}
</code>```

Out of curiosity, In NativeJpaQuery class I can see that it contains the following code to check if it's a valid jpa query:

```<code>public NativeJpaQuery(JpaQueryMethod method, EntityManager em, String queryString, EvaluationContextProvider evaluationContextProvider, SpelExpressionParser parser) {
   super(method, em, queryString, evaluationContextProvider, parser);
   JpaParameters parameters = method.getParameters();
   boolean hasPagingOrSortingParameter = parameters.hasPageableParameter() || parameters.hasSortParameter();
   boolean containsPageableOrSortInQueryExpression = queryString.contains("#pageable") || queryString.contains("#sort");
   if(hasPagingOrSortingParameter && !containsPageableOrSortInQueryExpression) {
       throw new InvalidJpaQueryMethodException("Cannot use native queries with dynamic sorting and/or pagination in method " + method);
   }
}
</code>```

My query contains a Pageable parameter, so hasPagingOrSortingParameter is true, but it's also looking for a #pageable or #sort sequence inside the queryString, which I do not provide.

I've tried adding #pageable (it's a comment) at the end of my query, which makes validation to pass but then, it fails at execution saying that the query expects one additional parameter: 3 instead of 2.

Funny thing is that, if I manually change containsPageableOrSortInQueryExpression from false to true while running, the query works fine so I don't know why it's checking for that string to be at my queryString and I don't know how to provide it.

Any help would be much appreciated.

Update 01/30/2018
It seems that developers at spring-data project are working on a fix for this issue with a PR by Jens Schauder

答:
You can use below code for h2 and MySQl</p>

```<code>    @Query(value = "SELECT req.CREATED_AT createdAt, req.CREATED_BY createdBy,req.APP_ID appId,req.NOTE_ID noteId,req.MODEL model FROM SUMBITED_REQUESTS  req inner join NOTE note where req.NOTE_ID=note.ID and note.CREATED_BY= :userId "
        ,
         countQuery = "SELECT count(*) FROM SUMBITED_REQUESTS req inner join NOTE note WHERE req.NOTE_ID=note.ID and note.CREATED_BY=:userId",
        nativeQuery = true)
Page<UserRequestsDataMapper> getAllRequestForCreator(@Param("userId") String userId,Pageable pageable);
</code>```

Body:
In a web project, using latest spring-data (1.10.2) with a MySQL 5.6 database, I'm trying to use a native query with pagination but I'm experiencing an org.springframework.data.jpa.repository.query.InvalidJpaQueryMethodException at startup.

UPDATE: 20180306 This issue is now fixed in Spring 2.0.4 For those still interested or stuck with older versions check the related answers and comments for workarounds.

According to Example 50 at Using @Query from spring-data documentation this is possible specifying the query itself and a countQuery, like this:

public interface UserRepository extends JpaRepository<User, Long> {
  @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1",
    countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
    nativeQuery = true)
  Page<User> findByLastname(String lastname, Pageable pageable);
}

Out of curiosity, In NativeJpaQuery class I can see that it contains the following code to check if it's a valid jpa query:

public NativeJpaQuery(JpaQueryMethod method, EntityManager em, String queryString, EvaluationContextProvider evaluationContextProvider, SpelExpressionParser parser) {
   super(method, em, queryString, evaluationContextProvider, parser);
   JpaParameters parameters = method.getParameters();
   boolean hasPagingOrSortingParameter = parameters.hasPageableParameter() || parameters.hasSortParameter();
   boolean containsPageableOrSortInQueryExpression = queryString.contains("#pageable") || queryString.contains("#sort");
   if(hasPagingOrSortingParameter && !containsPageableOrSortInQueryExpression) {
       throw new InvalidJpaQueryMethodException("Cannot use native queries with dynamic sorting and/or pagination in method " + method);
   }
}

My query contains a Pageable parameter, so hasPagingOrSortingParameter is true, but it's also looking for a #pageable or #sort sequence inside the queryString, which I do not provide.

I've tried adding #pageable (it's a comment) at the end of my query, which makes validation to pass but then, it fails at execution saying that the query expects one additional parameter: 3 instead of 2.

Funny thing is that, if I manually change containsPageableOrSortInQueryExpression from false to true while running, the query works fine so I don't know why it's checking for that string to be at my queryString and I don't know how to provide it.

Any help would be much appreciated.

Update 01/30/2018
It seems that developers at spring-data project are working on a fix for this issue with a PR by Jens Schauder

Body:
You can use below code for h2 and MySQl

    @Query(value = "SELECT req.CREATED_AT createdAt, req.CREATED_BY createdBy,req.APP_ID appId,req.NOTE_ID noteId,req.MODEL model FROM SUMBITED_REQUESTS  req inner join NOTE note where req.NOTE_ID=note.ID and note.CREATED_BY= :userId "
        ,
         countQuery = "SELECT count(*) FROM SUMBITED_REQUESTS req inner join NOTE note WHERE req.NOTE_ID=note.ID and note.CREATED_BY=:userId",
        nativeQuery = true)
Page<UserRequestsDataMapper> getAllRequestForCreator(@Param("userId") String userId,Pageable pageable);


问:
Powershell newcomer
I am a total new comer to powershell so please forgive me if my question sounds stupid. I found the script below from Yuri Posidelov which I tweaked to activate a process and show the window and send keystrokes to shut down the process which works great. However it fails if there are two process with the same name can anyone help me with this.

Orignal code by Yuriy Posidelov

```<code>param([string] $proc="SBDDesktop", [string]$adm)

cls

Add-Type @"

  using System;

  using System.Runtime.InteropServices;

  public class WinAp {

     [DllImport("user32.dll")]

     [return: MarshalAs(UnmanagedType.Bool)]

     public static extern bool SetForegroundWindow(IntPtr hWnd);

     [DllImport("user32.dll")]

     [return: MarshalAs(UnmanagedType.Bool)]

     public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

  }

"@

$p = Get-Process |where {$_.mainWindowTItle }|where {$_.Name -like "$proc"}

if (($p -eq $null) -and ($adm -ne ""))

{

    Start-Process "$proc" -Verb runAs

}

elseif (($p -eq $null) -and ($adm -eq ""))

{

    Start-Process "$proc" #-Verb runAs

}

else

{

    $h = $p.MainWindowHandle

    [void] [WinAp]::SetForegroundWindow($h)

    [void] [WinAp]::ShowWindow($h,3);

    $wshell = New-Object -ComObject wscript.shell;

    #$wshell.SendKeys('~')

    $wshell.SendKeys('%fx')

    sleep 1

    $wshell.SendKeys('N')

}

#|format-table id,name,mainwindowtitle –AutoSize

# static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

# powershell.exe -windowstyle hidden -file *.ps1 -adm "a"
</code>```

答:
The problem is that the line $p = Get-Process |where {$_.mainWindowTItle }|where {$_.Name -like "$proc"} will create an object of type array if it's more than one process. Else it will create an object of type System.ComponentModel.Component. You can test this with:

```<code>$p.GetType()
</code>```

To compensate this you can execute your code foreach process in the array even if there is only one element in that array:

```<code>...
[array]$array = Get-Process |where {$_.mainWindowTItle }|where {$_.Name -like "$proc"}

foreach ($p in $array){

    if (($p -eq $null) -and ($adm -ne ""))

    {

        Start-Process "$proc" -Verb runAs

    }

    elseif (($p -eq $null) -and ($adm -eq ""))

    {

        Start-Process "$proc" #-Verb runAs

    }

    else

    {

        $h = $p.MainWindowHandle

        [void] [WinAp]::SetForegroundWindow($h)

        [void] [WinAp]::ShowWindow($h,3);

        $wshell = New-Object -ComObject wscript.shell;

        #$wshell.SendKeys('~')

        $wshell.SendKeys('%fx')

        sleep 1

        $wshell.SendKeys('N')

    }

    #|format-table id,name,mainwindowtitle –AutoSize

    # static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    # powershell.exe -windowstyle hidden -file *.ps1 -adm "a"

}
</code>```

Title: Powershell newcomer

Body:
I am a total new comer to powershell so please forgive me if my question sounds stupid. I found the script below from Yuri Posidelov which I tweaked to activate a process and show the window and send keystrokes to shut down the process which works great. However it fails if there are two process with the same name can anyone help me with this.

Orignal code by Yuriy Posidelov

param([string] $proc="SBDDesktop", [string]$adm)

cls

Add-Type @"

  using System;

  using System.Runtime.InteropServices;

  public class WinAp {

     [DllImport("user32.dll")]

     [return: MarshalAs(UnmanagedType.Bool)]

     public static extern bool SetForegroundWindow(IntPtr hWnd);

     [DllImport("user32.dll")]

     [return: MarshalAs(UnmanagedType.Bool)]

     public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

  }

"@

$p = Get-Process |where {$_.mainWindowTItle }|where {$_.Name -like "$proc"}

if (($p -eq $null) -and ($adm -ne ""))

{

    Start-Process "$proc" -Verb runAs

}

elseif (($p -eq $null) -and ($adm -eq ""))

{

    Start-Process "$proc" #-Verb runAs

}

else

{

    $h = $p.MainWindowHandle

    [void] [WinAp]::SetForegroundWindow($h)

    [void] [WinAp]::ShowWindow($h,3);

    $wshell = New-Object -ComObject wscript.shell;

    #$wshell.SendKeys('~')

    $wshell.SendKeys('%fx')

    sleep 1

    $wshell.SendKeys('N')

}

#|format-table id,name,mainwindowtitle –AutoSize

# static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

# powershell.exe -windowstyle hidden -file *.ps1 -adm "a"

Body:
The problem is that the line $p = Get-Process |where {$_.mainWindowTItle }|where {$_.Name -like "$proc"} will create an object of type array if it's more than one process. Else it will create an object of type System.ComponentModel.Component. You can test this with:

$p.GetType()

To compensate this you can execute your code foreach process in the array even if there is only one element in that array:

...
[array]$array = Get-Process |where {$_.mainWindowTItle }|where {$_.Name -like "$proc"}

foreach ($p in $array){

    if (($p -eq $null) -and ($adm -ne ""))

    {

        Start-Process "$proc" -Verb runAs

    }

    elseif (($p -eq $null) -and ($adm -eq ""))

    {

        Start-Process "$proc" #-Verb runAs

    }

    else

    {

        $h = $p.MainWindowHandle

        [void] [WinAp]::SetForegroundWindow($h)

        [void] [WinAp]::ShowWindow($h,3);

        $wshell = New-Object -ComObject wscript.shell;

        #$wshell.SendKeys('~')

        $wshell.SendKeys('%fx')

        sleep 1

        $wshell.SendKeys('N')

    }

    #|format-table id,name,mainwindowtitle –AutoSize

    # static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    # powershell.exe -windowstyle hidden -file *.ps1 -adm "a"

}


问:
Node.js execute shell command which requires an input after a few seconds
I'm trying to use the now cli to purchase a domain through my Node.js server but I cannot figure out how to execute a shell command in Node and to automatically insert the input when asked.

Here's my command using child_process.exec

const { stdout } = await exec(`now --token ${NOW_TOKEN} domains buy ${domainName}.${tld}`)
```

This does nothing because the command is waiting input (y/N) to confirm buying the domain.
They don't have any option in the commande to bypass the question like --yes.

How can I pass a string y + Enter when the process is waiting ?

答:
Be careful. Your usage can certainly violate their ToS if you are reselling parts of their offering. You may need to reach out to their support channel for clarification.

Regarding the code. You can take a look at this file for inspiration: https://github.com/zeit/now/blob/master/packages/now-cli/test/integration.js

One alternative is:

```<code>stdin.write('y\n')
</code>```

Body:
I'm trying to use the now cli to purchase a domain through my Node.js server but I cannot figure out how to execute a shell command in Node and to automatically insert the input when asked.

Here's my command using child_process.exec

const { stdout } = await exec(`now --token ${NOW_TOKEN} domains buy ${domainName}.${tld}`)

This does nothing because the command is waiting input (y/N) to confirm buying the domain.
They don't have any option in the commande to bypass the question like --yes.

How can I pass a string y + Enter when the process is waiting ?

Body:
Be careful. Your usage can certainly violate their ToS if you are reselling parts of their offering. You may need to reach out to their support channel for clarification.

Regarding the code. You can take a look at this file for inspiration: https://github.com/zeit/now/blob/master/packages/now-cli/test/integration.js

One alternative is:

stdin.write('y\n')


问:
SQLAlchemy insert from a JSON list to database
I have a list with a JSON like so:

```<code>print(type(listed)) # <class 'list'>
print (listed)

[
   {
       "email": "x@gmail.com",
       "fullname": "xg gf",
       "points": 5,
       "image_url", "https://imgur.com/random.pmg"
   },
   {
        ... similar json for the next user and so on
   }
]
</code>```

I'm trying to insert them into my postgres database that has a model like this:

```<code>class Users(db.Model):
    __tablename__ = 'users'

    email = db.Column(db.String(), primary_key=True)
    displayName = db.Column(db.String())
    image = db.Column(db.String())
    points = db.Column(db.Integer())
</code>```

But I'm quite stuck, I've tried several approaches but none worked, anyone can guide me with an example on how to do it properly?

答:
Here's a solution without pandas, using SQLAlchemy Core

create engine

```<code>engine = sqlalchemy.create_engine('...')
</code>```

load the metadata using the engine as the bind parameter

```<code>metadata = sqalchemy.Metadata(bind=engine)
</code>```

make a reference to the table

```<code>users_table = sqlalchemy.Table('users', metadata, autoload = True)
</code>```

you can then start your inserts

```<code>for user in json:
    query = users_table.insert()
    query.values(**user)

    my_session = Session(engine)
    my_session.execute(query)
    my_session.close()
</code>```

This creates a session for every user in json, but I thought you might like it anyway. Its very flexible and works for any table, you don't even need a model. Just make sure the json doesnt contain any columns that dont exist in the db (this means you will need to use "img_url" (column name) in both the json key and in the db column name)

Body:
I have a list with a JSON like so:

print(type(listed)) # <class 'list'>
print (listed)

[
   {
       "email": "x@gmail.com",
       "fullname": "xg gf",
       "points": 5,
       "image_url", "https://imgur.com/random.pmg"
   },
   {
        ... similar json for the next user and so on
   }
]

I'm trying to insert them into my postgres database that has a model like this:

class Users(db.Model):
    __tablename__ = 'users'

    email = db.Column(db.String(), primary_key=True)
    displayName = db.Column(db.String())
    image = db.Column(db.String())
    points = db.Column(db.Integer())

But I'm quite stuck, I've tried several approaches but none worked, anyone can guide me with an example on how to do it properly?

Body:
Here's a solution without pandas, using SQLAlchemy Core

create engine

engine = sqlalchemy.create_engine('...')

load the metadata using the engine as the bind parameter

metadata = sqalchemy.Metadata(bind=engine)

make a reference to the table

users_table = sqlalchemy.Table('users', metadata, autoload = True)

you can then start your inserts

for user in json:
    query = users_table.insert()
    query.values(**user)

    my_session = Session(engine)
    my_session.execute(query)
    my_session.close()

This creates a session for every user in json, but I thought you might like it anyway. Its very flexible and works for any table, you don't even need a model. Just make sure the json doesnt contain any columns that dont exist in the db (this means you will need to use "img_url" (column name) in both the json key and in the db column name)


问:
bazaar + cruise control
The team i work with is using Bazaar as its VCS, i would like to introduce CruiseControl (CC) with PHPUnderControl (PUC) into the mix, but cannot seem to find any documentation or plugin for bazaar and CC. There is a plugin for cc.net, but it has to run on linux yes i know mono but it seems PUC requires CC not cc.net. is there any way for bazaar to intergrate with CC.</p>

答:
If you have a functioning .NET plugin (with unit tests?) it would probably be straightforward to port to CC Java.

If you're not comfortable with Java you might ask on the CC developers mailing list to see if one them -- like me ;) -- would do the port for you. I'm always happy to help people who are writing plugins and I expect porting a SourceControl plugin would be quick and easy.

OwnerDisplayName: Daniel

ContentLicense: CC BY-SA 2.5

Title: bazaar + cruise control

OwnerDisplayName: Jeffrey Fredrick


问:
Exception: URL fetch failure on https://s3.amazonaws.com/text-datasets/imdb.npz: None -- [WinError 10060]
Following is the code for text classification problem over the IMDB dataset. I am unable to run the code as it is showing the error given below. Please help me with this. Thanks in advance.

CODE:

from keras.preprocessing import sequence

from keras.models import Sequential

from keras.layers import Dense, Embedding, Conv1D, GlobalMaxPooling1D

from keras.datasets import imdb

max_features = 5000

maxlen = 100

batch_size = 64

embedding_dims = 16

filters = 128

kernel_size = 3

epochs = 5

(x_train, y_train), (_, _) = imdb.load_data(num_words = max_features)

x_train = sequence.pad_sequences(x_train, maxlen = maxlen)

print(len(x_train))

for sample in x_train :

    print(sample)

model = Sequential()

model.add(Embedding(max_features, embedding_dims, input_length = maxlen))

model.add(Conv1D(filters, kernel_size, padding = 'valid', activation = 'relu', strides = 1))

model.add(GlobalMaxPooling1D())

model.add(Dense(128, activation = 'relu'))

model.add(Dense(1, activation = 'sigmoid'))

model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['acc'])

model.fit(x_train, y_train, batch_size = batch_size, epochs = epochs)
```

<p><strong>ERROR :</strong></p>

```Downloading data from https://s3.amazonaws.com/text-datasets/imdb.npz

---------------------------------------------------------------------------
TimeoutError                              Traceback (most recent call last)

~\Anaconda3\lib\urllib\request.py in do_open(self, http_class, req, **http_conn_args)

   1316                 h.request(req.get_method(), req.selector, req.data, headers,

-> 1317                           encode_chunked=req.has_header('Transfer-encoding'))

   1318             except OSError as err: # timeout error

~\Anaconda3\lib\http\client.py in request(self, method, url, body, headers, encode_chunked)

   1228         """Send a complete request to the server."""

-> 1229         self._send_request(method, url, body, headers, encode_chunked)

   1230

~\Anaconda3\lib\http\client.py in _send_request(self, method, url, body, headers, encode_chunked)

   1274             body = _encode(body, 'body')

-> 1275         self.endheaders(body, encode_chunked=encode_chunked)

   1276

~\Anaconda3\lib\http\client.py in endheaders(self, message_body, encode_chunked)

   1223             raise CannotSendHeader()

-> 1224         self._send_output(message_body, encode_chunked=encode_chunked)

   1225

~\Anaconda3\lib\http\client.py in _send_output(self, message_body, encode_chunked)

   1015         del self._buffer[:]

-> 1016         self.send(msg)

   1017

~\Anaconda3\lib\http\client.py in send(self, data)

    955             if self.auto_open:

--> 956                 self.connect()

    957             else:

~\Anaconda3\lib\http\client.py in connect(self)

   1383

-> 1384             super().connect()

   1385

~\Anaconda3\lib\http\client.py in connect(self)

    927         self.sock = self._create_connection(

--> 928             (self.host,self.port), self.timeout, self.source_address)

    929         self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

~\Anaconda3\lib\socket.py in create_connection(address, timeout, source_address)

    726     if err is not None:

--> 727         raise err

    728     else:

~\Anaconda3\lib\socket.py in create_connection(address, timeout, source_address)

    715                 sock.bind(source_address)

--> 716             sock.connect(sa)

    717             # Break explicitly a reference cycle

TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly

respond after a period of time, or established connection failed because connected host has failed to

respond

During handling of the above exception, another exception occurred:

URLError                                  Traceback (most recent call last)

~\Anaconda3\lib\site-packages\keras\utils\data_utils.py in get_file(fname, origin, untar, md5_hash,

file_hash, cache_subdir, hash_algorithm, extract, archive_format, cache_dir)

    221             try:

--> 222                 urlretrieve(origin, fpath, dl_progress)

    223             except HTTPError as e:

~\Anaconda3\lib\urllib\request.py in urlretrieve(url, filename, reporthook, data)

    246

--> 247     with contextlib.closing(urlopen(url, data)) as fp:

    248         headers = fp.info()

~\Anaconda3\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)

    221         opener = _opener

--> 222     return opener.open(url, data, timeout)

    223

~\Anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout)

    524

--> 525         response = self._open(req, data)

    526

~\Anaconda3\lib\urllib\request.py in _open(self, req, data)

    542         result = self._call_chain(self.handle_open, protocol, protocol +

--> 543                                   '_open', req)

    544         if result:

~\Anaconda3\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)

    502             func = getattr(handler, meth_name)

--> 503             result = func(*args)

    504             if result is not None:

~\Anaconda3\lib\urllib\request.py in https_open(self, req)

   1359             return self.do_open(http.client.HTTPSConnection, req,

-> 1360                 context=self._context, check_hostname=self._check_hostname)

   1361

~\Anaconda3\lib\urllib\request.py in do_open(self, http_class, req, **http_conn_args)

   1318             except OSError as err: # timeout error

-> 1319                 raise URLError(err)

   1320             r = h.getresponse()

URLError: <urlopen error [WinError 10060] A connection attempt failed because the connected party did not

properly respond after a period of time, or established connection failed because connected host has

failed to respond>

During handling of the above exception, another exception occurred:

Exception                                 Traceback (most recent call last)

<ipython-input-16-82c1e9073098> in <module>

      8 epochs = 5

      9

---> 10 (x_train, y_train), (_, _) = imdb.load_data(num_words = max_features)

     11

     12 x_train = sequence.pad_sequences(x_train, maxlen = maxlen)

~\Anaconda3\lib\site-packages\keras\datasets\imdb.py in load_data(path, num_words, skip_top, maxlen,

seed, start_char, oov_char, index_from, **kwargs)

     55     path = get_file(path,

     56                     origin='https://s3.amazonaws.com/text-datasets/imdb.npz',

---> 57                     file_hash='599dadb1135973df5b59232a0e9a887c')

     58     with np.load(path) as f:

     59         x_train, labels_train = f['x_train'], f['y_train']

~\Anaconda3\lib\site-packages\keras\utils\data_utils.py in get_file(fname, origin, untar, md5_hash,

file_hash, cache_subdir, hash_algorithm, extract, archive_format, cache_dir)

    224                 raise Exception(error_msg.format(origin, e.code, e.msg))

    225             except URLError as e:

--> 226                 raise Exception(error_msg.format(origin, e.errno, e.reason))

    227         except (Exception, KeyboardInterrupt):

    228             if os.path.exists(fpath):

Exception: URL fetch failure on https://s3.amazonaws.com/text-datasets/imdb.npz: None -- [WinError 10060]
```

A connection attempt failed because the connected party did not properly respond after a period of time,

or established connection failed because connected host has failed to respond

答: Your network issue. Url https://s3.amazonaws.com/text-datasets/imdb.npz is accessible from other networks.</p>

Body:
Following is the code for text classification problem over the IMDB dataset. I am unable to run the code as it is showing the error given below. Please help me with this. Thanks in advance.

CODE:

from keras.preprocessing import sequence

from keras.models import Sequential

from keras.layers import Dense, Embedding, Conv1D, GlobalMaxPooling1D

from keras.datasets import imdb

max_features = 5000

maxlen = 100

batch_size = 64

embedding_dims = 16

filters = 128

kernel_size = 3

epochs = 5

(x_train, y_train), (_, _) = imdb.load_data(num_words = max_features)

x_train = sequence.pad_sequences(x_train, maxlen = maxlen)

print(len(x_train))

for sample in x_train :

    print(sample)

model = Sequential()

model.add(Embedding(max_features, embedding_dims, input_length = maxlen))

model.add(Conv1D(filters, kernel_size, padding = 'valid', activation = 'relu', strides = 1))

model.add(GlobalMaxPooling1D())

model.add(Dense(128, activation = 'relu'))

model.add(Dense(1, activation = 'sigmoid'))

model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['acc'])

model.fit(x_train, y_train, batch_size = batch_size, epochs = epochs)

ERROR :

Downloading data from https://s3.amazonaws.com/text-datasets/imdb.npz

---------------------------------------------------------------------------
TimeoutError                              Traceback (most recent call last)

~\Anaconda3\lib\urllib\request.py in do_open(self, http_class, req, **http_conn_args)

   1316                 h.request(req.get_method(), req.selector, req.data, headers,

-> 1317                           encode_chunked=req.has_header('Transfer-encoding'))

   1318             except OSError as err: # timeout error

~\Anaconda3\lib\http\client.py in request(self, method, url, body, headers, encode_chunked)

   1228         """Send a complete request to the server."""

-> 1229         self._send_request(method, url, body, headers, encode_chunked)

   1230

~\Anaconda3\lib\http\client.py in _send_request(self, method, url, body, headers, encode_chunked)

   1274             body = _encode(body, 'body')

-> 1275         self.endheaders(body, encode_chunked=encode_chunked)

   1276

~\Anaconda3\lib\http\client.py in endheaders(self, message_body, encode_chunked)

   1223             raise CannotSendHeader()

-> 1224         self._send_output(message_body, encode_chunked=encode_chunked)

   1225

~\Anaconda3\lib\http\client.py in _send_output(self, message_body, encode_chunked)

   1015         del self._buffer[:]

-> 1016         self.send(msg)

   1017

~\Anaconda3\lib\http\client.py in send(self, data)

    955             if self.auto_open:

--> 956                 self.connect()

    957             else:

~\Anaconda3\lib\http\client.py in connect(self)

   1383

-> 1384             super().connect()

   1385

~\Anaconda3\lib\http\client.py in connect(self)

    927         self.sock = self._create_connection(

--> 928             (self.host,self.port), self.timeout, self.source_address)

    929         self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

~\Anaconda3\lib\socket.py in create_connection(address, timeout, source_address)

    726     if err is not None:

--> 727         raise err

    728     else:

~\Anaconda3\lib\socket.py in create_connection(address, timeout, source_address)

    715                 sock.bind(source_address)

--> 716             sock.connect(sa)

    717             # Break explicitly a reference cycle

TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly

respond after a period of time, or established connection failed because connected host has failed to

respond

During handling of the above exception, another exception occurred:

URLError                                  Traceback (most recent call last)

~\Anaconda3\lib\site-packages\keras\utils\data_utils.py in get_file(fname, origin, untar, md5_hash,

file_hash, cache_subdir, hash_algorithm, extract, archive_format, cache_dir)

    221             try:

--> 222                 urlretrieve(origin, fpath, dl_progress)

    223             except HTTPError as e:

~\Anaconda3\lib\urllib\request.py in urlretrieve(url, filename, reporthook, data)

    246

--> 247     with contextlib.closing(urlopen(url, data)) as fp:

    248         headers = fp.info()

~\Anaconda3\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)

    221         opener = _opener

--> 222     return opener.open(url, data, timeout)

    223

~\Anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout)

    524

--> 525         response = self._open(req, data)

    526

~\Anaconda3\lib\urllib\request.py in _open(self, req, data)

    542         result = self._call_chain(self.handle_open, protocol, protocol +

--> 543                                   '_open', req)

    544         if result:

~\Anaconda3\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)

    502             func = getattr(handler, meth_name)

--> 503             result = func(*args)

    504             if result is not None:

~\Anaconda3\lib\urllib\request.py in https_open(self, req)

   1359             return self.do_open(http.client.HTTPSConnection, req,

-> 1360                 context=self._context, check_hostname=self._check_hostname)

   1361

~\Anaconda3\lib\urllib\request.py in do_open(self, http_class, req, **http_conn_args)

   1318             except OSError as err: # timeout error

-> 1319                 raise URLError(err)

   1320             r = h.getresponse()

URLError: <urlopen error [WinError 10060] A connection attempt failed because the connected party did not

properly respond after a period of time, or established connection failed because connected host has

failed to respond>

During handling of the above exception, another exception occurred:

Exception                                 Traceback (most recent call last)

<ipython-input-16-82c1e9073098> in <module>

      8 epochs = 5

      9

---> 10 (x_train, y_train), (_, _) = imdb.load_data(num_words = max_features)

     11

     12 x_train = sequence.pad_sequences(x_train, maxlen = maxlen)

~\Anaconda3\lib\site-packages\keras\datasets\imdb.py in load_data(path, num_words, skip_top, maxlen,

seed, start_char, oov_char, index_from, **kwargs)

     55     path = get_file(path,

     56                     origin='https://s3.amazonaws.com/text-datasets/imdb.npz',

---> 57                     file_hash='599dadb1135973df5b59232a0e9a887c')

     58     with np.load(path) as f:

     59         x_train, labels_train = f['x_train'], f['y_train']

~\Anaconda3\lib\site-packages\keras\utils\data_utils.py in get_file(fname, origin, untar, md5_hash,

file_hash, cache_subdir, hash_algorithm, extract, archive_format, cache_dir)

    224                 raise Exception(error_msg.format(origin, e.code, e.msg))

    225             except URLError as e:

--> 226                 raise Exception(error_msg.format(origin, e.errno, e.reason))

    227         except (Exception, KeyboardInterrupt):

    228             if os.path.exists(fpath):

Exception: URL fetch failure on https://s3.amazonaws.com/text-datasets/imdb.npz: None -- [WinError 10060]

A connection attempt failed because the connected party did not properly respond after a period of time,

or established connection failed because connected host has failed to respond


问:
Application could not be Installed on this phone
I have my own Android Application, I named it "SMS App" and I want to install it at my Android Phone, but every time I install this application in phone there is a message that pop up:

Application not Installed. SMS App could not be Installed on this
  phone.

Anyone who encountered this and solved this kind of problems?

答:
Things to check:

Minumum SDK version

If it is an unsigned version, it WILL NOT overwrite a signed version installed currently on your phone.  Uninstall current version, or sign your test .apk and try again.

Check under Settings > applications > install from unknown sources.  Must be checked to install things not from market


问:
filter array based on IDs available in another array
I have two arrays. The first array has only id objects:

```<code>arr1 = [
  { id: 1 },
  { id: 2 }
];
</code>```

and another array has list:

```<code>arr2 = [
  { id: 1, name: "kedar" },
  { id: 2, name: "murli" },
  { id: 3, name: "krishnadas" }
];
</code>```

I need to write arr2 filter function which result as, based on ID available in first array

```<code>arr2 = [
  { id: 1, name: "kedar" },
  { id: 2, name: "murli" }
];
</code>```

答:
```<code>arr2.filter(el2 => arr1.some(el1 => el1.id === el2.id))
</code>```

Body:
I have two arrays. The first array has only id objects:

arr1 = [
  { id: 1 },
  { id: 2 }
];

and another array has list:

arr2 = [
  { id: 1, name: "kedar" },
  { id: 2, name: "murli" },
  { id: 3, name: "krishnadas" }
];

I need to write arr2 filter function which result as, based on ID available in first array

arr2 = [
  { id: 1, name: "kedar" },
  { id: 2, name: "murli" }
];


问:
How to invoke a function of a js file to a typescript component in angular
I have placed the js file in assets folder and imported it in index.html.

I need to use the functions of js file in angular component

via.js

```<code>var _via_reg_canvas = document.getElementById('region_canvas');
function _via_init() {
       show_message(VIA_NAME + ' (' + VIA_SHORT_NAME + ') version ' + VIA_VERSION +
        '. Ready !', 2 * VIA_THEME_MESSAGE_TIMEOUT_MS);

    if (_via_is_debug_mode) {
        document.getElementById('ui_top_panel').innerHTML += '<span>DEBUG MODE</span>';
    }

    document.getElementById('img_fn_list').style.display = 'block';
    document.getElementById('leftsidebar').style.display = 'table-cell';

    project_init_default_project();

  _via_init_reg_canvas_context();
  _via_init_keyboard_handlers();
  _via_init_mouse_handlers();
  image_grid_init();

  show_single_image_view();
  init_leftsidebar_accordion();
  attribute_update_panel_set_active_button();
  annotation_editor_set_active_button();
  init_message_panel();
}
</code>```

view.ts

```<code>inside this ts , I want to use _via_init() function which is from via.js
</code>```

答:
You need to export the function from your js file.

```<code>export function _via_init() {
       ...
}
</code>```

Now in your view.ts you simply import it like:

```<code>import * as via from 'path/to/assets/via.js'
</code>```

And use it like:

```<code>via._via_init();
</code>```

Body:
I have placed the js file in assets folder and imported it in index.html.

I need to use the functions of js file in angular component

via.js

var _via_reg_canvas = document.getElementById('region_canvas');
function _via_init() {
       show_message(VIA_NAME + ' (' + VIA_SHORT_NAME + ') version ' + VIA_VERSION +
        '. Ready !', 2 * VIA_THEME_MESSAGE_TIMEOUT_MS);

    if (_via_is_debug_mode) {
        document.getElementById('ui_top_panel').innerHTML += 'DEBUG MODE';
    }

    document.getElementById('img_fn_list').style.display = 'block';
    document.getElementById('leftsidebar').style.display = 'table-cell';

    project_init_default_project();

  _via_init_reg_canvas_context();
  _via_init_keyboard_handlers();
  _via_init_mouse_handlers();
  image_grid_init();

  show_single_image_view();
  init_leftsidebar_accordion();
  attribute_update_panel_set_active_button();
  annotation_editor_set_active_button();
  init_message_panel();
}

view.ts

inside this ts , I want to use _via_init() function which is from via.js

Body:
You need to export the function from your js file.

export function _via_init() {
       ...
}

Now in your view.ts you simply import it like:

import * as via from 'path/to/assets/via.js'

And use it like:

via._via_init();


问:
ClientSecret in appsettings.json with IdentityServer4
I'm trying to get IdentityServer4 working with appsettings.json specifying a client secret for hybrid grant type.

The end of this article says that I need to sha256 hash and then base64 encode the secret if I want to put it in appsettings.json. So take the secret "secret" and put it through https://emn178.github.io/online-tools/sha256.html gets "2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b" which base64 encoded is "MmJiODBkNTM3YjFkYTNlMzhiZDMwMzYxYWE4NTU2ODZiZGUwZWFjZDcxNjJmZWY2YTI1ZmU5N2JmNTI3YTI1Yg==". That makes my appsettings.json for the mvc client look like this

```<code>{
    ...
    "ClientSecrets": [ {
        "Value": "MkJCODBENTM3QjFEQTNFMzhCRDMwMzYxQUE4NTU2ODZCREUwRUFDRDcxNjJGRUY2QTI1RkU5N0JGNTI3QTI1Qg=="
    } ],
    ...
}
</code>```

On the MVC client, the config looks like this

```<code>.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    options.Authority = Configuration["OpenIdConnectAuthority"];

    options.ClientId = "xxx-mvc";
    options.ClientSecret = "secret";

    options.RemoteAuthenticationTimeout = TimeSpan.FromHours(2);
    options.ResponseType = "code id_token";
    options.RequireHttpsMetadata = !Environment.IsDevelopment();
    options.Scope.Clear();
    options.Scope.Add("openid profile");

    options.CallbackPath = new PathString("/signin-callback-oidc");
    options.SignedOutCallbackPath = new PathString("/signout-callback-oidc");
    options.SignedOutRedirectUri = new PathString("/");
    options.ClaimsIssuer = OpenIdConnectDefaults.AuthenticationScheme;

    options.TokenValidationParameters = new TokenValidationParameters
    {
        NameClaimType = JwtClaimTypes.Name
    };
})
</code>```

Despite this seemingly being correct, the identity server logs have

```<code>fail: IdentityServer4.Validation.ClientSecretValidator[0]
      Client secret validation failed for client: xxx-mvc.
</code>```

If I remove a portion of the base64 secret, identity server logs

Secret: no description uses invalid hashing algorithm.

So I know that the appsettings.json client secret is being picked up. If I comment out options.ClientSecret = "secret"; on the mvc side, identity server logs Hashed shared secret validator cannot process NoSecret so I know that config is being picked up.

How do I specify the correct two strings to get the secret "secret" to work in this situation?

Full logs from identity server are:

```<code>dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Request path /.well-known/openid-configuration matched to endpoint type Discovery
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Endpoint enabled: Discovery, successfully created handler: IdentityServer4.Endpoints.DiscoveryEndpoint
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: IdentityServer4.Endpoints.DiscoveryEndpoint for /.well-known/openid-configuration
trce: IdentityServer4.Endpoints.DiscoveryEndpoint[0]
      Processing discovery request.
dbug: IdentityServer4.Endpoints.DiscoveryEndpoint[0]
      Start discovery request
trce: IdentityServer4.Endpoints.DiscoveryEndpoint[0]
      Calling into discovery response generator: IdentityServer4.ResponseHandling.DiscoveryResponseGenerator
trce: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking result: IdentityServer4.Endpoints.Results.DiscoveryDocumentResult
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Request path /.well-known/openid-configuration/jwks matched to endpoint type Discovery
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Endpoint enabled: Discovery, successfully created handler: IdentityServer4.Endpoints.DiscoveryKeyEndpoint
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: IdentityServer4.Endpoints.DiscoveryKeyEndpoint for /.well-known/openid-configuration/jwks
trce: IdentityServer4.Endpoints.DiscoveryKeyEndpoint[0]
      Processing discovery request.
dbug: IdentityServer4.Endpoints.DiscoveryKeyEndpoint[0]
      Start key discovery request
trce: IdentityServer4.Endpoints.DiscoveryKeyEndpoint[0]
      Calling into discovery response generator: IdentityServer4.ResponseHandling.DiscoveryResponseGenerator
trce: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking result: IdentityServer4.Endpoints.Results.JsonWebKeysResult
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Request path /connect/authorize matched to endpoint type Authorize
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Endpoint enabled: Authorize, successfully created handler: IdentityServer4.Endpoints.AuthorizeEndpoint
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: IdentityServer4.Endpoints.AuthorizeEndpoint for /connect/authorize
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      Start authorize request
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      User in authorize request: 3a28f734-5d49-49e0-a28c-c851adfb4bf6
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Start authorize request protocol validation
trce: IdentityServer4.Stores.ValidatingClientStore[0]
      Calling into client configuration validator: IdentityServer4.Validation.DefaultClientConfigurationValidator
dbug: IdentityServer4.Stores.ValidatingClientStore[0]
      client configuration validation for client xxx-mvc succeeded.
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Checking for PKCE parameters
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      No PKCE used.
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Calling into custom validator: IdentityServer4.Validation.DefaultCustomAuthorizeRequestValidator
trce: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Authorize request protocol validation successful
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      ValidatedAuthorizeRequest
      {
        "ClientId": "xxx-mvc",
        "ClientName": "xxx MVC Client",
        "RedirectUri": "http://localhost:4500/signin-callback-oidc",
        "AllowedRedirectUris": [
          "http://localhost:4500/signin-callback-oidc"
        ],
        "SubjectId": "3a28f734-5d49-49e0-a28c-c851adfb4bf6",
        "ResponseType": "code id_token",
        "ResponseMode": "form_post",
        "GrantType": "hybrid",
        "RequestedScopes": "openid profile",
        "State": "CfDJ8BvOOrOwFENEmcvniNGXxvPnb1gKLB_qQdpSkS5FI88I3vvopAgk9v23GYrBOce_S5PeDsBUzYEj28zpC__y1Q8ZcU2LE9vf7x9pBvmqltXBBdp4zRbhV52iiTEtfpj-MyvDrMTUWR1jCx_b4CmdObvZdVdqf3KvUKO6dCJvPVP5G0OBG6jkuWUvsQnm8uUTE28XBrhwMIn_3D1ns2BgShqtV6j9G7HzatthP-yg9tDV198xILScflYHAgNPWGiJUZcZoar1_FSi9ynxlJSonnkuAw6epwPYk1lvIKZrK5ofTHizmOBUHI_b-xyVXIzoQw",
        "Nonce": "637027688717360370.ODBiYTgwZGMtNjRhYy00NmE4LWI3MDAtYWY4MTcxMmNkMmNjYmYwYjY1ZDUtMTUyYy00YjFlLWE2ZmMtNTdkM2YzMDY3NTAy",
        "SessionId": "3b0abfecf91a43a58e3f24ccb6ff1351",
        "Raw": {
          "client_id": "xxx-mvc",
          "redirect_uri": "http://localhost:4500/signin-callback-oidc",
          "response_type": "code id_token",
          "scope": "openid profile",
          "response_mode": "form_post",
          "nonce": "637027688717360370.ODBiYTgwZGMtNjRhYy00NmE4LWI3MDAtYWY4MTcxMmNkMmNjYmYwYjY1ZDUtMTUyYy00YjFlLWE2ZmMtNTdkM2YzMDY3NTAy",
          "state": "CfDJ8BvOOrOwFENEmcvniNGXxvPnb1gKLB_qQdpSkS5FI88I3vvopAgk9v23GYrBOce_S5PeDsBUzYEj28zpC__y1Q8ZcU2LE9vf7x9pBvmqltXBBdp4zRbhV52iiTEtfpj-MyvDrMTUWR1jCx_b4CmdObvZdVdqf3KvUKO6dCJvPVP5G0OBG6jkuWUvsQnm8uUTE28XBrhwMIn_3D1ns2BgShqtV6j9G7HzatthP-yg9tDV198xILScflYHAgNPWGiJUZcZoar1_FSi9ynxlJSonnkuAw6epwPYk1lvIKZrK5ofTHizmOBUHI_b-xyVXIzoQw",
          "x-client-SKU": "ID_NETSTANDARD2_0",
          "x-client-ver": "5.3.0.0"
        }
      }
trce: IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator[0]
      ProcessInteractionAsync
dbug: IdentityServer4.Services.DefaultConsentService[0]
      Client is configured to not require consent, no consent is required
dbug: IdentityServer4.ResponseHandling.AuthorizeResponseGenerator[0]
      Creating Hybrid Flow response.
dbug: IdentityServer4.EntityFramework.Stores.PersistedGrantStore[0]
      GpVcH5oK1O8xEaWazwBmHumW8moTQsBnVATxPiUxIfs= not found in database
dbug: IdentityServer4.ResponseHandling.AuthorizeResponseGenerator[0]
      Creating Implicit Flow response.
trce: IdentityServer4.Services.DefaultTokenService[0]
      Creating identity token
dbug: IdentityServer4.Services.DefaultClaimsService[0]
      Getting claims for identity token for subject: 3a28f734-5d49-49e0-a28c-c851adfb4bf6 and client: xxx-mvc
dbug: IdentityServer4.Services.DefaultClaimsService[0]
      In addition to an id_token, an access_token was requested. No claims other than sub are included in the id_token. To obtain more user claims, either use the user info endpoint or set AlwaysIncludeUserClaimsInIdToken on the client configuration.
trce: IdentityServer4.Services.DefaultTokenService[0]
      Creating JWT identity token
trce: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      Identity token issued for xxx-mvc (xxx MVC Client) / 3a28f734-5d49-49e0-a28c-c851adfb4bf6: eyJhbGciOiJSUzI1NiIsImtpZCI6Ijc3ODc1NWJmMmZkMWRiZWVmNjZkZDdmZjY2YmM5NjBlIiwidHlwIjoiSldUIn0.eyJuYmYiOjE1NjcxNzIwNzEsImV4cCI6MTU2NzE3MjM3MSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo0NDAwIiwiYXVkIjoibW9uZXRlZXItbXZjIiwibm9uY2UiOiI2MzcwMjc2ODg3MTczNjAzNzAuT0RCaVlUZ3daR010TmpSaFl5MDBObUU0TFdJM01EQXRZV1k0TVRjeE1tTmtNbU5qWW1Zd1lqWTFaRFV0TVRVeVl5MDBZakZsTFdFMlptTXROVGRrTTJZek1EWTNOVEF5IiwiaWF0IjoxNTY3MTcyMDcxLCJjX2hhc2giOiJNR3A5SzlLSm5KRTFaZW83YndoNG5BIiwic2lkIjoiM2IwYWJmZWNmOTFhNDNhNThlM2YyNGNjYjZmZjEzNTEiLCJzdWIiOiIzYTI4ZjczNC01ZDQ5LTQ5ZTAtYTI4Yy1jODUxYWRmYjRiZjYiLCJhdXRoX3RpbWUiOjE1NjcxNjk2NTAsImlkcCI6ImxvY2FsIiwiYW1yIjpbInB3ZCJdfQ.p9LKUCqmK8fjlznJtU5NGgtKE2fsSnxx8EW2ngu2pw-eSJXsuvI7t6FkxlHw6joVG178JXGfMY4BXt83binl9li3NLjzjJC7k8_07QUL_fknYB05rwhfAH995mxqXTV1A5n8ppjXzXcixAkVaA1Cxgb7mvqqfVHqRY2ra-MeIa7Esew5CiTeerlMT87wdWbIMmbK84TGSM26jLN1Uav6YYB-8Lonu2hcS3s4LXLS42bvy04Uc-UUOXcxK0LDgQu-stWfFjr9tYeoIefsgZIOJaEDtgwulExhNWTrPlFF5k9qYyYv4keKM_1dckP47-B4TR5m_1PEzGNeSJb48RwrXQ
trce: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      Code issued for xxx-mvc (xxx MVC Client) / 3a28f734-5d49-49e0-a28c-c851adfb4bf6: 05331f140cb9626a391f6033d1ab6396711b614cdab5f224024336aa94f996f4
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      Authorize endpoint response
      {
        "SubjectId": "3a28f734-5d49-49e0-a28c-c851adfb4bf6",
        "ClientId": "xxx-mvc",
        "RedirectUri": "http://localhost:4500/signin-callback-oidc",
        "State": "CfDJ8BvOOrOwFENEmcvniNGXxvPnb1gKLB_qQdpSkS5FI88I3vvopAgk9v23GYrBOce_S5PeDsBUzYEj28zpC__y1Q8ZcU2LE9vf7x9pBvmqltXBBdp4zRbhV52iiTEtfpj-MyvDrMTUWR1jCx_b4CmdObvZdVdqf3KvUKO6dCJvPVP5G0OBG6jkuWUvsQnm8uUTE28XBrhwMIn_3D1ns2BgShqtV6j9G7HzatthP-yg9tDV198xILScflYHAgNPWGiJUZcZoar1_FSi9ynxlJSonnkuAw6epwPYk1lvIKZrK5ofTHizmOBUHI_b-xyVXIzoQw",
        "Scope": "openid profile"
      }
trce: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      End authorize request. result type: IdentityServer4.Endpoints.Results.AuthorizeResult
trce: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking result: IdentityServer4.Endpoints.Results.AuthorizeResult
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Request path /connect/token matched to endpoint type Token
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Endpoint enabled: Token, successfully created handler: IdentityServer4.Endpoints.TokenEndpoint
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: IdentityServer4.Endpoints.TokenEndpoint for /connect/token
trce: IdentityServer4.Endpoints.TokenEndpoint[0]
      Processing token request.
dbug: IdentityServer4.Endpoints.TokenEndpoint[0]
      Start token request.
dbug: IdentityServer4.Validation.ClientSecretValidator[0]
      Start client validation
dbug: IdentityServer4.Validation.BasicAuthenticationSecretParser[0]
      Start parsing Basic Authentication secret
dbug: IdentityServer4.Validation.PostBodySecretParser[0]
      Start parsing for secret in post body
dbug: IdentityServer4.Validation.SecretParser[0]
      Parser found secret: PostBodySecretParser
dbug: IdentityServer4.Validation.SecretParser[0]
      Secret id found: xxx-mvc
trce: IdentityServer4.Stores.ValidatingClientStore[0]
      Calling into client configuration validator: IdentityServer4.Validation.DefaultClientConfigurationValidator
dbug: IdentityServer4.Stores.ValidatingClientStore[0]
      client configuration validation for client xxx-mvc succeeded.
dbug: IdentityServer4.Validation.HashedSharedSecretValidator[0]
      No matching hashed secret found.
dbug: IdentityServer4.Validation.SecretValidator[0]
      Secret validators could not validate secret
fail: IdentityServer4.Validation.ClientSecretValidator[0]
      Client secret validation failed for client: xxx-mvc.
trce: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking result: IdentityServer4.Endpoints.Results.TokenErrorResult
</code>```

答:
Use this website to get base64 encoded sha256 of your secret https://hash.online-convert.com/sha256-generator

It produces the following results for "secret"

```<code>hex: 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b
HEX: 2BB80D537B1DA3E38BD30361AA855686BDE0EACD7162FEF6A25FE97BF527A25B
h:e:x: 2b:b8:0d:53:7b:1d:a3:e3:8b:d3:03:61:aa:85:56:86:bd:e0:ea:cd:71:62:fe:f6:a2:5f:e9:7b:f5:27:a2:5b
base64: K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=
</code>```

Take the base64 result and put it into appsettings.config

```<code>"Clients": [
  {
    ...
    "ClientId": "clientId",
    "ClientSecrets": [ { "Value": "K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=" } ],
    ...
  },
</code>```

And then in your C#

```<code>{
      ...
      ClientId = "clientId",
      ClientSecret = "secret",
      ...
 }
</code>```

Works for me

Body:
I'm trying to get IdentityServer4 working with appsettings.json specifying a client secret for hybrid grant type.

The end of this article says that I need to sha256 hash and then base64 encode the secret if I want to put it in appsettings.json. So take the secret "secret" and put it through https://emn178.github.io/online-tools/sha256.html gets "2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b" which base64 encoded is "MmJiODBkNTM3YjFkYTNlMzhiZDMwMzYxYWE4NTU2ODZiZGUwZWFjZDcxNjJmZWY2YTI1ZmU5N2JmNTI3YTI1Yg==". That makes my appsettings.json for the mvc client look like this

{
    ...
    "ClientSecrets": [ {
        "Value": "MkJCODBENTM3QjFEQTNFMzhCRDMwMzYxQUE4NTU2ODZCREUwRUFDRDcxNjJGRUY2QTI1RkU5N0JGNTI3QTI1Qg=="
    } ],
    ...
}

On the MVC client, the config looks like this

.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    options.Authority = Configuration["OpenIdConnectAuthority"];

    options.ClientId = "xxx-mvc";
    options.ClientSecret = "secret";

    options.RemoteAuthenticationTimeout = TimeSpan.FromHours(2);
    options.ResponseType = "code id_token";
    options.RequireHttpsMetadata = !Environment.IsDevelopment();
    options.Scope.Clear();
    options.Scope.Add("openid profile");

    options.CallbackPath = new PathString("/signin-callback-oidc");
    options.SignedOutCallbackPath = new PathString("/signout-callback-oidc");
    options.SignedOutRedirectUri = new PathString("/");
    options.ClaimsIssuer = OpenIdConnectDefaults.AuthenticationScheme;

    options.TokenValidationParameters = new TokenValidationParameters
    {
        NameClaimType = JwtClaimTypes.Name
    };
})

Despite this seemingly being correct, the identity server logs have

fail: IdentityServer4.Validation.ClientSecretValidator[0]
      Client secret validation failed for client: xxx-mvc.

If I remove a portion of the base64 secret, identity server logs

Secret: no description uses invalid hashing algorithm.

So I know that the appsettings.json client secret is being picked up. If I comment out options.ClientSecret = "secret"; on the mvc side, identity server logs Hashed shared secret validator cannot process NoSecret so I know that config is being picked up.

How do I specify the correct two strings to get the secret "secret" to work in this situation?

Full logs from identity server are:

dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Request path /.well-known/openid-configuration matched to endpoint type Discovery
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Endpoint enabled: Discovery, successfully created handler: IdentityServer4.Endpoints.DiscoveryEndpoint
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: IdentityServer4.Endpoints.DiscoveryEndpoint for /.well-known/openid-configuration
trce: IdentityServer4.Endpoints.DiscoveryEndpoint[0]
      Processing discovery request.
dbug: IdentityServer4.Endpoints.DiscoveryEndpoint[0]
      Start discovery request
trce: IdentityServer4.Endpoints.DiscoveryEndpoint[0]
      Calling into discovery response generator: IdentityServer4.ResponseHandling.DiscoveryResponseGenerator
trce: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking result: IdentityServer4.Endpoints.Results.DiscoveryDocumentResult
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Request path /.well-known/openid-configuration/jwks matched to endpoint type Discovery
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Endpoint enabled: Discovery, successfully created handler: IdentityServer4.Endpoints.DiscoveryKeyEndpoint
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: IdentityServer4.Endpoints.DiscoveryKeyEndpoint for /.well-known/openid-configuration/jwks
trce: IdentityServer4.Endpoints.DiscoveryKeyEndpoint[0]
      Processing discovery request.
dbug: IdentityServer4.Endpoints.DiscoveryKeyEndpoint[0]
      Start key discovery request
trce: IdentityServer4.Endpoints.DiscoveryKeyEndpoint[0]
      Calling into discovery response generator: IdentityServer4.ResponseHandling.DiscoveryResponseGenerator
trce: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking result: IdentityServer4.Endpoints.Results.JsonWebKeysResult
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Request path /connect/authorize matched to endpoint type Authorize
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Endpoint enabled: Authorize, successfully created handler: IdentityServer4.Endpoints.AuthorizeEndpoint
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: IdentityServer4.Endpoints.AuthorizeEndpoint for /connect/authorize
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      Start authorize request
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      User in authorize request: 3a28f734-5d49-49e0-a28c-c851adfb4bf6
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Start authorize request protocol validation
trce: IdentityServer4.Stores.ValidatingClientStore[0]
      Calling into client configuration validator: IdentityServer4.Validation.DefaultClientConfigurationValidator
dbug: IdentityServer4.Stores.ValidatingClientStore[0]
      client configuration validation for client xxx-mvc succeeded.
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Checking for PKCE parameters
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      No PKCE used.
dbug: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Calling into custom validator: IdentityServer4.Validation.DefaultCustomAuthorizeRequestValidator
trce: IdentityServer4.Validation.AuthorizeRequestValidator[0]
      Authorize request protocol validation successful
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      ValidatedAuthorizeRequest
      {
        "ClientId": "xxx-mvc",
        "ClientName": "xxx MVC Client",
        "RedirectUri": "http://localhost:4500/signin-callback-oidc",
        "AllowedRedirectUris": [
          "http://localhost:4500/signin-callback-oidc"
        ],
        "SubjectId": "3a28f734-5d49-49e0-a28c-c851adfb4bf6",
        "ResponseType": "code id_token",
        "ResponseMode": "form_post",
        "GrantType": "hybrid",
        "RequestedScopes": "openid profile",
        "State": "CfDJ8BvOOrOwFENEmcvniNGXxvPnb1gKLB_qQdpSkS5FI88I3vvopAgk9v23GYrBOce_S5PeDsBUzYEj28zpC__y1Q8ZcU2LE9vf7x9pBvmqltXBBdp4zRbhV52iiTEtfpj-MyvDrMTUWR1jCx_b4CmdObvZdVdqf3KvUKO6dCJvPVP5G0OBG6jkuWUvsQnm8uUTE28XBrhwMIn_3D1ns2BgShqtV6j9G7HzatthP-yg9tDV198xILScflYHAgNPWGiJUZcZoar1_FSi9ynxlJSonnkuAw6epwPYk1lvIKZrK5ofTHizmOBUHI_b-xyVXIzoQw",
        "Nonce": "637027688717360370.ODBiYTgwZGMtNjRhYy00NmE4LWI3MDAtYWY4MTcxMmNkMmNjYmYwYjY1ZDUtMTUyYy00YjFlLWE2ZmMtNTdkM2YzMDY3NTAy",
        "SessionId": "3b0abfecf91a43a58e3f24ccb6ff1351",
        "Raw": {
          "client_id": "xxx-mvc",
          "redirect_uri": "http://localhost:4500/signin-callback-oidc",
          "response_type": "code id_token",
          "scope": "openid profile",
          "response_mode": "form_post",
          "nonce": "637027688717360370.ODBiYTgwZGMtNjRhYy00NmE4LWI3MDAtYWY4MTcxMmNkMmNjYmYwYjY1ZDUtMTUyYy00YjFlLWE2ZmMtNTdkM2YzMDY3NTAy",
          "state": "CfDJ8BvOOrOwFENEmcvniNGXxvPnb1gKLB_qQdpSkS5FI88I3vvopAgk9v23GYrBOce_S5PeDsBUzYEj28zpC__y1Q8ZcU2LE9vf7x9pBvmqltXBBdp4zRbhV52iiTEtfpj-MyvDrMTUWR1jCx_b4CmdObvZdVdqf3KvUKO6dCJvPVP5G0OBG6jkuWUvsQnm8uUTE28XBrhwMIn_3D1ns2BgShqtV6j9G7HzatthP-yg9tDV198xILScflYHAgNPWGiJUZcZoar1_FSi9ynxlJSonnkuAw6epwPYk1lvIKZrK5ofTHizmOBUHI_b-xyVXIzoQw",
          "x-client-SKU": "ID_NETSTANDARD2_0",
          "x-client-ver": "5.3.0.0"
        }
      }
trce: IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator[0]
      ProcessInteractionAsync
dbug: IdentityServer4.Services.DefaultConsentService[0]
      Client is configured to not require consent, no consent is required
dbug: IdentityServer4.ResponseHandling.AuthorizeResponseGenerator[0]
      Creating Hybrid Flow response.
dbug: IdentityServer4.EntityFramework.Stores.PersistedGrantStore[0]
      GpVcH5oK1O8xEaWazwBmHumW8moTQsBnVATxPiUxIfs= not found in database
dbug: IdentityServer4.ResponseHandling.AuthorizeResponseGenerator[0]
      Creating Implicit Flow response.
trce: IdentityServer4.Services.DefaultTokenService[0]
      Creating identity token
dbug: IdentityServer4.Services.DefaultClaimsService[0]
      Getting claims for identity token for subject: 3a28f734-5d49-49e0-a28c-c851adfb4bf6 and client: xxx-mvc
dbug: IdentityServer4.Services.DefaultClaimsService[0]
      In addition to an id_token, an access_token was requested. No claims other than sub are included in the id_token. To obtain more user claims, either use the user info endpoint or set AlwaysIncludeUserClaimsInIdToken on the client configuration.
trce: IdentityServer4.Services.DefaultTokenService[0]
      Creating JWT identity token
trce: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      Identity token issued for xxx-mvc (xxx MVC Client) / 3a28f734-5d49-49e0-a28c-c851adfb4bf6: eyJhbGciOiJSUzI1NiIsImtpZCI6Ijc3ODc1NWJmMmZkMWRiZWVmNjZkZDdmZjY2YmM5NjBlIiwidHlwIjoiSldUIn0.eyJuYmYiOjE1NjcxNzIwNzEsImV4cCI6MTU2NzE3MjM3MSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo0NDAwIiwiYXVkIjoibW9uZXRlZXItbXZjIiwibm9uY2UiOiI2MzcwMjc2ODg3MTczNjAzNzAuT0RCaVlUZ3daR010TmpSaFl5MDBObUU0TFdJM01EQXRZV1k0TVRjeE1tTmtNbU5qWW1Zd1lqWTFaRFV0TVRVeVl5MDBZakZsTFdFMlptTXROVGRrTTJZek1EWTNOVEF5IiwiaWF0IjoxNTY3MTcyMDcxLCJjX2hhc2giOiJNR3A5SzlLSm5KRTFaZW83YndoNG5BIiwic2lkIjoiM2IwYWJmZWNmOTFhNDNhNThlM2YyNGNjYjZmZjEzNTEiLCJzdWIiOiIzYTI4ZjczNC01ZDQ5LTQ5ZTAtYTI4Yy1jODUxYWRmYjRiZjYiLCJhdXRoX3RpbWUiOjE1NjcxNjk2NTAsImlkcCI6ImxvY2FsIiwiYW1yIjpbInB3ZCJdfQ.p9LKUCqmK8fjlznJtU5NGgtKE2fsSnxx8EW2ngu2pw-eSJXsuvI7t6FkxlHw6joVG178JXGfMY4BXt83binl9li3NLjzjJC7k8_07QUL_fknYB05rwhfAH995mxqXTV1A5n8ppjXzXcixAkVaA1Cxgb7mvqqfVHqRY2ra-MeIa7Esew5CiTeerlMT87wdWbIMmbK84TGSM26jLN1Uav6YYB-8Lonu2hcS3s4LXLS42bvy04Uc-UUOXcxK0LDgQu-stWfFjr9tYeoIefsgZIOJaEDtgwulExhNWTrPlFF5k9qYyYv4keKM_1dckP47-B4TR5m_1PEzGNeSJb48RwrXQ
trce: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      Code issued for xxx-mvc (xxx MVC Client) / 3a28f734-5d49-49e0-a28c-c851adfb4bf6: 05331f140cb9626a391f6033d1ab6396711b614cdab5f224024336aa94f996f4
dbug: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      Authorize endpoint response
      {
        "SubjectId": "3a28f734-5d49-49e0-a28c-c851adfb4bf6",
        "ClientId": "xxx-mvc",
        "RedirectUri": "http://localhost:4500/signin-callback-oidc",
        "State": "CfDJ8BvOOrOwFENEmcvniNGXxvPnb1gKLB_qQdpSkS5FI88I3vvopAgk9v23GYrBOce_S5PeDsBUzYEj28zpC__y1Q8ZcU2LE9vf7x9pBvmqltXBBdp4zRbhV52iiTEtfpj-MyvDrMTUWR1jCx_b4CmdObvZdVdqf3KvUKO6dCJvPVP5G0OBG6jkuWUvsQnm8uUTE28XBrhwMIn_3D1ns2BgShqtV6j9G7HzatthP-yg9tDV198xILScflYHAgNPWGiJUZcZoar1_FSi9ynxlJSonnkuAw6epwPYk1lvIKZrK5ofTHizmOBUHI_b-xyVXIzoQw",
        "Scope": "openid profile"
      }
trce: IdentityServer4.Endpoints.AuthorizeEndpoint[0]
      End authorize request. result type: IdentityServer4.Endpoints.Results.AuthorizeResult
trce: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking result: IdentityServer4.Endpoints.Results.AuthorizeResult
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Request path /connect/token matched to endpoint type Token
dbug: IdentityServer4.Hosting.EndpointRouter[0]
      Endpoint enabled: Token, successfully created handler: IdentityServer4.Endpoints.TokenEndpoint
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: IdentityServer4.Endpoints.TokenEndpoint for /connect/token
trce: IdentityServer4.Endpoints.TokenEndpoint[0]
      Processing token request.
dbug: IdentityServer4.Endpoints.TokenEndpoint[0]
      Start token request.
dbug: IdentityServer4.Validation.ClientSecretValidator[0]
      Start client validation
dbug: IdentityServer4.Validation.BasicAuthenticationSecretParser[0]
      Start parsing Basic Authentication secret
dbug: IdentityServer4.Validation.PostBodySecretParser[0]
      Start parsing for secret in post body
dbug: IdentityServer4.Validation.SecretParser[0]
      Parser found secret: PostBodySecretParser
dbug: IdentityServer4.Validation.SecretParser[0]
      Secret id found: xxx-mvc
trce: IdentityServer4.Stores.ValidatingClientStore[0]
      Calling into client configuration validator: IdentityServer4.Validation.DefaultClientConfigurationValidator
dbug: IdentityServer4.Stores.ValidatingClientStore[0]
      client configuration validation for client xxx-mvc succeeded.
dbug: IdentityServer4.Validation.HashedSharedSecretValidator[0]
      No matching hashed secret found.
dbug: IdentityServer4.Validation.SecretValidator[0]
      Secret validators could not validate secret
fail: IdentityServer4.Validation.ClientSecretValidator[0]
      Client secret validation failed for client: xxx-mvc.
trce: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking result: IdentityServer4.Endpoints.Results.TokenErrorResult

Body:
Use this website to get base64 encoded sha256 of your secret https://hash.online-convert.com/sha256-generator

It produces the following results for "secret"

hex: 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b
HEX: 2BB80D537B1DA3E38BD30361AA855686BDE0EACD7162FEF6A25FE97BF527A25B
h:e:x: 2b:b8:0d:53:7b:1d:a3:e3:8b:d3:03:61:aa:85:56:86:bd:e0:ea:cd:71:62:fe:f6:a2:5f:e9:7b:f5:27:a2:5b
base64: K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=

Take the base64 result and put it into appsettings.config

"Clients": [
  {
    ...
    "ClientId": "clientId",
    "ClientSecrets": [ { "Value": "K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=" } ],
    ...
  },

And then in your C#

{
      ...
      ClientId = "clientId",
      ClientSecret = "secret",
      ...
 }

Works for me