问:
How to make the training using Tensorflow 2 Object Detection API deterministic i.e. achieve Reproducibility?
I am using TF2 Object Detection API to train a ssd_resnet50. Each time I train it I get different losses and evaluation scores (tensorboard logs -- graphs).

I am using VOC2012 dataset to retrain a pretrained ssd_resnet50_v1_fpn_640x640_coco17_tpu-8 model. I have religiously followed the API setup using this link: https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/training.html.

Organised my workspace/training files

Prepared/annotated image datasets

Generate tf records from such datasets

Configured a simple training pipeline

Trained a model and monitored its progress

Everything is working just fine except for the reproducibility. In order to train a customized model I am using the configurations mentioned below (pipeline.config).

```<code>model {
  ssd {
    num_classes: 20 # Set this to the number of different label classes
    image_resizer {
      fixed_shape_resizer {
        height: 640
        width: 640
      }
    }
    feature_extractor {
      type: "ssd_resnet50_v1_fpn_keras"
      depth_multiplier: 1.0
      min_depth: 16
      conv_hyperparams {
        regularizer {
          l2_regularizer {
            weight: 0.00039999998989515007
          }
        }
        initializer {
          truncated_normal_initializer {
            mean: 0.0
            stddev: 0.029999999329447746
          }
        }
        activation: RELU_6
        batch_norm {
          decay: 0.996999979019165
          scale: true
          epsilon: 0.0010000000474974513
        }
      }
      override_base_feature_extractor_hyperparams: true
      fpn {
        min_level: 3
        max_level: 7
      }
    }
    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
        use_matmul_gather: true
      }
    }
    similarity_calculator {
      iou_similarity {
      }
    }
    box_predictor {
      weight_shared_convolutional_box_predictor {
        conv_hyperparams {
          regularizer {
            l2_regularizer {
              weight: 0.00039999998989515007
            }
          }
          initializer {
            random_normal_initializer {
              mean: 0.0
              stddev: 0.009999999776482582
            }
          }
          activation: RELU_6
          batch_norm {
            decay: 0.996999979019165
            scale: true
            epsilon: 0.0010000000474974513
          }
        }
        depth: 256
        num_layers_before_predictor: 4
        kernel_size: 3
        class_prediction_bias_init: -4.599999904632568
      }
    }
    anchor_generator {
      multiscale_anchor_generator {
        min_level: 3
        max_level: 7
        anchor_scale: 4.0
        aspect_ratios: 1.0
        aspect_ratios: 2.0
        aspect_ratios: 0.5
        scales_per_octave: 2
      }
    }
    post_processing {
      batch_non_max_suppression {
        score_threshold: 9.99999993922529e-09
        iou_threshold: 0.6000000238418579
        max_detections_per_class: 100
        max_total_detections: 100
        use_static_shapes: false
      }
      score_converter: SIGMOID
    }
    normalize_loss_by_num_matches: true
    loss {
      localization_loss {
        weighted_smooth_l1 {
        }
      }
      classification_loss {
        weighted_sigmoid_focal {
          gamma: 2.0
          alpha: 0.25
        }
      }
      classification_weight: 1.0
      localization_weight: 1.0
    }
    encode_background_as_zeros: true
    normalize_loc_loss_by_codesize: true
    inplace_batchnorm_update: true
    freeze_batchnorm: false
  }
}
train_config {
  batch_size: 8 # Increase/Decrease this value depending on the available memory (Higher values require more memory and vice-versa)
  data_augmentation_options {
    random_horizontal_flip {
    }
  }
  data_augmentation_options {
    random_crop_image {
      min_object_covered: 0.0
      min_aspect_ratio: 0.75
      max_aspect_ratio: 3.0
      min_area: 0.75
      max_area: 1.0
      overlap_thresh: 0.0
    }
  }
  sync_replicas: true
  optimizer {
    momentum_optimizer {
      learning_rate {
        cosine_decay_learning_rate {
          learning_rate_base: 0.03999999910593033
          total_steps: 25000
          warmup_learning_rate: 0.013333000242710114
          warmup_steps: 2000
        }
      }
      momentum_optimizer_value: 0.8999999761581421
    }
    use_moving_average: false
  }
  fine_tune_checkpoint: "pre-trained-models/ssd_resnet50_v1_fpn_640x640_coco17_tpu-8/checkpoint/ckpt-0" # Path to checkpoint of pre-trained model
  num_steps: 25000
  startup_delay_steps: 0.0
  replicas_to_aggregate: 8
  max_number_of_boxes: 100
  unpad_groundtruth_tensors: false
  fine_tune_checkpoint_type: "detection" # Set this to "detection" since we want to be training the full detection model
  use_bfloat16: false # Set this to false if you are not training on a TPU
  fine_tune_checkpoint_version: V2
}
train_input_reader {
  label_map_path: "annotations/label_map.pbtxt" # Path to label map file
  tf_record_input_reader {
    input_path: "annotations/train.record" # Path to training TFRecord file
  }
}
eval_config {
  metrics_set: "coco_detection_metrics"
  use_moving_averages: false
}
eval_input_reader {
  label_map_path: "annotations/label_map.pbtxt" # Path to label map file
  shuffle: false
  num_epochs: 1
  tf_record_input_reader {
    input_path: "annotations/test.record" # Path to testing TFRecord
  }
}
</code>```

I tried a few things to achieve reproducibility:

Set a global seed in various modules across the training pipeline

I tried setting up the operation-based seed for say shuffle, data augmentations etc.

Manually setting attributes coming from .proto files, like shuffle = False in build() function of Tensorflow/models/research/object_detection/builders/data_builder.py module
etc.

De-selecting or removing data_augmentation_options from pipeline.config file altogether.

The graphs above show 2 separate training runs (everything is kept the same in both experiments: global seeding is done in data_builder.py -- tf.random.set_seed(1234), no data augmentation selected i.e. "data_augmentation_options" removed from pipeline.config, data shuffle and related attributes adjusted as mentioned in point 3)

```<code># Operations that rely on a random seed actually derive it from two seeds:
# the global and operation-level seeds. Adding this on top of a module sets the global seed.
tf.random.set_seed(1234)
# Switch off shuffle, config.filenames_shuffle_buffer_size
config.shuffle = False
# Make number of readers to zero
config.num_readers = 0
# Set sample_from_datasets_weights to zero
config.sample_from_datasets_weights = 0
</code>```

答:
You might try to set the Python Hash Seed, at least for some this did the job
See

https://keras.io/getting_started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development
or

https://github.com/keras-team/keras/issues/2280#issuecomment-411542012

Another thing that might help is to try a different optimizer. Some optimizers - like Adam - have an internal random initilization.

Body:
I am using TF2 Object Detection API to train a ssd_resnet50. Each time I train it I get different losses and evaluation scores (tensorboard logs -- graphs).

I am using VOC2012 dataset to retrain a pretrained ssd_resnet50_v1_fpn_640x640_coco17_tpu-8 model. I have religiously followed the API setup using this link: https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/training.html.

Organised my workspace/training files

Prepared/annotated image datasets

Generate tf records from such datasets

Configured a simple training pipeline

Trained a model and monitored its progress

Everything is working just fine except for the reproducibility. In order to train a customized model I am using the configurations mentioned below (pipeline.config).

model {
  ssd {
    num_classes: 20 # Set this to the number of different label classes
    image_resizer {
      fixed_shape_resizer {
        height: 640
        width: 640
      }
    }
    feature_extractor {
      type: "ssd_resnet50_v1_fpn_keras"
      depth_multiplier: 1.0
      min_depth: 16
      conv_hyperparams {
        regularizer {
          l2_regularizer {
            weight: 0.00039999998989515007
          }
        }
        initializer {
          truncated_normal_initializer {
            mean: 0.0
            stddev: 0.029999999329447746
          }
        }
        activation: RELU_6
        batch_norm {
          decay: 0.996999979019165
          scale: true
          epsilon: 0.0010000000474974513
        }
      }
      override_base_feature_extractor_hyperparams: true
      fpn {
        min_level: 3
        max_level: 7
      }
    }
    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
        use_matmul_gather: true
      }
    }
    similarity_calculator {
      iou_similarity {
      }
    }
    box_predictor {
      weight_shared_convolutional_box_predictor {
        conv_hyperparams {
          regularizer {
            l2_regularizer {
              weight: 0.00039999998989515007
            }
          }
          initializer {
            random_normal_initializer {
              mean: 0.0
              stddev: 0.009999999776482582
            }
          }
          activation: RELU_6
          batch_norm {
            decay: 0.996999979019165
            scale: true
            epsilon: 0.0010000000474974513
          }
        }
        depth: 256
        num_layers_before_predictor: 4
        kernel_size: 3
        class_prediction_bias_init: -4.599999904632568
      }
    }
    anchor_generator {
      multiscale_anchor_generator {
        min_level: 3
        max_level: 7
        anchor_scale: 4.0
        aspect_ratios: 1.0
        aspect_ratios: 2.0
        aspect_ratios: 0.5
        scales_per_octave: 2
      }
    }
    post_processing {
      batch_non_max_suppression {
        score_threshold: 9.99999993922529e-09
        iou_threshold: 0.6000000238418579
        max_detections_per_class: 100
        max_total_detections: 100
        use_static_shapes: false
      }
      score_converter: SIGMOID
    }
    normalize_loss_by_num_matches: true
    loss {
      localization_loss {
        weighted_smooth_l1 {
        }
      }
      classification_loss {
        weighted_sigmoid_focal {
          gamma: 2.0
          alpha: 0.25
        }
      }
      classification_weight: 1.0
      localization_weight: 1.0
    }
    encode_background_as_zeros: true
    normalize_loc_loss_by_codesize: true
    inplace_batchnorm_update: true
    freeze_batchnorm: false
  }
}
train_config {
  batch_size: 8 # Increase/Decrease this value depending on the available memory (Higher values require more memory and vice-versa)
  data_augmentation_options {
    random_horizontal_flip {
    }
  }
  data_augmentation_options {
    random_crop_image {
      min_object_covered: 0.0
      min_aspect_ratio: 0.75
      max_aspect_ratio: 3.0
      min_area: 0.75
      max_area: 1.0
      overlap_thresh: 0.0
    }
  }
  sync_replicas: true
  optimizer {
    momentum_optimizer {
      learning_rate {
        cosine_decay_learning_rate {
          learning_rate_base: 0.03999999910593033
          total_steps: 25000
          warmup_learning_rate: 0.013333000242710114
          warmup_steps: 2000
        }
      }
      momentum_optimizer_value: 0.8999999761581421
    }
    use_moving_average: false
  }
  fine_tune_checkpoint: "pre-trained-models/ssd_resnet50_v1_fpn_640x640_coco17_tpu-8/checkpoint/ckpt-0" # Path to checkpoint of pre-trained model
  num_steps: 25000
  startup_delay_steps: 0.0
  replicas_to_aggregate: 8
  max_number_of_boxes: 100
  unpad_groundtruth_tensors: false
  fine_tune_checkpoint_type: "detection" # Set this to "detection" since we want to be training the full detection model
  use_bfloat16: false # Set this to false if you are not training on a TPU
  fine_tune_checkpoint_version: V2
}
train_input_reader {
  label_map_path: "annotations/label_map.pbtxt" # Path to label map file
  tf_record_input_reader {
    input_path: "annotations/train.record" # Path to training TFRecord file
  }
}
eval_config {
  metrics_set: "coco_detection_metrics"
  use_moving_averages: false
}
eval_input_reader {
  label_map_path: "annotations/label_map.pbtxt" # Path to label map file
  shuffle: false
  num_epochs: 1
  tf_record_input_reader {
    input_path: "annotations/test.record" # Path to testing TFRecord
  }
}

I tried a few things to achieve reproducibility:

Set a global seed in various modules across the training pipeline

I tried setting up the operation-based seed for say shuffle, data augmentations etc.

Manually setting attributes coming from .proto files, like shuffle = False in build() function of Tensorflow/models/research/object_detection/builders/data_builder.py module
etc.

De-selecting or removing data_augmentation_options from pipeline.config file altogether.

The graphs above show 2 separate training runs (everything is kept the same in both experiments: global seeding is done in data_builder.py -- tf.random.set_seed(1234), no data augmentation selected i.e. "data_augmentation_options" removed from pipeline.config, data shuffle and related attributes adjusted as mentioned in point 3)

# Operations that rely on a random seed actually derive it from two seeds:
# the global and operation-level seeds. Adding this on top of a module sets the global seed.
tf.random.set_seed(1234)
# Switch off shuffle, config.filenames_shuffle_buffer_size
config.shuffle = False
# Make number of readers to zero
config.num_readers = 0
# Set sample_from_datasets_weights to zero
config.sample_from_datasets_weights = 0


来源: stackexchange

问:
How can I make a Java method accept arrays of different (primitive) variable types?
I want to write a simple method to print an array - looking like an array -  with its elements in the terminal, independent of whether it is an int[], boolean[], String[], double[] etc.

The String info parameter is just meant to output some answer phrase with the array shown, like "The wanted array is { .... }".

I am aware that in Java

unspecified parameter types should be handled with extreme care

primitive variable types cannot easily be used with generic data types

the usual answer for accepting different parameter types is overloading (which I finally did),

but the only difference between the different versions of the method printArray(...) is the variable type of the array handed over in the parameter list.

I also tried to hand over an object[] pArray as a parameter, but then it would only accept integer arrays, or give a runtime error message.

A similar concept is addressed in the answers to the former post Parameter For All Primitive Types of Java?, but - although it is pretty much the same question - the answers don't give solutions for arrays of simple primitives. They only answer

ways to find out, which parameter type was used, or

are limited to object types (including wrapper classes) or Number-objects, but which both don't solve my problem.

Looking at this the mantra "avoid code duplication" seems to be so obviously violated that I believe there must be a better solution.

Can anyone help me with this?    Here is the code:

```<code>void printArray(String info, boolean[] pArray)
{
    String arrayString = "";

    if (pArray.length > 0){
        arrayString = "{ " + pArray[0];

        for (int a = 1; a < pArray.length; a++){
            arrayString = arrayString + ", " + pArray[a];
        }
        arrayString = arrayString + " }";
    } else {
        arrayString = "{}";
    }

    System.out.println(info + arrayString + "\n");
}

void printArray(String info, int[] pArray)
{
    String arrayString = "";

    if (pArray.length > 0){
        arrayString = "{ " + pArray[0];

        for (int a = 1; a < pArray.length; a++){
            arrayString = arrayString + ", " + pArray[a];
        }
        arrayString = arrayString + " }";
    } else {
        arrayString = "{}";
    }

    System.out.println(info + arrayString + "\n");
}
</code>```

答:
You can create a Stream from an array of primitives, and then create an array of Objects from the Stream. This is one example.

```<code>import java.util.Arrays;

public class ArrayPrinter {

    public static void printArray(Object[] arr) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            sb.append(i == 0 ? arr[i] : " " + arr[i]);
        }
        System.out.println(sb.toString());
    }

    public static void main(String[] args) {
        int[] arr = new int[] {1, 2, 3, 4, 5, 6};
        Integer[] objs = Arrays.stream(arr).boxed().toArray(Integer[]::new);
        printArray(objs);
    }
}
</code>```

It's also fine to just have multiple versions of a method, one for an int array, one for a boolean array, one for a String array, et cetera. This strategy is called method overloading, and it's common. You can see examples of method overloading in the java.lang.Math class. The methods java.lang.Math.abs, java.lang.Math.max, and java.lang.Math.min are overloaded for different parameter types.

ContentLicense: CC BY-SA 4.0

Body:
I want to write a simple method to print an array - looking like an array -  with its elements in the terminal, independent of whether it is an int[], boolean[], String[], double[] etc.

The String info parameter is just meant to output some answer phrase with the array shown, like "The wanted array is { .... }".

I am aware that in Java

unspecified parameter types should be handled with extreme care

primitive variable types cannot easily be used with generic data types

the usual answer for accepting different parameter types is overloading (which I finally did),

but the only difference between the different versions of the method printArray(...) is the variable type of the array handed over in the parameter list.

I also tried to hand over an object[] pArray as a parameter, but then it would only accept integer arrays, or give a runtime error message.

A similar concept is addressed in the answers to the former post Parameter For All Primitive Types of Java?, but - although it is pretty much the same question - the answers don't give solutions for arrays of simple primitives. They only answer

ways to find out, which parameter type was used, or

are limited to object types (including wrapper classes) or Number-objects, but which both don't solve my problem.

Looking at this the mantra "avoid code duplication" seems to be so obviously violated that I believe there must be a better solution.

Can anyone help me with this?    Here is the code:

void printArray(String info, boolean[] pArray)
{
    String arrayString = "";

    if (pArray.length > 0){
        arrayString = "{ " + pArray[0];

        for (int a = 1; a < pArray.length; a++){
            arrayString = arrayString + ", " + pArray[a];
        }
        arrayString = arrayString + " }";
    } else {
        arrayString = "{}";
    }

    System.out.println(info + arrayString + "\n");
}

void printArray(String info, int[] pArray)
{
    String arrayString = "";

    if (pArray.length > 0){
        arrayString = "{ " + pArray[0];

        for (int a = 1; a < pArray.length; a++){
            arrayString = arrayString + ", " + pArray[a];
        }
        arrayString = arrayString + " }";
    } else {
        arrayString = "{}";
    }

    System.out.println(info + arrayString + "\n");
}

Body:
You can create a Stream from an array of primitives, and then create an array of Objects from the Stream. This is one example.

import java.util.Arrays;

public class ArrayPrinter {

    public static void printArray(Object[] arr) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            sb.append(i == 0 ? arr[i] : " " + arr[i]);
        }
        System.out.println(sb.toString());
    }

    public static void main(String[] args) {
        int[] arr = new int[] {1, 2, 3, 4, 5, 6};
        Integer[] objs = Arrays.stream(arr).boxed().toArray(Integer[]::new);
        printArray(objs);
    }
}

It's also fine to just have multiple versions of a method, one for an int array, one for a boolean array, one for a String array, et cetera. This strategy is called method overloading, and it's common. You can see examples of method overloading in the java.lang.Math class. The methods java.lang.Math.abs, java.lang.Math.max, and java.lang.Math.min are overloaded for different parameter types.


问:
How to add image attributes on .liquid (shopify)
Hi there community i'm fixing code from my theme, and i have some issues with it, wish anyone can help me,

this code shows that fail:

Missing width and height attributestheme-checkImgWidthAndHeight

https://github.com/Shopify/theme-check/blob/main/docs/checks/img_width_and_height.md

How can i add this attributes to that part of code?

```<code><div class="about-banner__image-2">
                {% if block.settings.image_2 != blank %}
                <noscript>
                  <img src="{{ block.settings.image_2 | img_url: '600x' }}" loading="lazy" alt="{{ block.settings.image_2.alt }}" class="image-content__image">
                </noscript>
                <div class="image-content__image-container">
                  <div class="image-content__image-wrapper" style="padding-top:{{ 1 | divided_by: block.settings.image_2.aspect_ratio | times: 100}}%;">
                    {% assign img_url = block.settings.image_2 | img_url: '1x1' | replace: '_1x1.', '_{width}x.' %}
                    <img class="image-content__image"
                         loading="lazy"
                         src="{{ block.settings.image_2 | img_url: '300x300' }}"
                         data-src="{{ img_url }}"
                         data-widths="[180, 360, 540, 720, 900, 1080, 1296, 1512, 1728, 1944, 2048]"
                         data-aspectratio="{{ block.settings.image_2.aspect_ratio }}"
                         data-sizes="auto"
                         alt="{{ block.settings.image_2.alt | escape }}">
                  </div>
                </div>
                {% else %}
                <div class="image-content__image">
                  {{ 'image' | placeholder_svg_tag: 'placeholder-svg' }}
                </div>
                {% endif %}
              </div>
</code>```

thanks to anyone!

答:
It is not necessary to use liquid, but you can simply add a filter like this:

    {{ settings.favicon | image_url: width: 200 | image_tag: alt: 'My favicon', srcset: nil, class: 'css-class-1 css-class-2' }}
```

Notice the last filter syntax is ... | image_tag: att1: 'value1', att2: 'value2'
Here, you can use attribute names like width and height, just like you would do in HTML.

Don't confuse | image_url: width: 200 filter, this is how you tell Shopify to render an image in a certain resolution.

Learn more about the liquid image tag here

Body:
Hi there community i'm fixing code from my theme, and i have some issues with it, wish anyone can help me,

this code shows that fail:

Missing width and height attributestheme-checkImgWidthAndHeight

https://github.com/Shopify/theme-check/blob/main/docs/checks/img_width_and_height.md

How can i add this attributes to that part of code?

                {% if block.settings.image_2 != blank %}

                    {% assign img_url = block.settings.image_2 | img_url: '1x1' | replace: '_1x1.', '_{width}x.' %}
                    <img class="image-content__image"
                         loading="lazy"
                         src="{{ block.settings.image_2 | img_url: '300x300' }}"
                         data-src="{{ img_url }}"
                         data-widths="[180, 360, 540, 720, 900, 1080, 1296, 1512, 1728, 1944, 2048]"
                         data-aspectratio="{{ block.settings.image_2.aspect_ratio }}"
                         data-sizes="auto"
                         alt="{{ block.settings.image_2.alt | escape }}">

                {% else %}

                  {{ 'image' | placeholder_svg_tag: 'placeholder-svg' }}

                {% endif %}

thanks to anyone!

Body:
It is not necessary to use liquid, but you can simply add a filter like this:

    {{ settings.favicon | image_url: width: 200 | image_tag: alt: 'My favicon', srcset: nil, class: 'css-class-1 css-class-2' }}

Notice the last filter syntax is ... | image_tag: att1: 'value1', att2: 'value2'
Here, you can use attribute names like width and height, just like you would do in HTML.

Don't confuse | image_url: width: 200 filter, this is how you tell Shopify to render an image in a certain resolution.

Learn more about the liquid image tag here


问:
how to hide TextFormField based on a value of Radio Button OR DropdownButtonFormField in Flutter
I'm new to Flutter and Dart language and I'm trying so hard to learn it by myself.

So, my question is I have a DropdownButtonFormField with 2 values (private chat and phone number) :

```<code>Widget menu(){
  return DropdownButtonFormField(
    decoration: InputDecoration(
      border: OutlineInputBorder(),
      labelText: 'how to contact with the buyer?',
      labelStyle: TextStyle(
          fontSize: 16,
          color: Colors.grey,
          fontFamily: 'Almarai'
        ),
    ),
  items: <String>['phone number', 'private chat'].map((String value) {
    return DropdownMenuItem<String>(
      value: value,
      child: Text(value),
    );
  }).toList(),
  onChanged: (String newValue) {
    setState(() {
      dropdownvalue = newValue;
    });
  },
);
}
</code>```

And I have this TextFormField that I want it to be hidden if the (private chat) option is selected :

```<code> Widget phonenum(){
    return
          TextFormField(
            maxLength: 10,
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: 'phone number',
              labelStyle: TextStyle(
                fontSize: 16,
                color: Colors.grey,
                fontFamily: 'Almarai'
              ),
            ),
          );
  }
</code>```

How can I achieve that please? And also, how can I achieve it using RadioButton rather than DropdownButtonFormField ? Because I still didn't decide which one is more suitable with my project flow.

答:
You can set an if else statement in front of the textfield widget.
Here for example it only shows Text "Mr ABC" if wishOnePerson is true. You can set a bool, and switch its value with setState(). When true show when false hide.

```<code>Column(
  children: <Widget>[
    Text('Good Morning'), // Always visible
    if (wishOnePerson) Text(' Mr ABC'), // Only visible if condition is true
  ],
)
</code>```

Body:
I'm new to Flutter and Dart language and I'm trying so hard to learn it by myself.

So, my question is I have a DropdownButtonFormField with 2 values (private chat and phone number) :

Widget menu(){
  return DropdownButtonFormField(
    decoration: InputDecoration(
      border: OutlineInputBorder(),
      labelText: 'how to contact with the buyer?',
      labelStyle: TextStyle(
          fontSize: 16,
          color: Colors.grey,
          fontFamily: 'Almarai'
        ),
    ),
  items: <String>['phone number', 'private chat'].map((String value) {
    return DropdownMenuItem<String>(
      value: value,
      child: Text(value),
    );
  }).toList(),
  onChanged: (String newValue) {
    setState(() {
      dropdownvalue = newValue;
    });
  },
);
}

And I have this TextFormField that I want it to be hidden if the (private chat) option is selected :

 Widget phonenum(){
    return
          TextFormField(
            maxLength: 10,
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: 'phone number',
              labelStyle: TextStyle(
                fontSize: 16,
                color: Colors.grey,
                fontFamily: 'Almarai'
              ),
            ),
          );
  }

How can I achieve that please? And also, how can I achieve it using RadioButton rather than DropdownButtonFormField ? Because I still didn't decide which one is more suitable with my project flow.

Body:
You can set an if else statement in front of the textfield widget.
Here for example it only shows Text "Mr ABC" if wishOnePerson is true. You can set a bool, and switch its value with setState(). When true show when false hide.

Column(
  children: <Widget>[
    Text('Good Morning'), // Always visible
    if (wishOnePerson) Text(' Mr ABC'), // Only visible if condition is true
  ],
)


问:
Fatal error: Call to undefined method stdClass::My()
I am getting this error when I call for the function My() for the second time. The first time (when I'm calling for the user_id) everything seems to be fine.. Stripped down code:

```<code>class User {
    function My($field) {
        global $user;
        global $db;
        global $sessions;

        if ($sessions == 2) {
            $user = $db->Row("SELECT * FROM users WHERE username='".$_SESSION['username']."'");
            return $user->$field;
        }
    }
}

$user = new User;

class Index {
    function Startup() {
        global $user;

        $user_id = $user->My("user_id");
        $name = $user->My("firstname")." ".$user->My("surname");
    }
}
</code>```

Any suggestions would be greatly appreciated.

答:
You have to initalize the variable first like

```<code>$user = new User();
$user->my();
</code>```

Also please never use global unless you know what you are doing.

ContentLicense: CC BY-SA 3.0

Body:
I am getting this error when I call for the function My() for the second time. The first time (when I'm calling for the user_id) everything seems to be fine.. Stripped down code:

class User {
    function My($field) {
        global $user;
        global $db;
        global $sessions;

        if ($sessions == 2) {
            $user = $db->Row("SELECT * FROM users WHERE username='".$_SESSION['username']."'");
            return $user->$field;
        }
    }
}

$user = new User;

class Index {
    function Startup() {
        global $user;

        $user_id = $user->My("user_id");
        $name = $user->My("firstname")." ".$user->My("surname");
    }
}

Any suggestions would be greatly appreciated.

Body:
You have to initalize the variable first like

$user = new User();
$user->my();

Also please never use global unless you know what you are doing.


问:
How to call direct imports of libraries in the creation of a Python package
Background

I'm trying to create a Python package with a semi-complicated structure. I have published a few packages before, and because they were simple, I put all the classes and functions necessary in __init__.py itself. For example, the file structure of one of my simple packages would be:

```<code>Package/
    venv # my virtual environment
    package-name/
        __init__.py
    setup.py # with setuptools, etc.
</code>```

A sample __init__.py file from a sample package would be:

# __init__.py from a sample simple package
import requests

class User:
    def __init__(self, something):
        self.something = requests.get(url).json()['something']

    def do_something(self):
        return float(self.something) * 10
```
<p>As a sample package like this is basic and only requires the <code>User</code> class, this would suffice. On installing the package with <code>pip</code>, using <code>import package-name</code> works to call the <code>User</code> object.</p>
<pre class="lang-py prettyprint-override"><code># random computer with simple package installed
import package_name

api = package_name.User()
</code>```

And this works fine.

Question

A more complicated package like the one I'm working on cannot contain all classes and functions directly in the __init__.py file. The structure is below:

```<code>Package/
    venv # my virtual environment
    package-name/
        __init__.py
        related.py
        something.py
    setup.py
</code>```

The problem is that I can't quite figure out how to get the contents of related.py and something.py to work implicitly. By implicitly, I mean that when the user executes import package_name, they can use package_name.attribute to access any attributes from any of the files, whether it's in __init__.py, related.py, or something.py.

Currently, if I structure the __init__.py file like this:

# complex package __init__.py
from package_name import related
from package_name import something
```
<p>The user still has to call <code>related</code> and <code>something</code> as attributes of <code>package_name</code>:</p>
<pre class="lang-py prettyprint-override"><code># random computer user file with package_name installed
import package_name

x = package_name.related.x()
y = package_name.something.y()
</code>```

I want them to be able to do this instead:

# random computer user file with package_name installed
import package_name

x = package_name.x()
y = package_name.y()
```

Without having to themselves write: from package_name import related and from package_name import something on their own computer.

Apologies for the long question but I wanted to be as clear as possible about what I'm asking because there are a lot of moving parts.

答: Whatever names are available in your __init__.py will be available as package_name.whatever when someone does import package_name.  So if you want to make names from submodules available, you can do from package_name.related import x (or from .related import x) inside your __init__.py.

Body:
Background

I'm trying to create a Python package with a semi-complicated structure. I have published a few packages before, and because they were simple, I put all the classes and functions necessary in __init__.py itself. For example, the file structure of one of my simple packages would be:

Package/
    venv # my virtual environment
    package-name/
        __init__.py
    setup.py # with setuptools, etc.

A sample __init__.py file from a sample package would be:

# __init__.py from a sample simple package
import requests

class User:
    def __init__(self, something):
        self.something = requests.get(url).json()['something']

    def do_something(self):
        return float(self.something) * 10

As a sample package like this is basic and only requires the User class, this would suffice. On installing the package with pip, using import package-name works to call the User object.

# random computer with simple package installed
import package_name

api = package_name.User()

And this works fine.

Question

A more complicated package like the one I'm working on cannot contain all classes and functions directly in the __init__.py file. The structure is below:

Package/
    venv # my virtual environment
    package-name/
        __init__.py
        related.py
        something.py
    setup.py

The problem is that I can't quite figure out how to get the contents of related.py and something.py to work implicitly. By implicitly, I mean that when the user executes import package_name, they can use package_name.attribute to access any attributes from any of the files, whether it's in __init__.py, related.py, or something.py.

Currently, if I structure the __init__.py file like this:

# complex package __init__.py
from package_name import related
from package_name import something

The user still has to call related and something as attributes of package_name:

# random computer user file with package_name installed
import package_name

x = package_name.related.x()
y = package_name.something.y()

I want them to be able to do this instead:

# random computer user file with package_name installed
import package_name

x = package_name.x()
y = package_name.y()

Without having to themselves write: from package_name import related and from package_name import something on their own computer.

Apologies for the long question but I wanted to be as clear as possible about what I'm asking because there are a lot of moving parts.


问:
Create Laravel Relationship through Many-To-One and Many-To-Many
I'm having trouble defining a relationship between several models.
In the Laravel documentation, I was able to find a hasManyThrough() relationship where the relationship was extended down through two many-to-one models, but I'm having issues with mine from a many-to-one then many-to-many relationship. Here are the tables:

```<code>practices
  id
  name

locations
  id
  practice_id
  name

doctors
  id
  name

doctor_location
  doctor_id
  location_id
</code>```

As you can see, practices can have many locations, and locations can only belong to one practice. Doctors can have many locations, and locations can have many doctors. I'm not certain how to drill down to create a $practice->doctors relationship, however. I did attempt the hasManyThrough() relationship in the practices model:

```<code>public function doctors() {
  return $this->hasManyThrough(Doctor::class, Location::class);
}
</code>```

but this simply threw an sqlstate error looking for a location_id in the doctors table. Is it possible to relate these models?

Edit: SQLState error

```<code>Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'doctors.location_id' in 'on clause' (SQL: select `doctors`.*, `locations`.`practice_id` as `laravel_through_key` from `doctors` inner join `locations` on `locations`.`id` = `doctors`.`location_id` where `locations`.`practice_id` = 1)
</code>```

答:
The error message and the documentation are clear.
hasManyThrough relation works only with one to many relations

Practices -> Locations is one to many but Locations -> Doctors
is many to many there is a pivot table between Locations and Doctors. therefore you can't use hasManyThrough in this scenario

if you really want to use hasManyThrough, you must convert the Locations -> Doctors relation to one to many by placing location_id in the doctors table

Otherwise the only way the get the doctors is like @Bulent suggested

```<code>$practice = Practice::where("id", your_id )->with('locations.doctors')->first();
</code>```

and then iterate thought locations and doctors

```<code>foreach ($practice->locations as $location) {
    foreach ($location->doctors as $doctor) {
        // do stuff with each doctor here
    }
}
</code>```

Body:
I'm having trouble defining a relationship between several models.
In the Laravel documentation, I was able to find a hasManyThrough() relationship where the relationship was extended down through two many-to-one models, but I'm having issues with mine from a many-to-one then many-to-many relationship. Here are the tables:

practices
  id
  name

locations
  id
  practice_id
  name

doctors
  id
  name

doctor_location
  doctor_id
  location_id

As you can see, practices can have many locations, and locations can only belong to one practice. Doctors can have many locations, and locations can have many doctors. I'm not certain how to drill down to create a $practice->doctors relationship, however. I did attempt the hasManyThrough() relationship in the practices model:

public function doctors() {
  return $this->hasManyThrough(Doctor::class, Location::class);
}

but this simply threw an sqlstate error looking for a location_id in the doctors table. Is it possible to relate these models?

Edit: SQLState error

Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'doctors.location_id' in 'on clause' (SQL: select `doctors`.*, `locations`.`practice_id` as `laravel_through_key` from `doctors` inner join `locations` on `locations`.`id` = `doctors`.`location_id` where `locations`.`practice_id` = 1)

Body:
The error message and the documentation are clear.
hasManyThrough relation works only with one to many relations

Practices -> Locations is one to many but Locations -> Doctors
is many to many there is a pivot table between Locations and Doctors. therefore you can't use hasManyThrough in this scenario

if you really want to use hasManyThrough, you must convert the Locations -> Doctors relation to one to many by placing location_id in the doctors table

Otherwise the only way the get the doctors is like @Bulent suggested

$practice = Practice::where("id", your_id )->with('locations.doctors')->first();

and then iterate thought locations and doctors

foreach ($practice->locations as $location) {
    foreach ($location->doctors as $doctor) {
        // do stuff with each doctor here
    }
}


问:
Get Google "pills" value as Plain text from Google docs with Google Apps Script
I am trying to pull the value of the new feature in Google Docs: the "pills"(unsure about this name).

I am parsing a table in a doc with a Google App Script. When I am getting to the row (see image) I am getting null. I can't figure out what should I run to get this value as Plain text.

The code I run to get this at the moment that returns null:

```<code>Logger.log(table.getCell(i, 1).getText())
> null
</code>```

How can I get the actual value of the "pill"?

答:
I thought that from your provided image, it's the smart chips and it might be Class Date, and also, it seems that it is put into a cell of the column "B". Unfortunately, that cannot be directly retrieved using getText(). I think that this is the reason for your issue.

But, 3 Classes for retrieving the smart chips has been added on August 23, 2021. You can retrieve the value using these Classes. If you want to retrieve the value, how about the following sample script?

Sample script:

When the table of your sample image is used, a simple sample script is as follows.

const cell = table.getCell(i, 1); // This is from your script.

const p = cell.getChild(0).asParagraph();
const c = p.getChild(0);
if (c.getType() == DocumentApp.ElementType.DATE) {
  const value = c.asDate().getDisplayText();
  console.log(value)
} else if (c.getType() == DocumentApp.ElementType.TEXT) {
  const value = c.asText().getText();
  console.log(value)
}
```
<p>or, if your cells have multiple paragraphs, you can also the following sample script.</p>
<pre class="lang-js prettyprint-override"><code>const cell = table.getCell(i, 1);  // This is from your script.

for (let j = 0; j < cell.getNumChildren(); j++) {
  const p = cell.getChild(j).asParagraph();
  for (let k = 0; k < p.getNumChildren(); k++) {
    const c = p.getChild(k);
    if (c.getType() == DocumentApp.ElementType.DATE) {
      const value = c.asDate().getDisplayText();
      console.log(value)
    } else if (c.getType() == DocumentApp.ElementType.TEXT) {
      const value = c.asText().getText();
      console.log(value)
    }
  }
}
</code>```

When getDisplayText() is changed to getTimestamp(), the Date object can be retrieved instead of the string value.

References:

Class Date

Classes for retrieving the smart chips has been added on August 23, 2021.

Body:
I am trying to pull the value of the new feature in Google Docs: the "pills"(unsure about this name).

I am parsing a table in a doc with a Google App Script. When I am getting to the row (see image) I am getting null. I can't figure out what should I run to get this value as Plain text.

The code I run to get this at the moment that returns null:

Logger.log(table.getCell(i, 1).getText())
> null

How can I get the actual value of the "pill"?

Body:
I thought that from your provided image, it's the smart chips and it might be Class Date, and also, it seems that it is put into a cell of the column "B". Unfortunately, that cannot be directly retrieved using getText(). I think that this is the reason for your issue.

But, 3 Classes for retrieving the smart chips has been added on August 23, 2021. You can retrieve the value using these Classes. If you want to retrieve the value, how about the following sample script?

Sample script:

When the table of your sample image is used, a simple sample script is as follows.

const cell = table.getCell(i, 1); // This is from your script.

const p = cell.getChild(0).asParagraph();
const c = p.getChild(0);
if (c.getType() == DocumentApp.ElementType.DATE) {
  const value = c.asDate().getDisplayText();
  console.log(value)
} else if (c.getType() == DocumentApp.ElementType.TEXT) {
  const value = c.asText().getText();
  console.log(value)
}

or, if your cells have multiple paragraphs, you can also the following sample script.

const cell = table.getCell(i, 1);  // This is from your script.

for (let j = 0; j < cell.getNumChildren(); j++) {
  const p = cell.getChild(j).asParagraph();
  for (let k = 0; k < p.getNumChildren(); k++) {
    const c = p.getChild(k);
    if (c.getType() == DocumentApp.ElementType.DATE) {
      const value = c.asDate().getDisplayText();
      console.log(value)
    } else if (c.getType() == DocumentApp.ElementType.TEXT) {
      const value = c.asText().getText();
      console.log(value)
    }
  }
}

When getDisplayText() is changed to getTimestamp(), the Date object can be retrieved instead of the string value.

References:

Class Date

Classes for retrieving the smart chips has been added on August 23, 2021.


问:
NodeJS webpack configuration error for sass and css
I recently updated my NodeJS version to 'v16.13.2' and ever since then my template I built is breaking when trying to bundle the scss and css. Everything else works just fine when building.
I'm aware that node-sass had been deprecated and I should use sass (dart-sass). However, when I run my build I get this error:

```<code>Module parse failed: C:\Users\...\src\styles\styles.scss Unexpected token (1:3)
You may need an appropriate loader to handle this file type.
| h1 {

|   color: white;

|   text-align: center;

 @ ./src/app.js 25:0-31
 @ multi (webpack)-dev-server/client?http://localhost:8080 babel-polyfill ./src/app.js
</code>```

I'm trying to get basic css to work but the loader doesn't seem to recognize the code.
Here is my code

package.json:

```<code>"scripts": {
"build:dev": "webpack",
"build:prod": "webpack -p --env production",
"dev-server": "webpack-dev-server",
"test": "cross-env NODE_ENV=test jest --config=jest.config.json",
"start": "node server/server.js",
"heroku-postbuild": "yarn run build:prod"
},
 "dependencies": {
"babel-cli": "6.24.1",
"babel-core": "6.25.0",
"babel-loader": "7.1.1",
"babel-plugin-transform-class-properties": "6.24.1",
"babel-plugin-transform-object-rest-spread": "6.23.0",
"babel-polyfill": "6.26.0",
"babel-preset-env": "1.5.2",
"babel-preset-react": "6.24.1",
"css-loader": "^6.5.1",
"express": "4.15.4",
"extract-text-webpack-plugin": "3.0.0",
"firebase": "^8.9.1",
"history": "4.10.1",
"moment": "2.18.1",
"normalize.css": "7.0.0",
"numeral": "2.0.6",
"react": "^16.14.0",
"react-addons-shallow-compare": "15.6.0",
"react-dates": "12.7.0",
"react-dom": "^16.14.0",
"react-modal": "2.2.2",
"react-redux": "5.0.5",
"react-router-dom": "4.1.2",
"redux": "3.7.2",
"redux-mock-store": "1.2.3",
"redux-thunk": "2.2.0",
"sass": "^1.49.7",
"sass-loader": "7.3.1",
"style-loader": "0.18.2",
"uuid": "3.1.0",
"validator": "8.0.0",
"webpack": "3.1.0"
},
"devDependencies": {
"cross-env": "5.0.5",
"dotenv": "^14.2.0",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.6",
"enzyme-to-json": "^3.6.1",
"jest": "20.0.4",
"raf": "^3.4.1",
"react-test-renderer": "^16.14.0",
"webpack-dev-server": "2.5.1"
</code>```

}

webpack.cnfig.js:

```<code>return{
entry: ['babel-polyfill','./src/app.js'],
output: {
  path: path.join(__dirname, 'public', 'dist'),
  filename: 'bundle.js'
},
module: {
  rules: [{
    loader: 'babel-loader',
    test: /\.js$/,
    exclude: /node_modules/
  },
  {
    test: /\.s?css$/,
    use: CSSExtract.extract({
      use: [
        {
          loader: 'css-loader',
          options:{
            sourceMap: true
          }
        },
        {
          loader: 'sass-loader',
          options:{
            sourceMap: true
          }
        }
      ]
    })
  }
]
},
</code>```

EDIT: So after much research, I have also figured out that 'extract-text-webpack-plugin' is also deprecated and the documentation suggests that I use 'mini-css-extract-plugin'. So, I read the documentation for that and applied it but still nothing is working. I just want my webpack to bundle my .js and .css in separate files . Right now all of it is being pushed into 'bundle.js' and it does not render any css.

EDIT 2: Here is my new webpack.config.js and it is working as I wanted:

```<code>webpack.config.js:
</code>```

webpack.config.js:

```<code>  const path = require('path');
  const webpack = require('webpack');
  const MiniCssExtractPlugin = require("mini-css-extract-plugin");

  process.env.NODE_ENV = process.env.NODE_ENV || 'development'

  if(process.env.NODE_ENV === 'test'){
    require('dotenv').config({ path: '.env.test'})
  }else if(process.env.NODE_ENV === 'development'){
    require('dotenv').config({ path: '.env.development'})
  }

  module.exports = (env) => {
    const isProd = env === 'production'

    return{
      entry: ['babel-polyfill','./src/app.js'],
      output: {
        path: path.join(__dirname, 'public', 'dist'),
        filename: 'bundle.js'
      },
      module: {
        rules: [{
          loader: 'babel-loader',
          test: /\.js$/,
          exclude: /node_modules/
        },
        {
          test: /\.(css)$/,
          use: [MiniCssExtractPlugin.loader, 'css-loader']
        },
        {
          test: /\.(s[ca]ss)$/,
          use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
        }
      ]
      },
      plugins:[
        new MiniCssExtractPlugin({
          filename:'styles.css'
        }),
        new webpack.DefinePlugin({
          'process.env.FIREBASE_API_KEY': JSON.stringify(process.env.FIREBASE_API_KEY),
          'process.env.FIREBASE_AUTH_DOMAIN': JSON.stringify(process.env.FIREBASE_AUTH_DOMAIN),
          'process.env.FIREBASE_DATABASE_URL': JSON.stringify(process.env.FIREBASE_DATABASE_URL),
          'process.env.FIREBASE_PROJECT_ID': JSON.stringify(process.env.FIREBASE_PROJECT_ID),
          'process.env.FIREBASE_STORAGE_BUCKET': JSON.stringify(process.env.FIREBASE_STORAGE_BUCKET),
          'process.env.FIREBASE_MESSAGE_SENDER_ID': JSON.stringify(process.env.FIREBASE_MESSAGE_SENDER_ID),
          'process.env.FIREBASE_APP_ID': JSON.stringify(process.env.FIREBASE_APP_ID)
        })
      ],
      devtool: isProd ? 'source-map' :'inline-source-map',
      devServer: {
        contentBase: path.join(__dirname, 'public'),
        historyApiFallback: true,
        publicPath: '/dist'
      }
    }
  }
</code>```

答: Alright I finally have an answer for all of this. So I essentially had to update a lot of my webpack due to deprecated modules. I ended up using 'mini-css-extract-plugin' and found out how to set it up. If anyone is working on a project using Nodejs version 16 and up, try this for the webpack and see if it works. I'll post my results in the initial question.</p>

Body:
I recently updated my NodeJS version to 'v16.13.2' and ever since then my template I built is breaking when trying to bundle the scss and css. Everything else works just fine when building.
I'm aware that node-sass had been deprecated and I should use sass (dart-sass). However, when I run my build I get this error:

Module parse failed: C:\Users\...\src\styles\styles.scss Unexpected token (1:3)
You may need an appropriate loader to handle this file type.
| h1 {

|   color: white;

|   text-align: center;

 @ ./src/app.js 25:0-31
 @ multi (webpack)-dev-server/client?http://localhost:8080 babel-polyfill ./src/app.js

I'm trying to get basic css to work but the loader doesn't seem to recognize the code.
Here is my code

package.json:

"scripts": {
"build:dev": "webpack",
"build:prod": "webpack -p --env production",
"dev-server": "webpack-dev-server",
"test": "cross-env NODE_ENV=test jest --config=jest.config.json",
"start": "node server/server.js",
"heroku-postbuild": "yarn run build:prod"
},
 "dependencies": {
"babel-cli": "6.24.1",
"babel-core": "6.25.0",
"babel-loader": "7.1.1",
"babel-plugin-transform-class-properties": "6.24.1",
"babel-plugin-transform-object-rest-spread": "6.23.0",
"babel-polyfill": "6.26.0",
"babel-preset-env": "1.5.2",
"babel-preset-react": "6.24.1",
"css-loader": "^6.5.1",
"express": "4.15.4",
"extract-text-webpack-plugin": "3.0.0",
"firebase": "^8.9.1",
"history": "4.10.1",
"moment": "2.18.1",
"normalize.css": "7.0.0",
"numeral": "2.0.6",
"react": "^16.14.0",
"react-addons-shallow-compare": "15.6.0",
"react-dates": "12.7.0",
"react-dom": "^16.14.0",
"react-modal": "2.2.2",
"react-redux": "5.0.5",
"react-router-dom": "4.1.2",
"redux": "3.7.2",
"redux-mock-store": "1.2.3",
"redux-thunk": "2.2.0",
"sass": "^1.49.7",
"sass-loader": "7.3.1",
"style-loader": "0.18.2",
"uuid": "3.1.0",
"validator": "8.0.0",
"webpack": "3.1.0"
},
"devDependencies": {
"cross-env": "5.0.5",
"dotenv": "^14.2.0",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.6",
"enzyme-to-json": "^3.6.1",
"jest": "20.0.4",
"raf": "^3.4.1",
"react-test-renderer": "^16.14.0",
"webpack-dev-server": "2.5.1"

}

webpack.cnfig.js:

return{
entry: ['babel-polyfill','./src/app.js'],
output: {
  path: path.join(__dirname, 'public', 'dist'),
  filename: 'bundle.js'
},
module: {
  rules: [{
    loader: 'babel-loader',
    test: /\.js$/,
    exclude: /node_modules/
  },
  {
    test: /\.s?css$/,
    use: CSSExtract.extract({
      use: [
        {
          loader: 'css-loader',
          options:{
            sourceMap: true
          }
        },
        {
          loader: 'sass-loader',
          options:{
            sourceMap: true
          }
        }
      ]
    })
  }
]
},

EDIT: So after much research, I have also figured out that 'extract-text-webpack-plugin' is also deprecated and the documentation suggests that I use 'mini-css-extract-plugin'. So, I read the documentation for that and applied it but still nothing is working. I just want my webpack to bundle my .js and .css in separate files . Right now all of it is being pushed into 'bundle.js' and it does not render any css.

EDIT 2: Here is my new webpack.config.js and it is working as I wanted:

webpack.config.js:

webpack.config.js:

  const path = require('path');
  const webpack = require('webpack');
  const MiniCssExtractPlugin = require("mini-css-extract-plugin");

  process.env.NODE_ENV = process.env.NODE_ENV || 'development'

  if(process.env.NODE_ENV === 'test'){
    require('dotenv').config({ path: '.env.test'})
  }else if(process.env.NODE_ENV === 'development'){
    require('dotenv').config({ path: '.env.development'})
  }

  module.exports = (env) => {
    const isProd = env === 'production'

    return{
      entry: ['babel-polyfill','./src/app.js'],
      output: {
        path: path.join(__dirname, 'public', 'dist'),
        filename: 'bundle.js'
      },
      module: {
        rules: [{
          loader: 'babel-loader',
          test: /\.js$/,
          exclude: /node_modules/
        },
        {
          test: /\.(css)$/,
          use: [MiniCssExtractPlugin.loader, 'css-loader']
        },
        {
          test: /\.(s[ca]ss)$/,
          use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
        }
      ]
      },
      plugins:[
        new MiniCssExtractPlugin({
          filename:'styles.css'
        }),
        new webpack.DefinePlugin({
          'process.env.FIREBASE_API_KEY': JSON.stringify(process.env.FIREBASE_API_KEY),
          'process.env.FIREBASE_AUTH_DOMAIN': JSON.stringify(process.env.FIREBASE_AUTH_DOMAIN),
          'process.env.FIREBASE_DATABASE_URL': JSON.stringify(process.env.FIREBASE_DATABASE_URL),
          'process.env.FIREBASE_PROJECT_ID': JSON.stringify(process.env.FIREBASE_PROJECT_ID),
          'process.env.FIREBASE_STORAGE_BUCKET': JSON.stringify(process.env.FIREBASE_STORAGE_BUCKET),
          'process.env.FIREBASE_MESSAGE_SENDER_ID': JSON.stringify(process.env.FIREBASE_MESSAGE_SENDER_ID),
          'process.env.FIREBASE_APP_ID': JSON.stringify(process.env.FIREBASE_APP_ID)
        })
      ],
      devtool: isProd ? 'source-map' :'inline-source-map',
      devServer: {
        contentBase: path.join(__dirname, 'public'),
        historyApiFallback: true,
        publicPath: '/dist'
      }
    }
  }


问:
Passing a dynamic parameter through URL in SSRS
I have two reports, the first one passes two parameters through the second report which works fine when using 'Go to Report'

However I need to use 'Go to URL' as I need to be able to control the Zoom.

The problem is, I also need to pass the 2 parameters through the URL.

These Parameters are @Reason1 and @Reason2.

I have tried using the following:

```<code>http://servername/ReportServer/Pages/ReportViewer.aspxnameofmyreportpart&rs:Command=Render&Reason1=@Reason1&Reason2=@Reason2
</code>```

But then it hard codes @Reason1 and @Reason2 as the values of my Reason1/Reason2 parameter value box's which obviously yields no results.

How do I structure the URL to receive the 2 parameters from the selection made in the previous report.

答:
```<code>="javascript:void(window.open('http://Servername/ReportServer?/Foldername/Reportname&rs:Commnd=Render&parameter1=" & Fields!A.Value & "&parameter2=" & Fields!B.Value & "'))"
</code>```

Use the above URL to open the report in a new window with dynamic parameters.

Body:
I have two reports, the first one passes two parameters through the second report which works fine when using 'Go to Report'

However I need to use 'Go to URL' as I need to be able to control the Zoom.

The problem is, I also need to pass the 2 parameters through the URL.

These Parameters are @Reason1 and @Reason2.

I have tried using the following:

http://servername/ReportServer/Pages/ReportViewer.aspxnameofmyreportpart&rs:Command=Render&Reason1=@Reason1&Reason2=@Reason2

But then it hard codes @Reason1 and @Reason2 as the values of my Reason1/Reason2 parameter value box's which obviously yields no results.

How do I structure the URL to receive the 2 parameters from the selection made in the previous report.

Body:
="javascript:void(window.open('http://Servername/ReportServer?/Foldername/Reportname&rs:Commnd=Render&parameter1=" & Fields!A.Value & "&parameter2=" & Fields!B.Value & "'))"

Use the above URL to open the report in a new window with dynamic parameters.


问:
Base64 String throwing invalid character error
I keep getting a Base64 invalid character error even though I shouldn't.

The program takes an XML file and exports it to a document. If the user wants, it will compress the file as well. The compression works fine and returns a Base64 String which is encoded into UTF-8 and written to a file.

When its time to reload the document into the program I have to check whether its compressed or not, the code is simply:

```<code>byte[] gzBuffer = System.Convert.FromBase64String(text);
return "1F-8B-08" == BitConverter.ToString(new List<Byte>(gzBuffer).GetRange(4, 3).ToArray());
</code>```

It checks the beginning of the string to see if it has GZips code in it.

Now the thing is, all my tests work. I take a string, compress it, decompress it, and compare it to the original. The problem is when I get the string returned from an ADO Recordset. The string is exactly what was written to the file (with the addition of a "\0" at the end, but I don't think that even does anything, even trimmed off it still throws). I even copy and pasted the entire string into a test method and compress/decompress that. Works fine.

The tests will pass but the code will fail using the exact same string? The only difference is instead of just declaring a regular string and passing it in I'm getting one returned from a recordset.

Any ideas on what am I doing wrong?

答:
You say

The string is exactly what was written
  to the file (with the addition of a
  "\0" at the end, but I don't think
  that even does anything).

In fact, it does do something (it causes your code to throw a FormatException:"Invalid character in a Base-64 string") because the Convert.FromBase64String does not consider "\0" to be a valid Base64 character.

```<code>  byte[] data1 = Convert.FromBase64String("AAAA\0"); // Throws exception
  byte[] data2 = Convert.FromBase64String("AAAA");   // Works
</code>```

Solution: Get rid of the zero termination.  (Maybe call .Trim("\0"))

Notes:

The MSDN docs for Convert.FromBase64String say it will throw a FormatException when

The length of s, ignoring white space
  characters, is not zero or a multiple
  of 4.

-or-

The format of s is invalid. s contains a non-base 64 character, more
  than two padding characters, or a
  non-white space character among the
  padding characters.

and that

The base 64 digits in ascending order
  from zero are the uppercase characters
  'A' to 'Z', lowercase characters 'a'
  to 'z', numerals '0' to '9', and the
  symbols '+' and '/'.

OwnerDisplayName: Brandon

ContentLicense: CC BY-SA 2.5

Body:
I keep getting a Base64 invalid character error even though I shouldn't.

The program takes an XML file and exports it to a document. If the user wants, it will compress the file as well. The compression works fine and returns a Base64 String which is encoded into UTF-8 and written to a file.

When its time to reload the document into the program I have to check whether its compressed or not, the code is simply:

byte[] gzBuffer = System.Convert.FromBase64String(text);
return "1F-8B-08" == BitConverter.ToString(new List<Byte>(gzBuffer).GetRange(4, 3).ToArray());

It checks the beginning of the string to see if it has GZips code in it.

Now the thing is, all my tests work. I take a string, compress it, decompress it, and compare it to the original. The problem is when I get the string returned from an ADO Recordset. The string is exactly what was written to the file (with the addition of a "\0" at the end, but I don't think that even does anything, even trimmed off it still throws). I even copy and pasted the entire string into a test method and compress/decompress that. Works fine.

The tests will pass but the code will fail using the exact same string? The only difference is instead of just declaring a regular string and passing it in I'm getting one returned from a recordset.

Any ideas on what am I doing wrong?

LastEditorDisplayName: Brandon

Body:
You say

The string is exactly what was written
  to the file (with the addition of a
  "\0" at the end, but I don't think
  that even does anything).

In fact, it does do something (it causes your code to throw a FormatException:"Invalid character in a Base-64 string") because the Convert.FromBase64String does not consider "\0" to be a valid Base64 character.

  byte[] data1 = Convert.FromBase64String("AAAA\0"); // Throws exception
  byte[] data2 = Convert.FromBase64String("AAAA");   // Works

Solution: Get rid of the zero termination.  (Maybe call .Trim("\0"))

Notes:

The MSDN docs for Convert.FromBase64String say it will throw a FormatException when

The length of s, ignoring white space
  characters, is not zero or a multiple
  of 4.

-or-

The format of s is invalid. s contains a non-base 64 character, more
  than two padding characters, or a
  non-white space character among the
  padding characters.

and that

The base 64 digits in ascending order
  from zero are the uppercase characters
  'A' to 'Z', lowercase characters 'a'
  to 'z', numerals '0' to '9', and the
  symbols '+' and '/'.

OwnerDisplayName: Daniel L

LastEditorDisplayName: Daniel L


问:
Android Studio project not reading correctly from SQLite database?
I've been struggling with this for days now and can't work out what's wrong. The thing is, I am not getting errors at the moment. Im just not producing the result I hoped for. I am trying to read from a specific record in my sqlite database where the data is a week ago today - I am trying to get the weather on this day, which is in my database. Here is my DB code for the method I am using:

```<code>public long homepageTB(){

    LocalDate now = LocalDate.now();

    LocalDate lastWeek = now.minusDays(7+now.getDayOfWeek().getValue()-1);
    LocalDate currentDate = now.minusDays(now.getDayOfWeek().getValue());

    String[] lweek = new String[1];
    lweek[0] = String.valueOf(lastWeek);
    String lastwk = String.valueOf(lastWeek);

    long rv = -1; //<<<< default return to indicate no such row
    SQLiteDatabase DB=this.getReadableDatabase();
    Cursor cursor=DB.rawQuery("select weather from dailyQuiz1 where date =?",lweek);
    if (cursor.moveToFirst()) {
        rv = cursor.getLong(cursor.getColumnIndex("weather"));
    }

    System.out.println(lweek[0]);
    System.out.println(rv);

    return rv;
}
</code>```

At the moment, this correctly returns the data week ago in format: 2022-01-31
and returns rv: -1 (which means it can't find the record). However, the record is there in my database:

So realistically I don't want -1 to be returned as I would want the variable in another class I am calling it from to now hold the value of the weather, which you can see in my database is 'Rainy'. Any ideas what I've done wrong or what is a better approach? I feel it will be something so obvious but I've been trying so many things for the past few days :( Thanks for the help

答:
With the exception that you will have an issue with the returned value being 0 if the data is found

i.e. you are getting a long from a text value when using rv = cursor.getLong(cursor.getColumnIndex("weather")) so instead of crashing when trying to convert Rainy to a long 0 is given.

What you have shown works as expected. That leaves the issue to probably be that the database does not in fact contain a row where the date column does  equal the String 2022-01-31.

You  need to ensure that what is in the actual database being used is as expected (your image appears to be from a tool rather than the actual database and often issues are due to differences).

So in Android Studio run the App and get to a point where it is awaiting for user interaction. The click on App Inspection do you see the same data? e.g. it should look like (not all columns have been included in the example):-

If not then your issue is that the data is not being added as expected and that needs to be corrected.

Otherwise click on the Query Icon

Enter and run SELECT length(date), * FROM dailyquiz1 WHERE date like '2022-01%' e.g. :-

if the first column returned is > 10 then there is an issue with the data that is being stored, as it contains additional data.

if the first column returned is < 10 then you are storing data that is shorter than it should be.

if no data is returned then the data stored is even further away from what it should be.

Body:
I've been struggling with this for days now and can't work out what's wrong. The thing is, I am not getting errors at the moment. Im just not producing the result I hoped for. I am trying to read from a specific record in my sqlite database where the data is a week ago today - I am trying to get the weather on this day, which is in my database. Here is my DB code for the method I am using:

public long homepageTB(){

    LocalDate now = LocalDate.now();

    LocalDate lastWeek = now.minusDays(7+now.getDayOfWeek().getValue()-1);
    LocalDate currentDate = now.minusDays(now.getDayOfWeek().getValue());

    String[] lweek = new String[1];
    lweek[0] = String.valueOf(lastWeek);
    String lastwk = String.valueOf(lastWeek);

    long rv = -1; //<<<< default return to indicate no such row
    SQLiteDatabase DB=this.getReadableDatabase();
    Cursor cursor=DB.rawQuery("select weather from dailyQuiz1 where date =?",lweek);
    if (cursor.moveToFirst()) {
        rv = cursor.getLong(cursor.getColumnIndex("weather"));
    }

    System.out.println(lweek[0]);
    System.out.println(rv);

    return rv;
}

At the moment, this correctly returns the data week ago in format: 2022-01-31
and returns rv: -1 (which means it can't find the record). However, the record is there in my database:

So realistically I don't want -1 to be returned as I would want the variable in another class I am calling it from to now hold the value of the weather, which you can see in my database is 'Rainy'. Any ideas what I've done wrong or what is a better approach? I feel it will be something so obvious but I've been trying so many things for the past few days :( Thanks for the help


问:
Errors : Cannot use import statement outside a module THREE.OrbitControl
Im starting with three.js. After trying to implement orbit controls i have some errors. It looks simple but i cannot find a good solution for my errors. When im trying to implement controls like :

var controls = new THREE.OrbitControls(camera, renderer.domElement);

im getting these errors

Cannot use import statement outside a module and THREE.OrbitControls is not a constructor

I added both threejs and orbitcontrols just before starting a new script. What am I doing wrong here?

```<code>
        <script src="scripts/three.js"></script>
        <script src="scripts/OrbitControls.js"></script>

        <script type="text/javascript">
                var scene = new THREE.Scene();

                var camera = new
                THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight, 0.1, 1000);

                var renderer = new THREE.WebGLRenderer();
                renderer.setSize(window.innerWidth, window.innerHeight);
                renderer.setClearColor(0x888888,1)
                document.body.appendChild(renderer.domElement);

                var controls = new THREE.OrbitControls(camera, renderer.domElement);

</code>```

答:
Jest solution

The examples that ship in the npm module have not been built and would need to be transformed.

Because I'm not testing these files themselves I just stub them out:

//jest.config.js
  moduleNameMapper: {
    'three/examples/jsm/': '<rootDir/config/jest/mockUndefined.js'
  }

//config/jest/mockUndefined.js
module.exports = undefined

```
<p>If you really need to include them in tests, a <code>ts-jest</code> solution would look like this:</p>
<pre class="lang-js prettyprint-override"><code>//jest.config.js
{
  //slow preset - does many extra transforms
  preset: 'ts-jest/presets/js-with-ts-esm',
  transformIgnorePatterns: ['/node_modules/(?!(three/examples/jsm)/)'],

</code>```

Be warned, the second solution is much slower as now jest has to transform many extra files.

Body:
Jest solution

The examples that ship in the npm module have not been built and would need to be transformed.

Because I'm not testing these files themselves I just stub them out:

//jest.config.js
  moduleNameMapper: {
    'three/examples/jsm/': '<rootDir/config/jest/mockUndefined.js'
  }

//config/jest/mockUndefined.js
module.exports = undefined

If you really need to include them in tests, a ts-jest solution would look like this:

//jest.config.js
{
  //slow preset - does many extra transforms
  preset: 'ts-jest/presets/js-with-ts-esm',
  transformIgnorePatterns: ['/node_modules/(?!(three/examples/jsm)/)'],

Be warned, the second solution is much slower as now jest has to transform many extra files.


问:
Randomly return items in array based on number
I'm trying to randomly display items from an array and I've been able to get it so that one item displays at random, now I want it to display a random number of items based on a number that I put in e.g when I input 2 I want 2 random items, when I input 5 I want 5 random items, etc...
How'd I go by this?

Code

```<code>const counter = 2; // Number of items I want to show
const Accounts = accountsData.sort(() => Math.random() - Math.random()).find(() => true); // This displays only one random item

<div className="text-area">
  {"Email: " + Accounts.email + " | Password: " + Accounts.password + " | Country: " + Accounts.country + " | Current Plan: " + Accounts.currentPlan + " | Has UHD: " + Accounts.hasUHD + " |  Max Streams: " + Accounts.maxStreams + " | Payment Method: " + Accounts.paymentMethod}
</div>
</code>```

答:
const fetchRandomValues = (arr) => (counter) =>
  [...Array(counter)].map(() => arr[Math.floor(Math.random() * arr.length)]);

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const values = fetchRandomValues(arr)(2);
console.log(values)```

Body:
I'm trying to randomly display items from an array and I've been able to get it so that one item displays at random, now I want it to display a random number of items based on a number that I put in e.g when I input 2 I want 2 random items, when I input 5 I want 5 random items, etc...
How'd I go by this?

Code

const counter = 2; // Number of items I want to show
const Accounts = accountsData.sort(() => Math.random() - Math.random()).find(() => true); // This displays only one random item

  {"Email: " + Accounts.email + " | Password: " + Accounts.password + " | Country: " + Accounts.country + " | Current Plan: " + Accounts.currentPlan + " | Has UHD: " + Accounts.hasUHD + " |  Max Streams: " + Accounts.maxStreams + " | Payment Method: " + Accounts.paymentMethod}


问:
How do I give a name to a primary key constraint?
I have (another) question about indexing.

I use the following code:

```<code>CREATE TABLE [dbo].[PnrDetails1](
        [OId] [int] IDENTITY(1,1) NOT NULL ,
    [file_name] [varchar](256) NOT NULL,
    [gds_id] [int] NOT NULL,
    [pnr_locator] [varchar](15) NOT NULL,
    [first_cust_name] [varchar](50) NOT NULL,
    [ticket_number] [varchar](20) NOT NULL,
    [full_price] [decimal](18, 0) NOT NULL,
    [currency_desc] [varchar](4) NOT NULL,
    [user_name] [varchar](50) NOT NULL,
    [save_time] [datetime] NOT NULL,
    [update_time] [datetime] NOT NULL,
    [clerk_id] [int] NOT NULL,
    [isUpdated] [bit] NOT NULL,
    [isDeleted] [bit] NOT NULL,
    [pnr_file_id] [int] NOT NULL
) ON [PRIMARY]

ALTER TABLE [dbo].[PnrDetails1] ADD PRIMARY KEY CLUSTERED
(
[OId] ASC
)ON [PRIMARY]
</code>```

this is actually a script sql server 2008 created for me,
but when I look at the object explorer I see an ugly name for the index (something like PK_PnrDetai_CB394B1958F2C25C). How can I change it? If so?

答:
You can (and you should) explicitly give a name to your primary key constraint:

```<code>ALTER TABLE [dbo].[PnrDetails1]
ADD CONSTRAINT PK_PnrDetails1
PRIMARY KEY CLUSTERED([OId] ASC) ON [PRIMARY]
</code>```

You can only do this at the time of creation - so in your case, you probably have to drop it first, and then re-create it with the proper, readable name.

Body:
I have (another) question about indexing.

I use the following code:

CREATE TABLE [dbo].[PnrDetails1](
        [OId] [int] IDENTITY(1,1) NOT NULL ,
    [file_name] [varchar](256) NOT NULL,
    [gds_id] [int] NOT NULL,
    [pnr_locator] [varchar](15) NOT NULL,
    [first_cust_name] [varchar](50) NOT NULL,
    [ticket_number] [varchar](20) NOT NULL,
    [full_price] [decimal](18, 0) NOT NULL,
    [currency_desc] [varchar](4) NOT NULL,
    [user_name] [varchar](50) NOT NULL,
    [save_time] [datetime] NOT NULL,
    [update_time] [datetime] NOT NULL,
    [clerk_id] [int] NOT NULL,
    [isUpdated] [bit] NOT NULL,
    [isDeleted] [bit] NOT NULL,
    [pnr_file_id] [int] NOT NULL
) ON [PRIMARY]

ALTER TABLE [dbo].[PnrDetails1] ADD PRIMARY KEY CLUSTERED
(
[OId] ASC
)ON [PRIMARY]

this is actually a script sql server 2008 created for me,
but when I look at the object explorer I see an ugly name for the index (something like PK_PnrDetai_CB394B1958F2C25C). How can I change it? If so?

Body:
You can (and you should) explicitly give a name to your primary key constraint:

ALTER TABLE [dbo].[PnrDetails1]
ADD CONSTRAINT PK_PnrDetails1
PRIMARY KEY CLUSTERED([OId] ASC) ON [PRIMARY]

You can only do this at the time of creation - so in your case, you probably have to drop it first, and then re-create it with the proper, readable name.


问:
AWS EC2 instance upgade - IP changes?
I'm thinking of upgrading my instance type in my AWS EC2. Will the IP change? If so, how do I retain the ip?

P.S I'm referring to the public IP

答:
As per Change the instance type - Amazon Elastic Compute Cloud:

Considerations for compatible instance types

Consider the following when changing the instance type of an existing instance:

You must stop your Amazon EBS-backed instance before you can change
its instance type. Ensure that you plan for downtime while your
instance is stopped. Stopping the instance and changing its instance
type might take a few minutes, and restarting your instance might
take a variable amount of time depending on your application's
startup scripts. For more information, see Stop and start your
instance.

When you stop and start an instance, we move the instance to new
hardware. If your instance has a public IPv4 address, we release the
address and give your instance a new public IPv4 address. If you
require a public IPv4 address that does not change, use an Elastic IP
address.

Title: AWS EC2 instance upgade - IP changes?


问:
Reading whole Google Spreadsheet with Sheets API v4 Java
I would like to read a Google Spreadsheet like described in the Java Quickstart

https://developers.google.com/sheets/quickstart/java

The Quickstart explaines how to read data from a give range

```<code>.....
String range = "Class Data!A2:E";
ValueRange response = service.spreadsheets().values()
        .get(spreadsheetId, range)
        .execute();

List<List<Object>> values = response.getValues();
....
</code>```

But I have the problem that I do not know the Range of the Spreadsheet. The number of columns can change. So how can I read for example all the data of the Sheet without knowing the range?

Regards

Michael

答:
If you are a little confused after @Bardy's answer (like me), then next line could help you (to get proper title of the Sheet):

```<code>response.getSheets().get(0).getProperties().getTitle();
</code>```

So, about topic, you can firstly get your Spreadsheet:

```<code>   Spreadsheet response = service
        .spreadsheets()
        .get(spreadsheetId)
        .execute();
</code>```

And then get ValueRange this way:

```<code>ValueRange response1 = service.spreadsheets().values()
        .get(spreadsheetId,response.getSheets().get(0).getProperties().getTitle())
    .execute();
</code>```

(Assuming you got only 1 sheet, otherwise try to debug/print all sheets with

```<code>response.getSheets()
</code>```

and then find the title of sheet you are using.

Body:
I would like to read a Google Spreadsheet like described in the Java Quickstart

https://developers.google.com/sheets/quickstart/java

The Quickstart explaines how to read data from a give range

.....
String range = "Class Data!A2:E";
ValueRange response = service.spreadsheets().values()
        .get(spreadsheetId, range)
        .execute();

List<List<Object>> values = response.getValues();
....

But I have the problem that I do not know the Range of the Spreadsheet. The number of columns can change. So how can I read for example all the data of the Sheet without knowing the range?

Regards

Michael

Body:
If you are a little confused after @Bardy's answer (like me), then next line could help you (to get proper title of the Sheet):

response.getSheets().get(0).getProperties().getTitle();

So, about topic, you can firstly get your Spreadsheet:

   Spreadsheet response = service
        .spreadsheets()
        .get(spreadsheetId)
        .execute();

And then get ValueRange this way:

ValueRange response1 = service.spreadsheets().values()
        .get(spreadsheetId,response.getSheets().get(0).getProperties().getTitle())
    .execute();

(Assuming you got only 1 sheet, otherwise try to debug/print all sheets with

response.getSheets()

and then find the title of sheet you are using.


问:
Why use get on generic function
Why can you have a getter on a generic function, and how to use it?</p>
```<code>T MyGenericFunc<T>(T x) {return x;} get what {
  print("what");
}

main(){
  var s = MyGenericFunc<String>("hey");
  print(s);
  // how to use the getter?
}
</code>```

答:
Why can you have a getter on a generic function

"Getter on a generic function" sounds like nonsense.  Your example is a getter that returns a generic function.

In most cases, you probably wouldn't want a getter that returns a function; you'd just define a function directly.  For example, it's pointless to do:

num Function(num x) get square {
  return (x) => x * x;
}
```
<p>when you instead could write:</p>
<pre class="lang-dart prettyprint-override"><code>num square(num x) {
  return x * x;
}
</code>```

with no difference to callers: in either case, they'd just call, for example, square(3).

However, there can be a difference if the getter does work before the returned function is invoked.  For example:

num Function(num x) get square {
  print('square');
  return (x) => x * x;
}

void main() {
  var f = square; // Prints: square
  print('Hello world!');
  var result = f(3); // Does not print.
  print(result); // Prints: 9
}
```
<p>would print:</p>
```square
Hello world!
9
```
<p>In contrast:</p>
<pre class="lang-dart prettyprint-override"><code>num square(num x) {
  print('square');
  return x * x;
}

void main() {
  var f = square; // Does not print.
  print('Hello world!');
  var result = f(3); // Prints: square
  print(result); // Prints: 9
}
</code>```

would print:

```<code>Hello world!
square
9
</code>```

In your example from your related question, the getter sets an internal flag (for what purpose, I don't know).

how to use it?

You'd call it like a function.  In your example, since what is a getter that returns a generic function, you'd call it as what<DesiredType>(argument).

Title: Why use get on generic function

Body:
Why can you have a getter on a generic function, and how to use it?

T MyGenericFunc<T>(T x) {return x;} get what {
  print("what");
}

main(){
  var s = MyGenericFunc<String>("hey");
  print(s);
  // how to use the getter?
}

Body:
Why can you have a getter on a generic function

"Getter on a generic function" sounds like nonsense.  Your example is a getter that returns a generic function.

In most cases, you probably wouldn't want a getter that returns a function; you'd just define a function directly.  For example, it's pointless to do:

num Function(num x) get square {
  return (x) => x * x;
}

when you instead could write:

num square(num x) {
  return x * x;
}

with no difference to callers: in either case, they'd just call, for example, square(3).

However, there can be a difference if the getter does work before the returned function is invoked.  For example:

num Function(num x) get square {
  print('square');
  return (x) => x * x;
}

void main() {
  var f = square; // Prints: square
  print('Hello world!');
  var result = f(3); // Does not print.
  print(result); // Prints: 9
}

would print:

square
Hello world!
9

In contrast:

num square(num x) {
  print('square');
  return x * x;
}

void main() {
  var f = square; // Does not print.
  print('Hello world!');
  var result = f(3); // Prints: square
  print(result); // Prints: 9
}

would print:

Hello world!
square
9

In your example from your related question, the getter sets an internal flag (for what purpose, I don't know).

how to use it?

You'd call it like a function.  In your example, since what is a getter that returns a generic function, you'd call it as what<DesiredType>(argument).


问:
Return mutable instance of entry of an object
I want to understand if it is allowed to get a mutable reference to an entry of a vector inside a struct in Rust.

I have a vector in a struct and I want to return a reference to one of its indexed fields.

Sample code:

```<code>
#[derive(Debug)]
pub struct Definition {
    v1: Vec<(String, i32)>,
}

impl Definition {
    fn new() -> Self {
        Self {
            v1: Vec::new(),
        }
    }

    fn insert_some_values(&mut self) {
        self.v1.push(("V1".to_string(), 0));
        self.v1.push(("V2".to_string(), 1));
        self.v1.push(("V3".to_string(), 2));
        self.v1.push(("V4".to_string(), 3));
    }

    fn search(&mut self, st: String) -> Result<&mut (String, i32), u32> {
        for i in &self.v1 {
            if st.eq(&i.0) {
                return Ok(I); // Is this supported in someway?
            }
        }
        return Err(0);
    }
}

fn main() {
    let mut def = Definition::new();
    def.insert_some_values();
    let res = def.search("V2".to_string());
    println!("{:?}", res);
}
</code>```

Obviously, it errors in compiling only:

```<code>   Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
  --> src/main.rs:23:27
   |
23 |                 return Ok(i);
   |                           ^ types differ in mutability
   |
   = note: expected mutable reference `&mut (String, i32)`
                      found reference `&(String, i32)`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` due to previous error
</code>```

But I want to understand if there is some way to support it?

Most likely, it is not supported since in this way, it is essentially losing part ownership of the field to the caller and that is not allowed. Perhaps only partial ownership of the individual items in a struct is allowed but not within the object.

But if it is supported, can someone please help?

Thanks!

Playground

答:
What you're trying to do is fine — you just missed one point:

    fn search(&mut self, st: String) -> Result<&mut (String, i32), u32> {
        for i in &mut self.v1 {   // HERE
            if st.eq(&i.0) {
                return Ok(i);
            }
        }
        return Err(0);
    }
```
<p>The loop must be written as <code>for i in &mut self.v1</code> (or, equivalently, <code>for i in self.v1.iter_mut()</code> so that the <code>i</code>s you iterate over are <code>&mut</code> references, not <code>&</code> references. With this change your code will compile and run.</p>
<hr />
<p>Some additional suggestions:</p>
<ul>
<li>Don't use unnecessary <code>return</code>s.</li>
<li>Use <code>==</code> instead of <code>.eq()</code>.</li>
<li>Don't return an error value that conveys no information — use <code>Option</code> instead.</li>
<li>Use <code>&str</code> instead of <code>String</code> so the caller is not obligated to pass in a string that will then be deallocated.</li>
</ul>
<pre class="lang-rust prettyprint-override"><code>    fn search(&mut self, st: &str) -> Option<&mut (String, i32)> {
        for i in self.v1.iter_mut() {
            if i.0.as_str() == st {
                return Some(i);
            }
        }
        None
    }
</code>```

You can also, if you choose, write the function using iterator methods alone. This is the same as the loop but might be more convenient and/or readable — not necessarily in this case, but in slightly more complex ones:

    fn search(&mut self, st: &str) -> Option<&mut (String, i32)> {
        self.v1.iter_mut().filter(|i| i.0.as_str() == st).next()
    }
```

Body:
I want to understand if it is allowed to get a mutable reference to an entry of a vector inside a struct in Rust.

I have a vector in a struct and I want to return a reference to one of its indexed fields.

Sample code:

#[derive(Debug)]
pub struct Definition {
    v1: Vec<(String, i32)>,
}

impl Definition {
    fn new() -> Self {
        Self {
            v1: Vec::new(),
        }
    }

    fn insert_some_values(&mut self) {
        self.v1.push(("V1".to_string(), 0));
        self.v1.push(("V2".to_string(), 1));
        self.v1.push(("V3".to_string(), 2));
        self.v1.push(("V4".to_string(), 3));
    }

    fn search(&mut self, st: String) -> Result<&mut (String, i32), u32> {
        for i in &self.v1 {
            if st.eq(&i.0) {
                return Ok(I); // Is this supported in someway?
            }
        }
        return Err(0);
    }
}

fn main() {
    let mut def = Definition::new();
    def.insert_some_values();
    let res = def.search("V2".to_string());
    println!("{:?}", res);
}

Obviously, it errors in compiling only:

   Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
  --> src/main.rs:23:27
   |
23 |                 return Ok(i);
   |                           ^ types differ in mutability
   |
   = note: expected mutable reference `&mut (String, i32)`
                      found reference `&(String, i32)`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` due to previous error

But I want to understand if there is some way to support it?

Most likely, it is not supported since in this way, it is essentially losing part ownership of the field to the caller and that is not allowed. Perhaps only partial ownership of the individual items in a struct is allowed but not within the object.

But if it is supported, can someone please help?

Thanks!

Playground

Body:
What you're trying to do is fine — you just missed one point:

    fn search(&mut self, st: String) -> Result<&mut (String, i32), u32> {
        for i in &mut self.v1 {   // HERE
            if st.eq(&i.0) {
                return Ok(i);
            }
        }
        return Err(0);
    }

The loop must be written as for i in &mut self.v1 (or, equivalently, for i in self.v1.iter_mut() so that the is you iterate over are &mut references, not & references. With this change your code will compile and run.

Some additional suggestions:

Don't use unnecessary returns.

Use == instead of .eq().

Don't return an error value that conveys no information — use Option instead.

Use &str instead of String so the caller is not obligated to pass in a string that will then be deallocated.

    fn search(&mut self, st: &str) -> Option<&mut (String, i32)> {
        for i in self.v1.iter_mut() {
            if i.0.as_str() == st {
                return Some(i);
            }
        }
        None
    }

You can also, if you choose, write the function using iterator methods alone. This is the same as the loop but might be more convenient and/or readable — not necessarily in this case, but in slightly more complex ones:

    fn search(&mut self, st: &str) -> Option<&mut (String, i32)> {
        self.v1.iter_mut().filter(|i| i.0.as_str() == st).next()
    }


问:
Proportions using prop.table
I'm working on an assignment and wanted to double check to ensure I performed this code correctly. The question asked: What proportion of female infants were born by abdominal method of delivery?

```<code>table(SB_xlsx$sex)
##
## female   male
##    320    330
table(SB_xlsx$delivery)
##
## abdominal   vaginal
##       314       335
prop.table(table(SB_xlsx$sex, SB_xlsx$delivery))
##
##          abdominal   vaginal
##   female 0.2426584 0.2503864
##   male   0.2395672 0.2673879
</code>```

Have I done this correctly to say the proportion of female infants that were born through abdominal means is 0.24? I wanted to double check!

EDIT: Thank you to those who helped, this was my final solution!

```<code>library(dplyr)
SB_xlsx <- SB_xlsx %>% filter(sex=="female")
prop.table(table(SB_xlsx$sex, SB_xlsx$delivery))
##
##          abdominal  vaginal
##   female  0.492163 0.507837
</code>```

答:
It's partially completed. You can apply a filter before calculating the proportions like this:

```<code>library(dplyr)

SB_xlsx <- SB_xlsx %>% filter(sex=="female")

prop.table(table(SB_xlsx$sex, SB_xlsx$delivery))
</code>```

Now you make sure that only females are measured.

Title: Proportions using prop.table

Body:
I'm working on an assignment and wanted to double check to ensure I performed this code correctly. The question asked: What proportion of female infants were born by abdominal method of delivery?

table(SB_xlsx$sex)
##
## female   male
##    320    330
table(SB_xlsx$delivery)
##
## abdominal   vaginal
##       314       335
prop.table(table(SB_xlsx$sex, SB_xlsx$delivery))
##
##          abdominal   vaginal
##   female 0.2426584 0.2503864
##   male   0.2395672 0.2673879

Have I done this correctly to say the proportion of female infants that were born through abdominal means is 0.24? I wanted to double check!

EDIT: Thank you to those who helped, this was my final solution!

library(dplyr)
SB_xlsx <- SB_xlsx %>% filter(sex=="female")
prop.table(table(SB_xlsx$sex, SB_xlsx$delivery))
##
##          abdominal  vaginal
##   female  0.492163 0.507837

Body:
It's partially completed. You can apply a filter before calculating the proportions like this:

library(dplyr)

SB_xlsx <- SB_xlsx %>% filter(sex=="female")

prop.table(table(SB_xlsx$sex, SB_xlsx$delivery))

Now you make sure that only females are measured.


问:
Rails / Rename or move files
I found a couple of different ways to move a file with ROR, but I couldnt get it to work, whats the best and simplest way to move or rename a file ? </p>

答:
You can use the standard method:

```<code>File.rename(old_name, new_name)
</code>```

Or you can use FileUtils which offers additional functionality.

Title: Rails / Rename or move files

Body:
You can use the standard method:

File.rename(old_name, new_name)

Or you can use FileUtils which offers additional functionality.