问:
PyTorch Model Training: RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR
After training a PyTorch model on a GPU for several hours, the program fails with the error

RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR

Training Conditions

Neural Network: PyTorch 4-layer nn.LSTM with nn.Linear output

Deep Q Network Agent (Vanilla DQN with Replay Memory)

state passed into forward() has the shape (32, 20, 15), where 32 is the batch size

50 seconds per episode

Error occurs after about 583 episodes (8 hours) or 1,150,000 steps, where each step involves a forward pass through the LSTM model.

My code also has the following values set before the training began

```<code>torch.manual_seed(0)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(0)
</code>```

How can we troubleshoot this problem? Since this occurred 8 hours into the training, some educated guess will be very helpful here!

Thanks!

Update:

Commenting out the 2 torch.backends.cudnn... lines did not work. CUDNN_STATUS_INTERNAL_ERROR still occurs, but much earlier at around Episode 300 (585,000 steps).

```<code>torch.manual_seed(0)
#torch.backends.cudnn.deterministic = True
#torch.backends.cudnn.benchmark = False
np.random.seed(0)
</code>```

System

PyTorch 1.6.0.dev20200525

CUDA 10.2

cuDNN 7604

Python 3.8

Windows 10

nVidia 1080 GPU

Error Traceback

```<code>RuntimeError                              Traceback (most recent call last)
<ipython-input-18-f5bbb4fdfda5> in <module>
     57
     58     while not done:
---> 59         action = agent.choose_action(state)
     60         state_, reward, done, info = env.step(action)
     61         score += reward

<ipython-input-11-5ad4dd57b5ad> in choose_action(self, state)
     58         if np.random.random() > self.epsilon:
     59             state = T.tensor([state], dtype=T.float).to(self.q_eval.device)
---> 60             actions = self.q_eval.forward(state)
     61             action = T.argmax(actions).item()
     62         else:

<ipython-input-10-94271a92f66e> in forward(self, state)
     20
     21     def forward(self, state):
---> 22         lstm, hidden = self.lstm(state)
     23         actions = self.fc1(lstm[:,-1:].squeeze(1))
     24         return actions

~\AppData\Local\Continuum\anaconda3\envs\rl\lib\site-packages\torch\nn\modules\module.py in __call__(self, *input, **kwargs)
    575             result = self._slow_forward(*input, **kwargs)
    576         else:
--> 577             result = self.forward(*input, **kwargs)
    578         for hook in self._forward_hooks.values():
    579             hook_result = hook(self, input, result)

~\AppData\Local\Continuum\anaconda3\envs\rl\lib\site-packages\torch\nn\modules\rnn.py in forward(self, input, hx)
    571         self.check_forward_args(input, hx, batch_sizes)
    572         if batch_sizes is None:
--> 573             result = _VF.lstm(input, hx, self._flat_weights, self.bias, self.num_layers,
    574                               self.dropout, self.training, self.bidirectional, self.batch_first)
    575         else:

RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR
</code>```

Update: Tried try... except on my code where this error occurs at, and in addition to RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR, we also get a second traceback for the error RuntimeError: CUDA error: unspecified launch failure

```<code>During handling of the above exception, another exception occurred:

RuntimeError                              Traceback (most recent call last)
<ipython-input-4-e8f15cc8cf4f> in <module>
     61
     62     while not done:
---> 63         action = agent.choose_action(state)
     64         state_, reward, done, info = env.step(action)
     65         score += reward

<ipython-input-3-1aae79080e99> in choose_action(self, state)
     58         if np.random.random() > self.epsilon:
     59             state = T.tensor([state], dtype=T.float).to(self.q_eval.device)
---> 60             actions = self.q_eval.forward(state)
     61             action = T.argmax(actions).item()
     62         else:

<ipython-input-2-6d22bb632c4c> in forward(self, state)
     25         except Exception as e:
     26             print('error in forward() with state:', state.shape, 'exception:', e)
---> 27             print('state:', state)
     28         actions = self.fc1(lstm[:,-1:].squeeze(1))
     29         return actions

~\AppData\Local\Continuum\anaconda3\envs\rl\lib\site-packages\torch\tensor.py in __repr__(self)
    152     def __repr__(self):
    153         # All strings are unicode in Python 3.
--> 154         return torch._tensor_str._str(self)
    155
    156     def backward(self, gradient=None, retain_graph=None, create_graph=False):

~\AppData\Local\Continuum\anaconda3\envs\rl\lib\site-packages\torch\_tensor_str.py in _str(self)
    331                 tensor_str = _tensor_str(self.to_dense(), indent)
    332             else:
--> 333                 tensor_str = _tensor_str(self, indent)
    334
    335     if self.layout != torch.strided:

~\AppData\Local\Continuum\anaconda3\envs\rl\lib\site-packages\torch\_tensor_str.py in _tensor_str(self, indent)
    227     if self.dtype is torch.float16 or self.dtype is torch.bfloat16:
    228         self = self.float()
--> 229     formatter = _Formatter(get_summarized_data(self) if summarize else self)
    230     return _tensor_str_with_formatter(self, indent, formatter, summarize)
    231

~\AppData\Local\Continuum\anaconda3\envs\rl\lib\site-packages\torch\_tensor_str.py in __init__(self, tensor)
     99
    100         else:
--> 101             nonzero_finite_vals = torch.masked_select(tensor_view, torch.isfinite(tensor_view) & tensor_view.ne(0))
    102
    103             if nonzero_finite_vals.numel() == 0:

RuntimeError: CUDA error: unspecified launch failure
</code>```

答:
The error RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR is notoriously difficult to debug, but surprisingly often it's an out of memory problem. Usually, you would get the out of memory error, but depending on where it occurs, PyTorch cannot intercept the error and therefore not provide a meaningful error message.

A memory issue seems to be likely in your case, because you are using a while loop until the agent is done, which might take long enough that you run out of memory, it's just a matter of time. That can also possibly occur rather late, once the model's parameters in combination with a certain input is unable to finish in time.

You can avoid that scenario by limiting the number of allowed actions instead of hoping that the actor will be done in a reasonable time.

What you also need to be careful about, is that you don't occupy unnecessary memory. A common mistake is to keep computing gradients of the past states in future iterations. The state from the last iteration should be considered constant, since the current action should not affect past actions, therefore no gradients are required. This is usually achieved by detaching the state from the computational graph for the next iteration, e.g. state = state_.detach(). Maybe you are already doing that, but without the code it's impossible to tell.

Similarly, if you keep a history of the states, you should detach them and even more importantly put them on the CPU, i.e. history.append(state.detach().cpu()).

Body:
After training a PyTorch model on a GPU for several hours, the program fails with the error

RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR

Training Conditions

Neural Network: PyTorch 4-layer nn.LSTM with nn.Linear output

Deep Q Network Agent (Vanilla DQN with Replay Memory)

state passed into forward() has the shape (32, 20, 15), where 32 is the batch size

50 seconds per episode

Error occurs after about 583 episodes (8 hours) or 1,150,000 steps, where each step involves a forward pass through the LSTM model.

My code also has the following values set before the training began

torch.manual_seed(0)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(0)

How can we troubleshoot this problem? Since this occurred 8 hours into the training, some educated guess will be very helpful here!

Thanks!

Update:

Commenting out the 2 torch.backends.cudnn... lines did not work. CUDNN_STATUS_INTERNAL_ERROR still occurs, but much earlier at around Episode 300 (585,000 steps).

torch.manual_seed(0)
#torch.backends.cudnn.deterministic = True
#torch.backends.cudnn.benchmark = False
np.random.seed(0)

System

PyTorch 1.6.0.dev20200525

CUDA 10.2

cuDNN 7604

Python 3.8

Windows 10

nVidia 1080 GPU

Error Traceback

RuntimeError                              Traceback (most recent call last)
<ipython-input-18-f5bbb4fdfda5> in <module>
     57
     58     while not done:
---> 59         action = agent.choose_action(state)
     60         state_, reward, done, info = env.step(action)
     61         score += reward

<ipython-input-11-5ad4dd57b5ad> in choose_action(self, state)
     58         if np.random.random() > self.epsilon:
     59             state = T.tensor([state], dtype=T.float).to(self.q_eval.device)
---> 60             actions = self.q_eval.forward(state)
     61             action = T.argmax(actions).item()
     62         else:

<ipython-input-10-94271a92f66e> in forward(self, state)
     20
     21     def forward(self, state):
---> 22         lstm, hidden = self.lstm(state)
     23         actions = self.fc1(lstm[:,-1:].squeeze(1))
     24         return actions

~\AppData\Local\Continuum\anaconda3\envs\rl\lib\site-packages\torch\nn\modules\module.py in __call__(self, *input, **kwargs)
    575             result = self._slow_forward(*input, **kwargs)
    576         else:
--> 577             result = self.forward(*input, **kwargs)
    578         for hook in self._forward_hooks.values():
    579             hook_result = hook(self, input, result)

~\AppData\Local\Continuum\anaconda3\envs\rl\lib\site-packages\torch\nn\modules\rnn.py in forward(self, input, hx)
    571         self.check_forward_args(input, hx, batch_sizes)
    572         if batch_sizes is None:
--> 573             result = _VF.lstm(input, hx, self._flat_weights, self.bias, self.num_layers,
    574                               self.dropout, self.training, self.bidirectional, self.batch_first)
    575         else:

RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR

Update: Tried try... except on my code where this error occurs at, and in addition to RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR, we also get a second traceback for the error RuntimeError: CUDA error: unspecified launch failure

During handling of the above exception, another exception occurred:

RuntimeError                              Traceback (most recent call last)
<ipython-input-4-e8f15cc8cf4f> in <module>
     61
     62     while not done:
---> 63         action = agent.choose_action(state)
     64         state_, reward, done, info = env.step(action)
     65         score += reward

<ipython-input-3-1aae79080e99> in choose_action(self, state)
     58         if np.random.random() > self.epsilon:
     59             state = T.tensor([state], dtype=T.float).to(self.q_eval.device)
---> 60             actions = self.q_eval.forward(state)
     61             action = T.argmax(actions).item()
     62         else:

<ipython-input-2-6d22bb632c4c> in forward(self, state)
     25         except Exception as e:
     26             print('error in forward() with state:', state.shape, 'exception:', e)
---> 27             print('state:', state)
     28         actions = self.fc1(lstm[:,-1:].squeeze(1))
     29         return actions

~\AppData\Local\Continuum\anaconda3\envs\rl\lib\site-packages\torch\tensor.py in __repr__(self)
    152     def __repr__(self):
    153         # All strings are unicode in Python 3.
--> 154         return torch._tensor_str._str(self)
    155
    156     def backward(self, gradient=None, retain_graph=None, create_graph=False):

~\AppData\Local\Continuum\anaconda3\envs\rl\lib\site-packages\torch\_tensor_str.py in _str(self)
    331                 tensor_str = _tensor_str(self.to_dense(), indent)
    332             else:
--> 333                 tensor_str = _tensor_str(self, indent)
    334
    335     if self.layout != torch.strided:

~\AppData\Local\Continuum\anaconda3\envs\rl\lib\site-packages\torch\_tensor_str.py in _tensor_str(self, indent)
    227     if self.dtype is torch.float16 or self.dtype is torch.bfloat16:
    228         self = self.float()
--> 229     formatter = _Formatter(get_summarized_data(self) if summarize else self)
    230     return _tensor_str_with_formatter(self, indent, formatter, summarize)
    231

~\AppData\Local\Continuum\anaconda3\envs\rl\lib\site-packages\torch\_tensor_str.py in __init__(self, tensor)
     99
    100         else:
--> 101             nonzero_finite_vals = torch.masked_select(tensor_view, torch.isfinite(tensor_view) & tensor_view.ne(0))
    102
    103             if nonzero_finite_vals.numel() == 0:

RuntimeError: CUDA error: unspecified launch failure


来源: stackexchange

问:
Android Studio choreographer.java
I am new in Android Studio and Firebase.  The error shows when I try to build the app.  I had tried invalidate/restart, clean project, and reinstall the android studio but it does not solve the problem.

.

Here is description Logcat.

答: choreographer.java is a class of Android and Android studio can't see other android classes (android.*) in your app... But don't worry it works fine... If you have any problem review your code.</p>

ContentLicense: CC BY-SA 4.0

Title: Android Studio choreographer.java


问:
Updating JSON when there is multiple objects named the same - Python
I am new to the JSON python lib.

I have this JSON file:

```<code>   {
        "usrdata": [
            {
                "user": "---/ LandiPlayz \\---#****",
                "money": 10
            },
            {
                "user": "Snubz#****",
                "money": 10
            }
        ]
    }
</code>```

and I need to modify the "money" field of one of the users. There will be more added users, so I need to find which one it is by finding the users name. Is that possible, or should I do format the file differently.

Thanks in advance

答:
You have to iterate over the user_infos, and when getting the good one, update the money

```<code>json_value =    {
        "usrdata": [
            {"user": "---/ LandiPlayz \\---#****","money": 10},
            {"user": "Snubz#****","money": 10}
        ]
    }
username = "Snubz#****"
new_money = 50

for user_info in json_value["usrdata"]:
    if user_info['user'] == username:
        user_info['money'] = new_money
</code>```

Body:
I am new to the JSON python lib.

I have this JSON file:

   {
        "usrdata": [
            {
                "user": "---/ LandiPlayz \\---#****",
                "money": 10
            },
            {
                "user": "Snubz#****",
                "money": 10
            }
        ]
    }

and I need to modify the "money" field of one of the users. There will be more added users, so I need to find which one it is by finding the users name. Is that possible, or should I do format the file differently.

Thanks in advance

Body:
You have to iterate over the user_infos, and when getting the good one, update the money

json_value =    {
        "usrdata": [
            {"user": "---/ LandiPlayz \\---#****","money": 10},
            {"user": "Snubz#****","money": 10}
        ]
    }
username = "Snubz#****"
new_money = 50

for user_info in json_value["usrdata"]:
    if user_info['user'] == username:
        user_info['money'] = new_money


问:
Differences between XMPP and Channel API for Google App Engine
I am developing an application that doesn't reside on AppEngine and having the functionality of a chat putting in communication web clients (browser + javascript) and mobile clients (ActionScript).
I'm thinking of using the XMPP protocol on AppEngine (then use only the servers for the chat feature on Google and still leave the rest on my server). You tell me if this is possible?
What are the differences with the Channel API?
Thanks</p>

答:
The XMPP API facilitates communication between your app and an XMPP client, like Google Talk.

The Channel API is used to push data from your app to a web browser using web sockets.

Either can be used as part of a chat app; the choice just depends on whether chat clients are going to be using an XMPP client or a web browser.

ContentLicense: CC BY-SA 3.0


问:
Resource (resx) files always returns english (default) strings
Im having some trouble using .resx files. Everything was created using windows MAT toolkit extension (the problem occurred regardless of this).

I have two languages (en and es). When I make a new project and use the code below it works:

```<code>System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("es");
string temp = MultilingualResources.strings.Hello;
</code>```

The string is returned as "Hallo" so the translation works. But when I do this in GoDot (c#) inside visual code, the string always returns in english no matter which culture or UIculture I specify, but the code is exactly the same. I've tried with resource manager and result is the same. So basically it gets the strings.resx values but not strings.es.resx values. The resx files are embedded resources. Any idea why this is happening and how to make this work?

I also tried using

```<code>CultureInfo culture = CultureInfo.CreateSpecificCulture("es");
CultureInfo.DefaultThreadCurrentUICulture = culture;
</code>```

答:
The problem started for me after the last visual studio (MAC) update (Version 8.6 (build 4520))

Look this:

https://github.com/xamarin/xamarin-android/issues/4664#issuecomment-632986668

This workaround solved my problem.

But, there is a new preview visual studio update in that solve the problem.

Edit: The problem was solved in the new Visual Studio version

Body:
Im having some trouble using .resx files. Everything was created using windows MAT toolkit extension (the problem occurred regardless of this).

I have two languages (en and es). When I make a new project and use the code below it works:

System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("es");
string temp = MultilingualResources.strings.Hello;

The string is returned as "Hallo" so the translation works. But when I do this in GoDot (c#) inside visual code, the string always returns in english no matter which culture or UIculture I specify, but the code is exactly the same. I've tried with resource manager and result is the same. So basically it gets the strings.resx values but not strings.es.resx values. The resx files are embedded resources. Any idea why this is happening and how to make this work?

I also tried using

CultureInfo culture = CultureInfo.CreateSpecificCulture("es");
CultureInfo.DefaultThreadCurrentUICulture = culture;


问:
How to migrate from MongoDB Compass Community version?
I am new to MongoDB and installed MongoDB Compass Community version while installing MongoDB. I would like to migrate from Compass Community to Compass. I am having some hard time to follow the steps.
   The compass version is DMG file, I converted it to ZIP and extracted the files from folder. I don't find any .exe to launch the Compass App. Not sure what I am missing here.
Files and folders I see after extraction

https://docs.mongodb.com/compass/master/upgrade/#upgrade-compass

答:
Following is what I did for my migration from MongoDB Compass Community edition in Windows10.

I uninstalled the MongoDB Compass Community edition.

I downloaded and installed MongoDB Compass(Windows 64 bit MSI) from the url Upgrade MongoDB Compass

I started new MongoDB Compass then.

Went to the following folder in File Explorer.

C:\Users\userName\AppData\Roaming\MongoDB Compass Community

Copied the folders Connections,     FavoriteQueries, RecentQueries, SavedPipelines from 'MongoDB Compass Community' folder to 'MongoDB Compass' folder which was in the same location.

Then I just stopped and restarted MongoDB Compass. I saw my old connections, favorites from Community edition.

So I will suggest you to clean up your MongoDB Compass first and follow the above steps for smooth migration.


问:
How can solve 'error: RPC failed; curl 56 OpenSSL SSL_read: Connection was reset, errno 10054' when pushing files to a github repository?
I initialized git and I did git push -u origin master but when I'm trying to push files to my github repository I get these logs in my terminal

```<code>Enumerating objects: 118, done.
Counting objects: 100% (118/118), done.
Delta compression using up to 4 threads
Compressing objects: 100% (118/118), done.
Writing objects: 100% (118/118), 2.78 MiB | 2.55 MiB/s, done.
Total 118 (delta 0), reused 0 (delta 0), pack-reused 0
error: RPC failed; curl 56 OpenSSL SSL_read: Connection was reset, errno 10054
fatal: the remote end hung up unexpectedly
fatal: the remote end hung up unexpectedly
Everything up-to-date

</code>```

And turns out it hasn't push anyhting to repository and my repo is still empty .
How can I solve this error and push to my repo ?

答: I solved the error by building my project again and git init and other steps again and finally it worked</p>

Body:
I initialized git and I did git push -u origin master but when I'm trying to push files to my github repository I get these logs in my terminal

Enumerating objects: 118, done.
Counting objects: 100% (118/118), done.
Delta compression using up to 4 threads
Compressing objects: 100% (118/118), done.
Writing objects: 100% (118/118), 2.78 MiB | 2.55 MiB/s, done.
Total 118 (delta 0), reused 0 (delta 0), pack-reused 0
error: RPC failed; curl 56 OpenSSL SSL_read: Connection was reset, errno 10054
fatal: the remote end hung up unexpectedly
fatal: the remote end hung up unexpectedly
Everything up-to-date

And turns out it hasn't push anyhting to repository and my repo is still empty .
How can I solve this error and push to my repo ?


问:
Proper use of Task.Run & Task.WaitAll for EF calls in ASP.NET
SHORT VERSION:

Can anyone confirm, does Task.Run/Task.WaitAll on non-async sub-functions with EF calls gain anything for ASP.NET apps?

LONG VERSION:

We have an Asp.Net WebApi service with a method which makes multiple DB calls (all using EntityFramework) to collect a set of data that all get returned into a single response object.  We broke this up into a series of sub-functions, and wanted these to run in parallel (NOTE: None of these use any async calls).

To achieve some form of parallel coding, we invoke each function with Task.Run, followed by Task.WaitAll:

```<code>public ResponseObject PopulateResponseObject(int id)
{
    var response = new ResponseObject();

    Task<DataSetA> dataSetATask = Task.Run(() => getDataSetA(id));
    Task<DataSetB> dataSetBTask = Task.Run(() => getDataSetB(id));
    Task.WaitAll(dataSetATask, dataSetBTask);

    response.SetA = dataSetATask.Result;
    response.SetB = dataSetBTask.Result;

    return response;
}
</code>```

From what I've been reading, Task.Run may not gain much in an Asp.Net application, and what we have here may just result in unnecessary thread-pool overhead.

Are we wasting time writing our code this way?

UPDATE:
We are familiar with the fact that EF has async versions, but there is a significant amount of code that would need to be modified.  We'd like to leave these functions as-is.

答:
using Task.Run at least lets you run the two queries in parallel, so yes there is improvement to be gained (vs the totally synchronous version where you run the queries sequentially).

However, the gain is limited to the number of threads you have in threadpool (which is ultimately limited by your server capacity).  You'll get more gain by using the EF async apis because that will allow many queries to be executed without tieing up a thread for each query.

But this is a reasonable strategy to start using async code.  Once you've done this, you can come back and slowly convert the queries to use the async api.

Body:
SHORT VERSION:

Can anyone confirm, does Task.Run/Task.WaitAll on non-async sub-functions with EF calls gain anything for ASP.NET apps?

LONG VERSION:

We have an Asp.Net WebApi service with a method which makes multiple DB calls (all using EntityFramework) to collect a set of data that all get returned into a single response object.  We broke this up into a series of sub-functions, and wanted these to run in parallel (NOTE: None of these use any async calls).

To achieve some form of parallel coding, we invoke each function with Task.Run, followed by Task.WaitAll:

public ResponseObject PopulateResponseObject(int id)
{
    var response = new ResponseObject();

    Task<DataSetA> dataSetATask = Task.Run(() => getDataSetA(id));
    Task<DataSetB> dataSetBTask = Task.Run(() => getDataSetB(id));
    Task.WaitAll(dataSetATask, dataSetBTask);

    response.SetA = dataSetATask.Result;
    response.SetB = dataSetBTask.Result;

    return response;
}

From what I've been reading, Task.Run may not gain much in an Asp.Net application, and what we have here may just result in unnecessary thread-pool overhead.

Are we wasting time writing our code this way?

UPDATE:
We are familiar with the fact that EF has async versions, but there is a significant amount of code that would need to be modified.  We'd like to leave these functions as-is.


问:
Spacing between Itext PDF fonts is incorrect
I'm using itext(2.x) to create pdfs.

Locally on my computer, the pdf output is correct.

But when i run the code on the production server, running ubuntu, the spacing between characters in the fonts is wrong.

Anyone have any experience from a similar situation ?

答:
I Strongly Suspect this is a font issue.

Possibility 1: The font you're using simply isn't present on the server (VSU's answer).  This will cause the font in question to default back to Helvetica... which will Look Wrong.

Possibility 2: You're not embedding the font and are viewing the PDF on a different system than the one that generated it.  If both machines have a font named "Arial", but there are subtle (or not so subtle) differences, the character spacing could look Way Off.

Possibility 3: You're "baking" kerning info into your app, which is wrong for the version (or font, cross-talk with possibility 1 here) that ends up in the PDF.

There's probably another couple varients I'm not thinking of that could be The Problem, but that covers every scenario I've run into in my 14 years as a PDF Guy.

PS: You could talk all the guesswork out of this if you'd post links to your PDFs... one from your dev box and an "identical" one from the server.


答:
Based on my experiences, I strongly recommend you never kill simplicity for insignificant performance gain. Impact of this parallelism seems to me insignificant with huge development, maintenance and debugging burden.

Specially because you use EF and interacting with DB, probably you'll face to many concurrency issues that could be mare! also I suggest to take a look at this.

Title: Proper use of Task.Run & Task.WaitAll for EF calls in ASP.NET


问:
Python - 2 Equations In 1 Loop
I'm a beginner with Python and trying to learn how to put 2 equations into 1 loop.

```<code>months = paymentTerm * 12
startingMonth = 1
while startingMonth <= months :
    print(startingMonth)
    startingMonth = startingMonth + 1

principal = principalAmount
startingPrincipal = principalAmount - monthlyInterest
while startingPrincipal <= principal :
    print(startingPrincipal)
    startingPrincipal = startingPrincipal - monthlyInterest
</code>```

Any ideas on how? Essentially I want the outputs to print side by side while using the \t\t function because the values for my principal are printing after the months, but I want them to be side by side. Thank you!!

答:
Check for both conditions in the while condition.

```<code>while startingMonth <= months and startingPrincipal <= principal:
    print(startingMonth, startingPrincipal)
    startingMonth += 1
    startingPrincipal += monthlyInterest
</code>```

This will stop when either limit is reached.

Title: Python - 2 Equations In 1 Loop

Body:
I'm a beginner with Python and trying to learn how to put 2 equations into 1 loop.

months = paymentTerm * 12
startingMonth = 1
while startingMonth <= months :
    print(startingMonth)
    startingMonth = startingMonth + 1

principal = principalAmount
startingPrincipal = principalAmount - monthlyInterest
while startingPrincipal <= principal :
    print(startingPrincipal)
    startingPrincipal = startingPrincipal - monthlyInterest

Any ideas on how? Essentially I want the outputs to print side by side while using the \t\t function because the values for my principal are printing after the months, but I want them to be side by side. Thank you!!

Body:
Check for both conditions in the while condition.

while startingMonth <= months and startingPrincipal <= principal:
    print(startingMonth, startingPrincipal)
    startingMonth += 1
    startingPrincipal += monthlyInterest

This will stop when either limit is reached.


问:
Java MouseAdapter
So I have my custom mouse adapter. I want to call a method if:
The x and y coordinates are in a Rectangle with for example the coordinates x = 40 y = 40 and the width = 10 length = 10. How can I check if the x and y coordinates (of the mouse) are in the rectangle?
I tried this:

```<code>@Override
public void mouseClicked(MouseEvent e) {
    if(isXinBounds(e.getX()) || isYinBounds(e.getY())) {
        //This happens if the mouse click is in the rectangle
    }
}

//Check if the x coordinate of the mouse click is in the rectangle
private boolean isXinBounds(int x) {
    if(x <= ob.getBounds().getX() + ob.getBounds().getWidth() / 2 && x >= ob.getBounds().getX() - ob.getBounds().getWidth() / 2) return true;
    return false;
}

//Check if the y coordinate of the mouse click is in the rectangle
private boolean isYinBounds(int y) {
    if(y <= ob.getBounds().getY() + ob.getBounds().getHeight() / 2 && y >= ob.getBounds().getY() - ob.getBounds().getHeight() / 2) return true;
    return false;
}
</code>```

But that didn't work

答:
The x and y coordinates are in a Rectangle

The Rectangle class already supports a contains(…) method.

You can just use:

```<code>if (yourRectangle.contains(e.getPoint())
    // do something
</code>```

Title: Java MouseAdapter

Body:
So I have my custom mouse adapter. I want to call a method if:
The x and y coordinates are in a Rectangle with for example the coordinates x = 40 y = 40 and the width = 10 length = 10. How can I check if the x and y coordinates (of the mouse) are in the rectangle?
I tried this:

@Override
public void mouseClicked(MouseEvent e) {
    if(isXinBounds(e.getX()) || isYinBounds(e.getY())) {
        //This happens if the mouse click is in the rectangle
    }
}

//Check if the x coordinate of the mouse click is in the rectangle
private boolean isXinBounds(int x) {
    if(x <= ob.getBounds().getX() + ob.getBounds().getWidth() / 2 && x >= ob.getBounds().getX() - ob.getBounds().getWidth() / 2) return true;
    return false;
}

//Check if the y coordinate of the mouse click is in the rectangle
private boolean isYinBounds(int y) {
    if(y <= ob.getBounds().getY() + ob.getBounds().getHeight() / 2 && y >= ob.getBounds().getY() - ob.getBounds().getHeight() / 2) return true;
    return false;
}

But that didn't work

Body:
The x and y coordinates are in a Rectangle

The Rectangle class already supports a contains(…) method.

You can just use:

if (yourRectangle.contains(e.getPoint())
    // do something


问:
Using future<> and promise<> for message passing?
I'm trying write a simple program to pass message with future<> and promise<> so I understand how they work.  The intent is to pass 10  objects from the produce to the consumer.  Unfortunately, I'm running into compilation issues.  Does anyone know where I have gone wrong?
Thank you!

Update solution.

```<code>#include <iostream>
#include <thread>
#include <unistd.h>
#include <stdlib.h>
#include <future>
#include <functional>
#include <vector>
using namespace std;
using namespace std::chrono;

struct MSG {
  int val;
};

void consumer(vector<future<MSG>> *futv) {
  for (auto& p : *futv) {
    this_thread::sleep_for(milliseconds{rand() % 25});
    MSG m = p.get();
    cout << m.val << endl;
  }
}

void producer(vector<promise<MSG>> *promv) {
  MSG m = {0};

  for (auto& p : *promv) {
    this_thread::sleep_for(milliseconds{rand() % 25});
    p.set_value(m);
    m.val++;
  }
}

int main(int argc, char *argv[])
{
  vector<promise<MSG>> promv;
  vector<future<MSG>> futv;

  for (int i=0; i<10; i++) {
    promv.push_back(promise<MSG>());
    futv.push_back(promv[i].get_future());
  }

  thread tp {producer, &promv};
  thread tc {consumer, &futv};

  tp.join();
  tc.join();

  return 0;
}
</code>```

Compilation...,

```<code>g++ -lpthread -pedantic -Wall test84.cc && ./a.out
0
1
2
3
4
5
6
7
8
9
</code>```

答:
You can use condition_variable, it is well placed than future/promise implementations in this case.

For example, taking two threads, product and consumer, when the product 'i' (product element) is finished, it will be passed on to a consumer 'i' who waits until the product is ready and is consumed afterwards.

future/promise is used, for instance, for multiple return value threads.

If you want your thread to return multiple values at different point of time then just pass multiple std::promise objects in thread and fetch multiple return values from thier associated multiple std::future objects.

Body:
I'm trying write a simple program to pass message with future<> and promise<> so I understand how they work.  The intent is to pass 10  objects from the produce to the consumer.  Unfortunately, I'm running into compilation issues.  Does anyone know where I have gone wrong?
Thank you!

Update solution.

#include <iostream>
#include <thread>
#include <unistd.h>
#include <stdlib.h>
#include <future>
#include <functional>
#include <vector>
using namespace std;
using namespace std::chrono;

struct MSG {
  int val;
};

void consumer(vector<future<MSG>> *futv) {
  for (auto& p : *futv) {
    this_thread::sleep_for(milliseconds{rand() % 25});
    MSG m = p.get();
    cout << m.val << endl;
  }
}

void producer(vector<promise<MSG>> *promv) {
  MSG m = {0};

  for (auto& p : *promv) {
    this_thread::sleep_for(milliseconds{rand() % 25});
    p.set_value(m);
    m.val++;
  }
}

int main(int argc, char *argv[])
{
  vector<promise<MSG>> promv;
  vector<future<MSG>> futv;

  for (int i=0; i<10; i++) {
    promv.push_back(promise<MSG>());
    futv.push_back(promv[i].get_future());
  }

  thread tp {producer, &promv};
  thread tc {consumer, &futv};

  tp.join();
  tc.join();

  return 0;
}

Compilation...,

g++ -lpthread -pedantic -Wall test84.cc && ./a.out
0
1
2
3
4
5
6
7
8
9


问:
How to reach a property of a generic interface with other non-generic interface
Let me list all of my current classes and interfaces:

IItem:

public interface IItem<T> where T : ItemData {
    T Data { get; }
}
```

<p>Item:</p>

<pre class="lang-cs prettyprint-override"><code>public class Item<T> : IItem<T> where T : ItemData {
    T data = null; // I am setting this something else later on

    T Data => data;
}
</code>```

Equipment:

public class Equipment<T> : Item<T>, IEquipment where T : EquipmentData {
    // Code...
}
```

How can I get Data using IEquipment? Thanks.

答:
You can't directly, you need some cast first.</p>

```<code>IEquipment equipement = new Equipment();

// ...

// 'object as type' will cast the object with the corresponding type if possible, else return null
var data = (equipement as ItemData)?.Data; // data will be null if cast is not possible
</code>```

Body:
Let me list all of my current classes and interfaces:

IItem:

public interface IItem<T> where T : ItemData {
    T Data { get; }
}

Item:

public class Item<T> : IItem<T> where T : ItemData {
    T data = null; // I am setting this something else later on

    T Data => data;
}

Equipment:

public class Equipment<T> : Item<T>, IEquipment where T : EquipmentData {
    // Code...
}

How can I get Data using IEquipment? Thanks.

Body:
You can't directly, you need some cast first.

IEquipment equipement = new Equipment();

// ...

// 'object as type' will cast the object with the corresponding type if possible, else return null
var data = (equipement as ItemData)?.Data; // data will be null if cast is not possible


问:
javascript set element background color
i have a little javascript function that does something when one clicks on the element having onclick that function.

my problem is:
i want that, into this function, to set a font color fot the html element having this function onclick. but i don't suceed. my code:

```<code><script type="text/javascript">
    function selecteazaElement(id,stock){
        document.addtobasket.idOfSelectedItem.value=id;
        var number23=document.addtobasket.number;
        number23.options.length=0;
        if (stock>=6) stock=6;

        for (i=1;i<=stock;i++){
            //alert ('id: '+id+'; stock: '+stock);
            number23.options[number23.options.length]=new Option(i, i);
        }
    }
</script>
</code>```

and how i use it:

```<code><li id = "product_types">
    <a href="#" onclick='selecteazaElement(<?= $type->id; ?>,<?= $type->stock_2; ?>);'><?= $type->label; ?></a>
</li>
</code>```

any suggestions? thanks!

i have added another function (jquery one) that does partially what i need. the new problem is: i want that background color to be set only on the last clicked item, not on all items that i click. code above:

```<code>$(document).ready(function() {
    $('.product_types > li').click(function() {
    $(this)
        .css('background-color','#EE178C')
        .siblings()
        .css('background-color','#ffffff');
    });
});
</code>```

any ideas why?

thanks!

答:
Your element could have this code:

<li id = "product_types" onclick="selecteazaElement(this);" <...>

To change the foreground color of that element:

```<code>function selecteazaElement(element)
{
    element.style.foregroundColor="#SOMECOLOR";
}
</code>```

If you want to change the background color on only the last element clicked, each element must have a different id.  I'd suggest naming each one something like product_types1, product_types2, ..., product_typesN, and so on.  Then have a reset function:

```<code>function Reset()
{
    for (var i = 1; i <= N; i = i + 1)
    {
        document.getElementById('product_types'+i).style.backgroundColor="#RESETCOLOR";
    }
}
</code>```

When you call your selecteazaElement(this) function, first call the Reset function, then set the new element:

```<code>function selecteazaElement(element)
{
    Reset();
    element.style.backgroundColor="#SOMECOLOR";
}
</code>```

This way all of the elements that start with product_types followed by a number will be reset to one particular color, and only the element clicked on will have the background changed.

Title: javascript set element background color

Body:
i have a little javascript function that does something when one clicks on the element having onclick that function.

my problem is:
i want that, into this function, to set a font color fot the html element having this function onclick. but i don't suceed. my code:

and how i use it:

    <a href="#" onclick='selecteazaElement(<?= $type->id; ?>,<?= $type->stock_2; ?>);'><?= $type->label; ?>

any suggestions? thanks!

i have added another function (jquery one) that does partially what i need. the new problem is: i want that background color to be set only on the last clicked item, not on all items that i click. code above:

$(document).ready(function() {
    $('.product_types > li').click(function() {
    $(this)
        .css('background-color','#EE178C')
        .siblings()
        .css('background-color','#ffffff');
    });
});

any ideas why?

thanks!

Body:
Your element could have this code:

<li id = "product_types" onclick="selecteazaElement(this);" <...>  </li>

To change the foreground color of that element:

function selecteazaElement(element)
{
    element.style.foregroundColor="#SOMECOLOR";
}

If you want to change the background color on only the last element clicked, each element must have a different id.  I'd suggest naming each one something like product_types1, product_types2, ..., product_typesN, and so on.  Then have a reset function:

function Reset()
{
    for (var i = 1; i <= N; i = i + 1)
    {
        document.getElementById('product_types'+i).style.backgroundColor="#RESETCOLOR";
    }
}

When you call your selecteazaElement(this) function, first call the Reset function, then set the new element:

function selecteazaElement(element)
{
    Reset();
    element.style.backgroundColor="#SOMECOLOR";
}

This way all of the elements that start with product_types followed by a number will be reset to one particular color, and only the element clicked on will have the background changed.


问:
Client sent an HTTP request to an HTTPS server
I have a python application running on a virtual machine, were a legacy, and now I'm migrating to a Kubernetes.

I use influxdb==5.2.3 package, connecting to this form Influx(host=r'influx_HOST', port=8086, username='MY_USER', password='***', database='DB_NAME', ssl=True). This python script calls an InfluxBD using an SSL certificate and when I run directly using python app.py works well, but, the problem is when:

 I dockerized the script shows me the following error.

```<code>Traceback (most recent call last):
  File "app.py", line 591, in <module>
    get_horas_stock()
  File "app.py", line 513, in get_horas_stock
    df_temp = influx_temperatura.multiple_query_to_df(queries_temperatura)
  File "/usr/src/app/analitica_py_lib_conexiones/conexion_influx.py", line 82, in multiple_query_to_df
    resultado = self.__cliente.query(";".join(queries))
  File "/usr/local/lib/python3.8/site-packages/influxdb/client.py", line 445, in query
    response = self.request(
  File "/usr/local/lib/python3.8/site-packages/influxdb/client.py", line 302, in request
    raise InfluxDBClientError(response.content, response.status_code)
influxdb.exceptions.InfluxDBClientError: 400: Client sent an HTTP request to an HTTPS server.
</code>```

I understand to, from inside the container, the script is using https to call Influx, but I think the connection is redirected outside the container using Http and lose all SSL configuration, why? I don't know.

I tested deployed on Kubernetes

I tried to deploy on Kubernetes thinking I get the same error, but it`s changed.

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/urllib3/response.py", line 360, in _error_catcher
    yield
  File "/usr/local/lib/python3.8/site-packages/urllib3/response.py", line 442, in read
    data = self._fp.read(amt)
  File "/usr/local/lib/python3.8/http/client.py", line 454, in read
    n = self.readinto(b)
  File "/usr/local/lib/python3.8/http/client.py", line 498, in readinto
    n = self.fp.readinto(b)
  File "/usr/local/lib/python3.8/socket.py", line 669, in readinto
    return self._sock.recv_into(b)
ConnectionResetError: [Errno 104] Connection reset by peer

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/requests/models.py", line 750, in generate
    for chunk in self.raw.stream(chunk_size, decode_content=True):
  File "/usr/local/lib/python3.8/site-packages/urllib3/response.py", line 494, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/usr/local/lib/python3.8/site-packages/urllib3/response.py", line 459, in read
    raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
  File "/usr/local/lib/python3.8/contextlib.py", line 131, in __exit__
    self.gen.throw(type, value, traceback)
  File "/usr/local/lib/python3.8/site-packages/urllib3/response.py", line 378, in _error_catcher
    raise ProtocolError('Connection broken: %r' % e, e)
urllib3.exceptions.ProtocolError: ("Connection broken: ConnectionResetError(104, 'Connection reset by peer')", ConnectionResetError(104, 'Connection reset by peer'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "app.py", line 591, in <module>
    get_horas_stock()
  File "app.py", line 513, in get_horas_stock
    df_temp = influx_temperatura.multiple_query_to_df(queries_temperatura)
  File "/usr/src/app/analitica_py_lib_conexiones/conexion_influx.py", line 82, in multiple_query_to_df
    resultado = self.__cliente.query(";".join(queries))
  File "/usr/local/lib/python3.8/site-packages/influxdb/client.py", line 445, in query
    response = self.request(
  File "/usr/local/lib/python3.8/site-packages/influxdb/client.py", line 274, in request
    response = self._session.request(
  File "/usr/local/lib/python3.8/site-packages/requests/sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python3.8/site-packages/requests/sessions.py", line 686, in send
    r.content
  File "/usr/local/lib/python3.8/site-packages/requests/models.py", line 828, in content
    self._content = b''.join(self.iter_content(CONTENT_CHUNK_SIZE)) or b''
  File "/usr/local/lib/python3.8/site-packages/requests/models.py", line 753, in generate
    raise ChunkedEncodingError(e)
requests.exceptions.ChunkedEncodingError: ("Connection broken: ConnectionResetError(104, 'Connection reset by peer')", ConnectionResetError(104, 'Connection reset by peer'))
</code>```

I don't know if is related to the previous error.

Edited

Dockerfile

```<code>FROM python:3.8.2-buster

WORKDIR /usr/src/app

COPY . .

RUN pip install --no-cache-dir -r requirements.txt

EXPOSE 8080

CMD ["python", "app.py"]
</code>```

Kubernetes Deployment YML

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-ms
spec:
  replicas: 1
  selector:
    matchLabels:
      ip-service: my-ms
  template:
    metadata:
      labels:
        ip-service: my-ms
    spec:
      containers:
        - name: my-ms
          image: myprivate.azurecr.io/my-ms:latest
          ports:
            - containerPort: 8080
          resources:
            requests:
              cpu: 100m
              memory: 10Mi
      imagePullSecrets:
        - name: tecnoregistry
</code>```

Edited 2

I get the same error I have on Kubernetes, but running the script locally, I change the SSL value from True to False in the service call Influx(host=r'influx_HOST', port=8086, username='MY_USER', password='***', database='DB_NAME', ssl=False).

```<code>~$ python3 app.py
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/response.py", line 360, in _error_catcher
    yield
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/response.py", line 442, in read
    data = self._fp.read(amt)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 457, in read
    n = self.readinto(b)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 501, in readinto
    n = self.fp.readinto(b)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 589, in readinto
    return self._sock.recv_into(b)
ConnectionResetError: [Errno 54] Connection reset by peer

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py", line 750, in generate
    for chunk in self.raw.stream(chunk_size, decode_content=True):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/response.py", line 494, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/response.py", line 459, in read
    raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/contextlib.py", line 130, in __exit__
    self.gen.throw(type, value, traceback)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/response.py", line 378, in _error_catcher
    raise ProtocolError('Connection broken: %r' % e, e)
urllib3.exceptions.ProtocolError: ("Connection broken: ConnectionResetError(54, 'Connection reset by peer')", ConnectionResetError(54, 'Connection reset by peer'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "app.py", line 1272, in <module>
    generate_excels_consumo()
  File "/Volumes/DATA/IdeaProjects/australia/analitica_py_sw_recolect_info/calculo_excels.py", line 206, in generate_excels_consumo
    df_sector = influx_kpis.multiple_query_to_multiple_df(queries)
  File "/Volumes/DATA/IdeaProjects/australia/analitica_py_sw_recolect_info/analitica_py_lib_conexiones/conexion_influx.py", line 126, in multiple_query_to_multiple_df
    resultado = self.__cliente.query(";".join(query))
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/influxdb/client.py", line 450, in query
    expected_response_code=expected_response_code
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/influxdb/client.py", line 283, in request
    timeout=self._timeout
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py", line 686, in send
    r.content
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py", line 828, in content
    self._content = b''.join(self.iter_content(CONTENT_CHUNK_SIZE)) or b''
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py", line 753, in generate
    raise ChunkedEncodingError(e)
requests.exceptions.ChunkedEncodingError: ("Connection broken: ConnectionResetError(54, 'Connection reset by peer')", ConnectionResetError(54, 'Connection reset by peer'))
</code>```

答:
It seems to be a network problem. I faced a similar problem connecting with MongoDB because of Proxy.

By default, each container run by Docker has its own network namespace.

Offering Some Solution Methods:

traceroute <cluster-ip> perform this command and check whether arrive to cluster inside of container attach container and perform the command docker exec -it container /bin/bash.

Check Proxy. export check environment variables related with proxy.

curl www.google.com

Try to connect another things in the cluster. For example MySQL, etc. (Once time a machine write me blacklist automatically I tried to solve connection problem 2 day)

Try to use python-slim image. slim image is based from ubuntu.

It is very good document to understand and solve docker connection problem.

https://pythonspeed.com/articles/docker-connection-refused/

Body:
I have a python application running on a virtual machine, were a legacy, and now I'm migrating to a Kubernetes.

I use influxdb==5.2.3 package, connecting to this form Influx(host=r'influx_HOST', port=8086, username='MY_USER', password='***', database='DB_NAME', ssl=True). This python script calls an InfluxBD using an SSL certificate and when I run directly using python app.py works well, but, the problem is when:

 I dockerized the script shows me the following error.

Traceback (most recent call last):
  File "app.py", line 591, in <module>
    get_horas_stock()
  File "app.py", line 513, in get_horas_stock
    df_temp = influx_temperatura.multiple_query_to_df(queries_temperatura)
  File "/usr/src/app/analitica_py_lib_conexiones/conexion_influx.py", line 82, in multiple_query_to_df
    resultado = self.__cliente.query(";".join(queries))
  File "/usr/local/lib/python3.8/site-packages/influxdb/client.py", line 445, in query
    response = self.request(
  File "/usr/local/lib/python3.8/site-packages/influxdb/client.py", line 302, in request
    raise InfluxDBClientError(response.content, response.status_code)
influxdb.exceptions.InfluxDBClientError: 400: Client sent an HTTP request to an HTTPS server.

I understand to, from inside the container, the script is using https to call Influx, but I think the connection is redirected outside the container using Http and lose all SSL configuration, why? I don't know.

I tested deployed on Kubernetes

I tried to deploy on Kubernetes thinking I get the same error, but it`s changed.

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/urllib3/response.py", line 360, in _error_catcher
    yield
  File "/usr/local/lib/python3.8/site-packages/urllib3/response.py", line 442, in read
    data = self._fp.read(amt)
  File "/usr/local/lib/python3.8/http/client.py", line 454, in read
    n = self.readinto(b)
  File "/usr/local/lib/python3.8/http/client.py", line 498, in readinto
    n = self.fp.readinto(b)
  File "/usr/local/lib/python3.8/socket.py", line 669, in readinto
    return self._sock.recv_into(b)
ConnectionResetError: [Errno 104] Connection reset by peer

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/requests/models.py", line 750, in generate
    for chunk in self.raw.stream(chunk_size, decode_content=True):
  File "/usr/local/lib/python3.8/site-packages/urllib3/response.py", line 494, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/usr/local/lib/python3.8/site-packages/urllib3/response.py", line 459, in read
    raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
  File "/usr/local/lib/python3.8/contextlib.py", line 131, in __exit__
    self.gen.throw(type, value, traceback)
  File "/usr/local/lib/python3.8/site-packages/urllib3/response.py", line 378, in _error_catcher
    raise ProtocolError('Connection broken: %r' % e, e)
urllib3.exceptions.ProtocolError: ("Connection broken: ConnectionResetError(104, 'Connection reset by peer')", ConnectionResetError(104, 'Connection reset by peer'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "app.py", line 591, in <module>
    get_horas_stock()
  File "app.py", line 513, in get_horas_stock
    df_temp = influx_temperatura.multiple_query_to_df(queries_temperatura)
  File "/usr/src/app/analitica_py_lib_conexiones/conexion_influx.py", line 82, in multiple_query_to_df
    resultado = self.__cliente.query(";".join(queries))
  File "/usr/local/lib/python3.8/site-packages/influxdb/client.py", line 445, in query
    response = self.request(
  File "/usr/local/lib/python3.8/site-packages/influxdb/client.py", line 274, in request
    response = self._session.request(
  File "/usr/local/lib/python3.8/site-packages/requests/sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python3.8/site-packages/requests/sessions.py", line 686, in send
    r.content
  File "/usr/local/lib/python3.8/site-packages/requests/models.py", line 828, in content
    self._content = b''.join(self.iter_content(CONTENT_CHUNK_SIZE)) or b''
  File "/usr/local/lib/python3.8/site-packages/requests/models.py", line 753, in generate
    raise ChunkedEncodingError(e)
requests.exceptions.ChunkedEncodingError: ("Connection broken: ConnectionResetError(104, 'Connection reset by peer')", ConnectionResetError(104, 'Connection reset by peer'))

I don't know if is related to the previous error.

Edited

Dockerfile

FROM python:3.8.2-buster

WORKDIR /usr/src/app

COPY . .

RUN pip install --no-cache-dir -r requirements.txt

EXPOSE 8080

CMD ["python", "app.py"]

Kubernetes Deployment YML

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-ms
spec:
  replicas: 1
  selector:
    matchLabels:
      ip-service: my-ms
  template:
    metadata:
      labels:
        ip-service: my-ms
    spec:
      containers:
        - name: my-ms
          image: myprivate.azurecr.io/my-ms:latest
          ports:
            - containerPort: 8080
          resources:
            requests:
              cpu: 100m
              memory: 10Mi
      imagePullSecrets:
        - name: tecnoregistry

Edited 2

I get the same error I have on Kubernetes, but running the script locally, I change the SSL value from True to False in the service call Influx(host=r'influx_HOST', port=8086, username='MY_USER', password='***', database='DB_NAME', ssl=False).

~$ python3 app.py
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/response.py", line 360, in _error_catcher
    yield
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/response.py", line 442, in read
    data = self._fp.read(amt)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 457, in read
    n = self.readinto(b)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 501, in readinto
    n = self.fp.readinto(b)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 589, in readinto
    return self._sock.recv_into(b)
ConnectionResetError: [Errno 54] Connection reset by peer

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py", line 750, in generate
    for chunk in self.raw.stream(chunk_size, decode_content=True):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/response.py", line 494, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/response.py", line 459, in read
    raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/contextlib.py", line 130, in __exit__
    self.gen.throw(type, value, traceback)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/response.py", line 378, in _error_catcher
    raise ProtocolError('Connection broken: %r' % e, e)
urllib3.exceptions.ProtocolError: ("Connection broken: ConnectionResetError(54, 'Connection reset by peer')", ConnectionResetError(54, 'Connection reset by peer'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "app.py", line 1272, in <module>
    generate_excels_consumo()
  File "/Volumes/DATA/IdeaProjects/australia/analitica_py_sw_recolect_info/calculo_excels.py", line 206, in generate_excels_consumo
    df_sector = influx_kpis.multiple_query_to_multiple_df(queries)
  File "/Volumes/DATA/IdeaProjects/australia/analitica_py_sw_recolect_info/analitica_py_lib_conexiones/conexion_influx.py", line 126, in multiple_query_to_multiple_df
    resultado = self.__cliente.query(";".join(query))
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/influxdb/client.py", line 450, in query
    expected_response_code=expected_response_code
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/influxdb/client.py", line 283, in request
    timeout=self._timeout
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py", line 686, in send
    r.content
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py", line 828, in content
    self._content = b''.join(self.iter_content(CONTENT_CHUNK_SIZE)) or b''
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py", line 753, in generate
    raise ChunkedEncodingError(e)
requests.exceptions.ChunkedEncodingError: ("Connection broken: ConnectionResetError(54, 'Connection reset by peer')", ConnectionResetError(54, 'Connection reset by peer'))


问:
Unable to verify a Valid token with a VALID secret
I googled 2 pages and haven't found any solution to the problem. The token, as well as the public key are valid,

Here is a link to jwt debugger

And the implementation

```<code>package internal

import (
    "fmt"
    "log"
    "net/http"

    "github.com/dgrijalva/jwt-go"
)

const publicKey = `-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA1PlcNpfUNweGd3eSRLuF
Cp0kZpdsO9tzHCkKMxgaU3jvQI9BzWPdljJfxwEedmEWlJ9G/4oCLdB0w5JhYNoR
uOvs02/goDduPWlnr9cwRsGG3hFDbY8oJ4i9APj6jQFCTvP+yfI7e12SV6RDb58z
7qO4g1BJqoc8sXPk/VsFQMnNuTs7qLM1aWl3uZUXqSrCqJY92YerbDdH5J8LFEi7
aTL7opu1GZ8s75SRWpzg5AjdXGseEm5sjGpURSdmPq8hH7u6+AQBZPTy9ozsgX2V
2Hj0X8Q/AAzrh4mFpnVj8mT/Kny7OcG+yjW+Nwqnq2zFeuyQISQgAMzrnn2GClsi
KUET2yRV2+5l5VZOhLDc8mF6vU2L5aSwZ2zoTGEt/su44tMRXQwoBK99yS7R59pg
IV5x2wusPUmz0IS3y0b6PlLUb4BdMhBLBN1Wy+hIuN1HCptOeKrqvaCrA3ABP/9O
/xJUK8xJDPZS+YW47uJqxk1Hon4ql9dEjOb8Q1onuhC1BRKbWcx3qTOEGbxaT0hT
gX2cTZ8dsFB3iJkDAS0/Xx6nO+a/xgXsWluUkvmrfbYlVgcz3inDWRQ3hSGjvnHK
DJZQju2Vi+v/F9joKUKb8AYnkE1vkRoAgYQ84rU+VpEk+iVL7xtVP63noMUyqtha
aPMC597mD4QGFw7wcXcxCx0CAwEAAQ==
-----END PUBLIC KEY-----`

const testToken = `eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlYzI4ZWEwMzgyMjI3ZDM4MzA4ZWI1ZiIsImlhdCI6MTU5MDY5NDM2MCwiZXhwIjoxNTkwNzgwNzYwfQ.nkP8Ot8bdLy_HwJ05IEMcZY5rpkMGbnMjMRtNrNKhm9UX3yMCWra3mwqnWQSXLoqSucxm3ngF4bsuegxVxczdzFj34cjeAtJZ21YFlNYq6y7FoEsTB3HZ4SXkbLeiCireVVzj1-ynbE0u97wELtjZ8mhkD29CesxRUNtaMP39cZk_nPz62oQQVnUYTE7CrN13mmlkWHC0hGxk_qNe-x9XvGWbVdJlmguuA1IrS3X6xNCk17igcWD97B3yAWSMAryXtJMuMGIX8lC0nGKIUhg-eumeziSB1j12LIAvVlY3bd6zRHsTUJjr8dQpP6T-kZk1zUAZRcl9CFX0a8XWoXjNsK6-NngovvnxK2eM-_QYPtUjMBt0bN89hnYycfnvT8ItdUQwkEpBzqMyeU2Bc1YslJZE9oz0MJ3PZ5iuOV4yKULyOmVJyESs_ViOUzCrzPbfvPXMVmdpabn3j8FHS6X8ixoixjqtNHv1WItN8BMsm377cdB_QyxKLHgbrd_DfiCXKxC01szttPgF5B9-8mxvv7VpZuIpQ7-KnStrJgfRVKaD5dPIHoLRHKRgO-fZ0tLDB4D5hdj1zs32JUZUQ-uQew0p3lXpYmWku67n8U_WVXUD8YOPTD6GVMdiAB8cZl1hOMAs1tjicIhnE7VLwK1ogOAJVq6OTpuVmmD5ALRxyI`

func VerifyToken() bool {

    claims := jwt.MapClaims{}

    token, err := jwt.ParseWithClaims(testToken, claims, func(token *jwt.Token) (interface{}, error) {
        return []byte(publicKey), nil
    })
    log.Printf("%v", err)
    log.Printf("%v", token.Valid)
    for key, val := range claims {
        fmt.Printf("Key: %v, value: %v\n", key, val)
    }

    return true
}

</code>```

The verification fails no matter what. However, it does work with Node.JS library as well as in the above-mentioned jwt debugger.

答:
You are trying to validate the token using a PEM encoded key. You have to decode the key and parse it for validation. The validation requires a key object depending on the signing algorithm:</p>

```<code>token, err := jwt.ParseWithClaims(testToken, claims, func(token *jwt.Token) (interface{}, error) {
    block, _ := pem.Decode([]byte(publicKey))
    if block==nil {
        // return error
    }

    return x509.ParsePKIXPublicKey(block.Bytes)
 })
</code>```

Body:
I googled 2 pages and haven't found any solution to the problem. The token, as well as the public key are valid,

Here is a link to <a href="https://jwt.io/#debugger-io?token=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlYzI4ZWEwMzgyMjI3ZDM4MzA4ZWI1ZiIsImlhdCI6MTU5MDY5NDM2MCwiZXhwIjoxNTkwNzgwNzYwfQ.nkP8Ot8bdLy_HwJ05IEMcZY5rpkMGbnMjMRtNrNKhm9UX3yMCWra3mwqnWQSXLoqSucxm3ngF4bsuegxVxczdzFj34cjeAtJZ21YFlNYq6y7FoEsTB3HZ4SXkbLeiCireVVzj1-ynbE0u97wELtjZ8mhkD29CesxRUNtaMP39cZk_nPz62oQQVnUYTE7CrN13mmlkWHC0hGxk_qNe-x9XvGWbVdJlmguuA1IrS3X6xNCk17igcWD97B3yAWSMAryXtJMuMGIX8lC0nGKIUhg-eumeziSB1j12LIAvVlY3bd6zRHsTUJjr8dQpP6T-kZk1zUAZRcl9CFX0a8XWoXjNsK6-NngovvnxK2eM-_QYPtUjMBt0bN89hnYycfnvT8ItdUQwkEpBzqMyeU2Bc1YslJZE9oz0MJ3PZ5iuOV4yKULyOmVJyESs_ViOUzCrzPbfvPXMVmdpabn3j8FHS6X8ixoixjqtNHv1WItN8BMsm377cdB_QyxKLHgbrd_DfiCXKxC01szttPgF5B9-8mxvv7VpZuIpQ7-KnStrJgfRVKaD5dPIHoLRHKRgO-fZ0tLDB4D5hdj1zs32JUZUQ-uQew0p3lXpYmWku67n8U_WVXUD8YOPTD6GVMdiAB8cZl1hOMAs1tjicIhnE7VLwK1ogOAJVq6OTpuVmmD5ALRxyI&publicKey=-----BEGIN%20PUBLIC%20KEY-----%0AMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA1PlcNpfUNweGd3eSRLuF%0ACp0kZpdsO9tzHCkKMxgaU3jvQI9BzWPdljJfxwEedmEWlJ9G%2F4oCLdB0w5JhYNoR%0AuOvs02%2FgoDduPWlnr9cwRsGG3hFDbY8oJ4i9APj6jQFCTvP%2ByfI7e12SV6RDb58z%0A7qO4g1BJqoc8sXPk%2FVsFQMnNuTs7qLM1aWl3uZUXqSrCqJY92YerbDdH5J8LFEi7%0AaTL7opu1GZ8s75SRWpzg5AjdXGseEm5sjGpURSdmPq8hH7u6%2BAQBZPTy9ozsgX2V%0A2Hj0X8Q%2FAAzrh4mFpnVj8mT%2FKny7OcG%2ByjW%2BNwqnq2zFeuyQISQgAMzrnn2GClsi%0AKUET2yRV2%2B5l5VZOhLDc8mF6vU2L5aSwZ2zoTGEt%2Fsu44tMRXQwoBK99yS7R59pg%0AIV5x2wusPUmz0IS3y0b6PlLUb4BdMhBLBN1Wy%2BhIuN1HCptOeKrqvaCrA3ABP%2F9O%0A%2FxJUK8xJDPZS%2BYW47uJqxk1Hon4ql9dEjOb8Q1onuhC1BRKbWcx3qTOEGbxaT0hT%0AgX2cTZ8dsFB3iJkDAS0%2FXx6nO%2Ba%2FxgXsWluUkvmrfbYlVgcz3inDWRQ3hSGjvnHK%0ADJZQju2Vi%2Bv%2FF9joKUKb8AYnkE1vkRoAgYQ84rU%2BVpEk%2BiVL7xtVP63noMUyqtha%0AaPMC597mD4QGFw7wcXcxCx0CAwEAAQ%3D%3D%0A-----END%20PUBLIC%20KEY-----" rel="nofollow noreferrer">jwt debugger

And the implementation

package internal

import (
    "fmt"
    "log"
    "net/http"

    "github.com/dgrijalva/jwt-go"
)

const publicKey = `-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA1PlcNpfUNweGd3eSRLuF
Cp0kZpdsO9tzHCkKMxgaU3jvQI9BzWPdljJfxwEedmEWlJ9G/4oCLdB0w5JhYNoR
uOvs02/goDduPWlnr9cwRsGG3hFDbY8oJ4i9APj6jQFCTvP+yfI7e12SV6RDb58z
7qO4g1BJqoc8sXPk/VsFQMnNuTs7qLM1aWl3uZUXqSrCqJY92YerbDdH5J8LFEi7
aTL7opu1GZ8s75SRWpzg5AjdXGseEm5sjGpURSdmPq8hH7u6+AQBZPTy9ozsgX2V
2Hj0X8Q/AAzrh4mFpnVj8mT/Kny7OcG+yjW+Nwqnq2zFeuyQISQgAMzrnn2GClsi
KUET2yRV2+5l5VZOhLDc8mF6vU2L5aSwZ2zoTGEt/su44tMRXQwoBK99yS7R59pg
IV5x2wusPUmz0IS3y0b6PlLUb4BdMhBLBN1Wy+hIuN1HCptOeKrqvaCrA3ABP/9O
/xJUK8xJDPZS+YW47uJqxk1Hon4ql9dEjOb8Q1onuhC1BRKbWcx3qTOEGbxaT0hT
gX2cTZ8dsFB3iJkDAS0/Xx6nO+a/xgXsWluUkvmrfbYlVgcz3inDWRQ3hSGjvnHK
DJZQju2Vi+v/F9joKUKb8AYnkE1vkRoAgYQ84rU+VpEk+iVL7xtVP63noMUyqtha
aPMC597mD4QGFw7wcXcxCx0CAwEAAQ==
-----END PUBLIC KEY-----`

const testToken = `eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlYzI4ZWEwMzgyMjI3ZDM4MzA4ZWI1ZiIsImlhdCI6MTU5MDY5NDM2MCwiZXhwIjoxNTkwNzgwNzYwfQ.nkP8Ot8bdLy_HwJ05IEMcZY5rpkMGbnMjMRtNrNKhm9UX3yMCWra3mwqnWQSXLoqSucxm3ngF4bsuegxVxczdzFj34cjeAtJZ21YFlNYq6y7FoEsTB3HZ4SXkbLeiCireVVzj1-ynbE0u97wELtjZ8mhkD29CesxRUNtaMP39cZk_nPz62oQQVnUYTE7CrN13mmlkWHC0hGxk_qNe-x9XvGWbVdJlmguuA1IrS3X6xNCk17igcWD97B3yAWSMAryXtJMuMGIX8lC0nGKIUhg-eumeziSB1j12LIAvVlY3bd6zRHsTUJjr8dQpP6T-kZk1zUAZRcl9CFX0a8XWoXjNsK6-NngovvnxK2eM-_QYPtUjMBt0bN89hnYycfnvT8ItdUQwkEpBzqMyeU2Bc1YslJZE9oz0MJ3PZ5iuOV4yKULyOmVJyESs_ViOUzCrzPbfvPXMVmdpabn3j8FHS6X8ixoixjqtNHv1WItN8BMsm377cdB_QyxKLHgbrd_DfiCXKxC01szttPgF5B9-8mxvv7VpZuIpQ7-KnStrJgfRVKaD5dPIHoLRHKRgO-fZ0tLDB4D5hdj1zs32JUZUQ-uQew0p3lXpYmWku67n8U_WVXUD8YOPTD6GVMdiAB8cZl1hOMAs1tjicIhnE7VLwK1ogOAJVq6OTpuVmmD5ALRxyI`

func VerifyToken() bool {

    claims := jwt.MapClaims{}

    token, err := jwt.ParseWithClaims(testToken, claims, func(token *jwt.Token) (interface{}, error) {
        return []byte(publicKey), nil
    })
    log.Printf("%v", err)
    log.Printf("%v", token.Valid)
    for key, val := range claims {
        fmt.Printf("Key: %v, value: %v\n", key, val)
    }

    return true
}

The verification fails no matter what. However, it does work with Node.JS library as well as in the above-mentioned jwt debugger.

Body:
You are trying to validate the token using a PEM encoded key. You have to decode the key and parse it for validation. The validation requires a key object depending on the signing algorithm:

token, err := jwt.ParseWithClaims(testToken, claims, func(token *jwt.Token) (interface{}, error) {
    block, _ := pem.Decode([]byte(publicKey))
    if block==nil {
        // return error
    }

    return x509.ParsePKIXPublicKey(block.Bytes)
 })


问:
How to perform cluster with weights/density in python? Something like kmeans with weights?
My data is like this:

```<code>powerplantname, latitude, longitude, powergenerated
A, -92.3232, 100.99, 50
B, <lat>, <long>, 10
C, <lat>, <long>, 20
D, <lat>, <long>, 40
E, <lat>, <long>, 5
</code>```

I want to be able to cluster the data into N number of clusters (say 3). Normally I would use a kmeans:

```<code>import numpy as np

import matplotlib.pyplot as plt
from scipy.cluster.vq import kmeans2, whiten
coordinates= np.array([
           [lat, long],
           [lat, long],
            ...
           [lat, long]
           ])
x, y = kmeans2(whiten(coordinates), 3, iter = 20)
plt.scatter(coordinates[:,0], coordinates[:,1], c=y);
plt.show()
</code>```

The problem with this is it does not account for any weighting (in this case, my powergenerated value) I want to ideally have my clusters taking the value "powergenerated" into account, trying to keep the clusters not only spatially close, but also have close to relatively equal total powergenerated.

Should I be doing this with kmeans (or some other method)? Or is there something else I should be using for this problem that would be better?

答: If you are looking for a solution where you form clusters based on coordinates and power being weights to these co-ordinates, you can add sample_weight= power. This will give you clusters based on coordinates and centroid will be leaning towards the higher weights observations in the cluster</p>

Body:
My data is like this:

powerplantname, latitude, longitude, powergenerated
A, -92.3232, 100.99, 50
B, <lat>, <long>, 10
C, <lat>, <long>, 20
D, <lat>, <long>, 40
E, <lat>, <long>, 5

I want to be able to cluster the data into N number of clusters (say 3). Normally I would use a kmeans:

import numpy as np

import matplotlib.pyplot as plt
from scipy.cluster.vq import kmeans2, whiten
coordinates= np.array([
           [lat, long],
           [lat, long],
            ...
           [lat, long]
           ])
x, y = kmeans2(whiten(coordinates), 3, iter = 20)
plt.scatter(coordinates[:,0], coordinates[:,1], c=y);
plt.show()

The problem with this is it does not account for any weighting (in this case, my powergenerated value) I want to ideally have my clusters taking the value "powergenerated" into account, trying to keep the clusters not only spatially close, but also have close to relatively equal total powergenerated.

Should I be doing this with kmeans (or some other method)? Or is there something else I should be using for this problem that would be better?


问:
Why string str = new string("abc") doesn't pass compiler?
Given public String(char*) why we cannot use the following statement?

```<code>string str = new string("aaa");
</code>```

Error   1

The best overloaded method match for
  'string.String(char*)' has some
  invalid
  arguments C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  26  ConsoleApplication2

Error   2

Argument 1: cannot convert from
  'string' to
  'char*'   C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  37  ConsoleApplication2

答:
Because this isn't meant to be used in safe code...

In C#, this constructor is defined only in the context of unsafe code.

from: http://msdn.microsoft.com/en-us/library/6y4za026.aspx

If you need to construct a string you could just use the literal decleration..

```<code>string str = "aaa";
</code>```

Body:
Given public String(char*) why we cannot use the following statement?

string str = new string("aaa");

Error   1

The best overloaded method match for
  'string.String(char*)' has some
  invalid
  arguments C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  26  ConsoleApplication2

Error   2

Argument 1: cannot convert from
  'string' to
  'char*'   C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  37  ConsoleApplication2

Body:
Because this isn't meant to be used in safe code...

In C#, this constructor is defined only in the context of unsafe code.

from: http://msdn.microsoft.com/en-us/library/6y4za026.aspx

If you need to construct a string you could just use the literal decleration..

string str = "aaa";


问:
F# client, IIS7, and WCF
I am trying to learn a bit of F# and thought I would start by creating a "data layer" for my client applications.

I currently have a very large visual studio client solution in C# that accesses a PostgreSQL database via WCF services (hosted in IIS7). I have grown quite spoiled by the "Add Service Reference" ability of WCF to create proxy clients and DTO's.

I am new to F#. Is there any similar process of automatically creating client DTO's and proxies in an F# project for WCF services? And if not, what would be the recommended process of creating F# types for access to the WCF services?

Any starting point would be helpful, as most of the Googled references are very old.

TIA.

答:
You could use the WSDL type provider

https://fsprojects.github.io/FSharp.Data.TypeProviders/wsdl.html

Title: F# client, IIS7, and WCF


问:
How to count one column and adding up several columns at the same time using summarise in dplyr R
I have this dataframe (there are 20 more columns like class but just for the example I show a short version):

```<code> niv  ID  class1 class2 class3
  A   x    10      5      7
  A   y    15      3      1
  A   z    11      2      4
  B   u    17      7      3
  B   w    18      7      9
</code>```

So I wanted to group_by(niv) and to summarise the ID column just counting it and class1, class2 and class3 columns to add up in just one command. I tried summarise_each but I can't sort out how to use it. Also the objetive would be to learn how to mix different funs in the summarise function when you have a dataframe with a lot of columns.

The summarise dataframe I need is this one:

```<code> niv  n_ID  sum_class1 sum_class2 sum_class3
  A    3        36         10         12
  B    2        35         14         12
</code>```

Thanks in advance.

答:
We can use summarise with across

```<code>library(dplyr)
df %>%
   mutate(n_ID = 1) %>%
   group_by(niv) %>%
   summarise(across(starts_with('class'), sum))
</code>```

With across, we can have multiple functions

```<code>iris %>%
   summarise(across(where(is.factor), nlevels),
            across(where(is.numeric), mean))
#  Species Sepal.Length Sepal.Width Petal.Length Petal.Width
#1       3     5.843333    3.057333        3.758    1.199333
</code>```

data

```<code>df <- structure(list(niv = c("A", "A", "A", "B", "B"), ID = c("x",
"y", "z", "u", "w"), class1 = c(10L, 15L, 11L, 17L, 18L), class2 = c(5L,
3L, 2L, 7L, 7L), class3 = c(7L, 1L, 4L, 3L, 9L)),
class = "data.frame", row.names = c(NA, -5L))
</code>```

Body:
I have this dataframe (there are 20 more columns like class but just for the example I show a short version):

 niv  ID  class1 class2 class3
  A   x    10      5      7
  A   y    15      3      1
  A   z    11      2      4
  B   u    17      7      3
  B   w    18      7      9

So I wanted to group_by(niv) and to summarise the ID column just counting it and class1, class2 and class3 columns to add up in just one command. I tried summarise_each but I can't sort out how to use it. Also the objetive would be to learn how to mix different funs in the summarise function when you have a dataframe with a lot of columns.

The summarise dataframe I need is this one:

 niv  n_ID  sum_class1 sum_class2 sum_class3
  A    3        36         10         12
  B    2        35         14         12

Thanks in advance.

Body:
We can use summarise with across

library(dplyr)
df %>%
   mutate(n_ID = 1) %>%
   group_by(niv) %>%
   summarise(across(starts_with('class'), sum))

With across, we can have multiple functions

iris %>%
   summarise(across(where(is.factor), nlevels),
            across(where(is.numeric), mean))
#  Species Sepal.Length Sepal.Width Petal.Length Petal.Width
#1       3     5.843333    3.057333        3.758    1.199333

data

df <- structure(list(niv = c("A", "A", "A", "B", "B"), ID = c("x",
"y", "z", "u", "w"), class1 = c(10L, 15L, 11L, 17L, 18L), class2 = c(5L,
3L, 2L, 7L, 7L), class3 = c(7L, 1L, 4L, 3L, 9L)),
class = "data.frame", row.names = c(NA, -5L))


问:
Reading property from body with req.body
In the application generating dummy data every second and when I log it with "req.body" the output as below.

```<code>[
  {
    dataType: 'Number',
    deviceName: 'device1',
    attributeName: 'value',
    min: '1',
    max: '11',
    value: '9.000438216772668',
    ESP_OPS: 'i',
    timestamp: '2020-05-28T20:08:56.544Z'
  }
]
</code>```

However I would like to get "value" in this array. When I try to log it with "req.body.value" it returns "undefined". How can I catch "value" in this array?

答:
Just use req.body[0].value

The [0] statement have the function to reference the first element of the array.

Body:
In the application generating dummy data every second and when I log it with "req.body" the output as below.

[
  {
    dataType: 'Number',
    deviceName: 'device1',
    attributeName: 'value',
    min: '1',
    max: '11',
    value: '9.000438216772668',
    ESP_OPS: 'i',
    timestamp: '2020-05-28T20:08:56.544Z'
  }
]

However I would like to get "value" in this array. When I try to log it with "req.body.value" it returns "undefined". How can I catch "value" in this array?


问:
Creating a new column in a specific place in Pandas
I would like to create a new column in Python and place in a specific position. For instance, let "example" be the following dataframe:

```<code>import pandas as pd

example = pd.DataFrame({
            'name': ['alice','bob','charlie'],
            'age': [25,26,27],
            'job': ['manager','clerk','policeman'],
            'gender': ['female','male','male'],
            'nationality': ['french','german','american']
        })
</code>```

I would like to create a new column to contain the values of the column "age":

```<code>example['age_times_two']= example['age'] *2
</code>```

Yet, this code creates a column at the end of the dataframe. I would like to place it as the third column, or, in other words, the column right next to the column "age". How could this be done:

a) By setting an absolute place to the new column (e.g. third position)?

b) By setting a relative place for the new column (e.g. right to the column "age")?

答:
This is a bit manual way of doing it:

```<code>example['age_times_two']= example['age'] *2

cols = list(example.columns.values)
cols
</code>```

You get a list of all the columns, and you can rearrange them manually and place them in the code below

```<code>example = example[['name', 'age', 'age_times_two', 'job', 'gender', 'nationality']]
</code>```

Body:
I would like to create a new column in Python and place in a specific position. For instance, let "example" be the following dataframe:

import pandas as pd

example = pd.DataFrame({
            'name': ['alice','bob','charlie'],
            'age': [25,26,27],
            'job': ['manager','clerk','policeman'],
            'gender': ['female','male','male'],
            'nationality': ['french','german','american']
        })

I would like to create a new column to contain the values of the column "age":

example['age_times_two']= example['age'] *2

Yet, this code creates a column at the end of the dataframe. I would like to place it as the third column, or, in other words, the column right next to the column "age". How could this be done:

a) By setting an absolute place to the new column (e.g. third position)?

b) By setting a relative place for the new column (e.g. right to the column "age")?

Body:
This is a bit manual way of doing it:

example['age_times_two']= example['age'] *2

cols = list(example.columns.values)
cols

You get a list of all the columns, and you can rearrange them manually and place them in the code below

example = example[['name', 'age', 'age_times_two', 'job', 'gender', 'nationality']]


问:
How to change default strong blue color in HTML form controls in Chrome?

Is there any workaround except using 3 rd css libraries to change default sharp blue styling of input elements? After such update the look of complicated interfaces happened to be completely inconsistent...

答:
I don't think that the way a checkbox or similar inputs look can be changes with CSS, because they are part of the browser's interface. So what could you do?

CSS libraries are a solution, as you have already suggested.

If it was only the brightness of the blue colour you didn't like, an alternative could be to lay another element over each checkbox with a reduced opacity (a div with an absolute position and a white fill could be a solution).

The disadvantage of this approach is that it would require adding additional elements to your HTML, and the appearances available would still be very limited.

I would recommend creating your own checkboxes with CSS – it isn't actually that difficult, and the checkbox input elements can remain as they are now in the background.

I think that this tutorial on w3schools might be quite useful for you. Maybe a little more work, but with the extra advantage that your checkboxes etc. look exactly the way you want them to, not just in chrome but in every browser.

Sorry I couldn't provide a single, simple solution, but I hope it helped a bit!


问:
How can i remove different items on same page
how can i remove different items on same page without reloading page
like i want to remove some items and leave the rest </p>

```<code><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").remove();
  });
});
</script>
</head>
<body>

<div>
<p>remove this paragraph</p><button>close</button>
<p>leave this paragraph</p><button>close</button>
<p>remove this paragraph</p><button>close</button>
<p>leave this paragraph</p><button>close</button>
</div>
</body>
</html>
</code>```

答:
Here is a way to remove the previous paragraph of the button and the button as well:

```<code>$(document).ready(function(){
  $('button').click(function(){
    $( this ).prev('p').remove();
    $( this ).remove();
  });
});
</code>```

Demo there: https://codepen.io/aureliendebord/full/vYNqdrw

Body:
how can i remove different items on same page without reloading page
like i want to remove some items and leave the rest

<!DOCTYPE html>

remove this paragraph
<button>close</button>

leave this paragraph
<button>close</button>

remove this paragraph
<button>close</button>

leave this paragraph
<button>close</button>

Body:
Here is a way to remove the previous paragraph of the button and the button as well:

$(document).ready(function(){
  $('button').click(function(){
    $( this ).prev('p').remove();
    $( this ).remove();
  });
});

Demo there: https://codepen.io/aureliendebord/full/vYNqdrw


问:
Unable to add in app products in google play console suddenly ( Please check the list below for problems. )
My app was published about 4-5 months ago. My in-app products works fine. Suddenly I am unable to add or edit new in-app products. It shows me error "Please check the list below for problems.", but there is no problem in the list. Any help will be appreciated.

答: I enabled Managed Google Play option in Pricing & distribution page under Store presence section and that did the trick.


问:
Splitting items in a list - R
I have some items in my list that have / built in to them.
I want to split and duplucate them, e.g
a/b/c z -> becomes
a z
b z
c z

This is an example of my data but i don't have a clue on how to start. Any thoughts?

```<code>structure(list(keyword = c("deltoid muscle", "teres major/minor muscle",
"latissimus dorsi muscle", "serratus anterior/posterior superior/inferior muscle",
"levator scapulae", "rhomboid major/minor muscle", "erector spinae muscle",
"thoracolumbar fascia.", "Bone â\200“", "Clavicle:")), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

e.g The output of

```<code>"rhomboid major/minor muscle"
</code>```

should be

```<code>"rhomboid major  muscle"
</code>```

and

```<code> "rhomboid minor muscle"
</code>```

Thanks!

答:
Here is a data.table-approach. I've been struggling with this one, so the code is MOST SURE not the best/most elegant. It should work no matter how many ../.. choices are presented in a string (not tested).

I'm open for all improvements..

but it seems to get the job done...

sample data

```<code>library( data.table)
DT <- structure(list(keyword = c("deltoid muscle", "teres major/minor muscle",
                           "latissimus dorsi muscle", "serratus anterior/posterior superior/inferior muscle",
                           "levator scapulae", "rhomboid major/minor muscle", "erector spinae muscle",
                           "thoracolumbar fascia.", "Bone â\200“", "Clavicle:")), row.names = c(NA,
                                                                                -10L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

code

```<code>setDT( DT )

#cut string into parts
DT[, paste0( "part_", 1:length( tstrsplit( gsub("([a-z]+\\/[a-z]+)", "~\\1~", DT$keyword ), "~" ) ) ) :=
               tstrsplit( gsub("([a-z]+\\/[a-z]+)", "~\\1~", DT$keyword ), "~" ) ][]

#replace all NA with %-sing (or any other sign that does NOT appear in your data!!)
#it can be removed later on
DT[ is.na(DT) ] <- "%"

#split all .../... values to a vector
cols = grep( "^part_", names(DT), value = TRUE )
DT[, (cols) := lapply( .SD, strsplit, "/" ), .SDcols = cols ][]

#now throw it all together
answer <- data.table::rbindlist( lapply( transpose( DT[, .SD, .SDcols = cols ] ), function(x) do.call( expand.grid, x ) ) )
answer[, final := Reduce( function(...) paste0(..., sep = ""), .SD[, mget(cols)])]

#now remove the "%"-sing
gsub( "%", "", answer$final )
</code>```

output

looks all right...

```<code># [1] "deltoid muscle"                     "teres major muscle"                 "teres minor muscle"
# [4] "latissimus dorsi muscle"            "serratus anterior superior muscle"  "serratus posterior superior muscle"
# [7] "serratus anterior inferior muscle"  "serratus posterior inferior muscle" "levator scapulae"
# [10] "rhomboid major muscle"              "rhomboid minor muscle"              "erector spinae muscle"
# [13] "thoracolumbar fascia."              "Bone â€“"                           "Clavicle:"
</code>```

Title: Splitting items in a list - R

Body:
I have some items in my list that have / built in to them.
I want to split and duplucate them, e.g
a/b/c z -> becomes
a z
b z
c z

This is an example of my data but i don't have a clue on how to start. Any thoughts?

structure(list(keyword = c("deltoid muscle", "teres major/minor muscle",
"latissimus dorsi muscle", "serratus anterior/posterior superior/inferior muscle",
"levator scapulae", "rhomboid major/minor muscle", "erector spinae muscle",
"thoracolumbar fascia.", "Bone â\200“", "Clavicle:")), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))

e.g The output of

"rhomboid major/minor muscle"

should be

"rhomboid major  muscle"

and

 "rhomboid minor muscle"

Thanks!

Body:
Here is a data.table-approach. I've been struggling with this one, so the code is MOST SURE not the best/most elegant. It should work no matter how many ../.. choices are presented in a string (not tested).

I'm open for all improvements..

but it seems to get the job done...

sample data

library( data.table)
DT <- structure(list(keyword = c("deltoid muscle", "teres major/minor muscle",
                           "latissimus dorsi muscle", "serratus anterior/posterior superior/inferior muscle",
                           "levator scapulae", "rhomboid major/minor muscle", "erector spinae muscle",
                           "thoracolumbar fascia.", "Bone â\200“", "Clavicle:")), row.names = c(NA,
                                                                                -10L), class = c("tbl_df", "tbl", "data.frame"))

code

setDT( DT )

#cut string into parts
DT[, paste0( "part_", 1:length( tstrsplit( gsub("([a-z]+\\/[a-z]+)", "~\\1~", DT$keyword ), "~" ) ) ) :=
               tstrsplit( gsub("([a-z]+\\/[a-z]+)", "~\\1~", DT$keyword ), "~" ) ][]

#replace all NA with %-sing (or any other sign that does NOT appear in your data!!)
#it can be removed later on
DT[ is.na(DT) ] <- "%"

#split all .../... values to a vector
cols = grep( "^part_", names(DT), value = TRUE )
DT[, (cols) := lapply( .SD, strsplit, "/" ), .SDcols = cols ][]

#now throw it all together
answer <- data.table::rbindlist( lapply( transpose( DT[, .SD, .SDcols = cols ] ), function(x) do.call( expand.grid, x ) ) )
answer[, final := Reduce( function(...) paste0(..., sep = ""), .SD[, mget(cols)])]

#now remove the "%"-sing
gsub( "%", "", answer$final )

output

looks all right...

# [1] "deltoid muscle"                     "teres major muscle"                 "teres minor muscle"
# [4] "latissimus dorsi muscle"            "serratus anterior superior muscle"  "serratus posterior superior muscle"
# [7] "serratus anterior inferior muscle"  "serratus posterior inferior muscle" "levator scapulae"
# [10] "rhomboid major muscle"              "rhomboid minor muscle"              "erector spinae muscle"
# [13] "thoracolumbar fascia."              "Bone â€“"                           "Clavicle:"


问:
How to rotate a node around a point outside of the object (i.e don't rotate around the center point of the object)
What I have Right now, my game loads up on the simulator on Xcode as it should, but when I tap the screen, "basic Top" doesn't rotate. Basic top is one of four triangles that makes up a square.

What I want In order to make that square rotate I have to get all four triangles to rotate. Right now, basic top doesn't rotate even when I click on the screen. Once I get basic top to rotate, I can replicate the code for the other triangles in order to make a square that rotates. I need these four triangles all to rotate around a certain point.

Code

```<code>class GameScene: SKScene {
var brickSwitch: SKSpriteNode!
var basicTop = SKSpriteNode(imageNamed: "Top Side");
var basicBottom: SKSpriteNode!
var basicLeft: SKSpriteNode!
var basicRight: SKSpriteNode!
override func didMove(to view: SKView) {
layoutScene()
}

func turnBasicTop() {
  basicTop.isUserInteractionEnabled = true
  basicTop.run(SKAction.rotate(byAngle: .pi/2, duration: 0.25))
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    turnBasicTop()
}

func spawnBasicTop() {
let basicTop = SKSpriteNode(imageNamed: "basic top")
basicTop.size = CGSize(width: 400, height: 400)
basicTop.position = CGPoint(x: 230, y: 200)
basicTop.zPosition = 1

basicTop.physicsBody = SKPhysicsBody(rectangleOf: basicTop.size)
basicTop.physicsBody?.categoryBitMask = PhysicsCategories.basicTopCategory
basicTop.physicsBody?.isDynamic = false
basicTop.physicsBody?.allowsRotation = true

addChild(basicTop)
}
</code>```

答:
The basicTop defined in spawnBasicTop() refers to the local variable defined within the method as a local variable with the same name as another variable with a greater scope takes precedence in reference. Hence, when you attempt to run an animation on basicTop in the turnBasicTop() method, the action is run on a completely separate SKSpriteNode instance. I suppose you aren't seeing anything happen because either the node referenced by the scene's basicTop property is out of the view; has its isHidden property as true; or cannot be assigned to the image "Top Side" since it doesn't exist and therefore has zero size. Adding

```<code>self.basicTop = basicTop
</code>```

to the spawnBasicTop() method will do the trick, although I recommend you learn more about Swift and how variables are declared, captured, etc.

Body:
What I have Right now, my game loads up on the simulator on Xcode as it should, but when I tap the screen, "basic Top" doesn't rotate. Basic top is one of four triangles that makes up a square.

What I want In order to make that square rotate I have to get all four triangles to rotate. Right now, basic top doesn't rotate even when I click on the screen. Once I get basic top to rotate, I can replicate the code for the other triangles in order to make a square that rotates. I need these four triangles all to rotate around a certain point.

Code

class GameScene: SKScene {
var brickSwitch: SKSpriteNode!
var basicTop = SKSpriteNode(imageNamed: "Top Side");
var basicBottom: SKSpriteNode!
var basicLeft: SKSpriteNode!
var basicRight: SKSpriteNode!
override func didMove(to view: SKView) {
layoutScene()
}

func turnBasicTop() {
  basicTop.isUserInteractionEnabled = true
  basicTop.run(SKAction.rotate(byAngle: .pi/2, duration: 0.25))
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    turnBasicTop()
}

func spawnBasicTop() {
let basicTop = SKSpriteNode(imageNamed: "basic top")
basicTop.size = CGSize(width: 400, height: 400)
basicTop.position = CGPoint(x: 230, y: 200)
basicTop.zPosition = 1

basicTop.physicsBody = SKPhysicsBody(rectangleOf: basicTop.size)
basicTop.physicsBody?.categoryBitMask = PhysicsCategories.basicTopCategory
basicTop.physicsBody?.isDynamic = false
basicTop.physicsBody?.allowsRotation = true

addChild(basicTop)
}

Body:
The basicTop defined in spawnBasicTop() refers to the local variable defined within the method as a local variable with the same name as another variable with a greater scope takes precedence in reference. Hence, when you attempt to run an animation on basicTop in the turnBasicTop() method, the action is run on a completely separate SKSpriteNode instance. I suppose you aren't seeing anything happen because either the node referenced by the scene's basicTop property is out of the view; has its isHidden property as true; or cannot be assigned to the image "Top Side" since it doesn't exist and therefore has zero size. Adding

self.basicTop = basicTop

to the spawnBasicTop() method will do the trick, although I recommend you learn more about Swift and how variables are declared, captured, etc.


问:
how solve error jest-worker at run build?
i have a problem at run build production in webpack. but when i run using dev-server, more code can't get error. please help.. I have to finish my last project and it must run with good at production mode. I hope I get a solution from you guys.

here my error at run build:

```<code>    /MovieDB/node_modules/jest-worker/build/WorkerPool.js:25
      } catch {
              ^

    SyntaxError: Unexpected token {
        at NativeCompileCache._moduleCompile (/home/donquixote/Desktop/dicoding-submission/MovieDB/node_modules/v8-compile-cache/v8-compile-cache.js:240:18)
        at Module._compile (/home/donquixote/Desktop/dicoding-submission/MovieDB/node_modules/v8-compile-cache/v8-compile-cache.js:186:36)
        at Object.Module._extensions..js (module.js:663:10)
        at Module.load (module.js:565:32)
  ...
        at Object.Module._extensions..js (module.js:663:10)
        at Module.load (module.js:565:32)
        at tryModuleLoad (module.js:505:12)
        at Function.Module._load (module.js:497:3)
    error Command failed with exit code 1.
    info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code>```

here my webpack.common.js:

```<code>const path = require('path');
const webpack = require('webpack');
const HtmlPackPlugin = require('html-webpack-plugin');
const terserPlugin = require('terser-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },
  plugins: [
  new HtmlPackPlugin({
    template: './src/index.html',
    filename: 'index.html'})
  ],
  optimization: {
    minimize: true,
    minimizer: [
      new terserPlugin({
        test: /\.js(\?.*)?$/i,
      })
    ],
    sourceMap: true
  }
}
</code>```

here my webpack.dev.js

```<code>const merge = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
    mode: "development",
    devtool: 'inline-source-map'
})
</code>```

答:
what's the version of Node.js are you using?

I ran into the same error when I was running the latest terser-webpack-plugin @ 3.0.2. According to the release log, there were some breaking changes introduced in 3.0.0 and one of them was "minimum supported Node.js version is 10.13"

It worked when I downgraded terser-webpack-plugin to 2.3.6.

So you'll probably have to upgrade your Node.js if you're using a version earlier than 10.13, or downgrade your terser-webpack-plugin.

Body:
i have a problem at run build production in webpack. but when i run using dev-server, more code can't get error. please help.. I have to finish my last project and it must run with good at production mode. I hope I get a solution from you guys.

here my error at run build:

    /MovieDB/node_modules/jest-worker/build/WorkerPool.js:25
      } catch {
              ^

    SyntaxError: Unexpected token {
        at NativeCompileCache._moduleCompile (/home/donquixote/Desktop/dicoding-submission/MovieDB/node_modules/v8-compile-cache/v8-compile-cache.js:240:18)
        at Module._compile (/home/donquixote/Desktop/dicoding-submission/MovieDB/node_modules/v8-compile-cache/v8-compile-cache.js:186:36)
        at Object.Module._extensions..js (module.js:663:10)
        at Module.load (module.js:565:32)
  ...
        at Object.Module._extensions..js (module.js:663:10)
        at Module.load (module.js:565:32)
        at tryModuleLoad (module.js:505:12)
        at Function.Module._load (module.js:497:3)
    error Command failed with exit code 1.
    info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

here my webpack.common.js:

const path = require('path');
const webpack = require('webpack');
const HtmlPackPlugin = require('html-webpack-plugin');
const terserPlugin = require('terser-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },
  plugins: [
  new HtmlPackPlugin({
    template: './src/index.html',
    filename: 'index.html'})
  ],
  optimization: {
    minimize: true,
    minimizer: [
      new terserPlugin({
        test: /\.js(\?.*)?$/i,
      })
    ],
    sourceMap: true
  }
}

here my webpack.dev.js

const merge = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
    mode: "development",
    devtool: 'inline-source-map'
})