问:
What algorithms there are for failover in a distributed system?
I'm planning on making a distributed database system using a shared-nothing architecture and multiversion concurrency control. Redundancy will be achieved through asynchronous replication (it's allowed to lose some recent changes in case of a failure, as long as the data in the system remains consistent). For each database entry, one node has the master copy (only that node has write access to it), in addition to which one or more nodes have secondary copies of the entry for scalability and redundancy purposes (the secondary copies are read-only). When the master copy of an entry is updated, it is timestamped and sent asynchronously to nodes with secondary copies so that finally they will get the latest version of the entry. The node that has the master copy can change at any time - if another node needs to write that entry, it will request the current owner of the master copy to give that node the ownership of that entry's master copy, and after receiving ownership that node can write the entry (all transactions and writes are local).

Lately I've been thinking about what to do when a node in the cluster goes down, that what strategy to use for failover. Here are some questions. I hope that you would know available alternatives to at least some of them.

What algorithms there are for doing failover in a distributed system?

What algorithms there are for consensus in a distributed system?

How should the nodes in the cluster determine that a node is down?

How should the nodes determine that what database entries had their master copy on the failed node at the time of failure, so that other nodes may recover those entries?

How to decide that which node(s) has the latest secondary copy of some entry?

How to decide that which node's secondary copy should be promoted to be the new master copy?

How to handle it, if the node which was though to be down, suddenly comes back as if nothing happened?

How to avoid split-brain scenarios, where the network is temporarily split into two, and both sides think that the other side has died?

答: This problem was solved by DEC for VMS with the Distributed Lock Manager. Modern solutions are based on this design. Read the Wikipedia article for some current solutions. You should look at OCFS2, which is now part of the Linux kernel.</p>

OwnerDisplayName: Esko Luontola

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Esko Luontola

OwnerDisplayName: Jared Oberhaus

LastEditorDisplayName: Jared Oberhaus


来源: stackexchange

问:
Search for a key in a list of dictionaries
"trip" is a list of dictionaries.  In this instance, the key "trip_block" only appears in the 6th dictionary.  Why doesn't this work:

```<code>trip[:]['trip_block']
TypeError: list indices must be integers or slices, not str
</code>```

But this does work and returns the value:

```<code>trip[5]['trip_block']
</code>```

Since that key appears in different indexes, I would really like to search for it by using trip[:].  I'm trying to use this in an if statement:

```<code>if trip[:]['trip_block']:
</code>```

答:
My suggestion would be to loop through your list. The [:] variant just grabs all of the dictionaries in the list. Take a look at this and see if it will work for you:

```<code>for dictionary in trip: #loop through list of dicts
    if 'trip_block' in dictionary.keys(): #check if key is in this dict
        print(dictionary['trip_block'])
        break #end loop, don't use break if there's more than one dict with this key and you need them all
</code>```

ContentLicense: CC BY-SA 4.0

Body:
"trip" is a list of dictionaries.  In this instance, the key "trip_block" only appears in the 6th dictionary.  Why doesn't this work:

trip[:]['trip_block']
TypeError: list indices must be integers or slices, not str

But this does work and returns the value:

trip[5]['trip_block']

Since that key appears in different indexes, I would really like to search for it by using trip[:].  I'm trying to use this in an if statement:

if trip[:]['trip_block']:

Body:
My suggestion would be to loop through your list. The [:] variant just grabs all of the dictionaries in the list. Take a look at this and see if it will work for you:

for dictionary in trip: #loop through list of dicts
    if 'trip_block' in dictionary.keys(): #check if key is in this dict
        print(dictionary['trip_block'])
        break #end loop, don't use break if there's more than one dict with this key and you need them all


问:
Python loop through list of csv and check for value?
I have five .csv's that have the same fields in the same order that need to be processed as such:

Get list of files

Make each file into a dataframe

Check if a column of letter-number combinations has a specific value (different for each file) eg: check if the number PT333 is in column1 for the file name data1:

```<code>column1   column2    column3
PT389     LA       image.jpg
PT372     NY       image2.jpg
</code>```

If the column has a specific value, print which value it has and the filename/variable name that i've assigned to that file, and then rename that dataframe to output1

I tried to do this, but I don't know how to make it loop and do the same thing for each file.
At the moment it returns the number, but I also want it to return the data frame name, and I also want it to loop through all the files (a to e) to check for all the values in the numbers list.

This is what I have:

```<code>import os
import glob
import pandas as pd
from glob import glob
from os.path import expanduser

home = expanduser("~")
os.chdir(home + f'/files/')

data = glob.glob('data*.csv')
data

# If you have tips on how to loop through these rather than
# have a line for each one, open to feedback
a = pd.read_csv(data[0], encoding='ISO-8859-1', error_bad_lines=False)
b = pd.read_csv(data[1], encoding='ISO-8859-1', error_bad_lines=False)
c = pd.read_csv(data[2], encoding='ISO-8859-1', error_bad_lines=False)
d = pd.read_csv(data[3], encoding='ISO-8859-1', error_bad_lines=False)
e = pd.read_csv(data[4], encoding='ISO-8859-1', error_bad_lines=False)
filenames = [a,b,c,d,e]
filelist= ['a','b','c','d','e']

# I am aware that this part is repetitive. Unsure how to fix this,
# I keep getting errors
# Any help appreciated
numbers = ['PT333', 'PT121', 'PT111', 'PT211', 'PT222']
def type():
    for i in a.column1:
        if i == numbers[0]:
            print(numbers[0])
        elif i == numbers[1]:
            print(numbers[1])
        elif i == numbers[2]:
            print(numbers[2])
        elif i == numbers[3]:
            print(numbers[3])
        elif i == numbers[4]:
            print(numbers[4])
type()
</code>```

Also happy to take any constructive criticism as to how to repeat less code and make things smoother. TIA

答:
Also happy to take any constructive criticism as to how to repeat less
code and make things smoother.

I hope you don't mind that i started with code restructure. it makes explaining the next steps easier

loading the Files Array

Using list builder allows us to iterate through the files and load them into an a list in 1 line. It also has a lot of memory and time benefits.

files = [pd.read_csv(entry, encoding='ISO-8859-1', error_bad_lines=False) for entry in data]

```
<p>more on comprehension</p>
<h2>Type Function</h2>
<p>First we need an argument so that we can give call this function for any given file.  Along with the list we can loop over it with a for each loop.</p>
<h2>Calling the Type Function on Multiple Files</h2>
<p>We use for each loops again here</p>
<pre class="lang-py prettyprint-override"><code>for file in files:
    type(file)
</code>```

more on python for loops

def type(file):
    for value in file.column1:
        if value in numbers:
            print(value)
```
<h1>Result</h1>
<pre class="lang-py prettyprint-override"><code>
import os
import glob
import pandas as pd
from glob import glob
from os.path import expanduser

home = expanduser("~")
os.chdir(home + f'/files/')

#please note that i am use glob instead of glob.glob here.
data = glob('data*.csv')
files = [pd.read_csv(entry, encoding='ISO-8859-1', error_bad_lines=False) for entry in data]

numbers = ['PT333', 'PT121', 'PT111', 'PT211', 'PT222']

def type(file):
    for value in file.column1:
        if value in numbers:
            print(value)

for file in files:
    type(file)

</code>```

Body:
I have five .csv's that have the same fields in the same order that need to be processed as such:

Get list of files

Make each file into a dataframe

Check if a column of letter-number combinations has a specific value (different for each file) eg: check if the number PT333 is in column1 for the file name data1:

column1   column2    column3
PT389     LA       image.jpg
PT372     NY       image2.jpg

If the column has a specific value, print which value it has and the filename/variable name that i've assigned to that file, and then rename that dataframe to output1

I tried to do this, but I don't know how to make it loop and do the same thing for each file.
At the moment it returns the number, but I also want it to return the data frame name, and I also want it to loop through all the files (a to e) to check for all the values in the numbers list.

This is what I have:

import os
import glob
import pandas as pd
from glob import glob
from os.path import expanduser

home = expanduser("~")
os.chdir(home + f'/files/')

data = glob.glob('data*.csv')
data

# If you have tips on how to loop through these rather than
# have a line for each one, open to feedback
a = pd.read_csv(data[0], encoding='ISO-8859-1', error_bad_lines=False)
b = pd.read_csv(data[1], encoding='ISO-8859-1', error_bad_lines=False)
c = pd.read_csv(data[2], encoding='ISO-8859-1', error_bad_lines=False)
d = pd.read_csv(data[3], encoding='ISO-8859-1', error_bad_lines=False)
e = pd.read_csv(data[4], encoding='ISO-8859-1', error_bad_lines=False)
filenames = [a,b,c,d,e]
filelist= ['a','b','c','d','e']

# I am aware that this part is repetitive. Unsure how to fix this,
# I keep getting errors
# Any help appreciated
numbers = ['PT333', 'PT121', 'PT111', 'PT211', 'PT222']
def type():
    for i in a.column1:
        if i == numbers[0]:
            print(numbers[0])
        elif i == numbers[1]:
            print(numbers[1])
        elif i == numbers[2]:
            print(numbers[2])
        elif i == numbers[3]:
            print(numbers[3])
        elif i == numbers[4]:
            print(numbers[4])
type()

Also happy to take any constructive criticism as to how to repeat less code and make things smoother. TIA

Body:
Also happy to take any constructive criticism as to how to repeat less
code and make things smoother.

I hope you don't mind that i started with code restructure. it makes explaining the next steps easier

loading the Files Array

Using list builder allows us to iterate through the files and load them into an a list in 1 line. It also has a lot of memory and time benefits.

files = [pd.read_csv(entry, encoding='ISO-8859-1', error_bad_lines=False) for entry in data]

more on comprehension

Type Function

First we need an argument so that we can give call this function for any given file.  Along with the list we can loop over it with a for each loop.

Calling the Type Function on Multiple Files

We use for each loops again here

for file in files:
    type(file)

more on python for loops

def type(file):
    for value in file.column1:
        if value in numbers:
            print(value)

Result

import os
import glob
import pandas as pd
from glob import glob
from os.path import expanduser

home = expanduser("~")
os.chdir(home + f'/files/')

#please note that i am use glob instead of glob.glob here.
data = glob('data*.csv')
files = [pd.read_csv(entry, encoding='ISO-8859-1', error_bad_lines=False) for entry in data]

numbers = ['PT333', 'PT121', 'PT111', 'PT211', 'PT222']

def type(file):
    for value in file.column1:
        if value in numbers:
            print(value)

for file in files:
    type(file)


问:
How to verify log message in Unit testing for a passing test?
I'm testing an endpoint. I need to figure out how to get the test to pass with my loggerMock. Here is how I currently have the test set up:

```<code>public void GetExceptionReportSessionData_Returns200OK()
        {
            //Arrange
            var response = new RetrieveExceptionReportSessionDatesResponse
            {
                RetrieveExceptionReportSessionDatesResult = string.Empty
            };
            var serviceClient = new Mock<WorkflowService.WorkflowService>();
            serviceClient
                .Setup(x => x.RetrieveExceptionReportSessionDatesAsync(It.IsAny<RetrieveExceptionReportSessionDatesRequest>()))
               .ReturnsAsync(response);

            var loggerMock = new Mock<ILogger>();
            loggerMock.Setup(x => x.LogInfo(null));

            var controller = new ExceptionReportController(loggerMock.Object);

            var ctx = new ControllerContext() { HttpContext = new DefaultHttpContext() };
            ctx.HttpContext.Request.Headers["token"] = "fake_token_here"; //Set header
            controller.ControllerContext = ctx;

            //Act
            var result = controller.GetExceptionReportSessionData();

            //Assert
            var viewResult = Assert.IsType<OkObjectResult>(result);
            Assert.Equal(StatusCodes.Status200OK, viewResult.StatusCode);

        }
</code>```

Here is how the logger is setup in the endpoint when returning a 200:

```<code>if (result != null && result.ExceptionReportLines != null && result.ExceptionReportLines.Count > 0)
            {
                logText = LogFormatter.Format(
                                WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.ViewOrderExceptionReport,
                                "Get Exception Report", "Exception Report retrieved successfully.");
                logger.LogInfo(logText);
            }
            else
            {
                logText = LogFormatter.Format
                                (WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.ViewOrderExceptionReport,
                                "Get Exception Report", "Exception report is empty for the given report filters.");
                logger.LogWarn(logText);
            }

            return Ok(result);
</code>```

My test is set up so that the latter message appears. How can I get the test to pass?

答:
Instead of passing just a null value to Setup of LogInfo method you can use an expression to match the logText string

loggerMock
    .Setup(x => x.LogInfo(It.Is<string>(s => s.Contains("Exception Report retrieved successfully."))))
    .Verifiable();
```

<p>And use <code>Verify()</code> in <code>Assert</code> step</p>

<pre class="lang-cs prettyprint-override"><code>loggerMock.Verify();
</code>```

It ensures, that LogInfo() method in loggerMock was called with string matches the specified expression. Have a look at matching arguments in Moq wiki for more details

Body:
I'm testing an endpoint. I need to figure out how to get the test to pass with my loggerMock. Here is how I currently have the test set up:

public void GetExceptionReportSessionData_Returns200OK()
        {
            //Arrange
            var response = new RetrieveExceptionReportSessionDatesResponse
            {
                RetrieveExceptionReportSessionDatesResult = string.Empty
            };
            var serviceClient = new Mock<WorkflowService.WorkflowService>();
            serviceClient
                .Setup(x => x.RetrieveExceptionReportSessionDatesAsync(It.IsAny<RetrieveExceptionReportSessionDatesRequest>()))
               .ReturnsAsync(response);

            var loggerMock = new Mock<ILogger>();
            loggerMock.Setup(x => x.LogInfo(null));

            var controller = new ExceptionReportController(loggerMock.Object);

            var ctx = new ControllerContext() { HttpContext = new DefaultHttpContext() };
            ctx.HttpContext.Request.Headers["token"] = "fake_token_here"; //Set header
            controller.ControllerContext = ctx;

            //Act
            var result = controller.GetExceptionReportSessionData();

            //Assert
            var viewResult = Assert.IsType<OkObjectResult>(result);
            Assert.Equal(StatusCodes.Status200OK, viewResult.StatusCode);

        }

Here is how the logger is setup in the endpoint when returning a 200:

if (result != null && result.ExceptionReportLines != null && result.ExceptionReportLines.Count > 0)
            {
                logText = LogFormatter.Format(
                                WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.ViewOrderExceptionReport,
                                "Get Exception Report", "Exception Report retrieved successfully.");
                logger.LogInfo(logText);
            }
            else
            {
                logText = LogFormatter.Format
                                (WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.ViewOrderExceptionReport,
                                "Get Exception Report", "Exception report is empty for the given report filters.");
                logger.LogWarn(logText);
            }

            return Ok(result);

My test is set up so that the latter message appears. How can I get the test to pass?

Body:
Instead of passing just a null value to Setup of LogInfo method you can use an expression to match the logText string

loggerMock
    .Setup(x => x.LogInfo(It.Is<string>(s => s.Contains("Exception Report retrieved successfully."))))
    .Verifiable();

And use Verify() in Assert step

loggerMock.Verify();

It ensures, that LogInfo() method in loggerMock was called with string matches the specified expression. Have a look at matching arguments in Moq wiki for more details


答:
trip[:] is a list. Trying to index it like a dictionary isn't going to work. If you want a list of all the values that dictionaries that contain 'trip_block' try:

[d['trip_block'] for d in trip if 'trip_block' in d]
```

Title: Search for a key in a list of dictionaries


问:
How do I create a column in a pandas dataframe using values from two rows?
How do I do this operation?

Initial Df :

```<code>    A B C D
0   0 1 0 0
1   1 1 1 1
2   0 0 1 1
3   0 1 0 1
4   1 1 0 0
5   1 1 1 0
</code>```

Final Df :

```<code>    A B C D Param1 Param2 Param3
0   0 1 0 0      0      0      0
1   1 1 1 1      3      1      0
2   0 0 1 1      0      2      2
3   0 1 0 1      1      1      1
4   1 1 0 0      1      1      1
5   1 1 1 0      1      2      0
</code>```

Basically what I want to do is compare values on two consecutive rows and store the count of those comparison in a new column.

Details of the calculation :

    For the first row (index 0): Param1, Param2, Param3 will be equal to 0

Param1 : This is the count of the number of times a 0 from preview row changed to 1 in the current row, example(look at index 1) : three 0 from index 0 converts to 1, in index 1, hence Param1 for index 1 = 3

Param2 : This is the count of the number of 1 from previous row which remain unchanged in the current row, example(look at index 3) : one 1 from index 2 remains unchanged, in index 3, hence Param2 for index 3 = 1

Param3 : This is the count of the number of 1 from previous row which changed to 0 in the current row, example(look at index 2) : two 1 from index 1 changed to 0, in index 2, hence Param3 for index 3 = 2

答:
You can just thake the diff and check for the above conditions as:

```<code>d = df.diff()
df.assign(param1=d.eq(1).sum(1),
          param2=(d.eq(0)&df.eq(1)).sum(1),
          param3=d.eq(-1).sum(1))

   A  B  C  D  param1  param2  param3
0  0  1  0  0       0       0       0
1  1  1  1  1       3       1       0
2  0  0  1  1       0       2       2
3  0  1  0  1       1       1       1
4  1  1  0  0       1       1       1
5  1  1  1  0       1       2       0
</code>```

Body:
How do I do this operation?

Initial Df :

    A B C D
0   0 1 0 0
1   1 1 1 1
2   0 0 1 1
3   0 1 0 1
4   1 1 0 0
5   1 1 1 0

Final Df :

    A B C D Param1 Param2 Param3
0   0 1 0 0      0      0      0
1   1 1 1 1      3      1      0
2   0 0 1 1      0      2      2
3   0 1 0 1      1      1      1
4   1 1 0 0      1      1      1
5   1 1 1 0      1      2      0

Basically what I want to do is compare values on two consecutive rows and store the count of those comparison in a new column.

Details of the calculation :

    For the first row (index 0): Param1, Param2, Param3 will be equal to 0

Param1 : This is the count of the number of times a 0 from preview row changed to 1 in the current row, example(look at index 1) : three 0 from index 0 converts to 1, in index 1, hence Param1 for index 1 = 3

Param2 : This is the count of the number of 1 from previous row which remain unchanged in the current row, example(look at index 3) : one 1 from index 2 remains unchanged, in index 3, hence Param2 for index 3 = 1

Param3 : This is the count of the number of 1 from previous row which changed to 0 in the current row, example(look at index 2) : two 1 from index 1 changed to 0, in index 2, hence Param3 for index 3 = 2

Body:
You can just thake the diff and check for the above conditions as:

d = df.diff()
df.assign(param1=d.eq(1).sum(1),
          param2=(d.eq(0)&df.eq(1)).sum(1),
          param3=d.eq(-1).sum(1))

   A  B  C  D  param1  param2  param3
0  0  1  0  0       0       0       0
1  1  1  1  1       3       1       0
2  0  0  1  1       0       2       2
3  0  1  0  1       1       1       1
4  1  1  0  0       1       1       1
5  1  1  1  0       1       2       0


问:
Processing unhandled exceptions in ASP.NET Core 3.1
In ASP.NET Core 3.1 a feature was added where unhandled exceptions can be passed onto an instance of ILogger as noted here:
Logging in .NET Core and ASP.NET Core

I have a Server side Blazor website where I want to be able to process these exceptions in a function where I can log them to a database or perhaps send an email.  However I am unable to come up with code to do this based on the provided documentation.  Could someone provide sample code to trap unhandled exceptions?

答:
Doing some playing around, I found a way to do error logging without having to use a third party tool.  Here is my code:

```<code>  public class ExceptionLogger : ILogger
  {
    public IDisposable BeginScope<TState>(TState state)
    {
      return null;
    }

    public bool IsEnabled(LogLevel logLevel)
    {
      return logLevel == LogLevel.Error;
    }

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
    {
      if (logLevel == LogLevel.Error)
      {
        while (exception.InnerException != null)
          exception = exception.InnerException;

        LogException(exception);
      }
    }

    private void LogException(Exception error)
    {
      ...
    }

  public sealed class ExceptionLoggerProvider : ILoggerProvider
  {

    public ILogger CreateLogger(string categoryName)
    {
      return new ExceptionLogger();
    }

    public void Dispose()
    {
    }
  }
</code>```

And in Startup.cs add this:

```<code>public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
  loggerFactory.AddProvider(new ExceptionLoggerProvider());
  ...
</code>```

Body:
Doing some playing around, I found a way to do error logging without having to use a third party tool.  Here is my code:

  public class ExceptionLogger : ILogger
  {
    public IDisposable BeginScope<TState>(TState state)
    {
      return null;
    }

    public bool IsEnabled(LogLevel logLevel)
    {
      return logLevel == LogLevel.Error;
    }

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
    {
      if (logLevel == LogLevel.Error)
      {
        while (exception.InnerException != null)
          exception = exception.InnerException;

        LogException(exception);
      }
    }

    private void LogException(Exception error)
    {
      ...
    }

  public sealed class ExceptionLoggerProvider : ILoggerProvider
  {

    public ILogger CreateLogger(string categoryName)
    {
      return new ExceptionLogger();
    }

    public void Dispose()
    {
    }
  }

And in Startup.cs add this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
  loggerFactory.AddProvider(new ExceptionLoggerProvider());
  ...


问:
Is it possible to integrate Stripe into a chrome extension
I am trying to integrate Stripe but facing the following issues.

When I am loading normally via ngx-stripe, it's giving me this error in the console.

Refused to load the script 'https://js.stripe.com/v3/' because it
  violates the following Content Security Policy directive: "script-src
  'self' 'unsafe-eval'". Note that 'script-src-elem' was not explicitly
  set, so 'script-src' is used as a fallback.

I change content_security_policy in manifest to "script-src 'self' https://js.stripe.com/v3/; object-src 'self' " but it's giving me this error in the console.

Uncaught EvalError: Refused to evaluate a string as JavaScript because
  'unsafe-eval' is not an allowed source of script in the following
  Content Security Policy directive: "script-src 'self'
  https://js.stripe.com/v3/".

After that, I tried adding content_scripts but it's giving me this error and don't let me to import the zip file as well while saying

Could not load javascript '' for content script.

How can I overcome this issue? and is it possible to integrate Stripe into a chrome extension because Stripe only works via https but extension working with chrome://

答:
I ran into these and several subsequent issues integrating stripe into a chrome extension.

Explanation:

I'll first state what I believe was happening. Using the stripe react libraries, I believe they have an inline js call somewhere, causing the error you're seeing about js.stripe.com. I think this would be fixed by adding unsafe-inline into your content_security_policy, but that will not be executed by chrome extensions per the extension CSP.

Solutions:

So here are the various things I did (solving one typically led to having to solve the next set of errors).

I initially had my constent_security_policy set to

```<code>"content_security_policy": "script-src 'self' https://js.stripe.com/v3; object-src 'self';"
</code>```

I was running into your issue above, and so I added the script into my header call, leading my index.html file to be the following:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://js.stripe.com/v3" async></script>
  </head>
  <body>
    <div id="modal-window"></div>
  </body>
</html>
</code>```

That resolved the first set of errors which matched yours above, but it led to the next set of issues:

I then hit a series of errors around Refused to frame ... because it violates the following Content Security Policy directive: "frame-src"..., so I fixed these by adding to my content_security_policy the following:

```<code>frame-src https://js.stripe.com/v3
</code>```

So my final version of my content_security_policy is as follows:

```<code>"content_security_policy": "script-src 'self' https://js.stripe.com/v3; object-src 'self'; frame-src https://js.stripe.com/v3"
</code>```

I hope that does it for you. It took several hours to work through all of that for me.

Body:
I ran into these and several subsequent issues integrating stripe into a chrome extension.

Explanation:

I'll first state what I believe was happening. Using the stripe react libraries, I believe they have an inline js call somewhere, causing the error you're seeing about js.stripe.com. I think this would be fixed by adding unsafe-inline into your content_security_policy, but that will not be executed by chrome extensions per the extension CSP.

Solutions:

So here are the various things I did (solving one typically led to having to solve the next set of errors).

I initially had my constent_security_policy set to

"content_security_policy": "script-src 'self' https://js.stripe.com/v3; object-src 'self';"

I was running into your issue above, and so I added the script into my header call, leading my index.html file to be the following:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://js.stripe.com/v3" async></script>
  </head>
  <body>
    <div id="modal-window"></div>
  </body>
</html>

That resolved the first set of errors which matched yours above, but it led to the next set of issues:

I then hit a series of errors around Refused to frame ... because it violates the following Content Security Policy directive: "frame-src"..., so I fixed these by adding to my content_security_policy the following:

frame-src https://js.stripe.com/v3

So my final version of my content_security_policy is as follows:

"content_security_policy": "script-src 'self' https://js.stripe.com/v3; object-src 'self'; frame-src https://js.stripe.com/v3"

I hope that does it for you. It took several hours to work through all of that for me.


答:
the [:] is a slicing, and what it does depends on the type of trip. If trip is a list, this line will create a shallow copy of the list. For an object of type tuple or a str, it will do nothing (the line will do the same without [:]), and for a (say) NumPy array, it will create a new view to the same data.

You could use the following instead:

```<code>trip = [
{"name": "name1", "trip_block__": 10},
{"name": "name2", "trip_block_": 5},
{"name": "name3", "trip_block": 7}
]

res1 = next(item for item in trip if 'trip_block' in item.keys())
print(res1)

res2 = list(filter(lambda trip_block: 'trip_block' in trip_block.keys(), trip))
print(res2)
</code>```

The first method is finding the dict that has the desired key.

The second one the filter the dict that consist the desired key

Body:
the [:] is a slicing, and what it does depends on the type of trip. If trip is a list, this line will create a shallow copy of the list. For an object of type tuple or a str, it will do nothing (the line will do the same without [:]), and for a (say) NumPy array, it will create a new view to the same data.

You could use the following instead:

trip = [
{"name": "name1", "trip_block__": 10},
{"name": "name2", "trip_block_": 5},
{"name": "name3", "trip_block": 7}
]

res1 = next(item for item in trip if 'trip_block' in item.keys())
print(res1)

res2 = list(filter(lambda trip_block: 'trip_block' in trip_block.keys(), trip))
print(res2)

The first method is finding the dict that has the desired key.

The second one the filter the dict that consist the desired key


问:
Why is Fabric not initialized? java.lang.IllegalStateException: Must Initialize Fabric before using singleton()
I set up Firebase Crashlytics according to Get started with Firebase Crashlytics for my Android app (using Android studio 3.1.3). On my own device as well as on the Emulator, everything works fine and my crashes appear correctly within the Firebase Console. So far so good.

However, there was a crash for one of my app users that was unexpected:

java.lang.IllegalStateException: Must Initialize Fabric before using singleton()

The exception was thrown in another Activity than the MainActivity.

I am aware that you could manually execute the initialization as described here by calling Fabric.with(this, new Crashlytics()); However, there is nothing said about one has to manually initialize the Crashlytics in the Getting Started article mentioned above. I was expecting this is done automatically since all my own tests run fine. So why is it that for some users Crashlytics is set up correctly and for some not?

答:
To anyone who is working with NDK and has the same issue.
Before completing this step from the official documentation
    // Add the Crashlytics NDK dependency (if you have the
    // Firebase Crashlytics dependency, replace it).
initialize it using original dependency.</p>


问:
How to specify the database in an ArangoDb AQL query?
If have multiple databases defined on a particular ArangoDB server, how do I specify the database I'd like an AQL query to run against?

Running the query through the REST endpoint that includes the db name (substituted into [DBNAME] below) ie:

```<code>/_db/[DBNAME]/_api/cursor
</code>```

doesn't seem to work.  The error message says 'unknown path /_db/[DBNAME]/_api/cursor'

Is this something I have to specify in the query itself?

Also: The query I'm trying to run is:

```<code>FOR col in COLLECTIONS() RETURN col.name
</code>```

Fwiw, I haven't found a way to set the "current" database through the REST API.  Also, I'm accessing the REST API from C++ using fuerte.

答:
The docs aren't very helpful right now, so just incase someone is looking for a more complete example, then please consider the following code.</p>

```<code>EventLoopService eventLoopService;
// adjust the connection for your environment!
std::shared_ptr<Connection> conn = ConnectionBuilder().endpoint("http://localhost:8529")
        .authenticationType(AuthenticationType::Basic)
        .user(?)      // enter a user with access
        .password(?)  // enter the password
        .connect(eventLoopService);

// create the request
std::unique_ptr<Request> request = createRequest(RestVerb::Post, ContentType::VPack);

// enter the database name (ensure the user has access)
request->header.database = ?;

// API endpoint to submit AQL queries
request->header.path = "/_api/cursor";

// Create a payload to be submitted to the API endpoint
VPackBuilder builder;
builder.openObject();
// here is your query
builder.add("query", VPackValue("for col in collections() return col.name"));
builder.close();

// add the payload to the request
request->addVPack(builder.slice());

// send the request (blocking)
std::unique_ptr<Response> response = conn->sendRequest(std::move(request));

// check the response code - it should be 201
unsigned int statusCode = response->statusCode();

// slice has the response data
VPackSlice slice = response->slices().front();

std::cout << slice.get("result").toJson() << std::endl;
</code>```

Body:
If have multiple databases defined on a particular ArangoDB server, how do I specify the database I'd like an AQL query to run against?

Running the query through the REST endpoint that includes the db name (substituted into [DBNAME] below) ie:

/_db/[DBNAME]/_api/cursor

doesn't seem to work.  The error message says 'unknown path /_db/[DBNAME]/_api/cursor'

Is this something I have to specify in the query itself?

Also: The query I'm trying to run is:

FOR col in COLLECTIONS() RETURN col.name

Fwiw, I haven't found a way to set the "current" database through the REST API.  Also, I'm accessing the REST API from C++ using fuerte.

Body:
The docs aren't very helpful right now, so just incase someone is looking for a more complete example, then please consider the following code.

EventLoopService eventLoopService;
// adjust the connection for your environment!
std::shared_ptr<Connection> conn = ConnectionBuilder().endpoint("http://localhost:8529")
        .authenticationType(AuthenticationType::Basic)
        .user(?)      // enter a user with access
        .password(?)  // enter the password
        .connect(eventLoopService);

// create the request
std::unique_ptr<Request> request = createRequest(RestVerb::Post, ContentType::VPack);

// enter the database name (ensure the user has access)
request->header.database = ?;

// API endpoint to submit AQL queries
request->header.path = "/_api/cursor";

// Create a payload to be submitted to the API endpoint
VPackBuilder builder;
builder.openObject();
// here is your query
builder.add("query", VPackValue("for col in collections() return col.name"));
builder.close();

// add the payload to the request
request->addVPack(builder.slice());

// send the request (blocking)
std::unique_ptr<Response> response = conn->sendRequest(std::move(request));

// check the response code - it should be 201
unsigned int statusCode = response->statusCode();

// slice has the response data
VPackSlice slice = response->slices().front();

std::cout << slice.get("result").toJson() << std::endl;


问:
How do I input signs for constraints without an error message in R
I would like to include "signs" in my constraints regarding an LP problem.

For example,

Maximize 120X1 + 230X2 + 410X3 + 100X4

580X1 + 600X2 + 800X3 + 300X4 ≤ 1000

0 ≤ X1 ≤ 10

6 ≤ X2 ≤ 10

5 ≤ X3 ≤ 12

0 ≤ X4 ≤ 10

The code is as follows,

library(lpSolve)

```<code>cvec <- c(120,230,410,100) #OF Coefficients
Amat <- rbind(c(580,600,800,300),**c(x<6,x>10)**,c(15),c(22),c(10))
bvec <- c(10000,40,15,22,10)   #RHS values

res <- solveLP(cvec, Amat, bvec, maximum = TRUE, const.dir = c("<=","<=","<=","<=","<="),solve.dual=FALSE, verbose = 4)

print(res)

The output shows : Matrix A must have as many rows as constraints (=elements of vector b) and as many columns as variables (=elements of vector c).
</code>```

Body:
I would like to include "signs" in my constraints regarding an LP problem.

For example,

Maximize 120X1 + 230X2 + 410X3 + 100X4

580X1 + 600X2 + 800X3 + 300X4 ≤ 1000

0 ≤ X1 ≤ 10

6 ≤ X2 ≤ 10

5 ≤ X3 ≤ 12

0 ≤ X4 ≤ 10

The code is as follows,

library(lpSolve)

cvec <- c(120,230,410,100) #OF Coefficients
Amat <- rbind(c(580,600,800,300),**c(x<6,x>10)**,c(15),c(22),c(10))
bvec <- c(10000,40,15,22,10)   #RHS values

res <- solveLP(cvec, Amat, bvec, maximum = TRUE, const.dir = c("<=","<=","<=","<=","<="),solve.dual=FALSE, verbose = 4)

print(res)

The output shows : Matrix A must have as many rows as constraints (=elements of vector b) and as many columns as variables (=elements of vector c).

Body:
Note that 580X1 + 600X2 + 800X3 + 300X4 ≤ 1000 makes the model infeasible. This is a very simple textbook LP solver, and does not seem to handle that very gracefully.

> library(linprog)
> cvec <- c(120,230,410,100) # obj coefficients
> Amat <- rbind(
+ #    x1  x2  x3  x4
+   c(580,600,800,300),    # 580X1 + 600X2 + 800X3 + 300X4 ≤ 10000
+   c(  1,  0,  0,  0),    # x1 <= 10
+   c(  0,  1,  0,  0),    # x2 >= 6
+   c(  0,  1,  0,  0),    # X2 <= 10
+   c(  0,  0,  1,  0),    # x3 >= 5
+   c(  0,  0,  1,  0),    # x3 <= 12
+   c(  0,  0,  0,  1))    # x4 <= 10
> bvec <- c(10000,10,6,10,5,12,10)  # RHS values
> dir  <- c("<=","<=",">=","<=",">=","<=","<=")
> res <- solveLP(cvec, bvec, Amat, maximum = TRUE, const.dir = dir, verbose = 1)
> print(res)

Results of Linear Programming / Linear Optimization

Objective function (Maximum): 4660

Iterations in phase 1: 2
Iterations in phase 2: 1
Solution
  opt
1   0
2   6
3   8
4   0

Basic Variables
    opt
2     6
3     8
S 2  10
S 4   4
S 5   3
S 6   4
S 7  10

Constraints
  actual dir  bvec free    dual dual.reg
1  10000  <= 10000    0  0.5125     2400
2      0  <=    10   10  0.0000       10
3      6  >=     6    0 77.5000        4
4      6  <=    10    4  0.0000        4
5      8  >=     5    3  0.0000        3
6      8  <=    12    4  0.0000        4
7      0  <=    10   10  0.0000       10

All Variables (including slack variables)
    opt cvec    min.c    max.c      marg   marg.reg
1     0  120     -Inf 297.2500 -177.2500    4.13793
2     6  230     -Inf 307.5000        NA         NA
3     8  410  306.667      Inf        NA         NA
4     0  100     -Inf 153.7500  -53.7500    8.00000
S 1   0    0     -Inf   0.5125   -0.5125 2400.00000
S 2  10    0 -177.250      Inf    0.0000         NA
S 3   0    0     -Inf  77.5000  -77.5000    4.00000
S 4   4    0  -77.500      Inf    0.0000         NA
S 5   3    0 -103.333      Inf    0.0000         NA
S 6   4    0       NA 103.3333    0.0000         NA
S 7  10    0  -53.750      Inf    0.0000         NA

>

There are way better tools and solvers around.


问:
How to get my selection box to move properly using PySide2?
Im working on a maya GUI and I created a drag selection box using QRubberBand. Now i'm trying to move it when I hold 'Alt'.
The problem is that when I move the QRubberBand, it moves from the origin
of the box, like this Currently.

What I'm trying to do is get it moving from the end point of the box, like this expected behaviour

.

Here is the code:

```<code>from PySide2 import QtCore, QtGui, QtWidgets

class Ui_Form(QtWidgets.QWidget):
    def __init__(self):
        super(Ui_Form, self).__init__()
        self.rubberBand = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle, self)
        self.setupUi(self)

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            if event.modifiers() == QtCore.Qt.ShiftModifier:
                print 'shift is selected'
            elif event.modifiers() == QtCore.Qt.CTRL:
                print 'Ctrl is selected'
            else:
                print 'Reseting selection'

            self.origin = event.pos()
            self.drag_selection = QtCore.QRect(self.origin, QtCore.QSize())
            self.rubberBand.setGeometry(self.drag_selection)
            self.rubberBand.show()

    def mouseMoveEvent(self, event):
        if event.modifiers() == QtCore.Qt.AltModifier:
            self.rubberBand.move(event.pos())
            self.origin = self.rubberBand.pos()
        else:
            self.drag_selection = QtCore.QRect(self.origin, event.pos()).normalized()
            self.rubberBand.setGeometry(self.drag_selection)

    def mouseReleaseEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.rubberBand.hide()
            if event.modifiers() == QtCore.Qt.CTRL:
                print 'Removing from selection'
            else:
                print 'Selecting'
</code>```

答:
It's trickier than it seems because you can't simply set the position of the rubber band to the cursor, as it would pop it instead of translating it like one would expect.

So instead I opted to use the rubber band's geometry as it was more consistent no matter what direction the user drags in. The idea is when the user pressed the alt key, we save the mouse's current position so that we can calculate a delta as the mouse moves around. With this delta we can move the geometry and set it without getting any pops. It's also possible that the user may repeatedly press and release alt to size the rubber band, move it, resize it, move it, and so on.. So we have to take that into account otherwise it will pop.

Here's a full example that seems to work. Hopefully the comments make it easy to follow the logic:

```<code>from PySide2 import QtCore, QtGui, QtWidgets

class Ui_Form(QtWidgets.QWidget):

    def __init__(self):
        super(Ui_Form, self).__init__()
        self.rubberBand = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle, self)

        # Create variables that will be handling the moving logic.
        self.sourceGeo = None
        self.altPoint = None
        self.delta = None

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.origin = event.pos()
            self.drag_selection = QtCore.QRect(self.origin, QtCore.QSize())
            self.rubberBand.setGeometry(self.drag_selection)
            self.rubberBand.show()

    # Must implement this event to detect when alt gets released
    def keyReleaseEvent(self, event):
        if event.key() == QtCore.Qt.Key_Alt:
            if self.delta is not None:
                # This is important: Add delta to origin so that it shifts it over.
                # This is needed if the user repeatedly pressed alt to move it, otherwise it would pop.
                self.origin += self.delta

                # Reset the rest of the variables.
                self.sourceGeo = None
                self.altPoint = None
                self.delta = None

    def mouseMoveEvent(self, event):
        if event.modifiers() == QtCore.Qt.AltModifier:
            # Get the point where alt is pressed and the selection's current geometry.
            if self.altPoint is None:
                self.sourceGeo = self.rubberBand.geometry()
                self.altPoint = event.pos()

            self.delta = event.pos() - self.altPoint  # Calculate difference from the point alt was pressed to where the cursor is now.
            newGeo = QtCore.QRect(self.sourceGeo)  # Create a copy
            newGeo.moveTopLeft(self.sourceGeo.topLeft() + self.delta)  # Apply the delta onto the geometry to move it.
            self.rubberBand.setGeometry(newGeo)  # Move the selection!
        else:
            self.drag_selection = QtCore.QRect(self.origin, event.pos()).normalized()
            self.rubberBand.setGeometry(self.drag_selection)

    def mouseReleaseEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.rubberBand.hide()

inst = Ui_Form()
inst.show()
</code>```

Body:
Im working on a maya GUI and I created a drag selection box using QRubberBand. Now i'm trying to move it when I hold 'Alt'.
The problem is that when I move the QRubberBand, it moves from the origin
of the box, like this Currently.

What I'm trying to do is get it moving from the end point of the box, like this expected behaviour

.

Here is the code:

from PySide2 import QtCore, QtGui, QtWidgets

class Ui_Form(QtWidgets.QWidget):
    def __init__(self):
        super(Ui_Form, self).__init__()
        self.rubberBand = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle, self)
        self.setupUi(self)

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            if event.modifiers() == QtCore.Qt.ShiftModifier:
                print 'shift is selected'
            elif event.modifiers() == QtCore.Qt.CTRL:
                print 'Ctrl is selected'
            else:
                print 'Reseting selection'

            self.origin = event.pos()
            self.drag_selection = QtCore.QRect(self.origin, QtCore.QSize())
            self.rubberBand.setGeometry(self.drag_selection)
            self.rubberBand.show()

    def mouseMoveEvent(self, event):
        if event.modifiers() == QtCore.Qt.AltModifier:
            self.rubberBand.move(event.pos())
            self.origin = self.rubberBand.pos()
        else:
            self.drag_selection = QtCore.QRect(self.origin, event.pos()).normalized()
            self.rubberBand.setGeometry(self.drag_selection)

    def mouseReleaseEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.rubberBand.hide()
            if event.modifiers() == QtCore.Qt.CTRL:
                print 'Removing from selection'
            else:
                print 'Selecting'

Body:
It's trickier than it seems because you can't simply set the position of the rubber band to the cursor, as it would pop it instead of translating it like one would expect.

So instead I opted to use the rubber band's geometry as it was more consistent no matter what direction the user drags in. The idea is when the user pressed the alt key, we save the mouse's current position so that we can calculate a delta as the mouse moves around. With this delta we can move the geometry and set it without getting any pops. It's also possible that the user may repeatedly press and release alt to size the rubber band, move it, resize it, move it, and so on.. So we have to take that into account otherwise it will pop.

Here's a full example that seems to work. Hopefully the comments make it easy to follow the logic:

from PySide2 import QtCore, QtGui, QtWidgets

class Ui_Form(QtWidgets.QWidget):

    def __init__(self):
        super(Ui_Form, self).__init__()
        self.rubberBand = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle, self)

        # Create variables that will be handling the moving logic.
        self.sourceGeo = None
        self.altPoint = None
        self.delta = None

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.origin = event.pos()
            self.drag_selection = QtCore.QRect(self.origin, QtCore.QSize())
            self.rubberBand.setGeometry(self.drag_selection)
            self.rubberBand.show()

    # Must implement this event to detect when alt gets released
    def keyReleaseEvent(self, event):
        if event.key() == QtCore.Qt.Key_Alt:
            if self.delta is not None:
                # This is important: Add delta to origin so that it shifts it over.
                # This is needed if the user repeatedly pressed alt to move it, otherwise it would pop.
                self.origin += self.delta

                # Reset the rest of the variables.
                self.sourceGeo = None
                self.altPoint = None
                self.delta = None

    def mouseMoveEvent(self, event):
        if event.modifiers() == QtCore.Qt.AltModifier:
            # Get the point where alt is pressed and the selection's current geometry.
            if self.altPoint is None:
                self.sourceGeo = self.rubberBand.geometry()
                self.altPoint = event.pos()

            self.delta = event.pos() - self.altPoint  # Calculate difference from the point alt was pressed to where the cursor is now.
            newGeo = QtCore.QRect(self.sourceGeo)  # Create a copy
            newGeo.moveTopLeft(self.sourceGeo.topLeft() + self.delta)  # Apply the delta onto the geometry to move it.
            self.rubberBand.setGeometry(newGeo)  # Move the selection!
        else:
            self.drag_selection = QtCore.QRect(self.origin, event.pos()).normalized()
            self.rubberBand.setGeometry(self.drag_selection)

    def mouseReleaseEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.rubberBand.hide()

inst = Ui_Form()
inst.show()


问:
Validation error "Bad value apple-touch-icon-precomposed for attribute rel on element link: Keyword apple-touch-icon-precomposed is not registered."
I'm getting this error in w3C HTML 5 validator

Line 9, Column 101: Bad value
  apple-touch-icon-precomposed for
  attribute rel on element link: Keyword
  apple-touch-icon-precomposed is not
  registered. …-icon-precomposed"
  sizes="72x72"
  href="images/sl/touch/m/apple-touch-icon.png">
  Syntax of link type valid for :
  A whitespace-separated list of link
  types listed as allowed on  in
  the HTML specification or listed as an
  allowed on  on the Microformats
  wiki

How to fix this error?

答:
If you move the touch icons into your web root and follow the Apple documentation for naming conventions, you won't actually need to insert the link tags in your HTML and will avoid those validation errors.

The iOS devices will look for the icons in the web root automatically, using the predefined naming conventions and the correct resolution as also outline here. Good luck.

ContentLicense: CC BY-SA 3.0


问:
Props (style) aren't be passed to children
I have this component

And i'm trying to apply background:

Someone know why background isn't appearing?

答:
In your BorderLayout,

```<code>return(
  <View style={props.style}>
    //rest implementation
  </View>
)
</code>```

Please make sure that you have removed props.style from StyleSheet.flatten(...)

Body:
In your BorderLayout,

return(
  <View style={props.style}>
    //rest implementation
  </View>
)

Please make sure that you have removed props.style from StyleSheet.flatten(...)


问:
Numpy matrix multiplications with multiprocessing suddenly slow down as dimension increase
I want to do some large matrix multiplications using multiprocessing.Pool.

Suddenly, when the dimension is higher than 50, it takes an extremely long computation time.

Is there any easy way to be faster?

Here, I don't want to use shared memory like RawArray, because my original code randomly generate the matrix for each time.

The sample code is as follows.

import numpy as np
from time import time
from multiprocessing import Pool
from functools import partial

def f(d):
    a = int(10*d)
    N = int(10000/d)
    for _ in range(N):
        X = np.random.randn(a,10) @ np.random.randn(10,10)
    return X

# Dimensions
ds = [1,2,3,4,5,6,8,10,20,35,40,45,50,60,62,64,66,68,70,80,90,100]

# Serial processing
serial = []
for d in ds:
    t1 = time()
    for i in range(20):
        f(d)
    serial.append(time()-t1)

# Parallel processing
parallel = []
for d in ds:
    t1 = time()
    pool = Pool()
    for i in range(20):
        pool.apply_async(partial(f,d), args=())
    pool.close()
    pool.join()
    parallel.append(time()-t1)

# Plot
import matplotlib.pyplot as plt
plt.title('Matrix multiplication time with 10000/d repetitions')
plt.plot(ds,serial,label='serial')
plt.plot(ds,parallel,label='parallel')
plt.xlabel('d (dimension)')
plt.ylabel('Total time (sec)')
plt.legend()
plt.show()
```

<p>Due to the total computation cost of <code>f(d)</code> is the same for all <code>d</code>, the parallel processing time should be equal. </p>

<p>But the actual output is not.</p>

<p><img src="https://i.stack.imgur.com/D1a1k.png" alt="enter image description here"></p>

<p>System info:</p>

```Linux-4.15.0-47-generic-x86_64-with-debian-stretch-sid
3.6.8 |Anaconda custom (64-bit)| (default, Dec 30 2018, 01:22:34)
[GCC 7.3.0]
Intel(R) Core(TM) i9-7940X CPU @ 3.10GHz
```

NOTE I want to use parallel computation as a complicated internal simulation (like @), not sending data to the child process.

答:
I just found an explanation here: https://github.com/numpy/numpy/issues/10145.
Looks like the CPU caching gets messed up when you have conflicting MKL matrix multiplications going at the same time. </p>

Body:
I want to do some large matrix multiplications using multiprocessing.Pool.

Suddenly, when the dimension is higher than 50, it takes an extremely long computation time.

Is there any easy way to be faster?

Here, I don't want to use shared memory like RawArray, because my original code randomly generate the matrix for each time.

The sample code is as follows.

import numpy as np
from time import time
from multiprocessing import Pool
from functools import partial

def f(d):
    a = int(10*d)
    N = int(10000/d)
    for _ in range(N):
        X = np.random.randn(a,10) @ np.random.randn(10,10)
    return X

# Dimensions
ds = [1,2,3,4,5,6,8,10,20,35,40,45,50,60,62,64,66,68,70,80,90,100]

# Serial processing
serial = []
for d in ds:
    t1 = time()
    for i in range(20):
        f(d)
    serial.append(time()-t1)

# Parallel processing
parallel = []
for d in ds:
    t1 = time()
    pool = Pool()
    for i in range(20):
        pool.apply_async(partial(f,d), args=())
    pool.close()
    pool.join()
    parallel.append(time()-t1)

# Plot
import matplotlib.pyplot as plt
plt.title('Matrix multiplication time with 10000/d repetitions')
plt.plot(ds,serial,label='serial')
plt.plot(ds,parallel,label='parallel')
plt.xlabel('d (dimension)')
plt.ylabel('Total time (sec)')
plt.legend()
plt.show()

Due to the total computation cost of f(d) is the same for all d, the parallel processing time should be equal.

But the actual output is not.

System info:

Linux-4.15.0-47-generic-x86_64-with-debian-stretch-sid
3.6.8 |Anaconda custom (64-bit)| (default, Dec 30 2018, 01:22:34)
[GCC 7.3.0]
Intel(R) Core(TM) i9-7940X CPU @ 3.10GHz

NOTE I want to use parallel computation as a complicated internal simulation (like @), not sending data to the child process.


问:
Best way to remove non uniques values from an array, keep the order, and not use vectors?
I apologize if this has been asked, but I ran into a coding question, which was supposed to be simple but I struggled on. Please provide a link if already answered (I may just be bad at searching).

Question: Given the sample code fill in the function to return only unique values in the array. Values must keep order.

Example Input : 1, 2, 3, 10, 4, 3, 2, 10, 1, 11, 6

Example Output: 1 2 3 10 4 11 6

Below is my solution, but I can not seem to think of an easy solution that does not include the use of a vector to store unique values. The tester did not like the use of a vector so I can only assume additional headers / libraries were unacceptable. Any other solutions? I am guessing the tester was looking for the array to be filtered in place.

```<code>#include <iostream>
#include <vector> //I was not allowed to add this...

//Function to fill in...
int fxn(int *a, int size)
{
  std::vector<int> temp;
  for(int i(0); i < size; ++i)
  {
    bool found(false);
    for(auto j : temp)
    {
      if( j == a[i])
      {
        found = true;
        break;
      }
    }

    if(!found)
    {
      temp.push_back(a[i]);
    }
  }

  int *ptr_a = &a[0];
  for(auto j : temp)
  {
    *ptr_a = j;
    ++ptr_a;
  }

  return size - temp.size();
}

//The rest untochable...
void print(int *a, int size)
{
  for(int i(0); i < size; ++i)
  {
    std::cout << a[i] << " ";
  }

  std::cout << std::endl;
}

int main(void)
{

  int a[] = { 1, 2, 3, 10, 4, 3, 2, 10, 1, 11, 6 };
  int size = 11;

  int count = fxn(a, size);
  print(a, size - count);

  return 0;
}
</code>```

答:
Admittedly, this problem would be easier if you could use external libraries, but if you are certain you cannot, it is still solvable.

I read the question incorrectly the first time. Here is a link to as similar question.

```<code>#include<iostream>
using namespace std;

int removeDuplicates(int arr[], int n)
{
    int j = 0;

    for (int i=0; i < n; i++){
        for(int j=0;j<i;j++){

            if(arr[i]==arr[j]){
                n--;
                for (int k=i; k<n; k++){
                    arr[k]=arr[k+1];
                }
                i--;     // you forgot to decrement i
            }
        }
    }

    return n;
}
</code>```

Body:
I apologize if this has been asked, but I ran into a coding question, which was supposed to be simple but I struggled on. Please provide a link if already answered (I may just be bad at searching).

Question: Given the sample code fill in the function to return only unique values in the array. Values must keep order.

Example Input : 1, 2, 3, 10, 4, 3, 2, 10, 1, 11, 6

Example Output: 1 2 3 10 4 11 6

Below is my solution, but I can not seem to think of an easy solution that does not include the use of a vector to store unique values. The tester did not like the use of a vector so I can only assume additional headers / libraries were unacceptable. Any other solutions? I am guessing the tester was looking for the array to be filtered in place.

#include <iostream>
#include <vector> //I was not allowed to add this...

//Function to fill in...
int fxn(int *a, int size)
{
  std::vector<int> temp;
  for(int i(0); i < size; ++i)
  {
    bool found(false);
    for(auto j : temp)
    {
      if( j == a[i])
      {
        found = true;
        break;
      }
    }

    if(!found)
    {
      temp.push_back(a[i]);
    }
  }

  int *ptr_a = &a[0];
  for(auto j : temp)
  {
    *ptr_a = j;
    ++ptr_a;
  }

  return size - temp.size();
}

//The rest untochable...
void print(int *a, int size)
{
  for(int i(0); i < size; ++i)
  {
    std::cout << a[i] << " ";
  }

  std::cout << std::endl;
}

int main(void)
{

  int a[] = { 1, 2, 3, 10, 4, 3, 2, 10, 1, 11, 6 };
  int size = 11;

  int count = fxn(a, size);
  print(a, size - count);

  return 0;
}

Body:
Admittedly, this problem would be easier if you could use external libraries, but if you are certain you cannot, it is still solvable.

I read the question incorrectly the first time. Here is a link to as similar question.

#include<iostream>
using namespace std;

int removeDuplicates(int arr[], int n)
{
    int j = 0;

    for (int i=0; i < n; i++){
        for(int j=0;j<i;j++){

            if(arr[i]==arr[j]){
                n--;
                for (int k=i; k<n; k++){
                    arr[k]=arr[k+1];
                }
                i--;     // you forgot to decrement i
            }
        }
    }

    return n;
}


问:
Artillery.IO Logging and Debugging
I'm trying out Artillery.io (http://artillery.io) as a load and performance tool, but I can't seem to get the debugging working.

I'm seeing the output and reports get generated, but for certain HTTP responses (404/401/500.x) I want to see the packets sent and responses received retrospectively.

The documentation at https://artillery.io/docs/debugging.html#logging-everything says that I can run

```<code>set DEBUG=http,http:capture,http:response
</code>```

and then launch my script using the run command (I'm on Windows).

This makes no difference at all, there is no tracing of packets sent/received in either the console or the generated report.

Anyone know how to get artillery to trace out what its doing, request by request and response? Preferably added to the report file, but I'll take console alone if I have to.

答: Update: looks like http debugging was changed. See https://artillery.io/docs/examples/#debugging-http-tests for the revised debugging documentation.</p>

Title: Artillery.IO Logging and Debugging

Body:
I'm trying out Artillery.io (http://artillery.io) as a load and performance tool, but I can't seem to get the debugging working.

I'm seeing the output and reports get generated, but for certain HTTP responses (404/401/500.x) I want to see the packets sent and responses received retrospectively.

The documentation at https://artillery.io/docs/debugging.html#logging-everything says that I can run

set DEBUG=http,http:capture,http:response

and then launch my script using the run command (I'm on Windows).

This makes no difference at all, there is no tracing of packets sent/received in either the console or the generated report.

Anyone know how to get artillery to trace out what its doing, request by request and response? Preferably added to the report file, but I'll take console alone if I have to.


Title: Extract some part of data from json using regex?

Body:
My json looks like this.

{"d":2,"g":"(0.006, 1.000, -0.013, 0.584)","o":"0.081","t":"{\"Items\":[{\"f\":9,\"b\":{\"i\":72057594037929100,\"j\":[{\"s\":2,\"p\":\"(4.342, 76.616, 235.211)\",\"q\":\"(0.5, 0.2)\",\"o\":\"(0.000, 0.000, 0.000, 0.000)\"},{\"s\":2,\"p\":\"(6.307, 63.818, 237.308)\",\"q\":\"(0.5, 0.3)\",\"o\":\"(0.009, 0.988, -0.075, -0.137)\"},{\"s\":2,\"p\":\"(-6.896, 54.626, 241.427)\",\"q\":\"(0.5, 0.3)\",\"o\":\"(0.780, -0.615, -0.055, 0.103)\"},{\"s\":2,\"p\":\"(19.263, 53.431, 233.939)\",\"q\":\"(0.6, 0.3)\",\"o\":\"(0.790, 0.587, -0.161, -0.071)\"},{\"s\":2,\"p\":\"(-9.756, 36.885, 247.644)\",\"q\":\"(0.5, 0.4)\",\"o\":\"(0.708, -0.170, -0.682, 0.067)\"},{\"s\":2,\"p\":\"(32.613, 40.022, 228.385)\",\"q\":\"(0.6, 0.3)\",\"o\":\"(0.869, 0.301, 0.292, -0.263)\"},{\"s\":2,\"p\":\"(-10.174, 26.525, 230.599)\",\"q\":\"(0.5, 0.4)\",\"o\":\"(0.838, -0.145, 0.238, -0.468)\"},{\"s\":2,\"p\":\"(18.386, 34.191, 215.852)\",\"q\":\"(0.6, 0.3)\",\"o\":\"(-0.159, -0.297, 0.789, 0.515)\"},{\"s\":2,\"p\":\"(-8.486, 24.193, 232.817)\",\"q\":\"(0.5, 0.4)\",\"o\":\"(0.310, 0.404, 0.851, -0.126)\"},{\"s\":2,\"p\":\"(18.643, 35.331, 216.844)\",\"q\":\"(0.6, 0.3)\",\"o\":\"(0.296, -0.315, -0.201, 0.879)\"},{\"s\":2,\"p\":\"(6.328, 57.728, 238.241)\",\"q\":\"(0.5, 0.3)\",\"o\":\"(0.006, 0.989, -0.054, -0.137)\"},{\"s\":2,\"p\":\"(6.372, 39.007, 240.290)\",\"q\":\"(0.5, 0.3)\",\"o\":\"(0.004, 0.990, -0.038, -0.136)\"},{\"s\":2,\"p\":\"(6.421, 13.412, 242.259)\",\"q\":\"(0.5, 0.4)\",\"o\":\"(0.004, 0.990, -0.038, -0.135)\"},{\"s\":2,\"p\":\"(0.544, 13.591, 240.701)\",\"q\":\"(0.5, 0.4)\",\"o\":\"(-0.687, 0.714, -0.116, 0.066)\"},{\"s\":2,\"p\":\"(12.142, 12.902, 237.523)\",\"q\":\"(0.5, 0.4)\",\"o\":\"(0.680, 0.649, -0.268, -0.212)\"},{\"s\":2,\"p\":\"(-8.352, -7.874, 228.395)\",\"q\":\"(0.5, 0.5)\",\"o\":\"(-0.438, -0.137, 0.847, 0.270)\"},{\"s\":2,\"p\":\"(12.378, -15.666, 235.192)\",\"q\":\"(0.5, 0.5)\",\"o\":\"(0.794, -0.021, 0.606, -0.035)\"},{\"s\":2,\"p\":\"(-1.073, -37.353, 238.874)\",\"q\":\"(0.5, 0.6)\",\"o\":\"(-0.659, 0.050, 0.717, -0.222)\"},{\"s\":2,\"p\":\"(15.474, -46.941, 242.354)\",

And I want to extract only the numbers which starts inside the "p\": for example "p\":\"(4.342, 76.616, 235.211)\"

I tried using regex, but it is returning null output.

Code that I tried to run

import re

with open('skeleton.json') as file:

    for line in file:
       headings = re.search('\\\"p\\\":\\\"\([\d, \-.]+\)\\\"', line)
       print(headings)

Body: Try searching for \\\\\"p\\\\\":\\\\\"\([\d, \-.]+\)\\\\\".  So something like re.search('\\\\\"p\\\\\":\\\\\"\([\d, \-.]+\)\\\\\"', XXX), where XXX is your json.


问:
Need to use VFP code to display PDF files in VFP Windows
Users running my Foxpro 9.0 app generate a lot of PDF files. I need to show PDF files in a window.  I installed Google Chrome and set it as the default for PDFs and when double clicking on a PDF in file explorer it comes right up in Chrome.  I need to make that happen with Foxpro code.  Any ideas?</p>

答: Thanks for all the suggestions.  The ShellExecute works great.  However, it will not work when my VFP program is running in the Thinfinity web server. The fix is to convert the PDF to a JPG or PNG before saving them.  The PNG files take 1/3 the space of JPG files. I'm using PDFill with it's command line utility to convert them.</p>


问:
EditText settext on addTextChangedListener(TextWatcher) infite loop in Kotlin
I am using Kotlin. I need check EditText value &  add some logic to the value & set the value to same EditText every character. But unfortunately it is going infinite loop. I have use bellow code.

```<code>    EditText amount_txtAmount = findViewById(R.id.amount_txtAmount)

    amount_txtAmount.addTextChangedListener(object : TextWatcher {
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

        }

        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

        }

        override fun afterTextChanged(s: Editable) {
            if (amount_txtAmount.text.toString().length > 0) {

                    var amount1 =   ValidationUtil.commaSeparateAmount(amount_txtAmount.text.toString())
                    Log.e("formatAmount-->", amount1)
                    amount_txtAmount.setText(amount1)

           }
        }
    })
</code>```

Please help how to overcome infinite loop.

答:
var amount1 = ValidationUtil.commaSeparateAmount(amount_txtAmount.text.toString())
Log.e("formatAmount-->", amount1)
amount_txtAmount.setText(amount1)
```

This is a reason, if you need to constraint length of input you can set InputFilter to you EditText to make user can not input greater some value.

Body:
I am using Kotlin. I need check EditText value &  add some logic to the value & set the value to same EditText every character. But unfortunately it is going infinite loop. I have use bellow code.

    EditText amount_txtAmount = findViewById(R.id.amount_txtAmount)

    amount_txtAmount.addTextChangedListener(object : TextWatcher {
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

        }

        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

        }

        override fun afterTextChanged(s: Editable) {
            if (amount_txtAmount.text.toString().length > 0) {

                    var amount1 =   ValidationUtil.commaSeparateAmount(amount_txtAmount.text.toString())
                    Log.e("formatAmount-->", amount1)
                    amount_txtAmount.setText(amount1)

           }
        }
    })

Please help how to overcome infinite loop.

Body:
var amount1 = ValidationUtil.commaSeparateAmount(amount_txtAmount.text.toString())
Log.e("formatAmount-->", amount1)
amount_txtAmount.setText(amount1)

This is a reason, if you need to constraint length of input you can set InputFilter to you EditText to make user can not input greater some value.


问:
A little confused with Big O
So I have a quick question on how to verify the big O of a function.

for example: a quicksort algorithm sorting an array of 5000000 element yields a time interval of 0.008524 seconds, running the same algorithm with 1000000 element yields 0.017909.  How would I check the big O if my quicksort is/is not big O of n*log(n)??

What I think I understand: n increased by 2  thus the runtime should increase by 2*log(2)?

f(n) = 0.008524 -> n log (n)

f(2n) = 0.017909 ->2n*log(2n)

答:
Two data points aren't really enough.

However, 2*n*log(2*n) = 2*n*(log(n) + log(2)), so you can see that the multiplier should be approximately 2*log(2) when you double the size.  That looks plausible for the numbers you gave.  You should add a few more points and double check.

Note that there is likely to be some constant term in your timing, at least if you include program startup in there - it might be significant.  If, on the other hand, you only time the sorting phase without the startup, it is more accurate.  You should repeat the process over many permutations of the input data to ensure you get a representative set of values.

Title: A little confused with Big O


问:
How can I fix this Combinations calculating(nCr) program?
I have created this simple program using c to calculate combinations. But whenever I enter large value like 20,30,40.. for variable 'n' and for 'r' program output is not true. But this program works fine with small numbers like 5,7,10... How can i fix this problem to find combinations even input big numbers for n and r ?

Also I wanna use nCr = n-1Cr + n-1Cr-1 rule in this program and I am using C language

```<code>#include <stdio.h>

int fact(int i){

    if(i <= 1){
        return 1;
    }
    return i * fact(i-1);
}

int nCr(int n,int r){

    int nCr;

    if(r == 0 || n == r){
        nCr = 1;
    }else{

        nCr = (fact(n-1)/(fact(r) * fact(n-1-r))) + (fact(n-1)/(fact(r-1) * fact(n-r)));

    }
    return nCr;
}

int main(){

    int n,r;

    printf("Enter n : ");
    scanf("%d",&n);
    printf("Enter r : ");
    scanf("%d",&r);

    printf("nCr value : %d\n",nCr(n,r));
    return 0;
}
</code>```

Thank you so much for your answers.

答:
For large numbers use long long int instead of int.
Try this instead:

```<code>#include <stdio.h>

long long int fact(long long int i){

if(i <= 1){
    return 1;
}
   return i * fact(i-1);
}

long long int nCr(long long int n,long long int r){

long long int nCr;

if(r == 0 || n == r){
    nCr = 1;
}else{

    nCr = (fact(n-1)/(fact(r) * fact(n-1-r))) + (fact(n-1)/(fact(r-1) * fact(n-r)));

}
    return nCr;
}

int main(){

    long long int n,r;

    printf("Enter n : ");
    scanf("%lld",&n);
    printf("Enter r : ");
    scanf("%lld",&r);

    printf("nCr value : %lld\n",nCr(n,r));
    return 0;
}
</code>```

Body:
I have created this simple program using c to calculate combinations. But whenever I enter large value like 20,30,40.. for variable 'n' and for 'r' program output is not true. But this program works fine with small numbers like 5,7,10... How can i fix this problem to find combinations even input big numbers for n and r ?

Also I wanna use nCr = n-1Cr + n-1Cr-1 rule in this program and I am using C language

#include <stdio.h>

int fact(int i){

    if(i <= 1){
        return 1;
    }
    return i * fact(i-1);
}

int nCr(int n,int r){

    int nCr;

    if(r == 0 || n == r){
        nCr = 1;
    }else{

        nCr = (fact(n-1)/(fact(r) * fact(n-1-r))) + (fact(n-1)/(fact(r-1) * fact(n-r)));

    }
    return nCr;
}

int main(){

    int n,r;

    printf("Enter n : ");
    scanf("%d",&n);
    printf("Enter r : ");
    scanf("%d",&r);

    printf("nCr value : %d\n",nCr(n,r));
    return 0;
}

Thank you so much for your answers.

Body:
For large numbers use long long int instead of int.
Try this instead:

#include <stdio.h>

long long int fact(long long int i){

if(i <= 1){
    return 1;
}
   return i * fact(i-1);
}

long long int nCr(long long int n,long long int r){

long long int nCr;

if(r == 0 || n == r){
    nCr = 1;
}else{

    nCr = (fact(n-1)/(fact(r) * fact(n-1-r))) + (fact(n-1)/(fact(r-1) * fact(n-r)));

}
    return nCr;
}

int main(){

    long long int n,r;

    printf("Enter n : ");
    scanf("%lld",&n);
    printf("Enter r : ");
    scanf("%lld",&r);

    printf("nCr value : %lld\n",nCr(n,r));
    return 0;
}


问:
How to print a word from list upon executing a bot command
So I have this list of some cars below, and when I type in !car, the bot should be able to send only one word from the list but in an embedded message.
So every time I type in this command, the bot sends a single word, until it reaches the end of the list (ascending order).

Example:

List of cars: BMW, Mercedes, Porsche, Honda, Pontiac

User: !car

Bot: BMW

User: !car

Bot: Mercedes

Etc...

Here's my code: How can I modify it to fulfill my request?

```<code>import discord

client = discord.Client()

@client.event
async def on_message(message):

    cars = ['BMW', 'Mercedes', 'Porsche', 'Honda', 'Pontiac']

    if message.content == '!car'
        embed = discord.Embed(title=cars, description=None, color=0xfffb00)
        # It prints the whole list, I would like only one word from the list.
        await message.channel.send(content=None, embed=embed)

client.run('token')
</code>```

Any help would be appreciated

答:
Try an index-based approach. This will work for a list of any size > 0.

import discord

client = discord.Client()

i = 0
@client.event
async def on_message(message):
    global i # omitting this breaks the code! be careful!

    cars = ['BMW', 'Mercedes', 'Porsche', 'Honda', 'Pontiac']

    if message.content == '!car'
        car = cars[i]
        i += 1
        i = 0 if i == len(cars) else i
        embed = discord.Embed(title=car, description=None, color=0xfffb00)
        await message.channel.send(embed=embed)

client.run('token')
```

Body:
So I have this list of some cars below, and when I type in !car, the bot should be able to send only one word from the list but in an embedded message.
So every time I type in this command, the bot sends a single word, until it reaches the end of the list (ascending order).

Example:

List of cars: BMW, Mercedes, Porsche, Honda, Pontiac

User: !car

Bot: BMW

User: !car

Bot: Mercedes

Etc...

Here's my code: How can I modify it to fulfill my request?

import discord

client = discord.Client()

@client.event
async def on_message(message):

    cars = ['BMW', 'Mercedes', 'Porsche', 'Honda', 'Pontiac']

    if message.content == '!car'
        embed = discord.Embed(title=cars, description=None, color=0xfffb00)
        # It prints the whole list, I would like only one word from the list.
        await message.channel.send(content=None, embed=embed)

client.run('token')

Any help would be appreciated


问:
insert new field in mongodb database
I'm a beginner in mongodb and pymongo and I'm working on a project where I have a students mongodb collection . What I want is to add a new field and specifically an adrress of a student to each element in my collection (the field is obviously added everywhere as null and will be filled by me later).

However when I try using this specific example to add a new field I get a the following syntax error:

```<code> client = MongoClient('mongodb://localhost:27017/') #connect to local mongodb

 db = client['InfoSys']   #choose infosys database
 students = db['Students']

 students.update(  {  $set : {"address":1} }  ) #set address field to every column (error happens here)
</code>```

How can I fix this error?

答:
You are using the update operation in wrong manner. Update operation is having the following syntax:

db.collection.update(
   <query>,
   <update>,
   <options>
)
```

<p>The main parameter <code><query></code> is not at all mentioned. It has to be at least empty like <code>{}</code>, In your case the following query will work:</p>

<pre class="lang-js prettyprint-override"><code>db.students.update(
  {}, // To update the all the documents.
  {$set : {"address": 1}}, // Update the address field.
  {multi: true} // To do multiple updates, otherwise Mongo will just update the first matching document.
)
</code>```

So, in python, you can use update_many to achieve this. So, it will be like:

students.update_many(
  {},
  {"$set" : {"address": 1}}
)
```

You can read more about this operation here.

Title: insert new field in mongodb database

Body:
I'm a beginner in mongodb and pymongo and I'm working on a project where I have a students mongodb collection . What I want is to add a new field and specifically an adrress of a student to each element in my collection (the field is obviously added everywhere as null and will be filled by me later).

However when I try using this specific example to add a new field I get a the following syntax error:

 client = MongoClient('mongodb://localhost:27017/') #connect to local mongodb

 db = client['InfoSys']   #choose infosys database
 students = db['Students']

 students.update(  {  $set : {"address":1} }  ) #set address field to every column (error happens here)

How can I fix this error?

Body:
You are using the update operation in wrong manner. Update operation is having the following syntax:

db.collection.update(
   <query>,
   <update>,
   <options>
)

The main parameter <query> is not at all mentioned. It has to be at least empty like {}, In your case the following query will work:

db.students.update(
  {}, // To update the all the documents.
  {$set : {"address": 1}}, // Update the address field.
  {multi: true} // To do multiple updates, otherwise Mongo will just update the first matching document.
)

So, in python, you can use update_many to achieve this. So, it will be like:

students.update_many(
  {},
  {"$set" : {"address": 1}}
)

You can read more about this operation here.


问:
I'm writing a crud application using SpringBoot and Jquery with Ajax. And I'm getting the following exception
I'm writing a crud application using SpringBoot and Jquery with Ajax. And I'm getting the following exception:
(I'm getting an exception when I'm trying to add a new user)

```<code>.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of
`ru.javamentor.predproject3.model.User` out of START_ARRAY token; nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of
`ru.javamentor.predproject3.model.User` out of START_ARRAY token
at [Source: (PushbackInputStream); line: 1, column: 1]]
</code>```

Here is my js. GET method works fine.

```<code>$(document).ready(function () {
  gettingListOfUsers();
  addingUser();
});

function gettingListOfUsers() {
  $.ajax({
     url: '/rest/users',
     type: 'GET',
     dataType: 'json',
     success: function (listOfUsers) {
        let userData = '';
        $.each(listOfUsers, function (index, user) {
            userData += '<tr>';
            userData += '<td>' + user.id + '</td>';
            userData += '<td>' + user.firstName + '</td>';
            userData += '<td>' + user.secondName + '</td>';
            userData += '<td>' + user.email + '</td>';
            userData += '<td>' + user.role + '</td>';
            userData += '<td> <button class="btn btn-info" data-toggle="modal">update</button> ' +
                '<a class="btn btn-danger" onclick="if (!(confirm(\'Are you sure you want to delete this user?\'))) ' +
                'return false">delete</a></td>';

            userData += '</tr>';
        });

        $('#userTable2').html(userData);
    },

    error: function (error) {
        alert("Error");
    }
})
}

function addingUser() {
$('#addingButton').on('click', function (event) {
    event.preventDefault();

    const addingFormData = $('#addingUserForm').serializeArray();
    // alert(addingFormData.length);

    $.ajax({
        url: '/rest/adding',
        type: 'POST',
        data: JSON.stringify(addingFormData),
        dataType: 'json',
        contentType: "application/json",
        success: function (responseData, status, jqXHR) {
            alert('User has been added successfully');
            gettingListOfUsers();
        },
        error: function () {
            alert('Error');
        }
    })
})
}
</code>```

My programm don't even get till controller. It falls in error block

@PostMapping("/adding")

```<code>public ResponseEntity<User> addingPost(@RequestBody User user) {

    HttpHeaders httpHeaders = new HttpHeaders();

    user.setPassword(passwordEncoder.encode(user.getPassword()));

    userService.addUser(user);

    return new ResponseEntity<>(user, httpHeaders, HttpStatus.CREATED);
}
</code>```

答:
I could have a better idea if you post your controller.
It seems like you are deserializing a json string into json object.
If that is true, you have a malformed json string, it is possible you don't have initial curly brace.

EDITED

I double checked and I think your issue is in JS code.

```<code>$('#addingButton').on('click', function (event) {
    event.preventDefault();

    const addingFormData = $('#addingUserForm').serialize();
    // alert(addingFormData.length);

    $.ajax({
        url: '/rest/adding',
        type: 'POST',
        data: addingFormData,
        dataType: 'json',
        contentType: "application/json",
        success: function (responseData, status, jqXHR) {
            alert('User has been added successfully');
            gettingListOfUsers();
        },
        error: function () {
            alert('Error');
        }
    })
})
</code>```

Body:
I'm writing a crud application using SpringBoot and Jquery with Ajax. And I'm getting the following exception:
(I'm getting an exception when I'm trying to add a new user)

.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of
`ru.javamentor.predproject3.model.User` out of START_ARRAY token; nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of
`ru.javamentor.predproject3.model.User` out of START_ARRAY token
at [Source: (PushbackInputStream); line: 1, column: 1]]

Here is my js. GET method works fine.

$(document).ready(function () {
  gettingListOfUsers();
  addingUser();
});

function gettingListOfUsers() {
  $.ajax({
     url: '/rest/users',
     type: 'GET',
     dataType: 'json',
     success: function (listOfUsers) {
        let userData = '';
        $.each(listOfUsers, function (index, user) {
            userData += '
';
            userData += '' + user.id + '	';
            userData += '' + user.firstName + '	';
            userData += '' + user.secondName + '	';
            userData += '' + user.email + '	';
            userData += '' + user.role + '	';
            userData += ' <button class="btn btn-info" data-toggle="modal">update</button> ' +
                'delete	';

            userData += '
';
        });

        $('#userTable2').html(userData);
    },

    error: function (error) {
        alert("Error");
    }
})
}

function addingUser() {
$('#addingButton').on('click', function (event) {
    event.preventDefault();

    const addingFormData = $('#addingUserForm').serializeArray();
    // alert(addingFormData.length);

    $.ajax({
        url: '/rest/adding',
        type: 'POST',
        data: JSON.stringify(addingFormData),
        dataType: 'json',
        contentType: "application/json",
        success: function (responseData, status, jqXHR) {
            alert('User has been added successfully');
            gettingListOfUsers();
        },
        error: function () {
            alert('Error');
        }
    })
})
}

My programm don't even get till controller. It falls in error block

@PostMapping("/adding")

public ResponseEntity<User> addingPost(@RequestBody User user) {

    HttpHeaders httpHeaders = new HttpHeaders();

    user.setPassword(passwordEncoder.encode(user.getPassword()));

    userService.addUser(user);

    return new ResponseEntity<>(user, httpHeaders, HttpStatus.CREATED);
}

Body:
I could have a better idea if you post your controller.
It seems like you are deserializing a json string into json object.
If that is true, you have a malformed json string, it is possible you don't have initial curly brace.

EDITED

I double checked and I think your issue is in JS code.

$('#addingButton').on('click', function (event) {
    event.preventDefault();

    const addingFormData = $('#addingUserForm').serialize();
    // alert(addingFormData.length);

    $.ajax({
        url: '/rest/adding',
        type: 'POST',
        data: addingFormData,
        dataType: 'json',
        contentType: "application/json",
        success: function (responseData, status, jqXHR) {
            alert('User has been added successfully');
            gettingListOfUsers();
        },
        error: function () {
            alert('Error');
        }
    })
})


问:
Angular 6: Update Table in one component after adding data to another component
I have create a single page application in Angular 6 with two components. The are communicating to a web-server through a data service.
One component lists all the item, the other component allows the user to add an item to that list.
Interestingly, by calling getItems after deleting one item in the list component it refreshes the list, which calling get MatTableDataSource attribute from the create component does not.
Any points are hugely appreciated. Thanks.

List component:

```<code>import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { MatTableDataSource } from '@angular/material/table';

import { Item } from '../items.model';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {

  public items = new MatTableDataSource<Item>();
  private displayedColumns = ['name', 'status', 'actions'];

  constructor(private data: DataService) { }

  ngOnInit() {
    this.getItems();
    console.log('New list page initialized');
  }

  getItems() {
    this.data.getItems().subscribe( (items: Item[]) => {
      this.items.data = items;
      console.log(this.items);
    });
  }

  deleteItem(id) {
    this.data.deleteItem(id).subscribe( (res) => {
      console.log(res);
      this.getItems();
    });
  }
}
</code>```

Create component:

```<code>import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { ListComponent } from '../list/list.component';
import { Item } from '../items.model';

import { MatSnackBar } from '@angular/material';

import {FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-create',
  providers: [ListComponent],
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {

  createForm: FormGroup;

  constructor(private list: ListComponent ,private data: DataService, private fb: FormBuilder, private snackBar: MatSnackBar) {
    this.createForm = this.fb.group( {
      name: ['', Validators.required],
      status: ['']
    });
   }

  ngOnInit() {
  }

  addItem(name) {
    this.data.postItem(name).subscribe( (res) => {
      console.log(res);
      this.data.getItems().subscribe( (item: Item[])  => {
        this.list.items.data = item;
      })
      this.snackBar.open('Your item was succesfully added to the shopping list.', 'Cool!', {
        duration: 3000
      });
    });
  }
}
</code>```

Data Service:

```<code>    @Injectable({
  providedIn: 'root'
})
export class DataService {

  API_URL: string = 'https://cookie-munchies.herokuapp.com/api/items';

  constructor(private http : HttpClient) { }

  getItems(){
    return this.http.get(this.API_URL);
  }

  postItem(name){
    let item = {
      name: name,
    };

    return this.http.post(this.API_URL, item);
  }

  deleteItem(id) {
    return this.http.delete(`${this.API_URL}/${id}`);
  }

  updateItem(id, item: Item) {
    // TODO: write update function
    return this.http.put(`${this.API_URL}/${id}`, item);
  }
}
</code>```

答:
What I understand from your question that you need to add data from a component and display it as updated in other component list.
To achieve this you can use the feature of rxjs i,e subject.

In your  DataService:

```<code>//declare a subject instance

private subject =new Subject<any>();

//Value is any string message or boolean value
//this will notify that you have added or deleted the data successfully and you //want other component to listen that

sendNotification(value:any)
{
    this.subject.next({text:value});
}

//this will be subscribed by the listing component which needs to display the //added/deleted ie updated list.

getNotification(){
    return this.subject.asObservable();
}

//In the method which you are saving data either by http client or in a list. In //its success call sendNotification method.

postItem(name){
    let item = {
      name: name,
    };

    return this.http.post(this.API_URL, item).pipe(
      map((data=>{
        this.sendNotification(true);
        }
      }
    )));
  }
 deleteItem(id) {
    return this.http.delete(`${this.API_URL}/${id}`).pipe(
      map((data=>{
        this.sendNotification(true);
        }
      }
    )));;
  }
</code>```

In your List Component ts Add the following code:

```<code>// create a field of type Subscription
subscription:Subscription

//then add the following code in constructor:

constructor(private data: DataService){
this.subscription=this.dataService.getNotification().subscribe(data=>{
      if(data)
      {
        this.getItems();
      }
    });
}
</code>```

It will work fine and will update your list with every addition and deletion.

Always unsubscribe the subject after component disposed off to avoid unwanted memory leaks in your listing component.

```<code>ngOnDestroy():void
  {
      this.subscription.unsubscribe();
  }

</code>```

Body:
I have create a single page application in Angular 6 with two components. The are communicating to a web-server through a data service.
One component lists all the item, the other component allows the user to add an item to that list.
Interestingly, by calling getItems after deleting one item in the list component it refreshes the list, which calling get MatTableDataSource attribute from the create component does not.
Any points are hugely appreciated. Thanks.

List component:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { MatTableDataSource } from '@angular/material/table';

import { Item } from '../items.model';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {

  public items = new MatTableDataSource<Item>();
  private displayedColumns = ['name', 'status', 'actions'];

  constructor(private data: DataService) { }

  ngOnInit() {
    this.getItems();
    console.log('New list page initialized');
  }

  getItems() {
    this.data.getItems().subscribe( (items: Item[]) => {
      this.items.data = items;
      console.log(this.items);
    });
  }

  deleteItem(id) {
    this.data.deleteItem(id).subscribe( (res) => {
      console.log(res);
      this.getItems();
    });
  }
}

Create component:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { ListComponent } from '../list/list.component';
import { Item } from '../items.model';

import { MatSnackBar } from '@angular/material';

import {FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-create',
  providers: [ListComponent],
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {

  createForm: FormGroup;

  constructor(private list: ListComponent ,private data: DataService, private fb: FormBuilder, private snackBar: MatSnackBar) {
    this.createForm = this.fb.group( {
      name: ['', Validators.required],
      status: ['']
    });
   }

  ngOnInit() {
  }

  addItem(name) {
    this.data.postItem(name).subscribe( (res) => {
      console.log(res);
      this.data.getItems().subscribe( (item: Item[])  => {
        this.list.items.data = item;
      })
      this.snackBar.open('Your item was succesfully added to the shopping list.', 'Cool!', {
        duration: 3000
      });
    });
  }
}

Data Service:

    @Injectable({
  providedIn: 'root'
})
export class DataService {

  API_URL: string = 'https://cookie-munchies.herokuapp.com/api/items';

  constructor(private http : HttpClient) { }

  getItems(){
    return this.http.get(this.API_URL);
  }

  postItem(name){
    let item = {
      name: name,
    };

    return this.http.post(this.API_URL, item);
  }

  deleteItem(id) {
    return this.http.delete(`${this.API_URL}/${id}`);
  }

  updateItem(id, item: Item) {
    // TODO: write update function
    return this.http.put(`${this.API_URL}/${id}`, item);
  }
}

Body:
What I understand from your question that you need to add data from a component and display it as updated in other component list.
To achieve this you can use the feature of rxjs i,e subject.

In your  DataService:

//declare a subject instance

private subject =new Subject<any>();

//Value is any string message or boolean value
//this will notify that you have added or deleted the data successfully and you //want other component to listen that

sendNotification(value:any)
{
    this.subject.next({text:value});
}

//this will be subscribed by the listing component which needs to display the //added/deleted ie updated list.

getNotification(){
    return this.subject.asObservable();
}

//In the method which you are saving data either by http client or in a list. In //its success call sendNotification method.

postItem(name){
    let item = {
      name: name,
    };

    return this.http.post(this.API_URL, item).pipe(
      map((data=>{
        this.sendNotification(true);
        }
      }
    )));
  }
 deleteItem(id) {
    return this.http.delete(`${this.API_URL}/${id}`).pipe(
      map((data=>{
        this.sendNotification(true);
        }
      }
    )));;
  }

In your List Component ts Add the following code:

// create a field of type Subscription
subscription:Subscription

//then add the following code in constructor:

constructor(private data: DataService){
this.subscription=this.dataService.getNotification().subscribe(data=>{
      if(data)
      {
        this.getItems();
      }
    });
}

It will work fine and will update your list with every addition and deletion.

Always unsubscribe the subject after component disposed off to avoid unwanted memory leaks in your listing component.

ngOnDestroy():void
  {
      this.subscription.unsubscribe();
  }


问:
How create a DefaultTableModel with data from text file
I have this test file text_file
My table view is enter image description here
I want suit each row with each column(first_row-first_column,second_row-second_column, etc..) Where is error?

```<code>        BufferedReader infile = new BufferedReader(reader);
        String line = "";
        int counter = 0;
        String title = "";
        String author = "";
        String price = "";
        try {
            while ((line  = infile.readLine()) != null) {
                ++counter;

                if (counter == 1) {
                    title = line;
                } else if (counter == 2) {
                    author = line;
                } else if (counter == 3) {
                    price = line;
                    SimpleBook sb = new SimpleBook(title, author, price);
                    bookList.add(sb);
                    counter = 0;
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(SimpleBookList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
</code>```

答:
The problem in reading the file, because you read line by line not read all lines

```<code>        int counter = 0;
        String title = "", author = "";
        double price = 0.0;
        while ((line = infile.readLine()) != null) {
            ++counter;
            if (counter == 1)
                title = line;
            else if (counter == 2)
                author = line;
            else if (counter == 3) {
                price = Double.parseDouble(line);
                SimpleBook sb = new SimpleBook(title, author, price);
                bookList.add(sb);
                counter = 0;
            }
        }
</code>```

, or you can check readAllLines from Oracle doc

Body:
I have this test file text_file
My table view is enter image description here
I want suit each row with each column(first_row-first_column,second_row-second_column, etc..) Where is error?

        BufferedReader infile = new BufferedReader(reader);
        String line = "";
        int counter = 0;
        String title = "";
        String author = "";
        String price = "";
        try {
            while ((line  = infile.readLine()) != null) {
                ++counter;

                if (counter == 1) {
                    title = line;
                } else if (counter == 2) {
                    author = line;
                } else if (counter == 3) {
                    price = line;
                    SimpleBook sb = new SimpleBook(title, author, price);
                    bookList.add(sb);
                    counter = 0;
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(SimpleBookList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

Body:
The problem in reading the file, because you read line by line not read all lines

        int counter = 0;
        String title = "", author = "";
        double price = 0.0;
        while ((line = infile.readLine()) != null) {
            ++counter;
            if (counter == 1)
                title = line;
            else if (counter == 2)
                author = line;
            else if (counter == 3) {
                price = Double.parseDouble(line);
                SimpleBook sb = new SimpleBook(title, author, price);
                bookList.add(sb);
                counter = 0;
            }
        }

, or you can check readAllLines from Oracle doc


答:
Validating the user input inside a text watcher might not be the best solution. Maybe you could simply validate after the user has definitely finished with the editText. A couple of options could be

1) Validate on edit text lost focus

2) Have a validate button

Title: EditText settext on addTextChangedListener(TextWatcher) infite loop in Kotlin