问:
How to test Apache HttpClient RequestConfig values are set correctly? No public getters present
I have this class to configure a HttpClient instance:

```<code>package com.company.fraud.preauth.service.feignaccertifyclient;

    import com.company.fraud.preauth.config.ProviderClientConfig;
    import lombok.RequiredArgsConstructor;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.ssl.SSLContextBuilder;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;

    import java.security.KeyManagementException;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;

    @Slf4j
    @Configuration
    @RequiredArgsConstructor
    public class FeignClientConfig {

        private final ProviderClientConfig providerClientConfig;

        public HttpClient buildHttpClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
            RequestConfig.Builder requestBuilder = RequestConfig.custom();
            requestBuilder.setConnectTimeout(providerClientConfig.getConnectionTimeout());
            requestBuilder.setConnectionRequestTimeout(providerClientConfig.getConnectionRequestTimeout());
            requestBuilder.setSocketTimeout(providerClientConfig.getSocketTimeout());
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

            return HttpClientBuilder.create()
                    .setMaxConnPerRoute(providerClientConfig.getMaxConnectionNumber())
                    .setDefaultRequestConfig(requestBuilder.build())
                    .setSSLContext(builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()).build())
                    .build();
        }
    }
</code>```

How to unit test this class, to see into the resulted HttpClient that these values are correctly set?

From the httpClient I cannot get access to its RequestConfig.

I am aware of these two posts:

How do I test a private function or a class that has private methods, fields or inner classes?
(the number of upvotes in this question shows that it is a concurrent and controversial topic in testing, and my situation may offer an example that why we should look into the inner state of an instance in testing, despite that it is private)

Unit test timeouts in Apache HttpClient
(it shows a way of adding an interceptor in code to check configure values, but I don't like it because I want to separate tests with functional codes)

Is there any way? I understand that this class should be tested, right? You cannot blindly trust it to work; and checking it "notNull" seems fragile to me.

This link may point me to the right direction:

https://dzone.com/articles/testing-objects-internal-state

It uses PowerMock.Whitebox to check internal state of an instance.

答:
Whitebox was working for me. As it is not documented here I'm adding my version:

in my case wanted to test that the timeout is different from 0 to avoid deadlock

```<code>    HttpClient httpClient = factory.getHttpClient();

    RequestConfig sut = Whitebox.getInternalState(httpClient, "defaultConfig");

    assertNotEquals(0, sut.getConnectionRequestTimeout());
    assertNotEquals(0, sut.getConnectTimeout());
    assertNotEquals(0, sut.getSocketTimeout());
</code>```

Body:
I have this class to configure a HttpClient instance:

package com.company.fraud.preauth.service.feignaccertifyclient;

    import com.company.fraud.preauth.config.ProviderClientConfig;
    import lombok.RequiredArgsConstructor;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.ssl.SSLContextBuilder;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;

    import java.security.KeyManagementException;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;

    @Slf4j
    @Configuration
    @RequiredArgsConstructor
    public class FeignClientConfig {

        private final ProviderClientConfig providerClientConfig;

        public HttpClient buildHttpClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
            RequestConfig.Builder requestBuilder = RequestConfig.custom();
            requestBuilder.setConnectTimeout(providerClientConfig.getConnectionTimeout());
            requestBuilder.setConnectionRequestTimeout(providerClientConfig.getConnectionRequestTimeout());
            requestBuilder.setSocketTimeout(providerClientConfig.getSocketTimeout());
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

            return HttpClientBuilder.create()
                    .setMaxConnPerRoute(providerClientConfig.getMaxConnectionNumber())
                    .setDefaultRequestConfig(requestBuilder.build())
                    .setSSLContext(builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()).build())
                    .build();
        }
    }

How to unit test this class, to see into the resulted HttpClient that these values are correctly set?

From the httpClient I cannot get access to its RequestConfig.

I am aware of these two posts:

How do I test a private function or a class that has private methods, fields or inner classes?
(the number of upvotes in this question shows that it is a concurrent and controversial topic in testing, and my situation may offer an example that why we should look into the inner state of an instance in testing, despite that it is private)

Unit test timeouts in Apache HttpClient
(it shows a way of adding an interceptor in code to check configure values, but I don't like it because I want to separate tests with functional codes)

Is there any way? I understand that this class should be tested, right? You cannot blindly trust it to work; and checking it "notNull" seems fragile to me.

This link may point me to the right direction:

https://dzone.com/articles/testing-objects-internal-state

It uses PowerMock.Whitebox to check internal state of an instance.

Body:
Whitebox was working for me. As it is not documented here I'm adding my version:

in my case wanted to test that the timeout is different from 0 to avoid deadlock

    HttpClient httpClient = factory.getHttpClient();

    RequestConfig sut = Whitebox.getInternalState(httpClient, "defaultConfig");

    assertNotEquals(0, sut.getConnectionRequestTimeout());
    assertNotEquals(0, sut.getConnectTimeout());
    assertNotEquals(0, sut.getSocketTimeout());


来源: stackexchange

问:
How to fix bugs in a legacy application without profound refactoring first?
There is a mid-size legacy application (20K LoC, 150 java classes). The quality of design and code is very low, no unit tests, no documentation. However it works.

You're hired to maintain the application. There is a list of very specific properly-reported bugs. It's very difficult to understand how to fix them. Time is limited, you should start solving these bugs within a few weeks (you simply don't have time for a profound refactoring first). How to do this?

答:
Start with the first bug.  Maybe the easiest, maybe the highest-priority.  Whatever makes sense for your shop.

Don't fix it.

Instead, figure out why it's not working correctly.  From your description, it's not likely to be in some neat, nice, unit-testable method; it's probably deep in some convoluted logic somewhere.  Find it.

Don't fix it.

Work out a way to extract the culprit.  Maybe it's Extract Method; maybe it's Extract Class; maybe some other technique will help.  But get it out there, independent of other code.  Still failing, just easier to work with.  Now, write a test that demonstrates the failure.

OK, now fix it.

What have you done?  You've isolated the problem, fixed it, made a small section of your code easier to work it, and begun to get test coverage in place.

Lather, rinse, repeat.

ContentLicense: CC BY-SA 3.0


问:
Reload child component when variables on parent component changes. Angular2
I have a MasterComponent which loads header, footer, sidebar etc. On the header there is a dropdown whose options are set once the user is logged in. I want the header to be constant even if I navigate to different routes which loads different child component. Means that the selected option should not change and value of dropdown should be accessible in all the child component. Onchange of dropdown value, the current child component should be updated/reloaded.

How should I approach this problem? I want to have event-listener kind of functionality. Once the model from MasterComponent Changes, reload the current child component. On MasterComponent's variable update,
ChildComponent will listen to the update and run some function or call some API again and reload the ChildComponent.

// routes
const appRoutes: Routes = [
    {
        path: '',
        redirectTo: 'login',
        pathMatch: 'full',
    },
    {   path: 'login', component: LoginComponent },
    {   path: 'logout', component: LogoutComponent },
    {
        path: '',
        component: MasterComponent,
        canActivate: [AuthGuard],
        children: [
            { path: 'record/create', component: RecordCreateComponent }, // create record for selectedRestaurant in MasterComponent
            { path: 'record/', component: RecordComponent }, // shows all record of current selectedRestaurant in MasterComponent
            { path: 'record/:id/update', component:RecordUpdateComponent }, // show form to edit record having id
            { path: 'record/:id', component: RecordComponent }, // show record details having id
        ]
    },
    { path: '**', redirectTo: 'login' }
];
```
<pre class="lang-ts prettyprint-override"><code>// MasterComponent
@Component({
    selector: 'master',
    templateUrl: templateUrl,
    styleUrls:[styleUrl1]

})
export class MasterComponent implements AfterViewInit, OnInit{
    restaurants: Array<Restaurant> = [];
    user:User;
    selectedRestaurant: Restaurant;

    constructor(private router: Router, private storageHelper:StorageHelper){
    }
    ngAfterViewInit() {
    }
    ngOnInit(){
        this.user = JSON.parse(this.storageHelper.getItem('user'));
        this.restaurants = this.user.restaurants;
        this.selectedRestaurant = this.restaurants[0];
        this.router.navigate(['/record/' + this.selectedRestaurant.id]);
    }
    onRestaurantChange(){
        this.router.navigate(['/record/' + this.selectedRestaurant.id]);
    }
    createRecord(){
    }
}
</code>```

答:
In case, when we have no control over child component, like a 3rd party library component.

We can use *ngIf and setTimeout to reset the child component from parent without making any change in child component.

.template:

```<code><child-component *ngIf="show"></child-component>
<button (click)="resetChildForm()"></button>
</code>```

.ts:

```<code>show:boolean = true

resetChildForm(){
   this.show = false;

   setTimeout(() => {
      this.show = true
    }, 100);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a MasterComponent which loads header, footer, sidebar etc. On the header there is a dropdown whose options are set once the user is logged in. I want the header to be constant even if I navigate to different routes which loads different child component. Means that the selected option should not change and value of dropdown should be accessible in all the child component. Onchange of dropdown value, the current child component should be updated/reloaded.

How should I approach this problem? I want to have event-listener kind of functionality. Once the model from MasterComponent Changes, reload the current child component. On MasterComponent's variable update,
ChildComponent will listen to the update and run some function or call some API again and reload the ChildComponent.

// routes
const appRoutes: Routes = [
    {
        path: '',
        redirectTo: 'login',
        pathMatch: 'full',
    },
    {   path: 'login', component: LoginComponent },
    {   path: 'logout', component: LogoutComponent },
    {
        path: '',
        component: MasterComponent,
        canActivate: [AuthGuard],
        children: [
            { path: 'record/create', component: RecordCreateComponent }, // create record for selectedRestaurant in MasterComponent
            { path: 'record/', component: RecordComponent }, // shows all record of current selectedRestaurant in MasterComponent
            { path: 'record/:id/update', component:RecordUpdateComponent }, // show form to edit record having id
            { path: 'record/:id', component: RecordComponent }, // show record details having id
        ]
    },
    { path: '**', redirectTo: 'login' }
];

// MasterComponent
@Component({
    selector: 'master',
    templateUrl: templateUrl,
    styleUrls:[styleUrl1]

})
export class MasterComponent implements AfterViewInit, OnInit{
    restaurants: Array<Restaurant> = [];
    user:User;
    selectedRestaurant: Restaurant;

    constructor(private router: Router, private storageHelper:StorageHelper){
    }
    ngAfterViewInit() {
    }
    ngOnInit(){
        this.user = JSON.parse(this.storageHelper.getItem('user'));
        this.restaurants = this.user.restaurants;
        this.selectedRestaurant = this.restaurants[0];
        this.router.navigate(['/record/' + this.selectedRestaurant.id]);
    }
    onRestaurantChange(){
        this.router.navigate(['/record/' + this.selectedRestaurant.id]);
    }
    createRecord(){
    }
}

Body:
In case, when we have no control over child component, like a 3rd party library component.

We can use *ngIf and setTimeout to reset the child component from parent without making any change in child component.

.template:

<child-component *ngIf="show"></child-component>
<button (click)="resetChildForm()"></button>

.ts:

show:boolean = true

resetChildForm(){
   this.show = false;

   setTimeout(() => {
      this.show = true
    }, 100);
}


问:
Delete the old connectionstring
I have created a application that can create connectionstrings and edit connectionstrings.

```<code>doc.Load(Path.Combine(path, SelectConfigComboBox.SelectedItem.ToString(), "app.config"));
XmlNode xNode = doc.CreateNode(XmlNodeType.Element, "add", "");
XmlAttribute xName = doc.CreateAttribute("name");
XmlAttribute xconnectionString = doc.CreateAttribute("connectionString");
xName.Value = NewKeyTextBox.Text;

xconnectionString.Value = string.Format("data source={0};persist security info={1};initial catalog={2};USER ID={3};password={4}", NewValueTextBox.Text, SecurityInfocomboBox.Text, CatalogcomboBox.Text, UserIDtextBox.Text, PasswordtextBox.Text);

xNode.Attributes.Append(xName);
xNode.Attributes.Append(xconnectionString);
doc.GetElementsByTagName("connectionStrings")[0].InsertAfter(xNode,
doc.GetElementsByTagName("connectionStrings")[0].LastChild);

doc.Save(Path.Combine(path, SelectConfigComboBox.SelectedItem.ToString(), "app.config"));
</code>```

With this code I enter a new connectionString. When I want to edit the connectionstring it will add a new one without deleting the other one. How can I delete the old one before adding the new one?

答:
goto web.config file in visual studio and place the code as
below

<connectionStrings>
  <add name="ConnectionString"
       connectionString="Data Source=HP_01\MSSQLSERVER01;Initial Catalog=test;Integrated Security=true;"
       providerName="System.Data.SqlClient" />
  <add name="testEntities"
       connectionString="metadata=res:///webservice.csdl|res:///webservice.ssdl|res://*/webservice.msl;provider=System.Data.SqlClient;provider connection string="data source=HP_01\MSSQLSERVER01;initial catalog=test;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
       providerName="System.Data.EntityClient" />
</connectionStrings>
```

Title: Delete the old connectionstring

Body:
I have created a application that can create connectionstrings and edit connectionstrings.

doc.Load(Path.Combine(path, SelectConfigComboBox.SelectedItem.ToString(), "app.config"));
XmlNode xNode = doc.CreateNode(XmlNodeType.Element, "add", "");
XmlAttribute xName = doc.CreateAttribute("name");
XmlAttribute xconnectionString = doc.CreateAttribute("connectionString");
xName.Value = NewKeyTextBox.Text;

xconnectionString.Value = string.Format("data source={0};persist security info={1};initial catalog={2};USER ID={3};password={4}", NewValueTextBox.Text, SecurityInfocomboBox.Text, CatalogcomboBox.Text, UserIDtextBox.Text, PasswordtextBox.Text);

xNode.Attributes.Append(xName);
xNode.Attributes.Append(xconnectionString);
doc.GetElementsByTagName("connectionStrings")[0].InsertAfter(xNode,
doc.GetElementsByTagName("connectionStrings")[0].LastChild);

doc.Save(Path.Combine(path, SelectConfigComboBox.SelectedItem.ToString(), "app.config"));

With this code I enter a new connectionString. When I want to edit the connectionstring it will add a new one without deleting the other one. How can I delete the old one before adding the new one?

Body:
goto web.config file in visual studio and place the code as
below

<connectionStrings>
  <add name="ConnectionString"
       connectionString="Data Source=HP_01\MSSQLSERVER01;Initial Catalog=test;Integrated Security=true;"
       providerName="System.Data.SqlClient" />
  <add name="testEntities"
       connectionString="metadata=res:///webservice.csdl|res:///webservice.ssdl|res://*/webservice.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=HP_01\MSSQLSERVER01;initial catalog=test;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;"
       providerName="System.Data.EntityClient" />
</connectionStrings>


问:
create an ID column with randomly generated values in R
I am using the package called mtcars and I want to get a randomly generated number for every observations. I have written a function:

```<code>mtcars$ID <- NULL
for (i in mtcars){
  mtcars$ID <- runif(1, min=0, max=100)
}
</code>```

However, this assigns the same number to all cars.

I tried:

```<code>mtcars$ID <- NULL
for (i in mtcars){
  mtcars$ID[i] <- runif(1, min=0, max=100)
}
</code>```

which results in an error. I would like to get two type of results (two functions):

to assign a random number to each observation

to assign a unique random number to each observation

答:
You could use sample on the number of rows in the dataset.

```<code>mtcars$ID <- sample(nrow(mtcars))
</code>```

The range for this would be from 1 to number of rows in data and it would be randomly assigned to every row.

It can also be wrapped in a function if needed :

```<code>get_a_unique_id <- function(data) sample(nrow(data))

mtcars$ID <- get_a_unique_id(mtcars)
iris$ID <- get_a_unique_id(iris)
</code>```

Regarding OP's attempt on for loop. NULL deletes the column whereas NA initializes it with NA.Since there is no column present in mtcars, it results in an error. Also the loop for (i in mtcars){ loops over the column values and not rows. Try

```<code> for (i in mtcars){
    print(i)
 }
</code>```

Hence, it should be

```<code>mtcars$ID <- NA
for (i in seq_len(nrow(mtcars))){
   mtcars$ID[i] <- runif(1, min=0, max=100)
}
</code>```

However, even this does not guarantee 100% on having a unique value for each row since with runif we can have same numbers.

Body:
I am using the package called mtcars and I want to get a randomly generated number for every observations. I have written a function:

mtcars$ID <- NULL
for (i in mtcars){
  mtcars$ID <- runif(1, min=0, max=100)
}

However, this assigns the same number to all cars.

I tried:

mtcars$ID <- NULL
for (i in mtcars){
  mtcars$ID[i] <- runif(1, min=0, max=100)
}

which results in an error. I would like to get two type of results (two functions):

to assign a random number to each observation

to assign a unique random number to each observation

Body:
You could use sample on the number of rows in the dataset.

mtcars$ID <- sample(nrow(mtcars))

The range for this would be from 1 to number of rows in data and it would be randomly assigned to every row.

It can also be wrapped in a function if needed :

get_a_unique_id <- function(data) sample(nrow(data))

mtcars$ID <- get_a_unique_id(mtcars)
iris$ID <- get_a_unique_id(iris)

Regarding OP's attempt on for loop. NULL deletes the column whereas NA initializes it with NA.Since there is no column present in mtcars, it results in an error. Also the loop for (i in mtcars){ loops over the column values and not rows. Try

 for (i in mtcars){
    print(i)
 }

Hence, it should be

mtcars$ID <- NA
for (i in seq_len(nrow(mtcars))){
   mtcars$ID[i] <- runif(1, min=0, max=100)
}

However, even this does not guarantee 100% on having a unique value for each row since with runif we can have same numbers.


问:
How to tell JetBrains IDE that template string is JS code
I have an ES6 template string, which represents JS code. If I put

答:
IDEA auto-injects HTML in JavaScript string literals/template string if there are HTML tags in it; to inject other languages, you need adding language injection manually - for example, the language can be temporary injected via Inject language or reference intention available on Alt+Enter:

You can also annotate your injection with comments to make it permanent:

```<code>//language=JS
const baz = `console.log("test")`
</code>```

See https://www.jetbrains.com/help/idea/using-language-injections.html for more information

Body:
IDEA auto-injects HTML in JavaScript string literals/template string if there are HTML tags in it; to inject other languages, you need adding language injection manually - for example, the language can be temporary injected via Inject language or reference intention available on Alt+Enter:

You can also annotate your injection with comments to make it permanent:

//language=JS
const baz = `console.log("test")`

See https://www.jetbrains.com/help/idea/using-language-injections.html for more information


问:
ValueError: setting an array element with a sequence - passing a list in a dictionary to DataGenerator
I am working on a keras multilabel problem. In order to work with big amount of data to avoid memory issues, I implemented a custom data generator.

So far I work with a csv file with IDs, Filenames and their corresponding labels (21 in total), which looks like this:

```<code>Filename  label1  label2  label3  label4  ...   ID
abc1.jpg    1       0       0       1     ...  id-1
def2.jpg    1       0       0       1     ...  id-2
ghi3.jpg    1       0       0       1     ...  id-3
...
</code>```

I put the the ids and the labels in dictionaries which have the following output:

```<code>partition: {'train': ['id-1','id-2','id-3',...], 'validation': ['id-7','id-14','id-21',...]}
labels:    {'id-0': [1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            'id-1': [1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            'id-2': [1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
             ...}
</code>```

All my images are converted to arrays and saved in single npy files. id-1.npy, id-2.npy...

Then I am executing my code:

```<code>import numpy as np
import keras
from keras.layers import *
from keras.models import Sequential

class DataGenerator(keras.utils.Sequence):
    'Generates data for Keras'
    def __init__(self, list_IDs, labels, batch_size=32, dim=(224,224), n_channels=3,
                 n_classes=21, shuffle=True):
        'Initialization'
        self.dim = dim
        self.batch_size = batch_size
        self.labels = labels
        self.list_IDs = list_IDs
        self.n_channels = n_channels
        self.n_classes = n_classes
        self.shuffle = shuffle
        self.on_epoch_end()

    def __len__(self):
        'Denotes the number of batches per epoch'
        return int(np.floor(len(self.list_IDs) / self.batch_size))

    def __getitem__(self, index):
        'Generate one batch of data'
        # Generate indexes of the batch
        indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]

        # Find list of IDs
        list_IDs_temp = [self.list_IDs[k] for k in indexes]

        # Generate data
        X, y = self.__data_generation(list_IDs_temp)

        return X, y

    def on_epoch_end(self):
        'Updates indexes after each epoch'
        self.indexes = np.arange(len(self.list_IDs))
        if self.shuffle == True:
            np.random.shuffle(self.indexes)

    def __data_generation(self, list_IDs_temp):
        'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)
        # Initialization
        X = np.empty((self.batch_size, *self.dim, self.n_channels))
        y = np.empty((self.batch_size), dtype=int)

        # Generate data
        for i, ID in enumerate(list_IDs_temp):
            # Store sample
            X[i,] = np.load('Folder with npy files/' + ID + '.npy')

            # Store class
            y[i] = self.labels[ID]

        return X, keras.utils.to_categorical(y, num_classes=self.n_classes)
</code>```

```<code># Parameters
params = {'dim': (224, 224),
          'batch_size': 32,
          'n_classes': 21,
          'n_channels': 3,
          'shuffle': True}

# Datasets
partition = partition
labels = labels

# Generators
training_generator = DataGenerator(partition['train'], labels, **params)
validation_generator = DataGenerator(partition['validation'], labels, **params)

# Design model
model = Sequential()

model.add(Conv2D(32, (3,3), input_shape=(224, 224, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

...

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dense(21))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

# Train model on dataset
model.fit_generator(generator=training_generator,
                    validation_data=validation_generator)
</code>```

and the following Error raises:
ValueError: setting an array element with a sequence

the following part of the error seems to be crucial:

```<code><ipython-input-58-fedc63607310> in __getitem__(self, index)
     31
     32         # Generate data
---> 33         X, y = self.__data_generation(list_IDs_temp)
     34
     35         return X, y

<ipython-input-58-fedc63607310> in __data_generation(self, list_IDs_temp)
     53
     54             # Store class
---> 55             y[i] = self.labels[ID]
     56
     57         return X, keras.utils.to_categorical(y, num_classes=self.n_classes)
</code>```

as soon as i replace labels from the beginning with the following, the code gets executed:

```<code>labels = {'id-0': 0,
          'id-1': 2,
          'id-2': 1,
          ...}
</code>```

I still want to pass multiple labels to the DataGenerator, therefore I chose to put a list in the dictionary, as shown in the beginning, but this gives me the ValueError. How can I anyway pass multiple values for a single ID to the DataGenerator as suggested? What do I have to adjust?
A hint or a snippet of code I appreciate a lot.

答:
If i understand well your code here is the problem :

```<code>y = np.empty((self.batch_size), dtype=int)
</code>```

You are creating an emty 1D array, but here :

```<code>y[i] = self.labels[ID]
</code>```

You are filling it with a sequence :

```<code>'id-0': [1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
</code>```

In order to work you need to create your label array with the shape of your batch_size and the lenght of your sequence :

```<code>y = np.empty((self.batch_size, len(sequence)), dtype=int)
</code>```

EDIT

to_categorical is to encode categorical feature to be arrays like  [0, 0, 0, 1], [0, 0, 1, 0], etc But you are feeding sequences, not categorical features.

By feeding sequences to your network, you don't want to one_hot encode it so replace :

```<code>return X, keras.utils.to_categorical(y, num_classes=self.n_classes)
</code>```

by :

```<code>return X, y
</code>```

Recommendation from last comment

The problem is that your Softmax activation will try to give the best score to the correct class, but here you give sequence array that softmax will interpret with multiple "correct class" :

For exemple : if you have 3 labels [1, 2, 3], by one_hot encoding you will have [1, 0, 0], [0, 1, 0], [0, 0, 1], there is only one "1" per encoded label array, one correct class, softmax will try to get this class score bigger as possible.

But in you case your are giving arrays with multiple "1's" :
with that : [1, 0, 1] softmax don't know to which class give the best score.

So i would recommand that, you start with your 21 labels [0,1,2,3, ..] and then you one_hot encode this array and you give it to your network.

If you really need that sequence, you have to find an other solution !

Hope i'm clear !

Body:
I am working on a keras multilabel problem. In order to work with big amount of data to avoid memory issues, I implemented a custom data generator.

So far I work with a csv file with IDs, Filenames and their corresponding labels (21 in total), which looks like this:

Filename  label1  label2  label3  label4  ...   ID
abc1.jpg    1       0       0       1     ...  id-1
def2.jpg    1       0       0       1     ...  id-2
ghi3.jpg    1       0       0       1     ...  id-3
...

I put the the ids and the labels in dictionaries which have the following output:

partition: {'train': ['id-1','id-2','id-3',...], 'validation': ['id-7','id-14','id-21',...]}
labels:    {'id-0': [1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            'id-1': [1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            'id-2': [1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
             ...}

All my images are converted to arrays and saved in single npy files. id-1.npy, id-2.npy...

Then I am executing my code:

import numpy as np
import keras
from keras.layers import *
from keras.models import Sequential

class DataGenerator(keras.utils.Sequence):
    'Generates data for Keras'
    def __init__(self, list_IDs, labels, batch_size=32, dim=(224,224), n_channels=3,
                 n_classes=21, shuffle=True):
        'Initialization'
        self.dim = dim
        self.batch_size = batch_size
        self.labels = labels
        self.list_IDs = list_IDs
        self.n_channels = n_channels
        self.n_classes = n_classes
        self.shuffle = shuffle
        self.on_epoch_end()

    def __len__(self):
        'Denotes the number of batches per epoch'
        return int(np.floor(len(self.list_IDs) / self.batch_size))

    def __getitem__(self, index):
        'Generate one batch of data'
        # Generate indexes of the batch
        indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]

        # Find list of IDs
        list_IDs_temp = [self.list_IDs[k] for k in indexes]

        # Generate data
        X, y = self.__data_generation(list_IDs_temp)

        return X, y

    def on_epoch_end(self):
        'Updates indexes after each epoch'
        self.indexes = np.arange(len(self.list_IDs))
        if self.shuffle == True:
            np.random.shuffle(self.indexes)

    def __data_generation(self, list_IDs_temp):
        'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)
        # Initialization
        X = np.empty((self.batch_size, *self.dim, self.n_channels))
        y = np.empty((self.batch_size), dtype=int)

        # Generate data
        for i, ID in enumerate(list_IDs_temp):
            # Store sample
            X[i,] = np.load('Folder with npy files/' + ID + '.npy')

            # Store class
            y[i] = self.labels[ID]

        return X, keras.utils.to_categorical(y, num_classes=self.n_classes)

# Parameters
params = {'dim': (224, 224),
          'batch_size': 32,
          'n_classes': 21,
          'n_channels': 3,
          'shuffle': True}

# Datasets
partition = partition
labels = labels

# Generators
training_generator = DataGenerator(partition['train'], labels, **params)
validation_generator = DataGenerator(partition['validation'], labels, **params)

# Design model
model = Sequential()

model.add(Conv2D(32, (3,3), input_shape=(224, 224, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

...

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dense(21))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

# Train model on dataset
model.fit_generator(generator=training_generator,
                    validation_data=validation_generator)

and the following Error raises:
ValueError: setting an array element with a sequence

the following part of the error seems to be crucial:

<ipython-input-58-fedc63607310> in __getitem__(self, index)
     31
     32         # Generate data
---> 33         X, y = self.__data_generation(list_IDs_temp)
     34
     35         return X, y

<ipython-input-58-fedc63607310> in __data_generation(self, list_IDs_temp)
     53
     54             # Store class
---> 55             y[i] = self.labels[ID]
     56
     57         return X, keras.utils.to_categorical(y, num_classes=self.n_classes)

as soon as i replace labels from the beginning with the following, the code gets executed:

labels = {'id-0': 0,
          'id-1': 2,
          'id-2': 1,
          ...}

I still want to pass multiple labels to the DataGenerator, therefore I chose to put a list in the dictionary, as shown in the beginning, but this gives me the ValueError. How can I anyway pass multiple values for a single ID to the DataGenerator as suggested? What do I have to adjust?
A hint or a snippet of code I appreciate a lot.

Body:
If i understand well your code here is the problem :

y = np.empty((self.batch_size), dtype=int)

You are creating an emty 1D array, but here :

y[i] = self.labels[ID]

You are filling it with a sequence :

'id-0': [1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]

In order to work you need to create your label array with the shape of your batch_size and the lenght of your sequence :

y = np.empty((self.batch_size, len(sequence)), dtype=int)

EDIT

to_categorical is to encode categorical feature to be arrays like  [0, 0, 0, 1], [0, 0, 1, 0], etc But you are feeding sequences, not categorical features.

By feeding sequences to your network, you don't want to one_hot encode it so replace :

return X, keras.utils.to_categorical(y, num_classes=self.n_classes)

by :

return X, y

Recommendation from last comment

The problem is that your Softmax activation will try to give the best score to the correct class, but here you give sequence array that softmax will interpret with multiple "correct class" :

For exemple : if you have 3 labels [1, 2, 3], by one_hot encoding you will have [1, 0, 0], [0, 1, 0], [0, 0, 1], there is only one "1" per encoded label array, one correct class, softmax will try to get this class score bigger as possible.

But in you case your are giving arrays with multiple "1's" :
with that : [1, 0, 1] softmax don't know to which class give the best score.

So i would recommand that, you start with your 21 labels [0,1,2,3, ..] and then you one_hot encode this array and you give it to your network.

If you really need that sequence, you have to find an other solution !

Hope i'm clear !


问:
Closest spatial position from Lat and Long
I have an application that uses the DotSpatial framework to connect to a usb GPS on my laptop. I essentially use it when driving out on site to know where I am.

The application also includes a ShapeFile map as background so that I know where I am.

What I have is:

I have a database with each road devided into 5m increments with a lat.long location and a road name. (So Col 1 = UniqueID, Col 2 = Location Distance in m (I.e. 0, 5, 10 ...), Col 3 = Road Name, Col 4 = Lat, Col 5 = Long)

The database is SQLite and have one that I created in Access as well.

The full DotSpatial framework

What I need to do is the following:

Work out based on my current lat/long (which I get from the GPS receiver and the GPS.NET part of the software) what the nearest Location Distance in m is from the lat/long locations in the database.

If there are any other suggestions please let me know.

P.S the application needs to be portable so dont want to mess around with SQL Server or PostgrSQL with posGIS etc.

答:
You need the element in your table where the distance (pythagoras) to your point is closest.

```<code>select top 1 * from mytable
order by ( (table.lon - lon) * (table.lon - lon) + (table.lat - lat) * (table.lat - lat) )
</code>```

Lon&Lat: position you're at. Skipping the sqrt will speed things up quite a bit too.

Body:
You need the element in your table where the distance (pythagoras) to your point is closest.

select top 1 * from mytable
order by ( (table.lon - lon) * (table.lon - lon) + (table.lat - lat) * (table.lat - lat) )

Lon&Lat: position you're at. Skipping the sqrt will speed things up quite a bit too.


问:
Java constructor keywordS meaning
I'm an IT student and I've been trying to program since ever... tho there are still many things and concepts I really can't understand after all this time.
One of the most basic one is Java (since I should study that mostly) constructors.

Like ok, I get that a class is a blueprint and we use constructors to make an object and assign values to the class variables, but what how the hell does it work?

```<code>ExampleClass exampleClassObject = new ExampleClass()
</code>```

Ok so, of course I tried already to look for an answer for this but I guess it's too stupid to even explain it...

There are 4 keywords, right?

ExampleClass - is the class we want to make an object of

exampleClassObject - is the object name

= new - I actually don't know exactly what it does

ExampleClass() - THIS. This freaking thing.. what does it do? What's his purpose? Aren't we already telling Java to make an object of ExampleClass with the first keyword?

I think it's the type of our exampleClassObject, but... why do you need to specify that? And if you can change the type of object (as I've seen in other code) whats the point of it??
Making an object of ClassX but of type ClassY... I really don't understand, sorry, and that's just the tip of the iceberg :')

Thank you for your help.

EDIT 1
Thanks for the immediate replies! But..

@Michael

List<String> list = new ArrayList<>(); list = new LinkedList<>();

What's the point of this.. why not making a LinkedList right away? And why making a new object from an already existing object?

I feel like the dude from "1kg of steel vs 1kg of feathers"... I don't get it, thanks so much for the effort lol

EDIT 2
To those downvoting, it's not that I didn't look enough online or at the documentation, it's that I don't understand it :) StackOverflow was my last resource, I wouldn't have asked otherwise...

Thanks again for your help.

答:
There are 4 keywords, right?

This is not accurate. A keyword is a specific thing. In your case, only new is a keyword.

You mean that there are 4 tokens; 4 distinct items for a parser to interpret.

ExampleClass() - THIS. This freaking thing.. what does it do? What's
  his purpose? Aren't we already telling Java to make an object of
  ExampleClass with the first keyword?

You are right, to some degree. There is a kind of declaration redundancy in this particular case. This is one of the reasons people sometimes say that Java is verbose.

In C++ you can do something like this, which contains less repetition

```<code>ExampleClass exampleClassObject;
ExampleClass exampleClassObject(12);
</code>```

In Java the equivalent would be

```<code>ExampleClass exampleClassObject = new ExampleClass();
ExampleClass exampleClassObject = new ExampleClass(12);
</code>```

The reason why this is not completely redundant in Java is because you are specifying the type of the variable separately from the type of the instance which the variable initially holds.

For example

```<code>List<String> list = new ArrayList<>();
list.addAll(getSomeItems());
// some operations for a which an array-based list is most efficient
// ...

list = new LinkedList<>();
list.addAll(getSomeDifferentItems());
// some operations for a which a linked list is most efficient
// ...
</code>```

In this case, the type of the variable is more permissive than the type of the instance which it initially holds. This allows us to depend more upon the abstraction than on one specific implementation, and to potentially re-assign a different implementation later.

In more recent versions of Java, we can use var (a reserved type name) to reduce the duplication. In this case, the type of the variable is inferred from the type it is initialized with, so we don't have to write it twice.

```<code>var myclass = new ExampleClass();
</code>```

Title: Java constructor keywordS meaning

Body:
I'm an IT student and I've been trying to program since ever... tho there are still many things and concepts I really can't understand after all this time.
One of the most basic one is Java (since I should study that mostly) constructors.

Like ok, I get that a class is a blueprint and we use constructors to make an object and assign values to the class variables, but what how the hell does it work?

ExampleClass exampleClassObject = new ExampleClass()

Ok so, of course I tried already to look for an answer for this but I guess it's too stupid to even explain it...

There are 4 keywords, right?

ExampleClass - is the class we want to make an object of

exampleClassObject - is the object name

= new - I actually don't know exactly what it does

ExampleClass() - THIS. This freaking thing.. what does it do? What's his purpose? Aren't we already telling Java to make an object of ExampleClass with the first keyword?

I think it's the type of our exampleClassObject, but... why do you need to specify that? And if you can change the type of object (as I've seen in other code) whats the point of it??
Making an object of ClassX but of type ClassY... I really don't understand, sorry, and that's just the tip of the iceberg :')

Thank you for your help.

EDIT 1
Thanks for the immediate replies! But..

@Michael

List<String> list = new ArrayList<>(); list = new LinkedList<>();

What's the point of this.. why not making a LinkedList right away? And why making a new object from an already existing object?

I feel like the dude from "1kg of steel vs 1kg of feathers"... I don't get it, thanks so much for the effort lol

EDIT 2
To those downvoting, it's not that I didn't look enough online or at the documentation, it's that I don't understand it :) StackOverflow was my last resource, I wouldn't have asked otherwise...

Thanks again for your help.

Body:
There are 4 keywords, right?

This is not accurate. A keyword is a specific thing. In your case, only new is a keyword.

You mean that there are 4 tokens; 4 distinct items for a parser to interpret.

ExampleClass() - THIS. This freaking thing.. what does it do? What's
  his purpose? Aren't we already telling Java to make an object of
  ExampleClass with the first keyword?

You are right, to some degree. There is a kind of declaration redundancy in this particular case. This is one of the reasons people sometimes say that Java is verbose.

In C++ you can do something like this, which contains less repetition

ExampleClass exampleClassObject;
ExampleClass exampleClassObject(12);

In Java the equivalent would be

ExampleClass exampleClassObject = new ExampleClass();
ExampleClass exampleClassObject = new ExampleClass(12);

The reason why this is not completely redundant in Java is because you are specifying the type of the variable separately from the type of the instance which the variable initially holds.

For example

List<String> list = new ArrayList<>();
list.addAll(getSomeItems());
// some operations for a which an array-based list is most efficient
// ...

list = new LinkedList<>();
list.addAll(getSomeDifferentItems());
// some operations for a which a linked list is most efficient
// ...

In this case, the type of the variable is more permissive than the type of the instance which it initially holds. This allows us to depend more upon the abstraction than on one specific implementation, and to potentially re-assign a different implementation later.

In more recent versions of Java, we can use var (a reserved type name) to reduce the duplication. In this case, the type of the variable is inferred from the type it is initialized with, so we don't have to write it twice.

var myclass = new ExampleClass();


问:
How to reference existing image added earlier for header
How do I add an entry to an existing relationshipid for an image that is already added in another part?

For example : I have a Word document with a Header and Footer. I add an image, say A.gif, to the header using the code headerPart.AddImagePart(ImagePartType) and then call FeedData on it with a stream.

Now I want the same image to be displayed in the footer too, but without adding a duplicate entry of the same image and instead, referencing the same image that was added earlier for the header.

How do I add an entry to the footer.xml.rels file to reference the same relationShipId that exists for header?

答:
Below is the code to: 1) add a new image part, and 2) return an id to the added image:

ImagePart imagePart = addImagePart(partType, existingRelationShipId);
using (FileStream stream = new FileStream(imageFilePath, FileMode.Open))
{
 imagePart.FeedData(stream);
}
headerPart= currentPart;
return headerPart.GetIdOfPart(imagePart);```
</div>
</div>
</p>

<p>To add only a reference to an already existing image, use the id obtained earlier (above):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>var extPart = headerPart.GetPartById(existingRelationShipId);
footerPart.AddPart(extPart, existingRelationShipId);</code>```

Body:
Below is the code to: 1) add a new image part, and 2) return an id to the added image:

ImagePart imagePart = addImagePart(partType, existingRelationShipId);
using (FileStream stream = new FileStream(imageFilePath, FileMode.Open))
{
 imagePart.FeedData(stream);
}
headerPart= currentPart;
return headerPart.GetIdOfPart(imagePart);

To add only a reference to an already existing image, use the id obtained earlier (above):

var extPart = headerPart.GetPartById(existingRelationShipId);
footerPart.AddPart(extPart, existingRelationShipId);


问:
Font is doubled when creating pdf from html
I am building a web application with node.js that should create a pdf from a given HTML snippet.

For this I am using the html-pdf package. Everything works fine except for one bold font. When using this font with a font weight of 900, it looks like the font is doubled with an offset. You can see the effect in the picture (especially at the "3").

My CSS Code looks like this:

```<code>@font-face {
    font-family: 'Proxima Nova Condensed';
    src: url("/fonts/ProximaNovaCond-Regular.ttf") format("truetype");
    font-weight: 400;
}
@font-face {
    font-family: 'Proxima Nova Condensed';
    src: url("/fonts/ProximaNovaCond-Bold.ttf") format("truetype");
    font-weight: 700;
}
@font-face {
    font-family: 'Proxima Nova Condensed';
    src: url("/fonts/ProximaNovaCond-Extrabold.ttf") format("truetype");
    font-weight: 800;
}
@font-face {
    font-family: 'Proxima Nova Condensed';
    src: url("/fonts/ProximaNovaCond-Black.ttf") format("truetype");
    font-weight: 900;
}
</code>```

In the web application this works but when generating the pdf I am getting this problem.

Can anyone help me with this?

答:
can you try to add font-style ?

https://www.w3schools.com/cssref/pr_font_font-style.asp

Body:
I am building a web application with node.js that should create a pdf from a given HTML snippet.

For this I am using the html-pdf package. Everything works fine except for one bold font. When using this font with a font weight of 900, it looks like the font is doubled with an offset. You can see the effect in the picture (especially at the "3").

My CSS Code looks like this:

@font-face {
    font-family: 'Proxima Nova Condensed';
    src: url("/fonts/ProximaNovaCond-Regular.ttf") format("truetype");
    font-weight: 400;
}
@font-face {
    font-family: 'Proxima Nova Condensed';
    src: url("/fonts/ProximaNovaCond-Bold.ttf") format("truetype");
    font-weight: 700;
}
@font-face {
    font-family: 'Proxima Nova Condensed';
    src: url("/fonts/ProximaNovaCond-Extrabold.ttf") format("truetype");
    font-weight: 800;
}
@font-face {
    font-family: 'Proxima Nova Condensed';
    src: url("/fonts/ProximaNovaCond-Black.ttf") format("truetype");
    font-weight: 900;
}

In the web application this works but when generating the pdf I am getting this problem.

Can anyone help me with this?


问:
List of List C# question or something else any pointers in coding this
I need some help in coding this in C#

I have a list of Baskets and their Global_Weights in overall Basket in Kilograms:

Basket1, Basket2, Basket3, Basket4

0.1, 0.3, 0.9,0.6

Each of the Basket consist of the following thing:

Name,Level1, level2,Local_Weights

Name: String type

Level1:Double Type

Level2:Double Type

Local_Weights:Double Type

Each Basket will consist of N number of (Name,Level1, level2,Local_Weights) and there are M Baskets
N and M are variable which will be user Input

Should I be using List of list for this or something else any pointer on how to go about coding this?

How will I be accessing the members inside each of the Basket and perform calculation on them.

答:
You would use a class Basket that contains a list of objects of the class BasketInfo and create a list of that Basket class:

```<code>class Basket
{
    public Basket()
    {
        BasketInfos = new List<BasketInfo>();
    }

    public double GlobalWeight
    {
        get
        {
            return BasketInfos.Sum(x => x.LocalWeight);
        }
    }

    public IList<BasketInfo> BasketInfos { get; set; }
}

class BasketInfo
{
    public string Name { get; set; }
    public double Level1 { get; set; }
    public double Level2 { get; set; }
    public double LocalWeight { get; set; }
}

var baskets = new List<Basket>();
</code>```

Body:
You would use a class Basket that contains a list of objects of the class BasketInfo and create a list of that Basket class:

class Basket
{
    public Basket()
    {
        BasketInfos = new List<BasketInfo>();
    }

    public double GlobalWeight
    {
        get
        {
            return BasketInfos.Sum(x => x.LocalWeight);
        }
    }

    public IList<BasketInfo> BasketInfos { get; set; }
}

class BasketInfo
{
    public string Name { get; set; }
    public double Level1 { get; set; }
    public double Level2 { get; set; }
    public double LocalWeight { get; set; }
}

var baskets = new List<Basket>();


问:
How can I setup StaticResourceExtension when unit testing a markup extension that relies on it?
I have written a custom markup extension : CoalesceResourceExtension

```<code>[MarkupExtensionReturnType(typeof(object))]
public class CoalesceResourceExtension : MarkupExtension
{
    public CoalesceResourceExtension(string resources)
    {
        this.Resources = resources;
    }

    public string Separator { get; set; }

    [ConstructorArgument("resources")]
    public string Resources { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (Resources != null)
        {
            foreach (string resourceName in Resources.Split(new[] { Separator }, StringSplitOptions.RemoveEmptyEntries))
            {
                try
                {
                    if (new StaticResourceExtension(resourceName).ProvideValue(serviceProvider) is object resource)
                    {
                        return resource;
                    }
                }
                catch { }
            }
        }

        return null;
    }
}
</code>```

But when I come to unit testing CoalesceResourceExtension, I can't seem to find a way to setup the StaticResourceExtension so that it will find the desired mocked resources. Is there a way I can setup things for the StaticResourceExtension to find my mocked resources?

答:
StaticResourceExtension.ProvideValue(IServiceProvider)'s behaviour can be controlled via mocking the IServiceProvider passed by CoalesceResourceExtension to the StaticResourceExtension but you'll also need to mock all the services and objects from the services it uses : IAmbientProvider, IXamlSchemaContextProvider, XamlSchemaContext, ResourceDictionary, XamlType, PropertyInfo and XamlMember. I've built these mocks by watching what path the StaticResourceExtension was taking by both making the mocks strict and watching the exceptions they were throwing when meeting a member that wasn't setup and by looking at StaticResourceExtension's source code.

Here's a method that builds the whole mocked IServiceProvider for every needed key + value pair passed in :

```<code>private IServiceProvider MockIServiceProviderForStaticResourceExtension(params KeyValuePair<object, object>[] resources)
{
    Mock<IServiceProvider> serviceProviderMock = new Mock<IServiceProvider>(MockBehavior.Strict);
    Mock<IXamlSchemaContextProvider> xamlSchemaContextProviderMock = new Mock<IXamlSchemaContextProvider>(MockBehavior.Strict);
    Mock<IAmbientProvider> ambientProviderMock = new Mock<IAmbientProvider>(MockBehavior.Strict);
    Mock<XamlSchemaContext> xamlSchemaContextMock = new Mock<XamlSchemaContext>(MockBehavior.Strict);
    xamlSchemaContextMock.Setup(xsc => xsc.GetXamlType(It.IsAny<Type>())).Returns((Func<Type, XamlType>)(t => GetXamlTypeForType(t, xamlSchemaContextMock.Object)));
    ambientProviderMock.Setup(ap => ap.GetAllAmbientValues(null, false, It.IsAny<IEnumerable<XamlType>>(), It.IsAny<XamlMember[]>())).Returns((Func<IEnumerable<XamlType>, bool, IEnumerable<XamlType>, XamlMember[], IEnumerable<AmbientPropertyValue>>)GetAllAmbientValuesImplementation);
    xamlSchemaContextProviderMock.Setup(xscp => xscp.SchemaContext).Returns(xamlSchemaContextMock.Object);
    serviceProviderMock.Setup(s => s.GetService(typeof(IXamlSchemaContextProvider))).Returns(xamlSchemaContextProviderMock.Object);
    serviceProviderMock.Setup(s => s.GetService(typeof(IAmbientProvider))).Returns(ambientProviderMock.Object);
    serviceProviderMock.Setup(s => s.GetService(It.IsNotIn(typeof(IXamlSchemaContextProvider), typeof(IAmbientProvider)))).Returns(null);

    return serviceProviderMock.Object;

    IEnumerable<AmbientPropertyValue> GetAllAmbientValuesImplementation(IEnumerable<XamlType> ceilingTypes, bool searchLiveStackOnly, IEnumerable<XamlType> types, params XamlMember[] properties)
    {
        Mock<ResourceDictionary> resourceDictionaryMock = new Mock<ResourceDictionary>(MockBehavior.Strict);
        resourceDictionaryMock.Protected().Setup("OnGettingValue", false, ItExpr.Is<object>(o => resources.Any(kvp => kvp.Key.Equals(o))), ItExpr.Ref<object>.IsAny, ItExpr.Ref<bool>.IsAny).CallBase();
        foreach (KeyValuePair<object, object> kvp in resources)
        {
            resourceDictionaryMock.Object.Add(kvp.Key, kvp.Value);
        }

        Mock<AmbientPropertyValue> ambientPropertyValueMock = new Mock<AmbientPropertyValue>(MockBehavior.Strict, null, resourceDictionaryMock.Object);
        return new List<AmbientPropertyValue> { ambientPropertyValueMock.Object };
    }

    XamlType GetXamlTypeForType(Type t, XamlSchemaContext xamlSchemaContext)
    {
        Mock<XamlType> xamlTypeMock = new Mock<XamlType>(MockBehavior.Strict, t, xamlSchemaContext);
        xamlTypeMock.Protected().Setup<XamlMember>("LookupMember", true, "Resources", false).Returns((Func<string, bool, XamlMember>)LookupMemberImplementation);
        xamlTypeMock.Protected().Setup<XamlMember>("LookupMember", true, "BasedOn", false).Returns((Func<string, bool, XamlMember>)LookupMemberImplementation);
        xamlTypeMock.Setup(xt => xt.ToString()).CallBase();
        return xamlTypeMock.Object;

        XamlMember LookupMemberImplementation(string name, bool skipReadOnlyCheck)
        {
            Mock<PropertyInfo> propertyInfoMock = new Mock<PropertyInfo>(MockBehavior.Strict);
            propertyInfoMock.Setup(pi => pi.Name).Returns(name);
            propertyInfoMock.Setup(pi => pi.DeclaringType).Returns(t);
            Mock<XamlMember> xamlMemberMock = new Mock<XamlMember>(MockBehavior.Strict, propertyInfoMock.Object, xamlSchemaContext);
            xamlMemberMock.Setup(xm => xm.ToString()).CallBase();
            return xamlMemberMock.Object;
        }
    }
}
</code>```

Body:
I have written a custom markup extension : CoalesceResourceExtension

[MarkupExtensionReturnType(typeof(object))]
public class CoalesceResourceExtension : MarkupExtension
{
    public CoalesceResourceExtension(string resources)
    {
        this.Resources = resources;
    }

    public string Separator { get; set; }

    [ConstructorArgument("resources")]
    public string Resources { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (Resources != null)
        {
            foreach (string resourceName in Resources.Split(new[] { Separator }, StringSplitOptions.RemoveEmptyEntries))
            {
                try
                {
                    if (new StaticResourceExtension(resourceName).ProvideValue(serviceProvider) is object resource)
                    {
                        return resource;
                    }
                }
                catch { }
            }
        }

        return null;
    }
}

But when I come to unit testing CoalesceResourceExtension, I can't seem to find a way to setup the StaticResourceExtension so that it will find the desired mocked resources. Is there a way I can setup things for the StaticResourceExtension to find my mocked resources?

Body:
StaticResourceExtension.ProvideValue(IServiceProvider)'s behaviour can be controlled via mocking the IServiceProvider passed by CoalesceResourceExtension to the StaticResourceExtension but you'll also need to mock all the services and objects from the services it uses : IAmbientProvider, IXamlSchemaContextProvider, XamlSchemaContext, ResourceDictionary, XamlType, PropertyInfo and XamlMember. I've built these mocks by watching what path the StaticResourceExtension was taking by both making the mocks strict and watching the exceptions they were throwing when meeting a member that wasn't setup and by looking at StaticResourceExtension's source code.

Here's a method that builds the whole mocked IServiceProvider for every needed key + value pair passed in :

private IServiceProvider MockIServiceProviderForStaticResourceExtension(params KeyValuePair<object, object>[] resources)
{
    Mock<IServiceProvider> serviceProviderMock = new Mock<IServiceProvider>(MockBehavior.Strict);
    Mock<IXamlSchemaContextProvider> xamlSchemaContextProviderMock = new Mock<IXamlSchemaContextProvider>(MockBehavior.Strict);
    Mock<IAmbientProvider> ambientProviderMock = new Mock<IAmbientProvider>(MockBehavior.Strict);
    Mock<XamlSchemaContext> xamlSchemaContextMock = new Mock<XamlSchemaContext>(MockBehavior.Strict);
    xamlSchemaContextMock.Setup(xsc => xsc.GetXamlType(It.IsAny<Type>())).Returns((Func<Type, XamlType>)(t => GetXamlTypeForType(t, xamlSchemaContextMock.Object)));
    ambientProviderMock.Setup(ap => ap.GetAllAmbientValues(null, false, It.IsAny<IEnumerable<XamlType>>(), It.IsAny<XamlMember[]>())).Returns((Func<IEnumerable<XamlType>, bool, IEnumerable<XamlType>, XamlMember[], IEnumerable<AmbientPropertyValue>>)GetAllAmbientValuesImplementation);
    xamlSchemaContextProviderMock.Setup(xscp => xscp.SchemaContext).Returns(xamlSchemaContextMock.Object);
    serviceProviderMock.Setup(s => s.GetService(typeof(IXamlSchemaContextProvider))).Returns(xamlSchemaContextProviderMock.Object);
    serviceProviderMock.Setup(s => s.GetService(typeof(IAmbientProvider))).Returns(ambientProviderMock.Object);
    serviceProviderMock.Setup(s => s.GetService(It.IsNotIn(typeof(IXamlSchemaContextProvider), typeof(IAmbientProvider)))).Returns(null);

    return serviceProviderMock.Object;

    IEnumerable<AmbientPropertyValue> GetAllAmbientValuesImplementation(IEnumerable<XamlType> ceilingTypes, bool searchLiveStackOnly, IEnumerable<XamlType> types, params XamlMember[] properties)
    {
        Mock<ResourceDictionary> resourceDictionaryMock = new Mock<ResourceDictionary>(MockBehavior.Strict);
        resourceDictionaryMock.Protected().Setup("OnGettingValue", false, ItExpr.Is<object>(o => resources.Any(kvp => kvp.Key.Equals(o))), ItExpr.Ref<object>.IsAny, ItExpr.Ref<bool>.IsAny).CallBase();
        foreach (KeyValuePair<object, object> kvp in resources)
        {
            resourceDictionaryMock.Object.Add(kvp.Key, kvp.Value);
        }

        Mock<AmbientPropertyValue> ambientPropertyValueMock = new Mock<AmbientPropertyValue>(MockBehavior.Strict, null, resourceDictionaryMock.Object);
        return new List<AmbientPropertyValue> { ambientPropertyValueMock.Object };
    }

    XamlType GetXamlTypeForType(Type t, XamlSchemaContext xamlSchemaContext)
    {
        Mock<XamlType> xamlTypeMock = new Mock<XamlType>(MockBehavior.Strict, t, xamlSchemaContext);
        xamlTypeMock.Protected().Setup<XamlMember>("LookupMember", true, "Resources", false).Returns((Func<string, bool, XamlMember>)LookupMemberImplementation);
        xamlTypeMock.Protected().Setup<XamlMember>("LookupMember", true, "BasedOn", false).Returns((Func<string, bool, XamlMember>)LookupMemberImplementation);
        xamlTypeMock.Setup(xt => xt.ToString()).CallBase();
        return xamlTypeMock.Object;

        XamlMember LookupMemberImplementation(string name, bool skipReadOnlyCheck)
        {
            Mock<PropertyInfo> propertyInfoMock = new Mock<PropertyInfo>(MockBehavior.Strict);
            propertyInfoMock.Setup(pi => pi.Name).Returns(name);
            propertyInfoMock.Setup(pi => pi.DeclaringType).Returns(t);
            Mock<XamlMember> xamlMemberMock = new Mock<XamlMember>(MockBehavior.Strict, propertyInfoMock.Object, xamlSchemaContext);
            xamlMemberMock.Setup(xm => xm.ToString()).CallBase();
            return xamlMemberMock.Object;
        }
    }
}


问:
Ingress controller NodePort not reachable from outside
I have a cluster of 3 vm on which I install kubernetes and deployed some pods and services that I would like to be accessible from outside (my local pc for exemple)

I followed this tutorial https://kubernetes.github.io/ingress-nginx/deploy/#bare-metal to install my ingress controller.
I have created a service of type NodePort.
I have created a ingress that looks like this:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-ingress
  annotations:
      kubernetes.io/ingress.class: nginx
spec:
  rules:
  - host: my.service.com
    http:
      paths:
      - path: /
        backend:
          serviceName: myservice
          servicePort: 9090
</code>```

kubectl get svc myservice gives me:

```<code>NAME        TYPE       CLUSTER-IP        EXTERNAL-IP   PORT(S)          AGE
myservice   NodePort   xxx.xxx.xxx.xxx   <none>        9090:31220/TCP   47m
</code>```

kubectl get ingress test-ingress gives me

```<code>NAME            HOSTS            ADDRESS          PORTS   AGE
test-ingress    my.service.com   xx.xxx.xxx.xxx   80      49m
</code>```

On my local computer I have added to /etc/hosts I have mapped the ip address of the ingress to the name my.service.com
When I try to ping my.service.com or directly the ip I go request timeout 100% packet loss.
I tried to reach my service visual interface with the web browser and it does not work either.

How can I investigate further why I can't access to my service from outside the cluster ?

答:
There is probably an issue with your firewall. Check the firewall rules if they are blocking access from outside to that port.

Also you should access the service from the NodePort of the service you created while deploying the ingress controller.

Also edit your ingress and add the tls and hosts property with a self signed certificate for my.service.com

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-ingress
  annotations:
      ingress.kubernetes.io/rewrite-target: /
      kubernetes.io/ingress.class: nginx
spec:
  tls:
  - hosts:
    - my.service.com
    secretName: tls-secret-for my service
  rules:
  - host: my.service.com
    http:
      paths:
      - path: /
        backend:
          serviceName: myservice
          servicePort: 9090
</code>```

Body:
I have a cluster of 3 vm on which I install kubernetes and deployed some pods and services that I would like to be accessible from outside (my local pc for exemple)

I followed this tutorial https://kubernetes.github.io/ingress-nginx/deploy/#bare-metal to install my ingress controller.
I have created a service of type NodePort.
I have created a ingress that looks like this:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-ingress
  annotations:
      kubernetes.io/ingress.class: nginx
spec:
  rules:
  - host: my.service.com
    http:
      paths:
      - path: /
        backend:
          serviceName: myservice
          servicePort: 9090

kubectl get svc myservice gives me:

NAME        TYPE       CLUSTER-IP        EXTERNAL-IP   PORT(S)          AGE
myservice   NodePort   xxx.xxx.xxx.xxx   <none>        9090:31220/TCP   47m

kubectl get ingress test-ingress gives me

NAME            HOSTS            ADDRESS          PORTS   AGE
test-ingress    my.service.com   xx.xxx.xxx.xxx   80      49m

On my local computer I have added to /etc/hosts I have mapped the ip address of the ingress to the name my.service.com
When I try to ping my.service.com or directly the ip I go request timeout 100% packet loss.
I tried to reach my service visual interface with the web browser and it does not work either.

How can I investigate further why I can't access to my service from outside the cluster ?

Body:
There is probably an issue with your firewall. Check the firewall rules if they are blocking access from outside to that port.

Also you should access the service from the NodePort of the service you created while deploying the ingress controller.

Also edit your ingress and add the tls and hosts property with a self signed certificate for my.service.com

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-ingress
  annotations:
      ingress.kubernetes.io/rewrite-target: /
      kubernetes.io/ingress.class: nginx
spec:
  tls:
  - hosts:
    - my.service.com
    secretName: tls-secret-for my service
  rules:
  - host: my.service.com
    http:
      paths:
      - path: /
        backend:
          serviceName: myservice
          servicePort: 9090


问:
WP input box shows white background, even though I change to "background-color: none;" (Themify bulider)
Could someone help me with an annoying error?

I want to change the form input fields to transparent background, keeping only the solid line under the field in Themify Bulider with Contact form 7. When I add the custom CSS shown bellow, it still keeps me with the white input boxes, as you can see from: www.creedo.ee.

```<code>.wpcf7 input[type=text]{
   border: none;
   box-shadow: none;
   border-radius: 0;
   border-bottom: 1px solid #999;
   background-color: none;
}
</code>```

Any suggestions? Thank you!

答:
try the following: </p>

```<code>.mdc-text-field {
    background-color: transparent !important;
}
</code>```

Body:
Could someone help me with an annoying error?

I want to change the form input fields to transparent background, keeping only the solid line under the field in Themify Bulider with Contact form 7. When I add the custom CSS shown bellow, it still keeps me with the white input boxes, as you can see from: www.creedo.ee.

.wpcf7 input[type=text]{
   border: none;
   box-shadow: none;
   border-radius: 0;
   border-bottom: 1px solid #999;
   background-color: none;
}

Any suggestions? Thank you!

Body:
try the following:

.mdc-text-field {
    background-color: transparent !important;
}


问:
Getting value from nested map in groovy using a nested key
Suppose I have nested map like this

```<code>def someMap = [
   a : [
      b : [
         c : "value",
         d : "anothervalue"
      ]
   ]
]
</code>```

I get the key at runtime as a string.  Say it is "a.b.c"

How can I pull the value out of the map?

I know I can do myMap.a.b.c but for me, "a.b.c" is single string, I found out about at runtime?

Thanks

答:
You could just go down the nodes likes this and try to get the respective child:</p>

```<code>def key = "a.b.c"
def entry = someMap
key.split('\\.').each { entry = entry?.get(it) }
println entry?.value
</code>```

Body:
Suppose I have nested map like this

def someMap = [
   a : [
      b : [
         c : "value",
         d : "anothervalue"
      ]
   ]
]

I get the key at runtime as a string.  Say it is "a.b.c"

How can I pull the value out of the map?

I know I can do myMap.a.b.c but for me, "a.b.c" is single string, I found out about at runtime?

Thanks

Body:
You could just go down the nodes likes this and try to get the respective child:

def key = "a.b.c"
def entry = someMap
key.split('\\.').each { entry = entry?.get(it) }
println entry?.value


问:
In Mac: An unknown server-side error occurred while processing the command Original error: Could not find adb
While I start new session in APPIUM am getting the below error prompted in appium:

An unknown server-side error occurred while processing the command. Original error: Could not find 'adb' in ["/Library/platform-tools/adb/platform-tools/adb","/Library/platform-tools/adb/emulator/adb","/Library/platform-tools/adb/tools/adb","/Library/platform-tools/adb/tools/bin/adb"]. Do you have Android Build Tools installed at '/Library/platform-tools/adb'?

Is there any solution for MacOs?

答:
Make sure you setup env variable properly.

```<code>nano ~/.bash_profile
</code>```

Set variables making sure the path is correct

```<code>export ANDROID_HOME=/LOCAL_PATH_TO/android-sdk
export PATH=$ANDROID_HOME/platform-tools:$PATH
export PATH=$ANDROID_HOME/tools:$PATH
</code>```

Verify that it is working:

```<code>source ~/.bash_profile
echo $ANDROID_HOME
</code>```

You can also install appium-doctor tool to check you got everything setup for Appium:

```<code>npm install appium-doctor -g
</code>```

Check setup for Android testing

```<code>appium-doctor --android
</code>```

Body:
Make sure you setup env variable properly.

nano ~/.bash_profile

Set variables making sure the path is correct

export ANDROID_HOME=/LOCAL_PATH_TO/android-sdk
export PATH=$ANDROID_HOME/platform-tools:$PATH
export PATH=$ANDROID_HOME/tools:$PATH

Verify that it is working:

source ~/.bash_profile
echo $ANDROID_HOME

You can also install appium-doctor tool to check you got everything setup for Appium:

npm install appium-doctor -g

Check setup for Android testing

appium-doctor --android


问:
How to use Redux-Thunk with Redux Toolkit's createSlice?
I have come across Redux Toolkit (RTK) and wanting to implement further functionality it provides. My application dispatches to reducers slices created via the createSlice({}) (see createSlice api docs)

This so far works brilliantly. I can easily use the built in dispatch(action) and useSelector(selector) to dispatch the actions and receive/react to the state changes well in my components.

I would like to use an async call from axios to fetch data from the API and update the store as the request is A) started B) completed.

I have seen redux-thunk and it seems as though it is designed entirely for this purpose, but the new RTK does not seem to support it within a createSlice() following general googling.

Is the above the current state of implementing thunk with slices?

I have seen in the docs that you can add extraReducers to the slice but unsure if this means I could create more traditional reducers that use thunk and have the slice implement them?

Overall, it is misleading as the RTK docs show you can use thunk, but doesn't seem to mention it not being accessible via the new slices api.

Example from Redux Tool Kit Middleware

```<code>const store = configureStore({
  reducer: rootReducer,
  middleware: [thunk, logger]
})
</code>```

My code for a slice showing where an async call would fail and some other example reducers that do work.

```<code>import { getAxiosInstance } from '../../conf/index';

export const slice = createSlice({
    name: 'bundles',
    initialState: {
        bundles: [],
        selectedBundle: null,
        page: {
            page: 0,
            totalElements: 0,
            size: 20,
            totalPages: 0
        },
        myAsyncResponse: null
    },

    reducers: {
        //Update the state with the new bundles and the Spring Page object.
        recievedBundlesFromAPI: (state, bundles) => {
            console.log('Getting bundles...');
            const springPage = bundles.payload.pageable;
            state.bundles = bundles.payload.content;
            state.page = {
                page: springPage.pageNumber,
                size: springPage.pageSize,
                totalElements: bundles.payload.totalElements,
                totalPages: bundles.payload.totalPages
            };
        },

        //The Bundle selected by the user.
        setSelectedBundle: (state, bundle) => {
            console.log(`Selected ${bundle} `);
            state.selectedBundle = bundle;
        },

        //I WANT TO USE / DO AN ASYNC FUNCTION HERE...THIS FAILS.
        myAsyncInSlice: (state) => {
            getAxiosInstance()
                .get('/')
                .then((ok) => {
                    state.myAsyncResponse = ok.data;
                })
                .catch((err) => {
                    state.myAsyncResponse = 'ERROR';
                });
        }
    }
});

export const selectBundles = (state) => state.bundles.bundles;
export const selectedBundle = (state) => state.bundles.selectBundle;
export const selectPage = (state) => state.bundles.page;
export const { recievedBundlesFromAPI, setSelectedBundle, myAsyncInSlice } = slice.actions;
export default slice.reducer;
</code>```

My store setup (store config).

```<code>import { configureStore } from '@reduxjs/toolkit';
import thunk from 'redux-thunk';

import bundlesReducer from '../slices/bundles-slice';
import servicesReducer from '../slices/services-slice';
import menuReducer from '../slices/menu-slice';
import mySliceReducer from '../slices/my-slice';

const store = configureStore({
    reducer: {
        bundles: bundlesReducer,
        services: servicesReducer,
        menu: menuReducer,
        redirect: mySliceReducer
    }
});
export default store;
</code>```

答:
Use redux-toolkit v1.3.0-alpha.8

Try this

```<code>import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

export const myAsyncInSlice = createAsyncThunk('bundles/myAsyncInSlice', () =>
  getAxiosInstance()
    .get('/')
    .then(ok => ok.data)
    .catch(err => err),
);

const usersSlice = createSlice({
  name: 'bundles',
  initialState: {
    bundles: [],
    selectedBundle: null,
    page: {
      page: 0,
      totalElements: 0,
      size: 20,
      totalPages: 0,
    },
    myAsyncResponse: null,
    myAsyncResponseError: null,
  },
  reducers: {
    // add your non-async reducers here
  },
  extraReducers: {
    // you can mutate state directly, since it is using immer behind the scenes
    [myAsyncInSlice.fulfilled]: (state, action) => {
      state.myAsyncResponse = action.payload;
    },
    [myAsyncInSlice.rejected]: (state, action) => {
      state.myAsyncResponseError = action.payload;
    },
  },
});

</code>```

Body:
I have come across Redux Toolkit (RTK) and wanting to implement further functionality it provides. My application dispatches to reducers slices created via the createSlice({}) (see createSlice api docs)

This so far works brilliantly. I can easily use the built in dispatch(action) and useSelector(selector) to dispatch the actions and receive/react to the state changes well in my components.

I would like to use an async call from axios to fetch data from the API and update the store as the request is A) started B) completed.

I have seen redux-thunk and it seems as though it is designed entirely for this purpose, but the new RTK does not seem to support it within a createSlice() following general googling.

Is the above the current state of implementing thunk with slices?

I have seen in the docs that you can add extraReducers to the slice but unsure if this means I could create more traditional reducers that use thunk and have the slice implement them?

Overall, it is misleading as the RTK docs show you can use thunk, but doesn't seem to mention it not being accessible via the new slices api.

Example from Redux Tool Kit Middleware

const store = configureStore({
  reducer: rootReducer,
  middleware: [thunk, logger]
})

My code for a slice showing where an async call would fail and some other example reducers that do work.

import { getAxiosInstance } from '../../conf/index';

export const slice = createSlice({
    name: 'bundles',
    initialState: {
        bundles: [],
        selectedBundle: null,
        page: {
            page: 0,
            totalElements: 0,
            size: 20,
            totalPages: 0
        },
        myAsyncResponse: null
    },

    reducers: {
        //Update the state with the new bundles and the Spring Page object.
        recievedBundlesFromAPI: (state, bundles) => {
            console.log('Getting bundles...');
            const springPage = bundles.payload.pageable;
            state.bundles = bundles.payload.content;
            state.page = {
                page: springPage.pageNumber,
                size: springPage.pageSize,
                totalElements: bundles.payload.totalElements,
                totalPages: bundles.payload.totalPages
            };
        },

        //The Bundle selected by the user.
        setSelectedBundle: (state, bundle) => {
            console.log(`Selected ${bundle} `);
            state.selectedBundle = bundle;
        },

        //I WANT TO USE / DO AN ASYNC FUNCTION HERE...THIS FAILS.
        myAsyncInSlice: (state) => {
            getAxiosInstance()
                .get('/')
                .then((ok) => {
                    state.myAsyncResponse = ok.data;
                })
                .catch((err) => {
                    state.myAsyncResponse = 'ERROR';
                });
        }
    }
});

export const selectBundles = (state) => state.bundles.bundles;
export const selectedBundle = (state) => state.bundles.selectBundle;
export const selectPage = (state) => state.bundles.page;
export const { recievedBundlesFromAPI, setSelectedBundle, myAsyncInSlice } = slice.actions;
export default slice.reducer;

My store setup (store config).

import { configureStore } from '@reduxjs/toolkit';
import thunk from 'redux-thunk';

import bundlesReducer from '../slices/bundles-slice';
import servicesReducer from '../slices/services-slice';
import menuReducer from '../slices/menu-slice';
import mySliceReducer from '../slices/my-slice';

const store = configureStore({
    reducer: {
        bundles: bundlesReducer,
        services: servicesReducer,
        menu: menuReducer,
        redirect: mySliceReducer
    }
});
export default store;

Body:
Use redux-toolkit v1.3.0-alpha.8

Try this

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';

export const myAsyncInSlice = createAsyncThunk('bundles/myAsyncInSlice', () =>
  getAxiosInstance()
    .get('/')
    .then(ok => ok.data)
    .catch(err => err),
);

const usersSlice = createSlice({
  name: 'bundles',
  initialState: {
    bundles: [],
    selectedBundle: null,
    page: {
      page: 0,
      totalElements: 0,
      size: 20,
      totalPages: 0,
    },
    myAsyncResponse: null,
    myAsyncResponseError: null,
  },
  reducers: {
    // add your non-async reducers here
  },
  extraReducers: {
    // you can mutate state directly, since it is using immer behind the scenes
    [myAsyncInSlice.fulfilled]: (state, action) => {
      state.myAsyncResponse = action.payload;
    },
    [myAsyncInSlice.rejected]: (state, action) => {
      state.myAsyncResponseError = action.payload;
    },
  },
});


问:
Bind to a method in WPF?
How do you bind to an objects method in this scenario in WPF?

public class RootObject
{
    public string Name { get; }

    public ObservableCollection<ChildObject> GetChildren() {...}
}

public class ChildObject
{
    public string Name { get; }
}
```
<p>XAML:</p>
```<TreeView ItemsSource="some list of RootObjects">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type data:RootObject}"
                                  ItemsSource="???">
            <TextBlock Text="{Binding Path=Name}" />
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate DataType="{x:Type data:ChildObject}">
            <TextBlock Text="{Binding Path=Name}" />
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>
```

Here I want to bind to the GetChildren method on each RootObject of the tree.

EDIT Binding to an ObjectDataProvider doesn't seem to work because I'm binding to a list of items, and the ObjectDataProvider needs either a static method, or it creates it's own instance and uses that.

For example, using Matt's answer I get:

System.Windows.Data Error: 33 : ObjectDataProvider cannot create object; Type='RootObject'; Error='Wrong parameters for constructor.'

System.Windows.Data Error: 34 : ObjectDataProvider: Failure trying to invoke method on type; Method='GetChildren'; Type='RootObject'; Error='The specified member cannot be invoked on target.' TargetException:'System.Reflection.TargetException: Non-static method requires a target.

答: ObjectDataProvider also has an ObjectInstance property that can be used instead of ObjectType</p>

OwnerDisplayName: Cameron MacFarland

Title: Bind to a method in WPF?

Body:
How do you bind to an objects method in this scenario in WPF?

public class RootObject
{
    public string Name { get; }

    public ObservableCollection<ChildObject> GetChildren() {...}
}

public class ChildObject
{
    public string Name { get; }
}

XAML:

<TreeView ItemsSource="some list of RootObjects">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type data:RootObject}"
                                  ItemsSource="???">
            <TextBlock Text="{Binding Path=Name}" />
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate DataType="{x:Type data:ChildObject}">
            <TextBlock Text="{Binding Path=Name}" />
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>

Here I want to bind to the GetChildren method on each RootObject of the tree.

EDIT Binding to an ObjectDataProvider doesn't seem to work because I'm binding to a list of items, and the ObjectDataProvider needs either a static method, or it creates it's own instance and uses that.

For example, using Matt's answer I get:

System.Windows.Data Error: 33 : ObjectDataProvider cannot create object; Type='RootObject'; Error='Wrong parameters for constructor.'

System.Windows.Data Error: 34 : ObjectDataProvider: Failure trying to invoke method on type; Method='GetChildren'; Type='RootObject'; Error='The specified member cannot be invoked on target.' TargetException:'System.Reflection.TargetException: Non-static method requires a target.

LastEditorDisplayName: Cameron MacFarland

OwnerDisplayName: Graham Ambrose

ContentLicense: CC BY-SA 2.5


问:
Grouping by and filtering for column value containing string and aggregate function?
How can I group by a couple of columns for only values that contain a string anywhere in that column value?

For example if I want to look at state and theatre name but only look at the count or number of times a title as the word dog anywhere in it how can I group by to filter with that?

```<code>State | Theatre | Title           | TicketPrice
NY       B        Dog in heaven        5.50
NJ       C        Basketball           3.33
NY       B        Cats                 9.00
NY       B        Hair of Dog          44.00
NY       B        Lions                22.00
NJ       C        Dog Land             4.99
</code>```

Grouping by State and Theatre, I want only the count of titles where Dog as a word appears in the Title column and the sum for each grouped by only for titles where Dog appears?

Thanks!

答:
Compare column by Series.str.contains for mask, convert to integers for True->1 and False->0 mapping and count number of 1 by sum:

```<code>df1 = (df.assign(count = df['Title'].str.contains('Dog').astype(int))
        .groupby(['State', 'Theatre'])['count']
        .sum()
        .reset_index())

print (df1)
  State Theatre  count
0    NJ       C      1
1    NY       B      2
</code>```

If want also aggregate sum for TicketPrice column per groups:

```<code>df2 = (df.assign(count = df['Title'].str.contains('Dog').astype(int))
        .groupby(['State', 'Theatre'])['count', 'TicketPrice']
        .sum()
        .reset_index())

print (df2)
  State Theatre  count  TicketPrice
0    NJ       C      1         8.32
1    NY       B      2        80.50
</code>```

Filter rows and then count number of rows, but if filter out groups with no match:

```<code>df1 = (df[df['Title'].str.contains('Dog')]
        .groupby(['State', 'Theatre'])['TicketPrice']
        .size()
        .reset_index(name='count'))

print (df1)
  State Theatre  count
0    NJ       C      1
1    NY       B      2
</code>```

Body:
How can I group by a couple of columns for only values that contain a string anywhere in that column value?

For example if I want to look at state and theatre name but only look at the count or number of times a title as the word dog anywhere in it how can I group by to filter with that?

State | Theatre | Title           | TicketPrice
NY       B        Dog in heaven        5.50
NJ       C        Basketball           3.33
NY       B        Cats                 9.00
NY       B        Hair of Dog          44.00
NY       B        Lions                22.00
NJ       C        Dog Land             4.99

Grouping by State and Theatre, I want only the count of titles where Dog as a word appears in the Title column and the sum for each grouped by only for titles where Dog appears?

Thanks!

Body:
Compare column by Series.str.contains for mask, convert to integers for True->1 and False->0 mapping and count number of 1 by sum:

df1 = (df.assign(count = df['Title'].str.contains('Dog').astype(int))
        .groupby(['State', 'Theatre'])['count']
        .sum()
        .reset_index())

print (df1)
  State Theatre  count
0    NJ       C      1
1    NY       B      2

If want also aggregate sum for TicketPrice column per groups:

df2 = (df.assign(count = df['Title'].str.contains('Dog').astype(int))
        .groupby(['State', 'Theatre'])['count', 'TicketPrice']
        .sum()
        .reset_index())

print (df2)
  State Theatre  count  TicketPrice
0    NJ       C      1         8.32
1    NY       B      2        80.50

Filter rows and then count number of rows, but if filter out groups with no match:

df1 = (df[df['Title'].str.contains('Dog')]
        .groupby(['State', 'Theatre'])['TicketPrice']
        .size()
        .reset_index(name='count'))

print (df1)
  State Theatre  count
0    NJ       C      1
1    NY       B      2


问:
Nested IF ELSE in a derived column
I have the following logic to store the date in BI_StartDate as below:

If UpdatedDate is not null then BI_StartDate=UpddatedDate

ELSE BI_StartDate takes EntryDate value , if the EntryDate is null
then BI_StartDate=CreatedDate

If the CreatedDate IS NULL then BI_StartDate=GetDATE()

I am using a derived column as seen below:

```<code>ISNULL(UpdatedDateODS)  ? EntryDateODS : (ISNULL(EntryDateODS) ? CreatedDateODS :
(ISNULL(CreatedDateODS) ? GETDATE()  ))
</code>```

I am getting this error:

The expression "ISNULL(UpdatedDateODS)  ? EntryDateODS :
  (ISNULL(EntryDateODS) ? CreatedDateODS :(ISNULL(CreatedDateODS) ?
  GETDATE()  ))" on "Derived Column.Outputs[Derived Column
  Output].Columns[Derived Column 1]" is not valid.

答:
From syntax perspective, the nested if-else condition is not written well, since you have to make sure that all possible output should have the same data type, also you didn't mentioned the last "else" condition:

```<code>ISNULL(UpdatedDateODS)  ? EntryDateODS : (ISNULL(EntryDateODS) ? CreatedDateODS :
(ISNULL(CreatedDateODS) ? GETDATE() : **<missing>** ))
</code>```

From logical perspective, you the expression may throw exception since you are using EntryDateODS column if ISNULL(UpdatedDateODS) is true, while you should check if EntryDateODS is not null before using it, I suggest that the expression is as following:

```<code>ISNULL(UpdatedDateODS)  ? UpdatedDateODS : (ISNULL(EntryDateODS) ? EntryDateODS :
(ISNULL(CreatedDateODS) ? CreatedDateODS : GETDATE()  ))
</code>```

As mentioned above, if UpdatedDateODS , EntryDateODS, CreatedDateODS and GETDATE() don't have the same data type then you should cast to a unified data type as example:

```<code>ISNULL(UpdatedDateODS)  ? (DT_DATE)UpdatedDateODS : (ISNULL(EntryDateODS) ? (DT_DATE)EntryDateODS :
(ISNULL(CreatedDateODS) ? (DT_DATE)CreatedDateODS : (DT_DATE)GETDATE()  ))
</code>```

Title: Nested IF ELSE in a derived column

Body:
I have the following logic to store the date in BI_StartDate as below:

If UpdatedDate is not null then BI_StartDate=UpddatedDate

ELSE BI_StartDate takes EntryDate value , if the EntryDate is null
then BI_StartDate=CreatedDate

If the CreatedDate IS NULL then BI_StartDate=GetDATE()

I am using a derived column as seen below:

ISNULL(UpdatedDateODS)  ? EntryDateODS : (ISNULL(EntryDateODS) ? CreatedDateODS :
(ISNULL(CreatedDateODS) ? GETDATE()  ))

I am getting this error:

The expression "ISNULL(UpdatedDateODS)  ? EntryDateODS :
  (ISNULL(EntryDateODS) ? CreatedDateODS :(ISNULL(CreatedDateODS) ?
  GETDATE()  ))" on "Derived Column.Outputs[Derived Column
  Output].Columns[Derived Column 1]" is not valid.

Body:
From syntax perspective, the nested if-else condition is not written well, since you have to make sure that all possible output should have the same data type, also you didn't mentioned the last "else" condition:

ISNULL(UpdatedDateODS)  ? EntryDateODS : (ISNULL(EntryDateODS) ? CreatedDateODS :
(ISNULL(CreatedDateODS) ? GETDATE() : **<missing>** ))

From logical perspective, you the expression may throw exception since you are using EntryDateODS column if ISNULL(UpdatedDateODS) is true, while you should check if EntryDateODS is not null before using it, I suggest that the expression is as following:

ISNULL(UpdatedDateODS)  ? UpdatedDateODS : (ISNULL(EntryDateODS) ? EntryDateODS :
(ISNULL(CreatedDateODS) ? CreatedDateODS : GETDATE()  ))

As mentioned above, if UpdatedDateODS , EntryDateODS, CreatedDateODS and GETDATE() don't have the same data type then you should cast to a unified data type as example:

ISNULL(UpdatedDateODS)  ? (DT_DATE)UpdatedDateODS : (ISNULL(EntryDateODS) ? (DT_DATE)EntryDateODS :
(ISNULL(CreatedDateODS) ? (DT_DATE)CreatedDateODS : (DT_DATE)GETDATE()  ))


问:
Multithreading 1D Median Filtering in Python
I have tried the following python median filtering on time-series signals to find the fastest and more efficient function.

sig is a numpy array of size 80×188 which contains 188 samples measured by 80 sensors.

```<code>import numpy as np
from scipy.ndimage import median_filter
from scipy.signal import medfilt
from scipy.signal import medfilt2d
import time

sig = np.random.rand(80,188).astype('f')
print(type(sig))
print(type(sig[0][0]))

window_length = 181

t = time.time()
sigFiltered = medfilt2d(sig, (1,window_length))
elapsed = time.time() - t
print('scipy.signal.medfilt2d: %g seconds' % elapsed)

t = time.time()
sigFiltered = median_filter(sig, (1,window_length))
elapsed = time.time() - t
print('scipy.ndimage.median_filter: %g seconds' % elapsed)

t = time.time()
sigFiltered = medfilt(sig, (1,window_length))
elapsed = time.time() - t
print('scipy.signal.medfilt: %g seconds' % elapsed)
</code>```

The code can be tried here.

The result of the filter is another time-series array of size 80×188 with smoothed time-points for each sensor.

MATLAB medfilt1(sig, 181, [], 2) performs the filtering on the same data 10 times faster compared to scipy.signal.medfilt2d, which was the fastest among other functions. On my machine, MATLAB=2ms vs Python=20 ms. I think MATLAB performs multithreading processing and python does not.

Is there any way to perform multithreading median filtering to speed up the process and assign sensors to different threads? Is there a more efficient median filtering available in python? Can I achieve the performance of MATLAB win python or at least get closer to it?

答:
I'm wondering why you're using a median filter of 181 points for a data length of 188? The filter is so long that you're essentially just throwing away all the data and replacing it with the global median of the sensor's output. Typical median filter lengths would be a few samples, depending on what kind of transients you want to filter out.

The filter length also explains why it's so slow. On my machine, your median_filter example takes 46 ms. Running with a more normal filter size of 3 samples takes 0.7 ms.

Body:
I have tried the following python median filtering on time-series signals to find the fastest and more efficient function.

sig is a numpy array of size 80×188 which contains 188 samples measured by 80 sensors.

import numpy as np
from scipy.ndimage import median_filter
from scipy.signal import medfilt
from scipy.signal import medfilt2d
import time

sig = np.random.rand(80,188).astype('f')
print(type(sig))
print(type(sig[0][0]))

window_length = 181

t = time.time()
sigFiltered = medfilt2d(sig, (1,window_length))
elapsed = time.time() - t
print('scipy.signal.medfilt2d: %g seconds' % elapsed)

t = time.time()
sigFiltered = median_filter(sig, (1,window_length))
elapsed = time.time() - t
print('scipy.ndimage.median_filter: %g seconds' % elapsed)

t = time.time()
sigFiltered = medfilt(sig, (1,window_length))
elapsed = time.time() - t
print('scipy.signal.medfilt: %g seconds' % elapsed)

The code can be tried here.

The result of the filter is another time-series array of size 80×188 with smoothed time-points for each sensor.

MATLAB medfilt1(sig, 181, [], 2) performs the filtering on the same data 10 times faster compared to scipy.signal.medfilt2d, which was the fastest among other functions. On my machine, MATLAB=2ms vs Python=20 ms. I think MATLAB performs multithreading processing and python does not.

Is there any way to perform multithreading median filtering to speed up the process and assign sensors to different threads? Is there a more efficient median filtering available in python? Can I achieve the performance of MATLAB win python or at least get closer to it?