问:
Split joined slice with delimiter into chunks of maximum N length
I have slice of strings

```<code>s := []string{"some", "word", "anotherverylongword", "word", "yyy", "u"}

delimiter := ";"
</code>```

I want to get another slice of them joined if with delimiter length is less or equal to 10

so output would be:
{"some;word", "anotherverylongword", "word;yyy;u"}

"anotherverylongword" has more than 10 characters so its separated, rest has less or exactly 10 characters with delimiter so it's joined.

I asked same question with JavaScript (How to split joined array with delimiter into chunks)

but solution was written with immutability in mind.
Go nature is more mutable, and I can't wrap my head around to translate it into Go, that's why I'm asking it here.

答:
You can try this way, some comments added

```<code>s := []string{"some", "word", "anotherverylongword", "word", "yyy", "u", "kkkk"}
var res []string
var cur string
for i, e := range s {
    if len(cur)+len(e)+1 > 10 { // check adding string exceed chuck limit
        res = append(res, cur)  // append current string
        cur = e
    } else {
        if cur != "" {          // add delimeter if not empty string
            cur += ";"
        }
        cur += e
    }
    if i == len(s)-1 {
        res = append(res, cur)
    }
}
</code>```

Code on go playground here

And more simplified

```<code>s := []string{"some", "word", "anotherverylongword", "word", "yyy", "u", "kkkk"}
var res []string
for _, e := range s {
    l := len(res)
    if l > 0 && len(res[l-1])+len(e)+1 > 10 {
        res = append(res, e)
    } else {
        if l > 0 {
            res[l-1] += ";" + e
        } else {
            res = append(res, e)
        }
    }
}
</code>```

Body:
I have slice of strings

s := []string{"some", "word", "anotherverylongword", "word", "yyy", "u"}

delimiter := ";"

I want to get another slice of them joined if with delimiter length is less or equal to 10

so output would be:
{"some;word", "anotherverylongword", "word;yyy;u"}

"anotherverylongword" has more than 10 characters so its separated, rest has less or exactly 10 characters with delimiter so it's joined.

I asked same question with JavaScript (How to split joined array with delimiter into chunks)

but solution was written with immutability in mind.
Go nature is more mutable, and I can't wrap my head around to translate it into Go, that's why I'm asking it here.

Body:
You can try this way, some comments added

s := []string{"some", "word", "anotherverylongword", "word", "yyy", "u", "kkkk"}
var res []string
var cur string
for i, e := range s {
    if len(cur)+len(e)+1 > 10 { // check adding string exceed chuck limit
        res = append(res, cur)  // append current string
        cur = e
    } else {
        if cur != "" {          // add delimeter if not empty string
            cur += ";"
        }
        cur += e
    }
    if i == len(s)-1 {
        res = append(res, cur)
    }
}

Code on go playground here

And more simplified

s := []string{"some", "word", "anotherverylongword", "word", "yyy", "u", "kkkk"}
var res []string
for _, e := range s {
    l := len(res)
    if l > 0 && len(res[l-1])+len(e)+1 > 10 {
        res = append(res, e)
    } else {
        if l > 0 {
            res[l-1] += ";" + e
        } else {
            res = append(res, e)
        }
    }
}


来源: stackexchange

问:
can't perform a react state update on an unmounted component. this is a no-op but it indicates a memory leak
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.</p>

```<code>componentDidMount() {
    this.RetrieveSellerNo();
    this.requestLocationPermission();
    this.requestData();
    this.Watch();

    this._interval = setInterval(() => {

        if (this.state.SellerNo !== null) {
            this.uploadPosition();
        }
        this.requestData();
    }, 60000);
    setTimeout(() => {
        this.requestData();
        this.StoreiposLat();
        this.StoreiposLong();
    }, 5000);
}

componentWillUnmount = () => {
    Geolocation.clearWatch(this.watchId);

}

Watch = () => {
    this.watchId = Geolocation.watchPosition(
        (position) => {
            this.setState({
                watch: {
                    lat: position.coords.latitude,
                    long: position.coords.longitude
                }
            });
        },
        (error) => {
            // console.log(error.message)
        },
        { enableHighAccuracy: false, timeout: 20000, maximumAge: 1000, } //distanceFilter:1
    );
}
</code>```

答:
Your timeout and/or interval is probably still running and attempting to update the state even after the component was unmounted. You are not clearing the interval and the timeout created in componentDidMount.

Store the timeout just like you are storing the interval. In you componentDidMount:

```<code>this._timeout = setTimeout(...)
</code>```

Then, in your componentWillUnmount, do the following:

```<code>Geolocation.clearWatch(this.watchId)
clearInterval (this._interval)
clearTimeout(this._timeout)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

componentDidMount() {
    this.RetrieveSellerNo();
    this.requestLocationPermission();
    this.requestData();
    this.Watch();

    this._interval = setInterval(() => {

        if (this.state.SellerNo !== null) {
            this.uploadPosition();
        }
        this.requestData();
    }, 60000);
    setTimeout(() => {
        this.requestData();
        this.StoreiposLat();
        this.StoreiposLong();
    }, 5000);
}

componentWillUnmount = () => {
    Geolocation.clearWatch(this.watchId);

}

Watch = () => {
    this.watchId = Geolocation.watchPosition(
        (position) => {
            this.setState({
                watch: {
                    lat: position.coords.latitude,
                    long: position.coords.longitude
                }
            });
        },
        (error) => {
            // console.log(error.message)
        },
        { enableHighAccuracy: false, timeout: 20000, maximumAge: 1000, } //distanceFilter:1
    );
}

Body:
Your timeout and/or interval is probably still running and attempting to update the state even after the component was unmounted. You are not clearing the interval and the timeout created in componentDidMount.

Store the timeout just like you are storing the interval. In you componentDidMount:

this._timeout = setTimeout(...)

Then, in your componentWillUnmount, do the following:

Geolocation.clearWatch(this.watchId)
clearInterval (this._interval)
clearTimeout(this._timeout)


问:
Flexbox is not fitting on mobile
This is my first week working with flexbox, and I like it a lot until now. I am doing everything I can to get away of floating elements. Therefore my main purpose is not a solution there is floating elements in. I run into 2 problems, that I am not quite sure of the correct saolution.

Problem 1:
When I hit around 1200px I can see the 2 columns is starting moving together. How can that be?

Problem 2:
Why is my columns not fitting on viewport under 768px? I can see on the mobile the 900x200 is going over the edge of the max width on telephone.

Example page of my code here.

.column-layout {
  max-width: 1200px;
  background-color: #fff;
  margin: 40px auto 0 auto;
}

.column-layout-one {
  max-width: 1200px;
  background-color: #fff;
  margin: 40px auto 0 auto;
}

.header-item-one {
  order: 1;
}

.header-item-two {
  order: 2;
}

@media (min-width: 768px) {
  .column-layout-one {
    display: flex;
    justify-content: space-between;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="column-layout-one">
  <div class="header-item-one">
    <img src="http://placehold.it/280x200">
  </div>
  <div class="header-item-two">
    <img src="http://placehold.it/900x200">
  </div>
</div></code>```

答:
Set your .header-item-one and -two to flex: 1; to fill up the whole space in your flex box. Then, set max-width values for the expected results.

.header-item-one {
  flex: 1;
  max-width: 200px;
  background-color: red;
  height: 300px;
}

.header-item-two {
  flex: 1;
  max-width: 900px;
  background-color: blue;
  height: 300px;
}
```

About the other problem -- the divs go over the viewport boundaries, because you have placeholder images. Images are fixed-width inline block elements, meaning they won't fit the user's viewport, unless you crop them out with overflow-x: hidden; in the parent div or do something like div img { max-width: 100%; }.

Remove the images and try out that css. Fiddle: https://jsfiddle.net/59meh6vs/

Title: Flexbox is not fitting on mobile

Body:
Set your .header-item-one and -two to flex: 1; to fill up the whole space in your flex box. Then, set max-width values for the expected results.

.header-item-one {
  flex: 1;
  max-width: 200px;
  background-color: red;
  height: 300px;
}

.header-item-two {
  flex: 1;
  max-width: 900px;
  background-color: blue;
  height: 300px;
}

About the other problem -- the divs go over the viewport boundaries, because you have placeholder images. Images are fixed-width inline block elements, meaning they won't fit the user's viewport, unless you crop them out with overflow-x: hidden; in the parent div or do something like div img { max-width: 100%; }.

Remove the images and try out that css. Fiddle: https://jsfiddle.net/59meh6vs/


问:
Why Method Overriding is runtime bound
Overriding is a principle that allows you to change the functionality of a method in a child class.

For Ex.

```<code>//Overriding
public class test
{
        public virtual getStuff(int id)
        {
            //Get stuff default location
        }
}

public class test2 : test
{
        public override getStuff(int id)
        {
            //base.getStuff(id);
            //or - Get stuff new location
        }
}
</code>```

When we Inherit test class in test2 at that time compiler knows that there is a virtual method in parent class.
Then why Method overring is runtime bound and not compile time bound?

答: Just to add to other answers, anything that a the compiler can't figure out at compile time it makes it to happen at run time by emitting the appropriate code that does the stuff at run time or by using other techniques.</p>

ContentLicense: CC BY-SA 3.0

Title: Why Method Overriding is runtime bound

Body:
Overriding is a principle that allows you to change the functionality of a method in a child class.

For Ex.

//Overriding
public class test
{
        public virtual getStuff(int id)
        {
            //Get stuff default location
        }
}

public class test2 : test
{
        public override getStuff(int id)
        {
            //base.getStuff(id);
            //or - Get stuff new location
        }
}

When we Inherit test class in test2 at that time compiler knows that there is a virtual method in parent class.
Then why Method overring is runtime bound and not compile time bound?


问:
Can I use VGG16 for one channel images?
I've just started to learn Tensorflow (2.1.0), Keras (2.3.7) with Python 3.7.7.

I want to use VGG16 network to do semantic segmentation with black and white images (200x200x1).

I have used this network, with its original input_size was (224,224,3):

```<code>def vgg16_encoder_decoder(input_size = (200,200,1)):
    #################################
    # Encoder
    #################################
    inputs = Input(input_size, name = 'input')

    conv1 = Conv2D(64, (3, 3), activation = 'relu', padding = 'same', name ='conv1_1')(inputs)
    conv1 = Conv2D(64, (3, 3), activation = 'relu', padding = 'same', name ='conv1_2')(conv1)
    pool1 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_1')(conv1)

    conv2 = Conv2D(128, (3, 3), activation = 'relu', padding = 'same', name ='conv2_1')(pool1)
    conv2 = Conv2D(128, (3, 3), activation = 'relu', padding = 'same', name ='conv2_2')(conv2)
    pool2 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_2')(conv2)

    conv3 = Conv2D(256, (3, 3), activation = 'relu', padding = 'same', name ='conv3_1')(pool2)
    conv3 = Conv2D(256, (3, 3), activation = 'relu', padding = 'same', name ='conv3_2')(conv3)
    conv3 = Conv2D(256, (3, 3), activation = 'relu', padding = 'same', name ='conv3_3')(conv3)
    pool3 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_3')(conv3)

    conv4 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv4_1')(pool3)
    conv4 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv4_2')(conv4)
    conv4 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv4_3')(conv4)
    pool4 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_4')(conv4)

    conv5 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv5_1')(pool4)
    conv5 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv5_2')(conv5)
    conv5 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv5_3')(conv5)
    pool5 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_5')(conv5)

    #################################
    # Decoder
    #################################
    #conv1 = Conv2DTranspose(512, (2, 2), strides = 2, name = 'conv1')(pool5)

    upsp1 = UpSampling2D(size = (2,2), name = 'upsp1')(pool5)
    conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_1')(upsp1)
    conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_2')(conv6)
    conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_3')(conv6)

    upsp2 = UpSampling2D(size = (2,2), name = 'upsp2')(conv6)
    conv7 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv7_1')(upsp2)
    conv7 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv7_2')(conv7)
    conv7 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv7_3')(conv7)

    upsp3 = UpSampling2D(size = (2,2), name = 'upsp3')(conv7)
    conv8 = Conv2D(256, 3, activation = 'relu', padding = 'same', name = 'conv8_1')(upsp3)
    conv8 = Conv2D(256, 3, activation = 'relu', padding = 'same', name = 'conv8_2')(conv8)
    conv8 = Conv2D(256, 3, activation = 'relu', padding = 'same', name = 'conv8_3')(conv8)

    upsp4 = UpSampling2D(size = (2,2), name = 'upsp4')(conv8)
    conv9 = Conv2D(128, 3, activation = 'relu', padding = 'same', name = 'conv9_1')(upsp4)
    conv9 = Conv2D(128, 3, activation = 'relu', padding = 'same', name = 'conv9_2')(conv9)

    upsp5 = UpSampling2D(size = (2,2), name = 'upsp5')(conv9)
    conv10 = Conv2D(64, 3, activation = 'relu', padding = 'same', name = 'conv10_1')(upsp5)
    conv10 = Conv2D(64, 3, activation = 'relu', padding = 'same', name = 'conv10_2')(conv10)

    conv11 = Conv2D(3, 3, activation = 'relu', padding = 'same', name = 'conv11')(conv10)

    model = Model(inputs = inputs, outputs = conv11, name = 'vgg-16_encoder_decoder')

    return model
</code>```

Model summary:

```<code>Model: "vgg-16_encoder_decoder"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input (InputLayer)           (None, 200, 200, 1)       0
_________________________________________________________________
conv1_1 (Conv2D)             (None, 200, 200, 64)      640
_________________________________________________________________
conv1_2 (Conv2D)             (None, 200, 200, 64)      36928
_________________________________________________________________
pool_1 (MaxPooling2D)        (None, 100, 100, 64)      0
_________________________________________________________________
conv2_1 (Conv2D)             (None, 100, 100, 128)     73856
_________________________________________________________________
conv2_2 (Conv2D)             (None, 100, 100, 128)     147584
_________________________________________________________________
pool_2 (MaxPooling2D)        (None, 50, 50, 128)       0
_________________________________________________________________
conv3_1 (Conv2D)             (None, 50, 50, 256)       295168
_________________________________________________________________
conv3_2 (Conv2D)             (None, 50, 50, 256)       590080
_________________________________________________________________
conv3_3 (Conv2D)             (None, 50, 50, 256)       590080
_________________________________________________________________
pool_3 (MaxPooling2D)        (None, 25, 25, 256)       0
_________________________________________________________________
conv4_1 (Conv2D)             (None, 25, 25, 512)       1180160
_________________________________________________________________
conv4_2 (Conv2D)             (None, 25, 25, 512)       2359808
_________________________________________________________________
conv4_3 (Conv2D)             (None, 25, 25, 512)       2359808
_________________________________________________________________
pool_4 (MaxPooling2D)        (None, 12, 12, 512)       0
_________________________________________________________________
conv5_1 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
conv5_2 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
conv5_3 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
pool_5 (MaxPooling2D)        (None, 6, 6, 512)         0
_________________________________________________________________
upsp1 (UpSampling2D)         (None, 12, 12, 512)       0
_________________________________________________________________
conv6_1 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
conv6_2 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
conv6_3 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
upsp2 (UpSampling2D)         (None, 24, 24, 512)       0
_________________________________________________________________
conv7_1 (Conv2D)             (None, 24, 24, 512)       2359808
_________________________________________________________________
conv7_2 (Conv2D)             (None, 24, 24, 512)       2359808
_________________________________________________________________
conv7_3 (Conv2D)             (None, 24, 24, 512)       2359808
_________________________________________________________________
upsp3 (UpSampling2D)         (None, 48, 48, 512)       0
_________________________________________________________________
conv8_1 (Conv2D)             (None, 48, 48, 256)       1179904
_________________________________________________________________
conv8_2 (Conv2D)             (None, 48, 48, 256)       590080
_________________________________________________________________
conv8_3 (Conv2D)             (None, 48, 48, 256)       590080
_________________________________________________________________
upsp4 (UpSampling2D)         (None, 96, 96, 256)       0
_________________________________________________________________
conv9_1 (Conv2D)             (None, 96, 96, 128)       295040
_________________________________________________________________
conv9_2 (Conv2D)             (None, 96, 96, 128)       147584
_________________________________________________________________
upsp5 (UpSampling2D)         (None, 192, 192, 128)     0
_________________________________________________________________
conv10_1 (Conv2D)            (None, 192, 192, 64)      73792
_________________________________________________________________
conv10_2 (Conv2D)            (None, 192, 192, 64)      36928
_________________________________________________________________
conv11 (Conv2D)              (None, 192, 192, 3)       1731
=================================================================
Total params: 31,787,523
Trainable params: 31,787,523
Non-trainable params: 0
_________________________________________________________________
</code>```

The last convolutional layer returns a shape of (192, 192, 3) but I need to return an image with shape (200, 200, 1).

I think I can change the last convolutional layer with this one to get a 1 channel image:

```<code>conv11 = Conv2D(1, 3, activation = 'relu', padding = 'same', name = 'conv11')(conv10)
</code>```

But I don't know if this is correct because I've been reading about VGG16 network and it is for 3 channels images.

Can I use VGG16 for one channel images?

答:
What you read about VGG being for three channel (RGB) images applies only to the pre-trained model, which is trained on the ImageNet dataset and contains only color images. Since you are not using the pre-trained model, you are not bound by this limitation.

So you can use one, three, or any number of inputs or output channels.

Title: Can I use VGG16 for one channel images?

Body:
I've just started to learn Tensorflow (2.1.0), Keras (2.3.7) with Python 3.7.7.

I want to use VGG16 network to do semantic segmentation with black and white images (200x200x1).

I have used this network, with its original input_size was (224,224,3):

def vgg16_encoder_decoder(input_size = (200,200,1)):
    #################################
    # Encoder
    #################################
    inputs = Input(input_size, name = 'input')

    conv1 = Conv2D(64, (3, 3), activation = 'relu', padding = 'same', name ='conv1_1')(inputs)
    conv1 = Conv2D(64, (3, 3), activation = 'relu', padding = 'same', name ='conv1_2')(conv1)
    pool1 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_1')(conv1)

    conv2 = Conv2D(128, (3, 3), activation = 'relu', padding = 'same', name ='conv2_1')(pool1)
    conv2 = Conv2D(128, (3, 3), activation = 'relu', padding = 'same', name ='conv2_2')(conv2)
    pool2 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_2')(conv2)

    conv3 = Conv2D(256, (3, 3), activation = 'relu', padding = 'same', name ='conv3_1')(pool2)
    conv3 = Conv2D(256, (3, 3), activation = 'relu', padding = 'same', name ='conv3_2')(conv3)
    conv3 = Conv2D(256, (3, 3), activation = 'relu', padding = 'same', name ='conv3_3')(conv3)
    pool3 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_3')(conv3)

    conv4 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv4_1')(pool3)
    conv4 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv4_2')(conv4)
    conv4 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv4_3')(conv4)
    pool4 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_4')(conv4)

    conv5 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv5_1')(pool4)
    conv5 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv5_2')(conv5)
    conv5 = Conv2D(512, (3, 3), activation = 'relu', padding = 'same', name ='conv5_3')(conv5)
    pool5 = MaxPooling2D(pool_size = (2,2), strides = (2,2), name = 'pool_5')(conv5)

    #################################
    # Decoder
    #################################
    #conv1 = Conv2DTranspose(512, (2, 2), strides = 2, name = 'conv1')(pool5)

    upsp1 = UpSampling2D(size = (2,2), name = 'upsp1')(pool5)
    conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_1')(upsp1)
    conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_2')(conv6)
    conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_3')(conv6)

    upsp2 = UpSampling2D(size = (2,2), name = 'upsp2')(conv6)
    conv7 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv7_1')(upsp2)
    conv7 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv7_2')(conv7)
    conv7 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv7_3')(conv7)

    upsp3 = UpSampling2D(size = (2,2), name = 'upsp3')(conv7)
    conv8 = Conv2D(256, 3, activation = 'relu', padding = 'same', name = 'conv8_1')(upsp3)
    conv8 = Conv2D(256, 3, activation = 'relu', padding = 'same', name = 'conv8_2')(conv8)
    conv8 = Conv2D(256, 3, activation = 'relu', padding = 'same', name = 'conv8_3')(conv8)

    upsp4 = UpSampling2D(size = (2,2), name = 'upsp4')(conv8)
    conv9 = Conv2D(128, 3, activation = 'relu', padding = 'same', name = 'conv9_1')(upsp4)
    conv9 = Conv2D(128, 3, activation = 'relu', padding = 'same', name = 'conv9_2')(conv9)

    upsp5 = UpSampling2D(size = (2,2), name = 'upsp5')(conv9)
    conv10 = Conv2D(64, 3, activation = 'relu', padding = 'same', name = 'conv10_1')(upsp5)
    conv10 = Conv2D(64, 3, activation = 'relu', padding = 'same', name = 'conv10_2')(conv10)

    conv11 = Conv2D(3, 3, activation = 'relu', padding = 'same', name = 'conv11')(conv10)

    model = Model(inputs = inputs, outputs = conv11, name = 'vgg-16_encoder_decoder')

    return model

Model summary:

Model: "vgg-16_encoder_decoder"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input (InputLayer)           (None, 200, 200, 1)       0
_________________________________________________________________
conv1_1 (Conv2D)             (None, 200, 200, 64)      640
_________________________________________________________________
conv1_2 (Conv2D)             (None, 200, 200, 64)      36928
_________________________________________________________________
pool_1 (MaxPooling2D)        (None, 100, 100, 64)      0
_________________________________________________________________
conv2_1 (Conv2D)             (None, 100, 100, 128)     73856
_________________________________________________________________
conv2_2 (Conv2D)             (None, 100, 100, 128)     147584
_________________________________________________________________
pool_2 (MaxPooling2D)        (None, 50, 50, 128)       0
_________________________________________________________________
conv3_1 (Conv2D)             (None, 50, 50, 256)       295168
_________________________________________________________________
conv3_2 (Conv2D)             (None, 50, 50, 256)       590080
_________________________________________________________________
conv3_3 (Conv2D)             (None, 50, 50, 256)       590080
_________________________________________________________________
pool_3 (MaxPooling2D)        (None, 25, 25, 256)       0
_________________________________________________________________
conv4_1 (Conv2D)             (None, 25, 25, 512)       1180160
_________________________________________________________________
conv4_2 (Conv2D)             (None, 25, 25, 512)       2359808
_________________________________________________________________
conv4_3 (Conv2D)             (None, 25, 25, 512)       2359808
_________________________________________________________________
pool_4 (MaxPooling2D)        (None, 12, 12, 512)       0
_________________________________________________________________
conv5_1 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
conv5_2 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
conv5_3 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
pool_5 (MaxPooling2D)        (None, 6, 6, 512)         0
_________________________________________________________________
upsp1 (UpSampling2D)         (None, 12, 12, 512)       0
_________________________________________________________________
conv6_1 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
conv6_2 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
conv6_3 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
upsp2 (UpSampling2D)         (None, 24, 24, 512)       0
_________________________________________________________________
conv7_1 (Conv2D)             (None, 24, 24, 512)       2359808
_________________________________________________________________
conv7_2 (Conv2D)             (None, 24, 24, 512)       2359808
_________________________________________________________________
conv7_3 (Conv2D)             (None, 24, 24, 512)       2359808
_________________________________________________________________
upsp3 (UpSampling2D)         (None, 48, 48, 512)       0
_________________________________________________________________
conv8_1 (Conv2D)             (None, 48, 48, 256)       1179904
_________________________________________________________________
conv8_2 (Conv2D)             (None, 48, 48, 256)       590080
_________________________________________________________________
conv8_3 (Conv2D)             (None, 48, 48, 256)       590080
_________________________________________________________________
upsp4 (UpSampling2D)         (None, 96, 96, 256)       0
_________________________________________________________________
conv9_1 (Conv2D)             (None, 96, 96, 128)       295040
_________________________________________________________________
conv9_2 (Conv2D)             (None, 96, 96, 128)       147584
_________________________________________________________________
upsp5 (UpSampling2D)         (None, 192, 192, 128)     0
_________________________________________________________________
conv10_1 (Conv2D)            (None, 192, 192, 64)      73792
_________________________________________________________________
conv10_2 (Conv2D)            (None, 192, 192, 64)      36928
_________________________________________________________________
conv11 (Conv2D)              (None, 192, 192, 3)       1731
=================================================================
Total params: 31,787,523
Trainable params: 31,787,523
Non-trainable params: 0
_________________________________________________________________

The last convolutional layer returns a shape of (192, 192, 3) but I need to return an image with shape (200, 200, 1).

I think I can change the last convolutional layer with this one to get a 1 channel image:

conv11 = Conv2D(1, 3, activation = 'relu', padding = 'same', name = 'conv11')(conv10)

But I don't know if this is correct because I've been reading about VGG16 network and it is for 3 channels images.

Can I use VGG16 for one channel images?


问:
Other than portability and security reasons, why would someone want to run their existing go/rust/c++ applications in web browsers via WebAssembly?
Understand that WebAssembly code can be executed at near-native speed across different platforms and that it can be run in modern web browsers.

Other than the above reasons (portability, performance) and perhaps security reasons, why would someone want to run their existing go/rust/c++ applications in web browsers?

Just thought that what should run in web browsers should continue to run in web browsers (i.e., javascript/typescript) and what should run on systems should continue to run on systems (Rust, Go, C/C++)

Nathan Aw (Singapore)

答:
One reason is that they may have an application or library and they don't want to rewrite in Javascript. For example, if they have already made a game in a systems language and they want people on the web to be able to play it, they won't want to rewrite in javascript.

Javascript can be rather annoying to use in very large projects because it wasn't really designed for them. It might just be easier to write good code in a different language.


问:
how to deploy web.config modifications in a Sharepoint web application?
I have a website in Sharepoint 2007. We use a wsp to deploy our projects. We can deploy dlls, usercontrols, features, but i don't know how to include new lines in the web.config.

Which would be a possible way to make changes in web.config?

Another thing, how can I include resources (resx) in the wsp?

答:
Manually editing the web.config in a multi-server farm is a Bad Idea. Ensuring the web.config files stay in sync on each WFE will become a nightmare quickly.

Using the SPWebConfigModification class to manage web.config changes across the farm is a Good Idea, as changes will be persisted in the SharePoint configuration database, and automatically pushed to every server in the farm.

Having said that, coding against the class can be a pain. Luckily there's a pretty good front-end that's freely available, giving you a configuration screen in Central Administration to add/remove web.config changes.

OwnerDisplayName: netadictos

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: EvilGoatBob


问:
Django test not loading fixture data
I have written tests for a Django project that i am working on, but one particular fixture fails to load.
The fixture is generated using dumpdata and i havent fiddled with it at all.
I can load the data using manage.py on that fixture without errors. I have verified that the data actually loaded using shell and querying the data.
This is driving me nuts, any help would be much appreciated.

Here is my test file (irrelevant portions removed):

```<code>class ViewsFromUrls(TestCase):
    fixtures = [
        'centers/fixtures/test_data.json',
        'intranet/fixtures/test_data.json',
        'training/fixtures/test_data.json', #The one that fails to load
        ]

    def setUp(self):
        self.c = Client()
        self.c.login(username='USER', password='PASS')

    ...

    def test_ViewBatch(self):
        b = Batch.objects.all()[0].ticket_number
        response = self.c.get(reverse('training.views.view_batch', kwargs={'id':b}))
        self.assertTrue(response.status_code, 200)
    ...
</code>```

答:
Import the TestCase from django.test:

```<code>from django.test import TestCase

class test_something(TestCase):
    fixtures = ['one.json', 'two.json']
    ...
</code>```

Not: import unittest

Not: import django.utils.unittest

But: import django.test

That's a day of frustration right there.
Stop complaining - it's in the docs :-/

Title: Django test not loading fixture data

Body:
I have written tests for a Django project that i am working on, but one particular fixture fails to load.
The fixture is generated using dumpdata and i havent fiddled with it at all.
I can load the data using manage.py on that fixture without errors. I have verified that the data actually loaded using shell and querying the data.
This is driving me nuts, any help would be much appreciated.

Here is my test file (irrelevant portions removed):

class ViewsFromUrls(TestCase):
    fixtures = [
        'centers/fixtures/test_data.json',
        'intranet/fixtures/test_data.json',
        'training/fixtures/test_data.json', #The one that fails to load
        ]

    def setUp(self):
        self.c = Client()
        self.c.login(username='USER', password='PASS')

    ...

    def test_ViewBatch(self):
        b = Batch.objects.all()[0].ticket_number
        response = self.c.get(reverse('training.views.view_batch', kwargs={'id':b}))
        self.assertTrue(response.status_code, 200)
    ...

Body:
Import the TestCase from django.test:

from django.test import TestCase

class test_something(TestCase):
    fixtures = ['one.json', 'two.json']
    ...

Not: import unittest

Not: import django.utils.unittest

But: import django.test

That's a day of frustration right there.
Stop complaining - it's in the docs :-/


问:
How to apply java based filter with JPA pagination?

Input request -

```<code>{
Page size = 20
page = 1
withIn distance 20 km;
}
</code>```

Below is the JPA implemented method.

```<code>List<Hotels> hotels =  findsByHotelAddress(Address address, Pageable pageable);
</code>```

let say, After a search, we got 20 hotels on the first page.

Now, after applying the distance filter, we got five users on the first page(1st request) and, four users on the second page(2nd request) and, six users on the third page(3rd request).

I want to know better approach if I want to display all the fifteen filtered hotels only on the 1st page.

FYI: Distance is calculated(using google map) based on user location and Hotel location.
The Distance field is not available in the DB column.

答:
You can try to implement Specification interface . Check it out for more details
Specification-Properties</p>

Body:
Input request -

{
Page size = 20
page = 1
withIn distance 20 km;
}

Below is the JPA implemented method.

List<Hotels> hotels =  findsByHotelAddress(Address address, Pageable pageable);

let say, After a search, we got 20 hotels on the first page.

Now, after applying the distance filter, we got five users on the first page(1st request) and, four users on the second page(2nd request) and, six users on the third page(3rd request).

I want to know better approach if I want to display all the fifteen filtered hotels only on the 1st page.

FYI: Distance is calculated(using google map) based on user location and Hotel location.
The Distance field is not available in the DB column.


问:
Unban command JDA 4.1.1_101, can't make it work and I don't know why
i'm coding a Discord bot with JDA 4.1.1_101. I created the "ban" command, but i can't make the unban command work. I can't really understand why... Thank you for your help.

if (args[0].equalsIgnoreCase(Main.prefix + "unban")) {
            if(event.getGuild().getSelfMember().hasPermission(Permission.BAN_MEMBERS)) {
                if (args.length > 0 && args.length < 3) {

                    try {
                        event.getMessage().delete().queue();
                        User member = event.getMessage().getMentionedMembers().get(0).getUser();

                        String id = member.getId();

                        event.getGuild().unban(id).queue();
                        EmbedBuilder ban = new EmbedBuilder();
                        ban.setColor(Color.GREEN);
                        ban.setTitle("UnBan");
                        ban.setDescription("UnBan Report");
                        ban.addField("Staffer: ", event.getMessage().getAuthor().getName(), true);
                        ban.addField("Unban: ", member.getName(), true);

                        logs.sendMessage(ban.build()).queue();

                    } catch (IndexOutOfBoundsException exx) {
                        EmbedBuilder error = new EmbedBuilder();
                        error.setColor(0xff3923);
                        error.setTitle("Error: User");
                        error.setDescription("Invalid user.");
                        event.getChannel().sendMessage(error.build()).queue(message -> {
                            message.delete().queueAfter(5, TimeUnit.SECONDS);
                        });
                    }

                } else {
                    EmbedBuilder error = new EmbedBuilder();
                    error.setColor(0xff3923);
                    error.setTitle("Error: Wrong usage.");
                    error.setDescription("Use: .unban [@user].");
                    event.getChannel().sendMessage(error.build()).queue(message -> {
                        message.delete().queueAfter(5, TimeUnit.SECONDS);
                    });
                }

            }
        }
```

答:
The problem is, that you are trying to retrieve the user from the mention in the message.

Since the user isn't part of the guild anymore, it seems like this doesn't work.

In order to work around this issue, you have to retrieve the ID manually.

A mention is always in the format <@userid> or <!@userid>.

<s>To get the ID you could just split the message and replace the unnecessary parts, e.g. String id = event.getMessage().getContentRaw().split("<")[1].split(">")[0].replace("!", "").replace("@", "");

I'm sure there are better and smoother ways for doing this. ;)</s>

A better way of retrieving the ID would be using a regex such as <@!?(\d+)> as mentioned by Minn.

In order to get the name of the user, you just need the ID via event.getJDA().getUserById(id).getName().

It's important to mention that you can't properly mention a user who isn't on the server (which is the case when they are banned).

(Addition: I tried using .getMentionedUsers() with the same result as OP.)


答:
.column-layout {
  max-width: 1200px;
  background-color: #fff;
  margin: 40px auto 0 auto;
}
img {max-width: 100%;}
.column-layout-one {
  max-width: 1200px;
  background-color: #fff;
  margin: 40px auto 0 auto;
}

.header-item-one {
  order: 1;
}

.header-item-two {
  order: 2;
}

@media (min-width: 768px) {
  .column-layout-one {
    display: flex;
    justify-content: space-between;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="column-layout-one">
  <div class="header-item-one">
    <img src="http://placehold.it/280x200">
  </div>
  <div class="header-item-two">
    <img src="http://placehold.it/900x200">
  </div>
</div></code>```

When I hit around 1200px I can see the 2 columns is starting moving together. How can that be?

Your .column-layout-one has max width 1200 set, inner elements has 280+900 = 1180 px, and you have used space-between on its parent. so, when the parent has space more than its defined width, inner items will be seprated by diffrence of 1200-1180 = 20px; as soon as its parent will shrink this space will reduce, because its the space left by these 2 divs,

Space-between = outerWidth - (Total of inner width)

if you want your images to fit in screen on mobile, then provide it
max-width: 100%, if you will not do so, itwill take its orignal width and distort your design.

Title: Flexbox is not fitting on mobile

Body:
This is my first week working with flexbox, and I like it a lot until now. I am doing everything I can to get away of floating elements. Therefore my main purpose is not a solution there is floating elements in. I run into 2 problems, that I am not quite sure of the correct saolution.

Problem 1:
When I hit around 1200px I can see the 2 columns is starting moving together. How can that be?

Problem 2:
Why is my columns not fitting on viewport under 768px? I can see on the mobile the 900x200 is going over the edge of the max width on telephone.

Example page of my code here.

.column-layout {
  max-width: 1200px;
  background-color: #fff;
  margin: 40px auto 0 auto;
}

.column-layout-one {
  max-width: 1200px;
  background-color: #fff;
  margin: 40px auto 0 auto;
}

.header-item-one {
  order: 1;
}

.header-item-two {
  order: 2;
}

@media (min-width: 768px) {
  .column-layout-one {
    display: flex;
    justify-content: space-between;
  }
}

Body:
.column-layout {
  max-width: 1200px;
  background-color: #fff;
  margin: 40px auto 0 auto;
}
img {max-width: 100%;}
.column-layout-one {
  max-width: 1200px;
  background-color: #fff;
  margin: 40px auto 0 auto;
}

.header-item-one {
  order: 1;
}

.header-item-two {
  order: 2;
}

@media (min-width: 768px) {
  .column-layout-one {
    display: flex;
    justify-content: space-between;
  }
}

<div class="column-layout-one">
  <div class="header-item-one">
    <img src="http://placehold.it/280x200">
  </div>
  <div class="header-item-two">
    <img src="http://placehold.it/900x200">
  </div>
</div>

When I hit around 1200px I can see the 2 columns is starting moving together. How can that be?

Your .column-layout-one has max width 1200 set, inner elements has 280+900 = 1180 px, and you have used space-between on its parent. so, when the parent has space more than its defined width, inner items will be seprated by diffrence of 1200-1180 = 20px; as soon as its parent will shrink this space will reduce, because its the space left by these 2 divs,

Space-between = outerWidth - (Total of inner width)

if you want your images to fit in screen on mobile, then provide it
max-width: 100%, if you will not do so, itwill take its orignal width and distort your design.


问:
jqGrid does not selects cell value as a selected dorp down value In edit mode
I am using jqGrid v 4.0 in my application to display tabuler data with Inline edit feature. One of the column in the Grid is a type of "Select". I have populated this select with following server side code:

```<code>    //get all Departments
    HRDept = $.ajax({
                        url: '../../PerformanceReview/GetHRDepartments/',
                        async: false,
                        success: function(data, result) {
                                    if (!result)
                                        alert('Failure to retrieve the HR Departments.');
                                 }
                         }).responseText;
</code>```

I have populated the Grid column with following sysntax:

```<code>    name: 'HRDepartment', index: 'Department', align: 'left', editable: true, edittype: 'select', editoptions: {value: HRDept}
</code>```

But on click of edit button (inline), it shows dropdown on on top of cell but the value is not equal to current cell value. it is always first value of drop down. I had compared the text which i am populating while loading Grid with the text of Dropdown and they are matching.

Could some one help me to set dropdown value similar as cell value.

答:
If you get the select values from the server you should use dataUrl option of the editoptions instead of value. Then the jqGrid will make the Ajax request at the beginning of the editing and fill the select element with the server response. It is important to understand that the server response should be in another form:

```<code><select>
    <option value='101 - Equity Partners'>101 - Equity Partners</option>
    …
</select>
</code>```

If you have already the code on the server which provide the information in another format and you can't change the server code you can define additional buildSelect function which get as the parameter the server response and should return the data in the above format ('...'). See UPDATED part of the answer for the code example.

Body:
I am using jqGrid v 4.0 in my application to display tabuler data with Inline edit feature. One of the column in the Grid is a type of "Select". I have populated this select with following server side code:

    //get all Departments
    HRDept = $.ajax({
                        url: '../../PerformanceReview/GetHRDepartments/',
                        async: false,
                        success: function(data, result) {
                                    if (!result)
                                        alert('Failure to retrieve the HR Departments.');
                                 }
                         }).responseText;

I have populated the Grid column with following sysntax:

    name: 'HRDepartment', index: 'Department', align: 'left', editable: true, edittype: 'select', editoptions: {value: HRDept}

But on click of edit button (inline), it shows dropdown on on top of cell but the value is not equal to current cell value. it is always first value of drop down. I had compared the text which i am populating while loading Grid with the text of Dropdown and they are matching.

Could some one help me to set dropdown value similar as cell value.

Body:
If you get the select values from the server you should use dataUrl option of the editoptions instead of value. Then the jqGrid will make the Ajax request at the beginning of the editing and fill the select element with the server response. It is important to understand that the server response should be in another form:

<select>
    <option value='101 - Equity Partners'>101 - Equity Partners</option>
    …
</select>

If you have already the code on the server which provide the information in another format and you can't change the server code you can define additional buildSelect function which get as the parameter the server response and should return the data in the above format ('...'). See UPDATED part of the answer for the code example.


问:
How to add numbers for a string sentence in Java?
I want to add numbers using Java.

For example, the sentence is given String: "My age is 50, and your age is under 30." If I want to add 5 to the sentence, it should be like
"My age is 55, and your age is under 35."

The restriction is the sentence is given, so you need to extract numbers from the sentence and add the numbers to the original sentence.

I was trying to split by space (" ") and try to add numbers after that.
But I don't know how to substitute numbers with the original sentence.

I am confused since it has comma when I am trying to split by " " and even if you can extract all the numbers from the sentence, I am not sure how can I get back to numbers to string.

```<code>public class Main {

public static Pattern pattern = Pattern.compile("\\d+");

public static String addNumber(String str, int n) {

    Matcher matcher = pattern.matcher(str);
    if (matcher.find()) {
        String theAge = matcher.group(0);
        int newAge = Integer.parseInt(theAge) + n;
    }

    String addSentence = str;

    return addSentence;
}

public static void main(String[] args) {
    String testString = "My age is 50, and your age is under 30.";
    String testString2 = "My age is 50, and your age is under 30 and my friend age is 44.";

    String newSent = addNumber(testString, 5);
    // -> should be "My age is 55, and your age is under 35.
    String newSent2 = addNumber(testString2, 10);
    // -> should be "My age is 60, and your age is under 40 and my friend age is 54.";

}
</code>```

}
enter code here

答:
You are given a string. The string may contain numbers. You want to add the same increment to each number that appears in the string. And you want to replace each number appearing in the string with that same number plus the increment.

I suggest using java regular expressions, in particular method replaceAll() which was added in Java 9. Here is the code.

import java.util.function.Function;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main(String[] args) {
        String str = "My age is 50, and your age is under 30.";
        if (args.length > 0) {
            str = args[0];
        }
        int temp = 5;
        if (args.length > 1) {
            temp = Integer.parseInt(args[1]);
        }
        final int increment = temp;
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(str);
        Function<MatchResult, String> replacer = new Function<MatchResult, String>() {
            public String apply(MatchResult matchResult) {
                String str = matchResult.group();
                int val = Integer.parseInt(str);
                val += increment;
                return String.valueOf(val);
            }
        };
        String result = matcher.replaceAll(replacer);
        System.out.println(result);
    }
}
```

<p>Note that since <code>java.util.function.Function</code> is a functional interface, you can use a lambda expression which may make the code shorter but I think the code above is easier to understand. Here is the result of running the above code.</p>

```My age is 55, and your age is under 35.
```

Body:
I want to add numbers using Java.

For example, the sentence is given String: "My age is 50, and your age is under 30." If I want to add 5 to the sentence, it should be like
"My age is 55, and your age is under 35."

The restriction is the sentence is given, so you need to extract numbers from the sentence and add the numbers to the original sentence.

I was trying to split by space (" ") and try to add numbers after that.
But I don't know how to substitute numbers with the original sentence.

I am confused since it has comma when I am trying to split by " " and even if you can extract all the numbers from the sentence, I am not sure how can I get back to numbers to string.

public class Main {

public static Pattern pattern = Pattern.compile("\\d+");

public static String addNumber(String str, int n) {

    Matcher matcher = pattern.matcher(str);
    if (matcher.find()) {
        String theAge = matcher.group(0);
        int newAge = Integer.parseInt(theAge) + n;
    }

    String addSentence = str;

    return addSentence;
}

public static void main(String[] args) {
    String testString = "My age is 50, and your age is under 30.";
    String testString2 = "My age is 50, and your age is under 30 and my friend age is 44.";

    String newSent = addNumber(testString, 5);
    // -> should be "My age is 55, and your age is under 35.
    String newSent2 = addNumber(testString2, 10);
    // -> should be "My age is 60, and your age is under 40 and my friend age is 54.";

}

}
enter code here

Body:
You are given a string. The string may contain numbers. You want to add the same increment to each number that appears in the string. And you want to replace each number appearing in the string with that same number plus the increment.

I suggest using java regular expressions, in particular method replaceAll() which was added in Java 9. Here is the code.

import java.util.function.Function;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main(String[] args) {
        String str = "My age is 50, and your age is under 30.";
        if (args.length > 0) {
            str = args[0];
        }
        int temp = 5;
        if (args.length > 1) {
            temp = Integer.parseInt(args[1]);
        }
        final int increment = temp;
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(str);
        Function<MatchResult, String> replacer = new Function<MatchResult, String>() {
            public String apply(MatchResult matchResult) {
                String str = matchResult.group();
                int val = Integer.parseInt(str);
                val += increment;
                return String.valueOf(val);
            }
        };
        String result = matcher.replaceAll(replacer);
        System.out.println(result);
    }
}

Note that since java.util.function.Function is a functional interface, you can use a lambda expression which may make the code shorter but I think the code above is easier to understand. Here is the result of running the above code.

My age is 55, and your age is under 35.


问:
Conda environment conflicts with 3rd party software
I ran into a problem where my python2 environment is conflicting with the included python and packages of 3rd party software. I get many Runtime Error's. One software I'm writing for has PySide2 already installed. So it complains when I run it under this environment, but I need PySide2 in my environment because there is also stand-alone tools as part of this environment.

I assume the RuntimeError's are coming from the DLLs and other compiled stuff in my python env, so how should I approach this problem?

What I tried initially is to create another conda environment, with just the libs that I need, no python interpreter. Then I would include the site-packages of this second environment to the PYTHONPATH of the first one. This way I can run the main one in stand-alone applications and IDE's, and for 3rd party software I just include site-packages in the PYTHONPATH without any conda environment. The problem with this is when I run conda install <mypackage> --no-deps (to avoid it from install python as a dependency), it defaults to python 3.8 packages, and also leaves me in the dark in terms of what packages dependencies I need and which I don't. I'm thinking for sure there a cleaner way to approach and manage this problem.

答: I don't what is the actual error for your case, but I faced this type of conflict between 3rd party python based software and conda several times.I resolve my problem by reinstalling anaconda and check of the option "use anaconda as your default python" at that time. May be it will be helpful for you.</p>


问:
How to convert "#00E4FF" to Brush in code?
I need to convert some color ( in Hex ) to Brush.
I need to do it in the code. </p>

<p>How can i do it ? </p>

答:
```<code>//this would be initialized somewhere else, I assume
string hex = "#00E4FF";

//strip out any # if they exist
hex = hex.Replace("#", string.Empty);

byte r = (byte)(Convert.ToUInt32(hex.Substring(0, 2), 16));
byte g = (byte)(Convert.ToUInt32(hex.Substring(2, 2), 16));
byte b = (byte)(Convert.ToUInt32(hex.Substring(4, 2), 16));

SolidColorBrush myBrush = new SolidColorBrush(Color.FromArgb(255, r, g, b));
</code>```

Body:
I need to convert some color ( in Hex ) to Brush.
I need to do it in the code.

How can i do it ?


问:
Why does cuda_free have such a high overhead? (is it due to zeroing?)
I observe cudaFree operation takes unacceptably long time to operate it. To verify it, I wrote a simple micro benchmark code to test cudaFree overhead. It shows the similar trend.

first step: cudaMallocManaged
It doesn't take that long time. Actually it is less than 1ms just only for cudaMallocManaged.

second step: init
To initialize malloced memory region, init function is called. And it also doesn't take less than 1ms.

third step: cudaFree
Now, the overhead appears. It takes a lot of time. One more things is bigger gets the memory size, Longer it takes. (beautifully linearly)

Question is "Why does cudaFree have such a huge overhead? Does it fill whole memory region with zero for security issue? Or any other critical path it walks through?"

Here is the code and the measured result.
Thank you in advance :) !!!

```<code>   10 int getMilliCount(){
   11   timeb tb;
   12   ftime(&tb);
   13   int nCount = tb.millitm + (tb.time & 0xfffff) * 1000;
   14   return nCount;
   15 }
   16
   17 int getTimeDiff(int baseTime){
   18   int diff = getMilliCount() - baseTime;
   19   return diff;
   20 }
   21
   22 __global__ void init(int* x, size_t bytes_){
   23   int num_ = bytes_/sizeof(int);
   24   for (int i=0; i<num_; i++){
   25     x[i] = i;
   26   }
   27 }
   28
   29 int main(){
   30   printf("sizeof(size_t): %zu\n", sizeof(size_t));
   31   printf("sizeof(unsigned int): %zu\n", sizeof(unsigned int));
   32   printf("sizeof(int): %zu\n", sizeof(int));
   33   printf("sizeof(long): %zu\n", sizeof(long));
   34
   35   std::ofstream myfile;
   36   myfile.open("output3.csv");
   37   myfile<<"operation, num_bytes, start, end, duration\n";
   38   int baseTime = getMilliCount();
   39   int* dptr;
   40   int ts1 = 0;
   41   int ts2 = 0;
   42   size_t KB = 1024; // start from 1KB
   43   int num_trial_ = 1;
   44   for (int j=10; j<25; j++){
   45     size_t num_bytes_ = KB<<j;
   46     for (int i=0; i<num_trial_; i++){
   47       // measuring cudaMallocManaged
   48       ts1 = getTimeDiff(baseTime);
>> 49       cudaMallocManaged((void**)&dptr, num_bytes_);
   50       ts2 = getTimeDiff(baseTime);
   51       myfile<<"cudaMallocManaged, "<<num_bytes_/(1024*1024)<<","<<ts1<<","<<ts2<<","<<ts2-ts1<<"\n";
   52       //printf("cudaMallocManaged, memory_size:%zuMB, start:%d, end:%d, duration:%d\n", num_bytes_/(1024*1024), ts1, ts2, ts2-ts1);
   53       printf("cudaMallocManaged, memory_size:%zuMB, duration:%d\n", num_bytes_/(1024*1024), ts2-ts1);
   54
   55       // measuring initialization
   56       ts1 = getTimeDiff(baseTime);
>> 57       init<<<1,1>>>(dptr, num_bytes_);
   58       ts2 = getTimeDiff(baseTime);
   59       myfile<<"initialization, "<<num_bytes_/(1024*1024)<<","<<ts1<<","<<ts2<<","<<ts2-ts1<<"\n";
   60       //printf("init, memory_size:%zuMB, start:%d, end:%d, duration:%d\n", num_bytes_/(1024*1024), ts1, ts2, ts2-ts1);
   61       printf("init, memory_size:%zuMB, duration:%d\n", num_bytes_/(1024*1024), ts2-ts1);
   62
   63       // measuring cudaFree
   64       ts1 = getTimeDiff(baseTime);
>> 65       cudaFree(dptr);
   66       ts2 = getTimeDiff(baseTime);
   67       myfile<<"cudaFree, "<<num_bytes_/(1024*1024)<<","<<ts1<<","<<ts2<<","<<ts2-ts1<<"\n";
   68       //printf("cudaFree, memory_size:%zuMB, start:%d, end:%d, duration:%d\n", num_bytes_/(1024*1024), ts1, ts2, ts2-ts1);
   69       printf("cudaFree, memory_size:%zuMB, duration:%d\n", num_bytes_/(1024*1024), ts2-ts1);
   70       sleep(1);
   71       printf("\n");
   72     }
   73   }
   74   myfile.close();
   75   return 1;
   76 }
</code>```

Results

```<code>cudaMallocManaged, memory_size:1MB, duration:360
init, memory_size:1MB, duration:0
cudaFree, memory_size:1MB, **duration:2**

cudaMallocManaged, memory_size:2MB, duration:1
init, memory_size:2MB, duration:0
cudaFree, memory_size:2MB, **duration:4**

cudaMallocManaged, memory_size:4MB, duration:0
init, memory_size:4MB, duration:0
cudaFree, memory_size:4MB, **duration:9**

cudaMallocManaged, memory_size:8MB, duration:0
init, memory_size:8MB, duration:0
cudaFree, memory_size:8MB, **duration:18**

cudaMallocManaged, memory_size:16MB, duration:0
init, memory_size:16MB, duration:0
cudaFree, memory_size:16MB, **duration:34**

cudaMallocManaged, memory_size:32MB, duration:0
init, memory_size:32MB, duration:0
cudaFree, memory_size:32MB, **duration:69**

cudaMallocManaged, memory_size:64MB, duration:0
init, memory_size:64MB, duration:0
cudaFree, memory_size:64MB, **duration:132**

cudaMallocManaged, memory_size:128MB, duration:0
init, memory_size:128MB, duration:0
cudaFree, memory_size:128MB, **duration:241**

cudaMallocManaged, memory_size:256MB, duration:0
init, memory_size:256MB, duration:0
cudaFree, memory_size:256MB, **duration:476**

cudaMallocManaged, memory_size:512MB, duration:0
init, memory_size:512MB, duration:0
cudaFree, memory_size:512MB, **duration:984**

cudaMallocManaged, memory_size:1024MB, duration:0
init, memory_size:1024MB, duration:0
cudaFree, memory_size:1024MB, **duration:1910**

cudaMallocManaged, memory_size:2048MB, duration:0
init, memory_size:2048MB, duration:1
cudaFree, memory_size:2048MB, **duration:3830**

cudaMallocManaged, memory_size:4096MB, duration:0
init, memory_size:4096MB, duration:0
cudaFree, memory_size:4096MB, **duration:7715**

cudaMallocManaged, memory_size:8192MB, duration:0
init, memory_size:8192MB, duration:0
cudaFree, memory_size:8192MB, **duration:0**

cudaMallocManaged, memory_size:16384MB, duration:0
init, memory_size:16384MB, duration:0
cudaFree, memory_size:16384MB, **duration:0**
</code>```

weird thing is that 8192MB and 16384MB shows less than 0ms not only for cudaManagedMalloc and init but also for cudaFree....

Please enlighten me

答:
Why does cudaFree have such a huge overhead?

It doesn't. The timing method you are using is incorrect and the time you attributed to cudaFree comes from prior asynchronous operations

Does it fill whole memory region with zero for security issue?

No

Or any other critical path it walks through?

No, except it requires the device to be idle, which it is not in your case.

Let's fix the most obvious problem with you code:

```<code>  // measuring initialization
  ts1 = getTimeDiff(baseTime);
  init<<<1,1>>>(dptr, num_bytes_);
  cudaDeviceSynchronize(); // Wait until the GPU is idle
  ts2 = getTimeDiff(baseTime);
</code>```

And then run your experiment:

```<code>$ nvcc -std=c++11 -o fliestime fliestime.cu

$ ./fliestime
sizeof(size_t): 8
sizeof(unsigned int): 4
sizeof(int): 4
sizeof(long): 8
cudaMallocManaged, memory_size:1MB, duration:102
init, memory_size:1MB, duration:2
cudaFree, memory_size:1MB, duration:1

cudaMallocManaged, memory_size:2MB, duration:0
init, memory_size:2MB, duration:5
cudaFree, memory_size:2MB, duration:0

cudaMallocManaged, memory_size:4MB, duration:1
init, memory_size:4MB, duration:8
cudaFree, memory_size:4MB, duration:0

cudaMallocManaged, memory_size:8MB, duration:1
init, memory_size:8MB, duration:17
cudaFree, memory_size:8MB, duration:1

cudaMallocManaged, memory_size:16MB, duration:1
init, memory_size:16MB, duration:33
cudaFree, memory_size:16MB, duration:1

cudaMallocManaged, memory_size:32MB, duration:3
init, memory_size:32MB, duration:65
cudaFree, memory_size:32MB, duration:2

cudaMallocManaged, memory_size:64MB, duration:5
init, memory_size:64MB, duration:121
cudaFree, memory_size:64MB, duration:4

cudaMallocManaged, memory_size:128MB, duration:9
init, memory_size:128MB, duration:219
cudaFree, memory_size:128MB, duration:8

cudaMallocManaged, memory_size:256MB, duration:17
init, memory_size:256MB, duration:427
cudaFree, memory_size:256MB, duration:18

cudaMallocManaged, memory_size:512MB, duration:34
init, memory_size:512MB, duration:854
cudaFree, memory_size:512MB, duration:35

cudaMallocManaged, memory_size:1024MB, duration:67
init, memory_size:1024MB, duration:1709
cudaFree, memory_size:1024MB, duration:70

cudaMallocManaged, memory_size:2048MB, duration:133
init, memory_size:2048MB, duration:3418
cudaFree, memory_size:2048MB, duration:141

cudaMallocManaged, memory_size:4096MB, duration:786
init, memory_size:4096MB, duration:4
cudaFree, memory_size:4096MB, duration:0

cudaMallocManaged, memory_size:8192MB, duration:0
init, memory_size:8192MB, duration:0
cudaFree, memory_size:8192MB, duration:0

cudaMallocManaged, memory_size:16384MB, duration:0
init, memory_size:16384MB, duration:0
cudaFree, memory_size:16384MB, duration:0
</code>```

You can see that the time you have assumed is cudaFree is the time your completely serial init kernel takes to run. Both cudaMallocManaged and cudaFree do use more time as the allocations increase in size, but that isn't unreasonable IMHO.

weird thing is that 8192MB and 16384MB shows less than 0ms not only for cudaManagedMalloc and init but also for cudaFree....

That is because nothing is running. If you employ correct runtime error checking, you will see that everything is failing with out of memory runtime errors.

Body:
I observe cudaFree operation takes unacceptably long time to operate it. To verify it, I wrote a simple micro benchmark code to test cudaFree overhead. It shows the similar trend.

first step: cudaMallocManaged
It doesn't take that long time. Actually it is less than 1ms just only for cudaMallocManaged.

second step: init
To initialize malloced memory region, init function is called. And it also doesn't take less than 1ms.

third step: cudaFree
Now, the overhead appears. It takes a lot of time. One more things is bigger gets the memory size, Longer it takes. (beautifully linearly)

Question is "Why does cudaFree have such a huge overhead? Does it fill whole memory region with zero for security issue? Or any other critical path it walks through?"

Here is the code and the measured result.
Thank you in advance :) !!!

   10 int getMilliCount(){
   11   timeb tb;
   12   ftime(&tb);
   13   int nCount = tb.millitm + (tb.time & 0xfffff) * 1000;
   14   return nCount;
   15 }
   16
   17 int getTimeDiff(int baseTime){
   18   int diff = getMilliCount() - baseTime;
   19   return diff;
   20 }
   21
   22 __global__ void init(int* x, size_t bytes_){
   23   int num_ = bytes_/sizeof(int);
   24   for (int i=0; i<num_; i++){
   25     x[i] = i;
   26   }
   27 }
   28
   29 int main(){
   30   printf("sizeof(size_t): %zu\n", sizeof(size_t));
   31   printf("sizeof(unsigned int): %zu\n", sizeof(unsigned int));
   32   printf("sizeof(int): %zu\n", sizeof(int));
   33   printf("sizeof(long): %zu\n", sizeof(long));
   34
   35   std::ofstream myfile;
   36   myfile.open("output3.csv");
   37   myfile<<"operation, num_bytes, start, end, duration\n";
   38   int baseTime = getMilliCount();
   39   int* dptr;
   40   int ts1 = 0;
   41   int ts2 = 0;
   42   size_t KB = 1024; // start from 1KB
   43   int num_trial_ = 1;
   44   for (int j=10; j<25; j++){
   45     size_t num_bytes_ = KB<<j;
   46     for (int i=0; i<num_trial_; i++){
   47       // measuring cudaMallocManaged
   48       ts1 = getTimeDiff(baseTime);
>> 49       cudaMallocManaged((void**)&dptr, num_bytes_);
   50       ts2 = getTimeDiff(baseTime);
   51       myfile<<"cudaMallocManaged, "<<num_bytes_/(1024*1024)<<","<<ts1<<","<<ts2<<","<<ts2-ts1<<"\n";
   52       //printf("cudaMallocManaged, memory_size:%zuMB, start:%d, end:%d, duration:%d\n", num_bytes_/(1024*1024), ts1, ts2, ts2-ts1);
   53       printf("cudaMallocManaged, memory_size:%zuMB, duration:%d\n", num_bytes_/(1024*1024), ts2-ts1);
   54
   55       // measuring initialization
   56       ts1 = getTimeDiff(baseTime);
>> 57       init<<<1,1>>>(dptr, num_bytes_);
   58       ts2 = getTimeDiff(baseTime);
   59       myfile<<"initialization, "<<num_bytes_/(1024*1024)<<","<<ts1<<","<<ts2<<","<<ts2-ts1<<"\n";
   60       //printf("init, memory_size:%zuMB, start:%d, end:%d, duration:%d\n", num_bytes_/(1024*1024), ts1, ts2, ts2-ts1);
   61       printf("init, memory_size:%zuMB, duration:%d\n", num_bytes_/(1024*1024), ts2-ts1);
   62
   63       // measuring cudaFree
   64       ts1 = getTimeDiff(baseTime);
>> 65       cudaFree(dptr);
   66       ts2 = getTimeDiff(baseTime);
   67       myfile<<"cudaFree, "<<num_bytes_/(1024*1024)<<","<<ts1<<","<<ts2<<","<<ts2-ts1<<"\n";
   68       //printf("cudaFree, memory_size:%zuMB, start:%d, end:%d, duration:%d\n", num_bytes_/(1024*1024), ts1, ts2, ts2-ts1);
   69       printf("cudaFree, memory_size:%zuMB, duration:%d\n", num_bytes_/(1024*1024), ts2-ts1);
   70       sleep(1);
   71       printf("\n");
   72     }
   73   }
   74   myfile.close();
   75   return 1;
   76 }

Results

cudaMallocManaged, memory_size:1MB, duration:360
init, memory_size:1MB, duration:0
cudaFree, memory_size:1MB, **duration:2**

cudaMallocManaged, memory_size:2MB, duration:1
init, memory_size:2MB, duration:0
cudaFree, memory_size:2MB, **duration:4**

cudaMallocManaged, memory_size:4MB, duration:0
init, memory_size:4MB, duration:0
cudaFree, memory_size:4MB, **duration:9**

cudaMallocManaged, memory_size:8MB, duration:0
init, memory_size:8MB, duration:0
cudaFree, memory_size:8MB, **duration:18**

cudaMallocManaged, memory_size:16MB, duration:0
init, memory_size:16MB, duration:0
cudaFree, memory_size:16MB, **duration:34**

cudaMallocManaged, memory_size:32MB, duration:0
init, memory_size:32MB, duration:0
cudaFree, memory_size:32MB, **duration:69**

cudaMallocManaged, memory_size:64MB, duration:0
init, memory_size:64MB, duration:0
cudaFree, memory_size:64MB, **duration:132**

cudaMallocManaged, memory_size:128MB, duration:0
init, memory_size:128MB, duration:0
cudaFree, memory_size:128MB, **duration:241**

cudaMallocManaged, memory_size:256MB, duration:0
init, memory_size:256MB, duration:0
cudaFree, memory_size:256MB, **duration:476**

cudaMallocManaged, memory_size:512MB, duration:0
init, memory_size:512MB, duration:0
cudaFree, memory_size:512MB, **duration:984**

cudaMallocManaged, memory_size:1024MB, duration:0
init, memory_size:1024MB, duration:0
cudaFree, memory_size:1024MB, **duration:1910**

cudaMallocManaged, memory_size:2048MB, duration:0
init, memory_size:2048MB, duration:1
cudaFree, memory_size:2048MB, **duration:3830**

cudaMallocManaged, memory_size:4096MB, duration:0
init, memory_size:4096MB, duration:0
cudaFree, memory_size:4096MB, **duration:7715**

cudaMallocManaged, memory_size:8192MB, duration:0
init, memory_size:8192MB, duration:0
cudaFree, memory_size:8192MB, **duration:0**

cudaMallocManaged, memory_size:16384MB, duration:0
init, memory_size:16384MB, duration:0
cudaFree, memory_size:16384MB, **duration:0**

weird thing is that 8192MB and 16384MB shows less than 0ms not only for cudaManagedMalloc and init but also for cudaFree....

Please enlighten me

Body:
Why does cudaFree have such a huge overhead?

It doesn't. The timing method you are using is incorrect and the time you attributed to cudaFree comes from prior asynchronous operations

Does it fill whole memory region with zero for security issue?

No

Or any other critical path it walks through?

No, except it requires the device to be idle, which it is not in your case.

Let's fix the most obvious problem with you code:

  // measuring initialization
  ts1 = getTimeDiff(baseTime);
  init<<<1,1>>>(dptr, num_bytes_);
  cudaDeviceSynchronize(); // Wait until the GPU is idle
  ts2 = getTimeDiff(baseTime);

And then run your experiment:

$ nvcc -std=c++11 -o fliestime fliestime.cu

$ ./fliestime
sizeof(size_t): 8
sizeof(unsigned int): 4
sizeof(int): 4
sizeof(long): 8
cudaMallocManaged, memory_size:1MB, duration:102
init, memory_size:1MB, duration:2
cudaFree, memory_size:1MB, duration:1

cudaMallocManaged, memory_size:2MB, duration:0
init, memory_size:2MB, duration:5
cudaFree, memory_size:2MB, duration:0

cudaMallocManaged, memory_size:4MB, duration:1
init, memory_size:4MB, duration:8
cudaFree, memory_size:4MB, duration:0

cudaMallocManaged, memory_size:8MB, duration:1
init, memory_size:8MB, duration:17
cudaFree, memory_size:8MB, duration:1

cudaMallocManaged, memory_size:16MB, duration:1
init, memory_size:16MB, duration:33
cudaFree, memory_size:16MB, duration:1

cudaMallocManaged, memory_size:32MB, duration:3
init, memory_size:32MB, duration:65
cudaFree, memory_size:32MB, duration:2

cudaMallocManaged, memory_size:64MB, duration:5
init, memory_size:64MB, duration:121
cudaFree, memory_size:64MB, duration:4

cudaMallocManaged, memory_size:128MB, duration:9
init, memory_size:128MB, duration:219
cudaFree, memory_size:128MB, duration:8

cudaMallocManaged, memory_size:256MB, duration:17
init, memory_size:256MB, duration:427
cudaFree, memory_size:256MB, duration:18

cudaMallocManaged, memory_size:512MB, duration:34
init, memory_size:512MB, duration:854
cudaFree, memory_size:512MB, duration:35

cudaMallocManaged, memory_size:1024MB, duration:67
init, memory_size:1024MB, duration:1709
cudaFree, memory_size:1024MB, duration:70

cudaMallocManaged, memory_size:2048MB, duration:133
init, memory_size:2048MB, duration:3418
cudaFree, memory_size:2048MB, duration:141

cudaMallocManaged, memory_size:4096MB, duration:786
init, memory_size:4096MB, duration:4
cudaFree, memory_size:4096MB, duration:0

cudaMallocManaged, memory_size:8192MB, duration:0
init, memory_size:8192MB, duration:0
cudaFree, memory_size:8192MB, duration:0

cudaMallocManaged, memory_size:16384MB, duration:0
init, memory_size:16384MB, duration:0
cudaFree, memory_size:16384MB, duration:0

You can see that the time you have assumed is cudaFree is the time your completely serial init kernel takes to run. Both cudaMallocManaged and cudaFree do use more time as the allocations increase in size, but that isn't unreasonable IMHO.

weird thing is that 8192MB and 16384MB shows less than 0ms not only for cudaManagedMalloc and init but also for cudaFree....

That is because nothing is running. If you employ correct runtime error checking, you will see that everything is failing with out of memory runtime errors.


问:
Draw a object comparing two different values of stencil buffer
First draw Geometry_A and write to stencil buffer with the following value.

```<code>glStencilOp(GL_REPLACE, GL_KEEP, GL_KEEP);  // replace stencil buffer values to ref=1
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
glStencilFunc(GL_NEVER, 1, 0xFF); // never pass stencil test
glStencilMask(0xFF);
Draw Geometry_A
</code>```

Draw Geometry_B and write to the stencil buffer with following Value.

```<code> glStencilFunc(GL_NEVER, 2, 0xFF); // never pass stencil test
 glStencilMask(0xFF);
 Draw Geometry_B
</code>```

Draw Geomtery_C Comparing the stencil value of Geometry_A

```<code>glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glStencilFunc(GL_EQUAL, 1, 0xFF);
</code>```

Draw Geomtery_D Comparing the stencil value of Geometry_B

```<code>glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glStencilFunc(GL_EQUAL, 2, 0xFF);
</code>```

Can we draw a geometry comparing both the values of stencil buffer from Geometry_A and Geometry_B

something like.

```<code>glStencilFunc(GL_EQUAL, 1 & 2, 0xFF);
</code>```

答:
Can we draw a geometry comparing both the values of stencil buffer from Geometry_A and Geometry_B

Yes of course, just set a bit in the stencil buffer, instead of changing all bits.

Set the bit mask 0x01 for geometry Geometry_A

```<code>glStencilFunc(GL_NEVER, 1, 0xFF); // never pass stencil test
glStencilMask(0x01);
</code>```

Set the bit mask 0x02 for geometry Geometry_B

```<code>glStencilFunc(GL_NEVER, 2, 0xFF); // never pass stencil test
glStencilMask(0x02);
</code>```

If you want to find the sections where Geometry_A and Geometry_B have been drawn, then you have to find test if the fist 2 bits in the stencil buffer are set.

```<code>glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glStencilFunc(GL_EQUAL, 3, 0x03);
</code>```

Note, with this approach the bits 3 to 8 are not affected at all.

Body:
First draw Geometry_A and write to stencil buffer with the following value.

glStencilOp(GL_REPLACE, GL_KEEP, GL_KEEP);  // replace stencil buffer values to ref=1
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
glStencilFunc(GL_NEVER, 1, 0xFF); // never pass stencil test
glStencilMask(0xFF);
Draw Geometry_A

Draw Geometry_B and write to the stencil buffer with following Value.

 glStencilFunc(GL_NEVER, 2, 0xFF); // never pass stencil test
 glStencilMask(0xFF);
 Draw Geometry_B

Draw Geomtery_C Comparing the stencil value of Geometry_A

glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glStencilFunc(GL_EQUAL, 1, 0xFF);

Draw Geomtery_D Comparing the stencil value of Geometry_B

glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glStencilFunc(GL_EQUAL, 2, 0xFF);

Can we draw a geometry comparing both the values of stencil buffer from Geometry_A and Geometry_B

something like.

glStencilFunc(GL_EQUAL, 1 & 2, 0xFF);

Body:
Can we draw a geometry comparing both the values of stencil buffer from Geometry_A and Geometry_B

Yes of course, just set a bit in the stencil buffer, instead of changing all bits.

Set the bit mask 0x01 for geometry Geometry_A

glStencilFunc(GL_NEVER, 1, 0xFF); // never pass stencil test
glStencilMask(0x01);

Set the bit mask 0x02 for geometry Geometry_B

glStencilFunc(GL_NEVER, 2, 0xFF); // never pass stencil test
glStencilMask(0x02);

If you want to find the sections where Geometry_A and Geometry_B have been drawn, then you have to find test if the fist 2 bits in the stencil buffer are set.

glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glStencilFunc(GL_EQUAL, 3, 0x03);

Note, with this approach the bits 3 to 8 are not affected at all.


问:
Problem extracting model covariates for model summary table
I'm a graduate student using a linear regression (count) model to understand drivers of fish movement into and out of tidal wetlands. I am currently trying to generate a publication-worthy model summary table in r. I've been using the sel.table function which has been working well for this purpose.

However, I've been unable to generate a column that contains the individual model formulas. Below is my code which is based off of some nice instructions for using the MuMIn package. https://sites.google.com/site/rforfishandwildlifegrads/home/mumin_usage_examples

So to recap, my question pertains to the last line of code below,

How can I insert model formulas into a model selection table.**

```<code>install.packages("MuMIn")
library(MuMIn)

data = mtcars

models = list(
  model1 <- lm(mpg ~ cyl, data = data),
  model2 <- lm(mpg ~ cyl + hp, data = data),
  model3 <- lm(mpg ~ cyl * hp, data = data)
)

#create an object “out.put” that contains all of the model selection information
out.put <- model.sel(models)

#coerce the object out.put into a data frame
sel.table <-as.data.frame(out.put)[6:10]

#add a column for model names
sel.table$Model <- rownames(sel.table)

#replace model name with formulas
for(i in 1:nrow(sel.table)) sel.table$Model[i]<- as.character(formula(paste(sel.table$Model[i])))[3]

#Any help on this topic would be greatly appreciated!
</code>```

UPDATED CODE

My method of pulling out model names is pretty clunky but otherwise this code seems to generate what I intended (a complete model selection table). Also, I'm not sure if the model coefficients are displayed properly but I hope to follow up on this for my final answer.

```<code>data = mtcars

#write linear models
models = list(
  model1 <- lm(mpg ~ cyl, data = data),
  model2 <- lm(mpg ~ cyl + hp, data = data),
  model3 <- lm(mpg ~ cyl * hp + disp, data = data),
  model4 <- lm(mpg ~ cyl * hp + disp + wt + drat, data = data)
)

#create an object “out.put” that contains all of the model selection information
out.put <- model.sel(models)

#coerce the object out.put into a data frame
sel.table <-as.data.frame(out.put)

#slightly rename intercept column
names(sel.table)[1]="Intercept"

#select variables to display in model summary table
sel.table <- sel.table %>%
 select(Intercept,cyl,hp,disp,wt,drat,df,logLik,AICc,delta)

#round numerical coumns
sel.table[,1:6]<- round(sel.table[,1:6],2)

sel.table[,8:10]<-round(sel.table[,8:10],2)

#add a column for model (row) names
sel.table$Model <- rownames(sel.table)

#extract model formulas
form <- data.frame(name = as.character(lapply(models, `[[`, c(10,2))))

#generate a column with model (row) numbers (beside associated model formulas)
form <- form %>%
  mutate(Model=(1:4))

#merge model table and model formulas
sum_table <- merge (form,sel.table,by="Model")

#rename model equation column
names(sum_table)[2]="Formula"

print <- flextable(head(sum_table))
print <- autofit(print)
print
</code>```

6/1/20 UPDATE:

Below is an image that describes two issues that I'm having with the code. I've found a workaround to the first question but I'm still investigating the second.
see details here

Models end up being misnumbered

Model formula columns are being generated for each model

答:
I believe there is a part of the code missing in the examples you followed, that is why your code does not work.

The easiest way to generate formula-like strings is simply to deparse the right hand side of the model formulas (i.e. 3-rd element):

sapply(get.models(out.put, TRUE), function(mo) deparse(formula(mo)[[3]], width.cutoff = 500))
```

<p>or, if you want <code>A*B</code>'s expanded into <code>A + B + A:B</code>:</p>

<pre class="lang-r prettyprint-override"><code>sapply(get.models(out.put, TRUE), function(mo) deparse(terms(formula(mo), simplify = TRUE)[[3]], width.cutoff = 500))
</code>```

Update: the original example code improved and simplified:

```<code>library(MuMIn)

data <- mtcars

#! Feed the models directly to `model.sel`. No need to create a separate list of
#! models.
gm <- lm(mpg ~ cyl, data = data)
out.put <- model.sel(
  model1 = gm,
  model2 = update(gm, . ~. + hp),
  model3 = update(gm, . ~ . * hp + disp),
  model4 = update(gm, . ~ . * hp + disp + wt + drat)
  )

sel.table <- out.put
sel.table$family <- NULL
sel.table <- round(sel.table, 2)
#! Use `get.models` to get the list of models in the same order as in the
#! selection table
sel.table <- cbind(
    Model =
#! Update (2): model number according to their original order, use:
       attr(out.put, "order"),
#!     otherwise: seq(nrow(sel.table)),
#!
#! Update (2): add a large `width.cutoff` to `deparse` so that the result is
#!         always a single string and `sapply` returns a character vector
#!         rather than a list.
#!         For oversize formulas, use `paste0(deparse(...), collapse = "")`
    formula = sapply(get.models(out.put, TRUE),
        function(mo) deparse(formula(mo)[[3]], width.cutoff = 500)),
#!
    sel.table
    )
</code>```

Body:
I'm a graduate student using a linear regression (count) model to understand drivers of fish movement into and out of tidal wetlands. I am currently trying to generate a publication-worthy model summary table in r. I've been using the sel.table function which has been working well for this purpose.

However, I've been unable to generate a column that contains the individual model formulas. Below is my code which is based off of some nice instructions for using the MuMIn package. https://sites.google.com/site/rforfishandwildlifegrads/home/mumin_usage_examples

So to recap, my question pertains to the last line of code below,

How can I insert model formulas into a model selection table.**

install.packages("MuMIn")
library(MuMIn)

data = mtcars

models = list(
  model1 <- lm(mpg ~ cyl, data = data),
  model2 <- lm(mpg ~ cyl + hp, data = data),
  model3 <- lm(mpg ~ cyl * hp, data = data)
)

#create an object “out.put” that contains all of the model selection information
out.put <- model.sel(models)

#coerce the object out.put into a data frame
sel.table <-as.data.frame(out.put)[6:10]

#add a column for model names
sel.table$Model <- rownames(sel.table)

#replace model name with formulas
for(i in 1:nrow(sel.table)) sel.table$Model[i]<- as.character(formula(paste(sel.table$Model[i])))[3]

#Any help on this topic would be greatly appreciated!

UPDATED CODE

My method of pulling out model names is pretty clunky but otherwise this code seems to generate what I intended (a complete model selection table). Also, I'm not sure if the model coefficients are displayed properly but I hope to follow up on this for my final answer.

data = mtcars

#write linear models
models = list(
  model1 <- lm(mpg ~ cyl, data = data),
  model2 <- lm(mpg ~ cyl + hp, data = data),
  model3 <- lm(mpg ~ cyl * hp + disp, data = data),
  model4 <- lm(mpg ~ cyl * hp + disp + wt + drat, data = data)
)

#create an object “out.put” that contains all of the model selection information
out.put <- model.sel(models)

#coerce the object out.put into a data frame
sel.table <-as.data.frame(out.put)

#slightly rename intercept column
names(sel.table)[1]="Intercept"

#select variables to display in model summary table
sel.table <- sel.table %>%
 select(Intercept,cyl,hp,disp,wt,drat,df,logLik,AICc,delta)

#round numerical coumns
sel.table[,1:6]<- round(sel.table[,1:6],2)

sel.table[,8:10]<-round(sel.table[,8:10],2)

#add a column for model (row) names
sel.table$Model <- rownames(sel.table)

#extract model formulas
form <- data.frame(name = as.character(lapply(models, `[[`, c(10,2))))

#generate a column with model (row) numbers (beside associated model formulas)
form <- form %>%
  mutate(Model=(1:4))

#merge model table and model formulas
sum_table <- merge (form,sel.table,by="Model")

#rename model equation column
names(sum_table)[2]="Formula"

print <- flextable(head(sum_table))
print <- autofit(print)
print

6/1/20 UPDATE:

Below is an image that describes two issues that I'm having with the code. I've found a workaround to the first question but I'm still investigating the second.
see details here

Models end up being misnumbered

Model formula columns are being generated for each model

Body:
I believe there is a part of the code missing in the examples you followed, that is why your code does not work.

The easiest way to generate formula-like strings is simply to deparse the right hand side of the model formulas (i.e. 3-rd element):

sapply(get.models(out.put, TRUE), function(mo) deparse(formula(mo)[[3]], width.cutoff = 500))

or, if you want A*B's expanded into A + B + A:B:

sapply(get.models(out.put, TRUE), function(mo) deparse(terms(formula(mo), simplify = TRUE)[[3]], width.cutoff = 500))

Update: the original example code improved and simplified:

library(MuMIn)

data <- mtcars

#! Feed the models directly to `model.sel`. No need to create a separate list of
#! models.
gm <- lm(mpg ~ cyl, data = data)
out.put <- model.sel(
  model1 = gm,
  model2 = update(gm, . ~. + hp),
  model3 = update(gm, . ~ . * hp + disp),
  model4 = update(gm, . ~ . * hp + disp + wt + drat)
  )

sel.table <- out.put
sel.table$family <- NULL
sel.table <- round(sel.table, 2)
#! Use `get.models` to get the list of models in the same order as in the
#! selection table
sel.table <- cbind(
    Model =
#! Update (2): model number according to their original order, use:
       attr(out.put, "order"),
#!     otherwise: seq(nrow(sel.table)),
#!
#! Update (2): add a large `width.cutoff` to `deparse` so that the result is
#!         always a single string and `sapply` returns a character vector
#!         rather than a list.
#!         For oversize formulas, use `paste0(deparse(...), collapse = "")`
    formula = sapply(get.models(out.put, TRUE),
        function(mo) deparse(formula(mo)[[3]], width.cutoff = 500)),
#!
    sel.table
    )


问:
Why does MiniDLNA stop indexing files?

I've read the useful question why is the minidlna database not refreshed and minidlna - not indexing files but this problem is different: It seems to stop scanning files at a certain file/after a certain directory.

Set up:

Running on Raspberry PI

Minidlna v1.2.1 from Raspbian Buster

Large music collection (although it only gets up to a few hundred files), a mix of formats.

fs.inotify.maxuserwatches=65536 in sysctl.conf

User minidlna has read access to full media library

/var/cache/minidlna where it keeps its database files, is on an ext4 partition.

Logging is set to:

```<code>log_level=debug,artwork=debug,database=debug,inotify=debug,scanner=debug,metadata=debug,http=warn,ssdp=debug,tivo=warn
</code>```

Watching top, the system does not seem to run out of memory while scanning.

The only error in the log is:

[2019/11/14 20:07:35] tagutils/tagutils-mp3.c:695: info: Bad header... dropping back for full frame search [/drive/files/Music/00 Various/some-song.mp3]

But the scan appears to continue after this.

The problem lines seem to be here:

```<code>[2019/11/14 20:07:35] scanner.c:730: info: Scanning /drive/files/Music/00 Various/SomeFolder
[2019/11/14 20:07:37] monitor.c:178: debug: Add watch to /drive/files/Music
</code>```

where it looks like it stops scanning and starts adding watches; there's no errors or warnings.

Stumped!

答:
I had to run

sudo minidlnad -d -R
to find I had a file with an invalid JPEG in it. Luckily, I could just delete the file. If that's not an option for you, there may be some way of editing the metadata for whatever file you have a problem with.

Title: Why does MiniDLNA stop indexing files?

Body:
I've read the useful question why is the minidlna database not refreshed and minidlna - not indexing files but this problem is different: It seems to stop scanning files at a certain file/after a certain directory.

Set up:

Running on Raspberry PI

Minidlna v1.2.1 from Raspbian Buster

Large music collection (although it only gets up to a few hundred files), a mix of formats.

fs.inotify.maxuserwatches=65536 in sysctl.conf

User minidlna has read access to full media library

/var/cache/minidlna where it keeps its database files, is on an ext4 partition.

Logging is set to:

log_level=debug,artwork=debug,database=debug,inotify=debug,scanner=debug,metadata=debug,http=warn,ssdp=debug,tivo=warn

Watching top, the system does not seem to run out of memory while scanning.

The only error in the log is:

[2019/11/14 20:07:35] tagutils/tagutils-mp3.c:695: info: Bad header... dropping back for full frame search [/drive/files/Music/00 Various/some-song.mp3]

But the scan appears to continue after this.

The problem lines seem to be here:

[2019/11/14 20:07:35] scanner.c:730: info: Scanning /drive/files/Music/00 Various/SomeFolder
[2019/11/14 20:07:37] monitor.c:178: debug: Add watch to /drive/files/Music

where it looks like it stops scanning and starts adding watches; there's no errors or warnings.

Stumped!


问:
Fastest way to read QR codes Client vs Server side
I am in the design stages of an app involving QR codes. It will be a contest where a user sees a QR code and scans it. The first user to scan the QR code is the winner.

Because the contest is on a first come first serve basis I want to make sure that the first user who scans the code is the winner. I have noticed that (at least from what I have read) there are Javascript and C# ways to read QR codes (Is there a JQuery way?).

Which way would be the fastest/fairest/most efficient? Assume that there will be many many people scanning a QR code at once. I want to makes sure that the first guy who scans it is the winner, and not get into issues because his request wasn't processed fast enough.

I guess the real question I would be asking would be this: When there are many users attempting one action on one app, would a client side or server side method work better? Would the differences have an effect like I am worried about? ect.

答: On a modern smartphone, detecting and decoding a QR code is something that can happen in under 100ms. I doubt variability in the client-side would produce any meaningful unfairness. But, I certainly think the client-side variability is smaller than the network variability which would come into play when uploading images rather than decoding client side.</p>


答:
I'm assuming config.yml is already available on the server. As you know, you can get the FileConfiguration instance of the default config by calling JavaPlugin#getConfig().

To get all elements in a configuration section, you can call ConfigurationSection#getKeys(boolean deep). As FileConfiguration implements ConfigurationSection, you can call the getkeys method on your FileConfiguration instance. The boolean indicates whether you want to get all deep paths as well.

Examples:

FileConfiguration#getKeys(false)

"spawn"

"lol"

"xd"

...

FileConfiguration#getKeys(true)

"spawn"

"spawn.World"

"spawn.X"

...

"lol"

"lol.World"

...

Title: Java config, need return function7

Body:
I have a config.yml file like this below:
How do I write a function that returns spawn, lol, xd, Warpa, Warphei?
I know that for example if I want to get X inside spawn I can do this plugin.getConfig().getString("spawn.X");
I just don't know how to list all of the names.

spawn:
  World: world
  X: 80.96770114181192
  Y: 72.0
  Z: -377.6790770077272
  Pitch: 14.682037
  Yaw: 113.62133
lol:
  World: world
  X: 109.60479547630788
  Y: 71.0
  Z: -353.9986813646272
  Pitch: 2.6992812
  Yaw: 102.31512
xd:
  World: world
  X: 106.59929856356823
  Y: 71.0
  Z: -354.65178849406584
  Pitch: 2.6992812
  Yaw: 102.31512
Warpa:
  World: world
  X: 188.43198209818965
  Y: 70.5998614967549
  Z: -331.69999998807907
  Pitch: 15.525846
  Yaw: -129.82843
Warphei:
  World: world
  X: 190.8221960506558
  Y: 70.5998614967549
  Z: -341.26133473481616
  Pitch: 15.525846
  Yaw: -129.82843


问:
"Cannot use import statement outside a module" in typeorm migration when run nestjs app
I have created the nestjs app. In the root app folder I have these subfolders:

dist

migration

src

test

The migration folder contains typeorm migrations.

When run application with npm run start:dev I have this error:

```<code>import {MigrationInterface, QueryRunner} from "typeorm";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:891:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
    at Function.Module._load (internal/modules/cjs/loader.js:723:14)
    at Module.require (internal/modules/cjs/loader.js:848:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Function.PlatformTools.load (C:\Users\dakru1\Documents\employo\employo-api\node_modules\typeorm\platform\PlatformTools.js:114:28)
    at C:\Users\dakru1\Documents\employo\employo-api\node_modules\typeorm\util\DirectoryExportedClassesLoader.js:39:69
    at Array.map (<anonymous>)
    at Object.importClassesFromDirectories (C:\Users\dakru1\Documents\employo\employo-api\node_modules\typeorm\util\DirectoryExportedClassesLoader.js:39:10)
</code>```

I understand the error message and I know how to fix it when it relates to application's code.

However, my problem is that this error come from typeorm migration file: [app-root-folder]\migration\1587067680466-Init.ts which shouldn't be used when application runs.

Why nestjs uses migration files. How can I ignore migration folder when running nestjs app?

答:
I had the same issue. I did the following as a workaround:

Set your ormconfig.json to look for migrations files with only js suffix:

"migrations": ["migrations/*.js"],

Install typescript globally: npm install -g typescript

After generating your migration, transpile typescript files to javascript files with typescript command:

tsc migrations/migration-file.ts

Run your migration: npm run typeorm migration:run

You can now run your application: npm run start:dev

Body:
I have created the nestjs app. In the root app folder I have these subfolders:

dist

migration

src

test

The migration folder contains typeorm migrations.

When run application with npm run start:dev I have this error:

import {MigrationInterface, QueryRunner} from "typeorm";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:891:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
    at Function.Module._load (internal/modules/cjs/loader.js:723:14)
    at Module.require (internal/modules/cjs/loader.js:848:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Function.PlatformTools.load (C:\Users\dakru1\Documents\employo\employo-api\node_modules\typeorm\platform\PlatformTools.js:114:28)
    at C:\Users\dakru1\Documents\employo\employo-api\node_modules\typeorm\util\DirectoryExportedClassesLoader.js:39:69
    at Array.map (<anonymous>)
    at Object.importClassesFromDirectories (C:\Users\dakru1\Documents\employo\employo-api\node_modules\typeorm\util\DirectoryExportedClassesLoader.js:39:10)

I understand the error message and I know how to fix it when it relates to application's code.

However, my problem is that this error come from typeorm migration file: [app-root-folder]\migration\1587067680466-Init.ts which shouldn't be used when application runs.

Why nestjs uses migration files. How can I ignore migration folder when running nestjs app?