问:
EF Core DbContext Concurrency Issue with XUnit Tests
I seem to have a strange concurrency issue I can't seem to put my finger on.
When I construct my implementation of a DbContext I inject the Entities I want to be built by the modelbuilder (don't worry about why). This is only done once by my app at runtime and runs fine, but when I'm integration testing DB integration, I inject only the test entities I need for my InMemoryDatabase.

Now I seem to have a weird issue where two unit tests in different class files needing different entities seem to get crossed over.

I keep running the unit tests and the first test will pass, but the second test will fail saying that TestObjectB doesn't exist in the model. When I inspect the model it says TestObjectA exists instead, even though it wasn't injected on this test. So as if the implementation of the DataContext was static and overwritten...These are different files and fresh constructors for the context, I don't understand how they are crossing paths? If I run the unit test that fails on it's own, it passes.

Note the following code has been simplified for your view.

DB Context:

```<code>public class DataContext : DbContext
{
    private readonly List<IEntity> _entities;

    public DataContextA(List<IEntity> entities, DbContextOptions options) : base(options)
    {
        _entities = entities;
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        foreach (var entity in _entities)
        {
            modelBuilder.Entity(entity.GetType());
        }
    }
}
</code>```

Test Implementation 1:

```<code>[Fact]
            public void CheckUniqueFieldA()
            {
                var options = new DbContextOptionsBuilder<DataContext>();

                options.UseInMemoryDatabase(Guid.NewGuid().ToString());

                using (var context = new DataContext(new List<IEntity> { new TestObjectA() }, options.Options))
                {
                    //Do Something
                }
            }
</code>```

Test Implementation2:

```<code>[Fact]
            public void CheckUniqueFieldB()
            {
                var options = new DbContextOptionsBuilder<DataContext>();

                options.UseInMemoryDatabase(Guid.NewGuid().ToString());

                using (var context = new DataContext(new List<IEntity> { new TestObjectB() }, options.Options))
                {
                    //Do Something
                }
            }
</code>```

答:
The reason is EF Core model caching described in Alternating between multiple models with the same DbContext type documentation topic:

...the model caching mechanism EF uses to improve the performance by only invoking OnModelCreating once and caching the model.

By default EF assumes that for any given context type the model will be the same.

The link also contains an example how to solve it. You'd need to create custom implementation of IModelCacheKeyFactory interface and replace the default EF Core implementation using ReplaceService inside OnConfiguring. The implementation should return an object representing the unique cache key for a given DbContext instance. The default implementation simply returns context.GetType().

Body:
I seem to have a strange concurrency issue I can't seem to put my finger on.
When I construct my implementation of a DbContext I inject the Entities I want to be built by the modelbuilder (don't worry about why). This is only done once by my app at runtime and runs fine, but when I'm integration testing DB integration, I inject only the test entities I need for my InMemoryDatabase.

Now I seem to have a weird issue where two unit tests in different class files needing different entities seem to get crossed over.

I keep running the unit tests and the first test will pass, but the second test will fail saying that TestObjectB doesn't exist in the model. When I inspect the model it says TestObjectA exists instead, even though it wasn't injected on this test. So as if the implementation of the DataContext was static and overwritten...These are different files and fresh constructors for the context, I don't understand how they are crossing paths? If I run the unit test that fails on it's own, it passes.

Note the following code has been simplified for your view.

DB Context:

public class DataContext : DbContext
{
    private readonly List<IEntity> _entities;

    public DataContextA(List<IEntity> entities, DbContextOptions options) : base(options)
    {
        _entities = entities;
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        foreach (var entity in _entities)
        {
            modelBuilder.Entity(entity.GetType());
        }
    }
}

Test Implementation 1:

[Fact]
            public void CheckUniqueFieldA()
            {
                var options = new DbContextOptionsBuilder<DataContext>();

                options.UseInMemoryDatabase(Guid.NewGuid().ToString());

                using (var context = new DataContext(new List<IEntity> { new TestObjectA() }, options.Options))
                {
                    //Do Something
                }
            }

Test Implementation2:

[Fact]
            public void CheckUniqueFieldB()
            {
                var options = new DbContextOptionsBuilder<DataContext>();

                options.UseInMemoryDatabase(Guid.NewGuid().ToString());

                using (var context = new DataContext(new List<IEntity> { new TestObjectB() }, options.Options))
                {
                    //Do Something
                }
            }


来源: stackexchange

问:
button href is ignoring everything after question mark
I have this button

```<code><button href="account.html?gto=4356">go to</button>
</code>```

On click it redirects to ./account.html?# though i was expecting ./account.html?gto=4356.

Why is it ignoring everything after the question mark and how can I make this work?

答:
Button tag does not support href attribute. instead use a tag and css design to make it look like a button.

```<code><a href="account.html?gto=4356">go to</a>
</code>```

Hope it will help you.

ContentLicense: CC BY-SA 4.0

Body:
I have this button

<button href="account.html?gto=4356">go to</button>

On click it redirects to ./account.html?# though i was expecting ./account.html?gto=4356.

Why is it ignoring everything after the question mark and how can I make this work?

Body:
Button tag does not support href attribute. instead use a tag and css design to make it look like a button.

<a href="account.html?gto=4356">go to</a>

Hope it will help you.


问:
how to extract the contents of the array?
I'm writing an application on flutter and I'm a bit stuck at the moment of extracting the contents of firebase classes. How do I extract the contents of the PhoneNumber variable from "user"? I will need the extracted number to send to the server

This is the output of the debugPrint('user: $user'):

```<code>user: FirebaseUser({uid: hGLEDW6OT5ZMhWra9L4p6bB4Pw92, isAnonymous: false, phoneNumber: +79644054946, providerData: [{uid: hGLEDW6OT5ZMhWra9L4p6bB4Pw92, phoneNumber: +79644054946, providerId: firebase}], providerId: firebase, creationTimestamp: 1557420327980, lastSignInTimestamp: 1558848790729, isEmailVerified: false}
</code>```

void _signInWithPhoneNumber() async {
    final AuthCredential credential = PhoneAuthProvider.getCredential(
      verificationId: _verificationId,
      smsCode: _smsController.text,
    );
    final FirebaseUser user = await _auth.signInWithCredential(credential);
    final FirebaseUser currentUser = await _auth.currentUser();
    assert(user.uid == currentUser.uid);
    debugPrint('user: $user');
    setState(() {

      if (user != null) {

           Navigator.pushNamed(context, '/amenities');
      } else {
        _message = 'Вход не выполнен';
      }
    });
}
```

I need to extract PhoneNumber from "user" to send to server in Json

答: I'm pretty sure you can grab the phone number with just user.phoneNumber

Body:
I'm writing an application on flutter and I'm a bit stuck at the moment of extracting the contents of firebase classes. How do I extract the contents of the PhoneNumber variable from "user"? I will need the extracted number to send to the server

This is the output of the debugPrint('user: $user'):

user: FirebaseUser({uid: hGLEDW6OT5ZMhWra9L4p6bB4Pw92, isAnonymous: false, phoneNumber: +79644054946, providerData: [{uid: hGLEDW6OT5ZMhWra9L4p6bB4Pw92, phoneNumber: +79644054946, providerId: firebase}], providerId: firebase, creationTimestamp: 1557420327980, lastSignInTimestamp: 1558848790729, isEmailVerified: false}

void _signInWithPhoneNumber() async {
    final AuthCredential credential = PhoneAuthProvider.getCredential(
      verificationId: _verificationId,
      smsCode: _smsController.text,
    );
    final FirebaseUser user = await _auth.signInWithCredential(credential);
    final FirebaseUser currentUser = await _auth.currentUser();
    assert(user.uid == currentUser.uid);
    debugPrint('user: $user');
    setState(() {

      if (user != null) {

           Navigator.pushNamed(context, '/amenities');
      } else {
        _message = 'Вход не выполнен';
      }
    });
}

I need to extract PhoneNumber from "user" to send to server in Json


问:
How to use a vector when indexing columns?
So basically, I have a vector:

Note, thetitanic is a data frame of the people who attended the titanic.

```<code>femalesurvivors_1 <- thetitanic[(thetitanic$Sex=="female") & (thetitanic$Survived==1) & (thetitanic$PClass=="1st"),]
</code>```

This shows the female survivors of the 1st class. However, now I only want the female survivors of the 1st class who are above 18 years of age. So:

I want to also index (thetitanic$Sex>=18)

I have been trying some forms of code but I keep getting errors.
x <- thetitanic[(femalesurvivors_1) & (thetitanic$Age>=18)]

The error shows: 1: In Ops.factor(left, right) : '&' not meaningful for factors

Am I able to pass through a vector when doing? Or would I have to make a new vector and repeat code?

I am trying to return the value of female survivors in the 1st class, who are above 18 years age.

I am a noob.. Any help would be appreciated. Thank you.

答:
You could create a logical vector of conditions and take sum over it.

```<code>sum(with(thetitanic,
    Survived == 1 & Sex == "female" & Pclass == 1 & Age >= 18), na.rm = TRUE)
</code>```

Using subset

```<code>nrow(subset(thetitanic, Survived == 1 & Sex == "female" & Pclass == 1 & Age >= 18))
</code>```

Or with dplyr using filter

```<code>library(dplyr)

thetitanic %>%
  filter(Survived == 1 & Sex == "female" & Pclass == 1 & Age >= 18) %>%
   nrow
</code>```

This will return number of female survivors of 1st class above age of 18. If you want those entries then remove nrow from filter and subset functions.

Body:
So basically, I have a vector:

Note, thetitanic is a data frame of the people who attended the titanic.

femalesurvivors_1 <- thetitanic[(thetitanic$Sex=="female") & (thetitanic$Survived==1) & (thetitanic$PClass=="1st"),]

This shows the female survivors of the 1st class. However, now I only want the female survivors of the 1st class who are above 18 years of age. So:

I want to also index (thetitanic$Sex>=18)

I have been trying some forms of code but I keep getting errors.
x <- thetitanic[(femalesurvivors_1) & (thetitanic$Age>=18)]

The error shows: 1: In Ops.factor(left, right) : '&' not meaningful for factors

Am I able to pass through a vector when doing? Or would I have to make a new vector and repeat code?

I am trying to return the value of female survivors in the 1st class, who are above 18 years age.

I am a noob.. Any help would be appreciated. Thank you.

Body:
You could create a logical vector of conditions and take sum over it.

sum(with(thetitanic,
    Survived == 1 & Sex == "female" & Pclass == 1 & Age >= 18), na.rm = TRUE)

Using subset

nrow(subset(thetitanic, Survived == 1 & Sex == "female" & Pclass == 1 & Age >= 18))

Or with dplyr using filter

library(dplyr)

thetitanic %>%
  filter(Survived == 1 & Sex == "female" & Pclass == 1 & Age >= 18) %>%
   nrow

This will return number of female survivors of 1st class above age of 18. If you want those entries then remove nrow from filter and subset functions.


问:
keras multi-input model: Expected to see 2 array(s), but instead got the following list of 1 arrays
I'm training a functional keras model on mnist dataset. There's a layer that requires 2 inputs - the traditional input tensor and a current batch of on-hot encoded labels. I think I've set up my model to accept 2 inputs, but I get:

ValueError: Error when checking model : the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 2 array(s), but instead got the following list of 1 arrays. [array([[[[0.], ...

Most answers suggested converting inputs to numpy arrays, but mnist images and labels are numpy arrays by default.

batch_size = 128
num_classes = 10
epochs = 1

# Mnist part

img_rows, img_cols = 28, 28

(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255

y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

# Model part

images = Input(shape=input_shape, name='images_input')
labels = Input(shape=(num_classes,), name='labels_input')

x = Conv2D(32, kernel_size=(3, 3), activation='relu')(images)
x = Conv2D(64, (3, 3), activation='relu')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Dropout(0.25)(x)
x = Flatten()(x)
x = Dense(128, activation='relu', name='features')(x)
x = Dropout(0.5)(x)
x = SomeLayerWith2Inputs()([x, labels])
output = Dense(num_classes, activation='softmax')(x)

model = Model(inputs=[images, labels], outputs=output)

model.compile(
    loss=keras.losses.categorical_crossentropy,
    optimizer=keras.optimizers.Adadelta(),
    metrics=['accuracy']
)

# x_train = <type 'numpy.ndarray'> (60000, 28, 28, 1)
# y_train = <type 'numpy.ndarray'> (60000, 10)
# x_test = <type 'numpy.ndarray'> (10000, 28, 28, 1)
# y_test = <type 'numpy.ndarray'> (10000, 10)

model.fit(
    [x_train, y_train],
    y_train,
    batch_size=batch_size,
    callbacks=[tensorboard],
    epochs=epochs,
    verbose=1,
    validation_data=([x_test, y_test], y_test)
)
```

I've also tried to do model.fit(x={'images_input': x_train, 'labels_input': y_train}, y=y_train), but that also didn't work.

I'm using Keras v2.2.4

答:
Found the problem. There was also a tensorboard callback (not shown in original question):

```<code>tensorboard = TensorBoard(
    batch_size=128,
    embeddings_freq=1,
    embeddings_layer_names=['features'],
    embeddings_metadata='metadata.tsv',
    embeddings_data=x_test
)
</code>```

The embeddings_data argument should be [x_test, y_test].

Body:
I'm training a functional keras model on mnist dataset. There's a layer that requires 2 inputs - the traditional input tensor and a current batch of on-hot encoded labels. I think I've set up my model to accept 2 inputs, but I get:

ValueError: Error when checking model : the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 2 array(s), but instead got the following list of 1 arrays. [array([[[[0.], ...

Most answers suggested converting inputs to numpy arrays, but mnist images and labels are numpy arrays by default.

batch_size = 128
num_classes = 10
epochs = 1

# Mnist part

img_rows, img_cols = 28, 28

(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255

y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

# Model part

images = Input(shape=input_shape, name='images_input')
labels = Input(shape=(num_classes,), name='labels_input')

x = Conv2D(32, kernel_size=(3, 3), activation='relu')(images)
x = Conv2D(64, (3, 3), activation='relu')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Dropout(0.25)(x)
x = Flatten()(x)
x = Dense(128, activation='relu', name='features')(x)
x = Dropout(0.5)(x)
x = SomeLayerWith2Inputs()([x, labels])
output = Dense(num_classes, activation='softmax')(x)

model = Model(inputs=[images, labels], outputs=output)

model.compile(
    loss=keras.losses.categorical_crossentropy,
    optimizer=keras.optimizers.Adadelta(),
    metrics=['accuracy']
)

# x_train = <type 'numpy.ndarray'> (60000, 28, 28, 1)
# y_train = <type 'numpy.ndarray'> (60000, 10)
# x_test = <type 'numpy.ndarray'> (10000, 28, 28, 1)
# y_test = <type 'numpy.ndarray'> (10000, 10)

model.fit(
    [x_train, y_train],
    y_train,
    batch_size=batch_size,
    callbacks=[tensorboard],
    epochs=epochs,
    verbose=1,
    validation_data=([x_test, y_test], y_test)
)

I've also tried to do model.fit(x={'images_input': x_train, 'labels_input': y_train}, y=y_train), but that also didn't work.

I'm using Keras v2.2.4

Body:
Found the problem. There was also a tensorboard callback (not shown in original question):

tensorboard = TensorBoard(
    batch_size=128,
    embeddings_freq=1,
    embeddings_layer_names=['features'],
    embeddings_metadata='metadata.tsv',
    embeddings_data=x_test
)

The embeddings_data argument should be [x_test, y_test].


问:
Make socket.io work within an API endpoint in Node.js
I'm having the following logic (all servers are in Node.js) :

1- Client makes an API call to Server A's "api/request" endpoint.

2- Server A "request" endpoint receives the request, and just passes the original request to Server B with a socket.io emit event.

3- Server B socket.io on event receives the request, handles it, and sends back the response in a new socket.io emit event.

4- Server A socket.io on event receives the response, and is supposed to return the response to the Client who originally made the request.

The issue is that since in Server A I'm passing the request with socket.io emit event, I'm loosing the option to wait for an answer from Server B to return to Client anything. I would like Client to receive the response from Server B, as a response from its original call to Server A.

Any idea on how to achieve this?

答:
I found a way. Since you can only have one io.on('connection', function (socket) {}) in your code, I had to find a way around it.

The issue was that if you place io.on('connection', function (socket) {}) within your router.post('/', async (req, res) => {}), it will only be triggered when you call your endpoint. In my case, I had some sockets events that I wanted to be called at anytime, not only when the endpoint is called. So I had to place the io.on('connection', function (socket) {}) outside of my router.post('/', async (req, res) => {}). Thus I couldn't use var io = req.app.get('socketio'); inside the router. Here is what I have done instead in Server A code:

index.js:

```<code>const cors = require('cors');
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const taskRequest = require('./routes/taskRequest')(io);

app.use(cors())
app.use(express.json());
app.use('/api/taskRequest', taskRequest);

server.listen(4002);
</code>```

routes/taskRequest.js

```<code>const express = require('express');
const router = express.Router();

module.exports = function(io) {

    //we define the variables
    var sendResponse = function () {};

    io.sockets.on("connection",function(socket){
        // Everytime a client logs in, display a connected message
        console.log("Server-Client Connected!");

        socket.on('connected', function(data) {
            //listen to event at anytime (not only when endpoint is called)
            //execute some code here
        });

        socket.on('taskResponse', data => {
            //calling a function which is inside the router so we can send a res back
            sendResponse(data);
        })
    });

    router.post('/', async (req, res) => {

        //pickedUser is one of the connected client
        var pickedUser = "JZLpeA4pBECwbc5IAAAA";
        io.to(pickedUser).emit('taskRequest', req.body);

        sendResponse = function (data) {
            return res.status(200).json({"text": "Success", "response": data.data});
        }

    });

    return router;

};
</code>```

Like this, Server A is only sending back to Client the response once it has received the response from Server B.

Solved!

Body:
I found a way. Since you can only have one io.on('connection', function (socket) {}) in your code, I had to find a way around it.

The issue was that if you place io.on('connection', function (socket) {}) within your router.post('/', async (req, res) => {}), it will only be triggered when you call your endpoint. In my case, I had some sockets events that I wanted to be called at anytime, not only when the endpoint is called. So I had to place the io.on('connection', function (socket) {}) outside of my router.post('/', async (req, res) => {}). Thus I couldn't use var io = req.app.get('socketio'); inside the router. Here is what I have done instead in Server A code:

index.js:

const cors = require('cors');
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const taskRequest = require('./routes/taskRequest')(io);

app.use(cors())
app.use(express.json());
app.use('/api/taskRequest', taskRequest);

server.listen(4002);

routes/taskRequest.js

const express = require('express');
const router = express.Router();

module.exports = function(io) {

    //we define the variables
    var sendResponse = function () {};

    io.sockets.on("connection",function(socket){
        // Everytime a client logs in, display a connected message
        console.log("Server-Client Connected!");

        socket.on('connected', function(data) {
            //listen to event at anytime (not only when endpoint is called)
            //execute some code here
        });

        socket.on('taskResponse', data => {
            //calling a function which is inside the router so we can send a res back
            sendResponse(data);
        })
    });

    router.post('/', async (req, res) => {

        //pickedUser is one of the connected client
        var pickedUser = "JZLpeA4pBECwbc5IAAAA";
        io.to(pickedUser).emit('taskRequest', req.body);

        sendResponse = function (data) {
            return res.status(200).json({"text": "Success", "response": data.data});
        }

    });

    return router;

};

Like this, Server A is only sending back to Client the response once it has received the response from Server B.

Solved!


问:
Google Pay AutoResolveHelper.resolveTask() not calling onActivityResult in Fragment
I have implemented Google Pay in app and making paymentData request I am using AutoResolveHelper to display bottom sheet and than get results via onActivityResult. I am making this request from Fragment not from Activity. So I am passing parent activity like this.

```<code> paymentsClient?.loadPaymentData(gpayViewModel.paymentDataRequest)?.let { task ->
            AutoResolveHelper.resolveTask(task, requireActivity(), LOAD_PAYMENT_DATA_REQUEST_CODE)
        }
</code>```

the problem is that this AutoResolveHelper is not calling onActivityResult on Fragment but only on Activity.

I have read something like this:

If you're calling startActivityForResult() from the fragment then you
  should call startActivityForResult(), not
  getActivity().startActivityForResult(), as it will result in fragment
  onActivityResult().

So it suggest that when AutoResolveHelper is calling startActivityForResult() on passed activity then fragment's onActivityResult will never be called.

So now my only option is to implement onActivityResult in Activity and somehow pass control from this Activity to my child Fragment but this need some boilerplate code and as my Fragment is Reusable than this solution is not perfect.

Meanwhile I have spotted that this code startActivityForResult in correct way and than the Fragment's onActivityResult is called correctly:

```<code> val intent = Intent(activity, CardIOActivity::class.java)
        intent.putExtra(CardIOActivity.EXTRA_REQUIRE_EXPIRY, true)
        intent.putExtra(CardIOActivity.EXTRA_REQUIRE_CVV, true)
        intent.putExtra(CardIOActivity.EXTRA_REQUIRE_CARDHOLDER_NAME, true)

        startActivityForResult(intent, CARD_IO_REQUEST_CODE)
</code>```

So can I replace this  AutoResolveHelper.resolveTask() somehow to execute this task in such way that onActivityResult will not be necessary or I could startActivityForResult myself?

答:
Here is a link to the working code. It may be not the perfect approach but it gets the work done.
https://readyandroid.wordpress.com/onactivityresult-is-not-being-called-in-fragment/</p>

Body:
I have implemented Google Pay in app and making paymentData request I am using AutoResolveHelper to display bottom sheet and than get results via onActivityResult. I am making this request from Fragment not from Activity. So I am passing parent activity like this.

 paymentsClient?.loadPaymentData(gpayViewModel.paymentDataRequest)?.let { task ->
            AutoResolveHelper.resolveTask(task, requireActivity(), LOAD_PAYMENT_DATA_REQUEST_CODE)
        }

the problem is that this AutoResolveHelper is not calling onActivityResult on Fragment but only on Activity.

I have read something like this:

If you're calling startActivityForResult() from the fragment then you
  should call startActivityForResult(), not
  getActivity().startActivityForResult(), as it will result in fragment
  onActivityResult().

So it suggest that when AutoResolveHelper is calling startActivityForResult() on passed activity then fragment's onActivityResult will never be called.

So now my only option is to implement onActivityResult in Activity and somehow pass control from this Activity to my child Fragment but this need some boilerplate code and as my Fragment is Reusable than this solution is not perfect.

Meanwhile I have spotted that this code startActivityForResult in correct way and than the Fragment's onActivityResult is called correctly:

 val intent = Intent(activity, CardIOActivity::class.java)
        intent.putExtra(CardIOActivity.EXTRA_REQUIRE_EXPIRY, true)
        intent.putExtra(CardIOActivity.EXTRA_REQUIRE_CVV, true)
        intent.putExtra(CardIOActivity.EXTRA_REQUIRE_CARDHOLDER_NAME, true)

        startActivityForResult(intent, CARD_IO_REQUEST_CODE)

So can I replace this  AutoResolveHelper.resolveTask() somehow to execute this task in such way that onActivityResult will not be necessary or I could startActivityForResult myself?


问:
Why can't Visual Studio collapse Javascript functions that include Razor syntax?
My .cshtml file in Visual Studio looks like this:

Notice how createTabStrip can collapse, but createTeachersTab cannot. Why is this?

EDIT: It seems to have something to do with the razor syntax. I took out all of the @ signs and createTeachersTab was able to collapse.

答: Also you can highlight the block and press ctrl + m, ctrl + h to collapse the block</p>

ContentLicense: CC BY-SA 3.0


问:
sw-precache-webpack-plugin on windows - cannot resolve window
First time building a PWA, using Laravel 5.8 + Homestead. I am getting the following error when page loads:

```<code>app.js:42706 Uncaught ReferenceError: window is not defined
ServiceWorker registration failed:  TypeError: Failed to register a ServiceWorker: ServiceWorker script evaluation failed
</code>```

And the error line in my app.js is:

```<code>window._ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
</code>```

The worker cached app.js cannot resolve the window constant.

I have set up sw-precache-webpack-plugin, so my webpack.mix.js is:

```<code>const mix = require('laravel-mix');
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');

mix.js('resources/js/custom/buildings.js', 'public/js')
    .js('resources/js/custom/home.js', 'public/js')
    .js('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css')
    .options({
        processCssUrls: false
    })
    .webpackConfig({
    plugins: [
        new SWPrecacheWebpackPlugin({
            cacheId: 'sccpwa',
            filename: 'service-worker.js',
            staticFileGlobs: ['public/**/*.{css,eot,svg,ttf,woff,woff2,js,html}'],
            minify: true,
            stripPrefix: 'public/',
            handleFetch: true,
            dynamicUrlToDependencies: {
                '/': ['resources/views/auth/login.blade.php'],
                '/building/list': ['resources/views/pages/building.blade.php'],
                '/home': ['resources/views/pages/home.blade.php'],
            },
            staticFileGlobsIgnorePatterns: [/\.map$/, /mix-manifest\.json$/, /manifest\.json$/, /service-worker\.js$/],
            navigateFallback: '/',
            runtimeCaching: [
                {
                    urlPattern: /^https:\/\/fonts\.googleapis\.com\//,
                    handler: 'cacheFirst'
                },
                {
                    urlPattern: /^https:\/\/www\.projecturl\.com\/img\/(\w+)\.jpg/,
                    handler: 'cacheFirst'
                }
            ],
            importScripts: [
                './js/app.js',
                './js/buildings.js',
                './js/home.js'
            ]
        })
    ]
});
</code>```

I then added this to register the service worker at the top of my app.js

```<code>require('./app-bootstrap');

if ('serviceWorker' in navigator ) {
    window.addEventListener('load', function() {
        navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
            // Registration was successful
            console.log('ServiceWorker registration successful with scope: ', registration.scope);
        }, function(err) {
            // registration failed :(
            console.log('ServiceWorker registration failed: ', err);
        });
    });
}

$(document).ready(function() { .APP JS STUFF HERE. };
</code>```

npm compiles it with no errors and I can see the addEventListener being executed, but then the above error pops.

What have I missed? Thanks!

答:
The error is a very simple mistake. You're importing (importScript) your application code into the SW script. When it tries to execute, the error happens.

Service Worker execution context is different from the usual page execution context. You cannot execute 1:1 your app code in the SW. It usually wouldn't even make any sense.

I'm mostly sure you've understood the importScripts parameter in the workbox config wrong. It means: import these scripts into the SW and execute them.

Body:
First time building a PWA, using Laravel 5.8 + Homestead. I am getting the following error when page loads:

app.js:42706 Uncaught ReferenceError: window is not defined
ServiceWorker registration failed:  TypeError: Failed to register a ServiceWorker: ServiceWorker script evaluation failed

And the error line in my app.js is:

window._ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");

The worker cached app.js cannot resolve the window constant.

I have set up sw-precache-webpack-plugin, so my webpack.mix.js is:

const mix = require('laravel-mix');
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');

mix.js('resources/js/custom/buildings.js', 'public/js')
    .js('resources/js/custom/home.js', 'public/js')
    .js('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css')
    .options({
        processCssUrls: false
    })
    .webpackConfig({
    plugins: [
        new SWPrecacheWebpackPlugin({
            cacheId: 'sccpwa',
            filename: 'service-worker.js',
            staticFileGlobs: ['public/**/*.{css,eot,svg,ttf,woff,woff2,js,html}'],
            minify: true,
            stripPrefix: 'public/',
            handleFetch: true,
            dynamicUrlToDependencies: {
                '/': ['resources/views/auth/login.blade.php'],
                '/building/list': ['resources/views/pages/building.blade.php'],
                '/home': ['resources/views/pages/home.blade.php'],
            },
            staticFileGlobsIgnorePatterns: [/\.map$/, /mix-manifest\.json$/, /manifest\.json$/, /service-worker\.js$/],
            navigateFallback: '/',
            runtimeCaching: [
                {
                    urlPattern: /^https:\/\/fonts\.googleapis\.com\//,
                    handler: 'cacheFirst'
                },
                {
                    urlPattern: /^https:\/\/www\.projecturl\.com\/img\/(\w+)\.jpg/,
                    handler: 'cacheFirst'
                }
            ],
            importScripts: [
                './js/app.js',
                './js/buildings.js',
                './js/home.js'
            ]
        })
    ]
});

I then added this to register the service worker at the top of my app.js

require('./app-bootstrap');

if ('serviceWorker' in navigator ) {
    window.addEventListener('load', function() {
        navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
            // Registration was successful
            console.log('ServiceWorker registration successful with scope: ', registration.scope);
        }, function(err) {
            // registration failed :(
            console.log('ServiceWorker registration failed: ', err);
        });
    });
}

$(document).ready(function() { .APP JS STUFF HERE. };

npm compiles it with no errors and I can see the addEventListener being executed, but then the above error pops.

What have I missed? Thanks!


问:
How to convert Int32 to String in Swift 4?
I am having difficulty in converting an Int32 to String. I tried to following:

```<code>String(cartItem?.quantity)
</code>```

"\(cartItem?.quantity)"
but no luck.

cart.quantity is of type Int32.

quantity is an attribute of cart in the CoreData model.

答:
The question isn't clear but what I think this issue boils down to is that you can't init a string with an optional value.

So either do as @matt suggested and force unwrap the cartItem

```<code>String(cartItem!.quantity)
</code>```

or supply a default value

```<code>String(cartItem?.quantity ?? 0)
</code>```

Of course if you need to handle the fact that you might not have a cart then it is better to do it like

```<code>if let cart = cartItem {
    let str = "\(cart.quantity)" //or String(cart.quantity)
    //do stuff with str
} else {
    //handle no cart state
}
</code>```

Body:
I am having difficulty in converting an Int32 to String. I tried to following:

String(cartItem?.quantity)

"\(cartItem?.quantity)"
but no luck.

cart.quantity is of type Int32.

quantity is an attribute of cart in the CoreData model.

Body:
The question isn't clear but what I think this issue boils down to is that you can't init a string with an optional value.

So either do as @matt suggested and force unwrap the cartItem

String(cartItem!.quantity)

or supply a default value

String(cartItem?.quantity ?? 0)

Of course if you need to handle the fact that you might not have a cart then it is better to do it like

if let cart = cartItem {
    let str = "\(cart.quantity)" //or String(cart.quantity)
    //do stuff with str
} else {
    //handle no cart state
}


问:
Clipboard in VBA disappears after few steps
I have a code that should restore range formatting after applying few step.

```<code>Sub MyCode()
Sheets("My sheet").ListObjects("My Table").DataBodyRange.Copy
...
refreshing connection and calling function that applies stored formulas to table columns
...
Sheets("My sheet").[A10].PasteSpecial Paste:=xlPasteFormats
End sub
</code>```

I got error PasteSpecial method on range failed
If I paste immediately, it works.

Is it possible to save range formatting as variable?

答:
Here is an example on how to use variables to store the copy method and use it later. You can set the range to a variable CopyRange and use CopyRange.Copy to store it and later you can use it as the range was stored in the CopyRange and not lost along the way due to other processes running down the line.

```<code>Option Explicit
Sub CopyDataToTemplate()

Dim ws As Worksheet
Dim srcWB As Workbook
Dim destWB As Workbook
Dim srcWS As Worksheet
Dim destWS As Worksheet
Dim CopyRange As Variant

Dim i As Long, j As Long
Dim srcLRow As Long, destLRow As Long

Set destWB = Excel.Workbooks("DOLine_example.xlsx")
Set srcWB = ActiveWorkbook
Set srcWS = srcWB.ActiveSheet
Set destWS = destWB.Sheets("DOLine")

srcLRow = srcWS.Cells(srcWS.Rows.Count, "A").End(xlUp).Row
destLRow = destWS.Cells(destWS.Rows.Count, "A").End(xlUp).Row

Application.ScreenUpdating = False
'loop through column 1 to 19
For i = 1 To 19
    For j = 1 To 13
        'loop through columns

            If destWS.Cells(3, i).value = srcWS.Cells(1, j).value Then
                ' Copy column B to Column D as written in your code above
                Set CopyRange = srcWS.Range(Cells(2, j), Cells(srcLRow, j))
                    CopyRange.Copy
                ' paste columns from one wb to Columns to another wb
                destWS.Cells(destLRow, i).PasteSpecial Paste:=xlPasteAll, Transpose:=False
                Application.CutCopyMode = False
            End If
    Next j
Next i
Application.ScreenUpdating = True
MsgBox "Process completed!", vbInformation
End Sub
</code>```

Body:
I have a code that should restore range formatting after applying few step.

Sub MyCode()
Sheets("My sheet").ListObjects("My Table").DataBodyRange.Copy
...
refreshing connection and calling function that applies stored formulas to table columns
...
Sheets("My sheet").[A10].PasteSpecial Paste:=xlPasteFormats
End sub

I got error PasteSpecial method on range failed
If I paste immediately, it works.

Is it possible to save range formatting as variable?

Body:
Here is an example on how to use variables to store the copy method and use it later. You can set the range to a variable CopyRange and use CopyRange.Copy to store it and later you can use it as the range was stored in the CopyRange and not lost along the way due to other processes running down the line.

Option Explicit
Sub CopyDataToTemplate()

Dim ws As Worksheet
Dim srcWB As Workbook
Dim destWB As Workbook
Dim srcWS As Worksheet
Dim destWS As Worksheet
Dim CopyRange As Variant

Dim i As Long, j As Long
Dim srcLRow As Long, destLRow As Long

Set destWB = Excel.Workbooks("DOLine_example.xlsx")
Set srcWB = ActiveWorkbook
Set srcWS = srcWB.ActiveSheet
Set destWS = destWB.Sheets("DOLine")

srcLRow = srcWS.Cells(srcWS.Rows.Count, "A").End(xlUp).Row
destLRow = destWS.Cells(destWS.Rows.Count, "A").End(xlUp).Row

Application.ScreenUpdating = False
'loop through column 1 to 19
For i = 1 To 19
    For j = 1 To 13
        'loop through columns

            If destWS.Cells(3, i).value = srcWS.Cells(1, j).value Then
                ' Copy column B to Column D as written in your code above
                Set CopyRange = srcWS.Range(Cells(2, j), Cells(srcLRow, j))
                    CopyRange.Copy
                ' paste columns from one wb to Columns to another wb
                destWS.Cells(destLRow, i).PasteSpecial Paste:=xlPasteAll, Transpose:=False
                Application.CutCopyMode = False
            End If
    Next j
Next i
Application.ScreenUpdating = True
MsgBox "Process completed!", vbInformation
End Sub


问:
Element is also a path name in class
I am trying to parse this XML:

```<code><toteAdded id="R000000000012">
    <result code="S0000">Carrier added.</result>
</toteAdded>
</code>```

using this Java code:

```<code>@Root(name="toteAdded")
public class ToteAddedTelegram extends Telegram {
    @Element
    String result;

    @Attribute
    @Path("result")
    private String code;

    public String getCode() {
        return code;
    }

    public String getMessage() {
        return result;
    }
}
</code>```

But I am getting this error:

Element 'result' is also a path name in class nl.minerall.sapphire.lib.telegrams.ToteAddedTelegram

答:
You need to specify full path otherwise it will conflict with element name Result.

```<code>@Attribute
@Path("toteAdded/result")
private String code;
</code>```

Title: Element is also a path name in class

Body:
I am trying to parse this XML:

<toteAdded id="R000000000012">
    <result code="S0000">Carrier added.</result>
</toteAdded>

using this Java code:

@Root(name="toteAdded")
public class ToteAddedTelegram extends Telegram {
    @Element
    String result;

    @Attribute
    @Path("result")
    private String code;

    public String getCode() {
        return code;
    }

    public String getMessage() {
        return result;
    }
}

But I am getting this error:

Element 'result' is also a path name in class nl.minerall.sapphire.lib.telegrams.ToteAddedTelegram

Body:
You need to specify full path otherwise it will conflict with element name Result.

@Attribute
@Path("toteAdded/result")
private String code;


问:
Threads and threadgroups in Metal
I have some questions around threads per threadgroups and number of threadgroups.

Since, we have maxTotalThreadsPerThreadgroup and threadExecutionWidth, the length * width * height of a threadgroup should be equal to maxTotalThreadsPerThreadgroup. So, if I have maxTotalThreadsPerThreadgroup = 1024, and threadExecutionWidth = 32, what difference does it make if I make a threadgroup of size (1024 * 1 * 1) or 32 * 32 * 1? Is there any added benefit for the total GPU execution time? Or this is just for more effective management?

If I want to run threads more than maxTotalThreadsPerThreadgroup then I shall make multiple threadgroups. Is it safe to assume that ThreadGroup1 will be executed before ThreadGroup2?

答:
I'm not an authoritative source on Metal compute, and lots of details such as this are not documented, so take the following with a grain of salt:

Organizing the threadgroups into 1, 2, or 3 dimensions is mostly a convenience for you as the developer. If your problem is three-dimensional, use threadgroups with 3 dimensions. If your problem is one-dimensional, use threadgroups with 1 dimension. Metal doesn't really care one way or the other.

I don't think you can assume anything about the order in which the GPU threads from your threadgroups are scheduled.

For example, if you schedule 10 threadgroups that each compute an intermediate result (for example a sum), then you probably shouldn't depend on the 10th threadgroup to collect these results and combine them into one final result (the final sum). Instead, you'll have to launch a new compute kernel to do this.

(I'd be happy to be proven wrong about this, but I haven't read anywhere that Metal guarantees this sort of thing.)

Title: Threads and threadgroups in Metal


问:
Is there a Datetime format which not change the output date value?
I have a string in an XML which is a datetime with a timezone and I would like to change it to a DateTime format in C#.

The problem is that it go from the string format to datetime format, the value change due to the timezone.

So I would like to know how to change the xml string to c# datetime without the modification of the value.

The string xml value is :

2014-01-01T00:00:00.0000000+02:00

and when I apply the datetime format it goes to :

12/31/2013 10:00:00 PM

Here is my c# code to convert string to datetime :

Convert.ToDateTime(datestringXml);
```

I need to sort the date with the Max() and Min() function

I expect the output to be 01/01/2014... (I don't care about the hours, minutes and seconds)

答: You're using a DateTime object instead of a DateTimeOffset object. The offset part +02:00 doesn't fit in a DateTime object so it calculates the DateTime for you. You wouldn't have this issue if you'd just parse the value into a DateTimeOffset object.</p>

Body:
I have a string in an XML which is a datetime with a timezone and I would like to change it to a DateTime format in C#.

The problem is that it go from the string format to datetime format, the value change due to the timezone.

So I would like to know how to change the xml string to c# datetime without the modification of the value.

The string xml value is :

2014-01-01T00:00:00.0000000+02:00

and when I apply the datetime format it goes to :

12/31/2013 10:00:00 PM

Here is my c# code to convert string to datetime :

Convert.ToDateTime(datestringXml);

I need to sort the date with the Max() and Min() function

I expect the output to be 01/01/2014... (I don't care about the hours, minutes and seconds)


问:
Is there a way to find every combination to select an element from each list (in a list)?
I am trying to find all combinations to select exactly one element from each list inside a list. (I prefer the computationally fastest method.)

Example:
If my list is [[1], [2,3], [4,5,6]] I would want to get the following result (in any order):
[[1,2,4], [1,2,5], [1,2,6], [1,3,4], [1,3,5], [1,3,6]]

I tried finding functions in modules like itertools without any success and am not sure how to start this.

I was thinking about doing the following, but I have no idea how to finish this:
Find the number of permutations to find (called m here):

```<code>m = 1
for letter in letters:
    m *= len(letter)
</code>```

Then set up a for loop:

```<code>for i in range(m):
</code>```

Then find each combination by cycling through all lists in the list and taking one element. I was thinking of doing the selection somehow using the modulus (%) function, but I don't know how to make it work.

Body:
I am trying to find all combinations to select exactly one element from each list inside a list. (I prefer the computationally fastest method.)

Example:
If my list is [[1], [2,3], [4,5,6]] I would want to get the following result (in any order):
[[1,2,4], [1,2,5], [1,2,6], [1,3,4], [1,3,5], [1,3,6]]

I tried finding functions in modules like itertools without any success and am not sure how to start this.

I was thinking about doing the following, but I have no idea how to finish this:
Find the number of permutations to find (called m here):

m = 1
for letter in letters:
    m *= len(letter)

Then set up a for loop:

for i in range(m):

Then find each combination by cycling through all lists in the list and taking one element. I was thinking of doing the selection somehow using the modulus (%) function, but I don't know how to make it work.

Body:
Sounds like you want itertools.product():

>>> for x in itertools.product([1], [2,3], [4,5,6]):
...   print(x)
...
(1, 2, 4)
(1, 2, 5)
(1, 2, 6)
(1, 3, 4)
(1, 3, 5)
(1, 3, 6)


问:
Angular Json to class
I want to create a component with dummy data and have below code for service. I want to return observable to component.

Error

```<code>Type 'Observable<{ "CardModel": { "theme": string; "title": string; "description": string; }[]; }>' is not assignable to type 'Observable<CardModel[]>'.
</code>```

//Method

```<code>@Injectable()
export class PlanService {
  constructor() {}

  public getPlans(): Observable<CardModel[]> {
    return of(PlanServiceMock.plansMockData);
  }
}

export class PlanServiceMock {
  public static readonly plansMockData = {
    "CardModel": [
        {
            "theme": "",
            "title": "this is title",
            "description": "this is description"
        }
    ]
  };
}
</code>```

答:
The object that your are assigning to plansMockData is not compatible with your CardModel because the structures don't match.

Assuming your CardModel is something like this:

```<code>export class CardModel {
  theme: string
  title: string
  description: string
}
</code>```

Now in your code,
Instead of :

```<code>export class PlanServiceMock {
  public static readonly plansMockData = {
    "CardModel": [
        {
            "theme": "",
            "title": "this is title",
            "description": "this is description"
        }
    ]
  };
}
</code>```

Change your code like this:

```<code>export class PlanServiceMock {
  public static readonly plansMockData = [
    {
      theme: "",
      title: "this is title",
      description: "this is description"
    }
  ]
}
</code>```

Hope it helps :)

Title: Angular Json to class

Body:
I want to create a component with dummy data and have below code for service. I want to return observable to component.

Error

Type 'Observable<{ "CardModel": { "theme": string; "title": string; "description": string; }[]; }>' is not assignable to type 'Observable<CardModel[]>'.

//Method

@Injectable()
export class PlanService {
  constructor() {}

  public getPlans(): Observable<CardModel[]> {
    return of(PlanServiceMock.plansMockData);
  }
}

export class PlanServiceMock {
  public static readonly plansMockData = {
    "CardModel": [
        {
            "theme": "",
            "title": "this is title",
            "description": "this is description"
        }
    ]
  };
}

Body:
The object that your are assigning to plansMockData is not compatible with your CardModel because the structures don't match.

Assuming your CardModel is something like this:

export class CardModel {
  theme: string
  title: string
  description: string
}

Now in your code,
Instead of :

export class PlanServiceMock {
  public static readonly plansMockData = {
    "CardModel": [
        {
            "theme": "",
            "title": "this is title",
            "description": "this is description"
        }
    ]
  };
}

Change your code like this:

export class PlanServiceMock {
  public static readonly plansMockData = [
    {
      theme: "",
      title: "this is title",
      description: "this is description"
    }
  ]
}

Hope it helps :)


问:
Flutter function called infinitely in build
I am making an app which loads the CSV and show the table on the screen but the load function is being called infinitely in the build state can anyone know how to fix it I wanted to call only once but my code called it many times.

Here is the console screenshot:

Here is the code:

```<code>import 'package:flutter/material.dart';
import 'package:csv/csv.dart';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;

class TableLayout extends StatefulWidget {
  @override
  _TableLayoutState createState() => _TableLayoutState();
}
class _TableLayoutState extends State<TableLayout> {

  List<List<dynamic>> data = [];

  loadAsset() async {
    final myData = await rootBundle.loadString("asset/dreamss.csv");
    List<List<dynamic>> csvTable = CsvToListConverter().convert(myData);

    return csvTable;
  }
  void load() async{
    var newdata = await loadAsset();
    setState(() {
      data = newdata;
    });
    print("am i still being called called ");
  }

  @override
  Widget build(BuildContext context) {

    load();

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Apps"),),
        //floatingActionButton: FloatingActionButton( onPressed: load,child: Icon(Icons.refresh),),
        body: ListView(
          children: <Widget>[
            Container(margin: EdgeInsets.only(top: 20.0),),
        Table(
          border: TableBorder.all(width: 1.0,color: Colors.black),
          children: data.map((item){
            return TableRow(
              children: item.map((row){
                return Text(row.toString(),style: TextStyle(fontSize: 20.0,fontWeight: FontWeight.w900),);
              }).toList(),
            );
          }).toList(),
        ),
    ]),
    ));
  }
}

</code>```

答:
Here is the solution. </p>

```<code>@override
void initState() {
  super.initState();
  load(); // use it here
}

@override
Widget build(BuildContext context) {
  return MaterialApp(...); // no need to call initState() here
}
</code>```

Body:
I am making an app which loads the CSV and show the table on the screen but the load function is being called infinitely in the build state can anyone know how to fix it I wanted to call only once but my code called it many times.

Here is the console screenshot:

Here is the code:

import 'package:flutter/material.dart';
import 'package:csv/csv.dart';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;

class TableLayout extends StatefulWidget {
  @override
  _TableLayoutState createState() => _TableLayoutState();
}
class _TableLayoutState extends State<TableLayout> {

  List<List<dynamic>> data = [];

  loadAsset() async {
    final myData = await rootBundle.loadString("asset/dreamss.csv");
    List<List<dynamic>> csvTable = CsvToListConverter().convert(myData);

    return csvTable;
  }
  void load() async{
    var newdata = await loadAsset();
    setState(() {
      data = newdata;
    });
    print("am i still being called called ");
  }

  @override
  Widget build(BuildContext context) {

    load();

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Apps"),),
        //floatingActionButton: FloatingActionButton( onPressed: load,child: Icon(Icons.refresh),),
        body: ListView(
          children: <Widget>[
            Container(margin: EdgeInsets.only(top: 20.0),),
        Table(
          border: TableBorder.all(width: 1.0,color: Colors.black),
          children: data.map((item){
            return TableRow(
              children: item.map((row){
                return Text(row.toString(),style: TextStyle(fontSize: 20.0,fontWeight: FontWeight.w900),);
              }).toList(),
            );
          }).toList(),
        ),
    ]),
    ));
  }
}

Body:
Here is the solution.

@override
void initState() {
  super.initState();
  load(); // use it here
}

@override
Widget build(BuildContext context) {
  return MaterialApp(...); // no need to call initState() here
}


问:
How to retrieve the column index in ag-grid?
In ag-grid, when I want to retrieve the row index I use:

```<code>params.node.id
</code>```

However, I couldn't find a way to do the same for columns.
All that I found is retrieve the columnId which refers to the field variable in the column definition.

I.e: If this is the column definition:

```<code> {
   headerName: "checkButton 2",
   field: "checkbuttonTwo",
   cellRenderer: "checkButtonComponent",
   width: 150
 }
</code>```

This:

```<code>params.column.getId()
</code>```

Would return:

```<code> checkbuttonTwo
</code>```

So my question is:

Is there any way to retrieve the column index?
For example: For the second column I would have 2 and so on and so forth.

Thank you

答:
For each column,
You can define a unique id this way:  </p>

```<code>{
          headerName: "Axa premises",
          field: "axPr",
          width: 150,
          id:0,
          cellRenderer:'iasaCheckboxRendererComponent'
            }
</code>```

<p>And you can access it in this manner:  </p>

```<code>this.params.column.colDef.id
</code>```

Body:
In ag-grid, when I want to retrieve the row index I use:

params.node.id

However, I couldn't find a way to do the same for columns.
All that I found is retrieve the columnId which refers to the field variable in the column definition.

I.e: If this is the column definition:

 {
   headerName: "checkButton 2",
   field: "checkbuttonTwo",
   cellRenderer: "checkButtonComponent",
   width: 150
 }

This:

params.column.getId()

Would return:

 checkbuttonTwo

So my question is:

Is there any way to retrieve the column index?
For example: For the second column I would have 2 and so on and so forth.

Thank you

Body:
For each column,
You can define a unique id this way:

{
          headerName: "Axa premises",
          field: "axPr",
          width: 150,
          id:0,
          cellRenderer:'iasaCheckboxRendererComponent'
            }

And you can access it in this manner:

this.params.column.colDef.id


问:
Set fact with dynamic key name in ansible
I am trying to shrink several chunks of similar code which looks like:

```<code>- ... multiple things is going here
  register: list_register
- name: Generating list
  set_fact: my_list="{{ list_register.results | map(attribute='ansible_facts.list_item') | list }}"

# the same code repeats...
</code>```

The only difference between them is list name instead of my_list.

In fact, I want to do this:

```<code>set_fact:
  "{{ some var }}" : "{{ some value }}"
</code>```

I came across this post but didn't find any answer here.

Is it possible to do so or is there any workaround?

答:
```<code>- set_fact:
    var1={"{{variable_name}}":"{{ some value }}"}
</code>```

This will create a variable "var1" with your dynamic variable key and value.

Example: I used this for creating dynamic tags in AWS Autoscaling group for creating kubernetes tags for the instances like this:

```<code>- name: Dynamic clustertag
  set_fact:
    clustertag={"kubernetes.io/cluster/{{ clustername }}":"owned"}
</code>```

```<code>- name: Create the auto scale group
  ec2_asg:
    .
    .
    .
    tags:
      - "{{ clustertag }}"
</code>```

Body:
I am trying to shrink several chunks of similar code which looks like:

- ... multiple things is going here
  register: list_register
- name: Generating list
  set_fact: my_list="{{ list_register.results | map(attribute='ansible_facts.list_item') | list }}"

# the same code repeats...

The only difference between them is list name instead of my_list.

In fact, I want to do this:

set_fact:
  "{{ some var }}" : "{{ some value }}"

I came across this post but didn't find any answer here.

Is it possible to do so or is there any workaround?

Body:
- set_fact:
    var1={"{{variable_name}}":"{{ some value }}"}

This will create a variable "var1" with your dynamic variable key and value.

Example: I used this for creating dynamic tags in AWS Autoscaling group for creating kubernetes tags for the instances like this:

- name: Dynamic clustertag
  set_fact:
    clustertag={"kubernetes.io/cluster/{{ clustername }}":"owned"}

- name: Create the auto scale group
  ec2_asg:
    .
    .
    .
    tags:
      - "{{ clustertag }}"


问:
Jquery model popup maximize mode issue
I want to open JQuery Dialog in maximized mode.

When I set Width & Height properties of the model window It slightly goes out of inner window & shows up horizontal scollbar. What's wrong in my code

```<code> $("#popupwin").dialog({ width: $(document).width(),
                         height: $(document).height(),
                         resizable: false });
</code>```

答:
I guess you may want to use $(window)?

From jQuery documentation:

```<code>$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document
</code>```

Basically, HTML document can go way longer than the actual window viewport so it doesn't make sense to use $(document) at your case.

Title: Jquery model popup maximize mode issue

Body:
I want to open JQuery Dialog in maximized mode.

When I set Width & Height properties of the model window It slightly goes out of inner window & shows up horizontal scollbar. What's wrong in my code

 $("#popupwin").dialog({ width: $(document).width(),
                         height: $(document).height(),
                         resizable: false });

Body:
I guess you may want to use $(window)?

From jQuery documentation:

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document

Basically, HTML document can go way longer than the actual window viewport so it doesn't make sense to use $(document) at your case.


问:
Client from smart phone sends his/her username and password to a server via HTTP Post without any encryption, is it ok?
In an Android application in a smart phone,

Client sends his/her username and password to a server via HTTP Post

I wonder if it is a good procedure or not to send the username and password via HTTP Post without any encryption?
Is this procedure prone to any kind of attacks or not?

Isn't there any automatic encryption and decryption through HTTP Post from the smart phone to the server that makes sure nobody can see the username and password or not?

I've read some posts on this subject but non of them were about HTTP
  Post through Android smart phone and server and all focused on HTTP through browsers and servers

答: It seems if I utilize https instead of http, everything is fine and there is no need for encryption and nobody can sniff the usernames and passwords sent through Https Post


问:
Regex to match beginning and end of a word with a vowel
I'm trying with the following Regex:

```<code>/^[aeiou]\..*[aeiou]$/
</code>```

But it's not working, I tested "abcda" and didn't match.

Body:
I'm trying with the following Regex:

/^[aeiou]\..*[aeiou]$/

But it's not working, I tested "abcda" and didn't match.

Body:
This will work:

/^([aeiou]).+\1$/


问:
How to solve 'The column label 'Avg_Threat_Score' is not unique.'? issue in pandas
When running the code I am facing following error.
error - The column label 'Avg_Threat_Score' is not unique.

I was creating a pivot table and wanted to sort the value from high to low.

```<code>pt = df.pivot_table(index = 'User Name',values = ['Threat Score', 'Score'],
        aggfunc = {
                   'Threat Score': np.mean,
                   'Score' :[np.mean, lambda x: len(x.dropna())]
                  },
        margins = False)

new_col =['User Name Count', 'AVG_TH_Score', 'Avg_Threat_Score']
pt.columns = [new_col]
#befor this code is working, after that now working
df = df.reindex(pt.sort_values
                    (by = 'Avg_Threat_Score',ascending=False).index)
</code>```

need to sort the values high low for column 'Avg_Threat_Score'

答:
You need pass new columns names by list, not by nested list, because pandas create MultiIndex with one level.

```<code>new_col =['User Name Count', 'AVG_TH_Score', 'Avg_Threat_Score']
pt.columns = [new_col]
</code>```

Is same like:

```<code>pt.columns = [['User Name Count', 'AVG_TH_Score', 'Avg_Threat_Score']]
</code>```

ValueError: The column label 'Avg_Threat_Score' is not unique.

  For a multi-index, the label must be a tuple with elements corresponding to each level.

So use:

```<code>pt.columns = ['User Name Count', 'AVG_TH_Score', 'Avg_Threat_Score']
</code>```

Sample:

```<code>df = pd.DataFrame({
        'User Name':list('ababaa'),
         'Threat Score':[4,5,4,np.nan,5,4],
         'Score':[np.nan,8,9,4,2,np.nan],
         'D':[1,3,5,7,1,0]})

pt = (df.pivot_table(index = 'User Name',values = ['Threat Score', 'Score'],
        aggfunc = {
                   'Threat Score': np.mean,
                   'Score' :[np.mean, lambda x: len(x.dropna())]
                  },
        margins = False))

pt.columns = ['User Name Count', 'AVG_TH_Score', 'Avg_Threat_Score']
print (pt)
           User Name Count  AVG_TH_Score  Avg_Threat_Score
User Name
a                      2.0           5.5              4.25
b                      2.0           6.0              5.00
</code>```

And then for sorting by ordering from Avg_Threat_Score use ordered Categorical for column User Name, so last sort_values working:

```<code>names = pt.sort_values(by = 'Avg_Threat_Score',ascending=False).index
print (names)
#Index(['b', 'a'], dtype='object', name='User Name')

df['User Name'] = pd.CategoricalIndex(df['User Name'], categories=names, ordered=True)
df = df.sort_values('User Name')
</code>```

```<code>print (df)
  User Name  Threat Score  Score  D
1         b           5.0    8.0  3
3         b           NaN    4.0  7
0         a           4.0    NaN  1
2         a           4.0    9.0  5
4         a           5.0    2.0  1
5         a           4.0    NaN  0
</code>```

Body:
When running the code I am facing following error.
error - The column label 'Avg_Threat_Score' is not unique.

I was creating a pivot table and wanted to sort the value from high to low.

pt = df.pivot_table(index = 'User Name',values = ['Threat Score', 'Score'],
        aggfunc = {
                   'Threat Score': np.mean,
                   'Score' :[np.mean, lambda x: len(x.dropna())]
                  },
        margins = False)

new_col =['User Name Count', 'AVG_TH_Score', 'Avg_Threat_Score']
pt.columns = [new_col]
#befor this code is working, after that now working
df = df.reindex(pt.sort_values
                    (by = 'Avg_Threat_Score',ascending=False).index)

need to sort the values high low for column 'Avg_Threat_Score'

Body:
You need pass new columns names by list, not by nested list, because pandas create MultiIndex with one level.

new_col =['User Name Count', 'AVG_TH_Score', 'Avg_Threat_Score']
pt.columns = [new_col]

Is same like:

pt.columns = [['User Name Count', 'AVG_TH_Score', 'Avg_Threat_Score']]

ValueError: The column label 'Avg_Threat_Score' is not unique.

  For a multi-index, the label must be a tuple with elements corresponding to each level.

So use:

pt.columns = ['User Name Count', 'AVG_TH_Score', 'Avg_Threat_Score']

Sample:

df = pd.DataFrame({
        'User Name':list('ababaa'),
         'Threat Score':[4,5,4,np.nan,5,4],
         'Score':[np.nan,8,9,4,2,np.nan],
         'D':[1,3,5,7,1,0]})

pt = (df.pivot_table(index = 'User Name',values = ['Threat Score', 'Score'],
        aggfunc = {
                   'Threat Score': np.mean,
                   'Score' :[np.mean, lambda x: len(x.dropna())]
                  },
        margins = False))

pt.columns = ['User Name Count', 'AVG_TH_Score', 'Avg_Threat_Score']
print (pt)
           User Name Count  AVG_TH_Score  Avg_Threat_Score
User Name
a                      2.0           5.5              4.25
b                      2.0           6.0              5.00

And then for sorting by ordering from Avg_Threat_Score use ordered Categorical for column User Name, so last sort_values working:

names = pt.sort_values(by = 'Avg_Threat_Score',ascending=False).index
print (names)
#Index(['b', 'a'], dtype='object', name='User Name')

df['User Name'] = pd.CategoricalIndex(df['User Name'], categories=names, ordered=True)
df = df.sort_values('User Name')

print (df)
  User Name  Threat Score  Score  D
1         b           5.0    8.0  3
3         b           NaN    4.0  7
0         a           4.0    NaN  1
2         a           4.0    9.0  5
4         a           5.0    2.0  1
5         a           4.0    NaN  0


问:
How to do periodic polling/query to database in every 5 sec in background in ruby on rails
I have a ruby on rails application which sends push notifications based on new records created in database in every 5 seconds. Is there any way apart from CRON jobs to do polling/query in DB to check for new records.

My current code implementation is running CRON evey minute which sleeps for 5 seconds, but this approach taking huge memory consumption.

```<code>schedule.rb #whenever gem file

 every 1.minute do
  runner "DailyNotificationChecker.send_notifications"
end
</code>```

*
    ### below code calls method process_notes every 5 sec

```<code>    def self.send_notifications
        expiry_time = Time.now + 57
        while (Time.now < expiry_time)
            if RUN_SCHEDULER == "true" || RUN_SCHEDULER == true
              process_notes  #calls method mentioned below
            end
          sleep 5 #seconds
        end
      end

 ### below code check for new records and sends notification

    def self.process_notes
      notes = nil
      time = Benchmark.measure do
        Note.uncached do
          notes = Note.where("(created_at > DATE_SUB(now(), INTERVAL 2 minute)) AND `notes`.`processed` = 0")
          if notes.present?
            note_ids = notes.collect{|x| x.id}
            RealtimeNotifier.new.delay.perform(note_ids,NOTE_CREATED,TEMP_USER_NOTE)
          end
        end
      end
    end
</code>```

This code snippet is working but not an optimised solution. Is there a better way to achieve this.

答:
I have a ruby on rails application which sends push notifications based on new records created in database in every 5 seconds.

So you currently have a job/process that sits in memory and polls database, then does something about new records. How about inverting the workflow? Some other part of your code creates those records, yes? Also make that part put a new RealtimeNotifier job in the queue. Cut out the middleman*, so to say.

* yes, the code is now more coupled, but also easier to reason about.

Body:
I have a ruby on rails application which sends push notifications based on new records created in database in every 5 seconds. Is there any way apart from CRON jobs to do polling/query in DB to check for new records.

My current code implementation is running CRON evey minute which sleeps for 5 seconds, but this approach taking huge memory consumption.

schedule.rb #whenever gem file

 every 1.minute do
  runner "DailyNotificationChecker.send_notifications"
end

*
    ### below code calls method process_notes every 5 sec

    def self.send_notifications
        expiry_time = Time.now + 57
        while (Time.now < expiry_time)
            if RUN_SCHEDULER == "true" || RUN_SCHEDULER == true
              process_notes  #calls method mentioned below
            end
          sleep 5 #seconds
        end
      end

 ### below code check for new records and sends notification

    def self.process_notes
      notes = nil
      time = Benchmark.measure do
        Note.uncached do
          notes = Note.where("(created_at > DATE_SUB(now(), INTERVAL 2 minute)) AND `notes`.`processed` = 0")
          if notes.present?
            note_ids = notes.collect{|x| x.id}
            RealtimeNotifier.new.delay.perform(note_ids,NOTE_CREATED,TEMP_USER_NOTE)
          end
        end
      end
    end

This code snippet is working but not an optimised solution. Is there a better way to achieve this.


问:
Extension of STL container through composition or free functions?
Say I need a new type in my application, that consists of a std::vector<int> extended by a single function. The straightforward way would be composition (due to limitations in inheritance of STL containers):

```<code>class A {
    public:
        A(std::vector<int> & vec) : vec_(vec) {}
        int hash();
    private:
        std::vector<int> vec_
}
</code>```

This requires the user to first construct a vector<int> and a copy in the constructor, which is bad when we are going to handle a sizeable number of large vectors. One could, of course, write a pass-through to push_back(), but this introduces mutable state, which I would like to avoid.

So it seems to me, that we can either avoid copies or keep A immutable, is this correct?

If so, the simplest (and efficiency-wise equivalent) way would be to use a typedef and free functions at namespace scope:

```<code>namespace N {
typedef std::vector<int> A;
int a_hash(const A & a);
}
</code>```

This just feels wrong somehow, since extensions in the future will "pollute" the namespace. Also, calling a_hash(...) on any vector<int> is possible, which might lead to unexpected results (assuming that we impose constraints on A the user has to follow or that would otherwise be enforced in the first example)

My two questions are:

how can one not sacrifice both immutability and efficiency when using the above class code?

when does it make sense to use free functions as opposed to encapsulation in classes/structs?

Thank you!

答:
Ad immutable: You could use the range constructor of vector and create an input iterator to provide the content for the vector. The range constructor is just:

```<code>template <typename I>
A::A(I const &begin, I const &end) : vec_(begin, end) {}
</code>```

The generator is a bit more tricky. If you now have a loop that constructs a vector using push_back, it takes quite a bit of rewriting to convert to object that returns one item at a time from a method. Than you need to wrap a reference to it in a valid input iterator.

Ad free functions: Due to overloading, polluting the namespace is usually not a problem, because the symbol will only be considered for a call with the specific argument type.

Also free functions use the argument-dependent lookup. That means the function should be placed in the namespace the class is in. Like:

```<code>#include <vector>
namespace std {
    int hash(vector<int> const &vec) { /*...*/ }
}
//...
std::vector<int> v;
//...
hash(v);
</code>```

Now you can still call hash unqualified, but don't see it for any other purpose unless you do using namespace std (I personally almost never do that and either just use the std:: prefix or do using std::vector to get just the symbol I want). Unfortunately I am not sure how the namespace-dependent lookup works with typedef in another namespace.

In many template algorithms, free functions—and with fairly generic names—are often used instead of methods, because they can be added to existing classes, can be defined for primitive types or both.

Body:
Say I need a new type in my application, that consists of a std::vector<int> extended by a single function. The straightforward way would be composition (due to limitations in inheritance of STL containers):

class A {
    public:
        A(std::vector<int> & vec) : vec_(vec) {}
        int hash();
    private:
        std::vector<int> vec_
}

This requires the user to first construct a vector<int> and a copy in the constructor, which is bad when we are going to handle a sizeable number of large vectors. One could, of course, write a pass-through to push_back(), but this introduces mutable state, which I would like to avoid.

So it seems to me, that we can either avoid copies or keep A immutable, is this correct?

If so, the simplest (and efficiency-wise equivalent) way would be to use a typedef and free functions at namespace scope:

namespace N {
typedef std::vector<int> A;
int a_hash(const A & a);
}

This just feels wrong somehow, since extensions in the future will "pollute" the namespace. Also, calling a_hash(...) on any vector<int> is possible, which might lead to unexpected results (assuming that we impose constraints on A the user has to follow or that would otherwise be enforced in the first example)

My two questions are:

how can one not sacrifice both immutability and efficiency when using the above class code?

when does it make sense to use free functions as opposed to encapsulation in classes/structs?

Thank you!

Body:
Ad immutable: You could use the range constructor of vector and create an input iterator to provide the content for the vector. The range constructor is just:

template <typename I>
A::A(I const &begin, I const &end) : vec_(begin, end) {}

The generator is a bit more tricky. If you now have a loop that constructs a vector using push_back, it takes quite a bit of rewriting to convert to object that returns one item at a time from a method. Than you need to wrap a reference to it in a valid input iterator.

Ad free functions: Due to overloading, polluting the namespace is usually not a problem, because the symbol will only be considered for a call with the specific argument type.

Also free functions use the argument-dependent lookup. That means the function should be placed in the namespace the class is in. Like:

#include <vector>
namespace std {
    int hash(vector<int> const &vec) { /*...*/ }
}
//...
std::vector<int> v;
//...
hash(v);

Now you can still call hash unqualified, but don't see it for any other purpose unless you do using namespace std (I personally almost never do that and either just use the std:: prefix or do using std::vector to get just the symbol I want). Unfortunately I am not sure how the namespace-dependent lookup works with typedef in another namespace.

In many template algorithms, free functions—and with fairly generic names—are often used instead of methods, because they can be added to existing classes, can be defined for primitive types or both.


问:
Protocol buffers: read only fields?
Is it possible to mark fields as read only in a .proto file such that when the code is generated, these fields do not have setters?</p>

答:
Ultimately, I think the answer here will be "no". There's a good basic guidance rule that applies to DTOs:

DTOs should generally be as simple as possible to convey the data for serialization in a manner well-suited to the specific serializer.

if that basic model is sufficient for you to work with above that layer, then fine

but if not: do not fight the serializer; instead, create a separate domain model above the DTO layer, and simply map between the two models before serialization or after deserialization

Or put another way: the fact that the generator doesn't want to expose read-only members is irrelevant, because if you need something exotic, you shouldn't be using the generated type outside of the code that directly touches serialization. So: in your domain type that mirrors the DTO: make it read-only there.

As for why read-only fields aren't usually a thing in serialization tools: you presumably want to be able to give it a value. Serialization tools usually want to be able to write everything they can read, and read everything they can write.

Minor note for completeness since you mention C#: if you are using a code-first approach with protobuf-net, it'll work fine with {get;}-only auto-props, and with {get;}-only manual props if all public members trivially map to an obvious constructor.

Title: Protocol buffers: read only fields?


问:
button href is ignoring everything after question mark
I have this button

```<code><button href="account.html?gto=4356">go to</button>
</code>```

On click it redirects to ./account.html?# though i was expecting ./account.html?gto=4356.

Why is it ignoring everything after the question mark and how can I make this work?

答:
You Have to do it like this

<button>go to</button>```

I hope this works for you! regards

Body:
I have this button

<button href="account.html?gto=4356">go to</button>

On click it redirects to ./account.html?# though i was expecting ./account.html?gto=4356.

Why is it ignoring everything after the question mark and how can I make this work?

Body:
You Have to do it like this

<button><a href="/account.html?gto=4356">go to</a></button>

I hope this works for you! regards


问:
How to implement D3 scales to have children inherit colour from parent with graduations?
I have a D3.js tree that have different colours applied to nodes and links.

The colouring is hardcoded:

```<code>nodeUpdate.select("circle")
      .attr("r", 10)
       .style("fill", function(d) {
     if(d.name == "Top Level") {
      return d._children ? "blue" : "#fff";
      }
    if(d.name == "Second A") {
     return d._children ? "red" : "#fff";
    }
      if(d.name == "Second B") {
      return d._children ? "green" : "#fff";
      }
    if(d.name == "Second C") {
      return d._children ? "purple" : "#fff";
      }
      if(d.name == "Second D") {
      return d._children ? "gold" : "#fff";
      }
    })
     .style("stroke", function(d) {
     if(d.name == "Top Level") {
      return "blue";
      }
    if(d.name == "Second A") {
     return "red";
    }
      if(d.name == "Second B") {
      return "green";
      }
    if(d.name == "Second C") {
      return "purple";
      }
      if(d.name == "Second D") {
      return "gold";
      }
    });
</code>```

and

```<code>link.enter().insert("path", "g")
      .attr("class", "link")
      .attr("stroke-width", function(d){
        return 1;
      })
      .attr("d", function(d) {
        var o = {x: source.x0, y: source.y0};
        return diagonal({source: o, target: o});
      })
    .style("stroke", function(d) {
      return linkColor(d.target.name);
    });
</code>```

and

```<code>function linkColor(node_name) {
    switch (node_name)
    {
      case 'Second A': case 'Third A':  case 'Third B':
        return 'red';
        break;
      case 'Second B': case 'Third C':  case 'Third D':
        return 'green';
        break;
      case 'Second C': case 'Third E':  case 'Third F':
        return 'purple';
        break;
      case 'Second D': case 'Third G':  case 'Third H':
        return 'gold';
    }
}
</code>```

See fiddle

Rather than hardcoding the colour of each node and link, I want to implement d3-scale to colour the nodes and lines. The solution would have the children 'inherit' their parent's colour along a graduation of that colour automatically given x number of children.

https://www.d3indepth.com/scales/

How can I achieve this?

As always, thanks for your help.

答:
The scale you need is an ordinal scale, like this:

```<code>var colourScale = d3.scale.ordinal()
    .domain(["Top Level","Second A", "Second B", "Second C", "Second D"])
    .range(["blue","red", "green", "purple", "gold"]);
</code>```

Then, you can change this whole thing...

```<code>.style("fill", function(d) {
    if (d.name == "Top Level") {
        return d._children ? "blue" : "#fff";
    }
    if (d.name == "Second A") {
        return d._children ? "red" : "#fff";
    }
    if (d.name == "Second B") {
        return d._children ? "green" : "#fff";
    }
    if (d.name == "Second C") {
        return d._children ? "purple" : "#fff";
    }
    if (d.name == "Second D") {
        return d._children ? "gold" : "#fff";
    }
})
</code>```

...into just:

```<code>.style("fill", function(d) {
    return colourScale(d.name)
})
</code>```

And also get rid of that linkColor function.

Pay attention to the fact that, despite you have linked D3 v5 documentation, you're using D3 v3.

Here is your code with that change:

var treeData = [{
  "name": "Top Level",
  "children": [{
    "name": "Second A",
    "children": [{
      "name": "Third A"
    }, {
      "name": "Third B"
    }]
  }, {
    "name": "Second B",
    "children": [{
      "name": "Third C"
    }, {
      "name": "Third D"
    }]
  }, {
    "name": "Second C",
    "children": [{
      "name": "Third E"
    }, {
      "name": "Third F"
    }]
  }, {
    "name": "Second D",
    "children": [{
      "name": "Third G"
    }, {
      "name": "Third H"
    }, ]
  }, ]
}];

var colourScale = d3.scale.ordinal()
  .domain(["Top Level", "Second A", "Second B", "Second C", "Second D"])
  .range(["blue", "red", "green", "purple", "gold"]);

// ************** Generate the tree diagram  *****************
var margin = {
    top: 20,
    right: 120,
    bottom: 20,
    left: 120
  },
  width = 960 - margin.right - margin.left,
  height = 500 - margin.top - margin.bottom;

var i = 0,
  duration = 750,
  root;

var tree = d3.layout.tree()
  .size([height, width]);

var diagonal = d3.svg.diagonal()
  .projection(function(d) {
    return [d.y, d.x];
  });

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.right + margin.left)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

root = treeData[0];
root.x0 = height / 2;
root.y0 = 0;

update(root);

d3.select(self.frameElement).style("height", "500px");

// Collapse after the second level
root.children.forEach(collapse);

update(root);

// Collapse the node and all it's children
function collapse(d) {
  if (d.children) {
    d._children = d.children
    d._children.forEach(collapse)
    d.children = null
  }
}

function update(source) {

  // Compute the new tree layout.
  var nodes = tree.nodes(root).reverse(),
    links = tree.links(nodes);

  // Normalize for fixed-depth.
  nodes.forEach(function(d) {
    d.y = d.depth * 180;
  });

  // Update the nodes…
  var node = svg.selectAll("g.node")
    .data(nodes, function(d) {
      return d.id || (d.id = ++i);
    });

  // Enter any new nodes at the parent's previous position.
  var nodeEnter = node.enter().append("g")
    .attr("class", "node")
    .attr("transform", function(d) {
      return "translate(" + source.y0 + "," + source.x0 + ")";
    })
    .on("click", click);

  nodeEnter.append("circle")
    .attr("r", 1e-6)
    .style("fill", function(d) {
      return d._children ? "#C0C0C0" : "#fff";
    });

  nodeEnter.append("text")
    .attr("x", function(d) {
      return d.children || d._children ? -13 : 13;
    })
    .attr("dy", ".35em")
    .attr("text-anchor", function(d) {
      return d.children || d._children ? "end" : "start";
    })
    .text(function(d) {
      return d.name;
    })
    .style("fill-opacity", 1e-6);

  // Transition nodes to their new position.
  var nodeUpdate = node.transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + d.y + "," + d.x + ")";
    });

  nodeUpdate.select("circle")
    .attr("r", 10)
    .style("fill", function(d) {
      return d.depth === 2 ? colourScale(d.parent.name) : colourScale(d.name);
    })
    .style("stroke", function(d) {
      return d.depth === 2 ? colourScale(d.parent.name) : colourScale(d.name);
    });

  nodeUpdate.select("text")
    .style("fill-opacity", 1);

  // Transition exiting nodes to the parent's new position.
  var nodeExit = node.exit().transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + source.y + "," + source.x + ")";
    })
    .remove();

  nodeExit.select("circle")
    .attr("r", 1e-6);

  nodeExit.select("text")
    .style("fill-opacity", 1e-6);

  // Update the links…
  var link = svg.selectAll("path.link")
    .data(links, function(d) {
      return d.target.id;
    });

  // Enter any new links at the parent's previous position.
  link.enter().insert("path", "g")
    .attr("class", "link")
    .attr("stroke-width", function(d) {
      return 1;
    })
    .attr("d", function(d) {
      var o = {
        x: source.x0,
        y: source.y0
      };
      return diagonal({
        source: o,
        target: o
      });
    })
    .style("stroke", function(d) {
      return d.target.depth === 2 ? colourScale(d.target.parent.name) : colourScale(d.target.name);
    });

  // Transition links to their new position.
  link.transition()
    .duration(duration)
    .attr("d", diagonal);

  // Transition exiting nodes to the parent's new position.
  link.exit().transition()
    .duration(duration)
    .attr("d", function(d) {
      var o = {
        x: source.x,
        y: source.y
      };
      return diagonal({
        source: o,
        target: o
      });
    })
    .remove();

  // Stash the old positions for transition.
  nodes.forEach(function(d) {
    d.x0 = d.x;
    d.y0 = d.y;
  });
}

// Toggle children on click.
function click(d) {
  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }
  update(d);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.node {
  cursor: pointer;
}

.node circle {
  fill: #fff;
  stroke: #C0C0C0;
  stroke-width: 1.5px;
}

.node text {
  font: 10px sans-serif;
}

.link {
  fill: none;
  stroke: #C0C0C0;
  stroke-width: 1.5px;
}</code>```

```

Body:
I have a D3.js tree that have different colours applied to nodes and links.

The colouring is hardcoded:

nodeUpdate.select("circle")
      .attr("r", 10)
       .style("fill", function(d) {
     if(d.name == "Top Level") {
      return d._children ? "blue" : "#fff";
      }
    if(d.name == "Second A") {
     return d._children ? "red" : "#fff";
    }
      if(d.name == "Second B") {
      return d._children ? "green" : "#fff";
      }
    if(d.name == "Second C") {
      return d._children ? "purple" : "#fff";
      }
      if(d.name == "Second D") {
      return d._children ? "gold" : "#fff";
      }
    })
     .style("stroke", function(d) {
     if(d.name == "Top Level") {
      return "blue";
      }
    if(d.name == "Second A") {
     return "red";
    }
      if(d.name == "Second B") {
      return "green";
      }
    if(d.name == "Second C") {
      return "purple";
      }
      if(d.name == "Second D") {
      return "gold";
      }
    });

and

link.enter().insert("path", "g")
      .attr("class", "link")
      .attr("stroke-width", function(d){
        return 1;
      })
      .attr("d", function(d) {
        var o = {x: source.x0, y: source.y0};
        return diagonal({source: o, target: o});
      })
    .style("stroke", function(d) {
      return linkColor(d.target.name);
    });

and

function linkColor(node_name) {
    switch (node_name)
    {
      case 'Second A': case 'Third A':  case 'Third B':
        return 'red';
        break;
      case 'Second B': case 'Third C':  case 'Third D':
        return 'green';
        break;
      case 'Second C': case 'Third E':  case 'Third F':
        return 'purple';
        break;
      case 'Second D': case 'Third G':  case 'Third H':
        return 'gold';
    }
}

See fiddle

Rather than hardcoding the colour of each node and link, I want to implement d3-scale to colour the nodes and lines. The solution would have the children 'inherit' their parent's colour along a graduation of that colour automatically given x number of children.

https://www.d3indepth.com/scales/

How can I achieve this?

As always, thanks for your help.

Body:
The scale you need is an ordinal scale, like this:

var colourScale = d3.scale.ordinal()
    .domain(["Top Level","Second A", "Second B", "Second C", "Second D"])
    .range(["blue","red", "green", "purple", "gold"]);

Then, you can change this whole thing...

.style("fill", function(d) {
    if (d.name == "Top Level") {
        return d._children ? "blue" : "#fff";
    }
    if (d.name == "Second A") {
        return d._children ? "red" : "#fff";
    }
    if (d.name == "Second B") {
        return d._children ? "green" : "#fff";
    }
    if (d.name == "Second C") {
        return d._children ? "purple" : "#fff";
    }
    if (d.name == "Second D") {
        return d._children ? "gold" : "#fff";
    }
})

...into just:

.style("fill", function(d) {
    return colourScale(d.name)
})

And also get rid of that linkColor function.

Pay attention to the fact that, despite you have linked D3 v5 documentation, you're using D3 v3.

Here is your code with that change:

var treeData = [{
  "name": "Top Level",
  "children": [{
    "name": "Second A",
    "children": [{
      "name": "Third A"
    }, {
      "name": "Third B"
    }]
  }, {
    "name": "Second B",
    "children": [{
      "name": "Third C"
    }, {
      "name": "Third D"
    }]
  }, {
    "name": "Second C",
    "children": [{
      "name": "Third E"
    }, {
      "name": "Third F"
    }]
  }, {
    "name": "Second D",
    "children": [{
      "name": "Third G"
    }, {
      "name": "Third H"
    }, ]
  }, ]
}];

var colourScale = d3.scale.ordinal()
  .domain(["Top Level", "Second A", "Second B", "Second C", "Second D"])
  .range(["blue", "red", "green", "purple", "gold"]);

// ************** Generate the tree diagram  *****************
var margin = {
    top: 20,
    right: 120,
    bottom: 20,
    left: 120
  },
  width = 960 - margin.right - margin.left,
  height = 500 - margin.top - margin.bottom;

var i = 0,
  duration = 750,
  root;

var tree = d3.layout.tree()
  .size([height, width]);

var diagonal = d3.svg.diagonal()
  .projection(function(d) {
    return [d.y, d.x];
  });

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.right + margin.left)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

root = treeData[0];
root.x0 = height / 2;
root.y0 = 0;

update(root);

d3.select(self.frameElement).style("height", "500px");

// Collapse after the second level
root.children.forEach(collapse);

update(root);

// Collapse the node and all it's children
function collapse(d) {
  if (d.children) {
    d._children = d.children
    d._children.forEach(collapse)
    d.children = null
  }
}

function update(source) {

  // Compute the new tree layout.
  var nodes = tree.nodes(root).reverse(),
    links = tree.links(nodes);

  // Normalize for fixed-depth.
  nodes.forEach(function(d) {
    d.y = d.depth * 180;
  });

  // Update the nodes…
  var node = svg.selectAll("g.node")
    .data(nodes, function(d) {
      return d.id || (d.id = ++i);
    });

  // Enter any new nodes at the parent's previous position.
  var nodeEnter = node.enter().append("g")
    .attr("class", "node")
    .attr("transform", function(d) {
      return "translate(" + source.y0 + "," + source.x0 + ")";
    })
    .on("click", click);

  nodeEnter.append("circle")
    .attr("r", 1e-6)
    .style("fill", function(d) {
      return d._children ? "#C0C0C0" : "#fff";
    });

  nodeEnter.append("text")
    .attr("x", function(d) {
      return d.children || d._children ? -13 : 13;
    })
    .attr("dy", ".35em")
    .attr("text-anchor", function(d) {
      return d.children || d._children ? "end" : "start";
    })
    .text(function(d) {
      return d.name;
    })
    .style("fill-opacity", 1e-6);

  // Transition nodes to their new position.
  var nodeUpdate = node.transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + d.y + "," + d.x + ")";
    });

  nodeUpdate.select("circle")
    .attr("r", 10)
    .style("fill", function(d) {
      return d.depth === 2 ? colourScale(d.parent.name) : colourScale(d.name);
    })
    .style("stroke", function(d) {
      return d.depth === 2 ? colourScale(d.parent.name) : colourScale(d.name);
    });

  nodeUpdate.select("text")
    .style("fill-opacity", 1);

  // Transition exiting nodes to the parent's new position.
  var nodeExit = node.exit().transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + source.y + "," + source.x + ")";
    })
    .remove();

  nodeExit.select("circle")
    .attr("r", 1e-6);

  nodeExit.select("text")
    .style("fill-opacity", 1e-6);

  // Update the links…
  var link = svg.selectAll("path.link")
    .data(links, function(d) {
      return d.target.id;
    });

  // Enter any new links at the parent's previous position.
  link.enter().insert("path", "g")
    .attr("class", "link")
    .attr("stroke-width", function(d) {
      return 1;
    })
    .attr("d", function(d) {
      var o = {
        x: source.x0,
        y: source.y0
      };
      return diagonal({
        source: o,
        target: o
      });
    })
    .style("stroke", function(d) {
      return d.target.depth === 2 ? colourScale(d.target.parent.name) : colourScale(d.target.name);
    });

  // Transition links to their new position.
  link.transition()
    .duration(duration)
    .attr("d", diagonal);

  // Transition exiting nodes to the parent's new position.
  link.exit().transition()
    .duration(duration)
    .attr("d", function(d) {
      var o = {
        x: source.x,
        y: source.y
      };
      return diagonal({
        source: o,
        target: o
      });
    })
    .remove();

  // Stash the old positions for transition.
  nodes.forEach(function(d) {
    d.x0 = d.x;
    d.y0 = d.y;
  });
}

// Toggle children on click.
function click(d) {
  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }
  update(d);
}

.node {
  cursor: pointer;
}

.node circle {
  fill: #fff;
  stroke: #C0C0C0;
  stroke-width: 1.5px;
}

.node text {
  font: 10px sans-serif;
}

.link {
  fill: none;
  stroke: #C0C0C0;
  stroke-width: 1.5px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>