问:
Convolutional Neural Networks, Implementation using MatConvNet toolbox. How to deal with Overfitting?
I've currently been working with CNN's and am having a hard time with what I believe is overfitting. Specifically, even though my training data converges to a minimum error, my validation data still refuses to drop in respect to error. My input data that I'm using is 512 x 650 x 1 x 4000 (2D data, 4000 samples) and there are only two classes to the data that I'm trying to distinguish between (class A and class B). I'm aware I in the future need many more samples, but for now, I just would like to see my validation error decline even a little before I invest in generating more data.

My networks have all been around 60-70 layers long and have included the following types of layers:

Block Example

Convolutional Layers [3 x 3] filter size, stride [1 x 1], padding [1 1 1 1]

ReLU Layers (Non-linearity)

Batch normalization (Tremendous help to training data convergence and implementation speed)

Max Pooling Layers [2 x 2] filters sizes, stride [2 x 2], padding [0 0 0 0]

I then repeat this "block" until my input data is a 1 x 1 x N size where I then run it through a a few fully connected layers, and then into a softmax.

My actual MatConvNet code is below for inspection and the output plots are attached. For the plots, blue represents my training error and orange represents my validation error. I'm linking my most recent from the code below.

My Questions:

1) How does one know what filter sizes to use for their data? I know its an empirical process, but surely there is some kind of intuition behind this? I've read papers (VGG.net, and more) on using the [3x3] small filters and using a lot of them, but even after designing a 70 layer network with this in mind, still no validation error decline.

2) I have tried dropout layers due to their popularity of reducing over fitting... I placed the dropout layers throughout my network after the ReLU and pooling layers in the "block" shown above, but between all convolutional layers. It unfortunately had no effect on my validation data, the error was still the same. Next I tried only using it after the fully connected layers since thats where the most neurons (or feature maps) are being created in my architecture, and still no luck. I've read the paper on dropout. Should I give up on using it? Is there once again "a trick" to this?

3) If I try a smaller network (I've read that's a descent way to deal with overfitting) how do I effectively reduce the size of my data? Just max pooling?

ANY suggestions would be wonderful.

Again, thank you all for reading this long question. I assure you I've done my research, and found that asking here might help me more in the long run.

CNN Error Output plot

MatConvNet Code (Matlab Toolbox for CNN Design)

```<code>opts.train.batchSize = 25;
opts.train.numEpochs = 200 ;
opts.train.continue = true ;
opts.train.gpus = [1] ;
opts.train.learningRate = 1e-3;
opts.train.weightDecay  = 0.04;
opts.train.momentum = 0.9;
opts.train.expDir = 'epoch_data';
opts.train.numSubBatches = 1;

bopts.useGpu = numel(opts.train.gpus) >  0 ;

load('imdb4k.mat');
net = dagnn.DagNN() ;

% Block #1

net.addLayer('conv1', dagnn.Conv('size', [3 3 1 64], 'hasBias', true, 'stride', [1, 1], 'pad', [1 1 1 1]), {'input'}, {'conv1'},  {'conv1f'  'conv1b'});

net.addLayer('relu1', dagnn.ReLU(), {'conv1'}, {'relu1'}, {});

net.addLayer('bn1', dagnn.BatchNorm('numChannels', 64), {'relu1'}, {'bn1'}, {'bn1f', 'bn1b', 'bn1m'});

net.addLayer('pool1', dagnn.Pooling('method', 'max', 'poolSize', [2, 2], 'stride', [2 2], 'pad', [0 0 0 0]), {'bn1'}, {'pool1'}, {});

% Block #2

net.addLayer('conv2', dagnn.Conv('size', [3 3 64 64], 'hasBias', true, 'stride', [1, 1], 'pad', [1 1 1 1]), {'pool1'}, {'conv2'},  {'conv2f'  'conv2b'});

net.addLayer('relu2', dagnn.ReLU(), {'conv2'}, {'relu2'}, {});

net.addLayer('bn2', dagnn.BatchNorm('numChannels', 64), {'relu2'}, {'bn2'}, {'bn2f', 'bn2b', 'bn2m'});

net.addLayer('pool2', dagnn.Pooling('method', 'max', 'poolSize', [2, 2], 'stride', [2 2], 'pad', [0 0 0 0]), {'bn2'}, {'pool2'}, {});

% Block #3

net.addLayer('conv3', dagnn.Conv('size', [3 3 64 128], 'hasBias', true, 'stride', [1, 1], 'pad', [1 1 1 1]), {'pool2'}, {'conv3'},  {'conv3f'  'conv3b'});

net.addLayer('relu3', dagnn.ReLU(), {'conv3'}, {'relu3'}, {});

net.addLayer('bn3', dagnn.BatchNorm('numChannels', 128), {'relu3'}, {'bn3'},
{'bn3f', 'bn3b', 'bn3m'});

net.addLayer('pool3', dagnn.Pooling('method', 'max', 'poolSize', [2, 2], 'stride', [2 2], 'pad', [0 0 0 0]), {'bn3'}, {'pool3'}, {});

% Block #4

net.addLayer('conv4', dagnn.Conv('size', [3 3 128 128], 'hasBias', true, 'stride', [1, 1], 'pad', [1 1 1 1]), {'pool3'}, {'conv4'},  {'conv4f'  'conv4b'});

net.addLayer('relu4', dagnn.ReLU(), {'conv4'}, {'relu4'}, {});

net.addLayer('bn4', dagnn.BatchNorm('numChannels', 128), {'relu4'}, {'bn4'}, {'bn4f', 'bn4b', 'bn4m'});

net.addLayer('pool4', dagnn.Pooling('method', 'max', 'poolSize', [2, 2], 'stride', [2 2], 'pad', [0 0 0 0]), {'bn4'}, {'pool4'}, {});

% Block #5

net.addLayer('conv5', dagnn.Conv('size', [3 3 128 256], 'hasBias', true, 'stride', [1, 1], 'pad', [1 1 1 1]), {'pool4'}, {'conv5'},  {'conv5f'  'conv5b'});

net.addLayer('relu5', dagnn.ReLU(), {'conv5'}, {'relu5'}, {});

net.addLayer('bn5', dagnn.BatchNorm('numChannels', 256), {'relu5'}, {'bn5'}, {'bn5f', 'bn5b', 'bn5m'});

net.addLayer('pool5', dagnn.Pooling('method', 'max', 'poolSize', [2, 2], 'stride', [2 2], 'pad', [0 0 0 0]), {'bn5'}, {'pool5'}, {});

% Block #6

net.addLayer('conv6', dagnn.Conv('size', [3 3 256 256], 'hasBias', true, 'stride', [1, 1], 'pad', [1 1 1 1]), {'pool5'}, {'conv6'},  {'conv6f'  'conv6b'});

net.addLayer('relu6', dagnn.ReLU(), {'conv6'}, {'relu6'}, {});

net.addLayer('bn6', dagnn.BatchNorm('numChannels', 256), {'relu6'}, {'bn6'}, {'bn6f', 'bn6b', 'bn6m'});

net.addLayer('pool6', dagnn.Pooling('method', 'max', 'poolSize', [2, 2], 'stride', [2 2], 'pad', [0 0 0 0]), {'bn6'}, {'pool6'}, {});

% Block #7

net.addLayer('conv7', dagnn.Conv('size', [3 3 256 512], 'hasBias', true, 'stride', [1, 1], 'pad', [1 1 1 1]), {'pool6'}, {'conv7'},  {'conv7f'  'conv7b'});

net.addLayer('relu7', dagnn.ReLU(), {'conv7'}, {'relu7'}, {});

net.addLayer('bn7', dagnn.BatchNorm('numChannels', 512), {'relu7'}, {'bn7'}, {'bn7f', 'bn7b', 'bn7m'});

net.addLayer('pool7', dagnn.Pooling('method', 'max', 'poolSize', [2, 2], 'stride', [2 2], 'pad', [0 0 0 0]), {'bn7'}, {'pool7'}, {});

% Block #8

net.addLayer('conv8', dagnn.Conv('size', [3 3 512 512], 'hasBias', true, 'stride', [1, 1], 'pad', [1 1 1 1]), {'pool7'}, {'conv8'},  {'conv8f'  'conv8b'});

net.addLayer('relu8', dagnn.ReLU(), {'conv8'}, {'relu8'}, {});

net.addLayer('bn8', dagnn.BatchNorm('numChannels', 512), {'relu8'}, {'bn8'}, {'bn8f', 'bn8b', 'bn8m'});

net.addLayer('pool8', dagnn.Pooling('method', 'max', 'poolSize', [2, 2], 'stride', [1 2], 'pad', [0 0 0 0]), {'bn8'}, {'pool8'}, {});

% Block #9

net.addLayer('conv9', dagnn.Conv('size', [3 3 512 512], 'hasBias', true, 'stride', [1, 1], 'pad', [1 1 1 1]), {'pool8'}, {'conv9'},  {'conv9f'  'conv9b'});

net.addLayer('relu9', dagnn.ReLU(), {'conv9'}, {'relu9'}, {});

net.addLayer('bn9', dagnn.BatchNorm('numChannels', 512), {'relu9'}, {'bn9'}, {'bn9f', 'bn9b', 'bn9m'});

net.addLayer('pool9', dagnn.Pooling('method', 'max', 'poolSize', [2, 2], 'stride', [2 2], 'pad', [0 0 0 0]), {'bn9'}, {'pool9'}, {});

% Incorporate MLP

net.addLayer('fc1', dagnn.Conv('size', [1 1 512 1000], 'hasBias', true, 'stride', [1, 1], 'pad', [0 0 0 0]), {'pool9'}, {'fc1'},  {'conv15f'  'conv15b'});

net.addLayer('relu10', dagnn.ReLU(), {'fc1'}, {'relu10'}, {});

net.addLayer('bn10', dagnn.BatchNorm('numChannels', 1000), {'relu10'}, {'bn10'}, {'bn10f', 'bn10b', 'bn10m'});

net.addLayer('classifier', dagnn.Conv('size', [1 1 1000 2], 'hasBias', true, 'stride', [1, 1], 'pad', [0 0 0 0]), {'bn10'}, {'classifier'},  {'conv16f'  'conv16b'});

net.addLayer('prob', dagnn.SoftMax(), {'classifier'}, {'prob'}, {});

% The dagnn.Loss computes the loss incurred by the prediction scores X given the categorical labels

net.addLayer('objective', dagnn.Loss('loss', 'softmaxlog'), {'prob', 'label'}, {'objective'}, {});

net.addLayer('error', dagnn.Loss('loss', 'classerror'), {'prob','label'}, 'error') ;
</code>```

答:
First of all your network seems too complex to me for the data and you need two orders of magnitude more samples to see any kind of results on such a complex network. That if the problem itself is that complex. Try to see if results improve with a much smaller network. Answering your questions:

1)Filter sizes ARE empirical but popularly 1x1,3x3,5x5 filters are most used. A 70 layer network does not make sense unless the problem is very complex and you have huge data. Also for that to successfully train you might have to look into resnets.

2)Dropouts are most often used in the Fully Connected layers. You can look into dropconnect. No need to use them between conv layers in general.

3)Reduction of size of intermediate maps can be easily achieved by the conv + maxpooling stacks. You dont have to reduce it to size 1x1 before using a MLP. You can use it directly by the time the maps reach a size 8x8 in the network for example. Try to use more than one FC layer. Also reduce the width of the network to reduce the model complexity (number of filters per layer)

Overall you have very little data which is definitely not going to work for deep models. Finetuning a pretrained model might give you better results. It all depends on the data itself and the task at hand. Also remember networks like VGG are trained for 1000 different classes with Millions of Images which is a very complex problem.

Body:
I've currently been working with CNN's and am having a hard time with what I believe is overfitting. Specifically, even though my training data converges to a minimum error, my validation data still refuses to drop in respect to error. My input data that I'm using is 512 x 650 x 1 x 4000 (2D data, 4000 samples) and there are only two classes to the data that I'm trying to distinguish between (class A and class B). I'm aware I in the future need many more samples, but for now, I just would like to see my validation error decline even a little before I invest in generating more data.

My networks have all been around 60-70 layers long and have included the following types of layers:

Block Example

Convolutional Layers [3 x 3] filter size, stride [1 x 1], padding [1 1 1 1]

ReLU Layers (Non-linearity)

Batch normalization (Tremendous help to training data convergence and implementation speed)

Max Pooling Layers [2 x 2] filters sizes, stride [2 x 2], padding [0 0 0 0]

I then repeat this "block" until my input data is a 1 x 1 x N size where I then run it through a a few fully connected layers, and then into a softmax.

My actual MatConvNet code is below for inspection and the output plots are attached. For the plots, blue represents my training error and orange represents my validation error. I'm linking my most recent from the code below.

My Questions:

1) How does one know what filter sizes to use for their data? I know its an empirical process, but surely there is some kind of intuition behind this? I've read papers (VGG.net, and more) on using the [3x3] small filters and using a lot of them, but even after designing a 70 layer network with this in mind, still no validation error decline.

2) I have tried dropout layers due to their popularity of reducing over fitting... I placed the dropout layers throughout my network after the ReLU and pooling layers in the "block" shown above, but between all convolutional layers. It unfortunately had no effect on my validation data, the error was still the same. Next I tried only using it after the fully connected layers since thats where the most neurons (or feature maps) are being created in my architecture, and still no luck. I've read the paper on dropout. Should I give up on using it? Is there once again "a trick" to this?

3) If I try a smaller network (I've read that's a descent way to deal with overfitting) how do I effectively reduce the size of my data? Just max pooling?

ANY suggestions would be wonderful.

Again, thank you all for reading this long question. I assure you I've done my research, and found that asking here might help me more in the long run.

CNN Error Output plot

MatConvNet Code (Matlab Toolbox for CNN Design)

opts.train.batchSize = 25;
opts.train.numEpochs = 200 ;
opts.train.continue = true ;
opts.train.gpus = [1] ;
opts.train.learningRate = 1e-3;
opts.train.weightDecay  = 0.04;
opts.train.momentum = 0.9;
opts.train.expDir = 'epoch_data';
opts.train.numSubBatches = 1;

bopts.useGpu = numel(opts.train.gpus) >  0 ;

load('imdb4k.mat');
net = dagnn.DagNN() ;

% Block #1

net.addLayer('conv1', dagnn.Conv('size', [3 3 1 64], 'hasBias', true, 'stride', [1, 1], 'pad', [1 1 1 1]), {'input'}, {'conv1'},  {'conv1f'  'conv1b'});

net.addLayer('relu1', dagnn.ReLU(), {'conv1'}, {'relu1'}, {});

net.addLayer('bn1', dagnn.BatchNorm('numChannels', 64), {'relu1'}, {'bn1'}, {'bn1f', 'bn1b', 'bn1m'});

net.addLayer('pool1', dagnn.Pooling('method', 'max', 'poolSize', [2, 2], 'stride', [2 2], 'pad', [0 0 0 0]), {'bn1'}, {'pool1'}, {});

% Block #2

net.addLayer('conv2', dagnn.Conv('size', [3 3 64 64], 'hasBias', true, 'stride', [1, 1], 'pad', [1 1 1 1]), {'pool1'}, {'conv2'},  {'conv2f'  'conv2b'});

net.addLayer('relu2', dagnn.ReLU(), {'conv2'}, {'relu2'}, {});

net.addLayer('bn2', dagnn.BatchNorm('numChannels', 64), {'relu2'}, {'bn2'}, {'bn2f', 'bn2b', 'bn2m'});

net.addLayer('pool2', dagnn.Pooling('method', 'max', 'poolSize', [2, 2], 'stride', [2 2], 'pad', [0 0 0 0]), {'bn2'}, {'pool2'}, {});

% Block #3

net.addLayer('conv3', dagnn.Conv('size', [3 3 64 128], 'hasBias', true, 'stride', [1, 1], 'pad', [1 1 1 1]), {'pool2'}, {'conv3'},  {'conv3f'  'conv3b'});

net.addLayer('relu3', dagnn.ReLU(), {'conv3'}, {'relu3'}, {});

net.addLayer('bn3', dagnn.BatchNorm('numChannels', 128), {'relu3'}, {'bn3'},
{'bn3f', 'bn3b', 'bn3m'});

net.addLayer('pool3', dagnn.Pooling('method', 'max', 'poolSize', [2, 2], 'stride', [2 2], 'pad', [0 0 0 0]), {'bn3'}, {'pool3'}, {});

% Block #4

net.addLayer('conv4', dagnn.Conv('size', [3 3 128 128], 'hasBias', true, 'stride', [1, 1], 'pad', [1 1 1 1]), {'pool3'}, {'conv4'},  {'conv4f'  'conv4b'});

net.addLayer('relu4', dagnn.ReLU(), {'conv4'}, {'relu4'}, {});

net.addLayer('bn4', dagnn.BatchNorm('numChannels', 128), {'relu4'}, {'bn4'}, {'bn4f', 'bn4b', 'bn4m'});

net.addLayer('pool4', dagnn.Pooling('method', 'max', 'poolSize', [2, 2], 'stride', [2 2], 'pad', [0 0 0 0]), {'bn4'}, {'pool4'}, {});

% Block #5

net.addLayer('conv5', dagnn.Conv('size', [3 3 128 256], 'hasBias', true, 'stride', [1, 1], 'pad', [1 1 1 1]), {'pool4'}, {'conv5'},  {'conv5f'  'conv5b'});

net.addLayer('relu5', dagnn.ReLU(), {'conv5'}, {'relu5'}, {});

net.addLayer('bn5', dagnn.BatchNorm('numChannels', 256), {'relu5'}, {'bn5'}, {'bn5f', 'bn5b', 'bn5m'});

net.addLayer('pool5', dagnn.Pooling('method', 'max', 'poolSize', [2, 2], 'stride', [2 2], 'pad', [0 0 0 0]), {'bn5'}, {'pool5'}, {});

% Block #6

net.addLayer('conv6', dagnn.Conv('size', [3 3 256 256], 'hasBias', true, 'stride', [1, 1], 'pad', [1 1 1 1]), {'pool5'}, {'conv6'},  {'conv6f'  'conv6b'});

net.addLayer('relu6', dagnn.ReLU(), {'conv6'}, {'relu6'}, {});

net.addLayer('bn6', dagnn.BatchNorm('numChannels', 256), {'relu6'}, {'bn6'}, {'bn6f', 'bn6b', 'bn6m'});

net.addLayer('pool6', dagnn.Pooling('method', 'max', 'poolSize', [2, 2], 'stride', [2 2], 'pad', [0 0 0 0]), {'bn6'}, {'pool6'}, {});

% Block #7

net.addLayer('conv7', dagnn.Conv('size', [3 3 256 512], 'hasBias', true, 'stride', [1, 1], 'pad', [1 1 1 1]), {'pool6'}, {'conv7'},  {'conv7f'  'conv7b'});

net.addLayer('relu7', dagnn.ReLU(), {'conv7'}, {'relu7'}, {});

net.addLayer('bn7', dagnn.BatchNorm('numChannels', 512), {'relu7'}, {'bn7'}, {'bn7f', 'bn7b', 'bn7m'});

net.addLayer('pool7', dagnn.Pooling('method', 'max', 'poolSize', [2, 2], 'stride', [2 2], 'pad', [0 0 0 0]), {'bn7'}, {'pool7'}, {});

% Block #8

net.addLayer('conv8', dagnn.Conv('size', [3 3 512 512], 'hasBias', true, 'stride', [1, 1], 'pad', [1 1 1 1]), {'pool7'}, {'conv8'},  {'conv8f'  'conv8b'});

net.addLayer('relu8', dagnn.ReLU(), {'conv8'}, {'relu8'}, {});

net.addLayer('bn8', dagnn.BatchNorm('numChannels', 512), {'relu8'}, {'bn8'}, {'bn8f', 'bn8b', 'bn8m'});

net.addLayer('pool8', dagnn.Pooling('method', 'max', 'poolSize', [2, 2], 'stride', [1 2], 'pad', [0 0 0 0]), {'bn8'}, {'pool8'}, {});

% Block #9

net.addLayer('conv9', dagnn.Conv('size', [3 3 512 512], 'hasBias', true, 'stride', [1, 1], 'pad', [1 1 1 1]), {'pool8'}, {'conv9'},  {'conv9f'  'conv9b'});

net.addLayer('relu9', dagnn.ReLU(), {'conv9'}, {'relu9'}, {});

net.addLayer('bn9', dagnn.BatchNorm('numChannels', 512), {'relu9'}, {'bn9'}, {'bn9f', 'bn9b', 'bn9m'});

net.addLayer('pool9', dagnn.Pooling('method', 'max', 'poolSize', [2, 2], 'stride', [2 2], 'pad', [0 0 0 0]), {'bn9'}, {'pool9'}, {});

% Incorporate MLP

net.addLayer('fc1', dagnn.Conv('size', [1 1 512 1000], 'hasBias', true, 'stride', [1, 1], 'pad', [0 0 0 0]), {'pool9'}, {'fc1'},  {'conv15f'  'conv15b'});

net.addLayer('relu10', dagnn.ReLU(), {'fc1'}, {'relu10'}, {});

net.addLayer('bn10', dagnn.BatchNorm('numChannels', 1000), {'relu10'}, {'bn10'}, {'bn10f', 'bn10b', 'bn10m'});

net.addLayer('classifier', dagnn.Conv('size', [1 1 1000 2], 'hasBias', true, 'stride', [1, 1], 'pad', [0 0 0 0]), {'bn10'}, {'classifier'},  {'conv16f'  'conv16b'});

net.addLayer('prob', dagnn.SoftMax(), {'classifier'}, {'prob'}, {});

% The dagnn.Loss computes the loss incurred by the prediction scores X given the categorical labels

net.addLayer('objective', dagnn.Loss('loss', 'softmaxlog'), {'prob', 'label'}, {'objective'}, {});

net.addLayer('error', dagnn.Loss('loss', 'classerror'), {'prob','label'}, 'error') ;


来源: stackexchange

问:
How to find the indexpath of tableview when Collectionview is clicked which is in tabelview Cell
I have tableview cell which is having collection view in it.

CollectionView contains images coming from server.

I want particular image on which user has tapped.
i.e.
Let Tableview have 4 rows. In the four row I have collection in every tableview row. When I click on 3rd row collectionview cell, I have to get that image from that row.

code is here

```<code>    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    cell = (ISclassifiedCell*)[_isclassifed_tblview dequeueReusableCellWithIdentifier:@"ISclassifiedCell" forIndexPath:indexPath];
[cell.layer setCornerRadius:4.0f];
[cell.layer setMasksToBounds:YES];
     cell.profile_img.layer.cornerRadius=4.0f;
    cell.profile_img.layer.masksToBounds = YES;
    cell.iseventtype_lbl.text=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"title"];
cell.eventtype_lbl.text=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"category"];
cell.description_lbl.text=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"description"];

    UIFont *font=[UIFont fontWithName:@"Montserrat" size:14.0];

    CGFloat size = [self getLabelHeightForString:cell.description_lbl.text font:font];
    cell.description_lbl.frame=CGRectMake(cell.description_lbl.frame.origin.x, cell.description_lbl.frame.origin.y, cell.description_lbl.frame.size.width, size);
NSString *clubberid=[NSString stringWithFormat:@"%@",[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"clubberId"]];
    cell.clubbername_lbl.text=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"clubberName"];

if ([clubberid isEqualToString:[NSString stringWithFormat:@"%@",mainclubberId]]) {

    [cell.editbutnoutlet setImage:[UIImage imageNamed:@"note-interface-symbol"] forState:UIControlStateNormal];
    cell.pokebtnoutlet.hidden=YES;
    cell.editbutnoutlet.hidden=NO;
    cell.editbutnoutlet.tag = indexPath.section;
    [cell.editbutnoutlet addTarget:self action:@selector(editButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_providertbl reloadData];
}else{

 [cell.pokebtnoutlet setImage:[UIImage imageNamed:@"hold"] forState:UIControlStateNormal];
    cell.pokebtnoutlet.hidden=NO;
    cell.editbutnoutlet.hidden=YES;
    cell.pokebtnoutlet.tag = indexPath.section;
    [cell.pokebtnoutlet addTarget:self action:@selector(pokeButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

}
NSString *imgUrl = [NSString stringWithFormat:@"%s/presignin/clubber/getImage?clubberId=%@",urlPath,clubberid];

 NSURL *imageURL=[NSURL URLWithString:imgUrl];
imgarray=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"media"];
cell.profile_img.imageURL=imageURL;
    cell.imgcollection_view.tag=indexPath.section;
if (imgarray.count==0) {
    cell.imgcollection_view.hidden=YES;

}else{

   cell.imgcollection_view.hidden=NO;
}
cell.imgcollection_view.delegate=self;
cell.imgcollection_view.dataSource=self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //cell.imgcollection_view.allowsSelection=NO;
return cell;
}
 }
</code>```

collectionviewcode

```<code>    - (NSInteger)collectionView:(UICollectionView *)view
 numberOfItemsInSection:(NSInteger)section {

return imgarray.count;
 }
   // 2
   - (NSInteger)numberOfSectionsInCollectionView: (UICollectionView
                                            *)collectionView {
return 1;
  }

 - (UICollectionViewCell *)collectionView:(UICollectionView *)cv
              cellForItemAtIndexPath:(NSIndexPath *)indexPath {
//isclasifiedimageCell *cell1 = nil;

    cell1=[cv
          dequeueReusableCellWithReuseIdentifier:@"isclasifiedimageCell"
          forIndexPath:indexPath];

NSLog(@"%ld",(long)indexPath.row);

NSString *clubberid=[NSString stringWithFormat:@"%@",[[imgarray objectAtIndex:indexPath.row]valueForKey:@"idclassifieds_media"]];

NSString *clubberidtype=[NSString stringWithFormat:@"%@",[[imgarray objectAtIndex:indexPath.row]valueForKey:@"type"]];
}
else{
     NSString *typeimgUrl1 = [NSString stringWithFormat:@"%s/presignin/classifieds/showMedia?idclassifieds_media=%@",urlPath,clubberid];
    NSURL *imageURL=[NSURL URLWithString:typeimgUrl1];

     cell1.img_view.imageURL=imageURL;
 }

    return cell1;
}
 -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  {
NSLog(@"%ld",(long)cell.imgcollection_view.tag);
mediaimgarray=[[isclassifiedarray objectAtIndex:cell.imgcollection_view.tag]valueForKey:@"media"];
NSString *cluderimgid=[NSString stringWithFormat:@"%@",[[mediaimgarray objectAtIndex:indexPath.row]valueForKey:@"idclassifieds_media"]];
// NSString *mediatypeurlstr=[NSString stringWithFormat:@"%@",[[mediaimgarray objectAtIndex:indexPath.row]valueForKey:@"idclassifieds_media"]];
UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main"
                                                     bundle:nil];
isclasifiedImgpreviewVC * isclasifiedImgpreview =
[storyboard instantiateViewControllerWithIdentifier:@"isclasifiedImgpreview"];
// isclasifiedImgpreview.mediaatype=cluderimgid;
isclasifiedImgpreview.mediaatypeurlid=cluderimgid;
[self presentViewController:isclasifiedImgpreview
                   animated:YES
                 completion:nil];
</code>```

}

答:
While setting up UITableView set a tag to UICollectionView.

as

```<code>collectionView.tag = indexPath.row
</code>```

And in collectionViewDidSelect delegate method check tag of the collectionView

ContentLicense: CC BY-SA 3.0

Body:
I have tableview cell which is having collection view in it.

CollectionView contains images coming from server.

I want particular image on which user has tapped.
i.e.
Let Tableview have 4 rows. In the four row I have collection in every tableview row. When I click on 3rd row collectionview cell, I have to get that image from that row.

code is here

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    cell = (ISclassifiedCell*)[_isclassifed_tblview dequeueReusableCellWithIdentifier:@"ISclassifiedCell" forIndexPath:indexPath];
[cell.layer setCornerRadius:4.0f];
[cell.layer setMasksToBounds:YES];
     cell.profile_img.layer.cornerRadius=4.0f;
    cell.profile_img.layer.masksToBounds = YES;
    cell.iseventtype_lbl.text=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"title"];
cell.eventtype_lbl.text=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"category"];
cell.description_lbl.text=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"description"];

    UIFont *font=[UIFont fontWithName:@"Montserrat" size:14.0];

    CGFloat size = [self getLabelHeightForString:cell.description_lbl.text font:font];
    cell.description_lbl.frame=CGRectMake(cell.description_lbl.frame.origin.x, cell.description_lbl.frame.origin.y, cell.description_lbl.frame.size.width, size);
NSString *clubberid=[NSString stringWithFormat:@"%@",[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"clubberId"]];
    cell.clubbername_lbl.text=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"clubberName"];

if ([clubberid isEqualToString:[NSString stringWithFormat:@"%@",mainclubberId]]) {

    [cell.editbutnoutlet setImage:[UIImage imageNamed:@"note-interface-symbol"] forState:UIControlStateNormal];
    cell.pokebtnoutlet.hidden=YES;
    cell.editbutnoutlet.hidden=NO;
    cell.editbutnoutlet.tag = indexPath.section;
    [cell.editbutnoutlet addTarget:self action:@selector(editButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_providertbl reloadData];
}else{

 [cell.pokebtnoutlet setImage:[UIImage imageNamed:@"hold"] forState:UIControlStateNormal];
    cell.pokebtnoutlet.hidden=NO;
    cell.editbutnoutlet.hidden=YES;
    cell.pokebtnoutlet.tag = indexPath.section;
    [cell.pokebtnoutlet addTarget:self action:@selector(pokeButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

}
NSString *imgUrl = [NSString stringWithFormat:@"%s/presignin/clubber/getImage?clubberId=%@",urlPath,clubberid];

 NSURL *imageURL=[NSURL URLWithString:imgUrl];
imgarray=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"media"];
cell.profile_img.imageURL=imageURL;
    cell.imgcollection_view.tag=indexPath.section;
if (imgarray.count==0) {
    cell.imgcollection_view.hidden=YES;

}else{

   cell.imgcollection_view.hidden=NO;
}
cell.imgcollection_view.delegate=self;
cell.imgcollection_view.dataSource=self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //cell.imgcollection_view.allowsSelection=NO;
return cell;
}
 }

collectionviewcode

    - (NSInteger)collectionView:(UICollectionView *)view
 numberOfItemsInSection:(NSInteger)section {

return imgarray.count;
 }
   // 2
   - (NSInteger)numberOfSectionsInCollectionView: (UICollectionView
                                            *)collectionView {
return 1;
  }

 - (UICollectionViewCell *)collectionView:(UICollectionView *)cv
              cellForItemAtIndexPath:(NSIndexPath *)indexPath {
//isclasifiedimageCell *cell1 = nil;

    cell1=[cv
          dequeueReusableCellWithReuseIdentifier:@"isclasifiedimageCell"
          forIndexPath:indexPath];

NSLog(@"%ld",(long)indexPath.row);

NSString *clubberid=[NSString stringWithFormat:@"%@",[[imgarray objectAtIndex:indexPath.row]valueForKey:@"idclassifieds_media"]];

NSString *clubberidtype=[NSString stringWithFormat:@"%@",[[imgarray objectAtIndex:indexPath.row]valueForKey:@"type"]];
}
else{
     NSString *typeimgUrl1 = [NSString stringWithFormat:@"%s/presignin/classifieds/showMedia?idclassifieds_media=%@",urlPath,clubberid];
    NSURL *imageURL=[NSURL URLWithString:typeimgUrl1];

     cell1.img_view.imageURL=imageURL;
 }

    return cell1;
}
 -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  {
NSLog(@"%ld",(long)cell.imgcollection_view.tag);
mediaimgarray=[[isclassifiedarray objectAtIndex:cell.imgcollection_view.tag]valueForKey:@"media"];
NSString *cluderimgid=[NSString stringWithFormat:@"%@",[[mediaimgarray objectAtIndex:indexPath.row]valueForKey:@"idclassifieds_media"]];
// NSString *mediatypeurlstr=[NSString stringWithFormat:@"%@",[[mediaimgarray objectAtIndex:indexPath.row]valueForKey:@"idclassifieds_media"]];
UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main"
                                                     bundle:nil];
isclasifiedImgpreviewVC * isclasifiedImgpreview =
[storyboard instantiateViewControllerWithIdentifier:@"isclasifiedImgpreview"];
// isclasifiedImgpreview.mediaatype=cluderimgid;
isclasifiedImgpreview.mediaatypeurlid=cluderimgid;
[self presentViewController:isclasifiedImgpreview
                   animated:YES
                 completion:nil];

}

Body:
While setting up UITableView set a tag to UICollectionView.

as

collectionView.tag = indexPath.row

And in collectionViewDidSelect delegate method check tag of the collectionView


问:
google recaptcha reset response variable
I am using ajax to submit a form using recaptcha verification.Now since i am using ajax the page cannot refresh.So to check whether user has clicked the recaptcha box i am using the following check

```<code>var recaptcha = $("#g-recaptcha-response").val();
if (recaptcha === "")
{

    alert("Please check the recaptcha");

}
</code>```

and after form submission recaptcha is reloaded using

```<code>grecaptcha.reset();
</code>```

After the form submission the page is not refreshed and user may have to submit more data using same form.Now the problem is that recaptcha is loaded but var recaptcha = $("#g-recaptcha-response").val(); is returning true due to previous recaptcha submission.

How can i reset the recaptcha response variable?

答:
After your form submission, you need to reset recaptcha and then erase recaptcha response hidden input:</p>

```<code>grecaptcha.reset();
$("#g-recaptcha-response").val("");
</code>```

Body:
I am using ajax to submit a form using recaptcha verification.Now since i am using ajax the page cannot refresh.So to check whether user has clicked the recaptcha box i am using the following check

var recaptcha = $("#g-recaptcha-response").val();
if (recaptcha === "")
{

    alert("Please check the recaptcha");

}

and after form submission recaptcha is reloaded using

grecaptcha.reset();

After the form submission the page is not refreshed and user may have to submit more data using same form.Now the problem is that recaptcha is loaded but var recaptcha = $("#g-recaptcha-response").val(); is returning true due to previous recaptcha submission.

How can i reset the recaptcha response variable?

Body:
After your form submission, you need to reset recaptcha and then erase recaptcha response hidden input:

grecaptcha.reset();
$("#g-recaptcha-response").val("");


问:
How to redirect onclick while using iframe
I had to use an iframe to stop the page from reloading before the action was completed. However, I need it to refresh after the action is taking place. I tried two methods for this, refreshing the page and redirecting to the same page.

PHP:

```<code>if(isset($_POST['btn_name']) {
   //Action
   location.reload();
  //I also tried
    header("Location: index.php");
}
</code>```

HTML:

```<code><iframe width="0" height="0" border="0px solid white" style="display:none" name="iframe1" id="iframe1"></iframe>

        <form action="index.php" method="post" target="iframe1">
         <input type="submit" href="" style="margin-top:5px" name="btn_name" class="btn btn-success" value="Enter">
            </form>
</code>```

Thanks for your help. All input is appreciated.

答:
$_POST['btn'] doesn't post anything because it's a class.

Try $_POST['installer4_btn'] instead.

Body:
I had to use an iframe to stop the page from reloading before the action was completed. However, I need it to refresh after the action is taking place. I tried two methods for this, refreshing the page and redirecting to the same page.

PHP:

if(isset($_POST['btn_name']) {
   //Action
   location.reload();
  //I also tried
    header("Location: index.php");
}

HTML:

        <form action="index.php" method="post" target="iframe1">
         <input type="submit" href="" style="margin-top:5px" name="btn_name" class="btn btn-success" value="Enter">
            </form>

Thanks for your help. All input is appreciated.


问:
Making a Database search engine like Google
I'm new to creating websites.I'm creating a Telephone directory search Engine.(Using PostgreSql,CGI scripts).My Database is having Name,Tel.No,City,State,Address.

Upto now I have created a search field like "google" where I can give any of the above Database entries and search.But now I want to give like "name+city+..." So that I can minimize the output entries.

答: In addition to Silver Light's answer, you could use PostgreSQL's multicolumn index to search for any or all of the fields inside a single index.</p>

ContentLicense: CC BY-SA 2.5


问:
Computational complexity of a longest path algorithm witn a recursive method
I wrote a code segment to determine the longest path in a graph. Following is the code. But I don't know how to get the computational complexity in it because of the recursive method in the middle. Since finding the longest path is an NP complete problem I assume it's something like O(n!) or O(2^n), but how can I actually determine it?

```<code>public static int longestPath(int A) {
    int k;
    int dist2=0;
    int max=0;

    visited[A] = true;

    for (k = 1; k <= V; ++k) {
        if(!visited[k]){
            dist2= length[A][k]+longestPath(k);
            if(dist2>max){
                max=dist2;
            }
        }
    }
    visited[A]=false;
    return(max);
}
</code>```

答:
Your recurrence relation is T(n, m) = mT(n, m-1) + O(n), where n denotes number of nodes and m denotes number of unvisited nodes (because you call longestPath m times, and there is a loop which executes the visited test n times). The base case is T(n, 0) = O(n) (just the visited test).

Solve this and I believe you get T(n, n) is O(n * n!).

EDIT

Working:

```<code>T(n, n) = nT(n, n-1) + O(n)
        = n((n-1)T(n, n-2) + O(n)) + O(n) = ...
        = n(n-1)...1T(n, 0) + O(n)(1 + n + n(n-1) + ... + n(n-1)...2)
        = O(n)(1 + n + n(n-1) + ... + n!)
        = O(n)O(n!) (see http://oeis.org/A000522)
        = O(n*n!)
</code>```

Body:
I wrote a code segment to determine the longest path in a graph. Following is the code. But I don't know how to get the computational complexity in it because of the recursive method in the middle. Since finding the longest path is an NP complete problem I assume it's something like O(n!) or O(2^n), but how can I actually determine it?

public static int longestPath(int A) {
    int k;
    int dist2=0;
    int max=0;

    visited[A] = true;

    for (k = 1; k <= V; ++k) {
        if(!visited[k]){
            dist2= length[A][k]+longestPath(k);
            if(dist2>max){
                max=dist2;
            }
        }
    }
    visited[A]=false;
    return(max);
}

Body:
Your recurrence relation is T(n, m) = mT(n, m-1) + O(n), where n denotes number of nodes and m denotes number of unvisited nodes (because you call longestPath m times, and there is a loop which executes the visited test n times). The base case is T(n, 0) = O(n) (just the visited test).

Solve this and I believe you get T(n, n) is O(n * n!).

EDIT

Working:

T(n, n) = nT(n, n-1) + O(n)
        = n((n-1)T(n, n-2) + O(n)) + O(n) = ...
        = n(n-1)...1T(n, 0) + O(n)(1 + n + n(n-1) + ... + n(n-1)...2)
        = O(n)(1 + n + n(n-1) + ... + n!)
        = O(n)O(n!) (see http://oeis.org/A000522)
        = O(n*n!)


问:
Python Import class error, trying to understand the root directory __init__.py
I am just 4 days old to python. I am just trying to understand the root  __init__.py import functionality. Googled lot to understand the same but not able to find one useful link (may be my search key is not relevant) . Please share some links.

I am getting error as "ImportError: cannot import name Person"

Below is the structure

```<code>Example(directory)
    model
        __init__.py (empty)
        myclass.py
    __init__.py
    run.py
</code>```

myclass.py

```<code>class Person(object):
    def __init__(self):
        self.name = "Raja"

    def print_name(self):
        print self.name
</code>```

__init__.py

```<code>from model.myclass import Person
</code>```

run.py

```<code>from model import Person

def donext():
    person = Person()
    person.print_name()

if __name__ == '__main__':
    donext()
</code>```

答:
The error basically says the interpreter can't find anything that would match Person in a given namespace, in your case model package. It's because it's in model.myclass package, but it's imported to root and not to run.

Modules in python are basically directories with __init__.py script. But it's tricky to import anything at root level from init. And moreover, it's not necessary.

OK, so this means solution is either to import directly from model package, or from the rott-level __init__.py. I would recommend the former method, since it's more commonly used. You can do it this way:

```<code>from model.myclass import Person

def donext():
    person = Person()
    person.print_name()

if __name__ == '__main__':
    donext()
</code>```

And leave __init__.py empty. They are used only for initialization, so there is no need to import everything to them.

You could put something to your model/__init__.py and then import it in myclass.py like:

__init__.py:

```<code>something = 0
</code>```

myclass.py:

```<code>from . import something
print something
</code>```

Body:
I am just 4 days old to python. I am just trying to understand the root  __init__.py import functionality. Googled lot to understand the same but not able to find one useful link (may be my search key is not relevant) . Please share some links.

I am getting error as "ImportError: cannot import name Person"

Below is the structure

Example(directory)
    model
        __init__.py (empty)
        myclass.py
    __init__.py
    run.py

myclass.py

class Person(object):
    def __init__(self):
        self.name = "Raja"

    def print_name(self):
        print self.name

__init__.py

from model.myclass import Person

run.py

from model import Person

def donext():
    person = Person()
    person.print_name()

if __name__ == '__main__':
    donext()

Body:
The error basically says the interpreter can't find anything that would match Person in a given namespace, in your case model package. It's because it's in model.myclass package, but it's imported to root and not to run.

Modules in python are basically directories with __init__.py script. But it's tricky to import anything at root level from init. And moreover, it's not necessary.

OK, so this means solution is either to import directly from model package, or from the rott-level __init__.py. I would recommend the former method, since it's more commonly used. You can do it this way:

from model.myclass import Person

def donext():
    person = Person()
    person.print_name()

if __name__ == '__main__':
    donext()

And leave __init__.py empty. They are used only for initialization, so there is no need to import everything to them.

You could put something to your model/__init__.py and then import it in myclass.py like:

__init__.py:

something = 0

myclass.py:

from . import something
print something


问:
Git status shows files as changed even though contents are the same
I received a git checkout from someone else and am trying to commit the unstaged changes to the local repository. However, a lot (if not every) file appears as modified even though the contents are exactly the same.

I already set core.fileMode to false and also set core.autocrlf to false, without success.

Worth mentioning is that the Git repo I received was from someone using Windows, while I use Linux.

What can I do to commit the actual changes?

EDIT: output of git config -l:

```<code>user.name=Aron Rotteveel
user.email=<removed>
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=auto
color.ui=true
color.pager=true
color.branch.current=yellow reverse
color.branch.local=yellow
color.branch.remote=green
color.diff.meta=yellow bold
color.diff.frag=magenta bold
color.diff.old=red bold
color.diff.new=green bold
color.status.added=yellow
color.status.changed=green
color.status.untracked=cyan
core.pager=less -FRSX
core.whitespace=fix,-indent-with-non-tab,trailing-space,cr-at-eol
alias.co=checkout
core.repositoryformatversion=0
core.filemode=false
core.bare=false
core.logallrefupdates=true
core.symlinks=false
core.ignorecase=true
core.hidedotfiles=dotGitOnly
core.autocrlf=false
remote.origin.url=<removed>
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
</code>```

Update: added some random example files. These files are just plaintext, so are the easiest to include.

Original files are located here: https://gist.github.com/c3c5302430935155ef3d. Hexdumps definitely indicate that the files are different, but I have no clue what causes this, and how to fix it.

HEAD version:

```<code>0000000: 4854 4d4c 2e53 6166 654f 626a 6563 740d  HTML.SafeObject.
0000010: 0a54 5950 453a 2062 6f6f 6c0d 0a56 4552  .TYPE: bool..VER
0000020: 5349 4f4e 3a20 332e 312e 310d 0a44 4546  SION: 3.1.1..DEF
0000030: 4155 4c54 3a20 6661 6c73 650d 0a2d 2d44  AULT: false..--D
0000040: 4553 4352 4950 5449 4f4e 2d2d 0d0a 3c70  ESCRIPTION--..<p
0000050: 3e0d 0a20 2020 2057 6865 7468 6572 206f  >..    Whether o
0000060: 7220 6e6f 7420 746f 2070 6572 6d69 7420  r not to permit
0000070: 6f62 6a65 6374 2074 6167 7320 696e 2064  object tags in d
0000080: 6f63 756d 656e 7473 2c20 7769 7468 2061  ocuments, with a
0000090: 206e 756d 6265 7220 6f66 2065 7874 7261   number of extra
00000a0: 0d0a 2020 2020 7365 6375 7269 7479 2066  ..    security f
00000b0: 6561 7475 7265 7320 6164 6465 6420 746f  eatures added to
00000c0: 2070 7265 7665 6e74 2073 6372 6970 7420   prevent script
00000d0: 6578 6563 7574 696f 6e2e 2054 6869 7320  execution. This
00000e0: 6973 2073 696d 696c 6172 2074 6f0d 0a20  is similar to..
00000f0: 2020 2077 6861 7420 7765 6273 6974 6573     what websites
0000100: 206c 696b 6520 4d79 5370 6163 6520 646f   like MySpace do
0000110: 2074 6f20 6f62 6a65 6374 2074 6167 732e   to object tags.
0000120: 2020 596f 7520 7368 6f75 6c64 2061 6c73    You should als
0000130: 6f20 656e 6162 6c65 0d0a 2020 2020 254f  o enable..    %O
0000140: 7574 7075 742e 466c 6173 6843 6f6d 7061  utput.FlashCompa
0000150: 7420 696e 206f 7264 6572 2074 6f20 6765  t in order to ge
0000160: 6e65 7261 7465 2049 6e74 6572 6e65 7420  nerate Internet
0000170: 4578 706c 6f72 6572 0d0a 2020 2020 636f  Explorer..    co
0000180: 6d70 6174 6962 696c 6974 7920 636f 6465  mpatibility code
0000190: 2066 6f72 2079 6f75 7220 6f62 6a65 6374   for your object
00001a0: 2074 6167 732e 0d0a 3c2f 703e 0d0a 2d2d   tags...</p>..--
00001b0: 2320 7669 6d3a 2065 7420 7377 3d34 2073  # vim: et sw=4 s
00001c0: 7473 3d34 0d0a                           ts=4..
</code>```

Copied version:

```<code>0000000: 4854 4d4c 2e53 6166 654f 626a 6563 740a  HTML.SafeObject.
0000010: 5459 5045 3a20 626f 6f6c 0a56 4552 5349  TYPE: bool.VERSI
0000020: 4f4e 3a20 332e 312e 310a 4445 4641 554c  ON: 3.1.1.DEFAUL
0000030: 543a 2066 616c 7365 0a2d 2d44 4553 4352  T: false.--DESCR
0000040: 4950 5449 4f4e 2d2d 0a3c 703e 0a20 2020  IPTION--.<p>.
0000050: 2057 6865 7468 6572 206f 7220 6e6f 7420   Whether or not
0000060: 746f 2070 6572 6d69 7420 6f62 6a65 6374  to permit object
0000070: 2074 6167 7320 696e 2064 6f63 756d 656e   tags in documen
0000080: 7473 2c20 7769 7468 2061 206e 756d 6265  ts, with a numbe
0000090: 7220 6f66 2065 7874 7261 0a20 2020 2073  r of extra.    s
00000a0: 6563 7572 6974 7920 6665 6174 7572 6573  ecurity features
00000b0: 2061 6464 6564 2074 6f20 7072 6576 656e   added to preven
00000c0: 7420 7363 7269 7074 2065 7865 6375 7469  t script executi
00000d0: 6f6e 2e20 5468 6973 2069 7320 7369 6d69  on. This is simi
00000e0: 6c61 7220 746f 0a20 2020 2077 6861 7420  lar to.    what
00000f0: 7765 6273 6974 6573 206c 696b 6520 4d79  websites like My
0000100: 5370 6163 6520 646f 2074 6f20 6f62 6a65  Space do to obje
0000110: 6374 2074 6167 732e 2020 596f 7520 7368  ct tags.  You sh
0000120: 6f75 6c64 2061 6c73 6f20 656e 6162 6c65  ould also enable
0000130: 0a20 2020 2025 4f75 7470 7574 2e46 6c61  .    %Output.Fla
0000140: 7368 436f 6d70 6174 2069 6e20 6f72 6465  shCompat in orde
0000150: 7220 746f 2067 656e 6572 6174 6520 496e  r to generate In
0000160: 7465 726e 6574 2045 7870 6c6f 7265 720a  ternet Explorer.
0000170: 2020 2020 636f 6d70 6174 6962 696c 6974      compatibilit
0000180: 7920 636f 6465 2066 6f72 2079 6f75 7220  y code for your
0000190: 6f62 6a65 6374 2074 6167 732e 0a3c 2f70  object tags..</p
00001a0: 3e0a 2d2d 2320 7669 6d3a 2065 7420 7377  >.--# vim: et sw
00001b0: 3d34 2073 7473 3d34 0a                   =4 sts=4.
</code>```

答:
So, I tried just about everything here and want to contribute one more solution that fixed all of my problems. My issues was not with line endings or actual permissions or anything like that. It was because I had installed Cygwin and whole host of stuff that comes with that, which unbeknownst to me also installed its own version of git. I never noticed this, just that I was having strange issues with users and files being marked as changed (because of perms changes).

It turns out that I figured this out because I thought I should just update Git to the latest version, which I did, but running git --version returned the old version number. After the ensuing hunt for why, I found the cygwin bin directory root in my environment path, which contained a git executable, running at the old version number. Go figure.

This was also hard to find because I have TortoiseGit installed. My command line tools would use the cygwin version due to path fallbacks, and TortoiseGit was configured to use the windows version, making it even more confusing.

Hope this helps somebody.

ContentLicense: CC BY-SA 4.0

Body:
I received a git checkout from someone else and am trying to commit the unstaged changes to the local repository. However, a lot (if not every) file appears as modified even though the contents are exactly the same.

I already set core.fileMode to false and also set core.autocrlf to false, without success.

Worth mentioning is that the Git repo I received was from someone using Windows, while I use Linux.

What can I do to commit the actual changes?

EDIT: output of git config -l:

user.name=Aron Rotteveel
user.email=<removed>
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=auto
color.ui=true
color.pager=true
color.branch.current=yellow reverse
color.branch.local=yellow
color.branch.remote=green
color.diff.meta=yellow bold
color.diff.frag=magenta bold
color.diff.old=red bold
color.diff.new=green bold
color.status.added=yellow
color.status.changed=green
color.status.untracked=cyan
core.pager=less -FRSX
core.whitespace=fix,-indent-with-non-tab,trailing-space,cr-at-eol
alias.co=checkout
core.repositoryformatversion=0
core.filemode=false
core.bare=false
core.logallrefupdates=true
core.symlinks=false
core.ignorecase=true
core.hidedotfiles=dotGitOnly
core.autocrlf=false
remote.origin.url=<removed>
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*

Update: added some random example files. These files are just plaintext, so are the easiest to include.

Original files are located here: https://gist.github.com/c3c5302430935155ef3d. Hexdumps definitely indicate that the files are different, but I have no clue what causes this, and how to fix it.

HEAD version:

0000000: 4854 4d4c 2e53 6166 654f 626a 6563 740d  HTML.SafeObject.
0000010: 0a54 5950 453a 2062 6f6f 6c0d 0a56 4552  .TYPE: bool..VER
0000020: 5349 4f4e 3a20 332e 312e 310d 0a44 4546  SION: 3.1.1..DEF
0000030: 4155 4c54 3a20 6661 6c73 650d 0a2d 2d44  AULT: false..--D
0000040: 4553 4352 4950 5449 4f4e 2d2d 0d0a 3c70  ESCRIPTION--..
..    Whether o
0000060: 7220 6e6f 7420 746f 2070 6572 6d69 7420  r not to permit
0000070: 6f62 6a65 6374 2074 6167 7320 696e 2064  object tags in d
0000080: 6f63 756d 656e 7473 2c20 7769 7468 2061  ocuments, with a
0000090: 206e 756d 6265 7220 6f66 2065 7874 7261   number of extra
00000a0: 0d0a 2020 2020 7365 6375 7269 7479 2066  ..    security f
00000b0: 6561 7475 7265 7320 6164 6465 6420 746f  eatures added to
00000c0: 2070 7265 7665 6e74 2073 6372 6970 7420   prevent script
00000d0: 6578 6563 7574 696f 6e2e 2054 6869 7320  execution. This
00000e0: 6973 2073 696d 696c 6172 2074 6f0d 0a20  is similar to..
00000f0: 2020 2077 6861 7420 7765 6273 6974 6573     what websites
0000100: 206c 696b 6520 4d79 5370 6163 6520 646f   like MySpace do
0000110: 2074 6f20 6f62 6a65 6374 2074 6167 732e   to object tags.
0000120: 2020 596f 7520 7368 6f75 6c64 2061 6c73    You should als
0000130: 6f20 656e 6162 6c65 0d0a 2020 2020 254f  o enable..    %O
0000140: 7574 7075 742e 466c 6173 6843 6f6d 7061  utput.FlashCompa
0000150: 7420 696e 206f 7264 6572 2074 6f20 6765  t in order to ge
0000160: 6e65 7261 7465 2049 6e74 6572 6e65 7420  nerate Internet
0000170: 4578 706c 6f72 6572 0d0a 2020 2020 636f  Explorer..    co
0000180: 6d70 6174 6962 696c 6974 7920 636f 6465  mpatibility code
0000190: 2066 6f72 2079 6f75 7220 6f62 6a65 6374   for your object
00001a0: 2074 6167 732e 0d0a 3c2f 703e 0d0a 2d2d   tags...
..--
00001b0: 2320 7669 6d3a 2065 7420 7377 3d34 2073  # vim: et sw=4 s
00001c0: 7473 3d34 0d0a                           ts=4..

Copied version:

0000000: 4854 4d4c 2e53 6166 654f 626a 6563 740a  HTML.SafeObject.
0000010: 5459 5045 3a20 626f 6f6c 0a56 4552 5349  TYPE: bool.VERSI
0000020: 4f4e 3a20 332e 312e 310a 4445 4641 554c  ON: 3.1.1.DEFAUL
0000030: 543a 2066 616c 7365 0a2d 2d44 4553 4352  T: false.--DESCR
0000040: 4950 5449 4f4e 2d2d 0a3c 703e 0a20 2020  IPTION--.
.
0000050: 2057 6865 7468 6572 206f 7220 6e6f 7420   Whether or not
0000060: 746f 2070 6572 6d69 7420 6f62 6a65 6374  to permit object
0000070: 2074 6167 7320 696e 2064 6f63 756d 656e   tags in documen
0000080: 7473 2c20 7769 7468 2061 206e 756d 6265  ts, with a numbe
0000090: 7220 6f66 2065 7874 7261 0a20 2020 2073  r of extra.    s
00000a0: 6563 7572 6974 7920 6665 6174 7572 6573  ecurity features
00000b0: 2061 6464 6564 2074 6f20 7072 6576 656e   added to preven
00000c0: 7420 7363 7269 7074 2065 7865 6375 7469  t script executi
00000d0: 6f6e 2e20 5468 6973 2069 7320 7369 6d69  on. This is simi
00000e0: 6c61 7220 746f 0a20 2020 2077 6861 7420  lar to.    what
00000f0: 7765 6273 6974 6573 206c 696b 6520 4d79  websites like My
0000100: 5370 6163 6520 646f 2074 6f20 6f62 6a65  Space do to obje
0000110: 6374 2074 6167 732e 2020 596f 7520 7368  ct tags.  You sh
0000120: 6f75 6c64 2061 6c73 6f20 656e 6162 6c65  ould also enable
0000130: 0a20 2020 2025 4f75 7470 7574 2e46 6c61  .    %Output.Fla
0000140: 7368 436f 6d70 6174 2069 6e20 6f72 6465  shCompat in orde
0000150: 7220 746f 2067 656e 6572 6174 6520 496e  r to generate In
0000160: 7465 726e 6574 2045 7870 6c6f 7265 720a  ternet Explorer.
0000170: 2020 2020 636f 6d70 6174 6962 696c 6974      compatibilit
0000180: 7920 636f 6465 2066 6f72 2079 6f75 7220  y code for your
0000190: 6f62 6a65 6374 2074 6167 732e 0a3c 2f70  object tags..
.--# vim: et sw
00001b0: 3d34 2073 7473 3d34 0a                   =4 sts=4.


问:
How to extract the data from JSON file to write test case
How to extract the required parent/child node value from JSON output in postman.

I need to extract model.ConfirmPassword from the below JSON file.

```<code>{
  "Message": "The request is invalid.",
  "ModelState": {
  "model.ConfirmPassword": [
  "The password and confirmation password do not match."
  ]
}
</code>```

What is the property to be passed in order to get that. jsonData.value is not working as I mentioned below.

```<code>var jsonData = JSON.parse(responseBody);
tests["Your test name"] = jsonData.value;
</code>```

答:
The answer should be

```<code>var jsonData = JSON.parse(responseBody);
tests["Your test name"] = jsonData.ModelState['model.ConfirmPassword'][0] ==="The password and confirmation password do not match.";
</code>```

Need to pass the index as [0] in jsonData.ModelState['model.ConfirmPassword'][0]
Otherwise it wont work if we want to access child elems.
It can be [0] or the specific index.

Body:
How to extract the required parent/child node value from JSON output in postman.

I need to extract model.ConfirmPassword from the below JSON file.

{
  "Message": "The request is invalid.",
  "ModelState": {
  "model.ConfirmPassword": [
  "The password and confirmation password do not match."
  ]
}

What is the property to be passed in order to get that. jsonData.value is not working as I mentioned below.

var jsonData = JSON.parse(responseBody);
tests["Your test name"] = jsonData.value;

Body:
The answer should be

var jsonData = JSON.parse(responseBody);
tests["Your test name"] = jsonData.ModelState['model.ConfirmPassword'][0] ==="The password and confirmation password do not match.";

Need to pass the index as [0] in jsonData.ModelState['model.ConfirmPassword'][0]
Otherwise it wont work if we want to access child elems.
It can be [0] or the specific index.


问:
Why do I have to have double quotes inside single quotes in JavaScript?
Can someone explain why I must embed the double quotes within single quotes in my Webpack configuration below?  Why does it not work to just use double quotes?

```<code>module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  API: '"http://localhost:8080"'
});
</code>```

My app fails to load if I remove the single quotes, which seems really odd.

答:
This webpack plugin is going to be doing interpolation in your code. In other words, it will be replacing, at build time, process.env.NODE_ENV with whatever you have there.

So your code goes from console.log(process.env.NODE_ENV) to console.log("development"). If you left out the single quotes it would become console.log(development), which would fail since there is no variable development.

Body:
Can someone explain why I must embed the double quotes within single quotes in my Webpack configuration below?  Why does it not work to just use double quotes?

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  API: '"http://localhost:8080"'
});

My app fails to load if I remove the single quotes, which seems really odd.


问:
Bookshelf.JS | How to use where and orWhere in query
BookshelfJS has the following example for using 'query':

```<code>model
  .query({where: {other_id: '5'}, orWhere: {key: 'value'}})
  .fetch()
  .then(function(model) {
    ...
  });
</code>```

Is it okay to do the following:

```<code>var whereObj = {
  'key1':'value1',
  'key2':'value2'
};

model
  .query({where: whereObj, orWhere: {key: 'value'}})
  .fetch()
  .then(function(model) {
    ...
  });
</code>```

答:
Check out the bookshelf-eloquent extension which exposes many of the Knex.js functions directly on the bookshelf model. Your code would be simplified to something like this:</p>

```<code>let result = await Model.where({other_id: 5}).orWhere('key', 'value').fetch();
</code>```

Body:
BookshelfJS has the following example for using 'query':

model
  .query({where: {other_id: '5'}, orWhere: {key: 'value'}})
  .fetch()
  .then(function(model) {
    ...
  });

Is it okay to do the following:

var whereObj = {
  'key1':'value1',
  'key2':'value2'
};

model
  .query({where: whereObj, orWhere: {key: 'value'}})
  .fetch()
  .then(function(model) {
    ...
  });

Body:
Check out the bookshelf-eloquent extension which exposes many of the Knex.js functions directly on the bookshelf model. Your code would be simplified to something like this:

let result = await Model.where({other_id: 5}).orWhere('key', 'value').fetch();


问:
Asset Management Database Design
I am currently busy implementing a basic Asset Management System. It will not be very complicated. Simply something to keep track of any asset with it's name, serial number, parts number and type etc. The problem I have however, is that I want to incorporate books as well. Unfortunately, books have a very different structure than normal assets (for example title, authors, isbn codes etc.).

I would like some insight from the community as to what design they think is best. Incorporate books in asset management (and if so, how should the database design look), or should I simply write a completely seperate, independant Library module (maybe with some functionality to export a book to the Asset Management System [with fewer / other fields]).

Thanks!

EDIT: Something else that is possible is to make the capture screen dynamic, so the user can specify the fields and the values. This can then be stored in as XML in the database. But his would not be my preferred way of doing it.

EDIT 2: I forgot to mention, I am very bound by the technologies that I may use. These are MySQL, GWT, Hibernate and Spring (no Spring transactions).

答: From the technology constraints I would suggest keeping the modules separate.</p>

Title: Asset Management Database Design


问:
LDAP connection bind not successful
I am trying to make a LDAP connection to a test server from apache2(Ubuntu) with PHP. I have php-ldap installed. And this is my connection code snippet.

```<code>$ldap_dn = "cn=read-only-admin,dc=example,dc=com";
$ldap_password = "password";

$ldap_con = ldap_connect("ldap.forumsys.com", "389") or die("Not connected");

ldap_set_option($ldap_con, LDAP_OPT_PROTOCOL_VERSION, 3);

if(ldap_bind($ldap_con, $ldap_dn, $ldap_password)) {

  echo "Bind successful!";

} else {
    echo "Invalid user/pass or other errors!";
}
</code>```

Log: [:error] [pid 7332] [client 10.9.114.7:47852] PHP Warning:
  ldap_bind(): Unable to bind to server: Can't contact LDAP server in
  /var/www/html/connect_test.php

This code works on my localhost. But in the apache2 server, ldap_connect is successful but ldap_bind is not. Can I know what I am doing wrong? Newbie here! Thanks in advance! :)

答: For anyone who looks this up later. The problem is - there was a firewall blocking all other LDAP connections except our own. That's the reason why the test LDAP server from forumsys didn't work. Once you install php-ldap, you are good to go ahead and connect to any LDAP server if your firewall allows it. Hope this helps! :)

Title: LDAP connection bind not successful

Body:
I am trying to make a LDAP connection to a test server from apache2(Ubuntu) with PHP. I have php-ldap installed. And this is my connection code snippet.

$ldap_dn = "cn=read-only-admin,dc=example,dc=com";
$ldap_password = "password";

$ldap_con = ldap_connect("ldap.forumsys.com", "389") or die("Not connected");

ldap_set_option($ldap_con, LDAP_OPT_PROTOCOL_VERSION, 3);

if(ldap_bind($ldap_con, $ldap_dn, $ldap_password)) {

  echo "Bind successful!";

} else {
    echo "Invalid user/pass or other errors!";
}

Log: [:error] [pid 7332] [client 10.9.114.7:47852] PHP Warning:
  ldap_bind(): Unable to bind to server: Can't contact LDAP server in
  /var/www/html/connect_test.php

This code works on my localhost. But in the apache2 server, ldap_connect is successful but ldap_bind is not. Can I know what I am doing wrong? Newbie here! Thanks in advance! :)


问:
Add Trailing Ellipsis To Breadcrumb Depending On Device Width
On my user interface I have a breadcrumb of which shows on the top bar. Upon the device width being below a defined width, it'll drop below the top bar and be it's own bar, however what I do not know how to do is add a trailing ellipsis upon the breadcrumb length being larger than the device width.

Example Breadcrumb:

```<code><nav>
    <ul>
        <li>Home</li>
        <li>>></li>
        <li>User</li>
        <li>>></li>
        <li>Inbox</li>
        <li>>></li>
        <li>Mail_ID</li>
    </ul>
</nav>
</code>```

Note: >> represents a FontAwesome icon in an i tag

Upon the breadcrumb being larger than the device width, the best I can describe what I would like to happen is demonstrated below:

Home >> User >> Inbox >> Mail_ID

... User >> Inbox >> Mail_ID

... Inbox >> Mail_ID

... Mail_ID

答:
This is still a partial code but might help you.

Idea

On load, call a function that checks for with of ul and its parent container.

If ul has greater width, hide first 2 visible li. Also add an li for ellipsis and make it hidden initially and make it visible only if any of other divs are hidden.

Repeat this process recursively and you will get what you are looking for.

Sample

$(function() {
  $(".content").resizable();

  $(".content").on("resize", function() {
    var ul = $(this).find('ul');
    if (ul.width() > $(this).width()) {
      var lis = ul.find('li:not(.hide):not(.ellipsis)');
      for (var i = 0; i < 2; i++) {
        $(lis[i]).addClass("hide");
      }
      if ($(".ellipsis").not(":visible"))
        $(".ellipsis").removeClass("hide")
    }
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.content {
  text-align: left;
  border: 1px solid gray;
  width: 300px;
  height: 40px;
  max-height: 40px;
}

.content ul {
  padding: 0px;
  position: fixed;
  overflow: hidden;
  white-space: nowrap;
}

.content ul li {
  display: inline-block;
  text-decoration: none;
}

.hide {
  display: none!important;
}</code>```

<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />

...

Home

>>

User

>>

Inbox

>>

Mail_ID

```

Body:
On my user interface I have a breadcrumb of which shows on the top bar. Upon the device width being below a defined width, it'll drop below the top bar and be it's own bar, however what I do not know how to do is add a trailing ellipsis upon the breadcrumb length being larger than the device width.

Example Breadcrumb:

Home

>>

User

>>

Inbox

>>

Mail_ID

Note: >> represents a FontAwesome icon in an i tag

Upon the breadcrumb being larger than the device width, the best I can describe what I would like to happen is demonstrated below:

Home >> User >> Inbox >> Mail_ID

... User >> Inbox >> Mail_ID

... Inbox >> Mail_ID

... Mail_ID

Body:
This is still a partial code but might help you.

Idea

On load, call a function that checks for with of ul and its parent container.

If ul has greater width, hide first 2 visible li. Also add an li for ellipsis and make it hidden initially and make it visible only if any of other divs are hidden.

Repeat this process recursively and you will get what you are looking for.

Sample

$(function() {
  $(".content").resizable();

  $(".content").on("resize", function() {
    var ul = $(this).find('ul');
    if (ul.width() > $(this).width()) {
      var lis = ul.find('li:not(.hide):not(.ellipsis)');
      for (var i = 0; i < 2; i++) {
        $(lis[i]).addClass("hide");
      }
      if ($(".ellipsis").not(":visible"))
        $(".ellipsis").removeClass("hide")
    }
  })
});

.content {
  text-align: left;
  border: 1px solid gray;
  width: 300px;
  height: 40px;
  max-height: 40px;
}

.content ul {
  padding: 0px;
  position: fixed;
  overflow: hidden;
  white-space: nowrap;
}

.content ul li {
  display: inline-block;
  text-decoration: none;
}

.hide {
  display: none!important;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="content">

  <ul>
    <li class="hide ellipsis">...</li>
    <li>Home</li>
    <li>>></li>
    <li>User</li>
    <li>>></li>
    <li>Inbox</li>
    <li>>></li>
    <li>Mail_ID</li>
  </ul>

</div>


问:
React.JS: Sequence of timed state changes
I have a simple web app with one parent component and three child components. The children are just div boxes that can change their background color from white to red based on their property active. The animateChild() function can be used to turn a specific child red and then white again after 1s.

My goal is to "play" an arbitrary sequence of child animations with a break of 1s between each animation. This should happen in the animateSequence() function.

My initial idea to accomplish that, was to use a for loop and call animateChild(childNum) in a window.setTimeout() at each iteration. However, this didn't work. I guess because setState() is asynchronous and several state changes get merged together.

What is the best way to accomplish a sequence (e.g. Child 1, Child 2, Child 3) of animations with a break time of 1s between each animation? Thank you very much

Javascript Code:

```<code>class Child extends React.Component {

  render() {
    var childStyle = "basic";
    if (this.props.active){
      childStyle += " active";
    }
    return (
        <div className={childStyle}></div>
    );
  }
}

class Parent extends React.Component {
  constructor(){
    super();
    this.state = {
      firstChildActive:false,
      secondChildActive:false,
      thirdChildActive:false,
    };
    this.animateChild = this.animateChild.bind(this);

  }

  animateChild(childNum){
    var childDict = ["firstChildActive","secondChildActive","thirdChildActive"];
    this.setState({[childDict[childNum]]: true}, function() {

        window.setTimeout(() => {
        this.setState({[childDict[childNum]]: false});

        },1000);
    });
  }

  animateSequence(){
    // animate child 2, then child 1, then child 3, then child 1, etc.
  }

  render() {
    return (
      <div className ="container">
      <Child active={this.state.firstChildActive}/>
      <Child active={this.state.secondChildActive}/>
      <Child active={this.state.thirdChildActive}/>
      </div>
    );
  }
}

ReactDOM.render(<Parent />,document.getElementById('app'));
</code>```

CSS Code:

```<code>.container{
  display:flex;
  width:100%;
  justify-content: space-between;

}

.basic{
  margin: 10px;
  width: 100px;
  height:100px;
  border: 2px solid black;
}

.active{
  background: red;
}
</code>```

Codepen: https://codepen.io/miga89/full/owgZea/

答:
if you want do that without button use componentDidMount method in prototype:</p>

```<code> componentDidMount(){
  this.animateSequence();
}
  render() {
    return (
      <div className ="container">
      <Child isActive={this.state.firstChildActive }/>
      <Child isActive={this.state.secondChildActive } />
      <Child isActive={this.state.thirdChildActive }/>
      </div>
    );
  }
</code>```

Body:
I have a simple web app with one parent component and three child components. The children are just div boxes that can change their background color from white to red based on their property active. The animateChild() function can be used to turn a specific child red and then white again after 1s.

My goal is to "play" an arbitrary sequence of child animations with a break of 1s between each animation. This should happen in the animateSequence() function.

My initial idea to accomplish that, was to use a for loop and call animateChild(childNum) in a window.setTimeout() at each iteration. However, this didn't work. I guess because setState() is asynchronous and several state changes get merged together.

What is the best way to accomplish a sequence (e.g. Child 1, Child 2, Child 3) of animations with a break time of 1s between each animation? Thank you very much

Javascript Code:

class Child extends React.Component {

  render() {
    var childStyle = "basic";
    if (this.props.active){
      childStyle += " active";
    }
    return (

    );
  }
}

class Parent extends React.Component {
  constructor(){
    super();
    this.state = {
      firstChildActive:false,
      secondChildActive:false,
      thirdChildActive:false,
    };
    this.animateChild = this.animateChild.bind(this);

  }

  animateChild(childNum){
    var childDict = ["firstChildActive","secondChildActive","thirdChildActive"];
    this.setState({[childDict[childNum]]: true}, function() {

        window.setTimeout(() => {
        this.setState({[childDict[childNum]]: false});

        },1000);
    });
  }

  animateSequence(){
    // animate child 2, then child 1, then child 3, then child 1, etc.
  }

  render() {
    return (

      <Child active={this.state.firstChildActive}/>
      <Child active={this.state.secondChildActive}/>
      <Child active={this.state.thirdChildActive}/>

    );
  }
}

ReactDOM.render(<Parent />,document.getElementById('app'));

CSS Code:

.container{
  display:flex;
  width:100%;
  justify-content: space-between;

}

.basic{
  margin: 10px;
  width: 100px;
  height:100px;
  border: 2px solid black;
}

.active{
  background: red;
}

Codepen: https://codepen.io/miga89/full/owgZea/

Body:
if you want do that without button use componentDidMount method in prototype:

 componentDidMount(){
  this.animateSequence();
}
  render() {
    return (
      <div className ="container">
      <Child isActive={this.state.firstChildActive }/>
      <Child isActive={this.state.secondChildActive } />
      <Child isActive={this.state.thirdChildActive }/>
      </div>
    );
  }


问:
How to get the clicked html element and edit?
I want to get the clicked html elements and edit it after some times.

What I tried?

I tried the below one, but I can get the exact html element in html text format, but I can not able to change it. How can I change the value.

```<code>var _targetevent;

$( "body" ).click(function( event ) {
  _targetevent=event;
  console.log( "clicked: " + event.target); //<p>This is the old one</p>
});

function undateit()
{
  _targetevent.target="<b>This is the new div</b>";
}
</code>```

答:
1.Call undateit() inside click()

2.Use innerHTML along with _targetevent.target

Example:-

var _targetevent;

$( "body" ).click(function( event ) {
  _targetevent=event;
  console.log( "clicked: " + event.target.id); //get id of the clicked element
  undateit(); //call function on click
});

function undateit(){
  //use outerHTML to completly replace div with new-one

  _targetevent.target.outerHTML="This is the new div";

  /* if you want to change only content inside element then use inner HTML

  _targetevent.target.innerHTML="This is the new div"; //use innerHTML

  */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="mydiv">Check change</div>
</body></code>```

Body:
I want to get the clicked html elements and edit it after some times.

What I tried?

I tried the below one, but I can get the exact html element in html text format, but I can not able to change it. How can I change the value.

var _targetevent;

$( "body" ).click(function( event ) {
  _targetevent=event;
  console.log( "clicked: " + event.target); //
This is the old one

});

function undateit()
{
  _targetevent.target="This is the new div";
}

Body:
1.Call undateit() inside click()

2.Use innerHTML along with _targetevent.target

Example:-

var _targetevent;

$( "body" ).click(function( event ) {
  _targetevent=event;
  console.log( "clicked: " + event.target.id); //get id of the clicked element
  undateit(); //call function on click
});

function undateit(){
  //use outerHTML to completly replace div with new-one

  _targetevent.target.outerHTML="<b>This is the new div</b>";

  /* if you want to change only content inside element then use inner HTML

  _targetevent.target.innerHTML="<b>This is the new div</b>"; //use innerHTML

  */
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="mydiv">Check change</div>
</body>


问:
PhpStorm, Laravel and autocompletition
I have a method run() in TreeGen class:

```<code>class TreeGen implements TreeGenerable{

 public function run()
 {
     ...
     $this->pushEmptyGroupsToTree($numFighters);
     ...
 }
}
</code>```

Thing is $this could be one of the 4 Subclasses of tree gen, and all those method implement different versions of pushEmptyGroupsToTree.

But PhpStorm is only looking for pushEmptyGroupsToTree in TreeGen class and off course, I don't have it defined in the super class, so it doesn't detect it.

Is there a way to make him recognize subclass methods?

答:
If you dont want TreeGreen to be used directly, declare it abstract as such:

```<code>abstract class TreeGen implements TreeGenerable {
// ...
</code>```

If you need the child classes to have that method declared, declare it as abstract in your superclass:

```<code>abstract class TreeGen implements TreeGenerable
{
    // ...
    abstract public function pushEmptyGroupsToTree($numFighters);
}
</code>```

Now you cant extend TreeGen without implementing pushEmptyGroupsToTree as well

Title: PhpStorm, Laravel and autocompletition

Body:
I have a method run() in TreeGen class:

class TreeGen implements TreeGenerable{

 public function run()
 {
     ...
     $this->pushEmptyGroupsToTree($numFighters);
     ...
 }
}

Thing is $this could be one of the 4 Subclasses of tree gen, and all those method implement different versions of pushEmptyGroupsToTree.

But PhpStorm is only looking for pushEmptyGroupsToTree in TreeGen class and off course, I don't have it defined in the super class, so it doesn't detect it.

Is there a way to make him recognize subclass methods?

Body:
If you dont want TreeGreen to be used directly, declare it abstract as such:

abstract class TreeGen implements TreeGenerable {
// ...

If you need the child classes to have that method declared, declare it as abstract in your superclass:

abstract class TreeGen implements TreeGenerable
{
    // ...
    abstract public function pushEmptyGroupsToTree($numFighters);
}

Now you cant extend TreeGen without implementing pushEmptyGroupsToTree as well


问:
open new activity with button
here is the code of my xml.

```<code><Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn2"
            android:layout_gravity="center_horizontal"
            android:text="Make New Account"
            android:onClick="new"
            android:textColor="#E74C3C"
            android:textStyle="bold"
            android:paddingTop="20dp"/>
</code>```

and here is my code of java.

```<code> public Button btn2;
public void onClick(){
    btn2=(Button)findViewById(R.id.btn2);
    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,submit.class);
            startActivity(intent);
        }
    });

}
</code>```

my button is not working yet, even an message will appear after clicking on button that unfortunately application has stopped... what is the reason??

答:
Your code is perfect Nida..
Just Add Your activity name in menifest file like below code,</p>

```<code> <activity android:name=".submit"/>
</code>```

Title: open new activity with button

Body:
here is the code of my xml.

<Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn2"
            android:layout_gravity="center_horizontal"
            android:text="Make New Account"
            android:onClick="new"
            android:textColor="#E74C3C"
            android:textStyle="bold"
            android:paddingTop="20dp"/>

and here is my code of java.

 public Button btn2;
public void onClick(){
    btn2=(Button)findViewById(R.id.btn2);
    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,submit.class);
            startActivity(intent);
        }
    });

}

my button is not working yet, even an message will appear after clicking on button that unfortunately application has stopped... what is the reason??

Body:
Your code is perfect Nida..
Just Add Your activity name in menifest file like below code,

 <activity android:name=".submit"/>


问:
React.js Uncaught Error: _registerComponent(...): Target container is not a DOM element
Hi I am getting this error:

main.js:808 Uncaught Error: _registerComponent(...): Target container is not a DOM element.

I have visited this question, but I cannot figure out what is wrong with what I am doing.

Here is the code I have right now:

routes.js:

```<code>export default (
  <Route path="/" component={App}>
    <IndexRoute component={HomePage} />
  </Route>
);
</code>```

app.js

```<code>const store = configureStore();

render(
  <Provider store={store}>
    <Router history={browserHistory} routes={routes} />
  </Provider>,
  document.getElementById('app')
);
</code>```

homepage.js

```<code>class HomePage extends React.Component {
  render() {
    return (
      <div id="app">
        Hello
      </div>
    );
  }
}

export default HomePage;
</code>```

I think that I am missing something easy but I am not sure what it is.  I have tried modifying my code to match the answers of that other question but it didnt work out.  Thank you for any help

答:
The error says that document.getElementById('app') operation didn't find any corresponded html node in the page document. You have to create a

 directly in your index.html so document.getElementById('app') could find it. Your
 in HomePage container is useless as it's unavailable in DOM during React app initialization.

Also, be sure to inject your

Body:
Hi I am getting this error:

main.js:808 Uncaught Error: _registerComponent(...): Target container is not a DOM element.

I have visited this question, but I cannot figure out what is wrong with what I am doing.

Here is the code I have right now:

routes.js:

export default (
  <Route path="/" component={App}>
    <IndexRoute component={HomePage} />
  </Route>
);

app.js

const store = configureStore();

render(
  <Provider store={store}>
    <Router history={browserHistory} routes={routes} />
  </Provider>,
  document.getElementById('app')
);

homepage.js

class HomePage extends React.Component {
  render() {
    return (

        Hello

    );
  }
}

export default HomePage;

I think that I am missing something easy but I am not sure what it is.  I have tried modifying my code to match the answers of that other question but it didnt work out.  Thank you for any help

Body:
The error says that document.getElementById('app') operation didn't find any corresponded html node in the page document. You have to create a <div id="app"></div> directly in your index.html so document.getElementById('app') could find it. Your <div id="app"> in HomePage container is useless as it's unavailable in DOM during React app initialization.

Also, be sure to inject your <script> with bundled React app after <div id="app"></div> (inject that <script> to the end of the body tag to be safe).


问:
vue.js 'document.getElementById' shorthand
Does vue.js have a shorthand for document.getElementById('#id') like JQuery's $('#id')?

If so, where is the reference for this in the docs so I can locate other information?

答:
Try not to do DOM manipulation by referring the DOM directly, it will have lot of performance issue, also event handling becomes more tricky when we try to access DOM directly, instead use data and directives to manipulate the DOM.

This will give you more control over the manipulation, also you will be able to manage functionalities in the modular format.


问:
Tell GCC to assume an object is initialized
When compiling in GCC with -Wall, GCC will warn about using variables that might be uninitialized.  However, as the programmer, I know that a variable must be initialized if control enters a certain if statement:

```<code>int foo;

/* conditional assignment of foo goes here */

if (/* complicated condition that guarantees that foo has been initialized */){
    return test(foo);
}
</code>```

In the above code, GCC will complain that foo may be used uninitialized.  In particular, the complain will arise from inside the definition of test(), where foo is actually used.

Is there a GCC builtin or equivalent to tell the compiler that foo is already initialized?  For example:

```<code>if (/* complicated condition that guarantees that foo has been initialized */){
    __assume_initialized(foo);
    return test(foo);
}
</code>```

Note that placing #pragma GCC diagnostic ignored "-Wuninitialized" before the line return test(foo) is insufficient as the uninitialized warning arises from the usage (e.g. comparison) of foo in the definition of test(), possibly in another compilation unit, where the pragma won't exist.

Neither do I want to put the pragma inside the definition of test(), because the issue is not with test(). test() should of course not be called with random garbage, and putting the pragma there might cause other mistakes to go unnoticed.

Any solutions?

答:
The simplest solution is to (redundantly) initialize that variable e.g. by adding:

```<code>int foo=0;
</code>```

the optimizing compiler (e.g. g++ -O2) is very likely to remove that initialization if it is unneeded. BTW, if the compiler don't optimize that in your particular case, the overhead of such an initialization is really small.

If foo is an instance of some class you could define a no-op constructor (perhaps a private: one) and make your function friend of that class.
If foo is some pointer initialize it to nullptr.

BTW, such an explicit initialization makes your code more readable and less brittle and perhaps even more CPU cache friendly. You might add a comment explaining why and how it might be unneeded. IMHO the readability increase is enough to justify such an initialization.

I tend to always initialize locals, leaving the compiler the opportunity to optimize away most of the useless initializations.

Alternatively (but I don't recommend that) use a function specific pragma  (as mentioned in your question) to disable such a warning.

Body:
When compiling in GCC with -Wall, GCC will warn about using variables that might be uninitialized.  However, as the programmer, I know that a variable must be initialized if control enters a certain if statement:

int foo;

/* conditional assignment of foo goes here */

if (/* complicated condition that guarantees that foo has been initialized */){
    return test(foo);
}

In the above code, GCC will complain that foo may be used uninitialized.  In particular, the complain will arise from inside the definition of test(), where foo is actually used.

Is there a GCC builtin or equivalent to tell the compiler that foo is already initialized?  For example:

if (/* complicated condition that guarantees that foo has been initialized */){
    __assume_initialized(foo);
    return test(foo);
}

Note that placing #pragma GCC diagnostic ignored "-Wuninitialized" before the line return test(foo) is insufficient as the uninitialized warning arises from the usage (e.g. comparison) of foo in the definition of test(), possibly in another compilation unit, where the pragma won't exist.

Neither do I want to put the pragma inside the definition of test(), because the issue is not with test(). test() should of course not be called with random garbage, and putting the pragma there might cause other mistakes to go unnoticed.

Any solutions?

Body:
The simplest solution is to (redundantly) initialize that variable e.g. by adding:

int foo=0;

the optimizing compiler (e.g. g++ -O2) is very likely to remove that initialization if it is unneeded. BTW, if the compiler don't optimize that in your particular case, the overhead of such an initialization is really small.

If foo is an instance of some class you could define a no-op constructor (perhaps a private: one) and make your function friend of that class.
If foo is some pointer initialize it to nullptr.

BTW, such an explicit initialization makes your code more readable and less brittle and perhaps even more CPU cache friendly. You might add a comment explaining why and how it might be unneeded. IMHO the readability increase is enough to justify such an initialization.

I tend to always initialize locals, leaving the compiler the opportunity to optimize away most of the useless initializations.

Alternatively (but I don't recommend that) use a function specific pragma  (as mentioned in your question) to disable such a warning.


问:
Connect Qt application to PostgreSQL DB without driver
Subj: is it possible?
If yes:
1) Is it acceptable programming strategy?
2) How to do it?</p>

答:
Yes, it should be possible.

No, it's not an acceptable programming strategy.

You would use the classes in the QtNetwork Module to handle the communication with the database. You have to know (learn) the protocol and you would need a module to handle the respones of the database. You would need to reimplement most of the Qt psql driver and use or reimplement the PostgreSQL development libraries.


问:
How do I import a Java project into Firebase and create a database?
I had built java project with MySQL database. I want to import this java project into the firebase. please guide How to create DB in firebase and how to import the java ready project into the firebase?</p>

答:
First visit https://firebase.google.com/ for more details
then create a new Project as per your required platform.

In server Side create a table to store User FCM Key

```<code>Table: fcmkeys
Columns:
user varchar(10) PK
fcmkey varchar(1045)
</code>```

Generate FCM_AUTH_KEY
Create a Java Helper class like

```<code>public class FCMHelper {

    static Logger log = Logger.getLogger(FCMHelper.class);
    // Method to send Notifications from server to client end.

    public final static String AUTH_KEY_FCM = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";

    // userDeviceIdKey is the device id you will query from your database

    public static void pushFCMNotification(String userDeviceIdKey ,String NotificationString) throws Exception{

       String authKey = AUTH_KEY_FCM; // You FCM AUTH key
       String FMCurl = API_URL_FCM;

       URL url = new URL(FMCurl);
       HttpURLConnection conn = (HttpURLConnection) url.openConnection();

       conn.setUseCaches(false);
       conn.setDoInput(true);
       conn.setDoOutput(true);

       conn.setRequestMethod("POST");
       conn.setRequestProperty("Authorization","key="+authKey);
       conn.setRequestProperty("Content-Type","application/json");

       JSONObject json = new JSONObject();
       json.put("to",userDeviceIdKey.trim());
       JSONObject info = new JSONObject();
      // info.put("title", "Alert!"); // Notification title
       info.put("body", NotificationString); // Notification body
       json.put("data", info);

       OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
       wr.write(json.toString());
       wr.flush();
       conn.getInputStream();
       System.out.println("Notification Send Success!");
       System.out.println( conn.getInputStream().toString());

       InputStream in = new BufferedInputStream(conn.getInputStream());
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();

        String inputStr;
        while ((inputStr = streamReader.readLine()) != null)
            responseStrBuilder.append(inputStr);
        String s = responseStrBuilder.toString();
         System.out.println( s);
         log.info(s);

    }
}
</code>```

This Helper class can send FCM Notification to the client

Body:
First visit https://firebase.google.com/ for more details
then create a new Project as per your required platform.

In server Side create a table to store User FCM Key

Table: fcmkeys
Columns:
user varchar(10) PK
fcmkey varchar(1045)

Generate FCM_AUTH_KEY
Create a Java Helper class like

public class FCMHelper {

    static Logger log = Logger.getLogger(FCMHelper.class);
    // Method to send Notifications from server to client end.

    public final static String AUTH_KEY_FCM = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";

    // userDeviceIdKey is the device id you will query from your database

    public static void pushFCMNotification(String userDeviceIdKey ,String NotificationString) throws Exception{

       String authKey = AUTH_KEY_FCM; // You FCM AUTH key
       String FMCurl = API_URL_FCM;

       URL url = new URL(FMCurl);
       HttpURLConnection conn = (HttpURLConnection) url.openConnection();

       conn.setUseCaches(false);
       conn.setDoInput(true);
       conn.setDoOutput(true);

       conn.setRequestMethod("POST");
       conn.setRequestProperty("Authorization","key="+authKey);
       conn.setRequestProperty("Content-Type","application/json");

       JSONObject json = new JSONObject();
       json.put("to",userDeviceIdKey.trim());
       JSONObject info = new JSONObject();
      // info.put("title", "Alert!"); // Notification title
       info.put("body", NotificationString); // Notification body
       json.put("data", info);

       OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
       wr.write(json.toString());
       wr.flush();
       conn.getInputStream();
       System.out.println("Notification Send Success!");
       System.out.println( conn.getInputStream().toString());

       InputStream in = new BufferedInputStream(conn.getInputStream());
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();

        String inputStr;
        while ((inputStr = streamReader.readLine()) != null)
            responseStrBuilder.append(inputStr);
        String s = responseStrBuilder.toString();
         System.out.println( s);
         log.info(s);

    }
}

This Helper class can send FCM Notification to the client


问:
Autofill method of range class failed - help needed for my code
I've been trying to make this work. It worked fine on my x64 version of office but not the x86 on my colleagues' computers. Can anyone gimme a fix please?

The VBA engine highlighted Range("AV5").AutoFill Destination:=Range("AV5:AV" & NoOfClients) as the cause

```<code>Private Sub Check_Cases_Click()
Dim NoOfClients As Long

Application.DisplayAlerts = False
CO_Select = Application.InputBox("Please input the name of caseworker you would like to check on.", "Caseworker Name")
Range("A2").value = CO_Select

Application.ScreenUpdating = False
NoOfClients = Range("C2").value
CO_Name = Range("A2").value

CheckCaseMsg = MsgBox(CO_Name & ", there are " & NoOfClients & " clients under your name." & vbNewLine & vbNewLine & _
                    "System will now calculate all your active cases and display " & vbNewLine & _
                    "all the clients for your information." & vbNewLine & vbNewLine & _
                    "Confirm?", vbYesNo, "Case Checking")

If CheckCaseMsg = vbNo Then
Exit Sub
End If

If CheckCaseMsg = vbYes Then

'Remove the filters if one exists
'=========================================
If ActiveSheet.FilterMode Then
Selection.AutoFilter
End If

Clear
Startup_Formula

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Range("AV5").AutoFill Destination:=Range("AV5:AV" & NoOfClients)

Application.Calculation = xlCalculationAutomatic

Range("GI_Table[[#All],[Client number]]").Copy
Range("GI_Table[[#All],[Client number]]").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

Application.ScreenUpdating = True

ActiveSheet.ListObjects("GI_Table").Range.AutoFilter Field:=2, Criteria1:= _
        Array("ACTIVE", "INACTIVE", "RENEWED"), Operator:=xlFilterValues

GI_CustomSort
GI_CustomSort

MsgBox "Case Checking Ready", vbInformation, "Ready"
End If

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
</code>```

答:
Instead of just Range(".."). you should try

```<code>Dim sht as Worksheet
Set sht = Worksheets("Name")

sht.Range("..")
</code>```

and so on.

Body:
I've been trying to make this work. It worked fine on my x64 version of office but not the x86 on my colleagues' computers. Can anyone gimme a fix please?

The VBA engine highlighted Range("AV5").AutoFill Destination:=Range("AV5:AV" & NoOfClients) as the cause

Private Sub Check_Cases_Click()
Dim NoOfClients As Long

Application.DisplayAlerts = False
CO_Select = Application.InputBox("Please input the name of caseworker you would like to check on.", "Caseworker Name")
Range("A2").value = CO_Select

Application.ScreenUpdating = False
NoOfClients = Range("C2").value
CO_Name = Range("A2").value

CheckCaseMsg = MsgBox(CO_Name & ", there are " & NoOfClients & " clients under your name." & vbNewLine & vbNewLine & _
                    "System will now calculate all your active cases and display " & vbNewLine & _
                    "all the clients for your information." & vbNewLine & vbNewLine & _
                    "Confirm?", vbYesNo, "Case Checking")

If CheckCaseMsg = vbNo Then
Exit Sub
End If

If CheckCaseMsg = vbYes Then

'Remove the filters if one exists
'=========================================
If ActiveSheet.FilterMode Then
Selection.AutoFilter
End If

Clear
Startup_Formula

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Range("AV5").AutoFill Destination:=Range("AV5:AV" & NoOfClients)

Application.Calculation = xlCalculationAutomatic

Range("GI_Table[[#All],[Client number]]").Copy
Range("GI_Table[[#All],[Client number]]").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

Application.ScreenUpdating = True

ActiveSheet.ListObjects("GI_Table").Range.AutoFilter Field:=2, Criteria1:= _
        Array("ACTIVE", "INACTIVE", "RENEWED"), Operator:=xlFilterValues

GI_CustomSort
GI_CustomSort

MsgBox "Case Checking Ready", vbInformation, "Ready"
End If

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

Body:
Instead of just Range(".."). you should try

Dim sht as Worksheet
Set sht = Worksheets("Name")

sht.Range("..")

and so on.


问:
UILabel get Frame width or height
```<code>`lblAddress.frame.width`
`lblAddress.frame.size.width`
</code>```

I have searched so many time but still i haven't point out...what is difference between lblAddress.frame.width AND  lblAddress.frame.size.width. it gives me same output..I don't know which one to use when?

please suggest some example so I can figure out whole thing.

答:
To know more, you can look how CGRect structure is constructed.

```<code>struct CGRect {
  var origin: CGPoint
  var size: CGSize
}
</code>```

and to add some extra functionality, an extension of CGRect is also provided by apple, like the following

```<code>extension CGRect {

    @available(iOS 2.0, *)
    public var height: CGFloat { get }

    @available(iOS 2.0, *)
    public var width: CGFloat { get }
}
</code>```

Now to answer your question.
lblAddress.frame will return a CGRect

```<code>lblAddress.frame.width //This will use the extended functionality
lblAddress.frame.size.width //this will use the actual struct

internally the width extension on CGRect will always use the same
CGSize property from struct to give the width back and hence the same
size property is accessed in both case, but the difference is the first
one is standardized and hence only gives back positive values whereas
the second will give the negative values as well.
</code>```

Title: UILabel get Frame width or height

Body:
`lblAddress.frame.width`
`lblAddress.frame.size.width`

I have searched so many time but still i haven't point out...what is difference between lblAddress.frame.width AND  lblAddress.frame.size.width. it gives me same output..I don't know which one to use when?

please suggest some example so I can figure out whole thing.

Body:
To know more, you can look how CGRect structure is constructed.

struct CGRect {
  var origin: CGPoint
  var size: CGSize
}

and to add some extra functionality, an extension of CGRect is also provided by apple, like the following

extension CGRect {

    @available(iOS 2.0, *)
    public var height: CGFloat { get }

    @available(iOS 2.0, *)
    public var width: CGFloat { get }
}

Now to answer your question.
lblAddress.frame will return a CGRect

lblAddress.frame.width //This will use the extended functionality
lblAddress.frame.size.width //this will use the actual struct

internally the width extension on CGRect will always use the same
CGSize property from struct to give the width back and hence the same
size property is accessed in both case, but the difference is the first
one is standardized and hence only gives back positive values whereas
the second will give the negative values as well.