问:
Integrating HealthCheck endpoint into swagger (open API) UI on dotnet core
I am using Dotnet Core healthchecks as described here. In short, it looks like this:

First, you configure services like this:

services.AddHealthChecks()
    .AddSqlServer("connectionString", name: "SQlServerHealthCheck")
    ... // Add multiple other checks
```
<p>Then, you register an endpoint like this:</p>
<pre class="lang-cs prettyprint-override"><code>app.UseHealthChecks("/my/healthCheck/endpoint");
</code>```

We are also using Swagger (aka Open API) and we see all the endpoints via Swagger UI, but not the health check endpoint.

Is there a way to add this to a controller method so that Swagger picks up the endpoint automatically, or maybe integrate it with swagger in another way?

The best solution I found so far is to add a custom hardcoded endpoint (like described here), but it is not nice to maintain.

答:
Since Swagger has been updated, there's a breaking change between .NET 2.x and 3.1/Swagger 4.0.0 and 5.0.0

Below is a version of the poor man's solution (see eddyP23 answer) that works with 5.0.0.

    public class HealthChecksFilter : IDocumentFilter
    {
        public const string HealthCheckEndpoint = @"/healthcheck";

        public void Apply(OpenApiDocument openApiDocument, DocumentFilterContext context)
        {
            var pathItem = new OpenApiPathItem();

            var operation = new OpenApiOperation();
            operation.Tags.Add(new OpenApiTag { Name = "ApiHealth" });

            var properties = new Dictionary<string, OpenApiSchema>();
            properties.Add("status", new OpenApiSchema() { Type = "string" });
            properties.Add("errors", new OpenApiSchema() { Type = "array" });

            var response = new OpenApiResponse();
            response.Content.Add("application/json", new OpenApiMediaType
            {
                Schema = new OpenApiSchema
                {
                    Type = "object",
                    AdditionalPropertiesAllowed = true,
                    Properties = properties,
                }
            });

            operation.Responses.Add("200", response);
            pathItem.AddOperation(OperationType.Get, operation);
            openApiDocument?.Paths.Add(HealthCheckEndpoint, pathItem);
        }
    }
```

Body:
I am using Dotnet Core healthchecks as described here. In short, it looks like this:

First, you configure services like this:

services.AddHealthChecks()
    .AddSqlServer("connectionString", name: "SQlServerHealthCheck")
    ... // Add multiple other checks

Then, you register an endpoint like this:

app.UseHealthChecks("/my/healthCheck/endpoint");

We are also using Swagger (aka Open API) and we see all the endpoints via Swagger UI, but not the health check endpoint.

Is there a way to add this to a controller method so that Swagger picks up the endpoint automatically, or maybe integrate it with swagger in another way?

The best solution I found so far is to add a custom hardcoded endpoint (like described here), but it is not nice to maintain.


来源: stackexchange

问:
PHP proc_open opens multiple times
I have a utility function used for executing a program through CLI (cmd, bash etc). It returns an array of 3 items: STDOUT, STDERR and EXIT CODE.

So far, it's been working nicely without issues. In fact, the problem I have with it doesn't really hinder it's functionality, but I'm concerned about performance.

The problem is that in certain cases, PHP runs the same command multiple times (3 times in my case), even if it was supposed to only do this once.

```<code>/**
 * Executes a program and waits for it to finish, taking pipes into account.
 * @param string $cmd Command line to execute, including any arguments.
 * @param string $input Data for standard input.
 * @param boolean $log Whether to log execution failures or not (defaults to true).
 * @return array Array of "stdout", "stderr" and "return".
 */
public static function execute($cmd,$stdin=null,$log=true){
    //static $once=true; if(!$once)die; $once=false;
    $proc=proc_open($cmd, array(
        0=>array('pipe','r'),
        1=>array('pipe','w'),
        2=>array('pipe','w')   ), $pipes);
    fwrite($pipes[0],$stdin);                fclose($pipes[0]);
    $stdout=stream_get_contents($pipes[1]);  fclose($pipes[1]);
    $stderr=stream_get_contents($pipes[2]);  fclose($pipes[2]);
    $return=proc_close($proc);
    if($return!=0 && $log)
        xlog('Error: Program execution returned failure.',$stdout,$stderr,$return);
    return array( 'stdout'=>$stdout, 'stderr'=>$stderr, 'return'=>$return );
}
</code>```

Note the commented line (line 9). That was for testing. I enabled it to ensure the target program only runs once (I was thinking my code may be calling the same function somehow).
But even with that line enabled, the program still ran multiple times.

As it is, I have 2 places in my code where I'm executing the same program (on different occasions). The command line is the same for both of them.

However, on one occasion, the program runs once, while in the occasion, PHP runs the program 3 times.

I've been monitoring and seeing this behavior under Process Explorer. I'm using Windows 7 x64. The program is 32 bit, as is PHP.

Edit: The program in question is custom developed, and it doesn't open new processes.

答:
It is very strange. And It is very hard to figure out without the full code. </p>

<p>If you are stressing your server calling the same page several times, my best bet it is probably related to the CPU round robin process. The PHP does not have time to set the static variable to false because at the same there are an another request to this method. Other possibility is the PHP is failing to isolate properly the static value and the different request to this method can read different memory position until the PHP sinchronize the values. </p>

ContentLicense: CC BY-SA 3.0

Title: PHP proc_open opens multiple times

Body:
I have a utility function used for executing a program through CLI (cmd, bash etc). It returns an array of 3 items: STDOUT, STDERR and EXIT CODE.

So far, it's been working nicely without issues. In fact, the problem I have with it doesn't really hinder it's functionality, but I'm concerned about performance.

The problem is that in certain cases, PHP runs the same command multiple times (3 times in my case), even if it was supposed to only do this once.

/**
 * Executes a program and waits for it to finish, taking pipes into account.
 * @param string $cmd Command line to execute, including any arguments.
 * @param string $input Data for standard input.
 * @param boolean $log Whether to log execution failures or not (defaults to true).
 * @return array Array of "stdout", "stderr" and "return".
 */
public static function execute($cmd,$stdin=null,$log=true){
    //static $once=true; if(!$once)die; $once=false;
    $proc=proc_open($cmd, array(
        0=>array('pipe','r'),
        1=>array('pipe','w'),
        2=>array('pipe','w')   ), $pipes);
    fwrite($pipes[0],$stdin);                fclose($pipes[0]);
    $stdout=stream_get_contents($pipes[1]);  fclose($pipes[1]);
    $stderr=stream_get_contents($pipes[2]);  fclose($pipes[2]);
    $return=proc_close($proc);
    if($return!=0 && $log)
        xlog('Error: Program execution returned failure.',$stdout,$stderr,$return);
    return array( 'stdout'=>$stdout, 'stderr'=>$stderr, 'return'=>$return );
}

Note the commented line (line 9). That was for testing. I enabled it to ensure the target program only runs once (I was thinking my code may be calling the same function somehow).
But even with that line enabled, the program still ran multiple times.

As it is, I have 2 places in my code where I'm executing the same program (on different occasions). The command line is the same for both of them.

However, on one occasion, the program runs once, while in the occasion, PHP runs the program 3 times.

I've been monitoring and seeing this behavior under Process Explorer. I'm using Windows 7 x64. The program is 32 bit, as is PHP.

Edit: The program in question is custom developed, and it doesn't open new processes.

Body:
It is very strange. And It is very hard to figure out without the full code.

If you are stressing your server calling the same page several times, my best bet it is probably related to the CPU round robin process. The PHP does not have time to set the static variable to false because at the same there are an another request to this method. Other possibility is the PHP is failing to isolate properly the static value and the different request to this method can read different memory position until the PHP sinchronize the values.


问:
Which element should handle data in React?
For example, there are 2 components:

```<code>class App extends React.Component {
  state = {
    comments=[1, 2, 3, 4]
  }
  render() {
    return (
      <Comments />
    )
  }
}

class Comments extends React.Component {
  render() {
    return (
        /* show comments */
    )
  }
}
</code>```

and I want to show only even comments. Should I put sorting function into App and send prepared array to Comments or send entire array and let Comments sort it by itself?

答:
You can have the sorting logic in APP.jsx file.

like this

class App extends React.Component {
  state = {
    comments=[1, 2, 3, 4]
  }

  render() {
    return (
      <Comments type={return this.state.comments.filter((comment) => comment%2 === 0)} />
    )
  }
}

class Comments extends React.Component {
  render() {
    return (
        /* show comments */
    )
  }
}```

ContentLicense: CC BY-SA 4.0

Body:
For example, there are 2 components:

class App extends React.Component {
  state = {
    comments=[1, 2, 3, 4]
  }
  render() {
    return (
      <Comments />
    )
  }
}

class Comments extends React.Component {
  render() {
    return (
        /* show comments */
    )
  }
}

and I want to show only even comments. Should I put sorting function into App and send prepared array to Comments or send entire array and let Comments sort it by itself?


问:
Is it possible to call Go functions in one transactions?
I store a double linked list in PostgreSQL. I have a Go API to manage this list.

There is a function that creates new Node (in specific position). Let's assume there is an INSERT SQL query inside of it.

Also, there is a function that deletes Node (by id). Let's assume there is a DELETE SQL query inside of it.

It is well known that if you need to move a Node to different position you should call DeleteNode() function and CreateNode() function. So there is the third function called MoveNode()

```<code>func MoveNode() error {
  if err := DeleteNode(); err != nil {
    return err
  }
  if err := CreateNode(); err != nil {
    return err
  }
  return nil
}
</code>```

But these functions (which are inside of MoveNode() should be called in one transaction.

Is there a way to "merge" functions in Go? Or what is the way to solve this problem (except copy & paste code from 2 functions to the third)?

p.s The idea is simple: you have two functions which do some SQL queries and you need to do these queries in one transaction (or call 2 functions in one transaction)

答:
The better way to go about this here will be to move tx.Commit() outside the query execution functions (DeleteNode() and CreateNode() here)

Suggested Solution :

```<code>func MoveNode() error {
   tx, err := db.Begin()
   // err handling

  res, err := DeleteNode(tx)
  // err handling

  res, err := CreateNode(tx)
  // err handling

  tx.Commit()
}

func DeleteNode(transactionFromDbBegin) (responseFromExec, errorFromExec) {
    //...
}

func CreateNode(transactionFromDbBegin) (responseFromExec, errorFromExec) {
    //...
}
</code>```

This should do the trick.

Body:
I store a double linked list in PostgreSQL. I have a Go API to manage this list.

There is a function that creates new Node (in specific position). Let's assume there is an INSERT SQL query inside of it.

Also, there is a function that deletes Node (by id). Let's assume there is a DELETE SQL query inside of it.

It is well known that if you need to move a Node to different position you should call DeleteNode() function and CreateNode() function. So there is the third function called MoveNode()

func MoveNode() error {
  if err := DeleteNode(); err != nil {
    return err
  }
  if err := CreateNode(); err != nil {
    return err
  }
  return nil
}

But these functions (which are inside of MoveNode() should be called in one transaction.

Is there a way to "merge" functions in Go? Or what is the way to solve this problem (except copy & paste code from 2 functions to the third)?

p.s The idea is simple: you have two functions which do some SQL queries and you need to do these queries in one transaction (or call 2 functions in one transaction)

Body:
The better way to go about this here will be to move tx.Commit() outside the query execution functions (DeleteNode() and CreateNode() here)

Suggested Solution :

func MoveNode() error {
   tx, err := db.Begin()
   // err handling

  res, err := DeleteNode(tx)
  // err handling

  res, err := CreateNode(tx)
  // err handling

  tx.Commit()
}

func DeleteNode(transactionFromDbBegin) (responseFromExec, errorFromExec) {
    //...
}

func CreateNode(transactionFromDbBegin) (responseFromExec, errorFromExec) {
    //...
}

This should do the trick.


问:
when I use 'for xml path' syntax, I face ((No column name was specified for column 1 of 'x')) error
this is my code:

```<code>with resultMsg_reportCard
(
   select aa,bb,cc,dd,ee
   from tbl_something

   union

   select aa,bb,cc,dd,ee
   from tbl_somethingElse
)

insert aa,bb,cc,dd,ee
select aa,bb,cc,dd,ee
from
(
   select rm_rc.aa,rm_rc.bb,rm_rc.cc,rm_rc.dd,a.ee
     N'something'+gg.title
     char(13)+char(10)
     ...
)
   from resultMsg_reportCard rm_rc
   inner join
   (
     select something
     from tbl_something
   ) a on rm_rc.something=a.something
   inner join
   (
     select something
     from tbl_somethingElse
   ) b on a.something=b.something
   inner join gg on a.something=gg.soemthing
   for xml path ('')
) x
inner join tbl_somethingElse se on x.something=es.something
</code>```

first of all, I am sorry if my code is not clear enough because I do not have permission to use my company table names, so my only choice was to show main structure of a code

so, when I execute this code, I face No column name was specified for column 1 of 'x' error and also when I delete for xml path('') my query executed correctly!
I suppose I missed something easy and it is not a complicated error.

答:
You just need to specify not only table aliases but column aliases also

for example, this (APPLY) wont work

```<code>select t.size
, m.*
from (values (3)) as t(size)
outer apply (
    select fname
    from (values ('Mary', 1), ('John', 2), ('Sam', 3)) as t(fname, id)
    for xml path (''), type
) as m -- just table alias here
for xml path ('family')
</code>```

and this (JOIN) wont work too

```<code>select t.size
, m.*
from (values (3)) as t(size)
join (
    select fname
    from (values ('Mary', 1), ('John', 2), ('Sam', 3)) as t(fname, id)
    for xml path (''), type
) as m on 1=1 -- just table alias here
for xml path ('family')
</code>```

both will give you

Msg 8155, Level 16, State 2, Line 18 No column name was specified for
  column 1 of 'm'.

BUT specifying column aliases fixes both cases (JOIN, APPLY)

```<code>select t.size
, m.[members]
from (values (3)) as t(size)
join (
    select fname
    from (values ('Mary', 1), ('John', 2), ('Sam', 3)) as t(fname, id)
    for xml path (''), type
) as m([members]) on 1=1 -- here
for xml path ('family')
</code>```

or

```<code>select t.size
, m.[members]
from (values (3)) as t(size)
outer apply (
    select fname
    from (values ('Mary', 1), ('John', 2), ('Sam', 3)) as t(fname, id)
    for xml path (''), type
) as m([members]) - here
for xml path ('family')
</code>```

RESULT

```<code><family>
  <size>3</size>
  <members>
    <fname>Mary</fname>
    <fname>John</fname>
    <fname>Sam</fname>
  </members>
</family>
</code>```

Body:
this is my code:

with resultMsg_reportCard
(
   select aa,bb,cc,dd,ee
   from tbl_something

   union

   select aa,bb,cc,dd,ee
   from tbl_somethingElse
)

insert aa,bb,cc,dd,ee
select aa,bb,cc,dd,ee
from
(
   select rm_rc.aa,rm_rc.bb,rm_rc.cc,rm_rc.dd,a.ee
     N'something'+gg.title
     char(13)+char(10)
     ...
)
   from resultMsg_reportCard rm_rc
   inner join
   (
     select something
     from tbl_something
   ) a on rm_rc.something=a.something
   inner join
   (
     select something
     from tbl_somethingElse
   ) b on a.something=b.something
   inner join gg on a.something=gg.soemthing
   for xml path ('')
) x
inner join tbl_somethingElse se on x.something=es.something

first of all, I am sorry if my code is not clear enough because I do not have permission to use my company table names, so my only choice was to show main structure of a code

so, when I execute this code, I face No column name was specified for column 1 of 'x' error and also when I delete for xml path('') my query executed correctly!
I suppose I missed something easy and it is not a complicated error.

Body:
You just need to specify not only table aliases but column aliases also

for example, this (APPLY) wont work

select t.size
, m.*
from (values (3)) as t(size)
outer apply (
    select fname
    from (values ('Mary', 1), ('John', 2), ('Sam', 3)) as t(fname, id)
    for xml path (''), type
) as m -- just table alias here
for xml path ('family')

and this (JOIN) wont work too

select t.size
, m.*
from (values (3)) as t(size)
join (
    select fname
    from (values ('Mary', 1), ('John', 2), ('Sam', 3)) as t(fname, id)
    for xml path (''), type
) as m on 1=1 -- just table alias here
for xml path ('family')

both will give you

Msg 8155, Level 16, State 2, Line 18 No column name was specified for
  column 1 of 'm'.

BUT specifying column aliases fixes both cases (JOIN, APPLY)

select t.size
, m.[members]
from (values (3)) as t(size)
join (
    select fname
    from (values ('Mary', 1), ('John', 2), ('Sam', 3)) as t(fname, id)
    for xml path (''), type
) as m([members]) on 1=1 -- here
for xml path ('family')

or

select t.size
, m.[members]
from (values (3)) as t(size)
outer apply (
    select fname
    from (values ('Mary', 1), ('John', 2), ('Sam', 3)) as t(fname, id)
    for xml path (''), type
) as m([members]) - here
for xml path ('family')

RESULT

<family>
  <size>3</size>
  <members>
    <fname>Mary</fname>
    <fname>John</fname>
    <fname>Sam</fname>
  </members>
</family>


问:
Find out if a node is an ancestor of another node for a tree stored as an adjacency list in sqlite
The question

I have a tree structure stored as an adjacency table (also known as a Naive Tree) in an SQL database. I wish to find out if node_b is an ancestor of node_a. How can I do this?

Background details

The table where the nodes are stored is defined as shown below:

```<code>CREATE TABLE Nodes(
      id INTEGER PRIMARY KEY,
      parent INTEGER,
      -- Other node specific data
      FOREIGN KEY (parent) REFERENCES Nodes(id)
    );
</code>```

The tree depth is unknown, but in ordinary use cases is expected to be fairly small.

There are no loops in the tree.

Root nodes have a parent value of NULL. There may be multiple root nodes.

Answer Criteria

I'm looking for a query that is as fast as possible.

Work done already

I have come up with a solution which works, which I will post as an answer, but I would like to see if there is a better, simpler, quicker approach.

Examples

Given the following data set:

```<code>id     parent
1      NULL
2      1
3      NULL
4      1
5      2
</code>```

The query should return True (or 1) for node_a = 1, node_b = 1

The query should return True (or 1) for node_a = 2, node_b = 1

The query should return True (or 1) for node_a = 5, node_b = 1

The query should return True (or 1) for node_a = 5, node_b = 2

The query should return False (or 0) for node_a = 2, node_b = 3

The query should return False (or 0) for node_a = 2, node_b = 5

答:
My Solution

The following query is the solution I used (:node_a and :node_b are placeholders for the node in question and its possible ancestor):

```<code>WITH RECURSIVE ancestors AS(
  SELECT parent, id=:node_b AS match
  FROM NODES WHERE id=:node_a
  UNION ALL
  SELECT n.parent, n.id=:id AS match
  FROM Nodes n JOIN ancestors
  ON ancestors.parent=n.id AND NOT ancestors.match
)
SELECT MAX(match) AS is_ancestor FROM ancestors;
</code>```

Explanation

A common table expression is used to generate a query comprising the parent of each of the ancestors of node_a and whether that ancestor matches node_b

It starts with node_a itself, and checks whether that matches node_b, returning a row consisting of two columns parent and match - the direct parent of node_a and a boolean representing whether node_a matches node_b.

It then ascends up through the ancestors of node_a by recursively joining on the parent column, until either one of the ancestors matches node_b or the parent column is NULL.

If node_b is an ancestor of node_a then one row of this table will contain the value true for the match column.
If it is not then the match column will contain false for all rows. As true and false are represented as 1 and 0 respectively the MAX of the match column will be 1 in the first case and 0 in the second.

Therefore the whole query returns 1 if node_b is an ancestor of node_a and 0 otherwise.

Body:
The question

I have a tree structure stored as an adjacency table (also known as a Naive Tree) in an SQL database. I wish to find out if node_b is an ancestor of node_a. How can I do this?

Background details

The table where the nodes are stored is defined as shown below:

CREATE TABLE Nodes(
      id INTEGER PRIMARY KEY,
      parent INTEGER,
      -- Other node specific data
      FOREIGN KEY (parent) REFERENCES Nodes(id)
    );

The tree depth is unknown, but in ordinary use cases is expected to be fairly small.

There are no loops in the tree.

Root nodes have a parent value of NULL. There may be multiple root nodes.

Answer Criteria

I'm looking for a query that is as fast as possible.

Work done already

I have come up with a solution which works, which I will post as an answer, but I would like to see if there is a better, simpler, quicker approach.

Examples

Given the following data set:

id     parent
1      NULL
2      1
3      NULL
4      1
5      2

The query should return True (or 1) for node_a = 1, node_b = 1

The query should return True (or 1) for node_a = 2, node_b = 1

The query should return True (or 1) for node_a = 5, node_b = 1

The query should return True (or 1) for node_a = 5, node_b = 2

The query should return False (or 0) for node_a = 2, node_b = 3

The query should return False (or 0) for node_a = 2, node_b = 5

Body:
My Solution

The following query is the solution I used (:node_a and :node_b are placeholders for the node in question and its possible ancestor):

WITH RECURSIVE ancestors AS(
  SELECT parent, id=:node_b AS match
  FROM NODES WHERE id=:node_a
  UNION ALL
  SELECT n.parent, n.id=:id AS match
  FROM Nodes n JOIN ancestors
  ON ancestors.parent=n.id AND NOT ancestors.match
)
SELECT MAX(match) AS is_ancestor FROM ancestors;

Explanation

A common table expression is used to generate a query comprising the parent of each of the ancestors of node_a and whether that ancestor matches node_b

It starts with node_a itself, and checks whether that matches node_b, returning a row consisting of two columns parent and match - the direct parent of node_a and a boolean representing whether node_a matches node_b.

It then ascends up through the ancestors of node_a by recursively joining on the parent column, until either one of the ancestors matches node_b or the parent column is NULL.

If node_b is an ancestor of node_a then one row of this table will contain the value true for the match column.
If it is not then the match column will contain false for all rows. As true and false are represented as 1 and 0 respectively the MAX of the match column will be 1 in the first case and 0 in the second.

Therefore the whole query returns 1 if node_b is an ancestor of node_a and 0 otherwise.


问:
Verifying method calls on lambda with Mockito
I'm trying to verify and capture the arguments of some method calls within a lambda expression as so:

```<code>public Optional<UserDetails> findOne(String userName) {
    String selectStatement =
        "SELECT * FROM users WHERE userName = :userName;";

    return jdbi.withHandle(handle -> handle
            .createQuery(selectStatement)
            .bind("userName", userName)
            .map(new UserDetailsMapper())
            .findOne());
  }
</code>```

jdbi.withHandle() takes an argument of HandleCallBack, which looks like this:

```<code>public interface HandleCallback<T, X extends Exception> {
  T withHandle(Handle handle) throws X;
}
</code>```

For example, I want to verify that .bind() has been called with "userName" and the passed in userName argument string from my findOne method.

It does feel like I'm unit testing the Jdbi class rather than my own class, but I feel like the arguments to .createQuery() .bind() and .map() should be tested as these could be accidentally changed by a developer.

The approach I've currently taken is to create an in-memory database and test what is actually being returned, but this feels more like an integration test than a unit test. I also don't really care what is actually returned by the Jdbi .withHandle() method, as I would essentially be testing a library at that point.

My understanding is that I should be unit testing the arguments passed to .withHandle() (in this case, a lambda expression), which is what I'm trying to do here.

The closest I got was by moving the logic into a method reference, but that won't work as userName is passed into my findOne() method and then used inside the lambda.

I've also played around with Mockito's doAnswer to no avail.

I can only think of creating a new class with helper methods to return userName, selectStatement, etc, and verify that they are called, but it feels unnecessary and will be added simply to provide testability.

答:
The lambda expression is part of the implementation of the findOne method. So, you should test it as part of testing findOne. But it is not executed when doing the call to findOne. So, to be able to test it, executing findOne and doing verifications and assertions on that will not be enough.

I would mock jdbi and then do a verification on the call with an ArgumentCaptor that captures the lambda function. Then you can pass that lambda function as a parameter to a test method which tests the lambda function. That method can look the same as any other test method except that it can never be ran as a separate test case.

In this case, I think one such test method will be enough. But sometimes when testing lambda function, you might need to create and call several test methods to test the captured lambda function with different input values.

Body:
I'm trying to verify and capture the arguments of some method calls within a lambda expression as so:

public Optional<UserDetails> findOne(String userName) {
    String selectStatement =
        "SELECT * FROM users WHERE userName = :userName;";

    return jdbi.withHandle(handle -> handle
            .createQuery(selectStatement)
            .bind("userName", userName)
            .map(new UserDetailsMapper())
            .findOne());
  }

jdbi.withHandle() takes an argument of HandleCallBack, which looks like this:

public interface HandleCallback<T, X extends Exception> {
  T withHandle(Handle handle) throws X;
}

For example, I want to verify that .bind() has been called with "userName" and the passed in userName argument string from my findOne method.

It does feel like I'm unit testing the Jdbi class rather than my own class, but I feel like the arguments to .createQuery() .bind() and .map() should be tested as these could be accidentally changed by a developer.

The approach I've currently taken is to create an in-memory database and test what is actually being returned, but this feels more like an integration test than a unit test. I also don't really care what is actually returned by the Jdbi .withHandle() method, as I would essentially be testing a library at that point.

My understanding is that I should be unit testing the arguments passed to .withHandle() (in this case, a lambda expression), which is what I'm trying to do here.

The closest I got was by moving the logic into a method reference, but that won't work as userName is passed into my findOne() method and then used inside the lambda.

I've also played around with Mockito's doAnswer to no avail.

I can only think of creating a new class with helper methods to return userName, selectStatement, etc, and verify that they are called, but it feels unnecessary and will be added simply to provide testability.


问:
Why is a ConcurrentModificationException thrown and how to debug it
I am using a Collection (a HashMap used indirectly by the JPA, it so happens), but apparently randomly the code throws a ConcurrentModificationException. What is causing it and how do I fix this problem? By using some synchronization, perhaps?

Here is the full stack-trace:

```<code>Exception in thread "pool-1-thread-1" java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
        at java.util.HashMap$ValueIterator.next(Unknown Source)
        at org.hibernate.collection.AbstractPersistentCollection$IteratorProxy.next(AbstractPersistentCollection.java:555)
        at org.hibernate.engine.Cascade.cascadeCollectionElements(Cascade.java:296)
        at org.hibernate.engine.Cascade.cascadeCollection(Cascade.java:242)
        at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:219)
        at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:169)
        at org.hibernate.engine.Cascade.cascade(Cascade.java:130)
</code>```

答:
It sounds less like a Java synchronization issue and more like a database locking problem.

I don't know if adding a version to all your persistent classes will sort it out, but that's one way that Hibernate can provide exclusive access to rows in a table.

Could be that isolation level needs to be higher.  If you allow "dirty reads", maybe you need to bump up to serializable.

Body:
I am using a Collection (a HashMap used indirectly by the JPA, it so happens), but apparently randomly the code throws a ConcurrentModificationException. What is causing it and how do I fix this problem? By using some synchronization, perhaps?

Here is the full stack-trace:

Exception in thread "pool-1-thread-1" java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
        at java.util.HashMap$ValueIterator.next(Unknown Source)
        at org.hibernate.collection.AbstractPersistentCollection$IteratorProxy.next(AbstractPersistentCollection.java:555)
        at org.hibernate.engine.Cascade.cascadeCollectionElements(Cascade.java:296)
        at org.hibernate.engine.Cascade.cascadeCollection(Cascade.java:242)
        at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:219)
        at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:169)
        at org.hibernate.engine.Cascade.cascade(Cascade.java:130)

LastEditorDisplayName: Rich B

ContentLicense: CC BY-SA 2.5


问:
CSS Alignment Issue on Navigation Bar
I'm currently creating a navigation bar that expands and collapses whether the mouse is over or out of the navbar. My issue is that when the navbar is expanded, my icons are aligned to the center but I wish for them to be positioned exactly where they are before the navbar is expanded. I have them aligned to the center because the icons are not the same size and look 'out of place' without it, when the navbar is collapsed.

let sidenav = document.getElementById("sidenav");
sidenav.onmouseover = function() {
  sidenav.style.width = "280px";
  document.getElementById("expand-icon").classList.add("expand");
  document.getElementById("sidenav-expand").style.textAlign = "right";
  document.getElementById("sidenav-heading").style.display = "inline-block";
  //document.getElementById("links").style.float = "left";
};
sidenav.onmouseout = function() {
  sidenav.style.width = "75px";
  document.getElementById("expand-icon").classList.remove("expand");
  document.getElementById("sidenav-expand").style.textAlign = "center";
  document.getElementById("sidenav-heading").style.display = "none";
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: 0.2s;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading h2 {
  margin: 0;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

.expand {
  transform: rotate(180deg);
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
  text-align: center;
}

#links li {
  padding: 18px;
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>Navigation Bar</title>
  <link href="css/style.css" rel="stylesheet" type="text/css" />

Expanded

```

And JSFiddle link:
https://jsfiddle.net/h86zf4d3/

I tried to float my icons to the left as you can see from the commented out JS code, however, for some reason, this gets rid of the block display for the list items.

答:
why not just placing them to left ?</p>

```<code>#links li{
  text-align:left;
}
</code>```

Title: CSS Alignment Issue on Navigation Bar

Body:
I'm currently creating a navigation bar that expands and collapses whether the mouse is over or out of the navbar. My issue is that when the navbar is expanded, my icons are aligned to the center but I wish for them to be positioned exactly where they are before the navbar is expanded. I have them aligned to the center because the icons are not the same size and look 'out of place' without it, when the navbar is collapsed.

let sidenav = document.getElementById("sidenav");
sidenav.onmouseover = function() {
  sidenav.style.width = "280px";
  document.getElementById("expand-icon").classList.add("expand");
  document.getElementById("sidenav-expand").style.textAlign = "right";
  document.getElementById("sidenav-heading").style.display = "inline-block";
  //document.getElementById("links").style.float = "left";
};
sidenav.onmouseout = function() {
  sidenav.style.width = "75px";
  document.getElementById("expand-icon").classList.remove("expand");
  document.getElementById("sidenav-expand").style.textAlign = "center";
  document.getElementById("sidenav-heading").style.display = "none";
};

#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: 0.2s;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading h2 {
  margin: 0;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

.expand {
  transform: rotate(180deg);
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
  text-align: center;
}

#links li {
  padding: 18px;
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>Navigation Bar</title>
  <link href="css/style.css" rel="stylesheet" type="text/css" />

Expanded

And JSFiddle link:
https://jsfiddle.net/h86zf4d3/

I tried to float my icons to the left as you can see from the commented out JS code, however, for some reason, this gets rid of the block display for the list items.

Body:
why not just placing them to left ?

#links li{
  text-align:left;
}


问:
perl - matching greater than charater in regex
```<code>$string1="<a href='/channels/folder1'>Alpha-Seeking";
$string2="<a href='/channels/folder2'>No Underlying Index ,";
</code>```

I need to extract "Alpha-Seeking" and "No Underlying Index ," from the above 2 strings.
Basically, need everything from ('>) to the last character of the string.

Tried two ways,

1) The standard intuitive

```<code>($string1=~ /\'>(.*?)/) {print "got $1";}
</code>```

but this does not seem to work on '>' symbol.

2) Also tried

```<code>if ($string1=~ /(?=>)(.*?)/) {print "got $1";}
</code>```

based on inputs from Greater than and less than symbol in regular expressions, but it is not working.

Any inputs will be useful.

PS: Also, if the answer can include matching the "less than" symbo ("<"), that will be great!

Thanks

答:
This works for me

```<code>use warnings;
use strict;

my @strings = (
 "<a href='/channels/folder1'>Alpha-Seeking",
 "<a href='/channels/folder2'>No Underlying Index ,"
);

for my $string (@strings)
{
    if ($string =~ /'>(.*?)$/)
    {
        print "got $1\n";
    }
}
</code>```

running it gives

```<code>$ perl /tmp/abc.pl
got Alpha-Seeking
got No Underlying Index ,
</code>```

Body:
$string1="Alpha-Seeking";
$string2="No Underlying Index ,";

I need to extract "Alpha-Seeking" and "No Underlying Index ," from the above 2 strings.
Basically, need everything from ('>) to the last character of the string.

Tried two ways,

1) The standard intuitive

($string1=~ /\'>(.*?)/) {print "got $1";}

but this does not seem to work on '>' symbol.

2) Also tried

if ($string1=~ /(?=>)(.*?)/) {print "got $1";}

based on inputs from Greater than and less than symbol in regular expressions, but it is not working.

Any inputs will be useful.

PS: Also, if the answer can include matching the "less than" symbo ("<"), that will be great!

Thanks

Body:
This works for me

use warnings;
use strict;

my @strings = (
 "<a href='/channels/folder1'>Alpha-Seeking",
 "<a href='/channels/folder2'>No Underlying Index ,"
);

for my $string (@strings)
{
    if ($string =~ /'>(.*?)$/)
    {
        print "got $1\n";
    }
}

running it gives

$ perl /tmp/abc.pl
got Alpha-Seeking
got No Underlying Index ,


问:
Python execute bottom lines first and then top using while
My code requires me execute the lines at bottom and then top.
Here is my code:

```<code>test = True
while test:
   if test==False:
       print("Now executing top lines of the code")
       break
   elif test==True:
       print("Now executing bottom lines of the code")
       test = False
       continue
</code>```

My expected output:

```<code>Now executing bottom lines of the code
Now executing top lines of the code
</code>```

Somehow my code is not working. Either it halts printing nothing or goes infinite loop.

答:
I believe you are looking for something like this:

```<code>test = True

while True:
    if test==False:
        print("Now executing top lines of the code")
        break
    elif test==True:
        print("Now executing bottom lines of the code")
        test = False
        continue
</code>```

You have such behaviour of code because after first  iteration you set test to False (test = False) and it exits the loop by "while test" (now test is False)  condition. So you never have second iteration of loop

Body:
My code requires me execute the lines at bottom and then top.
Here is my code:

test = True
while test:
   if test==False:
       print("Now executing top lines of the code")
       break
   elif test==True:
       print("Now executing bottom lines of the code")
       test = False
       continue

My expected output:

Now executing bottom lines of the code
Now executing top lines of the code

Somehow my code is not working. Either it halts printing nothing or goes infinite loop.

Body:
I believe you are looking for something like this:

test = True

while True:
    if test==False:
        print("Now executing top lines of the code")
        break
    elif test==True:
        print("Now executing bottom lines of the code")
        test = False
        continue

You have such behaviour of code because after first  iteration you set test to False (test = False) and it exits the loop by "while test" (now test is False)  condition. So you never have second iteration of loop


问:
How to create a highcharts dot plot graph? - R Highcharter
How can I create a highcharts graph like this using the R highcharter package?

It is a simple count of sectors (instances) above or bellow 0 and coloured to reflect the value.

This may sometime be termed a dot plot (https://ggplot2.tidyverse.org/reference/geom_dotplot.html)?

image from (https://graphics.wsj.com/job-market-tracker/)

Some sample data:

```<code>data = data.table(
  CJ(date = seq(as.IDate("2019-01-01"), as.IDate("2019-01-10"), by = "day"),
     group = seq(1,20))
)

data[, value := runif(n=200, -5,5)]
</code>```

答:
This is as far as I got:

```<code>library(highcharter)
library(data.table)

data = data.table(
  CJ(date = seq(as.Date("2019-01-01"), as.Date("2019-02-10"), by = "day"),
     group = seq(1,20))
)

# generate random value
data[, value := round(runif(n=dim(data)[1], -5,5),4)]

# categorize it from 1 to 10
data[, cat:=cut(value, breaks=quantile(data[value!=0]$value, seq(0,1,0.1)), labels=seq(1,10))]

# assign colour based on value
colf = colorRampPalette(colors = c("red","yellow", "green"))
cols = colf(10)
data[, color := as.factor(cols[cat])]

# generate x and y
data[, x := datetime_to_timestamp(date)]
data[, y := order(order(value))-sum(value<0), date]

data[, name := group]

highchart() %>%
  hc_chart(type = "scatter") %>%
  hc_xAxis(type = "datetime", dateTimeLabelFormats = list(day = '%d of %b')) %>%
  hc_tooltip(pointFormat = "Performance = <b>{point.value}</b> <br> Group = <b>{point.name}</b>") %>%
  hc_add_theme(hc_theme_flat(chart = list(backgroundColor = "#FFF"))) %>%
  hc_add_series(data, groupPadding=0)
</code>```

It also works with more points:

Body:
How can I create a highcharts graph like this using the R highcharter package?

It is a simple count of sectors (instances) above or bellow 0 and coloured to reflect the value.

This may sometime be termed a dot plot (https://ggplot2.tidyverse.org/reference/geom_dotplot.html)?

image from (https://graphics.wsj.com/job-market-tracker/)

Some sample data:

data = data.table(
  CJ(date = seq(as.IDate("2019-01-01"), as.IDate("2019-01-10"), by = "day"),
     group = seq(1,20))
)

data[, value := runif(n=200, -5,5)]

Body:
This is as far as I got:

library(highcharter)
library(data.table)

data = data.table(
  CJ(date = seq(as.Date("2019-01-01"), as.Date("2019-02-10"), by = "day"),
     group = seq(1,20))
)

# generate random value
data[, value := round(runif(n=dim(data)[1], -5,5),4)]

# categorize it from 1 to 10
data[, cat:=cut(value, breaks=quantile(data[value!=0]$value, seq(0,1,0.1)), labels=seq(1,10))]

# assign colour based on value
colf = colorRampPalette(colors = c("red","yellow", "green"))
cols = colf(10)
data[, color := as.factor(cols[cat])]

# generate x and y
data[, x := datetime_to_timestamp(date)]
data[, y := order(order(value))-sum(value<0), date]

data[, name := group]

highchart() %>%
  hc_chart(type = "scatter") %>%
  hc_xAxis(type = "datetime", dateTimeLabelFormats = list(day = '%d of %b')) %>%
  hc_tooltip(pointFormat = "Performance = <b>{point.value}</b> <br> Group = <b>{point.name}</b>") %>%
  hc_add_theme(hc_theme_flat(chart = list(backgroundColor = "#FFF"))) %>%
  hc_add_series(data, groupPadding=0)

It also works with more points:


问:
f# mailboxprocessor - replying without waiting for delivery
I'm using an agent (MailboxProcessor) to do some stateful processing where a response is needed.

The caller posts a message using MailboxProcessor.PostAndAsyncReply

Within the agent, a response is given with AsyncReplyChannel.Reply

However, I've discovered by poking around the f# source code that the agent will not process the next message until the the response is delivered. This is a good thing in general. But in my case, it is more desirable for the agent to keep processing messages than to wait for response delivery.

Is it problematic to do something like this to deliver the response? (Or is there a better alternative?)

```<code>async { replyChannel.Reply response } |> Async.Start
</code>```

I realize that this method does not guarantee that responses will be delivered in order. I'm okay with that.

Reference example

```<code>// agent code
let doWork data =
    async { ... ; return response }

let rec loop ( inbox : MailboxProcessor<_> ) =
    async {
        let! msg = inbox.Receive()
        match msg with
        | None ->
            return ()

        | Some ( data, replyChannel ) ->
            let! response = doWork data
            replyChannel.Reply response (* waits for delivery, vs below *)
            // async { replyChannel.Reply response } |> Async.Start
            return! loop inbox
    }

let agent =
    MailboxProcessor.Start(loop)

// caller code
async {
    let! response =
        agent.PostAndAsyncReply(fun replyChannel -> Some (data, replyChannel))
    ...
}
</code>```

答:
FSharp.Control.AsyncSeq puts a friendlier face on top of mailbox processor. Async Sequences are a bit easier to follow, however the default implement mapping parallel has the same issue as described, waiting for the prior element in the sequence to be mapped to retain the order.

So I made a new function taht is just the original AsyncSeq.mapAsyncParallel, modified so that it no longer is a true map, since it's unordered, but it does map everything and the lazy seq does progress as work completes.

Full Source for AsyncSeq.mapAsyncParallelUnordered

```<code>let mapAsyncParallelUnordered (f:'a -> Async<'b>) (s:AsyncSeq<'a>) : AsyncSeq<'b> = asyncSeq {
  use mb = MailboxProcessor.Start (fun _ -> async.Return())
  let! err =
    s
    |> AsyncSeq.iterAsyncParallel (fun a -> async {
      let! b = f a
      mb.Post (Some b) })
    |> Async.map (fun _ -> mb.Post None)
    |> Async.StartChildAsTask
  yield!
    AsyncSeq.replicateUntilNoneAsync (Task.chooseTask (err |> Task.taskFault) (async.Delay mb.Receive))
  }
</code>```

Below is an example of how I use it in a tool that uses SSLlabs free and very slow api that can easily get overloaded. parallelProcessHost returns an lazy AsyncSeq that is generated by the webapi requests, So AsyncSeq.mapAsyncParallelUnordered AsyncSeq.toListAsync actually runs the requests and allows the console to printout the results as the come in, independent of the order sent.

Full Source

```<code>let! es =
    hosts
    |> Seq.indexed
    |> AsyncSeq.ofSeq
    |> AsyncSeq.map parallelProcessHost
    |> AsyncSeq.mapAsyncParallelUnordered AsyncSeq.toListAsync
    |> AsyncSeq.indexed
    |> AsyncSeq.map (fun (i, tail) -> (consoleN "-- %d of %i --- %O --" (i+1L) totalHosts (DateTime.UtcNow - startTime)) :: tail )
    |> AsyncSeq.collect AsyncSeq.ofSeq
    |> AsyncSeq.map stdoutOrStatus //Write out to console
    |> AsyncSeq.fold (|||) ErrorStatus.Okay
</code>```

Body:
I'm using an agent (MailboxProcessor) to do some stateful processing where a response is needed.

The caller posts a message using MailboxProcessor.PostAndAsyncReply

Within the agent, a response is given with AsyncReplyChannel.Reply

However, I've discovered by poking around the f# source code that the agent will not process the next message until the the response is delivered. This is a good thing in general. But in my case, it is more desirable for the agent to keep processing messages than to wait for response delivery.

Is it problematic to do something like this to deliver the response? (Or is there a better alternative?)

async { replyChannel.Reply response } |> Async.Start

I realize that this method does not guarantee that responses will be delivered in order. I'm okay with that.

Reference example

// agent code
let doWork data =
    async { ... ; return response }

let rec loop ( inbox : MailboxProcessor<_> ) =
    async {
        let! msg = inbox.Receive()
        match msg with
        | None ->
            return ()

        | Some ( data, replyChannel ) ->
            let! response = doWork data
            replyChannel.Reply response (* waits for delivery, vs below *)
            // async { replyChannel.Reply response } |> Async.Start
            return! loop inbox
    }

let agent =
    MailboxProcessor.Start(loop)

// caller code
async {
    let! response =
        agent.PostAndAsyncReply(fun replyChannel -> Some (data, replyChannel))
    ...
}

Body:
FSharp.Control.AsyncSeq puts a friendlier face on top of mailbox processor. Async Sequences are a bit easier to follow, however the default implement mapping parallel has the same issue as described, waiting for the prior element in the sequence to be mapped to retain the order.

So I made a new function taht is just the original AsyncSeq.mapAsyncParallel, modified so that it no longer is a true map, since it's unordered, but it does map everything and the lazy seq does progress as work completes.

Full Source for AsyncSeq.mapAsyncParallelUnordered

let mapAsyncParallelUnordered (f:'a -> Async<'b>) (s:AsyncSeq<'a>) : AsyncSeq<'b> = asyncSeq {
  use mb = MailboxProcessor.Start (fun _ -> async.Return())
  let! err =
    s
    |> AsyncSeq.iterAsyncParallel (fun a -> async {
      let! b = f a
      mb.Post (Some b) })
    |> Async.map (fun _ -> mb.Post None)
    |> Async.StartChildAsTask
  yield!
    AsyncSeq.replicateUntilNoneAsync (Task.chooseTask (err |> Task.taskFault) (async.Delay mb.Receive))
  }

Below is an example of how I use it in a tool that uses SSLlabs free and very slow api that can easily get overloaded. parallelProcessHost returns an lazy AsyncSeq that is generated by the webapi requests, So AsyncSeq.mapAsyncParallelUnordered AsyncSeq.toListAsync actually runs the requests and allows the console to printout the results as the come in, independent of the order sent.

Full Source

let! es =
    hosts
    |> Seq.indexed
    |> AsyncSeq.ofSeq
    |> AsyncSeq.map parallelProcessHost
    |> AsyncSeq.mapAsyncParallelUnordered AsyncSeq.toListAsync
    |> AsyncSeq.indexed
    |> AsyncSeq.map (fun (i, tail) -> (consoleN "-- %d of %i --- %O --" (i+1L) totalHosts (DateTime.UtcNow - startTime)) :: tail )
    |> AsyncSeq.collect AsyncSeq.ofSeq
    |> AsyncSeq.map stdoutOrStatus //Write out to console
    |> AsyncSeq.fold (|||) ErrorStatus.Okay


问:
NMAKE: How do I force a debug build? [7ZIP]
The suggested way of building 7Zip is on the command line via the nmake command line utility. 7zip doesn't seem to come with a working visual studio solution.

I have seen invocations such as nmake NEW_COMPILER=1 MY_STATIC_LINK=1 suggested for initiating a build using the various nested .MAK files.

Using this command line interface how might I force a build with debug symbols?

If there is no standard way to accomplish this via nmake, I'd be glad to receive help with regards to 7Zip in particular. I am much less familiar with .MAK than GNU make, and have thus far been unable to find something akin to a "debug target" in the GNU make sense in 7ZIP.

答:
To make a project that uses visual studio nmake build a debug output you need to edit the makefile and make 2 changes.

First you need to add /Zi to the list of flags used when compiling

```<code>CFLAGS = $(CFLAGS) -nologo -c -Fo$O/ -W4 -WX -EHsc -Gy -GR- -GF /Zi
</code>```

Second you need to add /debug to list of options for the linker e.g.

```<code>LFLAGS = $(LFLAGS) -nologo -OPT:REF -OPT:ICF /DEBUG
</code>```

I tested this on a different library, I assume there will be similarities here.

Body:
To make a project that uses visual studio nmake build a debug output you need to edit the makefile and make 2 changes.

First you need to add /Zi to the list of flags used when compiling

CFLAGS = $(CFLAGS) -nologo -c -Fo$O/ -W4 -WX -EHsc -Gy -GR- -GF /Zi

Second you need to add /debug to list of options for the linker e.g.

LFLAGS = $(LFLAGS) -nologo -OPT:REF -OPT:ICF /DEBUG

I tested this on a different library, I assume there will be similarities here.


问:
Normalization...Which table does the Address field belong in?
I'm trying to understand how to apply the concept of normalization. I’m working with this example that I came across online.

FIRST NORMAL FORM…

CONVERSION TO SECOND NORMAL FORM…
<img src="https://i.stack.imgur.com/e5703.png" alt="enter image description here">

My question about this is, how would I know if Address belongs in the Membership_Details_Table. Doesn’t it seem like the following would be a better schema in case a member has multiple addresses?

```<code>**Table1**
MembershipID
Salutation
FullName

**Table2**
MembershipID
Address

**Table3**
MembershipID
BooksIssued
</code>```

答:
No.  The second method is just duplicating information about a particular member across two different tables.  That is sometimes useful, but not for normalization.

It is possible that different members might be at the same address:

Members

MembershipID

Salutation

FullName

AddressId

Addresses

AddresssId

Address

Note the difference:  The addresses table has its own id.

Or it is also possible that the addresses change over time.  That would suggest a type-2 table.  However, your data has no dates, so that is beyond the scope of this question.

Body:
I'm trying to understand how to apply the concept of normalization. I’m working with this example that I came across online.

FIRST NORMAL FORM…

CONVERSION TO SECOND NORMAL FORM…
<img src="https://i.stack.imgur.com/e5703.png" alt="enter image description here">

My question about this is, how would I know if Address belongs in the Membership_Details_Table. Doesn’t it seem like the following would be a better schema in case a member has multiple addresses?

**Table1**
MembershipID
Salutation
FullName

**Table2**
MembershipID
Address

**Table3**
MembershipID
BooksIssued


问:
Why when i use float, last item going on next line?
I do not understand why and how to fix a fact that the red block is going to the next line. Ofc i can use margin-left: 5% to the 2nd and 3rd block to fix it but that's not right. So how to spread all three blocks in one line and make their total width with margins equal 100%?

.clearfix::after {
  content: " ";
  visibility: hidden;
  display: block;
  height: 0;
  clear: both;
}

.common-block {
  background-color: wheat;
  width: 800px;
  height: 400px;
  padding-top:20px;
}

.items {
  background-color: white;
  max-width: 600px;
  padding:20px;
  margin:auto;
  overflow: auto;
}

.item {
  float: left;
  width: 30%;
  margin-left: 5%;
  border-bottom: 1px solid black;
  height: 50px;
}

.item-1 {
  background-color: yellow;
}

.item-2 {
  background-color: green;
}

.item-3 {
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="common-block">
  <div class="items">
    <div class="item item-1"></div>
    <div class="item item-2"></div>
    <div class="item item-3"></div>
  </div>
</div></code>```

答:
3 * (30% + 5%) equals 105% (= wider than 100%), that's the reason. Change the margin value to 3% and it will work (3* (30% + 3%) = 99%).

.clearfix::after {
  content: " ";
  visibility: hidden;
  display: block;
  height: 0;
  clear: both;
}

.common-block {
  background-color: wheat;
  width: 800px;
  height: 400px;
  padding-top:20px;
}

.items {
  background-color: white;
  max-width: 600px;
  padding:20px;
  margin:auto;
  overflow: auto;
}

.item {
  float: left;
  width: 30%;
  margin-left: 3%;
  border-bottom: 1px solid black;
  height: 50px;
}

.item-1 {
  background-color: yellow;
}

.item-2 {
  background-color: green;
}

.item-3 {
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="common-block">
  <div class="items">
    <div class="item item-1"></div>
    <div class="item item-2"></div>
    <div class="item item-3"></div>
  </div>
</div></code>```

As an alternative, you could apply the left margin only to the second and third block and leave it at 5%. This will also keep the blocks centered inside their container:

.clearfix::after {
  content: " ";
  visibility: hidden;
  display: block;
  height: 0;
  clear: both;
}

.common-block {
  background-color: wheat;
  width: 800px;
  height: 400px;
  padding-top: 20px;
}

.items {
  background-color: white;
  max-width: 600px;
  padding: 20px;
  margin: auto;
  overflow: auto;
}

.item {
  float: left;
  width: 30%;
  border-bottom: 1px solid black;
  height: 50px;
}

.item-1 {
  background-color: yellow;
}

.item-2 {
  background-color: green;
}

.item-3 {
  background-color: red;
}

.item-2,
.item-3 {
  margin-left: 5%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="common-block">
  <div class="items">
    <div class="item item-1"></div>
    <div class="item item-2"></div>
    <div class="item item-3"></div>
  </div>
</div></code>```

Body:
3 * (30% + 5%) equals 105% (= wider than 100%), that's the reason. Change the margin value to 3% and it will work (3* (30% + 3%) = 99%).

.clearfix::after {
  content: " ";
  visibility: hidden;
  display: block;
  height: 0;
  clear: both;
}

.common-block {
  background-color: wheat;
  width: 800px;
  height: 400px;
  padding-top:20px;
}

.items {
  background-color: white;
  max-width: 600px;
  padding:20px;
  margin:auto;
  overflow: auto;
}

.item {
  float: left;
  width: 30%;
  margin-left: 3%;
  border-bottom: 1px solid black;
  height: 50px;
}

.item-1 {
  background-color: yellow;
}

.item-2 {
  background-color: green;
}

.item-3 {
  background-color: red;
}

<div class="common-block">
  <div class="items">
    <div class="item item-1"></div>
    <div class="item item-2"></div>
    <div class="item item-3"></div>
  </div>
</div>

As an alternative, you could apply the left margin only to the second and third block and leave it at 5%. This will also keep the blocks centered inside their container:

.clearfix::after {
  content: " ";
  visibility: hidden;
  display: block;
  height: 0;
  clear: both;
}

.common-block {
  background-color: wheat;
  width: 800px;
  height: 400px;
  padding-top: 20px;
}

.items {
  background-color: white;
  max-width: 600px;
  padding: 20px;
  margin: auto;
  overflow: auto;
}

.item {
  float: left;
  width: 30%;
  border-bottom: 1px solid black;
  height: 50px;
}

.item-1 {
  background-color: yellow;
}

.item-2 {
  background-color: green;
}

.item-3 {
  background-color: red;
}

.item-2,
.item-3 {
  margin-left: 5%;
}

<div class="common-block">
  <div class="items">
    <div class="item item-1"></div>
    <div class="item item-2"></div>
    <div class="item item-3"></div>
  </div>
</div>


问:
rxJava better way to wait on a specific sequence of values
I wondered what would be the proper way to filter for a certain sequence of values coming through a observable pipe. For example:

I had a problem where I needed to do something after the pipe becomes false but only directly after being true.

```<code>Observable x = Observable.just(false, false, false, true, false);
</code>```

My first approach:

```<code>x
.filter(state -> state)
.switchMap(x)
.filter(state -> !state)
.subscribe(x -> doSomething())

</code>```

Second approach:

```<code>private boolean globalState = false;

private void someFunction() {
   x.map(this::hasTurnedOffAgain)
   .filter(state -> state)
   .subscribe(doSomething)
}

...

private boolean hasTurnedOggAgain(Boolean state) {
    boolean hasTurnedOff= !state && peeping;
    globalState = state;
    return hasFinished;
}
</code>```

I had a third version using the scan operator but I think it was to complex for this simple problem.

Is there a better way to implement something like this? And even more complex  sequences?

Thank you and have a great day!

答:
This is the case when you need a class to save state and not just functions.</p>

```<code>class FilterClass {
    Boolean prev = null;

    boolean filter(Boolean current) {
        // detect false but only directly after being true.
        boolean res = (current==Boolean.FALSE) && (prev==Boolean.TRUE);
        prev = current;
        return res;
    }
}

Observable<Boolean> x = Observable.just(false, false, false, true, false);
FilterClass filter=new FilterClass();

x.filter(filter::filter)
 .subscribe(x -> doSomething(x));
</code>```

Body:
I wondered what would be the proper way to filter for a certain sequence of values coming through a observable pipe. For example:

I had a problem where I needed to do something after the pipe becomes false but only directly after being true.

Observable x = Observable.just(false, false, false, true, false);

My first approach:

x
.filter(state -> state)
.switchMap(x)
.filter(state -> !state)
.subscribe(x -> doSomething())

Second approach:

private boolean globalState = false;

private void someFunction() {
   x.map(this::hasTurnedOffAgain)
   .filter(state -> state)
   .subscribe(doSomething)
}

...

private boolean hasTurnedOggAgain(Boolean state) {
    boolean hasTurnedOff= !state && peeping;
    globalState = state;
    return hasFinished;
}

I had a third version using the scan operator but I think it was to complex for this simple problem.

Is there a better way to implement something like this? And even more complex  sequences?

Thank you and have a great day!

Body:
This is the case when you need a class to save state and not just functions.

class FilterClass {
    Boolean prev = null;

    boolean filter(Boolean current) {
        // detect false but only directly after being true.
        boolean res = (current==Boolean.FALSE) && (prev==Boolean.TRUE);
        prev = current;
        return res;
    }
}

Observable<Boolean> x = Observable.just(false, false, false, true, false);
FilterClass filter=new FilterClass();

x.filter(filter::filter)
 .subscribe(x -> doSomething(x));


问:
Java: Removing content from Json file
I wonder how to remove/empty an .json File.

I have found various Methods online, how to empty an JSON Objekt, however the Objekt that were given were defined and done in the very same file

What i want: To acces a .json File and delete all the content/empty the objekt.

How can i achieve this?
Filepath

EDIT
@Sagar Kharab
the Errors

答:
```<code>File file = new File(Paths.get("Path to your file").toString());
file.setWritable(true);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(Paths.get("Path to your file").toString()));
bufferedOutputStream.write("{}".getBytes());
bufferedOutputStream.flush();
</code>```

I think this should work for you.

Title: Java: Removing content from Json file

Body:
File file = new File(Paths.get("Path to your file").toString());
file.setWritable(true);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(Paths.get("Path to your file").toString()));
bufferedOutputStream.write("{}".getBytes());
bufferedOutputStream.flush();

I think this should work for you.


问:
getting get-credentials requires edit permission error on gcp
I'm trying to setup credentials for kubernetes on my local.

```<code>gcloud container clusters get-credentials ***** --zone **** --project elo-project-267109
</code>```

This query works fine when I tried it from cloud shell, but I got this error when I tried run it from my terminal:

```<code>ERROR: (gcloud.container.clusters.get-credentials) get-credentials requires edit permission on elo-project-267109
</code>```

I've tried this query from admin account as well as default service account also from new service account by assigning editor role and it still doesn't seem to work for me.

i am using macOs Mojave(10.14.6) and gcloud SDK version installed in my system is 274.0.1

i was able to resolve this issue on my local but i was actually trying to build a CI/CD from gitlab and the issue persists there, i have tried using gcloud(279.0.0) image version.

i am new to both gitlab and gcloud. i am trying to build CI/CD pipeline for the first time.

答: It's turned out to be the image version mismatch issue on GitLab. </p>

Body:
I'm trying to setup credentials for kubernetes on my local.

gcloud container clusters get-credentials ***** --zone **** --project elo-project-267109

This query works fine when I tried it from cloud shell, but I got this error when I tried run it from my terminal:

ERROR: (gcloud.container.clusters.get-credentials) get-credentials requires edit permission on elo-project-267109

I've tried this query from admin account as well as default service account also from new service account by assigning editor role and it still doesn't seem to work for me.

i am using macOs Mojave(10.14.6) and gcloud SDK version installed in my system is 274.0.1

i was able to resolve this issue on my local but i was actually trying to build a CI/CD from gitlab and the issue persists there, i have tried using gcloud(279.0.0) image version.

i am new to both gitlab and gcloud. i am trying to build CI/CD pipeline for the first time.