问:
tensorflow implementation is much slower than pytorch (with slow gpu utility) and occupy more memory
I am trying to converting a pytorch implementation to tensorflow, but I found that the program occupies more memory, has lower gpu utility and is much more slower than pytorch version. I am wondering it is a general case, or I am wrong with the tf model structure?

I put the code on, it can be directly run.
https://colab.research.google.com/drive/1oI6GVnt3sAULvbMMAGTY4B6LsHguJd9U#scrollTo=DNH5pPynm-jm

The pytorch version uses half memory with twice gpu util compared with tf version.

Code:

```<code>import math
import os
import tensorflow as tf
import json
import numpy as np
import time

def calc_diffusion_step_embedding(diffusion_steps, diffusion_step_embed_dim_in):

    assert diffusion_step_embed_dim_in % 2 == 0

    half_dim = diffusion_step_embed_dim_in // 2
    _embed = tf.math.log(tf.convert_to_tensor(10000.0)) / (half_dim - 1)

    _embed = tf.math.exp(tf.cast(tf.experimental.numpy.arange(start = 0,stop = half_dim),dtype = tf.float32) * -_embed)
    _embed = tf.cast(diffusion_steps,dtype=tf.float32) * _embed
    diffusion_step_embed = tf.concat((tf.math.sin(_embed),
                                      tf.math.cos(_embed)), 1)

    assert diffusion_step_embed.shape[0] == diffusion_steps.shape[0]
    assert diffusion_step_embed.shape[1] == diffusion_step_embed_dim_in

    return diffusion_step_embed

class Residual_block(tf.keras.layers.Layer):

    def __init__(self, res_channels, skip_channels,
                 diffusion_step_embed_dim_out, in_channels,
                s4_lmax,
                s4_d_state,
                s4_dropout,
                s4_bidirectional,
                s4_layernorm):

        super(Residual_block, self).__init__()

        self.res_channels = res_channels
        self.fc_t = tf.keras.layers.Dense(self.res_channels)

        self.conv_layer = tf.keras.layers.Conv1D(filters=2 * self.res_channels, kernel_size=3, padding = 'SAME',use_bias=False, kernel_initializer='he_normal', data_format='channels_first')

        self.cond_conv = tf.keras.layers.Conv1D(filters=2*self.res_channels, kernel_size=1, padding = 'SAME',use_bias=False, kernel_initializer='he_normal', data_format='channels_first')
        self.res_conv1 = tf.keras.layers.Conv1D(filters=res_channels, kernel_size=1, padding = 'SAME',use_bias=False, kernel_initializer='he_normal', data_format='channels_first')
        self.res_conv2 = tf.keras.layers.Conv1D(filters=skip_channels, kernel_size=1, padding = 'SAME',use_bias=False, kernel_initializer='he_normal', data_format='channels_first')

    def call(self, input_data):

        x, cond, diffusion_step_embed = input_data
        h = x
        B, C, L = h.shape

        part_t = self.fc_t(diffusion_step_embed)
        part_t = tf.reshape(part_t,[B, self.res_channels, 1])
        h = h + part_t

        h = self.conv_layer(h)
        cond = self.cond_conv(cond)
        h += cond

        out = tf.math.tanh(h[:,:self.res_channels,:]) * tf.math.sigmoid(h[:,self.res_channels:,:])

        res = self.res_conv1(out)
        skip = self.res_conv2(out)

        return (x + res) * tf.math.sqrt(0.5), skip  # normalize for training stability

class Residual_group(tf.keras.Model):

    def __init__(self, res_channels, skip_channels, num_res_layers,
                 diffusion_step_embed_dim_in,
                 diffusion_step_embed_dim_mid,
                 diffusion_step_embed_dim_out,
                 in_channels,
                 s4_lmax,
                 s4_d_state,
                 s4_dropout,
                 s4_bidirectional,
                 s4_layernorm):

        super(Residual_group, self).__init__()

        self.num_res_layers = num_res_layers
        self.diffusion_step_embed_dim_in = diffusion_step_embed_dim_in

        self.fc_t1 = tf.keras.layers.Dense(diffusion_step_embed_dim_mid)
        self.fc_t2 = tf.keras.layers.Dense(diffusion_step_embed_dim_out)

        self.residual_blocks = []

        for n in range(self.num_res_layers):
            self.residual_blocks.append(Residual_block(res_channels, skip_channels,
                                                       diffusion_step_embed_dim_out=diffusion_step_embed_dim_out,
                                                       in_channels=in_channels,
                                                       s4_lmax=s4_lmax,
                                                       s4_d_state=s4_d_state,
                                                       s4_dropout=s4_dropout,
                                                       s4_bidirectional=s4_bidirectional,
                                                       s4_layernorm=s4_layernorm))

    def call(self, input_data):

        h, conditional, diffusion_steps = input_data

        diffusion_step_embed = calc_diffusion_step_embedding(diffusion_steps, self.diffusion_step_embed_dim_in)

        diffusion_step_embed = tf.keras.activations.swish((self.fc_t1(diffusion_step_embed)))
        diffusion_step_embed = tf.keras.activations.swish((self.fc_t2(diffusion_step_embed)))

        #out = self.residual_blocks((h, tf.zeros((8,256,248)),conditional, diffusion_step_embed))
        #skip = out[1]
        skip = tf.zeros((8,256,248))
        for n in range(self.num_res_layers):
            h, skip_n = self.residual_blocks[n]((h, conditional, diffusion_step_embed))
            skip += skip_n

        return skip * tf.math.sqrt(1.0 / self.num_res_layers)

class SSSDS4Imputer(tf.keras.Model):

    def __init__(self, in_channels, res_channels, skip_channels, out_channels,
                 num_res_layers,
                 diffusion_step_embed_dim_in,
                 diffusion_step_embed_dim_mid,
                 diffusion_step_embed_dim_out,
                 s4_lmax,
                 s4_d_state,
                 s4_dropout,
                 s4_bidirectional,
                 s4_layernorm):

        super(SSSDS4Imputer, self).__init__()

        # convert the dimension of input from (B,in_channels,L) to (B,res_channels,L)
        self.init_conv = tf.keras.layers.Conv1D(filters=res_channels, kernel_size=1, padding = 'SAME',use_bias=False, kernel_initializer='he_normal', data_format='channels_first')

        self.res_channels = res_channels
        self.skip_channels = skip_channels

        self.residual_layer = Residual_group(res_channels=res_channels,
                                             skip_channels=skip_channels,
                                             num_res_layers=num_res_layers,
                                             diffusion_step_embed_dim_in=diffusion_step_embed_dim_in,
                                             diffusion_step_embed_dim_mid=diffusion_step_embed_dim_mid,
                                             diffusion_step_embed_dim_out=diffusion_step_embed_dim_out,
                                             in_channels=in_channels,
                                             s4_lmax=s4_lmax,
                                             s4_d_state=s4_d_state,
                                             s4_dropout=s4_dropout,
                                             s4_bidirectional=s4_bidirectional,
                                             s4_layernorm=s4_layernorm)

        # convert the dimension from (B,skip_channels,L) to (B,out_channels,L)
        self.final_conv1 = tf.keras.layers.Conv1D(filters=skip_channels, kernel_size=1, padding = 'SAME',use_bias=False, kernel_initializer='he_normal', data_format='channels_first')
        self.final_conv2 = tf.keras.layers.Conv1D(filters=out_channels, kernel_size=1, padding = 'SAME',use_bias=False, kernel_initializer='zeros', data_format='channels_first')

    def call(self, input_data):

        x, conditional, mask, diffusion_steps = input_data

        conditional = conditional * mask
        conditional = tf.concat([conditional, tf.cast(mask,dtype=tf.float32)], axis=1)

        x = tf.nn.relu(self.init_conv(x))
        x = self.residual_layer((x, conditional, diffusion_steps))

        y = tf.nn.relu(self.final_conv1(x))
        y = tf.nn.relu(self.final_conv2(y))

        return y

def train_step(X, y, net,loss_fn,optimizer):
    with tf.GradientTape() as tape:
        logits = net(X)
        loss_value = loss_fn(y, logits)
    grads = tape.gradient(loss_value, net.trainable_variables,unconnected_gradients=tf.UnconnectedGradients.ZERO)
    optimizer.apply_gradients(zip(grads, net.trainable_variables))
    return loss_value.numpy()

if __name__ == '__main__':

    model_config = {'in_channels': 12, 'out_channels': 12, 'num_res_layers': 36, 'res_channels': 256, 'skip_channels': 256,
                'diffusion_step_embed_dim_in': 128, 'diffusion_step_embed_dim_mid': 512, 'diffusion_step_embed_dim_out': 512,
                's4_lmax': 250, 's4_d_state': 64, 's4_dropout': 0.0, 's4_bidirectional': 1, 's4_layernorm': 1}

    net = SSSDS4Imputer(**model_config)

    # define optimizer
    optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)

    #training
    n_iter = 0
    #iterator = iter(dataset)
    while n_iter < 150000 + 1:
        #try:
        X = (tf.random.normal([8,12,248], 0, 1, tf.float32, seed=1),tf.random.normal([8,12,248], 0, 1, tf.float32, seed=2),
        tf.random.normal([8,12,248], 0, 1, tf.float32, seed=2),tf.random.normal([8,1], 0, 1, tf.float32, seed=4))
        y = tf.random.normal([8,12,248], 0, 1, tf.float32, seed=1)
        t0 = time.time()
        loss = train_step(X,y,net,tf.keras.losses.MeanSquaredError(),optimizer)
        print(time.time()-t0)

        n_iter += 1

</code>```

The tensorflow version I use is 2.4.1

Body:
I am trying to converting a pytorch implementation to tensorflow, but I found that the program occupies more memory, has lower gpu utility and is much more slower than pytorch version. I am wondering it is a general case, or I am wrong with the tf model structure?

I put the code on, it can be directly run.
https://colab.research.google.com/drive/1oI6GVnt3sAULvbMMAGTY4B6LsHguJd9U#scrollTo=DNH5pPynm-jm

The pytorch version uses half memory with twice gpu util compared with tf version.

Code:

import math
import os
import tensorflow as tf
import json
import numpy as np
import time

def calc_diffusion_step_embedding(diffusion_steps, diffusion_step_embed_dim_in):

    assert diffusion_step_embed_dim_in % 2 == 0

    half_dim = diffusion_step_embed_dim_in // 2
    _embed = tf.math.log(tf.convert_to_tensor(10000.0)) / (half_dim - 1)

    _embed = tf.math.exp(tf.cast(tf.experimental.numpy.arange(start = 0,stop = half_dim),dtype = tf.float32) * -_embed)
    _embed = tf.cast(diffusion_steps,dtype=tf.float32) * _embed
    diffusion_step_embed = tf.concat((tf.math.sin(_embed),
                                      tf.math.cos(_embed)), 1)

    assert diffusion_step_embed.shape[0] == diffusion_steps.shape[0]
    assert diffusion_step_embed.shape[1] == diffusion_step_embed_dim_in

    return diffusion_step_embed

class Residual_block(tf.keras.layers.Layer):

    def __init__(self, res_channels, skip_channels,
                 diffusion_step_embed_dim_out, in_channels,
                s4_lmax,
                s4_d_state,
                s4_dropout,
                s4_bidirectional,
                s4_layernorm):

        super(Residual_block, self).__init__()

        self.res_channels = res_channels
        self.fc_t = tf.keras.layers.Dense(self.res_channels)

        self.conv_layer = tf.keras.layers.Conv1D(filters=2 * self.res_channels, kernel_size=3, padding = 'SAME',use_bias=False, kernel_initializer='he_normal', data_format='channels_first')

        self.cond_conv = tf.keras.layers.Conv1D(filters=2*self.res_channels, kernel_size=1, padding = 'SAME',use_bias=False, kernel_initializer='he_normal', data_format='channels_first')
        self.res_conv1 = tf.keras.layers.Conv1D(filters=res_channels, kernel_size=1, padding = 'SAME',use_bias=False, kernel_initializer='he_normal', data_format='channels_first')
        self.res_conv2 = tf.keras.layers.Conv1D(filters=skip_channels, kernel_size=1, padding = 'SAME',use_bias=False, kernel_initializer='he_normal', data_format='channels_first')

    def call(self, input_data):

        x, cond, diffusion_step_embed = input_data
        h = x
        B, C, L = h.shape

        part_t = self.fc_t(diffusion_step_embed)
        part_t = tf.reshape(part_t,[B, self.res_channels, 1])
        h = h + part_t

        h = self.conv_layer(h)
        cond = self.cond_conv(cond)
        h += cond

        out = tf.math.tanh(h[:,:self.res_channels,:]) * tf.math.sigmoid(h[:,self.res_channels:,:])

        res = self.res_conv1(out)
        skip = self.res_conv2(out)

        return (x + res) * tf.math.sqrt(0.5), skip  # normalize for training stability

class Residual_group(tf.keras.Model):

    def __init__(self, res_channels, skip_channels, num_res_layers,
                 diffusion_step_embed_dim_in,
                 diffusion_step_embed_dim_mid,
                 diffusion_step_embed_dim_out,
                 in_channels,
                 s4_lmax,
                 s4_d_state,
                 s4_dropout,
                 s4_bidirectional,
                 s4_layernorm):

        super(Residual_group, self).__init__()

        self.num_res_layers = num_res_layers
        self.diffusion_step_embed_dim_in = diffusion_step_embed_dim_in

        self.fc_t1 = tf.keras.layers.Dense(diffusion_step_embed_dim_mid)
        self.fc_t2 = tf.keras.layers.Dense(diffusion_step_embed_dim_out)

        self.residual_blocks = []

        for n in range(self.num_res_layers):
            self.residual_blocks.append(Residual_block(res_channels, skip_channels,
                                                       diffusion_step_embed_dim_out=diffusion_step_embed_dim_out,
                                                       in_channels=in_channels,
                                                       s4_lmax=s4_lmax,
                                                       s4_d_state=s4_d_state,
                                                       s4_dropout=s4_dropout,
                                                       s4_bidirectional=s4_bidirectional,
                                                       s4_layernorm=s4_layernorm))

    def call(self, input_data):

        h, conditional, diffusion_steps = input_data

        diffusion_step_embed = calc_diffusion_step_embedding(diffusion_steps, self.diffusion_step_embed_dim_in)

        diffusion_step_embed = tf.keras.activations.swish((self.fc_t1(diffusion_step_embed)))
        diffusion_step_embed = tf.keras.activations.swish((self.fc_t2(diffusion_step_embed)))

        #out = self.residual_blocks((h, tf.zeros((8,256,248)),conditional, diffusion_step_embed))
        #skip = out[1]
        skip = tf.zeros((8,256,248))
        for n in range(self.num_res_layers):
            h, skip_n = self.residual_blocks[n]((h, conditional, diffusion_step_embed))
            skip += skip_n

        return skip * tf.math.sqrt(1.0 / self.num_res_layers)

class SSSDS4Imputer(tf.keras.Model):

    def __init__(self, in_channels, res_channels, skip_channels, out_channels,
                 num_res_layers,
                 diffusion_step_embed_dim_in,
                 diffusion_step_embed_dim_mid,
                 diffusion_step_embed_dim_out,
                 s4_lmax,
                 s4_d_state,
                 s4_dropout,
                 s4_bidirectional,
                 s4_layernorm):

        super(SSSDS4Imputer, self).__init__()

        # convert the dimension of input from (B,in_channels,L) to (B,res_channels,L)
        self.init_conv = tf.keras.layers.Conv1D(filters=res_channels, kernel_size=1, padding = 'SAME',use_bias=False, kernel_initializer='he_normal', data_format='channels_first')

        self.res_channels = res_channels
        self.skip_channels = skip_channels

        self.residual_layer = Residual_group(res_channels=res_channels,
                                             skip_channels=skip_channels,
                                             num_res_layers=num_res_layers,
                                             diffusion_step_embed_dim_in=diffusion_step_embed_dim_in,
                                             diffusion_step_embed_dim_mid=diffusion_step_embed_dim_mid,
                                             diffusion_step_embed_dim_out=diffusion_step_embed_dim_out,
                                             in_channels=in_channels,
                                             s4_lmax=s4_lmax,
                                             s4_d_state=s4_d_state,
                                             s4_dropout=s4_dropout,
                                             s4_bidirectional=s4_bidirectional,
                                             s4_layernorm=s4_layernorm)

        # convert the dimension from (B,skip_channels,L) to (B,out_channels,L)
        self.final_conv1 = tf.keras.layers.Conv1D(filters=skip_channels, kernel_size=1, padding = 'SAME',use_bias=False, kernel_initializer='he_normal', data_format='channels_first')
        self.final_conv2 = tf.keras.layers.Conv1D(filters=out_channels, kernel_size=1, padding = 'SAME',use_bias=False, kernel_initializer='zeros', data_format='channels_first')

    def call(self, input_data):

        x, conditional, mask, diffusion_steps = input_data

        conditional = conditional * mask
        conditional = tf.concat([conditional, tf.cast(mask,dtype=tf.float32)], axis=1)

        x = tf.nn.relu(self.init_conv(x))
        x = self.residual_layer((x, conditional, diffusion_steps))

        y = tf.nn.relu(self.final_conv1(x))
        y = tf.nn.relu(self.final_conv2(y))

        return y

def train_step(X, y, net,loss_fn,optimizer):
    with tf.GradientTape() as tape:
        logits = net(X)
        loss_value = loss_fn(y, logits)
    grads = tape.gradient(loss_value, net.trainable_variables,unconnected_gradients=tf.UnconnectedGradients.ZERO)
    optimizer.apply_gradients(zip(grads, net.trainable_variables))
    return loss_value.numpy()

if __name__ == '__main__':

    model_config = {'in_channels': 12, 'out_channels': 12, 'num_res_layers': 36, 'res_channels': 256, 'skip_channels': 256,
                'diffusion_step_embed_dim_in': 128, 'diffusion_step_embed_dim_mid': 512, 'diffusion_step_embed_dim_out': 512,
                's4_lmax': 250, 's4_d_state': 64, 's4_dropout': 0.0, 's4_bidirectional': 1, 's4_layernorm': 1}

    net = SSSDS4Imputer(**model_config)

    # define optimizer
    optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)

    #training
    n_iter = 0
    #iterator = iter(dataset)
    while n_iter < 150000 + 1:
        #try:
        X = (tf.random.normal([8,12,248], 0, 1, tf.float32, seed=1),tf.random.normal([8,12,248], 0, 1, tf.float32, seed=2),
        tf.random.normal([8,12,248], 0, 1, tf.float32, seed=2),tf.random.normal([8,1], 0, 1, tf.float32, seed=4))
        y = tf.random.normal([8,12,248], 0, 1, tf.float32, seed=1)
        t0 = time.time()
        loss = train_step(X,y,net,tf.keras.losses.MeanSquaredError(),optimizer)
        print(time.time()-t0)

        n_iter += 1

The tensorflow version I use is 2.4.1


来源: stackexchange

问:
Next 13 throwing error on tRPC client promise
I know Next 13 is only in beta, but recently I started experimenting with tRPC and Next's data fetching. I have a server component that queries projects.getAll from my tRPC server and puts them in a Component.
Server Error

Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
Code:

const fetchProjects = async () => {
    const data = await trpcClient.projects.getAll.query();
    return data;
};

const PortfolioSection = async () => {
    const getAllData = await fetchProjects();

    console.log(getAllData);

    return (

Portfolio

                {
                    getAllData &&
                    getAllData?.data?.map(({attributes}: any, projIdx: any) => (

                                <Image
                                    className='object-cover'
                                    src={env.NEXT_PUBLIC_STRAPI_URI + attributes.thumbnail.data.attributes.formats.small.url}
                                    alt='Project thumbnail'
                                    fill />

                                    {(attributes.tags as string).split(',').map((tag, tagIdx) => (
                                        <span
                                            key={tagIdx}
                                            className='rounded-full px-3 py-1 text-sm font-semibold text-gray-700'
                                            style={{background: `#${tag.split('#')[1]}`}}>
                                            {tag.split('#')[0]}

                                    ))}

{attributes.title}

                                    {attributes.blog_post.data.attributes.short}

                                    {
                                        attributes.links.split(', ').map((link: any, linkIdx: any) => {
                                            const [type, href] = link.match(/(?<=\[).+(?=\))/)[0].split('](');
                                            return <Link
                                                key={linkIdx}
                                                href={href}
                                                className='bg-gray-200 px-3 py-1 text-sm font-semibold text-gray-700'
                                                target='_blank'
                                                data-hover>
                                                {
                                                    (() => {
                                                        switch(type) {
                                                        case 'github':
                                                            return <LogoGithub />;
                                                        case 'website':
                                                            return <ContentView />;
                                                        default:
                                                            return <LinkIcon />;
                                                        }
                                                    })()
                                                }
                                            </Link>;
                                        })
                                    }

                    )) || <></>
                }

    );
};
```

The error message:

Server Error

Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

P.S. This example does work with the regular tRPC hooks

ContentLicense: CC BY-SA 4.0

Body:
I know Next 13 is only in beta, but recently I started experimenting with tRPC and Next's data fetching. I have a server component that queries projects.getAll from my tRPC server and puts them in a Component.
Server Error

Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
Code:

const fetchProjects = async () => {
    const data = await trpcClient.projects.getAll.query();
    return data;
};

const PortfolioSection = async () => {
    const getAllData = await fetchProjects();

    console.log(getAllData);

    return (

Portfolio

                {
                    getAllData &&
                    getAllData?.data?.map(({attributes}: any, projIdx: any) => (

                                <Image
                                    className='object-cover'
                                    src={env.NEXT_PUBLIC_STRAPI_URI + attributes.thumbnail.data.attributes.formats.small.url}
                                    alt='Project thumbnail'
                                    fill />

                                    {(attributes.tags as string).split(',').map((tag, tagIdx) => (
                                        <span
                                            key={tagIdx}
                                            className='rounded-full px-3 py-1 text-sm font-semibold text-gray-700'
                                            style={{background: `#${tag.split('#')[1]}`}}>
                                            {tag.split('#')[0]}

                                    ))}

{attributes.title}

                                    {attributes.blog_post.data.attributes.short}

                                    {
                                        attributes.links.split(', ').map((link: any, linkIdx: any) => {
                                            const [type, href] = link.match(/(?<=\[).+(?=\))/)[0].split('](');
                                            return <Link
                                                key={linkIdx}
                                                href={href}
                                                className='bg-gray-200 px-3 py-1 text-sm font-semibold text-gray-700'
                                                target='_blank'
                                                data-hover>
                                                {
                                                    (() => {
                                                        switch(type) {
                                                        case 'github':
                                                            return <LogoGithub />;
                                                        case 'website':
                                                            return <ContentView />;
                                                        default:
                                                            return <LinkIcon />;
                                                        }
                                                    })()
                                                }
                                            </Link>;
                                        })
                                    }

                    )) || <></>
                }

    );
};

The error message:

Server Error

Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

P.S. This example does work with the regular tRPC hooks


问:
difference between working of early binding and late binding in java?
I would like to share first what i know and probably think...

Binding -> Linking between method call and method defination.

It is said that early binding is the example of Method Overloading and
late binding is the example of Method Overriding

But, i was confused as we know that method is invoked after knowing the object type at run time and object is also created at run-time. So, when we write..

Parent obj = new Parent();

```<code>obj.method(int x) // one of the overloaded method
</code>```

now, then in this case also method call should be determined at run-time?

but, they say method overloading is example of early binding? and it is determined already which method is to be called but then it will interfere with what i've said in the above line(which is object is created and runtime so, method invoking will also be decided at run time)

Now, I am sharing what I think..

the method overloading concept is only holded in class scope so it is definitely known that the method with integer parameter will be called.

but, as the inheritance enters and if that

```<code>method(int x)
</code>```

is also overloaded then it comes to the kind of object is at run time.

even if it is not overridden and it calls like this

```<code>Parent obj = new Parent();
</code>```

I think jvm still checks the method to invoke according to the class instantiated.

but I am confused that what I am thinking is true or not. I would also like to know internal working of this.

Body:
I would like to share first what i know and probably think...

Binding -> Linking between method call and method defination.

It is said that early binding is the example of Method Overloading and
late binding is the example of Method Overriding

But, i was confused as we know that method is invoked after knowing the object type at run time and object is also created at run-time. So, when we write..

Parent obj = new Parent();

obj.method(int x) // one of the overloaded method

now, then in this case also method call should be determined at run-time?

but, they say method overloading is example of early binding? and it is determined already which method is to be called but then it will interfere with what i've said in the above line(which is object is created and runtime so, method invoking will also be decided at run time)

Now, I am sharing what I think..

the method overloading concept is only holded in class scope so it is definitely known that the method with integer parameter will be called.

but, as the inheritance enters and if that

method(int x)

is also overloaded then it comes to the kind of object is at run time.

even if it is not overridden and it calls like this

Parent obj = new Parent();

I think jvm still checks the method to invoke according to the class instantiated.

but I am confused that what I am thinking is true or not. I would also like to know internal working of this.


问:
Electron: crypto not defined
Hello – my electron app has one user experiencing the error below.  He's on Windows 10, and has reproduced it on two separate machines.  I can't reproduce, nor have any other users reported this issue.  The electron app is signed for Windows using a Comodo CA certificate.  Originally, it occurred for him only when using electron's built-in autoupdate feature.  Now that he's on the latest version, it occurs at launch – again, on two machines.

UPDATE: I have a second user reporting this now, though I still can't reproduce myself.

I can't seem to find anyone else posting with this error exactly, though I've tried changing the webpack require fallbacks, setting "browser": { "crypto": false }, and a few other things for similar errors (from Module not found: Error: Can't resolve 'crypto').

I'd love some direction to figure out what's going on here and what the fix should be.

Title: Electron: crypto not defined


问:
Why my tests is taking too long to execute?
PASS  src/components/Greet/Greet.spec.tsx (29.13 s)
PASS  src/components/Greet/Greet.test.tsx (35.275 s)

Test Suites: 2 passed, 2 total
Tests:       4 passed, 4 total
Snapshots:   0 total
Time:        100.769 s
Ran all test suites related to changed files.

Watch Usage: Press w to show more.

I have tried using only() in the Greet.test.tsx file but looks like it is also not working !

```<code>import { render, screen } from "@testing-library/react";
import { Greet } from "./Greet";

describe.only("Greet", () => {
  test("renders ok", () => {
    render(<Greet />);
    const textElement = screen.getByText(/hello/i);
    expect(textElement).toBeInTheDocument();
  });

  test("renders a name", () => {
    render(<Greet name="tanmoy" />);
    const textElem = screen.getByText(/hello tanmoy/i);
    expect(textElem).toBeInTheDocument();
  });
});
</code>```

Body:
PASS  src/components/Greet/Greet.spec.tsx (29.13 s)
PASS  src/components/Greet/Greet.test.tsx (35.275 s)

Test Suites: 2 passed, 2 total
Tests:       4 passed, 4 total
Snapshots:   0 total
Time:        100.769 s
Ran all test suites related to changed files.

Watch Usage: Press w to show more.

I have tried using only() in the Greet.test.tsx file but looks like it is also not working !

import { render, screen } from "@testing-library/react";
import { Greet } from "./Greet";

describe.only("Greet", () => {
  test("renders ok", () => {
    render(<Greet />);
    const textElement = screen.getByText(/hello/i);
    expect(textElement).toBeInTheDocument();
  });

  test("renders a name", () => {
    render(<Greet name="tanmoy" />);
    const textElem = screen.getByText(/hello tanmoy/i);
    expect(textElem).toBeInTheDocument();
  });
});


问:
Windows Regedit Profile List
In regedit under

```<code>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
</code>```

What does FullProfile means??

I tried searching it up, but had no luck in finding it's purpose

Title: Windows Regedit Profile List

Body:
In regedit under

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList

What does FullProfile means??

I tried searching it up, but had no luck in finding it's purpose


问:
Pre-formatted input in Kotlin
I'm trying to create a EditText input in Android Studio where the user enters a serial number, which is formatted as:

123456-78

What I'd like to do is make it so the user doesn't have to type the '-' character, and it is already displayed in the input field as they're typing. How can I achieve that?

Title: Pre-formatted input in Kotlin


问:
Why does the listview display the items incorrectly after I remove them in .NET MAUI?
I have recently started programming with .NET MAUI. The elements are correctly removed in the C# list. However, after deleting the remaining elements are only partially displayed. That means that only e.g. the 4th element is displayed. For the other elements only an empty bar is displayed.

My code so far:
XAML:

```<code><VerticalStackLayout>
        <ScrollView>
            <StackLayout>

                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>

                    <Image
                        Grid.Column="0"
                        Source="logo.png"
                        WidthRequest="150"
                        HorizontalOptions="Start"
                        VerticalOptions="Start"/>

                    <Label
                        TextColor="Black"
                        Grid.Column="1"
                        Text="TODO"
                        FontSize="35"
                        HorizontalOptions="Start"
                        VerticalOptions="Start"
                        Margin="23"/>

                </Grid>

                <Grid BackgroundColor="#24D4A3">
                        <Grid.RowDefinitions>
                            <RowDefinition />
                            <RowDefinition />
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition />
                            <ColumnDefinition />
                        </Grid.ColumnDefinitions>

                    <ListView
                    Grid.ColumnSpan="2"
                    Grid.RowSpan="2"
                    RowHeight="100"
                    x:Name="listview">
                    <ListView.ItemTemplate>
                            <DataTemplate >
                            <ViewCell >

                                    <Grid BackgroundColor="#24D4A3">
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="auto"/>
                                        </Grid.RowDefinitions>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="auto"/>
                                        </Grid.ColumnDefinitions>
                                        <Button BackgroundColor="#DEABF5"
                                            Text="{Binding Title}"
                                            Clicked="onNoteSelected"
                                            BorderWidth="2"
                                            TextColor="Black"
                                            FontSize="28"
                                            Margin="20"
                                            CornerRadius="100"
                                            WidthRequest="350"
                                            HeightRequest="70"
                                            HorizontalOptions="Center"
                                            VerticalOptions="Start"/>

                                        <Button
                                            BindingContext="{Binding Id}"
                                            Clicked="ToDoSolved"
                                            BorderWidth="2"
                                            BorderColor="Black"
                                            BackgroundColor="White"
                                            WidthRequest="45"
                                            HeightRequest="45"
                                            CornerRadius="35"
                                            Margin="0,0,260,0"
                                            />
                                    </Grid>
                                </ViewCell>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>

                    <ImageButton
                                Clicked="Settings"
                                Source="settings.png"
                                Grid.Row="0"
                                Grid.Column="2"
                                BorderColor="#2b3c3c"
                                BorderWidth="0"
                                BackgroundColor="#34A4EB"
                                CornerRadius="35"
                                HorizontalOptions="End"
                                WidthRequest="70"
                                HeightRequest="70"
                                Margin="0,10, 10, 0"
                                VerticalOptions="Start"/>
                        <ImageButton
                                Clicked="CreateNote"
                                Source="add.png"
                                Grid.Row="1"
                                Grid.Column="2"
                                BorderColor="#2b3c3c"
                                BorderWidth="0"
                                BackgroundColor="#34A4EB"
                                CornerRadius="35"
                                HorizontalOptions="End"
                                WidthRequest="70"
                                HeightRequest="70"
                                Margin="0,0,10,10"
                                Padding="2,0,0,0"/>
                    </Grid>
            </StackLayout>
        </ScrollView>
    </VerticalStackLayout>
</code>```

C#:

```<code>public partial class MainPage : ContentPage
    {

    private ObservableCollection<Note> notes = new ObservableCollection<Note>();
    public ObservableCollection<Note> Notes
    {
        get { return notes; }
        set { notes = value; }
    }
    public MainPage()
    {
        InitializeComponent();

        notes.Add(new Note(1, "My Note1", "I'm ugly"));
        notes.Add(new Note(2, "My Note2", "I'm short"));
        notes.Add(new Note(3, "My Note3", "I'm smart"));
        notes.Add(new Note(4, "My Note4", "I'm smart"));
        //notes.Add(new Note(6, "My Note6", "I'm smart"));
        //notes.Add(new Note(7, "My Note7", "I'm smart"));
        //notes.Add(new Note(8, "My Note8", "I'm smart"));
        //notes.Add(new Note(9, "My Note9", "I'm smart"));
        this.BindingContext= Notes;
        listview.ItemsSource= Notes;

    }

    private async void CreateNote(object sender, EventArgs e)
    {
        await Shell.Current.GoToAsync("//CreateNote");
    }

    private async void Settings(object sender, EventArgs e)
    {
        await Shell.Current.GoToAsync("//Settings");
    }

    private void ToDoSolved(object sender, EventArgs e)
    {
        Button button= (Button) sender ;

        var id = (int)button.BindingContext;

        var item = Notes.SingleOrDefault(x => x.Id == id);
        if (item != null)
        {
            Notes.Remove(item);
            Console.WriteLine(id);
        }

    }

    async void onNoteSelected(object sender, EventArgs e)
    {
        Button button= (Button) sender ;

        var id = (int)button.BindingContext;

        //await Shell.Current.GoToAsync("NotePage" + id);
    }
}
</code>```

I would be grateful for any help :)

Body:
I have recently started programming with .NET MAUI. The elements are correctly removed in the C# list. However, after deleting the remaining elements are only partially displayed. That means that only e.g. the 4th element is displayed. For the other elements only an empty bar is displayed.

My code so far:
XAML:

<VerticalStackLayout>
        <ScrollView>
            <StackLayout>

                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>

                    <Image
                        Grid.Column="0"
                        Source="logo.png"
                        WidthRequest="150"
                        HorizontalOptions="Start"
                        VerticalOptions="Start"/>

                </Grid>

                <Grid BackgroundColor="#24D4A3">
                        <Grid.RowDefinitions>
                            <RowDefinition />
                            <RowDefinition />
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition />
                            <ColumnDefinition />
                        </Grid.ColumnDefinitions>

                    <ListView
                    Grid.ColumnSpan="2"
                    Grid.RowSpan="2"
                    RowHeight="100"
                    x:Name="listview">
                    <ListView.ItemTemplate>
                            <DataTemplate >
                            <ViewCell >

                                    <Grid BackgroundColor="#24D4A3">
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="auto"/>
                                        </Grid.RowDefinitions>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="auto"/>
                                        </Grid.ColumnDefinitions>
                                        <Button BackgroundColor="#DEABF5"
                                            Text="{Binding Title}"
                                            Clicked="onNoteSelected"
                                            BorderWidth="2"
                                            TextColor="Black"
                                            FontSize="28"
                                            Margin="20"
                                            CornerRadius="100"
                                            WidthRequest="350"
                                            HeightRequest="70"
                                            HorizontalOptions="Center"
                                            VerticalOptions="Start"/>

                                        <Button
                                            BindingContext="{Binding Id}"
                                            Clicked="ToDoSolved"
                                            BorderWidth="2"
                                            BorderColor="Black"
                                            BackgroundColor="White"
                                            WidthRequest="45"
                                            HeightRequest="45"
                                            CornerRadius="35"
                                            Margin="0,0,260,0"
                                            />
                                    </Grid>
                                </ViewCell>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>

                    <ImageButton
                                Clicked="Settings"
                                Source="settings.png"
                                Grid.Row="0"
                                Grid.Column="2"
                                BorderColor="#2b3c3c"
                                BorderWidth="0"
                                BackgroundColor="#34A4EB"
                                CornerRadius="35"
                                HorizontalOptions="End"
                                WidthRequest="70"
                                HeightRequest="70"
                                Margin="0,10, 10, 0"
                                VerticalOptions="Start"/>
                        <ImageButton
                                Clicked="CreateNote"
                                Source="add.png"
                                Grid.Row="1"
                                Grid.Column="2"
                                BorderColor="#2b3c3c"
                                BorderWidth="0"
                                BackgroundColor="#34A4EB"
                                CornerRadius="35"
                                HorizontalOptions="End"
                                WidthRequest="70"
                                HeightRequest="70"
                                Margin="0,0,10,10"
                                Padding="2,0,0,0"/>
                    </Grid>
            </StackLayout>
        </ScrollView>
    </VerticalStackLayout>

C#:

public partial class MainPage : ContentPage
    {

    private ObservableCollection<Note> notes = new ObservableCollection<Note>();
    public ObservableCollection<Note> Notes
    {
        get { return notes; }
        set { notes = value; }
    }
    public MainPage()
    {
        InitializeComponent();

        notes.Add(new Note(1, "My Note1", "I'm ugly"));
        notes.Add(new Note(2, "My Note2", "I'm short"));
        notes.Add(new Note(3, "My Note3", "I'm smart"));
        notes.Add(new Note(4, "My Note4", "I'm smart"));
        //notes.Add(new Note(6, "My Note6", "I'm smart"));
        //notes.Add(new Note(7, "My Note7", "I'm smart"));
        //notes.Add(new Note(8, "My Note8", "I'm smart"));
        //notes.Add(new Note(9, "My Note9", "I'm smart"));
        this.BindingContext= Notes;
        listview.ItemsSource= Notes;

    }

    private async void CreateNote(object sender, EventArgs e)
    {
        await Shell.Current.GoToAsync("//CreateNote");
    }

    private async void Settings(object sender, EventArgs e)
    {
        await Shell.Current.GoToAsync("//Settings");
    }

    private void ToDoSolved(object sender, EventArgs e)
    {
        Button button= (Button) sender ;

        var id = (int)button.BindingContext;

        var item = Notes.SingleOrDefault(x => x.Id == id);
        if (item != null)
        {
            Notes.Remove(item);
            Console.WriteLine(id);
        }

    }

    async void onNoteSelected(object sender, EventArgs e)
    {
        Button button= (Button) sender ;

        var id = (int)button.BindingContext;

        //await Shell.Current.GoToAsync("NotePage" + id);
    }
}

I would be grateful for any help :)


问:
Creating edges and nodes from dataframe for sankey diagram
I've been using Python for a short while to create simple graphs which work fine and I am reasonably confident in that area. But now I have moved on to Sankey diagrams and here I am on deep waters with regards to creating nodes and edges.

I have a list of cases with the following associated values:

a case ID key

the decision

if the decision was a rejection an indication if it was in the bottom, middle or top third

a binary indication if it is a resubmission or not, a foreign key to the associated case ID and a year of the previous case

CaseID
Year
Decision
Reject grade
Resubmission
PreviousApplicationId
Year of prev case

1
2019
Rejection
Top
Yes
434
2018

2
2019
Accepted

No

3
2019
Rejection
Bottom
No

4
2019
Accepted

Yes
632
2018

5
2019
Rejection
Middle
Yes
485
2018

6
2020
Accepted

No

7
2020
Rejection
Top
Yes
5
2019

8
2020
Accepted

No

9
2020
Rejection
Middle
Yes
3
2019

10
2020
Accepted

No

(The above table can be generated thus:

```<code>df = pd.DataFrame( {'CaseID': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9, 9: 10},
'Year': {0: 2019, 1: 2019, 2: 2019, 3: 2019, 4: 2019, 5: 2020, 6: 2020, 7: 2020, 8: 2020, 9: 2020},
'Decision': {0: 'Rejection', 1: 'Accepted', 2: 'Rejection', 3: 'Accepted', 4: 'Rejection', 5: 'Accepted', 6: 'Rejection', 7: 'Accepted', 8: 'Rejection', 9: 'Accepted'},
'Reject grade': {0: 'Top', 1: float('nan'), 2: 'Bottom', 3: float('nan'), 4: 'Middle', 5: float('nan'), 6: 'Top', 7: float('nan'), 8: 'Middle', 9: float('nan')},
'Resubmission': {0: 'Yes', 1: 'No', 2: 'No', 3: 'Yes', 4: 'Yes', 5: 'No', 6: 'Yes', 7: 'No', 8: 'Yes', 9: 'No'},
'PreviousApplicationId': {0: 434.0, 1: float('nan'), 2: float('nan'), 3: 632.0, 4: 485.0, 5: float('nan'), 6: 5.0, 7: float('nan'), 8: 3.0, 9: float('nan')},
'Year of prev case': {0: 2018.0, 1: float('nan'), 2: float('nan'), 3: 2018.0, 4: 2018.0, 5: float('nan'), 6: 2019.0, 7: float('nan'), 8: 2019.0, 9: float('nan')}} )
</code>```

What I am trying to achieve is to see the flow from a case is submitted: Does it get rejected or accepted. If it is rejected, does it end in the top/middle/bottom pile. Does this result in a later resubmission? Overlaying all this is a timeflow, so it is possible to see how this flows over time. Some cases, if they get rejected, are not resubmitted. Others will be resubmitted, not in the following year, but maybe three years later.

I realise I have grasped over a problem that exceeds my current level of Python understanding haha

I used the wrapper function described at https://medium.com/kenlok/how-to-create-sankey-diagrams-from-dataframes-in-python-e221c1b4d6b0 which generated a sankey. So far so good. But unfortunately,  the year column is a variable like so many others, so it ends up being shown on the far left.

I would like for time instead to be shown as an overlay on top, so that the flow also depicts the temporal element.

Image of the Sankey generated by the wrapper function mentioned

Code below:

```<code>import numpy as np
import pandas as pd
import plotly

df = pd.read_excel("data.xlsx")

def genSankey(df,cat_cols=[],value_cols='',title='Sankey Diagram'):
    # maximum of 6 value cols -> 6 colors
    colorPalette = ['#4B8BBE','#306998','#FFE873','#FFD43B','#646464']
    labelList = []
    colorNumList = []
    for catCol in cat_cols:
        labelListTemp =  list(set(df[catCol].values))
        colorNumList.append(len(labelListTemp))
        labelList = labelList + labelListTemp

    # remove duplicates from labelList
    labelList = list(dict.fromkeys(labelList))

    # define colors based on number of levels
    colorList = []
    for idx, colorNum in enumerate(colorNumList):
        colorList = colorList + [colorPalette[idx]]*colorNum

    # transform df into a source-target pair
    for i in range(len(cat_cols)-1):
        if i==0:
            sourceTargetDf = df[[cat_cols[i],cat_cols[i+1],value_cols]]
            sourceTargetDf.columns = ['source','target','count']
        else:
            tempDf = df[[cat_cols[i],cat_cols[i+1],value_cols]]
            tempDf.columns = ['source','target','count']
            sourceTargetDf = pd.concat([sourceTargetDf,tempDf])
        sourceTargetDf = sourceTargetDf.groupby(['source','target']).agg({'count':'sum'}).reset_index()

    # add index for source-target pair
    sourceTargetDf['sourceID'] = sourceTargetDf['source'].apply(lambda x: labelList.index(x))
    sourceTargetDf['targetID'] = sourceTargetDf['target'].apply(lambda x: labelList.index(x))

    # creating the sankey diagram
    data = dict(
        type='sankey',
        node = dict(
          pad = 15,
          thickness = 20,
          line = dict(
            color = "black",
            width = 0.5
          ),
          label = labelList,
          color = colorList
        ),
        link = dict(
          source = sourceTargetDf['sourceID'],
          target = sourceTargetDf['targetID'],
          value = sourceTargetDf['count']
        )
      )

    layout =  dict(
        title = title,
        font = dict(
          size = 10
        )
    )

    fig = dict(data=[data], layout=layout)
    return fig

# Finanslovsaar = Year, Genansøgning = Resubmission, Afgørelse = Decision, Niveuakode = Grade
fig = genSankey(df,cat_cols=['Finanslovsaar', 'Genansøgning', 'Afgørelse', 'Niveaukode'],value_cols='count',title='Sankey Diagram')

plotly.offline.plot(fig, validate=False)
´´´
</code>```

Body:
I've been using Python for a short while to create simple graphs which work fine and I am reasonably confident in that area. But now I have moved on to Sankey diagrams and here I am on deep waters with regards to creating nodes and edges.

I have a list of cases with the following associated values:

a case ID key

the decision

if the decision was a rejection an indication if it was in the bottom, middle or top third

a binary indication if it is a resubmission or not, a foreign key to the associated case ID and a year of the previous case

CaseID
Year
Decision
Reject grade
Resubmission
PreviousApplicationId
Year of prev case

1
2019
Rejection
Top
Yes
434
2018

2
2019
Accepted

No

3
2019
Rejection
Bottom
No

4
2019
Accepted

Yes
632
2018

5
2019
Rejection
Middle
Yes
485
2018

6
2020
Accepted

No

7
2020
Rejection
Top
Yes
5
2019

8
2020
Accepted

No

9
2020
Rejection
Middle
Yes
3
2019

10
2020
Accepted

No

(The above table can be generated thus:

df = pd.DataFrame( {'CaseID': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9, 9: 10},
'Year': {0: 2019, 1: 2019, 2: 2019, 3: 2019, 4: 2019, 5: 2020, 6: 2020, 7: 2020, 8: 2020, 9: 2020},
'Decision': {0: 'Rejection', 1: 'Accepted', 2: 'Rejection', 3: 'Accepted', 4: 'Rejection', 5: 'Accepted', 6: 'Rejection', 7: 'Accepted', 8: 'Rejection', 9: 'Accepted'},
'Reject grade': {0: 'Top', 1: float('nan'), 2: 'Bottom', 3: float('nan'), 4: 'Middle', 5: float('nan'), 6: 'Top', 7: float('nan'), 8: 'Middle', 9: float('nan')},
'Resubmission': {0: 'Yes', 1: 'No', 2: 'No', 3: 'Yes', 4: 'Yes', 5: 'No', 6: 'Yes', 7: 'No', 8: 'Yes', 9: 'No'},
'PreviousApplicationId': {0: 434.0, 1: float('nan'), 2: float('nan'), 3: 632.0, 4: 485.0, 5: float('nan'), 6: 5.0, 7: float('nan'), 8: 3.0, 9: float('nan')},
'Year of prev case': {0: 2018.0, 1: float('nan'), 2: float('nan'), 3: 2018.0, 4: 2018.0, 5: float('nan'), 6: 2019.0, 7: float('nan'), 8: 2019.0, 9: float('nan')}} )

What I am trying to achieve is to see the flow from a case is submitted: Does it get rejected or accepted. If it is rejected, does it end in the top/middle/bottom pile. Does this result in a later resubmission? Overlaying all this is a timeflow, so it is possible to see how this flows over time. Some cases, if they get rejected, are not resubmitted. Others will be resubmitted, not in the following year, but maybe three years later.

I realise I have grasped over a problem that exceeds my current level of Python understanding haha

I used the wrapper function described at https://medium.com/kenlok/how-to-create-sankey-diagrams-from-dataframes-in-python-e221c1b4d6b0 which generated a sankey. So far so good. But unfortunately,  the year column is a variable like so many others, so it ends up being shown on the far left.

I would like for time instead to be shown as an overlay on top, so that the flow also depicts the temporal element.

Image of the Sankey generated by the wrapper function mentioned

Code below:

import numpy as np
import pandas as pd
import plotly

df = pd.read_excel("data.xlsx")

def genSankey(df,cat_cols=[],value_cols='',title='Sankey Diagram'):
    # maximum of 6 value cols -> 6 colors
    colorPalette = ['#4B8BBE','#306998','#FFE873','#FFD43B','#646464']
    labelList = []
    colorNumList = []
    for catCol in cat_cols:
        labelListTemp =  list(set(df[catCol].values))
        colorNumList.append(len(labelListTemp))
        labelList = labelList + labelListTemp

    # remove duplicates from labelList
    labelList = list(dict.fromkeys(labelList))

    # define colors based on number of levels
    colorList = []
    for idx, colorNum in enumerate(colorNumList):
        colorList = colorList + [colorPalette[idx]]*colorNum

    # transform df into a source-target pair
    for i in range(len(cat_cols)-1):
        if i==0:
            sourceTargetDf = df[[cat_cols[i],cat_cols[i+1],value_cols]]
            sourceTargetDf.columns = ['source','target','count']
        else:
            tempDf = df[[cat_cols[i],cat_cols[i+1],value_cols]]
            tempDf.columns = ['source','target','count']
            sourceTargetDf = pd.concat([sourceTargetDf,tempDf])
        sourceTargetDf = sourceTargetDf.groupby(['source','target']).agg({'count':'sum'}).reset_index()

    # add index for source-target pair
    sourceTargetDf['sourceID'] = sourceTargetDf['source'].apply(lambda x: labelList.index(x))
    sourceTargetDf['targetID'] = sourceTargetDf['target'].apply(lambda x: labelList.index(x))

    # creating the sankey diagram
    data = dict(
        type='sankey',
        node = dict(
          pad = 15,
          thickness = 20,
          line = dict(
            color = "black",
            width = 0.5
          ),
          label = labelList,
          color = colorList
        ),
        link = dict(
          source = sourceTargetDf['sourceID'],
          target = sourceTargetDf['targetID'],
          value = sourceTargetDf['count']
        )
      )

    layout =  dict(
        title = title,
        font = dict(
          size = 10
        )
    )

    fig = dict(data=[data], layout=layout)
    return fig

# Finanslovsaar = Year, Genansøgning = Resubmission, Afgørelse = Decision, Niveuakode = Grade
fig = genSankey(df,cat_cols=['Finanslovsaar', 'Genansøgning', 'Afgørelse', 'Niveaukode'],value_cols='count',title='Sankey Diagram')

plotly.offline.plot(fig, validate=False)
´´´


问:
How to implement the "Bezier approximation method" in Java programming language?
I have to implement Bezier approximation method into Java programming language by using the next input variables:

x [0, 3.3, 6.6, 9.9]
y(x) [2.1, 5.9, 2.4, 3.4]

Would really appreciate any resources and help in general about


问:
Is a good or a bad idea store Set<Long> in JPA as a string and convert it before to save and after get the entity?
I have a class Calculation that have many filters from screen and the result of calculation.

class Calculation {

    Set<Long> filterA;
    Set<Long> filterB;
    Set<Long> filterC;
    Set<Long> filterD;
    Set<Long> filterE;
}
```
<p>I need to save the data of calculation and the filters.</p>
<p>As I don't need to search what calculation I have some specific filter, I am thinking about store this filters as a string.</p>
<pre class="lang-java prettyprint-override"><code>class CalculationEntity {

    String filterA;
}
</code>```

And I could cast filterA (String) -> to -> Set<Long>
I don't have available a NoSQL like mongo at organization.

Is it a bad idea? Or can be a good idea?

I wouldn't want to use @ElementCollection because it would create five tables.

Body:
I have a class Calculation that have many filters from screen and the result of calculation.

class Calculation {

    Set<Long> filterA;
    Set<Long> filterB;
    Set<Long> filterC;
    Set<Long> filterD;
    Set<Long> filterE;
}

I need to save the data of calculation and the filters.

As I don't need to search what calculation I have some specific filter, I am thinking about store this filters as a string.

class CalculationEntity {

    String filterA;
}

And I could cast filterA (String) -> to -> Set<Long>
I don't have available a NoSQL like mongo at organization.

Is it a bad idea? Or can be a good idea?

I wouldn't want to use @ElementCollection because it would create five tables.


问:
Unable to convert multiple API response into xml in single call
I am sending multiple API calls and getting their respective responses back. I am trying to convert each response into XML but it is failing with an error.

The setup:

```<code>        * table requestTable
            | nameTags| ageGroups| status |
            | nameTag1| ageGroup1| 200    |
            | nameTag2| ageGroup2| 200    |
            | nameTag3| ageGroup3| 200    |
        * def getRequest = call read('target.feature@getRequest') requestTable
        * xml transformResponse = $getRequest[*].response

Getting the following error:
class com.sun.org.apache.xerces.internal.dom.DeferredDocumentImplAccAccess (in unnamed module @0x1414800e)
cannot access class com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl (in module java.xml) because
module java.xml does not export com.sun.org.apache.xerces.internal.dom to unnamed module @0x1414800e
</code>```

If I do a single conversion such as: * xml transformResponse = $getRequest[0].response it works as expected.

Please advise.

Body:
I am sending multiple API calls and getting their respective responses back. I am trying to convert each response into XML but it is failing with an error.

The setup:

        * table requestTable
            | nameTags| ageGroups| status |
            | nameTag1| ageGroup1| 200    |
            | nameTag2| ageGroup2| 200    |
            | nameTag3| ageGroup3| 200    |
        * def getRequest = call read('target.feature@getRequest') requestTable
        * xml transformResponse = $getRequest[*].response

Getting the following error:
class com.sun.org.apache.xerces.internal.dom.DeferredDocumentImplAccAccess (in unnamed module @0x1414800e)
cannot access class com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl (in module java.xml) because
module java.xml does not export com.sun.org.apache.xerces.internal.dom to unnamed module @0x1414800e

If I do a single conversion such as: * xml transformResponse = $getRequest[0].response it works as expected.

Please advise.


问:
3D Character rolls with sphere
I am trying to make a spider have a certain velocity when control keys are pressed using react three cannon. The 3D model rolls along with the sphere.

The code is as follows:

// import { useFBX } from "@react-three/drei"
import { useSphere } from "@react-three/cannon"
import { useAnimations } from "@react-three/drei"
import { useLoader } from "@react-three/fiber"
import { useEffect, useState } from "react"
import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader'

const Spider = (props) => {
    const [position, setPosition] = useState(props.position)
    const model = useLoader(FBXLoader, '../assets/models3D/spider/Spider.fbx')

    console.log(model)

    const animations = useAnimations(model.animations, model)
    const actions = {
        jump: {
            anim: animations.actions["Spider_Armature|Jump"],
            keys: [' '],
            active: false
        },
        normal: {
            anim: animations.actions["Spider_Armature|normal"],
            keys: [],
            active: false
        },
        wait: {
            anim: animations.actions["Spider_Armature|warte_pose"],
            keys: [],
            active: true
        },
        walkForward: {
            anim: animations.actions["Spider_Armature|walk_ani_vor"],
            keys: ['ArrowUp', 'w'],
            active: false
        },
        walkBackward: {
            anim: animations.actions["Spider_Armature|walk_ani_back"],
            keys: ['ArrowDown', 's'],
            active: false
        },
        walkLeft: {
            anim: animations.actions["Spider_Armature|walk_left"],
            keys: ['ArrowLeft', 'a'],
            active: false
        },
        walkRight: {
            anim: animations.actions["Spider_Armature|walk_right"],
            keys: ['ArrowRight', 'd'],
            active: false
        },
    }

    const [ref, api] = useSphere(() => ({ mass: 1, position: position, allowSleep: false, type: "Dynamic" }))

    useEffect(() => {
        actions.wait.anim.play()

        window.addEventListener("keydown", ({ key }) => {
            Object.keys(actions).forEach(i => {
                let action = actions[i]
                if (action.keys.indexOf(key) > -1) {
                    action.active = true
                    action.anim.play()
                    api.velocity.set(0, 0, -1);
                }
            })
        })
        window.addEventListener("keyup", ({ key }) => {
            Object.keys(actions).forEach(i => {
                let action = actions[i]
                if (action.keys.indexOf(key) > -1) {
                    action.active = false
                    action.anim.stop()
                    api.velocity.set(0, 0, 0);
                }
            })
        })
    }, [])

    return (<>
        <primitive object={model} scale={0.05} position={position} ref={ref} />
    </>)
}

export default Spider
```

How can the spider move along with the sphere without rolling? What could be a solution if useBox was used instead? Is reducing friction a good idea? If so how can it be done.

Please pardon my newness and thanks in advance!!

Title: 3D Character rolls with sphere

Body:
I am trying to make a spider have a certain velocity when control keys are pressed using react three cannon. The 3D model rolls along with the sphere.

The code is as follows:

// import { useFBX } from "@react-three/drei"
import { useSphere } from "@react-three/cannon"
import { useAnimations } from "@react-three/drei"
import { useLoader } from "@react-three/fiber"
import { useEffect, useState } from "react"
import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader'

const Spider = (props) => {
    const [position, setPosition] = useState(props.position)
    const model = useLoader(FBXLoader, '../assets/models3D/spider/Spider.fbx')

    console.log(model)

    const animations = useAnimations(model.animations, model)
    const actions = {
        jump: {
            anim: animations.actions["Spider_Armature|Jump"],
            keys: [' '],
            active: false
        },
        normal: {
            anim: animations.actions["Spider_Armature|normal"],
            keys: [],
            active: false
        },
        wait: {
            anim: animations.actions["Spider_Armature|warte_pose"],
            keys: [],
            active: true
        },
        walkForward: {
            anim: animations.actions["Spider_Armature|walk_ani_vor"],
            keys: ['ArrowUp', 'w'],
            active: false
        },
        walkBackward: {
            anim: animations.actions["Spider_Armature|walk_ani_back"],
            keys: ['ArrowDown', 's'],
            active: false
        },
        walkLeft: {
            anim: animations.actions["Spider_Armature|walk_left"],
            keys: ['ArrowLeft', 'a'],
            active: false
        },
        walkRight: {
            anim: animations.actions["Spider_Armature|walk_right"],
            keys: ['ArrowRight', 'd'],
            active: false
        },
    }

    const [ref, api] = useSphere(() => ({ mass: 1, position: position, allowSleep: false, type: "Dynamic" }))

    useEffect(() => {
        actions.wait.anim.play()

        window.addEventListener("keydown", ({ key }) => {
            Object.keys(actions).forEach(i => {
                let action = actions[i]
                if (action.keys.indexOf(key) > -1) {
                    action.active = true
                    action.anim.play()
                    api.velocity.set(0, 0, -1);
                }
            })
        })
        window.addEventListener("keyup", ({ key }) => {
            Object.keys(actions).forEach(i => {
                let action = actions[i]
                if (action.keys.indexOf(key) > -1) {
                    action.active = false
                    action.anim.stop()
                    api.velocity.set(0, 0, 0);
                }
            })
        })
    }, [])

    return (<>
        <primitive object={model} scale={0.05} position={position} ref={ref} />
    </>)
}

export default Spider

How can the spider move along with the sphere without rolling? What could be a solution if useBox was used instead? Is reducing friction a good idea? If so how can it be done.

Please pardon my newness and thanks in advance!!


问:
Bootstrap components not working on live, works perfect when offline
My html code works perfect in visual code with the live server extension.
But when I host it online the navbar-toggler doesn't work neither do my modals.
My css and js bootstrap files link to the right file, I added the ./ in front of it.
I've been searching all over the internet but I can't find a solution that works.</p>
```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="./CSS/hobbies.css">
    <link rel="stylesheet" href="./CSS/css/bootstrap.min.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap" rel="stylesheet">
    <title>Hobbies</title>
    <link rel="icon" type="image/x-icon" href="IMG/favicon.ico">
</head>
<body class="body">
    <nav class="navbar sticky-top navbar-expand-lg navbar navbar-dark" style="background-color: #332f357f;">
      <div class="d-md-flex d-block flex-row mx-md-auto mx-0">
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <a class="navbar-brand" href="#">text</a>
          <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav me-auto mb-2 mb-lg-0 navItemsToCenter">
              <li class="nav-item">
                <a class="nav-link"  href="index.html">HOMEPAGINA</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="cv.html">CURRICULUM VITAE</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="ervaring.html">ERVARINGEN</a>
              </li>
              <li class="nav-item">
                <a class="nav-link active" aria-current="page" href="#">HOBBIES</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="contact.html">CONTACT</a>
              </li>
              </li>
            </ul>
          </div>
        </div>
      </nav>

      <br>
      <div class="container col-xxl-8 px-4 py-5">
        <div class="row flex-lg-row-reverse align-items-center g-5 py-5">
          <div class="col-lg-12">
            <h1 class="display-5 fw-bold lh-1 mb-3">Programmeren in C#</h1>
            <p class="lead">text</p>
          </div>
        </div>
      </div>

      <div class="container col-xxl-8 px-4 py-5">
        <div class="row flex-lg-row-reverse align-items-center g-5 py-5">
          <div class="col-lg-12">
            <h1 class="display-5 fw-bold lh-1 mb-3">Gaming</h1>
            <p class="lead">text</p>
          </div>
          <div class="col-6 col-sm-8 col-lg-6">
            <img src="IMG/wurm_online_1.jpg" data-bs-toggle="modal" data-bs-target="#WurmModal" class="d-block mx-lg-auto img-fluid" alt="afbeelding Wurm Online" width="700" height="500" loading="lazy">
          </div>
          <div class="col-6 col-sm-8 col-lg-6">
            <img src="IMG/lotro_1.jpg" data-bs-toggle="modal" data-bs-target="#LotroModal" class="d-block mx-lg-auto img-fluid" alt="afbeelding Lotro" width="700" height="500" loading="lazy">
          </div>
        </div>
      </div>

      <div class="modal fade" id="LotroModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl" >
          <div class="modal-content" style="background-color: #4C4550;">
            <div class="modal-body">
              <img src="IMG/lotro_1.jpg" class="img-fluid" alt="afbeelding Lotro">
            </div>
          </div>
        </div>
      </div>

      <div class="modal fade" id="WurmModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl" >
          <div class="modal-content" style="background-color: #4C4550;">
            <div class="modal-body">
              <img src="IMG/wurm_online_1.jpg" class="img-fluid" alt="afbeelding Wurm Online">
            </div>
          </div>
        </div>
      </div>

    <script src="./js/bootstrap.bundle.js"></script>
</body>
</html>
```
`
</code>```

Body:
My html code works perfect in visual code with the live server extension.
But when I host it online the navbar-toggler doesn't work neither do my modals.
My css and js bootstrap files link to the right file, I added the ./ in front of it.
I've been searching all over the internet but I can't find a solution that works.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="./CSS/hobbies.css">
    <link rel="stylesheet" href="./CSS/css/bootstrap.min.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap" rel="stylesheet">
    <title>Hobbies</title>
    <link rel="icon" type="image/x-icon" href="IMG/favicon.ico">

        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

        </button>
        text

                HOMEPAGINA

                CURRICULUM VITAE

                ERVARINGEN

                HOBBIES

                CONTACT

Programmeren in C#

text

Gaming

text

```
`


问:
Can I run socket io server on codesandbox along with the app?
I am trying to run socket io server in my codesandbox project with my react app at the same time but It doesn't seem to work.

my package is containing the following:

```<code>  "main": "src/index.tsx",
  "scripts": {
    "start": "concurrently \"npm run server\" \"react-scripts start\"",
    "server": "nodemon --exec 'ts-node' server/index.ts localhost 8080"
  },
</code>```

I do no think my scripts are being detected by the codesandbox because I have tried deleting everything from them and my react app is working - without the server part. Can someone explain how does codesandbox handle those stuff and if you have an example how to run react + server in the same sandbox.

Body:
I am trying to run socket io server in my codesandbox project with my react app at the same time but It doesn't seem to work.

my package is containing the following:

  "main": "src/index.tsx",
  "scripts": {
    "start": "concurrently \"npm run server\" \"react-scripts start\"",
    "server": "nodemon --exec 'ts-node' server/index.ts localhost 8080"
  },

I do no think my scripts are being detected by the codesandbox because I have tried deleting everything from them and my react app is working - without the server part. Can someone explain how does codesandbox handle those stuff and if you have an example how to run react + server in the same sandbox.


问:
How to ignore onTap events from parent widgets
I wrapped my scaffold with RawGestureDetector and it receives all onTap events for closing keyboards.

RawGestureDetector(
      gestures: {
        AllowMultipleGestureRecognizer: GestureRecognizerFactoryWithHandlers<
            AllowMultipleGestureRecognizer>(
          () => AllowMultipleGestureRecognizer(),
          (AllowMultipleGestureRecognizer instance) {
            instance.onTap = () {
              FocusScopeNode currentFocus = FocusScope.of(context);

              if (!currentFocus.hasPrimaryFocus) {
                currentFocus.unfocus();
              }
            };
          },
        )
      },
      child: Scaffold(...
```

When I click text fields the first time it opens the keyboard correctly, but if I touch the text field when the keyboard is open, it closes and opens immediately. So I need to prevent onTap events that come from parents and need to allow just child's events.

I tried both AbsorbPointer and IgnorePointer. Both of them ignore all of the onTap events. They prevent focusing on the text field and opening the keyboard.

Body:
I wrapped my scaffold with RawGestureDetector and it receives all onTap events for closing keyboards.

RawGestureDetector(
      gestures: {
        AllowMultipleGestureRecognizer: GestureRecognizerFactoryWithHandlers<
            AllowMultipleGestureRecognizer>(
          () => AllowMultipleGestureRecognizer(),
          (AllowMultipleGestureRecognizer instance) {
            instance.onTap = () {
              FocusScopeNode currentFocus = FocusScope.of(context);

              if (!currentFocus.hasPrimaryFocus) {
                currentFocus.unfocus();
              }
            };
          },
        )
      },
      child: Scaffold(...

When I click text fields the first time it opens the keyboard correctly, but if I touch the text field when the keyboard is open, it closes and opens immediately. So I need to prevent onTap events that come from parents and need to allow just child's events.

I tried both AbsorbPointer and IgnorePointer. Both of them ignore all of the onTap events. They prevent focusing on the text field and opening the keyboard.


问:
chrome extension setPopup is not propagated immediately
I'm working on chrome extension and I want to have 2 pages one main popup and then on click on specific button I want to replace it with other one(some settings page) so far I managed to change it using

```<code>chrome.action.setPopup({ popup: "settings.html" })
</code>```

but problem is in fact that it's not immediately propagated, I have to click on extension to close it and click again to open it to be able to see settings page, did I missed something or what is the preferred way in such case?

Body:
I'm working on chrome extension and I want to have 2 pages one main popup and then on click on specific button I want to replace it with other one(some settings page) so far I managed to change it using

chrome.action.setPopup({ popup: "settings.html" })

but problem is in fact that it's not immediately propagated, I have to click on extension to close it and click again to open it to be able to see settings page, did I missed something or what is the preferred way in such case?


问:
Using CMake to create an SDK, and dependencies
Background:

I work for a company that sells chips and we provide an SDK that goes along with it.

So far, the creation SDK step has been pretty manual and it's created a lot of churn between the SDK providers and the SDK users.

I want to get the SDK generation into the workflow so that everybody (including the SDK providers) uses the SDK to build their applications and the SDK is automatically generated from the original source.

In basic workflow, I want

SDK Provider view:

/application (checked in)

/source (checked in)

/sdk    (not checked in)

/build  (not checked in)

SDK User view:

/application (checked in)

/sdk   (checked in)

/build (not checked in)

When the SDK provider starts work, configure/build would convert some of /source to libraries and deposit them into the /sdk directory along with other files (headers, interface .cpp files, CMake files, etc)

Then an application would configure w/the SDK directory and build.

When satisfied, we'd commit/push/tag, and automate the build of the SDK and commit to the SDK subrepo, etc.  Where an SDK user could clone and do the same thing as the provider, except without the /source directory.

Changes to the /source directory should rebuild/copy whatever is appropriate to the /sdk directory, and direct changes to the /sdk directory would be discarded/disallowed.

I'm assuming I want to make use of the "install" stuff in CMake, but I'm not exactly sure how to get the dependencies correct.

Also, how does the SDK provider, who has no /build or /sdk directories at the beginning get started?  I'm guessing trying FindPackage() for /sdk and then findpackage for /source (or something like that)

Anyways, any pointers would be appreciated.  It's not a typical flow so I'm having a hard time finding stuff on google that's exactly on point.


问:
How do I add a property to a wrapper of a decorator?
I do not really get how i can add a property to a wrapper of a decorator function (see the last line for the property that is expected)

Here is the code without the property:

```<code>function decorator(f , ms) {

    let timeout;

    function wrapper(...args) {

        clearTimeout(timeout);

        if (!timeout) {

            f.apply(this , args);

        }

        timeout = setTimeout(() => {

            f.apply(this , args);

        }, ms);

    }

        return wrapper;

}

const sendSignal = (signalOrder , delay) => console.log("Signal sent", signalOrder, delay);

const upgradedSendSignal = decorator(sendSignal, 2000);

setTimeout(() => upgradedSendSignal(1 , 0));
setTimeout(() => upgradedSendSignal(2, 300), 300);
setTimeout(() => upgradedSendSignal(3, 900), 900);
setTimeout(() => upgradedSendSignal(4, 1200), 1200);
setTimeout(() => upgradedSendSignal(5, 2300), 2300);
setTimeout(() => upgradedSendSignal(6, 4400), 4400);
setTimeout(() => upgradedSendSignal(7, 4500), 4500);
setTimeout(() => console.log(upgradedSendSignal.count), 7000); // here i need to use a property of a decorated function (.count) which is supposed to count all the Signals`
</code>```

Is it supposed to look something like this? If so, I'm confused about the arguments to be used in the function. How do I use the result of the decorator here?

wrapper.history = [];

wrapper.count = function() => {

wrapper.history.push();

return wrapper.history.length;

}

Body:
I do not really get how i can add a property to a wrapper of a decorator function (see the last line for the property that is expected)

Here is the code without the property:

function decorator(f , ms) {

    let timeout;

    function wrapper(...args) {

        clearTimeout(timeout);

        if (!timeout) {

            f.apply(this , args);

        }

        timeout = setTimeout(() => {

            f.apply(this , args);

        }, ms);

    }

        return wrapper;

}

const sendSignal = (signalOrder , delay) => console.log("Signal sent", signalOrder, delay);

const upgradedSendSignal = decorator(sendSignal, 2000);

setTimeout(() => upgradedSendSignal(1 , 0));
setTimeout(() => upgradedSendSignal(2, 300), 300);
setTimeout(() => upgradedSendSignal(3, 900), 900);
setTimeout(() => upgradedSendSignal(4, 1200), 1200);
setTimeout(() => upgradedSendSignal(5, 2300), 2300);
setTimeout(() => upgradedSendSignal(6, 4400), 4400);
setTimeout(() => upgradedSendSignal(7, 4500), 4500);
setTimeout(() => console.log(upgradedSendSignal.count), 7000); // here i need to use a property of a decorated function (.count) which is supposed to count all the Signals`

Is it supposed to look something like this? If so, I'm confused about the arguments to be used in the function. How do I use the result of the decorator here?

wrapper.history = [];

wrapper.count = function() => {

wrapper.history.push();

return wrapper.history.length;

}


问:
Swagger Codegen 3.0 Generate API Client but only for specific methods (routes)
So I have the openAPi YAML, that contains definitions for the api client and lots of methods, is there a way to generate a specific method only and not all of them?</p>


问:
Node js session exploit with known secret
I'm doing CTF challenge where I've successfully retrieved session cookie, can I somhow bruteforce or maybe predict next session cookie and login someone else or change my role.

Here is how thay generate session cookie:

```<code>app.use(session({
    resave: false, // leave this as false!!
    saveUninitialized: true,
    secret:'secret',
    store: new MongoStore({ mongooseConnection: mongoose.connection }),
    ttl: 14 * 24 * 60 * 60 // = 14 days. Default
}));
</code>```

I know that roles and all that is stored on server, but there must be some vulnerability that I could exploit.

I would appreciate a guide in right direction.

Body:
I'm doing CTF challenge where I've successfully retrieved session cookie, can I somhow bruteforce or maybe predict next session cookie and login someone else or change my role.

Here is how thay generate session cookie:

app.use(session({
    resave: false, // leave this as false!!
    saveUninitialized: true,
    secret:'secret',
    store: new MongoStore({ mongooseConnection: mongoose.connection }),
    ttl: 14 * 24 * 60 * 60 // = 14 days. Default
}));

I know that roles and all that is stored on server, but there must be some vulnerability that I could exploit.

I would appreciate a guide in right direction.


问:
Topology was destroyed message=Topology was destroyed, name=MongoError, stack=MongoError: Topology was destroyed
I'm getting this error when I'm trying to reuse an old backend. I'm connecting to mongoose like this.

Could someone suggest how to fix this?

```<code>module.exports = function () {
    const db = config.get('db');

    mongoose.connect(db).then(() => winston.info(`connected to ${db} .......`));
};

</code>```

Body:
I'm getting this error when I'm trying to reuse an old backend. I'm connecting to mongoose like this.

Could someone suggest how to fix this?

module.exports = function () {
    const db = config.get('db');

    mongoose.connect(db).then(() => winston.info(`connected to ${db} .......`));
};


问:
I'm trying to add a percentage value on a attribute that uses a number
I have a Tree component from the library React Arborist.

This component has a default height and I can modify it by using the prop height.
(for example: height={700})

The problem is: I want it to be responsive and this prop is using pixels, instead it should be %. However, this props only accepts numbers, not strings like '100%'.

Does anyone know how could I fix this?

I have tried by adding a className with a property height using the rule style !important and it worked but this is a terrible practice.

Also I tried to add an external component but the styles from the Tree are strongest I guess because it is inside.


问:
CSS transition doesn’t work when reducing height
In the following JSFiddle, the height change is not animated (using the transition property) when it’s being reduced:

https://jsfiddle.net/gcm0Ljrb/

When button A is pressed, the bottom left panel expands from height 0 to its full height. When B is pressed, the panel’s height reduces to a specific amount. Finally, when C is pressed, the panel’s height goes back to 0 (initial state).

I am trying to make all of these height changes animated using the transition property, but only button A’s height update is actually animated.

What could be going wrong here that is preventing the other two buttons from also being animated?


问:
Excel - Pull range out of a table and Match specific text
I am trying to automate a tracker that will let me know when an employee completes a specific training course.

Example Data:

Name
Course

A
Trng A

A
Trng B

A
Trng C

B
Trng A

B
Trng D

C
Trng C

What I would like to do is match against the name to pull a range of courses, and then Match against the course title to determine if the training course has been completed:

Name
Trng A
Trng B
Trng D

A
True
True
False

B
True
False
True

C
False
False
False

The data changes frequently and rows are added when a course is completed, so ranges need to remain dynamic matched against name.

I have tried using index/match but can only match the first course in the list.


问:
How can mock a Keycloak token for unit test in ScalaTest
The app I'm working (in Scala) keep a register of all the users that login using Keycloak, for that creates a user for every new keycloak user using the information on the keycloak authorization token

```<code>private def decodeToken(token: String): Try[User] = {
Try { AdapterTokenVerifier.verifyToken(token, keycloakDeployment) } match {
  case Success(accessToken: AccessToken) =>
    Try (User(name = accessToken.getName, userName = accessToken.getPreferredUsername, email = Some(accessToken.getEmail))
  case Failure(ex) =>
    throw new Exception("authentication failed")
}}
</code>```

My problem is the following, I need to do unit tests to my code, for that is used ScalaTest, how can a mock a token of keycloak inside the test so this code can be tested.
I already write the test and works but I have to pass manually a token, that means, any other time I run the test if the token expire the test files, also files if the test is run in another computer, also fails in gitlab (don't pass pipelines)

Note: I'm new with scala and with keycloak, also English is not my firs language, so it's understandable that some things are not very clear, if you think you can help me, feel free to ask anything

Note 2: With that user that is created with the Keycloak token, other things are done but this is the most relevant to my problem

Body:
The app I'm working (in Scala) keep a register of all the users that login using Keycloak, for that creates a user for every new keycloak user using the information on the keycloak authorization token

private def decodeToken(token: String): Try[User] = {
Try { AdapterTokenVerifier.verifyToken(token, keycloakDeployment) } match {
  case Success(accessToken: AccessToken) =>
    Try (User(name = accessToken.getName, userName = accessToken.getPreferredUsername, email = Some(accessToken.getEmail))
  case Failure(ex) =>
    throw new Exception("authentication failed")
}}

My problem is the following, I need to do unit tests to my code, for that is used ScalaTest, how can a mock a token of keycloak inside the test so this code can be tested.
I already write the test and works but I have to pass manually a token, that means, any other time I run the test if the token expire the test files, also files if the test is run in another computer, also fails in gitlab (don't pass pipelines)

Note: I'm new with scala and with keycloak, also English is not my firs language, so it's understandable that some things are not very clear, if you think you can help me, feel free to ask anything

Note 2: With that user that is created with the Keycloak token, other things are done but this is the most relevant to my problem


问:
Acyclic Visitor Pattern: is it actually inferior to the original Visitor pattern?
I have read several articles and answers about the merits of the Acyclic Visitor pattern over the original Visitor pattern. To avoid ambiguity, I refer to the Acyclic Visitor as described in this article by Uncle Bob.

In essence, the acyclic visitor decouples the creation of new elements in the visited object hierarchy from the need to update all of the visitors accordingly.
This allows independent expansion and deployment of the visitors and the elements.

However, how does one keep visitor correctness when implementing a new visited element?

Under the assumption that an addition of a new visited element would often necessitate changes in existing visitors to remain correct, that sounds to me like a horrible feature of the pattern.
Whenever an element is added, someone has to manually remember to check and update every relevant visitor, instead of being forced to do so by the compiler.
It essentially transforms what would be a compile time error in the original visitor pattern, into a software bug in the acyclic visitor pattern.

This goes directly against the promise of independently developable and deployable components.

Assuming work on a large project with many visitors and people working independently on visitors as features, the acyclic visitors will likely cause costly bugs that will only be revealed after deployment.

Are there any ways to mitigate this problem that are not manual?
If not, why should the acyclic visitor pattern ever be used?

Basic Example

Let's suppose we have the following visited hierarchy:

public abstract class Base {
    public abstract void accept(Visitor v);
}

public class A extends Base {
  public void accept(Visitor v) {
    if (v instanceof AVisitor) {
      AVisitor av = (AVisitor) v;
      av.visit(this);
    }
  }
}

public class B extends Base {
  public void accept(Visitor v) {
    if (v instanceof BVisitor) {
      BVisitor bv = (BVisitor) v;
      av.visit(this);
    }
  }
}
```
<p>And the following visitor, which reports a list of all element types by order:</p>
<pre class="lang-java prettyprint-override"><code>public interface Visitor {
}

public interface AVisitor {
  void visit(A a);
}

public interface BVisitor {
  void visit(B b);
}

public class ReportVisitor implements Visitor, AVisitor, BVisitor {
  private StringBuffer report;

  public ReportVisitor(StringBuffer report) {
    this.report = report;
  }

  public void visit(A a) {
    report.append("A\n");
  }

  public void visit(B b) {
    report.append("B\n");
  }
}

</code>```

Now, suppose we add a new visited object:

public class C extends Base {
  public void accept(Visitor v) {
    if (v instanceof CVisitor) {
      CVisitor cv = (AVisitor) v;
      cv.visit(this);
    }
  }
}

public interface CVisitor {
  void visit(C c);
}

```

The developer adding C has to know ReportVisitor and any other relevant visitor, and remember to modify them. Otherwise, the ReportVisitor would simply omit all the occurrences of C, which is a bug.

Note:

Another modified Visitor pattern achieves similar decoupling using the visitOther method, as described in this answer.

By not filtering visitors in the visited object, this can arguably provide the benefit of allowing any visitor that knows (or, more accurately, speculates and future-proofs) it needs to handle all of the visited elements to throw an exception, thus reducing what would be a bug to a runtime error.

While this might be beneficial, as runtime errors are easier to notice, debug and solve than bugs, it is still far inferior to compile time errors.

Body:
I have read several articles and answers about the merits of the Acyclic Visitor pattern over the original Visitor pattern. To avoid ambiguity, I refer to the Acyclic Visitor as described in this article by Uncle Bob.

In essence, the acyclic visitor decouples the creation of new elements in the visited object hierarchy from the need to update all of the visitors accordingly.
This allows independent expansion and deployment of the visitors and the elements.

However, how does one keep visitor correctness when implementing a new visited element?

Under the assumption that an addition of a new visited element would often necessitate changes in existing visitors to remain correct, that sounds to me like a horrible feature of the pattern.
Whenever an element is added, someone has to manually remember to check and update every relevant visitor, instead of being forced to do so by the compiler.
It essentially transforms what would be a compile time error in the original visitor pattern, into a software bug in the acyclic visitor pattern.

This goes directly against the promise of independently developable and deployable components.

Assuming work on a large project with many visitors and people working independently on visitors as features, the acyclic visitors will likely cause costly bugs that will only be revealed after deployment.

Are there any ways to mitigate this problem that are not manual?
If not, why should the acyclic visitor pattern ever be used?

Basic Example

Let's suppose we have the following visited hierarchy:

public abstract class Base {
    public abstract void accept(Visitor v);
}

public class A extends Base {
  public void accept(Visitor v) {
    if (v instanceof AVisitor) {
      AVisitor av = (AVisitor) v;
      av.visit(this);
    }
  }
}

public class B extends Base {
  public void accept(Visitor v) {
    if (v instanceof BVisitor) {
      BVisitor bv = (BVisitor) v;
      av.visit(this);
    }
  }
}

And the following visitor, which reports a list of all element types by order:

public interface Visitor {
}

public interface AVisitor {
  void visit(A a);
}

public interface BVisitor {
  void visit(B b);
}

public class ReportVisitor implements Visitor, AVisitor, BVisitor {
  private StringBuffer report;

  public ReportVisitor(StringBuffer report) {
    this.report = report;
  }

  public void visit(A a) {
    report.append("A\n");
  }

  public void visit(B b) {
    report.append("B\n");
  }
}

Now, suppose we add a new visited object:

public class C extends Base {
  public void accept(Visitor v) {
    if (v instanceof CVisitor) {
      CVisitor cv = (AVisitor) v;
      cv.visit(this);
    }
  }
}

public interface CVisitor {
  void visit(C c);
}

The developer adding C has to know ReportVisitor and any other relevant visitor, and remember to modify them. Otherwise, the ReportVisitor would simply omit all the occurrences of C, which is a bug.

Note:

Another modified Visitor pattern achieves similar decoupling using the visitOther method, as described in this answer.

By not filtering visitors in the visited object, this can arguably provide the benefit of allowing any visitor that knows (or, more accurately, speculates and future-proofs) it needs to handle all of the visited elements to throw an exception, thus reducing what would be a bug to a runtime error.

While this might be beneficial, as runtime errors are easier to notice, debug and solve than bugs, it is still far inferior to compile time errors.