问:
Tensorflow Object Detection API with Mobilenets overfits custom multiclass dataset
The model overfits the training set and fails to generalise to test set.

How could I add dropout to the feature extractor part of the model? (the .config file only provides a key value to add dropout to the box predictor)

What other measures I could take to minimize overfitting?

More details below:

I am attempting to retrain the model checkpoint "ssd_mobilenet_v1_coco_11_06_2017" on a dataset of toy animals. There are 14 classes, with 400-600 images in each. The network learns the training set in less than 30k steps. Tensorboard. The loss seems to remain quite volatile still after initial training, although I am not experienced enough to assess that.

I am testing the model by applying the exported graph to images and inspecting the results manually. (I just haven't had time to implement validation properly). The model works very well on pictures taken in very similar conditions to those in the training set. These bad test set images are randomly set aside from the training set which was acquired by taking many images in succession with slight changes in camera angle. The training set also includes various lighting conditions, backgrounds, distortions and camera locations. I would estimate it gets the classes and locations right in roughly 95% of the images from the bad test set. From this I conclude that the model fits the training set very well and can generalise a little bit.

However, the model performs very poorly on pictures taken separately with a different camera at a different time (i.e. there should be much less correlation between this test set and the training set). I would estimate the performance in this good test set is roughly 25%. From this I conclude that the model is overfitting and failing to generalise.

I have tried making some changes in the .config file.

Increasing the l2_regularizer weight from 0.00004 to 0.0001 for both the feature extractor and box predictor.

Setting box predictor use_dropout to true in order to enable the 20% dropout.

I am using Tensorflow 1.4 pip install and models cloned from github from about 3 weeks ago.

I call the train.py in object_detection with the following arguments:

```<code>python train.py --logtostderr --train_dir=/home/X/TrainDir/Process --pipeline_config_path=/home/X/ssd_mobilenet_v1_coco.config
</code>```

My configuration file is the following:

```<code># SSD with Mobilenet v1 configuration for MSCOCO Dataset.
# Users should configure the fine_tune_checkpoint field in the train config as
# well as the label_map_path and input_path fields in the train_input_reader and
# eval_input_reader. Search for "PATH_TO_BE_CONFIGURED" to find the fields that
# should be configured.

model {
  ssd {
    num_classes: 14
    box_coder {
      faster_rcnn_box_coder {
        y_scale: 10.0
        x_scale: 10.0
        height_scale: 5.0
        width_scale: 5.0
      }
    }
    matcher {
      argmax_matcher {
        matched_threshold: 0.5
        unmatched_threshold: 0.5
        ignore_thresholds: false
        negatives_lower_than_unmatched: true
        force_match_for_each_row: true
      }
    }
    similarity_calculator {
      iou_similarity {
      }
    }
    anchor_generator {
      ssd_anchor_generator {
        num_layers: 6
        min_scale: 0.2
        max_scale: 0.95
        aspect_ratios: 1.0
        aspect_ratios: 2.0
        aspect_ratios: 0.5
        aspect_ratios: 3.0
        aspect_ratios: 0.3333
      }
    }
    image_resizer {
      fixed_shape_resizer {
        height: 300
        width: 300
      }
    }
    box_predictor {
      convolutional_box_predictor {
        min_depth: 0
        max_depth: 0
        num_layers_before_predictor: 0
        use_dropout: true
        dropout_keep_probability: 0.8
        kernel_size: 1
        box_code_size: 4
        apply_sigmoid_to_scores: false
        conv_hyperparams {
          activation: RELU_6,
          regularizer {
            l2_regularizer {
              weight: 0.0001
            }
          }
          initializer {
            truncated_normal_initializer {
              stddev: 0.03
              mean: 0.0
            }
          }
          batch_norm {
            train: true,
            scale: true,
            center: true,
            decay: 0.9997,
            epsilon: 0.001,
          }
        }
      }
    }
    feature_extractor {
      type: 'ssd_mobilenet_v1'
      min_depth: 16
      depth_multiplier: 1.0
      conv_hyperparams {
        activation: RELU_6,
        regularizer {
          l2_regularizer {
            weight: 0.0001
          }
        }
        initializer {
          truncated_normal_initializer {
            stddev: 0.03
            mean: 0.0
          }
        }
        batch_norm {
          train: true,
          scale: true,
          center: true,
          decay: 0.9997,
          epsilon: 0.001,
        }
      }
    }
    loss {
      classification_loss {
        weighted_sigmoid {
          anchorwise_output: true
        }
      }
      localization_loss {
        weighted_smooth_l1 {
          anchorwise_output: true
        }
      }
      hard_example_miner {
        num_hard_examples: 3000
        iou_threshold: 0.99
        loss_type: CLASSIFICATION
        max_negatives_per_positive: 3
        min_negatives_per_image: 0
      }
      classification_weight: 1.0
      localization_weight: 1.0
    }
    normalize_loss_by_num_matches: true
    post_processing {
      batch_non_max_suppression {
        score_threshold: 1e-8
        iou_threshold: 0.6
        max_detections_per_class: 100
        max_total_detections: 100
      }
      score_converter: SIGMOID
    }
  }
}

train_config: {
  batch_size: 8
  optimizer {
    rms_prop_optimizer: {
      learning_rate: {
        exponential_decay_learning_rate {
          initial_learning_rate: 0.004
          decay_steps: 800720
          decay_factor: 0.95
        }
      }
      momentum_optimizer_value: 0.9
      decay: 0.9
      epsilon: 1.0
    }
  }
  fine_tune_checkpoint: "/home/X/tensorflow/models/research/object_detection/ssd_mobilenet_v1_coco_11_06_2017/model.ckpt"
  from_detection_checkpoint: true
  # Note: The below line limits the training process to 200K steps, which we
  # empirically found to be sufficient enough to train the pets dataset. This
  # effectively bypasses the learning rate schedule (the learning rate will
  # never decay). Remove the below line to train indefinitely.
  num_steps: 200000
  data_augmentation_options {
    random_horizontal_flip {
    }
  }
  data_augmentation_options {
    ssd_random_crop {
    }
  }
}

train_input_reader: {
  tf_record_input_reader {
    input_path: "/home/X/TrainDir/train.record"
  }
  label_map_path: "/home/X/TrainDir/data_label_map.pbtxt"
}

eval_config: {
  num_examples: 1200
  # Note: The below line limits the evaluation process to 10 evaluations.
  # Remove the below line to evaluate indefinitely.
  max_evals: 30
}

eval_input_reader: {
  tf_record_input_reader {
    input_path: "/home/X/TrainDir/test.record"
  }
  label_map_path: "/home/X/TrainDir/data_label_map.pbtxt"
  shuffle: false
  num_readers: 1
  num_epochs: 1
}
</code>```

答:
Have you tried to set up a validation set and automatically run the evaluation in parallel to the training using the partially trained models? If the validation accuracy is not converging yet, then probably you just need to train your model longer.

Other things to look at: Are there any other differences between the "good" and "bad" test sets? E.g. resolution/aspect ratio. Are you correctly following all the pre-processing steps exactly the same way you are performing those during training? E.g. data standardization, resizing with the same algorithm, etc...

EDIT: I checked your tensorboard screenshot, why do you think the net learned your training set? It does not seem the loss really converged. One other thing you should definitely do is to set up a scheduler to reduce your learning dividing by 10 say every 40K steps, it is possible after learning some features your gradient descent has trouble converging as you never change the learning rate from the starting value and it might be too big for that point in time in the training.

Body:
The model overfits the training set and fails to generalise to test set.

How could I add dropout to the feature extractor part of the model? (the .config file only provides a key value to add dropout to the box predictor)

What other measures I could take to minimize overfitting?

More details below:

I am attempting to retrain the model checkpoint "ssd_mobilenet_v1_coco_11_06_2017" on a dataset of toy animals. There are 14 classes, with 400-600 images in each. The network learns the training set in less than 30k steps. Tensorboard. The loss seems to remain quite volatile still after initial training, although I am not experienced enough to assess that.

I am testing the model by applying the exported graph to images and inspecting the results manually. (I just haven't had time to implement validation properly). The model works very well on pictures taken in very similar conditions to those in the training set. These bad test set images are randomly set aside from the training set which was acquired by taking many images in succession with slight changes in camera angle. The training set also includes various lighting conditions, backgrounds, distortions and camera locations. I would estimate it gets the classes and locations right in roughly 95% of the images from the bad test set. From this I conclude that the model fits the training set very well and can generalise a little bit.

However, the model performs very poorly on pictures taken separately with a different camera at a different time (i.e. there should be much less correlation between this test set and the training set). I would estimate the performance in this good test set is roughly 25%. From this I conclude that the model is overfitting and failing to generalise.

I have tried making some changes in the .config file.

Increasing the l2_regularizer weight from 0.00004 to 0.0001 for both the feature extractor and box predictor.

Setting box predictor use_dropout to true in order to enable the 20% dropout.

I am using Tensorflow 1.4 pip install and models cloned from github from about 3 weeks ago.

I call the train.py in object_detection with the following arguments:

python train.py --logtostderr --train_dir=/home/X/TrainDir/Process --pipeline_config_path=/home/X/ssd_mobilenet_v1_coco.config

My configuration file is the following:

# SSD with Mobilenet v1 configuration for MSCOCO Dataset.
# Users should configure the fine_tune_checkpoint field in the train config as
# well as the label_map_path and input_path fields in the train_input_reader and
# eval_input_reader. Search for "PATH_TO_BE_CONFIGURED" to find the fields that
# should be configured.

model {
  ssd {
    num_classes: 14
    box_coder {
      faster_rcnn_box_coder {
        y_scale: 10.0
        x_scale: 10.0
        height_scale: 5.0
        width_scale: 5.0
      }
    }
    matcher {
      argmax_matcher {
        matched_threshold: 0.5
        unmatched_threshold: 0.5
        ignore_thresholds: false
        negatives_lower_than_unmatched: true
        force_match_for_each_row: true
      }
    }
    similarity_calculator {
      iou_similarity {
      }
    }
    anchor_generator {
      ssd_anchor_generator {
        num_layers: 6
        min_scale: 0.2
        max_scale: 0.95
        aspect_ratios: 1.0
        aspect_ratios: 2.0
        aspect_ratios: 0.5
        aspect_ratios: 3.0
        aspect_ratios: 0.3333
      }
    }
    image_resizer {
      fixed_shape_resizer {
        height: 300
        width: 300
      }
    }
    box_predictor {
      convolutional_box_predictor {
        min_depth: 0
        max_depth: 0
        num_layers_before_predictor: 0
        use_dropout: true
        dropout_keep_probability: 0.8
        kernel_size: 1
        box_code_size: 4
        apply_sigmoid_to_scores: false
        conv_hyperparams {
          activation: RELU_6,
          regularizer {
            l2_regularizer {
              weight: 0.0001
            }
          }
          initializer {
            truncated_normal_initializer {
              stddev: 0.03
              mean: 0.0
            }
          }
          batch_norm {
            train: true,
            scale: true,
            center: true,
            decay: 0.9997,
            epsilon: 0.001,
          }
        }
      }
    }
    feature_extractor {
      type: 'ssd_mobilenet_v1'
      min_depth: 16
      depth_multiplier: 1.0
      conv_hyperparams {
        activation: RELU_6,
        regularizer {
          l2_regularizer {
            weight: 0.0001
          }
        }
        initializer {
          truncated_normal_initializer {
            stddev: 0.03
            mean: 0.0
          }
        }
        batch_norm {
          train: true,
          scale: true,
          center: true,
          decay: 0.9997,
          epsilon: 0.001,
        }
      }
    }
    loss {
      classification_loss {
        weighted_sigmoid {
          anchorwise_output: true
        }
      }
      localization_loss {
        weighted_smooth_l1 {
          anchorwise_output: true
        }
      }
      hard_example_miner {
        num_hard_examples: 3000
        iou_threshold: 0.99
        loss_type: CLASSIFICATION
        max_negatives_per_positive: 3
        min_negatives_per_image: 0
      }
      classification_weight: 1.0
      localization_weight: 1.0
    }
    normalize_loss_by_num_matches: true
    post_processing {
      batch_non_max_suppression {
        score_threshold: 1e-8
        iou_threshold: 0.6
        max_detections_per_class: 100
        max_total_detections: 100
      }
      score_converter: SIGMOID
    }
  }
}

train_config: {
  batch_size: 8
  optimizer {
    rms_prop_optimizer: {
      learning_rate: {
        exponential_decay_learning_rate {
          initial_learning_rate: 0.004
          decay_steps: 800720
          decay_factor: 0.95
        }
      }
      momentum_optimizer_value: 0.9
      decay: 0.9
      epsilon: 1.0
    }
  }
  fine_tune_checkpoint: "/home/X/tensorflow/models/research/object_detection/ssd_mobilenet_v1_coco_11_06_2017/model.ckpt"
  from_detection_checkpoint: true
  # Note: The below line limits the training process to 200K steps, which we
  # empirically found to be sufficient enough to train the pets dataset. This
  # effectively bypasses the learning rate schedule (the learning rate will
  # never decay). Remove the below line to train indefinitely.
  num_steps: 200000
  data_augmentation_options {
    random_horizontal_flip {
    }
  }
  data_augmentation_options {
    ssd_random_crop {
    }
  }
}

train_input_reader: {
  tf_record_input_reader {
    input_path: "/home/X/TrainDir/train.record"
  }
  label_map_path: "/home/X/TrainDir/data_label_map.pbtxt"
}

eval_config: {
  num_examples: 1200
  # Note: The below line limits the evaluation process to 10 evaluations.
  # Remove the below line to evaluate indefinitely.
  max_evals: 30
}

eval_input_reader: {
  tf_record_input_reader {
    input_path: "/home/X/TrainDir/test.record"
  }
  label_map_path: "/home/X/TrainDir/data_label_map.pbtxt"
  shuffle: false
  num_readers: 1
  num_epochs: 1
}


来源: stackexchange

问:
Qt installer framework mac desktop alias
I have create some application installer for mac using Qt installer framework.

Application installed fine but I want to add some desktop shortcut (alias) for my app. There is a lot of instructions how create it by Finder, but no one how create it by Qt installer framework or SH script (for that created while installation). So my question.

Is it possible to create desktop shortcut (alias) on MAC by Qt installer framework or some SH script?

答:
It's very strange for my developer experience, but it real work. I have found answer here
How do I create a Macintosh Finder Alias From the Command Line?

this SH command real work.

```<code>osascript -e 'tell application "Finder" to make alias file to POSIX file "/file/to/make/link/from" at POSIX file "/folder/where/to/make/link"'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It's very strange for my developer experience, but it real work. I have found answer here
How do I create a Macintosh Finder Alias From the Command Line?

this SH command real work.

osascript -e 'tell application "Finder" to make alias file to POSIX file "/file/to/make/link/from" at POSIX file "/folder/where/to/make/link"'


问:
Pass $(this) to a function
I am trying to build a media playlist that can advance the credits, play the video and change the title on thumb-hover, end of video and on next/prev click. So I need to write some functions that can then be called together. So like this:

```<code>    function showBox()
    {
        $(this).parents('.container').find('.box').show();
    };

    function hideBox()
    {
        $(this).parents('.container').find('.box').hide();
    };

    $('a').hover(
        function()
        {
            showBox();
        },
        function()
        {
            hideBox();
        }
    );
</code>```

The problem is that $(this) does not carry through to the functions from the .hover. How do I do this?

答:
Per @patrickdw's answer, jQuery sets the scope of a callback for an event to the DOM element upon which the event was fired. For example, see the eventObject parameter in the documentation for the click() handler.

My original answer (below) is useful when you want to create a jQuery plug-in so that you may invoke your own custom methods on jQuery objects and have the jQuery object set as this during execution. However, it is not the correct and simple answer to the original question.

```<code>// Within a plug-in, `this` is already a jQuery object, not DOM reference
$.fn.showBox = function(){ this.parents('.container').find('.box').show(); };
$.fn.hideBox = function(){ this.parents('.container').find('.box').hide(); };
$('a').hover(
  function(){ $(this).showBox() },
  function(){ $(this).hideBox() }
);
</code>```

Edit: Or, if (as suggested) you want to add only one name to the ~global jQuery method namespace:

```<code>$.fn.myBox = function(cmd){
  this.closest('.container').find('.box')[cmd]();
};

$('a').hover(
  function(){ $(this).myBox('show') },
  function(){ $(this).myBox('hide') }
);
</code>```

Or more generally:

```<code>$.fn.myBox = function(cmd){
  switch(cmd){
    case 'foo':
      ...
    break;
    case 'bar':
      ...
    break;
  }
  return this;
};
</code>```

For more information, see the jQuery Plugin Authoring Guide.

ContentLicense: CC BY-SA 4.0

Title: Pass $(this) to a function

Body:
I am trying to build a media playlist that can advance the credits, play the video and change the title on thumb-hover, end of video and on next/prev click. So I need to write some functions that can then be called together. So like this:

    function showBox()
    {
        $(this).parents('.container').find('.box').show();
    };

    function hideBox()
    {
        $(this).parents('.container').find('.box').hide();
    };

    $('a').hover(
        function()
        {
            showBox();
        },
        function()
        {
            hideBox();
        }
    );

The problem is that $(this) does not carry through to the functions from the .hover. How do I do this?

Body:
Per @patrickdw's answer, jQuery sets the scope of a callback for an event to the DOM element upon which the event was fired. For example, see the eventObject parameter in the documentation for the click() handler.

My original answer (below) is useful when you want to create a jQuery plug-in so that you may invoke your own custom methods on jQuery objects and have the jQuery object set as this during execution. However, it is not the correct and simple answer to the original question.

// Within a plug-in, `this` is already a jQuery object, not DOM reference
$.fn.showBox = function(){ this.parents('.container').find('.box').show(); };
$.fn.hideBox = function(){ this.parents('.container').find('.box').hide(); };
$('a').hover(
  function(){ $(this).showBox() },
  function(){ $(this).hideBox() }
);

Edit: Or, if (as suggested) you want to add only one name to the ~global jQuery method namespace:

$.fn.myBox = function(cmd){
  this.closest('.container').find('.box')[cmd]();
};

$('a').hover(
  function(){ $(this).myBox('show') },
  function(){ $(this).myBox('hide') }
);

Or more generally:

$.fn.myBox = function(cmd){
  switch(cmd){
    case 'foo':
      ...
    break;
    case 'bar':
      ...
    break;
  }
  return this;
};

For more information, see the jQuery Plugin Authoring Guide.

ContentLicense: CC BY-SA 2.5


问:
Disable selection of future dates in multiple months datepicker jquery
So i have a multiple month datepicker, when i move to a new month/year I wish to have  all the other month dates disabled, still visible but not selectable. could anyone suggest an idea, thnks</p>

答:
Correct i was playing with beforeShowDay option ( http://jsfiddle.net/201bb1pr/ ),i.e.

```<code>$('input').datepicker({
numberOfMonths: 3,
beforeShowDay: function(date){
    var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
    return [ dates_array_of_new_month.indexOf(string) != -1 ]
}
</code>```

});
,but as far I understand i need to get all the dates of the new month , How do I get them

Body:
Correct i was playing with beforeShowDay option ( http://jsfiddle.net/201bb1pr/ ),i.e.

$('input').datepicker({
numberOfMonths: 3,
beforeShowDay: function(date){
    var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
    return [ dates_array_of_new_month.indexOf(string) != -1 ]
}

});
,but as far I understand i need to get all the dates of the new month , How do I get them


问:
How to find an element present in data-hook through selenium
I have the HTML code as:

```<code><a class="a-size-base a-link-normal review-title a-color-base a-text-bold" data-hook="review-title" href="/gp/customer-reviews/R252N8IFRXV8TW/ref=cm_cr_getr_d_rvw_ttl?ie=UTF8&ASIN=B071NZZHF9">Security concern</a>
</code>```

and i have to search the element by data-hook as the class name is common for other attributes also and href and link-text are dynamic as it is changing for the next element as there are multiple elements that i need to fetch.

Can i search it by data-hook. If yes could someone help me with it!

答:
As per the HTML you have shared to find the element through data-hook attribute you can use the following line of code :

```<code>driver.findElement(By.xpath("//a[@data-hook='review-title']"));
</code>```

Though you mentioned class name is common it will be a good practice to keep the class name attribute in the xpath as follows :

```<code>driver.findElement(By.xpath("//a[@class='a-size-base a-link-normal review-title a-color-base a-text-bold' and @data-hook='review-title']"));
</code>```

Further, though you mentioned href is changing, I will suggest to use the combination of all the three attributes to uniquely identify the element as :

```<code>driver.findElement(By.xpath("//a[@class='a-size-base a-link-normal review-title a-color-base a-text-bold' and contains(@href,'/gp/customer-reviews/') and @data-hook='review-title']"));
</code>```

Body:
I have the HTML code as:

Security concern

and i have to search the element by data-hook as the class name is common for other attributes also and href and link-text are dynamic as it is changing for the next element as there are multiple elements that i need to fetch.

Can i search it by data-hook. If yes could someone help me with it!

Body:
As per the HTML you have shared to find the element through data-hook attribute you can use the following line of code :

driver.findElement(By.xpath("//a[@data-hook='review-title']"));

Though you mentioned class name is common it will be a good practice to keep the class name attribute in the xpath as follows :

driver.findElement(By.xpath("//a[@class='a-size-base a-link-normal review-title a-color-base a-text-bold' and @data-hook='review-title']"));

Further, though you mentioned href is changing, I will suggest to use the combination of all the three attributes to uniquely identify the element as :

driver.findElement(By.xpath("//a[@class='a-size-base a-link-normal review-title a-color-base a-text-bold' and contains(@href,'/gp/customer-reviews/') and @data-hook='review-title']"));


问:
How to keep footer at the bottom of page under the body content
What I am trying to accomplish is to get the footer of all my pages underneath the content of the body. All pages will have different sizes of body content. The challenging bit for me is to keep only one CSS for all pages.

I tried my best showing the css and HTML here but no luck. Instead here is a the JSFiddle of my code: https://jsfiddle.net/zsrsd20m/

```<code> .container {
min-height:80%;
position:relative;
}

.titleText{
width:100%;
padding-top: 35px;
padding-bottom: 35px;
background-color: #127577;

color: white;
text-align: center;
}

.navBar{
 padding-right: 20px;
 float:left;
 }

.mainText{
 height:100%;
 padding-left:220px;
 padding-right:250px;
 padding-bottom:0px;
 font-size: 20px;
 text-align: justify;
}

.footerText{
 width:100%;
 padding-top: 35px;
 padding-top: 23px;
 background-color: #127577;
 color: white;
 text-align: center;
}
</code>```

.Container and all the other Divs made in HTML was made because of this: http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page

I want it so that even if the body content is too small the footer always stays at the bottom of the page. Same applies for if the body content is big. Currently when setting the height of the body content to 100% it shows me a scroll bar even when the content is small and doesnt need a scroll bar. When removing the height it makes the footer directly under the small body content which is half good but its not at the bottom of the page so it looks horrible.

Screenshots of the problems:
https://imgur.com/a/x16RC

答:
Wow - that link's old. We've got some better techniques available these days, namely flexbox.

/* The magic: */
.Site {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
}

.Site-content {
  flex: 1;
}

/* Stlyes to make the demo easier to see: */
body { margin: 0; }
header { background-color: #FDD; }
main { background-color: #DFD; }
footer { background-color: #DDF; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body class="Site">
  <header>Header</header>
  <main class="Site-content">Content</main>
  <footer>Footer</footer>
</body></code>```

You can read all about it right here

Body:
What I am trying to accomplish is to get the footer of all my pages underneath the content of the body. All pages will have different sizes of body content. The challenging bit for me is to keep only one CSS for all pages.

I tried my best showing the css and HTML here but no luck. Instead here is a the JSFiddle of my code: https://jsfiddle.net/zsrsd20m/

 .container {
min-height:80%;
position:relative;
}

.titleText{
width:100%;
padding-top: 35px;
padding-bottom: 35px;
background-color: #127577;

color: white;
text-align: center;
}

.navBar{
 padding-right: 20px;
 float:left;
 }

.mainText{
 height:100%;
 padding-left:220px;
 padding-right:250px;
 padding-bottom:0px;
 font-size: 20px;
 text-align: justify;
}

.footerText{
 width:100%;
 padding-top: 35px;
 padding-top: 23px;
 background-color: #127577;
 color: white;
 text-align: center;
}

.Container and all the other Divs made in HTML was made because of this: http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page

I want it so that even if the body content is too small the footer always stays at the bottom of the page. Same applies for if the body content is big. Currently when setting the height of the body content to 100% it shows me a scroll bar even when the content is small and doesnt need a scroll bar. When removing the height it makes the footer directly under the small body content which is half good but its not at the bottom of the page so it looks horrible.

Screenshots of the problems:
https://imgur.com/a/x16RC

Body:
Wow - that link's old. We've got some better techniques available these days, namely flexbox.

/* The magic: */
.Site {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
}

.Site-content {
  flex: 1;
}

/* Stlyes to make the demo easier to see: */
body { margin: 0; }
header { background-color: #FDD; }
main { background-color: #DFD; }
footer { background-color: #DDF; }

<body class="Site">
  <header>Header</header>
  <main class="Site-content">Content</main>
  <footer>Footer</footer>
</body>

You can read all about it right here


问:
error pagination in codeigniter 3
My pagination is work fine, but it's show error when wanting to raise data over existing data
For example, show/index/5 or show/index/10 works fine and the data is right. But if I go to show/index/120 it shows error

```<code>   Invalid argument supplied for foreach()
</code>```

Here's my controller

```<code>   public function index(){
       $config['base_url']=base_url()."book/show/index";
       $config['total_rows']= $this->book_model->get_book();
       $config['per_page']=5;
       $config['num_links'] = 5;
       $config['uri_segment']=4;
       $config['full_tag_open'] = "<ul class='pagination'>";
       $config['full_tag_close'] ="</ul>";
       $config['num_tag_open'] = '<li>';
       $config['num_tag_close'] = '</li>';
       $config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";

       $config['first_link']='< Pertama ';
       $config['last_link']='Terakhir > ';
       $config['next_link']='> ';
       $config['prev_link']='< ';
       $this->pagination->initialize($config);

       $this->load->model('admin/book_model');
       $data['book']=$this->book_model->count_book($config);
       $this->load->view('admin/book', $data);
  }
</code>```

答:
In your view you have to apply a check in your code </p>

```<code>if(!empty($result)&& isset($result)){
     foreach($results as $data){
                    ----your code--
                     }
</code>```

Title: error pagination in codeigniter 3

Body:
My pagination is work fine, but it's show error when wanting to raise data over existing data
For example, show/index/5 or show/index/10 works fine and the data is right. But if I go to show/index/120 it shows error

   Invalid argument supplied for foreach()

Here's my controller

   public function index(){
       $config['base_url']=base_url()."book/show/index";
       $config['total_rows']= $this->book_model->get_book();
       $config['per_page']=5;
       $config['num_links'] = 5;
       $config['uri_segment']=4;
       $config['full_tag_open'] = "
";
       $config['full_tag_close'] ="
";
       $config['num_tag_open'] = '
';
       $config['num_tag_close'] = '
';
       $config['cur_tag_open'] = "

";

       $config['first_link']='< Pertama ';
       $config['last_link']='Terakhir > ';
       $config['next_link']='> ';
       $config['prev_link']='< ';
       $this->pagination->initialize($config);

       $this->load->model('admin/book_model');
       $data['book']=$this->book_model->count_book($config);
       $this->load->view('admin/book', $data);
  }

Body:
In your view you have to apply a check in your code

if(!empty($result)&& isset($result)){
     foreach($results as $data){
                    ----your code--
                     }


问:
Passing a String variable into a UIImage constructor does not return a UIImage?
I'm having trouble wrapping my head around this issue.

Currently in my Assets folder I have the following decline bench.png image:

In my code, I have a String variable equipmentName set somewhere else.

I set my UIImageView image like so:

```<code>equipmentImageView.image = UIImage(named: equipmentName)
</code>```

However, the image is never returned.

I checked to see if the image can actually be returned:

```<code>if let image = UIImage(named: equipmentName)
{
    print("GOOD")
}
else
{
    print("BAD")
}
</code>```

This prints out BAD.

However if I replaced equipmentName with the actual string name, it returns the correct image, and outputs GOOD:

```<code>if let image = UIImage(named: "decline bench")
{
    print("GOOD")
}
else
{
    print("BAD")
}
</code>```

What gives?

They are both the same thing, the type is a String so why does passing it the variable equipmentName of type String not work, but passing in a literal string work?

The variable equipmentName also contains the string decline bench before equipmentImageView.image is set.

Does it have anything to do with the naming of the image in the Assets folder?

Please help me understand. Thanks!

MORE INFO:
In my code, equipmentName is actually stored with upper-case first letters like so Decline Bench.

When I set the image, I am actually doing:

```<code>equipmentImageView.image = UIImage(named: equipmentName.lowercased())
</code>```

equipmentName.lowercased() still returns a String, which does not work.

However, doing the following does work:

```<code>equipmentName = "decline bench"
equipmentImageView.image = UIImage(named: equipmentName)
</code>```

What is the difference here that I am not doing correctly?

UPDATE: The following print out produces:

print(Data(equipmentName.utf8) as NSData): <4465636c 696e6520 42656e63 680a2020 20202020 20202020 2020>

print(Data(equipmentName.lowercased().utf8) as NSData): <6465636c 696e6520 62656e63 680a2020 20202020 20202020 2020>

答:
You said equipmentName = "Decline Bench", It's wrong, your asset named decline bench without the uppercase, just change it to lowercase then it work.

It have to have the correct case, D and d are different character

Body:
I'm having trouble wrapping my head around this issue.

Currently in my Assets folder I have the following decline bench.png image:

In my code, I have a String variable equipmentName set somewhere else.

I set my UIImageView image like so:

equipmentImageView.image = UIImage(named: equipmentName)

However, the image is never returned.

I checked to see if the image can actually be returned:

if let image = UIImage(named: equipmentName)
{
    print("GOOD")
}
else
{
    print("BAD")
}

This prints out BAD.

However if I replaced equipmentName with the actual string name, it returns the correct image, and outputs GOOD:

if let image = UIImage(named: "decline bench")
{
    print("GOOD")
}
else
{
    print("BAD")
}

What gives?

They are both the same thing, the type is a String so why does passing it the variable equipmentName of type String not work, but passing in a literal string work?

The variable equipmentName also contains the string decline bench before equipmentImageView.image is set.

Does it have anything to do with the naming of the image in the Assets folder?

Please help me understand. Thanks!

MORE INFO:
In my code, equipmentName is actually stored with upper-case first letters like so Decline Bench.

When I set the image, I am actually doing:

equipmentImageView.image = UIImage(named: equipmentName.lowercased())

equipmentName.lowercased() still returns a String, which does not work.

However, doing the following does work:

equipmentName = "decline bench"
equipmentImageView.image = UIImage(named: equipmentName)

What is the difference here that I am not doing correctly?

UPDATE: The following print out produces:

print(Data(equipmentName.utf8) as NSData): <4465636c 696e6520 42656e63 680a2020 20202020 20202020 2020>

print(Data(equipmentName.lowercased().utf8) as NSData): <6465636c 696e6520 62656e63 680a2020 20202020 20202020 2020>


答:
You need to modify your code to something like this:</p>

```<code>function showBox(elem)
{
    elem.parents('.container').find('.box').show();
};

function hideBox(elem)
{
    elem.parents('.container').find('.box').hide();
};

$('a').hover(
    function()
    {
        var $this = $(this);

        showBox($this);
    },
    function()
    {
        var $this = $(this);

        hideBox($this);
    }
);
</code>```

Title: Pass $(this) to a function

Body:
You need to modify your code to something like this:

function showBox(elem)
{
    elem.parents('.container').find('.box').show();
};

function hideBox(elem)
{
    elem.parents('.container').find('.box').hide();
};

$('a').hover(
    function()
    {
        var $this = $(this);

        showBox($this);
    },
    function()
    {
        var $this = $(this);

        hideBox($this);
    }
);


问:
Web login using python3 requests
I am trying to web scrape the a piece of news. I try to login into the website by python so that I can have full access to the whole web page. But I have looked at so many tutorials but still fail.
Here is the code. Can anyone tell me why.
There is no bug in my code. But I still can not see the full text, which means I am still not log in.

`

```<code>url='https://id.wsj.com/access/pages/wsj/us/signin.html?mg=id-wsj&mg=id-wsj'
payload={'username':'my_user_name',
         'password':'******'}
session=requests.Session()
session.get(url)
response=session.post(url,data=payload)
print(response.cookies)
r=requests.get('https://www.wsj.com/articles/companies-push-to-repeal-amt-after-senates-last-minute-move-to-keep-it-alive-1512435711')
print(r.text)
`
</code>```

答: Try sending your last GET request using the response variable. After all, it's the one who made the login and holds the cookies (if there are any). You've used a new requests object for your last request thus ignoring the login you just made.

Title: Web login using python3 requests

Body:
I am trying to web scrape the a piece of news. I try to login into the website by python so that I can have full access to the whole web page. But I have looked at so many tutorials but still fail.
Here is the code. Can anyone tell me why.
There is no bug in my code. But I still can not see the full text, which means I am still not log in.

`

url='https://id.wsj.com/access/pages/wsj/us/signin.html?mg=id-wsj&mg=id-wsj'
payload={'username':'my_user_name',
         'password':'******'}
session=requests.Session()
session.get(url)
response=session.post(url,data=payload)
print(response.cookies)
r=requests.get('https://www.wsj.com/articles/companies-push-to-repeal-amt-after-senates-last-minute-move-to-keep-it-alive-1512435711')
print(r.text)
`


问:
Array indexing appear twice how to solve it?
I have array values which will contains same array indexing for both the multidimenasional array. Both the results are from a svg result values which i have converted svg simplexmlelement object to array. Please check with my below code and advise on this. How to built re-indexing with 0,1,2 and so on

```<code>print '```';
    print_r(array_values(array($svg_array_values)));

Array
(
    [0] => Array
        (
            [@attributes] => Array
                (
                    [id] => Layer_1
                    [data-name] => Layer 1
                    [viewBox] => 0 0 72 72
                    [width] => 234
                    [height] => 170
                    [preserveAspectRatio] => none
                )

            [defs] => Array
                (
                    [style] => .cls-1{fill-rule:evenodd;}
                )

            [title] => Arrow 20
            [path] => Array
                (
                    [@attributes] => Array
                        (
                            [class] => cls-1
                            [d] => M70.47,34.06,48.11,11.7a2.75,2.75,0,0,0-4.69,1.94l1.72,11.93h-34a10.43,10.43,0,0,0,0,20.86h34L43.42,58.37a2.76,2.76,0,0,0,2.75,2.74,2.77,2.77,0,0,0,1.94-.8L70.47,37.94a2.73,2.73,0,0,0,0-3.88Z
                            [fill] => #000000
                        )

                )

        )

)
Array
(
    [0] => Array
        (
            [@attributes] => Array
                (
                    [id] => Layer_1
                    [data-name] => Layer 1
                    [viewBox] => 0 0 72 72
                    [width] => 160
                    [height] => 99
                    [preserveAspectRatio] => none
                )

            [defs] => Array
                (
                    [style] => .cls-1{fill-rule:evenodd;}
                )

            [title] => Arrow 18
            [polygon] => Array
                (
                    [@attributes] => Array
                        (
                            [class] => cls-1
                            [points] => 71.28 36 55.49 20.21 55.49 31.19 0.72 31.19 0.72 40.81 55.49 40.81 55.49 51.79 71.28 36 71.28 36
                        )

                )

        )

)
```

<p>Ouput should be</p>

```Array
(
    [0] => Array
        (
            [@attributes] => Array
                (
                    [id] => Layer_1
                    [data-name] => Layer 1
                    [viewBox] => 0 0 72 72
                    [width] => 234
                    [height] => 170
                    [preserveAspectRatio] => none
                )

            [defs] => Array
                (
                    [style] => .cls-1{fill-rule:evenodd;}
                )

            [title] => Arrow 20
            [path] => Array
                (
                    [@attributes] => Array
                        (
                            [class] => cls-1
                            [d] => M70.47,34.06,48.11,11.7a2.75,2.75,0,0,0-4.69,1.94l1.72,11.93h-34a10.43,10.43,0,0,0,0,20.86h34L43.42,58.37a2.76,2.76,0,0,0,2.75,2.74,2.77,2.77,0,0,0,1.94-.8L70.47,37.94a2.73,2.73,0,0,0,0-3.88Z
                            [fill] => #000000
                        )

                )

        )

)
Array
(
    [1] => Array
        (
            [@attributes] => Array
                (
                    [id] => Layer_1
                    [data-name] => Layer 1
                    [viewBox] => 0 0 72 72
                    [width] => 160
                    [height] => 99
                    [preserveAspectRatio] => none
                )

            [defs] => Array
                (
                    [style] => .cls-1{fill-rule:evenodd;}
                )

            [title] => Arrow 18
            [polygon] => Array
                (
                    [@attributes] => Array
                        (
                            [class] => cls-1
                            [points] => 71.28 36 55.49 20.21 55.49 31.19 0.72 31.19 0.72 40.81 55.49 40.81 55.49 51.79 71.28 36 71.28 36
                        )

                )

        )

)
```

答:
You used array_values() function this function remove the same value iteration. so do not use this function if you want to accepted output. simply you can add foreach loop and check with array_key_exist(). like this : </p>

```<code>$a=array("Volvo"=>"XC90","BMW"=>"X5");
if (array_key_exists("Volvo",$a))
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }
</code>```

Body:
I have array values which will contains same array indexing for both the multidimenasional array. Both the results are from a svg result values which i have converted svg simplexmlelement object to array. Please check with my below code and advise on this. How to built re-indexing with 0,1,2 and so on

print '
';
    print_r(array_values(array($svg_array_values)));

Array
(
    [0] => Array
        (
            [@attributes] => Array
                (
                    [id] => Layer_1
                    [data-name] => Layer 1
                    [viewBox] => 0 0 72 72
                    [width] => 234
                    [height] => 170
                    [preserveAspectRatio] => none
                )

            [defs] => Array
                (
                    [style] => .cls-1{fill-rule:evenodd;}
                )

            [title] => Arrow 20
            [path] => Array
                (
                    [@attributes] => Array
                        (
                            [class] => cls-1
                            [d] => M70.47,34.06,48.11,11.7a2.75,2.75,0,0,0-4.69,1.94l1.72,11.93h-34a10.43,10.43,0,0,0,0,20.86h34L43.42,58.37a2.76,2.76,0,0,0,2.75,2.74,2.77,2.77,0,0,0,1.94-.8L70.47,37.94a2.73,2.73,0,0,0,0-3.88Z
                            [fill] => #000000
                        )

                )

        )

)
Array
(
    [0] => Array
        (
            [@attributes] => Array
                (
                    [id] => Layer_1
                    [data-name] => Layer 1
                    [viewBox] => 0 0 72 72
                    [width] => 160
                    [height] => 99
                    [preserveAspectRatio] => none
                )

            [defs] => Array
                (
                    [style] => .cls-1{fill-rule:evenodd;}
                )

            [title] => Arrow 18
            [polygon] => Array
                (
                    [@attributes] => Array
                        (
                            [class] => cls-1
                            [points] => 71.28 36 55.49 20.21 55.49 31.19 0.72 31.19 0.72 40.81 55.49 40.81 55.49 51.79 71.28 36 71.28 36
                        )

                )

        )

)

Ouput should be

Array
(
    [0] => Array
        (
            [@attributes] => Array
                (
                    [id] => Layer_1
                    [data-name] => Layer 1
                    [viewBox] => 0 0 72 72
                    [width] => 234
                    [height] => 170
                    [preserveAspectRatio] => none
                )

            [defs] => Array
                (
                    [style] => .cls-1{fill-rule:evenodd;}
                )

            [title] => Arrow 20
            [path] => Array
                (
                    [@attributes] => Array
                        (
                            [class] => cls-1
                            [d] => M70.47,34.06,48.11,11.7a2.75,2.75,0,0,0-4.69,1.94l1.72,11.93h-34a10.43,10.43,0,0,0,0,20.86h34L43.42,58.37a2.76,2.76,0,0,0,2.75,2.74,2.77,2.77,0,0,0,1.94-.8L70.47,37.94a2.73,2.73,0,0,0,0-3.88Z
                            [fill] => #000000
                        )

                )

        )

)
Array
(
    [1] => Array
        (
            [@attributes] => Array
                (
                    [id] => Layer_1
                    [data-name] => Layer 1
                    [viewBox] => 0 0 72 72
                    [width] => 160
                    [height] => 99
                    [preserveAspectRatio] => none
                )

            [defs] => Array
                (
                    [style] => .cls-1{fill-rule:evenodd;}
                )

            [title] => Arrow 18
            [polygon] => Array
                (
                    [@attributes] => Array
                        (
                            [class] => cls-1
                            [points] => 71.28 36 55.49 20.21 55.49 31.19 0.72 31.19 0.72 40.81 55.49 40.81 55.49 51.79 71.28 36 71.28 36
                        )

                )

        )

)

Body:
You used array_values() function this function remove the same value iteration. so do not use this function if you want to accepted output. simply you can add foreach loop and check with array_key_exist(). like this :

$a=array("Volvo"=>"XC90","BMW"=>"X5");
if (array_key_exists("Volvo",$a))
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }


问:
How to delete all files in parent folder with same file name as in a specified subfolder?
I am new to batch file writing.

This is the current content of parent folder Folder1:

```<code>C:\Folder1\Subfolder1
C:\Folder1\Afile001.txt
C:\Folder1\Bfile002.txt
C:\Folder1\Cfile003.txt
C:\Folder1\Xfile004.txt
C:\Folder1\Yfile005.txt
</code>```

The number of files increases from time to time in this folder.

I need the current list of files from Folder1 and then copy them to Subfolder1 which is achieved by using command copy *.txt Subfolder1.

Next the files in Subfolder1 are taken (or copied) by some process and then contents of parent Folder1 changes to:

```<code>C:\Folder1\Subfolder1
C:\Folder1\Afile001.txt
C:\Folder1\Bfile002.txt
C:\Folder1\Cfile003.txt
C:\Folder1\Xfile004.txt
C:\Folder1\Yfile005.txt
C:\Folder1\Dfile001.txt
C:\Folder1\Efile002.txt
C:\Folder1\Ffile003.txt
C:\Folder1\Gfile004.txt
C:\Folder1\Hfile005.txt
</code>```

How can I achieve a batch file which takes the list of files from Subfolder1 and use that list to delete the files with same name from Folder1 and leaves behind only the new files in that folder?

So the result should be for Folder1:

```<code>C:\Folder1\Subfolder1
C:\Folder1\Dfile001.txt
C:\Folder1\Efile002.txt
C:\Folder1\Ffile003.txt
C:\Folder1\Gfile004.txt
C:\Folder1\Hfile005.txt
</code>```

答:
That can be done with just a single command line using the commands FOR and DEL:

```<code>@echo off
for %%I in ("C:\Folder1\Subfolder1\*.txt") do del "C:\Folder1\%%~nxI" 2>nul
</code>```

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

del /?

echo /?

for /?

Read also the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul to suppress the error message output by DEL to handle STDERR with redirection to device NUL in case of a *.txt file in C:\Folder1\Subfolder1 does not exist anymore in C:\Folder1.

By the way: It would be also possible to use the command

```<code>move /Y C:\Folder1\*.txt C:\Folder1\Subfolder1\
</code>```

to move the files from C:\Folder1 to C:\Folder1\Subfolder1 instead of copying them first and later deleting them.

Body:
I am new to batch file writing.

This is the current content of parent folder Folder1:

C:\Folder1\Subfolder1
C:\Folder1\Afile001.txt
C:\Folder1\Bfile002.txt
C:\Folder1\Cfile003.txt
C:\Folder1\Xfile004.txt
C:\Folder1\Yfile005.txt

The number of files increases from time to time in this folder.

I need the current list of files from Folder1 and then copy them to Subfolder1 which is achieved by using command copy *.txt Subfolder1.

Next the files in Subfolder1 are taken (or copied) by some process and then contents of parent Folder1 changes to:

C:\Folder1\Subfolder1
C:\Folder1\Afile001.txt
C:\Folder1\Bfile002.txt
C:\Folder1\Cfile003.txt
C:\Folder1\Xfile004.txt
C:\Folder1\Yfile005.txt
C:\Folder1\Dfile001.txt
C:\Folder1\Efile002.txt
C:\Folder1\Ffile003.txt
C:\Folder1\Gfile004.txt
C:\Folder1\Hfile005.txt

How can I achieve a batch file which takes the list of files from Subfolder1 and use that list to delete the files with same name from Folder1 and leaves behind only the new files in that folder?

So the result should be for Folder1:

C:\Folder1\Subfolder1
C:\Folder1\Dfile001.txt
C:\Folder1\Efile002.txt
C:\Folder1\Ffile003.txt
C:\Folder1\Gfile004.txt
C:\Folder1\Hfile005.txt

Body:
That can be done with just a single command line using the commands FOR and DEL:

@echo off
for %%I in ("C:\Folder1\Subfolder1\*.txt") do del "C:\Folder1\%%~nxI" 2>nul

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

del /?

echo /?

for /?

Read also the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul to suppress the error message output by DEL to handle STDERR with redirection to device NUL in case of a *.txt file in C:\Folder1\Subfolder1 does not exist anymore in C:\Folder1.

By the way: It would be also possible to use the command

move /Y C:\Folder1\*.txt C:\Folder1\Subfolder1\

to move the files from C:\Folder1 to C:\Folder1\Subfolder1 instead of copying them first and later deleting them.


问:
p5 understanding an function parameter
in an example given on the p5 Site a parameter (I think that's the correct term) is used 'function(other)' which I can't quite understand. I appreciate you will need the full code which is available from the above link. Anyone care to explain would be much appreciated. </p>

```<code>Particle.prototype.display = function(other) {
  stroke(0, this.lifespan);
  fill(0, this.lifespan/2);
  ellipse(this.position.x,this.position.y, 8, 8);
  // If we need to draw a line
  if (other) {
    line(this.position.x, this.position.y, other.position.x, other.position.y);
  }
}
</code>```

答:
A function can take a parameter. The parameter is writen in the brackets. In this example the paramether is other. In the example above. "other" is another object. E.g. Particle.prototype.display(someobject);

I hope this is somewhat understandable.

var div = document.getElementById("test");

test(true);
test(false);

function test(parameter){
  if(parameter){
    div.innerHTML += "Hello"
    }else{
    div.innerHTML += " World!"
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test"></div></code>```

Title: p5 understanding an function parameter

Body:
in an example given on the p5 Site a parameter (I think that's the correct term) is used 'function(other)' which I can't quite understand. I appreciate you will need the full code which is available from the above link. Anyone care to explain would be much appreciated.

Particle.prototype.display = function(other) {
  stroke(0, this.lifespan);
  fill(0, this.lifespan/2);
  ellipse(this.position.x,this.position.y, 8, 8);
  // If we need to draw a line
  if (other) {
    line(this.position.x, this.position.y, other.position.x, other.position.y);
  }
}

Body:
A function can take a parameter. The parameter is writen in the brackets. In this example the paramether is other. In the example above. "other" is another object. E.g. Particle.prototype.display(someobject);

I hope this is somewhat understandable.

var div = document.getElementById("test");

test(true);
test(false);

function test(parameter){
  if(parameter){
    div.innerHTML += "Hello"
    }else{
    div.innerHTML += " World!"
    }
}

<div id="test"></div>


答: Add parameters to showBox and hideBox so that they can accept the element, and then call showBox($(this)) and hideBox($(this)).

Title: Pass $(this) to a function

Body:
I am trying to build a media playlist that can advance the credits, play the video and change the title on thumb-hover, end of video and on next/prev click. So I need to write some functions that can then be called together. So like this:

    function showBox()
    {
        $(this).parents('.container').find('.box').show();
    };

    function hideBox()
    {
        $(this).parents('.container').find('.box').hide();
    };

    $('a').hover(
        function()
        {
            showBox();
        },
        function()
        {
            hideBox();
        }
    );

The problem is that $(this) does not carry through to the functions from the .hover. How do I do this?


问:
using $emit to pass a function from child to parent in angularJS
I want to send the result of a function to a parent controller from a child.

Here is my file structure

```<code>-submission.controller.js
--calculate.controller.js
</code>```

In calculate.controller.js i have a function that looks like:

```<code>function validForm() {
  var checkForm = false;
  if(files === true) {
    checkForm = true;
  }
  return checkForm;
}
</code>```

and i want to send the results of this function to the parent (submission.controller.js) and use it as an argument in a function.

```<code>showValidZip() {
  if (validForm() === true) {
    return false;
  }
  return true;
};
</code>```

So far i've tried to use $emit and $on to send validForm from calculate to submission but havent had much luck in doing so.

for example:

```<code>$scope.$emit('validForm', function () {
  var checkForm = false;
  if(files === true) {
    checkForm = true;
  }
  return checkForm;
});
</code>```

and

```<code>$scope.showValidZip = function () {
  if ($scope.$on('validForm') === true) {
    return false;
  }
  return true;
};
</code>```

but it's not really working as intended.

答:
'Emit' from child.

```<code>$scope.$emit('validForm', function () {
var checkForm = false;
if(files === true) {
checkForm = true;
}
return checkForm;
});
</code>```

Now Receive.

```<code>$scope.showValidZip = function () {
$scope.$on('validForm'), function(event, data) {
  if(data === true)
  return false;
});
return true;
};
</code>```

Body:
I want to send the result of a function to a parent controller from a child.

Here is my file structure

-submission.controller.js
--calculate.controller.js

In calculate.controller.js i have a function that looks like:

function validForm() {
  var checkForm = false;
  if(files === true) {
    checkForm = true;
  }
  return checkForm;
}

and i want to send the results of this function to the parent (submission.controller.js) and use it as an argument in a function.

showValidZip() {
  if (validForm() === true) {
    return false;
  }
  return true;
};

So far i've tried to use $emit and $on to send validForm from calculate to submission but havent had much luck in doing so.

for example:

$scope.$emit('validForm', function () {
  var checkForm = false;
  if(files === true) {
    checkForm = true;
  }
  return checkForm;
});

and

$scope.showValidZip = function () {
  if ($scope.$on('validForm') === true) {
    return false;
  }
  return true;
};

but it's not really working as intended.

Body:
'Emit' from child.

$scope.$emit('validForm', function () {
var checkForm = false;
if(files === true) {
checkForm = true;
}
return checkForm;
});

Now Receive.

$scope.showValidZip = function () {
$scope.$on('validForm'), function(event, data) {
  if(data === true)
  return false;
});
return true;
};


问:
How do I properly perform multiprocessing from PyQt?
I create a button and try to run multiprocessing when I click button ,

but the UI is become blocked . I hope process run in backgorund .

How can I fix it ?

```<code>from PySide2 import QtCore,QtGui,QtWidgets
import sys
import multiprocessing
from threading import Timer
class TTT(multiprocessing.Process):
    def __init__(self):
        super(TTT, self).__init__()
        self.daemon = True
    def run(self):
        while True:
            t = Timer(5, self.doSomething)
            t.start()
            t.join()

    def doSomething(self):
        try:
            print('123')
        except Exception as e:
            print(e)

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        btn = QtWidgets.QPushButton('run process')
        btn.clicked.connect(self.create_process)
        self.setCentralWidget(btn)

    def create_process(self):
        QtWidgets.QMessageBox.information(self,'hhh','hhh')
        t = TTT()
        t.start()
        t.join()

if __name__=="__main__":
    app=QtWidgets.QApplication(sys.argv)
    ex = MainWindow()
    ex.show()
    sys.exit(app.exec_())
</code>```

答:
Bendegúz Szatmári already answer the main question.

I just want to let you know that use Process is not best idea in most of usage.
Different process does not share memory with your program. You can not control them so easily as different thread.

Here is simple example how you can Start end Stop different thread.

```<code>from PyQt5 import QtWidgets
from PyQt5.QtCore import *
import sys
import time

class TTT(QThread):
    def __init__(self):
        super(TTT, self).__init__()
        self.quit_flag = False

    def run(self):
        while True:
            if not self.quit_flag:
                self.doSomething()
                time.sleep(1)
            else:
                break

        self.quit()
        self.wait()

    def doSomething(self):
        print('123')

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.btn = QtWidgets.QPushButton('run process')
        self.btn.clicked.connect(self.create_process)
        self.setCentralWidget(self.btn)

    def create_process(self):
        if self.btn.text() == "run process":
            print("Started")
            self.btn.setText("stop process")
            self.t = TTT()
            self.t.start()
        else:
            self.t.quit_flag = True
            print("Stop sent")
            self.t.wait()
            print("Stopped")
            self.btn.setText("run process")

if __name__=="__main__":
    app=QtWidgets.QApplication(sys.argv)
    ex = MainWindow()
    ex.show()
    sys.exit(app.exec_())
</code>```

Body:
I create a button and try to run multiprocessing when I click button ,

but the UI is become blocked . I hope process run in backgorund .

How can I fix it ?

from PySide2 import QtCore,QtGui,QtWidgets
import sys
import multiprocessing
from threading import Timer
class TTT(multiprocessing.Process):
    def __init__(self):
        super(TTT, self).__init__()
        self.daemon = True
    def run(self):
        while True:
            t = Timer(5, self.doSomething)
            t.start()
            t.join()

    def doSomething(self):
        try:
            print('123')
        except Exception as e:
            print(e)

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        btn = QtWidgets.QPushButton('run process')
        btn.clicked.connect(self.create_process)
        self.setCentralWidget(btn)

    def create_process(self):
        QtWidgets.QMessageBox.information(self,'hhh','hhh')
        t = TTT()
        t.start()
        t.join()

if __name__=="__main__":
    app=QtWidgets.QApplication(sys.argv)
    ex = MainWindow()
    ex.show()
    sys.exit(app.exec_())

Body:
Bendegúz Szatmári already answer the main question.

I just want to let you know that use Process is not best idea in most of usage.
Different process does not share memory with your program. You can not control them so easily as different thread.

Here is simple example how you can Start end Stop different thread.

from PyQt5 import QtWidgets
from PyQt5.QtCore import *
import sys
import time

class TTT(QThread):
    def __init__(self):
        super(TTT, self).__init__()
        self.quit_flag = False

    def run(self):
        while True:
            if not self.quit_flag:
                self.doSomething()
                time.sleep(1)
            else:
                break

        self.quit()
        self.wait()

    def doSomething(self):
        print('123')

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.btn = QtWidgets.QPushButton('run process')
        self.btn.clicked.connect(self.create_process)
        self.setCentralWidget(self.btn)

    def create_process(self):
        if self.btn.text() == "run process":
            print("Started")
            self.btn.setText("stop process")
            self.t = TTT()
            self.t.start()
        else:
            self.t.quit_flag = True
            print("Stop sent")
            self.t.wait()
            print("Stopped")
            self.btn.setText("run process")

if __name__=="__main__":
    app=QtWidgets.QApplication(sys.argv)
    ex = MainWindow()
    ex.show()
    sys.exit(app.exec_())


问:
Formatting javadoc in Enums
I'm looking for a way to set up code formatting to keep javadoc in enums in separate blocks. Right now wrapping of enum members works as intended, but for some reason javadoc comments start/end on the same line as the members
I'd keep getting this:

```<code>public enum FormatTest {
    FOO, /**
    * some description
    */BAR, BAZ;
}
</code>```

but I want it to look something like this:

```<code>public enum FormatTest {
    FOO,
    /**
     * docs either like this
     */
    BAR,
    /** or like this */
    BAZ;
}
</code>```

It works perfectly well for class members strangely enough...

答:
try changing the Code Style settings.

In IntelliJ, go to: Settings -> Code Style -> Java -> Wrapping and Braces tab.

Scroll down untill you see Enum constants, and change the value to: Wrap always.

See screenshot

Title: Formatting javadoc in Enums

Body:
I'm looking for a way to set up code formatting to keep javadoc in enums in separate blocks. Right now wrapping of enum members works as intended, but for some reason javadoc comments start/end on the same line as the members
I'd keep getting this:

public enum FormatTest {
    FOO, /**
    * some description
    */BAR, BAZ;
}

but I want it to look something like this:

public enum FormatTest {
    FOO,
    /**
     * docs either like this
     */
    BAR,
    /** or like this */
    BAZ;
}

It works perfectly well for class members strangely enough...


问:
Casting and the resulting consequence [Java]
What does using the casting word "(SuperClass)" do in the main method below?
  Does this change the object type?</p>

```<code>class SuperClass{
  public void method(){
    System.out.print("SuperClass");
  }
}

class Sub extends SuperClass{
  public void method(){
    System.out.print("SubClass");
  }
}

public class SubSub extends Sub{
  public static void main(String args[]){
    ((SuperClass)new SubSub()).method();
  }
  public void method(){
    System.out.print("SubsubClass");
  }
}
</code>```

答:
Casting does not change the object type. It simply tells the compiler to treat the object in a different manner. That is, it changes the object reference.

Here, although the object reference is SuperClass , the object is still an object of SubSub  class, so the method() of SubSub   class will be called. This is also called run time polymorphism. That is, using reference of parent class to point to an object of its child class.

Body:
What does using the casting word "(SuperClass)" do in the main method below?
  Does this change the object type?

class SuperClass{
  public void method(){
    System.out.print("SuperClass");
  }
}

class Sub extends SuperClass{
  public void method(){
    System.out.print("SubClass");
  }
}

public class SubSub extends Sub{
  public static void main(String args[]){
    ((SuperClass)new SubSub()).method();
  }
  public void method(){
    System.out.print("SubsubClass");
  }
}


答:
Use sticky footer CSS https://css-tricks.com/couple-takes-sticky-footer/</p>

```<code><body>
  <div class="content">
    <div class="content-inside">
      content
    </div>
  </div>
  <footer class="footer"></footer>
</body>

html, body {
  height: 100%;
  margin: 0;
}
.content {
  min-height: 100%;
}
.content-inside {
  padding: 20px;
  padding-bottom: 50px;
}
.footer {
  height: 50px;
  margin-top: -50px;
}
</code>```

Title: How to keep footer at the bottom of page under the body content

Body:
What I am trying to accomplish is to get the footer of all my pages underneath the content of the body. All pages will have different sizes of body content. The challenging bit for me is to keep only one CSS for all pages.

I tried my best showing the css and HTML here but no luck. Instead here is a the JSFiddle of my code: https://jsfiddle.net/zsrsd20m/

 .container {
min-height:80%;
position:relative;
}

.titleText{
width:100%;
padding-top: 35px;
padding-bottom: 35px;
background-color: #127577;

color: white;
text-align: center;
}

.navBar{
 padding-right: 20px;
 float:left;
 }

.mainText{
 height:100%;
 padding-left:220px;
 padding-right:250px;
 padding-bottom:0px;
 font-size: 20px;
 text-align: justify;
}

.footerText{
 width:100%;
 padding-top: 35px;
 padding-top: 23px;
 background-color: #127577;
 color: white;
 text-align: center;
}

.Container and all the other Divs made in HTML was made because of this: http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page

I want it so that even if the body content is too small the footer always stays at the bottom of the page. Same applies for if the body content is big. Currently when setting the height of the body content to 100% it shows me a scroll bar even when the content is small and doesnt need a scroll bar. When removing the height it makes the footer directly under the small body content which is half good but its not at the bottom of the page so it looks horrible.

Screenshots of the problems:
https://imgur.com/a/x16RC

Body:
Use sticky footer CSS https://css-tricks.com/couple-takes-sticky-footer/

<body>
  <div class="content">
    <div class="content-inside">
      content
    </div>
  </div>
  <footer class="footer"></footer>
</body>

html, body {
  height: 100%;
  margin: 0;
}
.content {
  min-height: 100%;
}
.content-inside {
  padding: 20px;
  padding-bottom: 50px;
}
.footer {
  height: 50px;
  margin-top: -50px;
}


问:
Importing data from excelsheet file into the mysql database C#
I have the following lines of code:

```<code>     protected void btnUpload_Click(object sender, EventArgs e)
{

        MySqlTransaction transaction;

        string ex_id = "";

        string file_name = Path.GetFileName(FileUpload1.FileName);
        string Excel_path = Server.MapPath("~/Excel/" + file_name);
    DataTable dtExceldata = new DataTable();//just added
    FileUpload1.SaveAs(Excel_path);

        OleDbConnection my_con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False");
    my_con.Open();
    OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", my_con);
        da.Fill(dtExceldata);
    if (dtExceldata.Rows.Count > 0)
    {
        //foreach (DataRow row in dtExceldata.Rows)
            for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)

        {

                string ex_dir = dtExceldata.Rows[i]["website_a"].ToString();
                //string ex_dir = row["website_a"].ToString();

                string ex_email = dtExceldata.Rows[i]["email_id"].ToString();
                // string ex_email = row["email_id"].ToString();

                string ex_email1 = dtExceldata.Rows[i]["email_id2"].ToString();
                //string ex_email1 = row["email_id2"].ToString();

                string ex_email2 = dtExceldata.Rows[i]["email_id3"].ToString();
                //string ex_email2 = row["email_id3"].ToString();

                string ex_company = dtExceldata.Rows[i]["company"].ToString();
                //string ex_company = row["company"].ToString();

                string ex_contact = dtExceldata.Rows[i]["contact_name"].ToString();
                //string ex_contact = row["contact_name"].ToString();

                string ex_proposal = dtExceldata.Rows[i]["proposal_status"].ToString();
                // string ex_proposal = row["proposal_status"].ToString();

                string ex_reason = dtExceldata.Rows[i]["reason"].ToString();
                //string ex_reason = row["reason"].ToString();

        int chk = 0;
            int type = 0;
            int dup = 0;
            int dir = 0;

            if (ddlwebsites.SelectedIndex != 0)
            {
                dir = Convert.ToInt32(ddlwebsites.SelectedValue);
                if (dir == 8)
                {
                    type = 1;
                }

            }

            foreach (ListItem lstAssign in ddlevents.Items)
            {
                if (lstAssign.Selected == true)
                {
                    chk = 1;
                }
            }

            if (type == 1 && chk == 0)
            {
                evyerror.Text = "Please Select the Event!!";
                return;

            }

            else
            {
                string querycomp = "", compID = "";
                querycomp = "Select * from barter_company where website like '%' '" + ex_dir + "' '%'";
                string connStr = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
                connect = new MySqlConnection(connStr);
                connect.Open();
                transaction = connect.BeginTransaction();
                try
                {
                    ClassDtBaseConnect clsDtResult = new ClassDtBaseConnect();
                    DataTable dt = clsDtResult.GetDataTable(querycomp);
                    if (dt.Rows.Count > 0)
                    {
                        compID = dt.Rows[0]["comp_id"].ToString();
                        ViewState["comp_id"] = compID;
                        if (type == 1)
                        {
                            dup = checkforDuplicates(Convert.ToInt32(compID));
                            if (dup == 1)
                            {
                                //Confirm_MP.Show();
                                // ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "confirmation();", true);
                            }

                        }
                        //return;
                    }
                    else
                    {

                        string queryStr = "insert into barter_company (comp_name,website) values(?comp,?website)";
                        MySqlCommand cmd = new MySqlCommand(queryStr, connect, transaction);
                        cmd.Parameters.AddWithValue("?comp", ex_company);
                        cmd.Parameters.AddWithValue("?website", ex_dir);
                        cmd.ExecuteNonQuery();
                        cmd.CommandText = "Select LAST_INSERT_ID()";
                        compID = cmd.ExecuteScalar().ToString();
                        transaction.Commit();
                        connect.Close();

                    }
                }
                catch
                {
                    transaction.Rollback();
                }

                if (dup == 0)
                {
                    // create a connection string with your sql database
                    string connStr1 = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
                    connect = new MySqlConnection(connStr1);
                    connect.Open();
                    DateTime date = new DateTime();
                    date = DateTime.ParseExact(txtsentdate.Text, "MM/dd/yyyy", null);
                    string SentDateString = date.ToString("yyyy/MM/dd");
                    //DateTime date = new DateTime();
                    //if (!string.IsNullOrEmpty(ex_date))
                    // {
                    //DateTime date = new DateTime();//added by chetan
                    //ex_date = ex_date.Split(' ')[0];//added by chetan
                    //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);//added by chetan
                    //string SentDateString = date.ToString("yyyy/MM/dd");//added by chetan
                    //DateTime SentDate = Convert.ToDateTime(SentDateString).Date;//added by chetan
                    //// DateTime date = DateTime.Parse(ex_date);//added by chetan

                    // }
                    //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);//added by chetan
                    //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
                    // string SentDateString = date.ToString("yyyy/MM/dd");
                    transaction = connect.BeginTransaction();
                    try
                    {

                        string ex_uid = Session["session_barterUser_id"].ToString();

                        MySqlCommand cmd = new MySqlCommand("insert into barter_proposals(user_id, sent_date, website_a, email_id, email_id2, email_id3, company, contact_name, proposal_status, reason,type) values(?uid,?sentdate,?dir,?email,?email2,?email3,?comp,?cont_name,?pro_status,?reason,?type)", connect);

                        cmd.Parameters.AddWithValue("?uid", ex_uid);
                        cmd.Parameters.AddWithValue("?comp", compID);

                        cmd.Parameters.AddWithValue("?sentdate", SentDateString);
                        // command.Parameters.AddWithValue("?event", eventname);
                        cmd.Parameters.AddWithValue("?dir", dir);
                        // command.Parameters.AddWithValue("?bar_type", ddlbartertype.SelectedValue);
                        // command.Parameters.AddWithValue("?website_b", txtwebsite.Text);
                        //cmd.Parameters.AddWithValue("?comp", ex_company);
                        cmd.Parameters.AddWithValue("?cont_name", ex_contact);
                        cmd.Parameters.AddWithValue("?email", ex_email);
                        cmd.Parameters.AddWithValue("?email2", ex_email1);
                        cmd.Parameters.AddWithValue("?email3", ex_email2);
                        cmd.Parameters.AddWithValue("?pro_status", ex_proposal);
                        cmd.Parameters.AddWithValue("?reason", ex_reason);
                        cmd.Parameters.AddWithValue("?type", type);
                        // command.Parameters.AddWithValue("?type", type);

                        cmd.ExecuteNonQuery();
                        if (type == 1)
                        {

                            cmd.CommandText = "Select LAST_INSERT_ID()";
                            Int64 CurrentProId = Convert.ToInt64(cmd.ExecuteScalar());
                            int eventAssignID;
                            string QueryInqEventAssign = "insert into barter_propeventassign(prop_id,event_id) values(?pro_id,?event_id)";

                            foreach (ListItem lstAssign in ddlevents.Items)
                            {
                                if (lstAssign.Selected == true)
                                {
                                    cmd = new MySqlCommand(QueryInqEventAssign, connect, transaction);
                                    cmd.Parameters.AddWithValue("?pro_id", CurrentProId);
                                    eventAssignID = Convert.ToInt32(lstAssign.Value);
                                    cmd.Parameters.AddWithValue("?event_id", eventAssignID);
                                    cmd.ExecuteNonQuery();

                                }
                            }

                        }//end of if
                        transaction.Commit();
                        connect.Close();
                        Response.Write("<script type=\"text/javascript\">alert('Proposal Added Successfully!!!');</script>");
                    }//end of try
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        Response.Write("<script>alert('There is an Error Ocurred:" + Server.HtmlEncode(ex.Message) + "')</script>");
                    }
                    finally
                    {
                        connect.Close();

                    }

                }//ifdupzero
            }//else
        }//for//foreach
      }//while //if

   // dr.Close();//commented by chetan

    my_con.Close();
    if (System.IO.File.Exists(Excel_path))
    {
        System.IO.File.Delete(Excel_path);
    }

}
</code>```

suppose there are 2 entries in the excelsheet file.When trying to import,it is inserting those 2 rows entries into the database table.but the problem is that, the reader does not stop its execution.After reading 2 rows entry,it is reading 3rd row which is blank.i have used dr.close and it keeps on reading the rows entries which is blank.

答:
Instead of checking if there are rows left (dr.Read()) as your loop condition, you could check if the first cell of the row is blank (dr[0].ToString() != String.Empty)

```<code>string file_name = Path.GetFileName(FileUpload1.FileName);
            string Excel_path = Server.MapPath("~/Excel/" + file_name);
            FileUpload1.SaveAs(Excel_path);

            OleDbConnection my_con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False");

            my_con.Open();
            OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", my_con);
            OleDbDataReader dr = command.ExecuteReader();
            dr.Read();
            while (dr[0].ToString() != String.Empty)
            {
            ex_id = dr[0].ToString();
            string ex_uid = dr[1].ToString();
            //get second row data and assign it ex_name variable
            string ex_date = dr[2].ToString();
            //get thirdt row data and assign it ex_name variable

            string ex_dir = dr[3].ToString();

            //get first row data and assign it ex_location variable
            string ex_email = dr[4].ToString();
            string ex_email1 = dr[5].ToString();
            string ex_email2 = dr[6].ToString();
            //string ex_company = dr[7].ToString();
            string ex_company = dr[7].ToString();
            string ex_contact = dr[8].ToString();
            string ex_proposal = dr[9].ToString();
            string ex_reason = dr[10].ToString();
               ...............
               //Insert operation
               ...............
            dr.Read();
            }
            dr.close();
            my_con.close();
</code>```

The premise of course is, that the first column is always filled if the rest of the row isn't blank.
If that isn't the case you can also check other columns in the loop condition.

Body:
I have the following lines of code:

     protected void btnUpload_Click(object sender, EventArgs e)
{

        MySqlTransaction transaction;

        string ex_id = "";

        string file_name = Path.GetFileName(FileUpload1.FileName);
        string Excel_path = Server.MapPath("~/Excel/" + file_name);
    DataTable dtExceldata = new DataTable();//just added
    FileUpload1.SaveAs(Excel_path);

        OleDbConnection my_con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False");
    my_con.Open();
    OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", my_con);
        da.Fill(dtExceldata);
    if (dtExceldata.Rows.Count > 0)
    {
        //foreach (DataRow row in dtExceldata.Rows)
            for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)

        {

                string ex_dir = dtExceldata.Rows[i]["website_a"].ToString();
                //string ex_dir = row["website_a"].ToString();

                string ex_email = dtExceldata.Rows[i]["email_id"].ToString();
                // string ex_email = row["email_id"].ToString();

                string ex_email1 = dtExceldata.Rows[i]["email_id2"].ToString();
                //string ex_email1 = row["email_id2"].ToString();

                string ex_email2 = dtExceldata.Rows[i]["email_id3"].ToString();
                //string ex_email2 = row["email_id3"].ToString();

                string ex_company = dtExceldata.Rows[i]["company"].ToString();
                //string ex_company = row["company"].ToString();

                string ex_contact = dtExceldata.Rows[i]["contact_name"].ToString();
                //string ex_contact = row["contact_name"].ToString();

                string ex_proposal = dtExceldata.Rows[i]["proposal_status"].ToString();
                // string ex_proposal = row["proposal_status"].ToString();

                string ex_reason = dtExceldata.Rows[i]["reason"].ToString();
                //string ex_reason = row["reason"].ToString();

        int chk = 0;
            int type = 0;
            int dup = 0;
            int dir = 0;

            if (ddlwebsites.SelectedIndex != 0)
            {
                dir = Convert.ToInt32(ddlwebsites.SelectedValue);
                if (dir == 8)
                {
                    type = 1;
                }

            }

            foreach (ListItem lstAssign in ddlevents.Items)
            {
                if (lstAssign.Selected == true)
                {
                    chk = 1;
                }
            }

            if (type == 1 && chk == 0)
            {
                evyerror.Text = "Please Select the Event!!";
                return;

            }

            else
            {
                string querycomp = "", compID = "";
                querycomp = "Select * from barter_company where website like '%' '" + ex_dir + "' '%'";
                string connStr = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
                connect = new MySqlConnection(connStr);
                connect.Open();
                transaction = connect.BeginTransaction();
                try
                {
                    ClassDtBaseConnect clsDtResult = new ClassDtBaseConnect();
                    DataTable dt = clsDtResult.GetDataTable(querycomp);
                    if (dt.Rows.Count > 0)
                    {
                        compID = dt.Rows[0]["comp_id"].ToString();
                        ViewState["comp_id"] = compID;
                        if (type == 1)
                        {
                            dup = checkforDuplicates(Convert.ToInt32(compID));
                            if (dup == 1)
                            {
                                //Confirm_MP.Show();
                                // ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "confirmation();", true);
                            }

                        }
                        //return;
                    }
                    else
                    {

                        string queryStr = "insert into barter_company (comp_name,website) values(?comp,?website)";
                        MySqlCommand cmd = new MySqlCommand(queryStr, connect, transaction);
                        cmd.Parameters.AddWithValue("?comp", ex_company);
                        cmd.Parameters.AddWithValue("?website", ex_dir);
                        cmd.ExecuteNonQuery();
                        cmd.CommandText = "Select LAST_INSERT_ID()";
                        compID = cmd.ExecuteScalar().ToString();
                        transaction.Commit();
                        connect.Close();

                    }
                }
                catch
                {
                    transaction.Rollback();
                }

                if (dup == 0)
                {
                    // create a connection string with your sql database
                    string connStr1 = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
                    connect = new MySqlConnection(connStr1);
                    connect.Open();
                    DateTime date = new DateTime();
                    date = DateTime.ParseExact(txtsentdate.Text, "MM/dd/yyyy", null);
                    string SentDateString = date.ToString("yyyy/MM/dd");
                    //DateTime date = new DateTime();
                    //if (!string.IsNullOrEmpty(ex_date))
                    // {
                    //DateTime date = new DateTime();//added by chetan
                    //ex_date = ex_date.Split(' ')[0];//added by chetan
                    //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);//added by chetan
                    //string SentDateString = date.ToString("yyyy/MM/dd");//added by chetan
                    //DateTime SentDate = Convert.ToDateTime(SentDateString).Date;//added by chetan
                    //// DateTime date = DateTime.Parse(ex_date);//added by chetan

                    // }
                    //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);//added by chetan
                    //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
                    // string SentDateString = date.ToString("yyyy/MM/dd");
                    transaction = connect.BeginTransaction();
                    try
                    {

                        string ex_uid = Session["session_barterUser_id"].ToString();

                        MySqlCommand cmd = new MySqlCommand("insert into barter_proposals(user_id, sent_date, website_a, email_id, email_id2, email_id3, company, contact_name, proposal_status, reason,type) values(?uid,?sentdate,?dir,?email,?email2,?email3,?comp,?cont_name,?pro_status,?reason,?type)", connect);

                        cmd.Parameters.AddWithValue("?uid", ex_uid);
                        cmd.Parameters.AddWithValue("?comp", compID);

                        cmd.Parameters.AddWithValue("?sentdate", SentDateString);
                        // command.Parameters.AddWithValue("?event", eventname);
                        cmd.Parameters.AddWithValue("?dir", dir);
                        // command.Parameters.AddWithValue("?bar_type", ddlbartertype.SelectedValue);
                        // command.Parameters.AddWithValue("?website_b", txtwebsite.Text);
                        //cmd.Parameters.AddWithValue("?comp", ex_company);
                        cmd.Parameters.AddWithValue("?cont_name", ex_contact);
                        cmd.Parameters.AddWithValue("?email", ex_email);
                        cmd.Parameters.AddWithValue("?email2", ex_email1);
                        cmd.Parameters.AddWithValue("?email3", ex_email2);
                        cmd.Parameters.AddWithValue("?pro_status", ex_proposal);
                        cmd.Parameters.AddWithValue("?reason", ex_reason);
                        cmd.Parameters.AddWithValue("?type", type);
                        // command.Parameters.AddWithValue("?type", type);

                        cmd.ExecuteNonQuery();
                        if (type == 1)
                        {

                            cmd.CommandText = "Select LAST_INSERT_ID()";
                            Int64 CurrentProId = Convert.ToInt64(cmd.ExecuteScalar());
                            int eventAssignID;
                            string QueryInqEventAssign = "insert into barter_propeventassign(prop_id,event_id) values(?pro_id,?event_id)";

                            foreach (ListItem lstAssign in ddlevents.Items)
                            {
                                if (lstAssign.Selected == true)
                                {
                                    cmd = new MySqlCommand(QueryInqEventAssign, connect, transaction);
                                    cmd.Parameters.AddWithValue("?pro_id", CurrentProId);
                                    eventAssignID = Convert.ToInt32(lstAssign.Value);
                                    cmd.Parameters.AddWithValue("?event_id", eventAssignID);
                                    cmd.ExecuteNonQuery();

                                }
                            }

                        }//end of if
                        transaction.Commit();
                        connect.Close();
                        Response.Write("");
                    }//end of try
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        Response.Write("");
                    }
                    finally
                    {
                        connect.Close();

                    }

                }//ifdupzero
            }//else
        }//for//foreach
      }//while //if

   // dr.Close();//commented by chetan

    my_con.Close();
    if (System.IO.File.Exists(Excel_path))
    {
        System.IO.File.Delete(Excel_path);
    }

}

suppose there are 2 entries in the excelsheet file.When trying to import,it is inserting those 2 rows entries into the database table.but the problem is that, the reader does not stop its execution.After reading 2 rows entry,it is reading 3rd row which is blank.i have used dr.close and it keeps on reading the rows entries which is blank.

Body:
Instead of checking if there are rows left (dr.Read()) as your loop condition, you could check if the first cell of the row is blank (dr[0].ToString() != String.Empty)

string file_name = Path.GetFileName(FileUpload1.FileName);
            string Excel_path = Server.MapPath("~/Excel/" + file_name);
            FileUpload1.SaveAs(Excel_path);

            OleDbConnection my_con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False");

            my_con.Open();
            OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", my_con);
            OleDbDataReader dr = command.ExecuteReader();
            dr.Read();
            while (dr[0].ToString() != String.Empty)
            {
            ex_id = dr[0].ToString();
            string ex_uid = dr[1].ToString();
            //get second row data and assign it ex_name variable
            string ex_date = dr[2].ToString();
            //get thirdt row data and assign it ex_name variable

            string ex_dir = dr[3].ToString();

            //get first row data and assign it ex_location variable
            string ex_email = dr[4].ToString();
            string ex_email1 = dr[5].ToString();
            string ex_email2 = dr[6].ToString();
            //string ex_company = dr[7].ToString();
            string ex_company = dr[7].ToString();
            string ex_contact = dr[8].ToString();
            string ex_proposal = dr[9].ToString();
            string ex_reason = dr[10].ToString();
               ...............
               //Insert operation
               ...............
            dr.Read();
            }
            dr.close();
            my_con.close();

The premise of course is, that the first column is always filled if the rest of the row isn't blank.
If that isn't the case you can also check other columns in the loop condition.


问:
Are sim cards supporting Java Card available, and if so where can I get them?
Are sim cards supporting Java Card available, and if so where can I get them?</p>

答:
Quite vague question... e.g. What you want to do with that smartcard?
I mean, the smartcard from my phone supports javacard and was brought from a common mobile phone store.

If you've got a smart idea about some javacard applet that you want to develop then look at this links: http://developer.gemalto.com/home/faq/simagine-contest.html and http://developer.gemalto.com/nc/download/dev-tools.html. That's simulation.

I think you'll never find smartcards to buy with 3GPP SIM/USIM/ISIM applications and javacard VM on them and necessary parameters/keys to use them in network and for javacard application loading except if you're working in a smartcard manufacturer or mobile operator company.


问:
Distinct query in Mongo
I have a document (name, firstName, age).

This command gives me the different names of the document:

```<code>db.getCollection('persons').distinct("name")
</code>```

How do I do to get the corresponding firstNames?

Thanks!

答:
You could try an aggregation query which groups the name and firstName. Eventually you could also add a count to it to see which combinations are repeated (but that is not necessary).

Here is an example:

```<code>db.test1.aggregate(
    [
        {
            $group: {_id: {name: "$name", firstName: "$firstName"}, count: {$sum: 1}}
        }
    ]
)
</code>```

Here is another another option to show an aggregated list:

```<code>db.test1.aggregate(
    [
        {
            $group: {_id: {name: "$name"}, firstName: { $push: "$firstName" }}
        }
    ]
)
</code>```

Title: Distinct query in Mongo

Body:
I have a document (name, firstName, age).

This command gives me the different names of the document:

db.getCollection('persons').distinct("name")

How do I do to get the corresponding firstNames?

Thanks!

Body:
You could try an aggregation query which groups the name and firstName. Eventually you could also add a count to it to see which combinations are repeated (but that is not necessary).

Here is an example:

db.test1.aggregate(
    [
        {
            $group: {_id: {name: "$name", firstName: "$firstName"}, count: {$sum: 1}}
        }
    ]
)

Here is another another option to show an aggregated list:

db.test1.aggregate(
    [
        {
            $group: {_id: {name: "$name"}, firstName: { $push: "$firstName" }}
        }
    ]
)