问:
Pytorch NN Training issue: Loss of NN does not decrase
I want to classify random Instagram images as "image has a dog" or "image has not a dog".
To train my NN to classify dogs I want to use the Stanford Dogs Dataset, so I have about 20.000 training images of different dogs with different breeds.

But while training my NN the loss does not decrease, I checked that with different learning rates and with or without dropout layers.

Can anyone give tips or does anyone see bugs in the following code?:

```<code>import torch
import torchvision
from torchvision import transforms
from PIL import Image
from os import listdir
import os
import random
import torch.optim as optim
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn

TRAINDATAPATH = 'C:/Users/.../Desktop/train/'
TESTDATAPATH = 'C:/Users/.../Desktop/#apfel/'

"""normalize = transforms.Normalize(
   mean=[0.485, 0.456, 0.406],
   std=[0.229, 0.224, 0.225]
)"""
normalize = transforms.Normalize(
   mean=[0.5, 0.5, 0.5],
   std=[0.5, 0.5, 0.5]
)
transforms = transforms.Compose([transforms.Resize(256),
                                 transforms.CenterCrop(256),
                                 transforms.ToTensor(),
                                 normalize])

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
train_data_list = []
target_list = []
train_data = []

batch_size = 1

files = listdir(TRAINDATAPATH)

for i in range(len(listdir(TRAINDATAPATH))):
    try:
        f = random.choice(files)
        files.remove(f)
        img = Image.open(TRAINDATAPATH + f)
        img_tensor = transforms(img) # (3,256,256)
        train_data_list.append(img_tensor)
        isObj = 1 if 'obj' in f else 0
        isNotObj = 0 if 'obj' in f else 1
        target = [isObj, isNotObj]

        target_list.append(target)
        if len(train_data_list) >= 1:
            train_data.append((torch.stack(train_data_list), target_list))
            train_data_list = []
            target_list = []
            print('Loaded batch ', int(len(train_data)/batch_size), 'of ', int(len(listdir(TRAINDATAPATH))/batch_size))
            print('Percentage Done: ', 100*int(len(train_data)/batch_size)/int(len(listdir(TRAINDATAPATH))/batch_size), '%')
    except Exception:
        print("Error occured but ignored")
        print(str(Exception))
        continue

class Netz(nn.Module):
    def __init__(self):
        super(Netz, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, kernel_size=5)
        self.conv2 = nn.Conv2d(6, 12, kernel_size=5)
        self.conv3 = nn.Conv2d(12, 18, kernel_size=5)
        self.conv4 = nn.Conv2d(18, 24, kernel_size=5)
        self.fc1 = nn.Linear(3456, 1000)
        self.fc2 = nn.Linear(1000, 2)

    def forward(self, x):
        x = self.conv1(x)
        x = F.max_pool2d(x,2)
        x = F.relu(x)
        x = self.conv2(x)
        x = F.max_pool2d(x,2)
        x = F.relu(x)
        x = self.conv3(x)
        x = F.max_pool2d(x,2)
        x = F.relu(x)
        x = self.conv4(x)
        x = F.max_pool2d(x,2)
        x = F.relu(x)
        x = x.view(-1,3456)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)

        return torch.sigmoid(x)

model = Netz()
model.to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))

optimizer = optim.Adadelta(model.parameters(), lr=10)
def train(epoch):
    global model

    model.train()
    batch_idx = 0
    for data, target in train_data:
        batch_idx += 1
        data = data.to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))
        target = torch.Tensor(target).to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))
        data = Variable(data)
        target = Variable(target)
        optimizer.zero_grad()

        output = model(data)

        criterion = F.binary_cross_entropy
        loss = criterion(output, target)
        loss.backward()

        optimizer.step()
        print('Train Epoch: '+ str(epoch) + '\tLoss: ' + str(loss.data.item()) )

def test():
    global model

    model.eval()
    files = listdir(TESTDATAPATH)
    f = random.choice(files)
    img = Image.open(TESTDATAPATH + f)
    img_eval_tensor = transforms(img)
    img_eval_tensor.unsqueeze_(0)
    data = Variable(img_eval_tensor.to(torch.device("cuda" if torch.cuda.is_available() else "cpu")) )
    out = model(data)
    string_prediction = str(out.data.max(0, keepdim=True)[1])
    print(string_prediction[9:10])

for epoch in range(1,4):
    train(epoch)
i = 100
while i > 0:
    test()
    i -= 1
</code>```

In the TRAINDATAPATH are thousands of Dog images with the filename "obj_XXX.jpg" and some other images WITHOUT dogs with other filenames don't including "obj".

In the TESTDATAPATH are just random images, some with dogs, some without.
The NN classifies them all as "not including dogs" or "0" which is incorrect.

Thanks for every help!

答:
You are doing a binary classification but you are using two classes:

isObj = 1 if 'obj' in f else 0
isNotObj = 0 if 'obj' in f else 1
target = [isObj, isNotObj]
```

<p>In the binary case, it should be a single class, where 1 means it is a dog, and 0 means it is not. You are already doing it, but twice. You can remove the <code>isNotObj</code> entirely and only keep the <code>isObj</code>.</p>

<p>You need to adapt the model accordingly, such that it only predicts the <code>isObj</code>, therefore <code>fc2</code> should only have 1 class as output:</p>

<pre class="lang-py prettyprint-override"><code>self.fc2 = nn.Linear(1000, 1)
</code>```

In the testing phase you need to make a prediction based on a single class, which can be seen as the probability of being a dog. Then you set a threshold for which you consider the model to be confident enough that it's actually a dog. To make it balanced, the threshold is 0.5, so everything above that is a dog and everything below it is not. This can easily be achieved with torch.round:

# Size: [batch_size, 1]
out = model(data)
predictions = torch.round(out)
# Get rid of the singular dimension
# To get size: [batch_size]
predictions = predictions.squeeze(1)
```

Besides that, the learning rate of 10 is astronomically high, and a learning rate greater than 1 makes it impossible to converge. A more appropriate learning rate is around 0.01 or 0.001.

And on side note, since you are new to PyTorch: Please don't use Variable, it was deprecated with PyTorch 0.4.0, which was released over 2 years ago, and all of its functionality has been merged into the tensors.

Body:
I want to classify random Instagram images as "image has a dog" or "image has not a dog".
To train my NN to classify dogs I want to use the Stanford Dogs Dataset, so I have about 20.000 training images of different dogs with different breeds.

But while training my NN the loss does not decrease, I checked that with different learning rates and with or without dropout layers.

Can anyone give tips or does anyone see bugs in the following code?:

import torch
import torchvision
from torchvision import transforms
from PIL import Image
from os import listdir
import os
import random
import torch.optim as optim
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn

TRAINDATAPATH = 'C:/Users/.../Desktop/train/'
TESTDATAPATH = 'C:/Users/.../Desktop/#apfel/'

"""normalize = transforms.Normalize(
   mean=[0.485, 0.456, 0.406],
   std=[0.229, 0.224, 0.225]
)"""
normalize = transforms.Normalize(
   mean=[0.5, 0.5, 0.5],
   std=[0.5, 0.5, 0.5]
)
transforms = transforms.Compose([transforms.Resize(256),
                                 transforms.CenterCrop(256),
                                 transforms.ToTensor(),
                                 normalize])

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
train_data_list = []
target_list = []
train_data = []

batch_size = 1

files = listdir(TRAINDATAPATH)

for i in range(len(listdir(TRAINDATAPATH))):
    try:
        f = random.choice(files)
        files.remove(f)
        img = Image.open(TRAINDATAPATH + f)
        img_tensor = transforms(img) # (3,256,256)
        train_data_list.append(img_tensor)
        isObj = 1 if 'obj' in f else 0
        isNotObj = 0 if 'obj' in f else 1
        target = [isObj, isNotObj]

        target_list.append(target)
        if len(train_data_list) >= 1:
            train_data.append((torch.stack(train_data_list), target_list))
            train_data_list = []
            target_list = []
            print('Loaded batch ', int(len(train_data)/batch_size), 'of ', int(len(listdir(TRAINDATAPATH))/batch_size))
            print('Percentage Done: ', 100*int(len(train_data)/batch_size)/int(len(listdir(TRAINDATAPATH))/batch_size), '%')
    except Exception:
        print("Error occured but ignored")
        print(str(Exception))
        continue

class Netz(nn.Module):
    def __init__(self):
        super(Netz, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, kernel_size=5)
        self.conv2 = nn.Conv2d(6, 12, kernel_size=5)
        self.conv3 = nn.Conv2d(12, 18, kernel_size=5)
        self.conv4 = nn.Conv2d(18, 24, kernel_size=5)
        self.fc1 = nn.Linear(3456, 1000)
        self.fc2 = nn.Linear(1000, 2)

    def forward(self, x):
        x = self.conv1(x)
        x = F.max_pool2d(x,2)
        x = F.relu(x)
        x = self.conv2(x)
        x = F.max_pool2d(x,2)
        x = F.relu(x)
        x = self.conv3(x)
        x = F.max_pool2d(x,2)
        x = F.relu(x)
        x = self.conv4(x)
        x = F.max_pool2d(x,2)
        x = F.relu(x)
        x = x.view(-1,3456)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)

        return torch.sigmoid(x)

model = Netz()
model.to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))

optimizer = optim.Adadelta(model.parameters(), lr=10)
def train(epoch):
    global model

    model.train()
    batch_idx = 0
    for data, target in train_data:
        batch_idx += 1
        data = data.to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))
        target = torch.Tensor(target).to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))
        data = Variable(data)
        target = Variable(target)
        optimizer.zero_grad()

        output = model(data)

        criterion = F.binary_cross_entropy
        loss = criterion(output, target)
        loss.backward()

        optimizer.step()
        print('Train Epoch: '+ str(epoch) + '\tLoss: ' + str(loss.data.item()) )

def test():
    global model

    model.eval()
    files = listdir(TESTDATAPATH)
    f = random.choice(files)
    img = Image.open(TESTDATAPATH + f)
    img_eval_tensor = transforms(img)
    img_eval_tensor.unsqueeze_(0)
    data = Variable(img_eval_tensor.to(torch.device("cuda" if torch.cuda.is_available() else "cpu")) )
    out = model(data)
    string_prediction = str(out.data.max(0, keepdim=True)[1])
    print(string_prediction[9:10])

for epoch in range(1,4):
    train(epoch)
i = 100
while i > 0:
    test()
    i -= 1

In the TRAINDATAPATH are thousands of Dog images with the filename "obj_XXX.jpg" and some other images WITHOUT dogs with other filenames don't including "obj".

In the TESTDATAPATH are just random images, some with dogs, some without.
The NN classifies them all as "not including dogs" or "0" which is incorrect.

Thanks for every help!

Body:
You are doing a binary classification but you are using two classes:

isObj = 1 if 'obj' in f else 0
isNotObj = 0 if 'obj' in f else 1
target = [isObj, isNotObj]

In the binary case, it should be a single class, where 1 means it is a dog, and 0 means it is not. You are already doing it, but twice. You can remove the isNotObj entirely and only keep the isObj.

You need to adapt the model accordingly, such that it only predicts the isObj, therefore fc2 should only have 1 class as output:

self.fc2 = nn.Linear(1000, 1)

In the testing phase you need to make a prediction based on a single class, which can be seen as the probability of being a dog. Then you set a threshold for which you consider the model to be confident enough that it's actually a dog. To make it balanced, the threshold is 0.5, so everything above that is a dog and everything below it is not. This can easily be achieved with torch.round:

# Size: [batch_size, 1]
out = model(data)
predictions = torch.round(out)
# Get rid of the singular dimension
# To get size: [batch_size]
predictions = predictions.squeeze(1)

Besides that, the learning rate of 10 is astronomically high, and a learning rate greater than 1 makes it impossible to converge. A more appropriate learning rate is around 0.01 or 0.001.

And on side note, since you are new to PyTorch: Please don't use Variable, it was deprecated with PyTorch 0.4.0, which was released over 2 years ago, and all of its functionality has been merged into the tensors.


来源: stackexchange

问:
Waiting for another flutter command to release the startup lock
When I run my flutter application it show

Waiting for another flutter command to release the startup lock

this messages and not proceed further.

答:
Nothing of ALL these answers didn't helped me.

The only one solution was to remove whole flutter stuff (and reinstall flutter from git):

```<code><flutter directory>
<user>/.flutter_tool_state
<user>/.dart
<user>/.pub-cache
<user>/.dartServer
<user>/.flutter
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Nothing of ALL these answers didn't helped me.

The only one solution was to remove whole flutter stuff (and reinstall flutter from git):

<flutter directory>
<user>/.flutter_tool_state
<user>/.dart
<user>/.pub-cache
<user>/.dartServer
<user>/.flutter


问:
How to add event handler for deleting a single item from the list?
I have the following code, and I want to add an even handler for detecting when delete button is clicked and then remove the specific item from list.

Favorites.js

```<code> constructor(props) {
        super(props);
        this.state = {
            movies: []
        };

        this.clearSaved = this.clearSaved.bind(this);
        this.handleDelete = this.handleDelete.bind(this);
    }
</code>```

MovieList.js

```<code>export default ({ movies }) => {
    return(
        <div id="saved-movies-list">
        <ul className="saved-movies-list">
        { movies.map(movie => <li key={ movie.imdbID }><Movie movie={ movie } /></li>) }
        </ul>
        </div>
    )
};
</code>```

Movie.js

```<code>const Movie = ({movie}) => {
     return (<div className="movie-card" id={movie.imdbID}>
          {
               // eslint-disable-next-line
               movie.poster == 'N/A' ?
               <div className="movie-card-poster missing">
               <img className="d-block h-100" src={movie_poster} alt="" />
               </div>
               :
               <div className="movie-card-poster">
               <img className="d-block h-100" src={movie.poster} alt="" />
               </div>
          }
          <div className="body">
               <div style={{ maxWidth: '80%' }}>
                    <h5 class="card-title">{movie.title}</h5>
               </div>
               <p className="text-secondary">{ movie.year }</p>
               {!movie.runtime ? "" : <p className="text-secondary">{ movie.runtime }</p>}
               <p className="plot">{movie.description}</p>
               <a href="#" className="delete-movie" title="Remove this movie"><FontAwesomeIcon icon="minus-circle" size="1x" /></a>
          </div>
     </div>)
}
</code>```

I need to attach event to this line:

```<code>       <a href="#" className="delete-movie" title="Remove this movie"><FontAwesomeIcon icon="minus-circle" size="1x" /></a>
</code>```

But, I do NOT know how to? Writing this.props. ... does not work!

答:
For the event handler, you can use simple onClick event like this:

```<code>{ movies.map(movie => <li onClick={()=>handleClick(movie.imdbID)} key={ movie.imdbID }><Movie movie={ movie } /></li>) }
</code>```

Then you should write your handleClick function, which you want to delete the movie.
Now, there's a lot of ways you can take that deletion. But lets asume you just don't want it to render. Then you should manage an array/collections of imdbID's you don't want to render and using it in your render event.

Using React Hooks:

```<code>export default ({ movies }) => {

    const [removeList, setRemoveList] = useState([]);
    const handleClick = (id) => setRemoveList([...removeList, id]);

    return(
        <div id="saved-movies-list">
            <ul className="saved-movies-list">
                { movies.map(movie => (!removeList.includes(movie.imdbID)) && <li onClick={()=>handleClick(movie.imdbID)} key={ movie.imdbID }><Movie movie={ movie } /></li>) }
            </ul>
        </div>
    )
};
</code>```

Body:
I have the following code, and I want to add an even handler for detecting when delete button is clicked and then remove the specific item from list.

Favorites.js

 constructor(props) {
        super(props);
        this.state = {
            movies: []
        };

        this.clearSaved = this.clearSaved.bind(this);
        this.handleDelete = this.handleDelete.bind(this);
    }

MovieList.js

export default ({ movies }) => {
    return(

        { movies.map(movie =>
<Movie movie={ movie } />
) }

    )
};

Movie.js

const Movie = ({movie}) => {
     return (

          {
               // eslint-disable-next-line
               movie.poster == 'N/A' ?

               :

          }

{movie.title}

{ movie.year }

               {!movie.runtime ? "" :
{ movie.runtime }
}

{movie.description}

               <FontAwesomeIcon icon="minus-circle" size="1x" />

)
}

I need to attach event to this line:

       <FontAwesomeIcon icon="minus-circle" size="1x" />

But, I do NOT know how to? Writing this.props. ... does not work!

Body:
For the event handler, you can use simple onClick event like this:

{ movies.map(movie => <li onClick={()=>handleClick(movie.imdbID)} key={ movie.imdbID }><Movie movie={ movie } /></li>) }

Then you should write your handleClick function, which you want to delete the movie.
Now, there's a lot of ways you can take that deletion. But lets asume you just don't want it to render. Then you should manage an array/collections of imdbID's you don't want to render and using it in your render event.

Using React Hooks:

export default ({ movies }) => {

    const [removeList, setRemoveList] = useState([]);
    const handleClick = (id) => setRemoveList([...removeList, id]);

    return(
        <div id="saved-movies-list">
            <ul className="saved-movies-list">
                { movies.map(movie => (!removeList.includes(movie.imdbID)) && <li onClick={()=>handleClick(movie.imdbID)} key={ movie.imdbID }><Movie movie={ movie } /></li>) }
            </ul>
        </div>
    )
};


问:
Getting "Response status code does not indicate success: 502 (Bad Gateway)" from Asp.net Core MVC Web App hosted in Azure
I have a client application built on Asp.net core MVC (V 1.1.1) and a Web API built on Asp.net core (v 2.1). I had hosted both on Azure.

While making some requests, the web app is failing and giving 502 Bad Gateway response.

Response status code does not indicate success: 502 (Bad Gateway).

The specified CGI application encountered an error and the server terminated the process.

This issue is intermittent, however, seems happening when request is taking more than 2 min to process. I have set up requestTimeout to 20 min on both client and API side in Web.config file still didn't get it resolved. Sometimes, the same request is being processed in less time and I am getting response.

Additionally, the 5 min timeout for Httpclient has also been set but no luck.

<aspNetCore requestTimeout="00:20:00"/>

_httpClient.Timeout = new TimeSpan(0, 5, 0);

I have tested the app locally and can't face this issue, also able to get response even it take more than 3 min to process.

It seems that Azure web app is not waiting for request to get processed if it's crossing 2 min. However, the azure session timeout specifies 230 seconds (3.8 min) but still it's not waiting and the app is not considering this case as an error and not logging anything.

Client Side code:

```<code>public class ApiClientFactory
{
    private static Uri ApiUrl;
    private static Lazy<ApiClient> restClient = new Lazy<ApiClient>(
        () => new ApiClient(ApiUrl),
        LazyThreadSafetyMode.ExecutionAndPublication);

    static ApiClientFactory()
    {
        ApiUrl = new Uri(Convert.ToString(ConfigurationManager.AppSettings["WebAPIUrl"]));
    }

    public static ApiClient Instance
    {
        get
        {
            return restClient.Value;
        }
    }
}
</code>```
```<code>public class ApiClient
{
   private readonly HttpClient _httpClient;
   private readonly Uri BaseEndPointUrl;

   public ApiClient(Uri baseEndPointUrl)
   {
       if (baseEndPointUrl == null)
           throw new ArgumentNullException("baseEndPointUrl");

       BaseEndPointUrl = baseEndPointUrl;
       _httpClient = new HttpClient();
       _httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
       _httpClient.Timeout = new TimeSpan(0, 5, 0); //Timeout needed for few modules to get results from db.
   }

   private HttpContent CreateHttpContent<T>(T content)
   {
       var json = JsonConvert.SerializeObject(content, MicrosoftDateFormatSettings);
       return new StringContent(json, Encoding.UTF8, "application/json");
   }

   private static JsonSerializerSettings MicrosoftDateFormatSettings
   {
       get
       {
           return new JsonSerializerSettings
           {
               DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
           };
       }
   }

   public async Task<T1> PostAsync<T1, T2>(string url, T2 content, string token)
   {
       try
       {
           _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
           var response = await _httpClient.PostAsync(url, CreateHttpContent<T2>(content));

           if (response.StatusCode == HttpStatusCode.InternalServerError){
               var exception = await response.Content.ReadAsStringAsync();
               throw new Exception(exception);
           }
           response.EnsureSuccessStatusCode();
           var data = await response.Content.ReadAsStringAsync();

           return JsonConvert.DeserializeObject<T1>(data);
       }
       catch (Exception ex){throw ex;}
   }
}
</code>```

Please assist where it's having an issue.

答:
You can implement a method that retry your requests, or simply use .Net Polly for this kind of errors. Is not a good practice to increase your timeout setup.

Method:

```<code>    private async Task<bool> PostAsync()//Params you need
    {
        HttpStatusCode[] httpStatusCodesWorthRetrying =
        {
            HttpStatusCode.RequestTimeout,
            HttpStatusCode.InternalServerError,
            HttpStatusCode.BadGateway,
            HttpStatusCode.ServiceUnavailable,
            HttpStatusCode.GatewayTimeout
        };

        var maxAttempts = 0;

        while (maxAttempts < 3)
        {
            var response =  await _httpClient.PostAsync(requestUrl, CreateHttpContent<T2>(content));
            if (!httpStatusCodesWorthRetrying.Contains(response.StatusCode))
            {
                return true;
            }

            maxAttempts ++;
            await Task.Delay(300);
        }
        return false;
    }
</code>```

Polly:

```<code>    private async Task PostAsync()//Params you need
    {
        HttpStatusCode[] httpStatusCodesWorthRetrying =
        {
            HttpStatusCode.RequestTimeout,
            HttpStatusCode.InternalServerError,
            HttpStatusCode.BadGateway,
            HttpStatusCode.ServiceUnavailable,
            HttpStatusCode.GatewayTimeout
        };

        _retryPolicy = Policy
            .Handle<HttpRequestException>()
            .OrResult<HttpResponseMessage>(r => httpStatusCodesWorthRetrying.Contains(r.StatusCode))
            .WaitAndRetry(4, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));

        _retryPolicy.Execute(await _httpClient.PostAsync(requestUrl, CreateHttpContent<T2>(content)));

    }
</code>```

Body:
I have a client application built on Asp.net core MVC (V 1.1.1) and a Web API built on Asp.net core (v 2.1). I had hosted both on Azure.

While making some requests, the web app is failing and giving 502 Bad Gateway response.

Response status code does not indicate success: 502 (Bad Gateway).

The specified CGI application encountered an error and the server terminated the process.

This issue is intermittent, however, seems happening when request is taking more than 2 min to process. I have set up requestTimeout to 20 min on both client and API side in Web.config file still didn't get it resolved. Sometimes, the same request is being processed in less time and I am getting response.

Additionally, the 5 min timeout for Httpclient has also been set but no luck.

<aspNetCore requestTimeout="00:20:00"/>

_httpClient.Timeout = new TimeSpan(0, 5, 0);

I have tested the app locally and can't face this issue, also able to get response even it take more than 3 min to process.

It seems that Azure web app is not waiting for request to get processed if it's crossing 2 min. However, the azure session timeout specifies 230 seconds (3.8 min) but still it's not waiting and the app is not considering this case as an error and not logging anything.

Client Side code:

public class ApiClientFactory
{
    private static Uri ApiUrl;
    private static Lazy<ApiClient> restClient = new Lazy<ApiClient>(
        () => new ApiClient(ApiUrl),
        LazyThreadSafetyMode.ExecutionAndPublication);

    static ApiClientFactory()
    {
        ApiUrl = new Uri(Convert.ToString(ConfigurationManager.AppSettings["WebAPIUrl"]));
    }

    public static ApiClient Instance
    {
        get
        {
            return restClient.Value;
        }
    }
}

public class ApiClient
{
   private readonly HttpClient _httpClient;
   private readonly Uri BaseEndPointUrl;

   public ApiClient(Uri baseEndPointUrl)
   {
       if (baseEndPointUrl == null)
           throw new ArgumentNullException("baseEndPointUrl");

       BaseEndPointUrl = baseEndPointUrl;
       _httpClient = new HttpClient();
       _httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
       _httpClient.Timeout = new TimeSpan(0, 5, 0); //Timeout needed for few modules to get results from db.
   }

   private HttpContent CreateHttpContent<T>(T content)
   {
       var json = JsonConvert.SerializeObject(content, MicrosoftDateFormatSettings);
       return new StringContent(json, Encoding.UTF8, "application/json");
   }

   private static JsonSerializerSettings MicrosoftDateFormatSettings
   {
       get
       {
           return new JsonSerializerSettings
           {
               DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
           };
       }
   }

   public async Task<T1> PostAsync<T1, T2>(string url, T2 content, string token)
   {
       try
       {
           _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
           var response = await _httpClient.PostAsync(url, CreateHttpContent<T2>(content));

           if (response.StatusCode == HttpStatusCode.InternalServerError){
               var exception = await response.Content.ReadAsStringAsync();
               throw new Exception(exception);
           }
           response.EnsureSuccessStatusCode();
           var data = await response.Content.ReadAsStringAsync();

           return JsonConvert.DeserializeObject<T1>(data);
       }
       catch (Exception ex){throw ex;}
   }
}

Please assist where it's having an issue.

Body:
You can implement a method that retry your requests, or simply use .Net Polly for this kind of errors. Is not a good practice to increase your timeout setup.

Method:

    private async Task<bool> PostAsync()//Params you need
    {
        HttpStatusCode[] httpStatusCodesWorthRetrying =
        {
            HttpStatusCode.RequestTimeout,
            HttpStatusCode.InternalServerError,
            HttpStatusCode.BadGateway,
            HttpStatusCode.ServiceUnavailable,
            HttpStatusCode.GatewayTimeout
        };

        var maxAttempts = 0;

        while (maxAttempts < 3)
        {
            var response =  await _httpClient.PostAsync(requestUrl, CreateHttpContent<T2>(content));
            if (!httpStatusCodesWorthRetrying.Contains(response.StatusCode))
            {
                return true;
            }

            maxAttempts ++;
            await Task.Delay(300);
        }
        return false;
    }

Polly:

    private async Task PostAsync()//Params you need
    {
        HttpStatusCode[] httpStatusCodesWorthRetrying =
        {
            HttpStatusCode.RequestTimeout,
            HttpStatusCode.InternalServerError,
            HttpStatusCode.BadGateway,
            HttpStatusCode.ServiceUnavailable,
            HttpStatusCode.GatewayTimeout
        };

        _retryPolicy = Policy
            .Handle<HttpRequestException>()
            .OrResult<HttpResponseMessage>(r => httpStatusCodesWorthRetrying.Contains(r.StatusCode))
            .WaitAndRetry(4, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));

        _retryPolicy.Execute(await _httpClient.PostAsync(requestUrl, CreateHttpContent<T2>(content)));

    }


问:
TradingView. How to count how many time an indicator matches a certain criteria?
I have created an indicator. It's more like a statistic, it calculates the maximum difference in the last ex.100 candlesticks.

I added a line at 10. I need to know: in how many cases the value is bellow and above the line.

How can this be achieved without a loop that runs the script multiple times?

答:
without a loop, you'll have to count as you go.
one way could be to count the times your line crossesunder 10.</p>


问:
Join two arrays of different size with condition
i have two arrays of different sizes and i want them to joint in one only if first three elements match.

for exapmle:

```<code>A1 = [
    [1,8,9,8,2],
    [2,9,9,8,2],
    [1,7,7,8,2],
    [8,6,2,6,7]
]

A2 = [[2,9,9,30,60],
      [8,6,2,70,20]]

Result = [[2,9,9,8,2,30,60]
         [8,6,2,6,7,70,20]]
</code>```

I guess there is some numpy function for this but i couldn't find it.

答:
You can simply do a broadcasted comparison, no loops are needed.

```<code>match = (A1[:,None,:])[:,:,:3] == A2[:,:3]
R1, R2 = np.where(match.sum(axis=2)==3)
result = np.hstack((A1[R1],A2[R2,-2:]))
</code>```

A1[:,None,:] returns a view of shape (4,1,5) as opposed to (4,5); this allows you to do a broadcasted operation between A1 and A2, giving you the bool array match of shape (4,2,3). Taking the sum across the third axis basically tells you which row in A1 is matching with which row of A2, from which it's simple to create te result.

Body:
i have two arrays of different sizes and i want them to joint in one only if first three elements match.

for exapmle:

A1 = [
    [1,8,9,8,2],
    [2,9,9,8,2],
    [1,7,7,8,2],
    [8,6,2,6,7]
]

A2 = [[2,9,9,30,60],
      [8,6,2,70,20]]

Result = [[2,9,9,8,2,30,60]
         [8,6,2,6,7,70,20]]

I guess there is some numpy function for this but i couldn't find it.

Body:
You can simply do a broadcasted comparison, no loops are needed.

match = (A1[:,None,:])[:,:,:3] == A2[:,:3]
R1, R2 = np.where(match.sum(axis=2)==3)
result = np.hstack((A1[R1],A2[R2,-2:]))

A1[:,None,:] returns a view of shape (4,1,5) as opposed to (4,5); this allows you to do a broadcasted operation between A1 and A2, giving you the bool array match of shape (4,2,3). Taking the sum across the third axis basically tells you which row in A1 is matching with which row of A2, from which it's simple to create te result.


问:
How to extract a number from a string using Puppeteer?
How would I extract the number 2,550 from the string "2,550 Things" using Puppeteer?</p>

```<code><div id="container" role="main">
  <h3 class="highlightedText" role="heading">2,550 Things</h3>
</div>
</code>```

答:
Like this :

await page.waitForSelector('div#container > h3.highlightedText');
const text = await page.$eval(
    'div#container > h3.highlightedText',
    el => el.innerText.replace(/\s+.*/, "")
);
console.log(text);
```

Body:
How would I extract the number 2,550 from the string "2,550 Things" using Puppeteer?

2,550 Things


问:
Add rows in a gridview c#
Im new in asp.net. I want to know how to add a row in a gridview programatically. I was able to do it but it just displays the latest addition.
Here is my code: </p>

```<code>DataTable dt = new DataTable();
dt.Columns.Add("Question");
dt.Columns.Add("Answer");

DataRow dr = dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
dt.Rows.Add(dr);
dt.AcceptChanges();

gvQnA.DataSource = dt;
gvQnA.DataBind();
</code>```

答:
You have added one row in your code thats why it is showing one row.
If you have added multiple rows it would have shown proper result

```<code>DataTable dt = new DataTable();
dt.Columns.Add("Question");
dt.Columns.Add("Answer");

DataRow dr = dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
dt.Rows.Add(dr);

**DataRow dr = dt.NewRow();
dr["Question"] = "2nd row";
dr["Answer"] = "2nd row";
dt.Rows.Add(dr);**

dt.AcceptChanges();

gvQnA.DataSource = dt;
gvQnA.DataBind();
</code>```

May be @Pranay is also right

ContentLicense: CC BY-SA 3.0

Title: Add rows in a gridview c#

Body:
Im new in asp.net. I want to know how to add a row in a gridview programatically. I was able to do it but it just displays the latest addition.
Here is my code:

DataTable dt = new DataTable();
dt.Columns.Add("Question");
dt.Columns.Add("Answer");

DataRow dr = dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
dt.Rows.Add(dr);
dt.AcceptChanges();

gvQnA.DataSource = dt;
gvQnA.DataBind();

Body:
You have added one row in your code thats why it is showing one row.
If you have added multiple rows it would have shown proper result

DataTable dt = new DataTable();
dt.Columns.Add("Question");
dt.Columns.Add("Answer");

DataRow dr = dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
dt.Rows.Add(dr);

**DataRow dr = dt.NewRow();
dr["Question"] = "2nd row";
dr["Answer"] = "2nd row";
dt.Rows.Add(dr);**

dt.AcceptChanges();

gvQnA.DataSource = dt;
gvQnA.DataBind();

May be @Pranay is also right


问:
Serilog sink for Oracle
I've been looking for a serilog sink for connecting to Oracle but no find anyone. Is there some way to connect with an Oracle database?

If not, is possible to connect at least with MySql??

Thanks,

答:
Following is the snippet from my dotnet core api POC where i used Serilog to log into Oracle database.

First download the required packages -

```<code>dotnet add package Serilog.AspNetCore

dotnet add pacakage Serilog.Settings.Configuration

dotnet add package Serilog.Sinks.Oracle
</code>```

Use the code in Program.cs class

```<code>using Serilog;
</code>```

Code in Main method -

```<code>   var connectionString =
        @"user id=system;password=oracle;data source=
        (DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL = TCP)(HOST = localhost)
        (PORT = 49161)))(CONNECT_DATA=(SERVICE_NAME = xe)))";

        Log.Logger = new LoggerConfiguration()
                    .MinimumLevel.Information()
                    .WriteTo.Oracle(cfg =>
                    cfg.WithSettings(connectionString)
                    .UseBurstBatch()
                    .CreateSink())
                    .CreateLogger();
         Log.Information("Writing Logs in Oracle Database...")
</code>```

Title: Serilog sink for Oracle

Body:
Following is the snippet from my dotnet core api POC where i used Serilog to log into Oracle database.

First download the required packages -

dotnet add package Serilog.AspNetCore

dotnet add pacakage Serilog.Settings.Configuration

dotnet add package Serilog.Sinks.Oracle

Use the code in Program.cs class

using Serilog;

Code in Main method -

   var connectionString =
        @"user id=system;password=oracle;data source=
        (DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL = TCP)(HOST = localhost)
        (PORT = 49161)))(CONNECT_DATA=(SERVICE_NAME = xe)))";

        Log.Logger = new LoggerConfiguration()
                    .MinimumLevel.Information()
                    .WriteTo.Oracle(cfg =>
                    cfg.WithSettings(connectionString)
                    .UseBurstBatch()
                    .CreateSink())
                    .CreateLogger();
         Log.Information("Writing Logs in Oracle Database...")


问:
Spring cloud stream + spring retry, How to add recovery callback and disable logic that send to DLQ?
I'm using spring cloud stream + rabbit mq binder.

In my @StreaListener I want to apply retry logic on specific exceptions using RetryTemplate. After retries are exhausted or not retriable error is thrown, I would like to add a recovery callback that will save a new record with an error message to my Postgres DB and finish with the message (move to the next).
Here what I got so far:

  @StreamListener(Sink.INPUT)
  public void saveUser(User user) {
    User user = userService.saveUser(user); //could throw exceptions
    log.info(">>>>>>User is created successfully: {}", user);
  }

  @StreamRetryTemplate
  public RetryTemplate myRetryTemplate() {
    RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setBackOffPolicy(new ExponentialBackOffPolicy());

    Map<Class<? extends Throwable>, Boolean> retryableExceptions = new HashMap<>();
    retryableExceptions.put(ConnectionException.class, true);
    retryTemplate.registerListener(new RetryListener() {
      @Override
      public <T, E extends Throwable> boolean open(RetryContext context,
        RetryCallback<T, E> callback) {
        return true;
      }

      @Override
      public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback,
        Throwable throwable) {
        //could add recovery logic here, like save error to db why sertain user was not saved
        log.info("retries exausted");
      }

      @Override
      public <T, E extends Throwable> void onError(RetryContext context,
        RetryCallback<T, E> callback, Throwable throwable) {
        log.error("Error on retry", throwable);
      }
    });

    retryTemplate.setRetryPolicy(
      new SimpleRetryPolicy(properties.getRetriesCount(), retryableExceptions, true));
    return retryTemplate;
  }
```

<p>from properties, I only have these  (no any dlq configuration)</p>

```spring.cloud.stream.bindings.input.destination = user-topic
spring.cloud.stream.bindings.input.group = user-consumer
```

<p>And after retries are exhausted I get this log.</p>

```2020-06-01 20:05:58.674  INFO 18524 --- [idge-consumer-1] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [localhost:56722]
2020-06-01 20:05:58.685  INFO 18524 --- [idge-consumer-1] o.s.a.r.c.CachingConnectionFactory       : Created new connection: rabbitConnectionFactory.publisher#319c51b0:0/SimpleConnection@2a060201 [delegate=amqp://guest@127.0.0.1:56722/, localPort= 50728]
2020-06-01 20:05:58.697  INFO 18524 --- [idge-consumer-1] c.e.i.o.b.c.RetryConfiguration           : retry finish
2020-06-01 20:05:58.702 ERROR 18524 --- [127.0.0.1:56722] o.s.a.r.c.CachingConnectionFactory       : Channel shutdown: channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no exchange 'DLX' in vhost '/', class-id=60, method-id=40)
```

After RetryListener close method triggered, I can see that listener tries to connect to DLX probably to publish an error message. And I don't want it to do that as well as observe this error message in the log each time.

So my questions are:

1) Where to add RecoveryCalback for my retryTemplate? Supposedly I could write my recover logic with saving error to db in RetryListener#close method, but there definetely should be more appropriate way to do that.

2) How to configure rabbit-mq binder not to send messages to DLQ, maybe I could override some method? Currently, after retries are exhausted (or not retriable error is coming) listener tries to send a message to DLX and logs error that couldn't find it. I don't need any messages to be sent to dlq in scope of my application, I only need to save it to DB.

答:
There is currently no mechanism to provision a custom recovery callback.

Set republishToDlq to false (it used to be). It was changed to true, which is wrong if autoBindDlq is false (default); I will open an issue for that.

Then, when retries are exhausted, the exception will be thrown back to the container; you can use a ListenerContainerCustomizer to add a custom ErrorHandler.

However, the data you get there will be a ListenerExecutionFailed exception with the raw (unconverted) Spring AMQP Message in its failedMessage property, not your User object.

EDIT

You can add a listener to the binding's error channel...

@SpringBootApplication
@EnableBinding(Sink.class)
public class So62137618Application {

    public static void main(String[] args) {
        SpringApplication.run(So62137618Application.class, args);
    }

    @StreamListener(Sink.INPUT)
    public void listen(String in) {
        System.out.println(in);
        throw new RuntimeException("test");
    }

    @ServiceActivator(inputChannel = "user-topic.user-consumer.errors")
    public void errors(String in) {
        System.out.println("Retries exhausted for " + new String((byte[]) in.getFailedMessage().getPayload()));
    }

}
```

Body:
I'm using spring cloud stream + rabbit mq binder.

In my @StreaListener I want to apply retry logic on specific exceptions using RetryTemplate. After retries are exhausted or not retriable error is thrown, I would like to add a recovery callback that will save a new record with an error message to my Postgres DB and finish with the message (move to the next).
Here what I got so far:

  @StreamListener(Sink.INPUT)
  public void saveUser(User user) {
    User user = userService.saveUser(user); //could throw exceptions
    log.info(">>>>>>User is created successfully: {}", user);
  }

  @StreamRetryTemplate
  public RetryTemplate myRetryTemplate() {
    RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setBackOffPolicy(new ExponentialBackOffPolicy());

    Map<Class<? extends Throwable>, Boolean> retryableExceptions = new HashMap<>();
    retryableExceptions.put(ConnectionException.class, true);
    retryTemplate.registerListener(new RetryListener() {
      @Override
      public <T, E extends Throwable> boolean open(RetryContext context,
        RetryCallback<T, E> callback) {
        return true;
      }

      @Override
      public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback,
        Throwable throwable) {
        //could add recovery logic here, like save error to db why sertain user was not saved
        log.info("retries exausted");
      }

      @Override
      public <T, E extends Throwable> void onError(RetryContext context,
        RetryCallback<T, E> callback, Throwable throwable) {
        log.error("Error on retry", throwable);
      }
    });

    retryTemplate.setRetryPolicy(
      new SimpleRetryPolicy(properties.getRetriesCount(), retryableExceptions, true));
    return retryTemplate;
  }

from properties, I only have these  (no any dlq configuration)

spring.cloud.stream.bindings.input.destination = user-topic
spring.cloud.stream.bindings.input.group = user-consumer

And after retries are exhausted I get this log.

2020-06-01 20:05:58.674  INFO 18524 --- [idge-consumer-1] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: [localhost:56722]
2020-06-01 20:05:58.685  INFO 18524 --- [idge-consumer-1] o.s.a.r.c.CachingConnectionFactory       : Created new connection: rabbitConnectionFactory.publisher#319c51b0:0/SimpleConnection@2a060201 [delegate=amqp://guest@127.0.0.1:56722/, localPort= 50728]
2020-06-01 20:05:58.697  INFO 18524 --- [idge-consumer-1] c.e.i.o.b.c.RetryConfiguration           : retry finish
2020-06-01 20:05:58.702 ERROR 18524 --- [127.0.0.1:56722] o.s.a.r.c.CachingConnectionFactory       : Channel shutdown: channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no exchange 'DLX' in vhost '/', class-id=60, method-id=40)

After RetryListener close method triggered, I can see that listener tries to connect to DLX probably to publish an error message. And I don't want it to do that as well as observe this error message in the log each time.

So my questions are:

1) Where to add RecoveryCalback for my retryTemplate? Supposedly I could write my recover logic with saving error to db in RetryListener#close method, but there definetely should be more appropriate way to do that.

2) How to configure rabbit-mq binder not to send messages to DLQ, maybe I could override some method? Currently, after retries are exhausted (or not retriable error is coming) listener tries to send a message to DLX and logs error that couldn't find it. I don't need any messages to be sent to dlq in scope of my application, I only need to save it to DB.


问:
how to write out multiple files in R?
I am a newbie R user. Now, I have a question related to write out multiple files with different names. Lets says that my data has the following structure:

```<code>IV_HAR_m1<-matrix(rnorm(1:100), ncol=30, nrow = 2000)
DV_HAR_m1<-matrix(rnorm(1:100), ncol=10, nrow = 2000)
</code>```

I am trying to estimate multiple LASSO regressions. At the beginning, I was storing the iterations in one object called Dinamic_beta. This object was stored in only one file, and it saves the required information each time that my code iterate.

For doing this I was using stew which belongs to pomp package, but the total process takes 5 or 6 days and I am worried about a power outage or a fail in my computer.

Now, I want to save each environment (iterations) in a .Rnd file. I do not know how can I do that? but the code that I am using is the following:

```<code>library(glmnet)
library(Matrix)
library(pomp)

  space <-  7 #THE NUMBER OF FILES THAT I would WANT TO CREATE

  Dinamic_betas<-array(NA, c(10, 31, (nrow(IV_HAR_m1)-space)))
  dimnames(Dinamic_betas) <- list(NULL, NULL)

  set.seed(12345)
  stew( #stew save the enviroment in a .Rnd file
file = "Dinamic_LASSO_RD",{ # The name required by stew for creating one file with all information
  for (i in 1:dim(Dinamic_betas)[3]) {
    tryCatch( #print messsages
      expr = {
        cv_dinamic <- cv.glmnet(IV_HAR_m1[i:(space+i-1),],
                                DV_HAR_m1[i:(space+i-1),], alpha = 1, family = "mgaussian", thresh=1e-08, maxit=10^9)
        LASSO_estimation_dinamic<- glmnet(IV_HAR_m1[i:(space+i-1),], DV_HAR_m1[i:(space+i-1),],
                                          alpha = 1, lambda = cv_dinamic$lambda.min, family = "mgaussian")
        coefs <- as.matrix(do.call(cbind, coef(LASSO_estimation_dinamic)))
        Dinamic_betas[,,i] <- t(coefs)
      },
      error = function(e){
        message("Caught an error!")
        print(e)
      },
      warning = function(w){
        message("Caught an warning!")
        print(w)
      },
      finally = {
        message("All done, quitting.")
      }
    )
    if (i%%400==0) {print(i)}
  }
}
  )
</code>```

If someone can suggest another package that stores the outputs in different files I will grateful.

答:
Try adding this just before the close of your loop

save.image(paste0("Results_iteration_",i,".RData"))

This should save your entire workspace to disk for every iteration. You can then use load() to load the workspace of every environment. Let me know if this works.

Title: how to write out multiple files in R?

Body:
I am a newbie R user. Now, I have a question related to write out multiple files with different names. Lets says that my data has the following structure:

IV_HAR_m1<-matrix(rnorm(1:100), ncol=30, nrow = 2000)
DV_HAR_m1<-matrix(rnorm(1:100), ncol=10, nrow = 2000)

I am trying to estimate multiple LASSO regressions. At the beginning, I was storing the iterations in one object called Dinamic_beta. This object was stored in only one file, and it saves the required information each time that my code iterate.

For doing this I was using stew which belongs to pomp package, but the total process takes 5 or 6 days and I am worried about a power outage or a fail in my computer.

Now, I want to save each environment (iterations) in a .Rnd file. I do not know how can I do that? but the code that I am using is the following:

library(glmnet)
library(Matrix)
library(pomp)

  space <-  7 #THE NUMBER OF FILES THAT I would WANT TO CREATE

  Dinamic_betas<-array(NA, c(10, 31, (nrow(IV_HAR_m1)-space)))
  dimnames(Dinamic_betas) <- list(NULL, NULL)

  set.seed(12345)
  stew( #stew save the enviroment in a .Rnd file
file = "Dinamic_LASSO_RD",{ # The name required by stew for creating one file with all information
  for (i in 1:dim(Dinamic_betas)[3]) {
    tryCatch( #print messsages
      expr = {
        cv_dinamic <- cv.glmnet(IV_HAR_m1[i:(space+i-1),],
                                DV_HAR_m1[i:(space+i-1),], alpha = 1, family = "mgaussian", thresh=1e-08, maxit=10^9)
        LASSO_estimation_dinamic<- glmnet(IV_HAR_m1[i:(space+i-1),], DV_HAR_m1[i:(space+i-1),],
                                          alpha = 1, lambda = cv_dinamic$lambda.min, family = "mgaussian")
        coefs <- as.matrix(do.call(cbind, coef(LASSO_estimation_dinamic)))
        Dinamic_betas[,,i] <- t(coefs)
      },
      error = function(e){
        message("Caught an error!")
        print(e)
      },
      warning = function(w){
        message("Caught an warning!")
        print(w)
      },
      finally = {
        message("All done, quitting.")
      }
    )
    if (i%%400==0) {print(i)}
  }
}
  )

If someone can suggest another package that stores the outputs in different files I will grateful.


问:
.xlam add-in does not work on other computers giving two workbooks with the same name error
I created 2 simple macros just to delete some columns and sort the data on Excel. It does not open a file, just works on the active workbook. I saved the macros as .xlam add-in to distribute other team mates.

I also created a custom Ribbon menu. In the ribbon menu I created 2 buttons and assigned my macros one by one. Now, on my computer, when I click on the button in the Ribbon menu, it calls the macro and the macro works perfectly.

When I add the same add-in to my friends' computers it imports the add-in succesfully. It creates a local copy under Add-In file as well.

When it comes to run the macros, however, it gives the following error ""Sorry, excel can't open two of the same workbooks at the same time".

No need to say there is not 2 workbooks with the same name, there is even no other workbooks opened. What could be the problem? Since it is not code related (at least it seems like) I don't share any code here. If you want I can, however, I receive the error as soon as I click on the button in the ribbon menu on my friends' computers. (FYI I created ribbon menu at my friends' computers as well.)

Any help will be appreciated.

答: I was able to resolve this issue by removing all of the menu items associated with the add-in (do so by customizing the ribbon) and then rebuilding the menu items.  In my situation the location of the add-in changed resulting in a path issue.</p>


答:
In the file that you are declaring movies, also declare this function

```<code>   const deleteMovie = key => this.setState({ movies: this.state.movies.filter(movie => movie.imdbID != key })
</code>```

Pass it as props to Movie, and use like

```<code>  onClick ={()=> deleteMovie(movie.imbdID)}
</code>```

Title: How to add event handler for deleting a single item from the list?

Body:
In the file that you are declaring movies, also declare this function

   const deleteMovie = key => this.setState({ movies: this.state.movies.filter(movie => movie.imdbID != key })

Pass it as props to Movie, and use like

  onClick ={()=> deleteMovie(movie.imbdID)}


问:
what is the Chomsky classification of this grammar after reduction ? i'm still confused
this is the grammar before reduction:

my reduction steps is

1- Generation

S -> aC

A -> bSca

C -> ad

2- Reachable

S -> aC

C -> ad

i'm still confused about Chomsky Classification of this grammar

答:
The Wikipedia article on the Chomsky hierarchy provides simple definitions. In particular, it says that a Type 2 (context-free) grammar is:

defined by rules of the form A → α with A being a nonterminal and α being a string of terminals and/or nonterminals.

And a Type 3 (regular) grammar:

restricts its rules to a single nonterminal on the left-hand side and a right-hand side consisting of a single terminal, possibly followed by a single nonterminal.

Your final grammar is:

```<code>S → aC
C → ad
</code>```

and that is not, strictly speaking, a Type 3 grammar because the production for C is not a "single terminal possibly followed by a single non-terminal"; rather, it is a single terminal followed by another single terminal. But that can trivially be rewritten as

```<code>S → aC
C → aD
D → d
</code>```

in which all of the productions obey the Type 3 restriction. This simple transformation can be applied to any grammar which has productions consisting of one or more terminals possibly followed by a single non-terminal, and that is often used as a definition instead of the one in Wikipedia, since the end result is effectively the same.

We can see that every Type 3 grammar is also a Type 2 grammar, since both of the right-hand sides allowed in the Type 3 grammar also conform to the description "a string of terminals and/or nonterminals". So it would not be wrong to say that your final grammar is Type 2, but since it is also Type 3, we would usually describe it as a Type 3 grammar.

Body:
The Wikipedia article on the Chomsky hierarchy provides simple definitions. In particular, it says that a Type 2 (context-free) grammar is:

defined by rules of the form A → α with A being a nonterminal and α being a string of terminals and/or nonterminals.

And a Type 3 (regular) grammar:

restricts its rules to a single nonterminal on the left-hand side and a right-hand side consisting of a single terminal, possibly followed by a single nonterminal.

Your final grammar is:

S → aC
C → ad

and that is not, strictly speaking, a Type 3 grammar because the production for C is not a "single terminal possibly followed by a single non-terminal"; rather, it is a single terminal followed by another single terminal. But that can trivially be rewritten as

S → aC
C → aD
D → d

in which all of the productions obey the Type 3 restriction. This simple transformation can be applied to any grammar which has productions consisting of one or more terminals possibly followed by a single non-terminal, and that is often used as a definition instead of the one in Wikipedia, since the end result is effectively the same.

We can see that every Type 3 grammar is also a Type 2 grammar, since both of the right-hand sides allowed in the Type 3 grammar also conform to the description "a string of terminals and/or nonterminals". So it would not be wrong to say that your final grammar is Type 2, but since it is also Type 3, we would usually describe it as a Type 3 grammar.


问:
Azure Bot Framework| If there is no response from the user for some time, then how to send reminder to the users?
By above question, I mean this-

If there is no activity on the bot for 10 seconds

Bot sends the message>> Looks like you aren't there for now.

Bot>> Ping me again once you are back. Bye for now.

答:
In nodejs you can do this by setting a timeout in your turn handler (onTurn or onMessage). You need to clear the timeout and reset it on every turn if you want the message to be X time after the user's last message. A timeout will send the message once. If you want it to repeat, e.g. every X time after the user's last message, you can use an interval instead of a timeout. I found the easiest way to send the message was as a proactive message, so you do need to include TurnContext and BotFrameworkAdapter from the botbuilder library with this method. The syntax is likely different for C#, but this should point you in the right direction. Here is the function I use:

    async onTurn(context) {

        if (context.activity.type === ActivityTypes.Message) {

            // Save the conversationReference
            const conversationData = await this.dialogState.get(context, {});
            conversationData.conversationReference = TurnContext.getConversationReference(context.activity);
            await this.conversationState.saveChanges(context);
            console.log(conversationData.conversationReference);

            // Reset the inactivity timer
            clearTimeout(this.inactivityTimer);
            this.inactivityTimer = setTimeout(async function(conversationReference) {
                console.log('User is inactive');
                try {
                    const adapter = new BotFrameworkAdapter({
                        appId: process.env.microsoftAppID,
                        appPassword: process.env.microsoftAppPassword
                    });
                    await adapter.continueConversation(conversationReference, async turnContext => {
                        await turnContext.sendActivity('Are you still there?');
                    });
                } catch (error) {
                    //console.log('Bad Request. Please ensure your message contains the conversation reference and message text.');
                    console.log(error);
                }
            }, 300000, conversationData.conversationReference);

            //<<THE REST OF YOUR TURN HANDLER>>
        }
    }
```


问:
How can I untar multiple tar files over ssh?
I am attempting to untar multiple tar files over ssh:

```<code>ssh user@hostname "cat /dir/file*.tgz" | tar xvzf -
</code>```

The above only works on the first file match on the remote server. The local (dest) server only receives one file. The wildcard has been verified to match multiple files though.

Is there another way to do this?

答:
It's easier to work with files than with commands. So rather than use the ssh command to access remote hosts, and the tar command to access archives, use the SSHFS filesystem to access files on remote hosts

```<code>mkdir hostname-dir.tmp
sshfs user@hostname:/dir hostname-dir.tmp
for a in hostname-dir.tmp/*.tgz; do tar xvf "$a"; done
fusermount -u hostname-dir.tmp
</code>```

You can even go one step further and the AVFS to access archives as directories¹. All brought to you by FUSE, a generic framework to access all kinds of things as files.

```<code>mountavfs
mkdir hostname-dir.tmp
sshfs user@hostname:/dir hostname-dir.tmp
for a in ~/.avfs$PWD/hostname-dir.tmp/*.tgz; do cp -Rp "$a#"/* .; done
fusermount -u hostname-dir.tmp
</code>```

If your shell is zsh, that for loop can be replaced by a glob qualifier.

```<code>cp -Rp ~/.avfs$PWD/hostname-dir.tmp/*.tgz(e\''reply=($REPLY\#/*)'\') .
</code>```

¹  AVFS can also access remote files over SSH, but I don't think you can access remote archives that way: AVFS paths only have a single hop. So SSHFS is still necessary.

Body:
I am attempting to untar multiple tar files over ssh:

ssh user@hostname "cat /dir/file*.tgz" | tar xvzf -

The above only works on the first file match on the remote server. The local (dest) server only receives one file. The wildcard has been verified to match multiple files though.

Is there another way to do this?

Body:
It's easier to work with files than with commands. So rather than use the ssh command to access remote hosts, and the tar command to access archives, use the SSHFS filesystem to access files on remote hosts

mkdir hostname-dir.tmp
sshfs user@hostname:/dir hostname-dir.tmp
for a in hostname-dir.tmp/*.tgz; do tar xvf "$a"; done
fusermount -u hostname-dir.tmp

You can even go one step further and the AVFS to access archives as directories¹. All brought to you by FUSE, a generic framework to access all kinds of things as files.

mountavfs
mkdir hostname-dir.tmp
sshfs user@hostname:/dir hostname-dir.tmp
for a in ~/.avfs$PWD/hostname-dir.tmp/*.tgz; do cp -Rp "$a#"/* .; done
fusermount -u hostname-dir.tmp

If your shell is zsh, that for loop can be replaced by a glob qualifier.

cp -Rp ~/.avfs$PWD/hostname-dir.tmp/*.tgz(e\''reply=($REPLY\#/*)'\') .

¹  AVFS can also access remote files over SSH, but I don't think you can access remote archives that way: AVFS paths only have a single hop. So SSHFS is still necessary.


问:
Javascript push function
I want to create simple social media app.I'am working now on part with groups.But I cant filter only groups where some user is member.The code is following

```<code>import { Component, OnInit, OnChanges } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { GroupsService } from '../groups.service';

@Component({
  selector: 'app-groups',
  templateUrl: './groups.component.html',
  styleUrls: ['./groups.component.scss']
})
export class GroupsComponent implements OnInit {
  uid = localStorage.getItem('uid')
  groups: Array<any>;
  mygroups: Array<any>;
  sgroups;
  constructor(private db: AngularFireDatabase, private _groups: GroupsService) {
   }

  ngOnInit() {
    this._groups.getGroups().subscribe((data) => {
      this.groups = data;
    })
    this.loadGroups()
  }
  search(e) {
    this.sgroups = this.groups.find(gr => gr.name.toLowerCase().indexOf(e.target.value.toLowerCase()) > -1)
  }
  loadGroups() {
    this.groups.map(gr => {
     this._groups.getGroupMembers(gr.id).subscribe((data: any) => {
         data.map(mem => {
           if(mem.uid == this.uid) {
            this.mygroups.push(gr); //here is the problem
           }
         })
     })

    })
  }
  scrollnav() {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
  }
}

</code>```

Every help is welcomed.
Thanks a lot!

答:
Problem is in initialization. intialize mygroups like </p>

```<code>mygroups: any[] = [];
</code>```

<p>instead of </p>

```<code> mygroups: Array<any>;
</code>```

Title: Javascript push function

Body:
I want to create simple social media app.I'am working now on part with groups.But I cant filter only groups where some user is member.The code is following

import { Component, OnInit, OnChanges } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { GroupsService } from '../groups.service';

@Component({
  selector: 'app-groups',
  templateUrl: './groups.component.html',
  styleUrls: ['./groups.component.scss']
})
export class GroupsComponent implements OnInit {
  uid = localStorage.getItem('uid')
  groups: Array<any>;
  mygroups: Array<any>;
  sgroups;
  constructor(private db: AngularFireDatabase, private _groups: GroupsService) {
   }

  ngOnInit() {
    this._groups.getGroups().subscribe((data) => {
      this.groups = data;
    })
    this.loadGroups()
  }
  search(e) {
    this.sgroups = this.groups.find(gr => gr.name.toLowerCase().indexOf(e.target.value.toLowerCase()) > -1)
  }
  loadGroups() {
    this.groups.map(gr => {
     this._groups.getGroupMembers(gr.id).subscribe((data: any) => {
         data.map(mem => {
           if(mem.uid == this.uid) {
            this.mygroups.push(gr); //here is the problem
           }
         })
     })

    })
  }
  scrollnav() {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
  }
}

Every help is welcomed.
Thanks a lot!

Body:
Problem is in initialization. intialize mygroups like

mygroups: any[] = [];

instead of

 mygroups: Array<any>;


问:
How to create layout background with 2 different colors in Flutter?
I am trying to make a layout as seen in the image in Flutter, but I don't get how to create a background with two colors and an overlapping button.
I don't know if there is a widget able to do this or need some code...
Any suggest or help will be great! (this was my very first post ever, sorry if there is something wrong about it!!)
Thanks.

答:
Do something like this.

```<code>body: Stack(
    children: <Widget>[
      Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Container(
            width: MediaQuery.of(context).size.width,
            height: 300,
            color: Colors.grey,
          ),
        ],
      ),
      Positioned(
        top: 280,
        left: 50,
        right: 50,
        child: RaisedButton(
          color: Colors.white,
          child: Text("Your Button"),
          onPressed: () {},
        ),
      )
    ],
  ),
</code>```

you will get

Let me know if it works

Body:
Do something like this.

body: Stack(
    children: <Widget>[
      Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Container(
            width: MediaQuery.of(context).size.width,
            height: 300,
            color: Colors.grey,
          ),
        ],
      ),
      Positioned(
        top: 280,
        left: 50,
        right: 50,
        child: RaisedButton(
          color: Colors.white,
          child: Text("Your Button"),
          onPressed: () {},
        ),
      )
    ],
  ),

you will get

Let me know if it works


问:
My JavaScript code won't run after jquery ajax call
jQuery code in a script1.js file

```<code>$(document).ready(()=>{
    $.ajax({
       method:"GET",
       url:"someurl",
       success :
       (data,status,xhr)=>{
         //Create some html buttons after I get the data

         //I want to append the js file here(the JavaScript file adds some event functions to the newly created buttons.I know i can add the event listeners to the button directly here but for some reason I prefer to have the code in a separate js file)
        //This does not work
          $('head'). append('<script src="script_here"></script>')

        }
     })
})
</code>```

JavaScript code in a script2.js file

```<code>document.addEventListener('DOMContentLoaded',ready)

function ready (){
   document.querySelector('button').addEventListener('click',()=>{
   //Do some other stuff
  })
}
</code>```

I have tried  appending the script2.js file through the jQuery but its not working.

I do not want to have everything in one file for easy debugging, and I need to have both vanilla js and jQuery in my project.

答:
If you just want to load an external js file after the ajax call. Then I will show you using in Pure JS. As I have encountered similar issue, so it might help you.

```<code>(data,status,xhr)=>{
    const fileref = document.createElement('script');
    fileref.setAttribute('type', 'text/javascript');
    fileref.setAttribute('src',
    'https://speechanywhere.nuancehdp.com/3.0/scripts/Nuance.SpeechAnywhere.js?_r=' +
    (Math.random() * Math.pow(10, 18)).toString(32)); // the math random will help from cache errors each time you load
    document.getElementsByTagName('head')[0].appendChild(fileref);
}
</code>```

Import and use external JS Library

Body:
jQuery code in a script1.js file

$(document).ready(()=>{
    $.ajax({
       method:"GET",
       url:"someurl",
       success :
       (data,status,xhr)=>{
         //Create some html buttons after I get the data

         //I want to append the js file here(the JavaScript file adds some event functions to the newly created buttons.I know i can add the event listeners to the button directly here but for some reason I prefer to have the code in a separate js file)
        //This does not work
          $('head'). append('')

        }
     })
})

JavaScript code in a script2.js file

document.addEventListener('DOMContentLoaded',ready)

function ready (){
   document.querySelector('button').addEventListener('click',()=>{
   //Do some other stuff
  })
}

I have tried  appending the script2.js file through the jQuery but its not working.

I do not want to have everything in one file for easy debugging, and I need to have both vanilla js and jQuery in my project.

Body:
If you just want to load an external js file after the ajax call. Then I will show you using in Pure JS. As I have encountered similar issue, so it might help you.

(data,status,xhr)=>{
    const fileref = document.createElement('script');
    fileref.setAttribute('type', 'text/javascript');
    fileref.setAttribute('src',
    'https://speechanywhere.nuancehdp.com/3.0/scripts/Nuance.SpeechAnywhere.js?_r=' +
    (Math.random() * Math.pow(10, 18)).toString(32)); // the math random will help from cache errors each time you load
    document.getElementsByTagName('head')[0].appendChild(fileref);
}

Import and use external JS Library


问:
SQL where clause with case statement
I have a problem with SQL that I have not yet found a solution to, what im trying to do is a where clause for a procedure where a userID variable can contain either a valid userID or -1 to indicate all users.

However im stuck at this part of the where clause:

```<code>AND usertable.userid = CASE WHEN @user = -1
THEN

ELSE
  @user
END
</code>```

I'm not sure how to process the -1 to say select all users

Thanks

答:
Could you not put the whole think in an if statement...

Something like

```<code>if (@userId = -1)
    SELECT * FROM usertable
else
    SELECT * FROM usertable WHERE Id = @userId
</code>```

Title: SQL where clause with case statement

Body:
I have a problem with SQL that I have not yet found a solution to, what im trying to do is a where clause for a procedure where a userID variable can contain either a valid userID or -1 to indicate all users.

However im stuck at this part of the where clause:

AND usertable.userid = CASE WHEN @user = -1
THEN

ELSE
  @user
END

I'm not sure how to process the -1 to say select all users

Thanks

Body:
Could you not put the whole think in an if statement...

Something like

if (@userId = -1)
    SELECT * FROM usertable
else
    SELECT * FROM usertable WHERE Id = @userId


问:
How to dump type hierarchy of a C/C++ compilation unit in LLVM
I want to dump the type hierarchy of a C/C++ compilation unit in LLVM. For example, consider this C code:

```<code>struct S {
  int a[3];
  char *s;
};

struct T {
  float f;
  struct S t;
};
</code>```

I want to get a type hierarchy graph like this:

答: You could write a parser for clang -ast-dump that emits a .dot (DOT is a simple graph description language) file where a node could represent a Decl AST node and have an incoming edge when it is a child of another Decl AST node. You could then pipe the .dot file to any any dot renderer, like my favorite, xdot

Body:
I want to dump the type hierarchy of a C/C++ compilation unit in LLVM. For example, consider this C code:

struct S {
  int a[3];
  char *s;
};

struct T {
  float f;
  struct S t;
};

I want to get a type hierarchy graph like this:


问:
Add SVG images to resource file
I think this issue transcends Dev Express, which is why I haven't gone to the vendor's forum just yet (although I could be wrong).  In the latest release of Dev Express Winforms (17.2), there is support for SVG images on the ribbon bar items.  When you use the Dev Express picker and add them to project resources, it looks like this:

I have some SVG images of my own I'd like to add.  Dragging and dropping them adds them as files.  Doing an import through the designer adds them to the form resources, and I want them as project resources (we reuse icons across multiple forms).

Is there an easy way to add local SVG images to my Resources File and have them visible to all controls within the project, the way the Dev Express gallery images are?

If not, is there a hard way?

答:
Don't know if something has changed or if something has happened in the last three years, but this is now super easy -- barely an inconvenience.

To add an SVG to the resources, go to the ImageOptions.SvgImage property of any control, Click on the properties (ellipsis) button, and it will bring up this familiar form:

The "import" button will allow you to add local SVGs into the resource file, which can then be accessed by the entire project.

Title: Add SVG images to resource file


问:
Ffmpeg 2 Input cameras in single ouput
I have app where it streams from a camera to a file with Preview using liabv.
Now there is requirement to be able to stream from 2 cameras simultaneously and output to a single file. The Preview will be like a CCTV camera and written to single output. Is this possible with libav?
Before doing anything I've tried with ffmpeg.exe directly and found this:

```<code>ffmpeg -f dshow -i video="Camera1" -i video="Camera2" -filter_complex "nullsrc=size=640x480 [base];[0:v] setpts=PTS-STARTPTS, scale=640x480 [upperleft];[1:v] setpts=PTS-STARTPTS, scale=640x480 [upperright];[base][upperleft] overlay=shortest=1 [tmp1];[tmp1][upperright] overlay=shortest=1:x=640:y=480 [tmp2];"-c:v libx264 output.mp4
</code>```

But every time throws error 'No such file or directory' for the second camera, while I've verified the camera is working if I use it as single input. Do I miss something?

Overall is it possible to achieve that?

答:
There are several typos in your command, -f dshow is missing for Camera2, your base is too small to show both inputs, and hstack (or vstack) is easier to use. Try:

```<code>ffmpeg -f dshow -i video="Camera1" -f dshow -i video="Camera2" -filter_complex "[0:v]setpts=PTS-STARTPTS,scale=640:-2[left];[1:v]setpts=PTS-STARTPTS,scale=640:-2[right];[left][right]hstack=inputs=2:shortest=1,format=yuv420p[v]" -map "[v]" -c:v libx264 -movflags +faststart output.mp4
</code>```

Title: Ffmpeg 2 Input cameras in single ouput

Body:
I have app where it streams from a camera to a file with Preview using liabv.
Now there is requirement to be able to stream from 2 cameras simultaneously and output to a single file. The Preview will be like a CCTV camera and written to single output. Is this possible with libav?
Before doing anything I've tried with ffmpeg.exe directly and found this:

ffmpeg -f dshow -i video="Camera1" -i video="Camera2" -filter_complex "nullsrc=size=640x480 [base];[0:v] setpts=PTS-STARTPTS, scale=640x480 [upperleft];[1:v] setpts=PTS-STARTPTS, scale=640x480 [upperright];[base][upperleft] overlay=shortest=1 [tmp1];[tmp1][upperright] overlay=shortest=1:x=640:y=480 [tmp2];"-c:v libx264 output.mp4

But every time throws error 'No such file or directory' for the second camera, while I've verified the camera is working if I use it as single input. Do I miss something?

Overall is it possible to achieve that?

Body:
There are several typos in your command, -f dshow is missing for Camera2, your base is too small to show both inputs, and hstack (or vstack) is easier to use. Try:

ffmpeg -f dshow -i video="Camera1" -f dshow -i video="Camera2" -filter_complex "[0:v]setpts=PTS-STARTPTS,scale=640:-2[left];[1:v]setpts=PTS-STARTPTS,scale=640:-2[right];[left][right]hstack=inputs=2:shortest=1,format=yuv420p[v]" -map "[v]" -c:v libx264 -movflags +faststart output.mp4


问:
Efficiently Join Two Tables with Several WHEREs
I meet a problem when I try to join two large tables and select entries with WHERE...OR clause:

```<code>SELECT A.a, B.b
FROM A JOIN B
ON A.equal = B.equal
WHERE A.condition1 > 100 OR B.condition2 > 200
</code>```

Here A and B are very very large tables, and the entries need to match the WHERE...OR conditions in different tables. May I ask if there are any approaches I can optimize this clause?

Thx in advance.

答:
Study the execution logs. If it is a skew (single reducer runs slow), see this answer.  And if there is no skew, then

try to increase parallelism:

Example settings for Mappers on Tez:

```<code>set hive.input.format=org.apache.hadoop.hive.ql.io.HiveInputFormat;
set tez.grouping.max-size=32000000;
set tez.grouping.min-size=32000;
</code>```

Example settings for Mappers if you decide to run on MR instead of Tez:

```<code>set mapreduce.input.fileinputformat.split.minsize=32000;
set mapreduce.input.fileinputformat.split.maxsize=32000000;
</code>```

--example settings for reducers:

```<code>set hive.exec.reducers.bytes.per.reducer=32000000; --decrease this to increase the number of reducers, increase to reduce parallelism
</code>```

Play with these settings. Success criteria is more mappers/reducers and your map and reduce stages are running faster.

See also: https://stackoverflow.com/a/48487306/2700344

@GordonLinoff recipe will work fine if WHERE conditions are selective and smaller filtered dataset fit in memory(before join) and map-join is enabled: set hive.auto.convert.join=true;

Body:
I meet a problem when I try to join two large tables and select entries with WHERE...OR clause:

SELECT A.a, B.b
FROM A JOIN B
ON A.equal = B.equal
WHERE A.condition1 > 100 OR B.condition2 > 200

Here A and B are very very large tables, and the entries need to match the WHERE...OR conditions in different tables. May I ask if there are any approaches I can optimize this clause?

Thx in advance.

Body:
Study the execution logs. If it is a skew (single reducer runs slow), see this answer.  And if there is no skew, then

try to increase parallelism:

Example settings for Mappers on Tez:

set hive.input.format=org.apache.hadoop.hive.ql.io.HiveInputFormat;
set tez.grouping.max-size=32000000;
set tez.grouping.min-size=32000;

Example settings for Mappers if you decide to run on MR instead of Tez:

set mapreduce.input.fileinputformat.split.minsize=32000;
set mapreduce.input.fileinputformat.split.maxsize=32000000;

--example settings for reducers:

set hive.exec.reducers.bytes.per.reducer=32000000; --decrease this to increase the number of reducers, increase to reduce parallelism

Play with these settings. Success criteria is more mappers/reducers and your map and reduce stages are running faster.

See also: https://stackoverflow.com/a/48487306/2700344

@GordonLinoff recipe will work fine if WHERE conditions are selective and smaller filtered dataset fit in memory(before join) and map-join is enabled: set hive.auto.convert.join=true;


问:
How to add trailing slash to url using htaccess?
I am using following htaccess code to redirect the page without extension. it's working fine but now i need to add slash at end of the url how to add i tried lot of nothing is working.

here is my code

```<code>#Alternate default index page
DirectoryIndex index.php

RewriteEngine On

# browser requests PHP
 RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.php
 RewriteRule ^/?(.*)\.php$ /$1 [L,R=301]

# check to see if the request is for a PHP file:
 RewriteCond %{REQUEST_FILENAME}\.php -f
 RewriteRule ^/?(.*)$ /$1.php [L]
</code>```

also i have another problem, while using this config. I tried to call "api/apis.php" file via ajax post request but request failed. request converted to GET like "api/apis".

答:
You just need to disable POST method in first redirect rule:

```<code>DirectoryIndex index.php

RewriteEngine On

# browser requests PHP if request method is not POST
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.php
RewriteRule ^/?(.+)\.php$ /$1 [L,R=301]

# check to see if the request is for a PHP file:
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]
</code>```

Body:
I am using following htaccess code to redirect the page without extension. it's working fine but now i need to add slash at end of the url how to add i tried lot of nothing is working.

here is my code

#Alternate default index page
DirectoryIndex index.php

RewriteEngine On

# browser requests PHP
 RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.php
 RewriteRule ^/?(.*)\.php$ /$1 [L,R=301]

# check to see if the request is for a PHP file:
 RewriteCond %{REQUEST_FILENAME}\.php -f
 RewriteRule ^/?(.*)$ /$1.php [L]

also i have another problem, while using this config. I tried to call "api/apis.php" file via ajax post request but request failed. request converted to GET like "api/apis".

Body:
You just need to disable POST method in first redirect rule:

DirectoryIndex index.php

RewriteEngine On

# browser requests PHP if request method is not POST
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.php
RewriteRule ^/?(.+)\.php$ /$1 [L,R=301]

# check to see if the request is for a PHP file:
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]


问:
“The assembly to be debugged was built with a platform incompatible with the current system.”
I am using Visual studio professional 2019, Version 16.6.0 dot net framework 4.8.03761.
I updated the visual studio and now my C# applications will not debug.

Target Framework is .net 4.7.2
Output type is Windows Application.

Under build Platform target is set to ANY CPU
Prefer 32 bit is unchecked.

My system is 64 bit Windows 10 Enterprise.

I get "Error while trying to run project: Cannot start debugging. The assembly to be debugged was built with a platform incompatible with the current system."

This is now happening with all my C# solutions.

I believe there is a configuration setting somewhere I am missing.

This application is a standard C# application it does not use any externally built DLL it was built created with the wizard for c#.

The application worked fine until I updated Visual studio. to the newest version.

I have reinstalled - repaired the installation/

I have selected Any CPU in configurations.

If I change the configuration it to x64 or x86 it will work but not after I reload the project.
I then have to delete the configuration and recreate it for it to debug.

The application will execute outside of the debugger on the command line and launch the UI with no issues.

Configuration Properties are set to Debug Any CPU with the Build box checked.

If someone else loads the solution in the visual studio the application works and debugs fine.

I have deleted the application and reloaded from the base that works from configuration management, unchanged from when it worked. I get the same issue.

答:
I found the error, it seems a user variable was set for the platform when cross-compiling another application this was not cleaned up and it caused Visual studio to inadvertently set the Platform architecture to ARM so no matter what you set the platform to while debugging in the UI it was defaulting to the system environment variable. When the debugger launches I think it validates against this environment variable set for the system and not the project it seems like a bug. Removing the environment variable specifying the platform resolves the issue.

A link to the list of env variables used by Visual Studio

https://learn.microsoft.com/en-us/cpp/build/reference/common-macros-for-build-commands-and-properties?redirectedfrom=MSDN&view=vs-2019

As a note, if using multiple build systems and visual studio it is possible to have conflicts with visual studio platform options that are not reset by the solution when changing configurations within the configuration manager.


问:
Evaluation order in ternary operator with increments
```<code>#define MAX(a,b) ((a)>(b) ? (a) : (b))
   int main(void) {
   int a=2;
   int b=3;

   int c = MAX(a++,b++); // c=((a++)>(b++) ? (a++) : (b++));
   printf("\na= %d", a);// a=3
   printf("\nb= %d", b);//b=5
   printf("\nc= %d", c);//c=4

   a=3;
   b=2;
   cc = MAX(a++,b++); // c=((a++)>(b++) ? (a++) : (b++));

   printf("\na= %d", a); // a=5
   printf("\nb= %d", b); //b=3
   printf("\nc= %d", c); //c=4

return 0;
}
</code>```

I would like to know why c is not evaluating to 5.

It appears to me the evaluation order should be:

First both a and be get incremented in  (a++)>(b++)

If for example the first one is greater, the ternary operator in
c=((a++)>(b++) ? (a++) : (b++)), goes to  (a++), so a
increments again.

The result of the ternary expression, which is a twice-increment,
should be assigned to c, then c should have the greater value
twice-incremented, that is 5. However, I am getting 4. I suspect the
greater value's second increment is happening at the end, but I can't
explain why, since the parentheses seem to indicate that the
assignment comes at the end.

Any idea?

答:
The postfix ++ operator has a result and a side effect.  The result of a++ is the value of a before the increment - given

```<code>int a = 1;
int x = a++;
</code>```

the value of x will be 1 and the value of a will be 2.  Note that the side effect of adding 1 to a does not have to be applied immediately after evaluation - it only has to be applied before the next sequence point.

So, looking at

```<code>((a++) > (b++)) ? (a++) : (b++)
</code>```

The ?: operator forces left-to-right evaluation, so the first thing that happens is that (a++) > (b++) is evaluated1.  Since a is initially 2 and b is initially 3, the result of the expression is false (0).  The ? operator introduces a sequence point, so the side effects to a and b are applied and a is now 3 and b is now 4.

Since the result of the condition expression was 0, we evaluate b++.  Same thing, the result of the expression is the current value of b (4), and that value gets assigned to c.  The side effect to b is applied at some point, and by the time everything's finished, a is 3, b is 5, and c is 4.

Although within that expression either a++ or b++ may be evaluated first, since the > operator doesn't force left-to-right evaluation.

Body:
#define MAX(a,b) ((a)>(b) ? (a) : (b))
   int main(void) {
   int a=2;
   int b=3;

   int c = MAX(a++,b++); // c=((a++)>(b++) ? (a++) : (b++));
   printf("\na= %d", a);// a=3
   printf("\nb= %d", b);//b=5
   printf("\nc= %d", c);//c=4

   a=3;
   b=2;
   cc = MAX(a++,b++); // c=((a++)>(b++) ? (a++) : (b++));

   printf("\na= %d", a); // a=5
   printf("\nb= %d", b); //b=3
   printf("\nc= %d", c); //c=4

return 0;
}

I would like to know why c is not evaluating to 5.

It appears to me the evaluation order should be:

First both a and be get incremented in  (a++)>(b++)

If for example the first one is greater, the ternary operator in
c=((a++)>(b++) ? (a++) : (b++)), goes to  (a++), so a
increments again.

The result of the ternary expression, which is a twice-increment,
should be assigned to c, then c should have the greater value
twice-incremented, that is 5. However, I am getting 4. I suspect the
greater value's second increment is happening at the end, but I can't
explain why, since the parentheses seem to indicate that the
assignment comes at the end.

Any idea?

Body:
The postfix ++ operator has a result and a side effect.  The result of a++ is the value of a before the increment - given

int a = 1;
int x = a++;

the value of x will be 1 and the value of a will be 2.  Note that the side effect of adding 1 to a does not have to be applied immediately after evaluation - it only has to be applied before the next sequence point.

So, looking at

((a++) > (b++)) ? (a++) : (b++)

The ?: operator forces left-to-right evaluation, so the first thing that happens is that (a++) > (b++) is evaluated1.  Since a is initially 2 and b is initially 3, the result of the expression is false (0).  The ? operator introduces a sequence point, so the side effects to a and b are applied and a is now 3 and b is now 4.

Since the result of the condition expression was 0, we evaluate b++.  Same thing, the result of the expression is the current value of b (4), and that value gets assigned to c.  The side effect to b is applied at some point, and by the time everything's finished, a is 3, b is 5, and c is 4.

Although within that expression either a++ or b++ may be evaluated first, since the > operator doesn't force left-to-right evaluation.


问:
Maven - Sharing libraries between projects
I'm working on a multi-project, and right now I have a structure that resembles this (actually there are a couple of jar projects and a couple of war projects)

```<code>/myProj
 |_______projA (jar)
 |          |____pom.xml
 |          |____target/jar files
 |_______projB (war)
 |          |___pom.xml
 |          |___web-inf/lib/jarfiles
 |_______projEar
 |          |___pom.xml
 |___pom.xml
</code>```

What I want to achieve, is to make projA and projB to read their dependences from a common shared folder, instead of keeping their own copy.

Actually, I don't really care where they read them from at compile time, but when I package my EAR file, I want each jar/war to appear just once, hence reducing the EAR size.

I've tried declaring the dependencies on the parent pom, declaring the dependencies as  and some other things, but so far I haven't achieved this.

Is there an easy way to achieve this? Any simple maven plugin?

Thanks in advance.

答:
When you are moving to Maven, you should not store the dependency JAR's in your code base.  I would suggest you to create a central Maven repository which will contain all the dependencies.

Refer mvn install to first install these artifacts into the local repository. Also, you can refer to the maven central repository to get artifacts while building.

What you need to do is: remove all the dependency jar's from the source code, and all their dependency in the pom.xml. These would be downloaded and packaged from the maven central repository as and when required. Set the Dependency Scope of the artifacts accordingly.

Body:
I'm working on a multi-project, and right now I have a structure that resembles this (actually there are a couple of jar projects and a couple of war projects)

/myProj
 |_______projA (jar)
 |          |____pom.xml
 |          |____target/jar files
 |_______projB (war)
 |          |___pom.xml
 |          |___web-inf/lib/jarfiles
 |_______projEar
 |          |___pom.xml
 |___pom.xml

What I want to achieve, is to make projA and projB to read their dependences from a common shared folder, instead of keeping their own copy.

Actually, I don't really care where they read them from at compile time, but when I package my EAR file, I want each jar/war to appear just once, hence reducing the EAR size.

I've tried declaring the dependencies on the parent pom, declaring the dependencies as  and some other things, but so far I haven't achieved this.

Is there an easy way to achieve this? Any simple maven plugin?

Thanks in advance.


问:
How to change X window Properties
I am using gdm and my goal is to disable user interaction on a specific X window id.

I have tried to change many X-win properties like WM_PROTOCOLS, WM_HINTS, _NET_WM_ALLOWED_ACTIONS using xprop. Although, I was successful to change the properties it looks either wm is ignoring my changes and instead of taking defaults or an xsync(like) step is required to reflect those changes.

Using xprop as follows to change WM_HINTS:

xprop -id 0x6a001f9 -format WM_HINTS 32cbcxxiixx -set WM_HINTS 3,False,1,0x0,0x0,0,0,0x0,0x0

result of xprop -id 0x6a001f9 WM_HINTS [BEFORE]:

```<code>WM_HINTS(WM_HINTS):
    Client accepts input or input focus: True
    Initial state is Normal State.
</code>```

result of xprop -id 0x6a001f9 WM_HINTS [AFTER]:

```<code>WM_HINTS(CARDINAL):
    Client accepts input or input focus: False
    Initial state is Normal State.
</code>```

Apart from property type, which changes from WM_HINTS to CARDINAL, everything else is as expected but still, window # 0x6a001f9 receives input.

Output of xwininfo confirms that:

xwininfo -id 0x6a001f9 -wm   ====>

```<code>xwininfo: Window id: 0x6a001f9 "Log Attribute Selection"

  No window manager hints defined
     Window manager hints:
     Displayed on desktop 0
     Process id: (unknown)
     Frame extents: 4, 4, 24, 4
</code>```

What am I missing?

答:
update: check this comment, it has the code that works here! https://gist.github.com/muktupavels/d03bb14ea6042b779df89b4c87df975d#gistcomment-3331569

unfortunatelly I cant comment... but this may help (one day when it is ready).

I have exactly the same problem:

https://unix.stackexchange.com/questions/590282/how-to-prevent-input-focus-for-a-single-window-in-gnome-shell-window-manager

I tested your command, it gives the same result, the window hint changes but it still receives input focus...

I guess we need to remove the WM_TAKE_FOCUS protocol then, but to do that may be complicated.

I think we could join forces to tweak this small code to let that happen:

https://gist.github.com/muktupavels/d03bb14ea6042b779df89b4c87df975d

I am still trying to understand it to see where/what to change there.

This may be the only answer if we manage to tweak that code.

obs.: what you did with xprop, may be if done with that gist code could work, it is like xprop cant change some things but can change others (like window title). So, it may be more simple as there is code there already to change window hints!

Title: How to change X window Properties

Body:
I am using gdm and my goal is to disable user interaction on a specific X window id.

I have tried to change many X-win properties like WM_PROTOCOLS, WM_HINTS, _NET_WM_ALLOWED_ACTIONS using xprop. Although, I was successful to change the properties it looks either wm is ignoring my changes and instead of taking defaults or an xsync(like) step is required to reflect those changes.

Using xprop as follows to change WM_HINTS:

xprop -id 0x6a001f9 -format WM_HINTS 32cbcxxiixx -set WM_HINTS 3,False,1,0x0,0x0,0,0,0x0,0x0

result of xprop -id 0x6a001f9 WM_HINTS [BEFORE]:

WM_HINTS(WM_HINTS):
    Client accepts input or input focus: True
    Initial state is Normal State.

result of xprop -id 0x6a001f9 WM_HINTS [AFTER]:

WM_HINTS(CARDINAL):
    Client accepts input or input focus: False
    Initial state is Normal State.

Apart from property type, which changes from WM_HINTS to CARDINAL, everything else is as expected but still, window # 0x6a001f9 receives input.

Output of xwininfo confirms that:

xwininfo -id 0x6a001f9 -wm   ====>

xwininfo: Window id: 0x6a001f9 "Log Attribute Selection"

  No window manager hints defined
     Window manager hints:
     Displayed on desktop 0
     Process id: (unknown)
     Frame extents: 4, 4, 24, 4

What am I missing?


答:
You can use forkJoin to fire all of the calls at once and get an array with all the results:

import {forkJoin} from 'rxjs';

...

const requests = this.groups.map(gr => this._groups.getGroupMembers(gr.id));

forkJoin(requests).subscribe((res) => this.mygroups = res);

```

Title: Javascript push function

Body:
I want to create simple social media app.I'am working now on part with groups.But I cant filter only groups where some user is member.The code is following

import { Component, OnInit, OnChanges } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { GroupsService } from '../groups.service';

@Component({
  selector: 'app-groups',
  templateUrl: './groups.component.html',
  styleUrls: ['./groups.component.scss']
})
export class GroupsComponent implements OnInit {
  uid = localStorage.getItem('uid')
  groups: Array<any>;
  mygroups: Array<any>;
  sgroups;
  constructor(private db: AngularFireDatabase, private _groups: GroupsService) {
   }

  ngOnInit() {
    this._groups.getGroups().subscribe((data) => {
      this.groups = data;
    })
    this.loadGroups()
  }
  search(e) {
    this.sgroups = this.groups.find(gr => gr.name.toLowerCase().indexOf(e.target.value.toLowerCase()) > -1)
  }
  loadGroups() {
    this.groups.map(gr => {
     this._groups.getGroupMembers(gr.id).subscribe((data: any) => {
         data.map(mem => {
           if(mem.uid == this.uid) {
            this.mygroups.push(gr); //here is the problem
           }
         })
     })

    })
  }
  scrollnav() {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
  }
}

Every help is welcomed.
Thanks a lot!


问:
Extra line getting added in c++ program csv file?
My current code adds extra portion to the final result. I am reading a csv file and adding certain elements to variables. My end result always adds an extra element to the screen? What am i doing wrong?

Code:

```<code>int main()
{
    ifstream file("data.csv");
    //checks to see if file is valid
    if (!file.is_open())
    {
        cout << "Invalid file" << endl;
    }
    string name;
    string age;
    string college;
    while (file.good())
    {
        getline(file, name, ',');
        getline(file, age, ',');
        getline(file, college, '\n');
        cout << "Name: " << name << '\n';
        cout << "Age: " << age << endl;
        cout << "College: " << college << endl;
        cout << "------------------" << endl;
    }
    //closes the file and program terminates
    file.close();
    return 0;
}
</code>```

答:
file.good() will return true after you've read the last line in the file so while (file.good()) will loop one extra round, but the getlines will fail.

Replace the loop with:

```<code>while (getline(file, name, ',') &&
       getline(file, age, ',') &&
       getline(file, college, '\n'))
{
    cout << "Name: " << name << '\n';
    cout << "Age: " << age << endl;
    cout << "College: " << college << endl;
    cout << "------------------" << endl;
}
</code>```

getline will return file& and an ifstream returns true or false in boolean contexts depending on if it's in a good state or not.

Body:
My current code adds extra portion to the final result. I am reading a csv file and adding certain elements to variables. My end result always adds an extra element to the screen? What am i doing wrong?

Code:

int main()
{
    ifstream file("data.csv");
    //checks to see if file is valid
    if (!file.is_open())
    {
        cout << "Invalid file" << endl;
    }
    string name;
    string age;
    string college;
    while (file.good())
    {
        getline(file, name, ',');
        getline(file, age, ',');
        getline(file, college, '\n');
        cout << "Name: " << name << '\n';
        cout << "Age: " << age << endl;
        cout << "College: " << college << endl;
        cout << "------------------" << endl;
    }
    //closes the file and program terminates
    file.close();
    return 0;
}

Body:
file.good() will return true after you've read the last line in the file so while (file.good()) will loop one extra round, but the getlines will fail.

Replace the loop with:

while (getline(file, name, ',') &&
       getline(file, age, ',') &&
       getline(file, college, '\n'))
{
    cout << "Name: " << name << '\n';
    cout << "Age: " << age << endl;
    cout << "College: " << college << endl;
    cout << "------------------" << endl;
}

getline will return file& and an ifstream returns true or false in boolean contexts depending on if it's in a good state or not.