问:
Custom divi builder child module not rendering
I am trying to create some custom Divi builder modules.
I followed the sparse documentation at their website, trying to create a module and a child module. Everything seems to be working fine, but the rendering.
It is just rendering the module shortcode as a string, and not the content.

Current code of the parent module is

```<code>class DEDE_Cards extends ET_Builder_Module {

public function init(){
    $this->name = esc_html__('Custom Card', 'dede-designvox-divi-extension');
    $this->plural = esc_html__('Custom Cards', 'dede-designvox-divi-extension');
    $this->main_css_element = 'cards-wrapper';
    $this->slug = 'dede_cards';
    $this->vb_support = 'on';
    $this->child_slug = 'dede_card_item';
}

public function get_fields(){
    return array(
        'title' => array(
            'label'           => esc_html__( 'Title', 'dede-designvox-divi-extension' ),
            'type'            => 'text',
            'toggle_slug'     => 'main_content',
            'description'     => esc_html__( 'Type the section title' ),
        ),
        'card_title_position' => array(
            'label'           => esc_html__( 'Title Position', 'dede-designvox-divi-extension' ),
            'type'            => 'select',
            'options'         => array(
                'overlay' => esc_html__( 'Overlay', 'et_builder' ),
                'top'  => esc_html__( 'Over image', 'et_builder' ),
                'bottom'  => esc_html__( 'Under image', 'et_builder' ),
            ),
            'toggle_slug'     => 'main_content',
            'description'     => esc_html__( 'Here you can choose the position of the card title', 'dede-designvox-divi-extension' ),
            'default_on_front' => 'bottom',
        ),
    );
}

function before_render() {
    global $dede_card_item_number;
    $dede_card_item_number = 1;
}

public function render($unprocessed_props, $content = null, $render_slug ){
    global $dede_card_item_number;

    return sprintf(
        '<div>%1$s</div>',
        $this->content
    );
}

public function add_new_child_text() {
    return esc_html__( 'Add New Card Item1', 'dede-designvox-divi-extension' );
}

}

new DEDE_Cards;
</code>```

And then the child module

```<code>class DEDE_Card_Item extends ET_Builder_Module {

    public function init(){
        $this->name = esc_html__('Custom Card', 'dede-designvox-divi-extension');
        $this->plural = esc_html__('Custom Cards', 'dede-designvox-divi-extension');
        $this->type= 'child';
        $this->child_title_var = 'title';
        $this->no_render = true;
        $this->slug = 'dede_card_item';
        $this->vb_support = 'on';
    }

    public function get_fields(){
        return array(
            'title' => array(
                'label' => esc_html__('Title', 'dede-designvox-divi-extension'),
                'type' => 'text',
                'description' => esc_html__('The title of this card', 'dede-designvox-divi-extension'),
                'toggle_slug' => 'main_content',
            ),
            'desc' => array(
                'label'           => esc_html__( 'Description', 'dede-designvox-divi-extension' ),
                'type'            => 'textarea',
                'description'     => esc_html__( 'The card description' ),
                'toggle_slug'     => 'main_content',
            ),
            'src'     => array(
                'label'           => esc_html__( 'Image', 'dede-designvox-divi-extension'),
                'type'            => 'upload',
                'description'     => esc_html__( 'Upload your desired image, or type in the URL to the image', 'dede-designvox-divi-extension'),
                'upload_button_text' => esc_attr__('Upload an image', 'dede-designvox-divi-extension'),
                'choose_text' => esc_attr__('Choose an Image', 'dede-designvox-divi-extension'),
                'update_text' => esc_attr__('Set as Image', 'dede-designvox-divi-extension'),
                'affects'         => 'alt',
                'toggle_slug'     => 'main_content',
            ),
            'alt' => array(
                'label'           => esc_html__( 'Image Alternative Text', 'dede-designvox-divi-extension' ),
                'type'            => 'text',
                'depends_show_if' => 'on',
                'depends_on'      => array(
                    'src',
                ),
                'description'     => esc_html__( 'This defines the HTML ALT text. A short description of your image can be placed here.', 'dede-designvox-divi-extension' ),
                'toggle_slug'     => 'main_content',
            ),
            'url' => array(
                'label'           => esc_html__( 'Link URL', 'dede-designvox-divi-extension' ),
                'type'            => 'text',
                'description'     => esc_html__( 'Enter the link that you would like this card to direct to.', 'dede-designvox-divi-extension' ),
                'toggle_slug'     => 'main_content',
            ),
        );
    }

}

new DEDE_Card_Item;
</code>```

The shortcode is just being rendered as a string on the website, like:

```<code>[dede_card_item _builder_version=”3.14″ title=”#1 card title” desc=”#1 card desc” src=”http://localhost:8888/wp-content/uploads/2018/09/14079861_1202408189819777_4296465020285869305_n.jpg” use_background_color_gradient=”off” background_color_gradient_start=”#2b87da” background_color_gradient_end=”#29c4a9″ background_color_gradient_type=”linear” background_color_gradient_direction=”180deg” background_color_gradient_direction_radial=”center” background_color_gradient_start_position=”0%” background_color_gradient_end_position=”100%” background_color_gradient_overlays_image=”off” parallax=”off” parallax_method=”on” background_size=”cover” background_position=”center” background_repeat=”no-repeat” background_blend=”normal” allow_player_pause=”off” background_video_pause_outside_viewport=”on” text_shadow_style=”none” module_text_shadow_style=”none” box_shadow_style=”none” /][dede_card_item _builder_version=”3.14″ title=”#1 card title” desc=”#1 card desc” src=”http://localhost:8888/wp-content/uploads/2018/09/14079861_1202408189819777_4296465020285869305_n.jpg” use_background_color_gradient=”off” background_color_gradient_start=”#2b87da” background_color_gradient_end=”#29c4a9″ background_color_gradient_type=”linear” background_color_gradient_direction=”180deg” background_color_gradient_direction_radial=”center” background_color_gradient_start_position=”0%” background_color_gradient_end_position=”100%” background_color_gradient_overlays_image=”off” parallax=”off” parallax_method=”on” background_size=”cover” background_position=”center” background_repeat=”no-repeat” background_blend=”normal” allow_player_pause=”off” background_video_pause_outside_viewport=”on” text_shadow_style=”none” module_text_shadow_style=”none” box_shadow_style=”none” /][dede_card_item _builder_version=”3.14″ title=”#1 card title” desc=”#1 card desc” src=”http://localhost:8888/wp-content/uploads/2018/09/14079861_1202408189819777_4296465020285869305_n.jpg” use_background_color_gradient=”off” background_color_gradient_start=”#2b87da” background_color_gradient_end=”#29c4a9″ background_color_gradient_type=”linear” background_color_gradient_direction=”180deg” background_color_gradient_direction_radial=”center” background_color_gradient_start_position=”0%” background_color_gradient_end_position=”100%” background_color_gradient_overlays_image=”off” parallax=”off” parallax_method=”on” background_size=”cover” background_position=”center” background_repeat=”no-repeat” background_blend=”normal” allow_player_pause=”off” background_video_pause_outside_viewport=”on” text_shadow_style=”none” module_text_shadow_style=”none” box_shadow_style=”none” /][dede_card_item _builder_version=”3.14″ title=”#1 card title” desc=”#1 card desc” src=”http://localhost:8888/wp-content/uploads/2018/09/14079861_1202408189819777_4296465020285869305_n.jpg” use_background_color_gradient=”off” background_color_gradient_start=”#2b87da” background_color_gradient_end=”#29c4a9″ background_color_gradient_type=”linear” background_color_gradient_direction=”180deg” background_color_gradient_direction_radial=”center” background_color_gradient_start_position=”0%” background_color_gradient_end_position=”100%” background_color_gradient_overlays_image=”off” parallax=”off” parallax_method=”on” background_size=”cover” background_position=”center” background_repeat=”no-repeat” background_blend=”normal” allow_player_pause=”off” background_video_pause_outside_viewport=”on” text_shadow_style=”none” module_text_shadow_style=”none” box_shadow_style=”none” /]
</code>```

答:
it's working for me you can try it,

Parents modules::

```<code><?php
class GRDI_Barchart extends ET_Builder_Module {

    public $slug       = 'grdi_bar_chart';
    public $vb_support = 'on';

    protected $module_credits = array(
        'module_uri' => '',
        'author'     => '',
        'author_uri' => '',
    );

    public function init() {

        $this->name = esc_html__( 'Bar Chart', 'grdi-graphina-divi' );
        $this->plural     = esc_html__( 'Bar Chart', 'et_builder' );
        $this->slug       = 'grdi_bar_chart';
        $this->vb_support = 'on';
        $this->child_slug = 'grdi_bar_chart_child';

        $this->settings_modal_toggles = array(
            'general'  => array(
                'toggles' => array(
                    'main_content' => esc_html__( 'Graphina Text', 'dsm-supreme-modules-for-divi' ),
                ),
            ),
            'advanced' => array(
                'toggles' => array(
                    'separator' => array(
                        'title'    => esc_html__( 'Separator', 'dsm-supreme-modules-for-divi' ),
                        'priority' => 70,
                    ),
                    'image'     => array(
                        'title'    => esc_html__( 'Image', 'dsm-supreme-modules-for-divi' ),
                        'priority' => 69,
                    ),
                ),
            ),
        );
    }

    public function get_fields() {
        return array(
            'title' => array(
                'label'           => esc_html__( 'Title', 'grdi-graphina-divi' ),
                'type'            => 'text',
                'option_category' => 'basic_option',
                'description'     => esc_html__( 'Input your desired heading here.', 'simp-simple-extension' ),
                'toggle_slug'     => 'main_content',
            ),
            'content' => array(
                'label'           => esc_html__( 'Description', 'grdi-graphina-divi' ),
                'type'            => 'tiny_mce',
                'option_category' => 'basic_option',
                'description'     => esc_html__( 'Content entered here will appear inside the module.', 'grdi-graphina-divi' ),
                'toggle_slug'     => 'main_content',
            ),
        );
    }

    public function get_advanced_fields_config() {
        return array();
    }

    public function get_charts(){
        echo "charts";
    }

    public function render( $attrs, $content = null, $render_slug ) {

        wp_enqueue_script( 'graphina_apex_chart_script' );
        wp_enqueue_style( 'graphina_apex_chart_style' );
        wp_enqueue_style( 'graphina-public' );

        echo "<pre/>";

        $var = "<script>
            var options = {
                series: [{
                    name: 'Sales',
                    data: [4, 3, 10, 9, 29, 19, 22, 9, 12, 7, 19, 5, 13, 9, 17, 2, 7, 5]
                }],
                chart: {
                    type: 'bar',
                    height: 350
                  },
                  plotOptions: {
                    bar: {
                      borderRadius: 4,
                      horizontal: true,
                    }
                  },
                  dataLabels: {
                    enabled: false
                  },
                  xaxis: {
                    categories: ['South Korea', 'Canada', 'United Kingdom', 'Netherlands', 'Italy', 'France', 'Japan',
                      'United States', 'China', 'Germany'
                    ],
                }
            };
            var chart = new ApexCharts(document.querySelector('#charts'), options);
            chart.render();
        </script>" ;

        $html = sprintf(
            '<h1>%1$s</h1>
            <p>%2$s</p>
            <div id="charts"></div>',
            $this->props['title'],
            $this->props['content']
        );

        echo $html ;
        echo $var ;

    }
}

new GRDI_Barchart;
</code>```

Child Modules::

```<code><?php

class GRDI_BarchartChild extends ET_Builder_Module {
    function init() {
        $this->name             = esc_html__( 'Bar Chart Items', 'et_builder' );
        $this->plural           = esc_html__( 'Bar Chart Items', 'et_builder' );
        $this->slug             = 'grdi_bar_chart_child';
        $this->vb_support       = 'on';
        $this->type             = 'child';
        $this->child_title_var  = 'title';
        $this->no_render        = true;
        $this->settings_text    = esc_html__( 'Bar Chart Settings', 'et_builder' );

        $this->settings_modal_toggles = array(
            'general'  => array(
                'toggles' => array(
                    'main_content' => et_builder_i18n( 'Text' ),
                ),
            ),
            'advanced' => array(
                'toggles' => array(
                    'icon'          => esc_html__( 'Icon', 'et_builder' ),
                    'toggle_layout' => esc_html__( 'Toggle', 'et_builder' ),
                    'text'          => array(
                        'title'    => et_builder_i18n( 'Text' ),
                        'priority' => 49,
                    ),
                ),
            ),
        );

    }

    function get_fields() {
        $fields = array(
            'child_title'       => array(
                'label'           => et_builder_i18n( 'Data Label' ),
                'type'            => 'text',
                'option_category' => 'basic_option',
                'description'     => esc_html__( 'Data Label', 'et_builder' ),
                'toggle_slug'     => 'main_content',
                'dynamic_content' => 'text',
                'hover'           => 'tabs',
                'mobile_options'  => true,
            ),
            'child_content'                        => array(
                'label'           => et_builder_i18n( 'Data Value' ),
                'type'            => 'text',
                'option_category' => 'basic_option',
                'description'     => esc_html__( 'Data Value', 'et_builder' ),
                'toggle_slug'     => 'main_content',
                'dynamic_content' => 'text',
                'hover'           => 'tabs',
                'mobile_options'  => true,
            ),
        );

        return $fields;
    }

    function render($attrs, $content, $render_slug){
        $output  = sprintf(
            '<h1>%1$s</h1>
            <p>%2$s</p>',
            $this->props['child_title'],
            $this->props['child_content']
        );

        return $output;
    }
}

if ( et_builder_should_load_all_module_data() ) {
    new GRDI_BarchartChild();
}

</code>```

Body:
I am trying to create some custom Divi builder modules.
I followed the sparse documentation at their website, trying to create a module and a child module. Everything seems to be working fine, but the rendering.
It is just rendering the module shortcode as a string, and not the content.

Current code of the parent module is

class DEDE_Cards extends ET_Builder_Module {

public function init(){
    $this->name = esc_html__('Custom Card', 'dede-designvox-divi-extension');
    $this->plural = esc_html__('Custom Cards', 'dede-designvox-divi-extension');
    $this->main_css_element = 'cards-wrapper';
    $this->slug = 'dede_cards';
    $this->vb_support = 'on';
    $this->child_slug = 'dede_card_item';
}

public function get_fields(){
    return array(
        'title' => array(
            'label'           => esc_html__( 'Title', 'dede-designvox-divi-extension' ),
            'type'            => 'text',
            'toggle_slug'     => 'main_content',
            'description'     => esc_html__( 'Type the section title' ),
        ),
        'card_title_position' => array(
            'label'           => esc_html__( 'Title Position', 'dede-designvox-divi-extension' ),
            'type'            => 'select',
            'options'         => array(
                'overlay' => esc_html__( 'Overlay', 'et_builder' ),
                'top'  => esc_html__( 'Over image', 'et_builder' ),
                'bottom'  => esc_html__( 'Under image', 'et_builder' ),
            ),
            'toggle_slug'     => 'main_content',
            'description'     => esc_html__( 'Here you can choose the position of the card title', 'dede-designvox-divi-extension' ),
            'default_on_front' => 'bottom',
        ),
    );
}

function before_render() {
    global $dede_card_item_number;
    $dede_card_item_number = 1;
}

public function render($unprocessed_props, $content = null, $render_slug ){
    global $dede_card_item_number;

    return sprintf(
        '
%1$s
',
        $this->content
    );
}

public function add_new_child_text() {
    return esc_html__( 'Add New Card Item1', 'dede-designvox-divi-extension' );
}

}

new DEDE_Cards;

And then the child module

class DEDE_Card_Item extends ET_Builder_Module {

    public function init(){
        $this->name = esc_html__('Custom Card', 'dede-designvox-divi-extension');
        $this->plural = esc_html__('Custom Cards', 'dede-designvox-divi-extension');
        $this->type= 'child';
        $this->child_title_var = 'title';
        $this->no_render = true;
        $this->slug = 'dede_card_item';
        $this->vb_support = 'on';
    }

    public function get_fields(){
        return array(
            'title' => array(
                'label' => esc_html__('Title', 'dede-designvox-divi-extension'),
                'type' => 'text',
                'description' => esc_html__('The title of this card', 'dede-designvox-divi-extension'),
                'toggle_slug' => 'main_content',
            ),
            'desc' => array(
                'label'           => esc_html__( 'Description', 'dede-designvox-divi-extension' ),
                'type'            => 'textarea',
                'description'     => esc_html__( 'The card description' ),
                'toggle_slug'     => 'main_content',
            ),
            'src'     => array(
                'label'           => esc_html__( 'Image', 'dede-designvox-divi-extension'),
                'type'            => 'upload',
                'description'     => esc_html__( 'Upload your desired image, or type in the URL to the image', 'dede-designvox-divi-extension'),
                'upload_button_text' => esc_attr__('Upload an image', 'dede-designvox-divi-extension'),
                'choose_text' => esc_attr__('Choose an Image', 'dede-designvox-divi-extension'),
                'update_text' => esc_attr__('Set as Image', 'dede-designvox-divi-extension'),
                'affects'         => 'alt',
                'toggle_slug'     => 'main_content',
            ),
            'alt' => array(
                'label'           => esc_html__( 'Image Alternative Text', 'dede-designvox-divi-extension' ),
                'type'            => 'text',
                'depends_show_if' => 'on',
                'depends_on'      => array(
                    'src',
                ),
                'description'     => esc_html__( 'This defines the HTML ALT text. A short description of your image can be placed here.', 'dede-designvox-divi-extension' ),
                'toggle_slug'     => 'main_content',
            ),
            'url' => array(
                'label'           => esc_html__( 'Link URL', 'dede-designvox-divi-extension' ),
                'type'            => 'text',
                'description'     => esc_html__( 'Enter the link that you would like this card to direct to.', 'dede-designvox-divi-extension' ),
                'toggle_slug'     => 'main_content',
            ),
        );
    }

}

new DEDE_Card_Item;

The shortcode is just being rendered as a string on the website, like:

[dede_card_item _builder_version=”3.14″ title=”#1 card title” desc=”#1 card desc” src=”http://localhost:8888/wp-content/uploads/2018/09/14079861_1202408189819777_4296465020285869305_n.jpg” use_background_color_gradient=”off” background_color_gradient_start=”#2b87da” background_color_gradient_end=”#29c4a9″ background_color_gradient_type=”linear” background_color_gradient_direction=”180deg” background_color_gradient_direction_radial=”center” background_color_gradient_start_position=”0%” background_color_gradient_end_position=”100%” background_color_gradient_overlays_image=”off” parallax=”off” parallax_method=”on” background_size=”cover” background_position=”center” background_repeat=”no-repeat” background_blend=”normal” allow_player_pause=”off” background_video_pause_outside_viewport=”on” text_shadow_style=”none” module_text_shadow_style=”none” box_shadow_style=”none” /][dede_card_item _builder_version=”3.14″ title=”#1 card title” desc=”#1 card desc” src=”http://localhost:8888/wp-content/uploads/2018/09/14079861_1202408189819777_4296465020285869305_n.jpg” use_background_color_gradient=”off” background_color_gradient_start=”#2b87da” background_color_gradient_end=”#29c4a9″ background_color_gradient_type=”linear” background_color_gradient_direction=”180deg” background_color_gradient_direction_radial=”center” background_color_gradient_start_position=”0%” background_color_gradient_end_position=”100%” background_color_gradient_overlays_image=”off” parallax=”off” parallax_method=”on” background_size=”cover” background_position=”center” background_repeat=”no-repeat” background_blend=”normal” allow_player_pause=”off” background_video_pause_outside_viewport=”on” text_shadow_style=”none” module_text_shadow_style=”none” box_shadow_style=”none” /][dede_card_item _builder_version=”3.14″ title=”#1 card title” desc=”#1 card desc” src=”http://localhost:8888/wp-content/uploads/2018/09/14079861_1202408189819777_4296465020285869305_n.jpg” use_background_color_gradient=”off” background_color_gradient_start=”#2b87da” background_color_gradient_end=”#29c4a9″ background_color_gradient_type=”linear” background_color_gradient_direction=”180deg” background_color_gradient_direction_radial=”center” background_color_gradient_start_position=”0%” background_color_gradient_end_position=”100%” background_color_gradient_overlays_image=”off” parallax=”off” parallax_method=”on” background_size=”cover” background_position=”center” background_repeat=”no-repeat” background_blend=”normal” allow_player_pause=”off” background_video_pause_outside_viewport=”on” text_shadow_style=”none” module_text_shadow_style=”none” box_shadow_style=”none” /][dede_card_item _builder_version=”3.14″ title=”#1 card title” desc=”#1 card desc” src=”http://localhost:8888/wp-content/uploads/2018/09/14079861_1202408189819777_4296465020285869305_n.jpg” use_background_color_gradient=”off” background_color_gradient_start=”#2b87da” background_color_gradient_end=”#29c4a9″ background_color_gradient_type=”linear” background_color_gradient_direction=”180deg” background_color_gradient_direction_radial=”center” background_color_gradient_start_position=”0%” background_color_gradient_end_position=”100%” background_color_gradient_overlays_image=”off” parallax=”off” parallax_method=”on” background_size=”cover” background_position=”center” background_repeat=”no-repeat” background_blend=”normal” allow_player_pause=”off” background_video_pause_outside_viewport=”on” text_shadow_style=”none” module_text_shadow_style=”none” box_shadow_style=”none” /]

Body:
it's working for me you can try it,

Parents modules::

<?php
class GRDI_Barchart extends ET_Builder_Module {

    public $slug       = 'grdi_bar_chart';
    public $vb_support = 'on';

    protected $module_credits = array(
        'module_uri' => '',
        'author'     => '',
        'author_uri' => '',
    );

    public function init() {

        $this->name = esc_html__( 'Bar Chart', 'grdi-graphina-divi' );
        $this->plural     = esc_html__( 'Bar Chart', 'et_builder' );
        $this->slug       = 'grdi_bar_chart';
        $this->vb_support = 'on';
        $this->child_slug = 'grdi_bar_chart_child';

        $this->settings_modal_toggles = array(
            'general'  => array(
                'toggles' => array(
                    'main_content' => esc_html__( 'Graphina Text', 'dsm-supreme-modules-for-divi' ),
                ),
            ),
            'advanced' => array(
                'toggles' => array(
                    'separator' => array(
                        'title'    => esc_html__( 'Separator', 'dsm-supreme-modules-for-divi' ),
                        'priority' => 70,
                    ),
                    'image'     => array(
                        'title'    => esc_html__( 'Image', 'dsm-supreme-modules-for-divi' ),
                        'priority' => 69,
                    ),
                ),
            ),
        );
    }

    public function get_fields() {
        return array(
            'title' => array(
                'label'           => esc_html__( 'Title', 'grdi-graphina-divi' ),
                'type'            => 'text',
                'option_category' => 'basic_option',
                'description'     => esc_html__( 'Input your desired heading here.', 'simp-simple-extension' ),
                'toggle_slug'     => 'main_content',
            ),
            'content' => array(
                'label'           => esc_html__( 'Description', 'grdi-graphina-divi' ),
                'type'            => 'tiny_mce',
                'option_category' => 'basic_option',
                'description'     => esc_html__( 'Content entered here will appear inside the module.', 'grdi-graphina-divi' ),
                'toggle_slug'     => 'main_content',
            ),
        );
    }

    public function get_advanced_fields_config() {
        return array();
    }

    public function get_charts(){
        echo "charts";
    }

    public function render( $attrs, $content = null, $render_slug ) {

        wp_enqueue_script( 'graphina_apex_chart_script' );
        wp_enqueue_style( 'graphina_apex_chart_style' );
        wp_enqueue_style( 'graphina-public' );

        echo "<pre/>";

        $var = "<script>
            var options = {
                series: [{
                    name: 'Sales',
                    data: [4, 3, 10, 9, 29, 19, 22, 9, 12, 7, 19, 5, 13, 9, 17, 2, 7, 5]
                }],
                chart: {
                    type: 'bar',
                    height: 350
                  },
                  plotOptions: {
                    bar: {
                      borderRadius: 4,
                      horizontal: true,
                    }
                  },
                  dataLabels: {
                    enabled: false
                  },
                  xaxis: {
                    categories: ['South Korea', 'Canada', 'United Kingdom', 'Netherlands', 'Italy', 'France', 'Japan',
                      'United States', 'China', 'Germany'
                    ],
                }
            };
            var chart = new ApexCharts(document.querySelector('#charts'), options);
            chart.render();
        </script>" ;

        $html = sprintf(
            '<h1>%1$s</h1>
            <p>%2$s</p>
            <div id="charts"></div>',
            $this->props['title'],
            $this->props['content']
        );

        echo $html ;
        echo $var ;

    }
}

new GRDI_Barchart;

Child Modules::

<?php

class GRDI_BarchartChild extends ET_Builder_Module {
    function init() {
        $this->name             = esc_html__( 'Bar Chart Items', 'et_builder' );
        $this->plural           = esc_html__( 'Bar Chart Items', 'et_builder' );
        $this->slug             = 'grdi_bar_chart_child';
        $this->vb_support       = 'on';
        $this->type             = 'child';
        $this->child_title_var  = 'title';
        $this->no_render        = true;
        $this->settings_text    = esc_html__( 'Bar Chart Settings', 'et_builder' );

        $this->settings_modal_toggles = array(
            'general'  => array(
                'toggles' => array(
                    'main_content' => et_builder_i18n( 'Text' ),
                ),
            ),
            'advanced' => array(
                'toggles' => array(
                    'icon'          => esc_html__( 'Icon', 'et_builder' ),
                    'toggle_layout' => esc_html__( 'Toggle', 'et_builder' ),
                    'text'          => array(
                        'title'    => et_builder_i18n( 'Text' ),
                        'priority' => 49,
                    ),
                ),
            ),
        );

    }

    function get_fields() {
        $fields = array(
            'child_title'       => array(
                'label'           => et_builder_i18n( 'Data Label' ),
                'type'            => 'text',
                'option_category' => 'basic_option',
                'description'     => esc_html__( 'Data Label', 'et_builder' ),
                'toggle_slug'     => 'main_content',
                'dynamic_content' => 'text',
                'hover'           => 'tabs',
                'mobile_options'  => true,
            ),
            'child_content'                        => array(
                'label'           => et_builder_i18n( 'Data Value' ),
                'type'            => 'text',
                'option_category' => 'basic_option',
                'description'     => esc_html__( 'Data Value', 'et_builder' ),
                'toggle_slug'     => 'main_content',
                'dynamic_content' => 'text',
                'hover'           => 'tabs',
                'mobile_options'  => true,
            ),
        );

        return $fields;
    }

    function render($attrs, $content, $render_slug){
        $output  = sprintf(
            '<h1>%1$s</h1>
            <p>%2$s</p>',
            $this->props['child_title'],
            $this->props['child_content']
        );

        return $output;
    }
}

if ( et_builder_should_load_all_module_data() ) {
    new GRDI_BarchartChild();
}


来源: stackexchange

问:
Express + Sequelize + bcrypt => question about scaffolding vis a vis inability to validate password
I'm trying to learn how to control sequelize on Node.js and i've created a terse register/login, atm I can't access my user.validPassword() method.

Application works great to include all process', the only issue is with password validation.

/index.js

```<code>const initConnection = async function () {
    httpsServer.listen(port, () => {
        console.log(`listening at https://localhost:${port}`)
    });

    //db ops
    const db = require("./models");
    await db.sequelize.sync();

}
</code>```

/models/index.js

```<code>const dbConfig = require("../config/db.config.js");

const Sequelize = require("sequelize");

const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
    host: dbConfig.HOST,
    dialect: dbConfig.dialect,
    operatorsAliases: false,

    pool: {
        max: dbConfig.pool.max,
        min: dbConfig.pool.min,
        acquire: dbConfig.pool.acquire,
        idle: dbConfig.pool.idle
    }
});

const db = {};

db.Sequelize = Sequelize;
db.sequelize = sequelize;

db.User = require("./User.model.js")(sequelize, Sequelize);
console.log({user: db.User});

module.exports = db;
</code>```

/models/User.model.js

```<code>const bcrypt = require("bcrypt");

module.exports = (sequelize, Sequelize) => {
    return sequelize.define("user", {
        name: {
            type: Sequelize.STRING,
            allowNull: 0,

        },
        email: {
            type: Sequelize.STRING,
            allowNull: 0,
        },
        password: {
            type: Sequelize.STRING,
            allowNull: 0,
        },

    },{
        hooks: {
            beforeCreate: async (user) => {
                if (user.password) {
                    const salt = await bcrypt.genSaltSync(10, 'a');
                    user.password = bcrypt.hashSync(user.password, salt);
                }
            },
            beforeUpdate:async (user) => {
                if (user.password) {
                    const salt = await bcrypt.genSaltSync(10, 'a');
                    user.password = bcrypt.hashSync(user.password, salt);
                }
            }
        },
        instanceMethods: {
            validPassword: (password) => {
                return bcrypt.compareSync(password, this.password);
            }
        }
    });
</code>```

/controllers/User.controller.js

```<code>const db = require("../models");
const path = require("path");
const User = db.User;
const Op = db.Sequelize.Op; //sql operators

exports.login = (req, res) => {
    const user = {
        email: req.body.email,
        password: req.body.password,
    };

    const isValidated = User.validPassword(user.password);
    console.log({isValidated});
};
</code>```

Error: TypeError: User.validPassword is not a function

I'm trying to wrap my head around this for last couple of hours with no avail.

Thanks,
Bud

答:
sequelize version >4 is changed the way instance methods are defined.

you can also refer to this link

```<code>const bcrypt = require("bcrypt");

module.exports = (sequelize, Sequelize) => {
    const User = sequelize.define("user", {
        name: {
            type: Sequelize.STRING,
            allowNull: 0,

        },
        email: {
            type: Sequelize.STRING,
            allowNull: 0,
        },
        password: {
            type: Sequelize.STRING,
            allowNull: 0,
        },

    }, {
        hooks: {
            beforeCreate: async (user) => {
                if (user.password) {
                    const salt = await bcrypt.genSaltSync(10, 'a');
                    user.password = bcrypt.hashSync(user.password, salt);
                }
            },
            beforeUpdate: async (user) => {
                if (user.password) {
                    const salt = await bcrypt.genSaltSync(10, 'a');
                    user.password = bcrypt.hashSync(user.password, salt);
                }
            }
        }
    })
    User.validPassword = (password) => {
        return bcrypt.compareSync(password, this.password);
    }
    return User;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to learn how to control sequelize on Node.js and i've created a terse register/login, atm I can't access my user.validPassword() method.

Application works great to include all process', the only issue is with password validation.

/index.js

const initConnection = async function () {
    httpsServer.listen(port, () => {
        console.log(`listening at https://localhost:${port}`)
    });

    //db ops
    const db = require("./models");
    await db.sequelize.sync();

}

/models/index.js

const dbConfig = require("../config/db.config.js");

const Sequelize = require("sequelize");

const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
    host: dbConfig.HOST,
    dialect: dbConfig.dialect,
    operatorsAliases: false,

    pool: {
        max: dbConfig.pool.max,
        min: dbConfig.pool.min,
        acquire: dbConfig.pool.acquire,
        idle: dbConfig.pool.idle
    }
});

const db = {};

db.Sequelize = Sequelize;
db.sequelize = sequelize;

db.User = require("./User.model.js")(sequelize, Sequelize);
console.log({user: db.User});

module.exports = db;

/models/User.model.js

const bcrypt = require("bcrypt");

module.exports = (sequelize, Sequelize) => {
    return sequelize.define("user", {
        name: {
            type: Sequelize.STRING,
            allowNull: 0,

        },
        email: {
            type: Sequelize.STRING,
            allowNull: 0,
        },
        password: {
            type: Sequelize.STRING,
            allowNull: 0,
        },

    },{
        hooks: {
            beforeCreate: async (user) => {
                if (user.password) {
                    const salt = await bcrypt.genSaltSync(10, 'a');
                    user.password = bcrypt.hashSync(user.password, salt);
                }
            },
            beforeUpdate:async (user) => {
                if (user.password) {
                    const salt = await bcrypt.genSaltSync(10, 'a');
                    user.password = bcrypt.hashSync(user.password, salt);
                }
            }
        },
        instanceMethods: {
            validPassword: (password) => {
                return bcrypt.compareSync(password, this.password);
            }
        }
    });

/controllers/User.controller.js

const db = require("../models");
const path = require("path");
const User = db.User;
const Op = db.Sequelize.Op; //sql operators

exports.login = (req, res) => {
    const user = {
        email: req.body.email,
        password: req.body.password,
    };

    const isValidated = User.validPassword(user.password);
    console.log({isValidated});
};

Error: TypeError: User.validPassword is not a function

I'm trying to wrap my head around this for last couple of hours with no avail.

Thanks,
Bud

Body:
sequelize version >4 is changed the way instance methods are defined.

you can also refer to this link

const bcrypt = require("bcrypt");

module.exports = (sequelize, Sequelize) => {
    const User = sequelize.define("user", {
        name: {
            type: Sequelize.STRING,
            allowNull: 0,

        },
        email: {
            type: Sequelize.STRING,
            allowNull: 0,
        },
        password: {
            type: Sequelize.STRING,
            allowNull: 0,
        },

    }, {
        hooks: {
            beforeCreate: async (user) => {
                if (user.password) {
                    const salt = await bcrypt.genSaltSync(10, 'a');
                    user.password = bcrypt.hashSync(user.password, salt);
                }
            },
            beforeUpdate: async (user) => {
                if (user.password) {
                    const salt = await bcrypt.genSaltSync(10, 'a');
                    user.password = bcrypt.hashSync(user.password, salt);
                }
            }
        }
    })
    User.validPassword = (password) => {
        return bcrypt.compareSync(password, this.password);
    }
    return User;
}


问:
Why can't I install the React Native Testing library?
I'm new to app testing and have started delving into this topic since yesterday. I wanted to write tests for my React Native app and tried to install React Native Testing Library with this command:

```<code>npm install --save-dev @testing-library/react-native @testing-library/jest-native
</code>```

Then I ran into the following problem:

I tried to find a solution to this problem in Google, but I did not succeed. As far as I understand, the problem lies in the dependencies?
Please tell me what can I do in this case?

P.S. I tried to create a completely clean project with expo init, tried to install the library but got exactly the same error

答:
it looks like you are running into a conflict with your react version dependencies. Please check the named modules for required packages they depend on.
Please have a look with: npm outdated and then maybe try to update your settings via npm update

also take a look here if you want: updating npm dependencies

Body:
I'm new to app testing and have started delving into this topic since yesterday. I wanted to write tests for my React Native app and tried to install React Native Testing Library with this command:

npm install --save-dev @testing-library/react-native @testing-library/jest-native

Then I ran into the following problem:

I tried to find a solution to this problem in Google, but I did not succeed. As far as I understand, the problem lies in the dependencies?
Please tell me what can I do in this case?

P.S. I tried to create a completely clean project with expo init, tried to install the library but got exactly the same error


问:
Add Javascript counters to colour counter
I am making a colour counter application, That has has 6 different colours.

I am currently trying to implement a pure JavaScript counter that has a individual counter for each colour.

(Correction: It is not to count the different colours displayed on the page, but when the user sees a colour in their surrounding environment that matches one of the 6 colours, they increase the counter by 1, for example the user sees the sky is blue and the grass is green, The user hovers over the blue colour, the increase and decrease buttons appear, the user increases the blue colour by 1 increment, Then for the grass the user hovers over the green colour, again the button appears and the user increases the green counter by 1.)

When a user hovers over the colour buttons must appear to increase or decrease the counter by 1, to a minimum of 0.

The count of each colour must always be displayed above the colour.

My current method seems rather long I'm sure there is a way to set up some sort of a method to handle all colours but again to have separate counters for each colour.

Please see the below image for what I am trying to achieve:
See this image

Any help would be appreciated,
I have included my current code below for reference

var green = 0;
var countEl1 = document.getElementById("green");
function plus1(){
    green++;
    countEl1.value = green;
}
function minus1(){
    if (green > 0) {
        green--;
        countEl1.value = green;
    }
}
var brown = 0;
var countEl2 = document.getElementById("brown");
function plus2(){
    brown++;
    countEl2.value = brown;
}
function minus2(){
    if (brown > 0) {
        brown--;
        countEl2.value = brown;
    }
}
var blue = 0;
var countEl3 = document.getElementById("blue");
function plus3(){
    blue++;
    countEl3.value = blue;
}
function minus3(){
    if (blue > 0) {
        blue--;
        countEl3.value = blue;
    }
}
var yellow = 0;
var countEl4 = document.getElementById("yellow");
function plus4(){
    yellow++;
    countEl4.value = yellow;
}
function minus4(){
    if (yellow > 0) {
        yellow--;
        countEl4.value = yellow;
    }
}
var gold = 0;
var countEl5 = document.getElementById("gold");
function plus5(){
    gold++;
    countEl5.value = gold;
}
function minus5(){
    if (gold > 0) {
        gold--;
        countEl5.value = gold;
    }
}
var red = 0;
var countEl6 = document.getElementById("red");
function plus6(){
    red++;
    countEl6.value = red;
}
function minus6(){
    if (red > 0) {
        red--;
        countEl6.value = red;
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pyramid {
    clip-path: polygon(50% 0, 100% 100%, 0 100%);
    width: 100vmin;
    aspect-ratio: 9 / 15; /* 2/1 */
    background-color: white;
    display: grid;
    grid-template-columns: 1fr;

}
.pyramid > * {
    background: white;
}
.one {
    background-color: rgba(234, 27, 7, 0.97);
}
.two {
    background-color: rgba(244, 182, 0, 0.98);
    margin-top: 10px;
}
.three {
    background-color: rgba(249, 224, 41, 0.98);
    margin-top: 10px;
}
.four {
    background-color: rgba(4, 157, 252, 0.98);
}
.five {
    background-color: rgba(167, 118, 67, 0.99);
    gap: 0% !important;
}
.six {
    background-color: rgba(92, 213, 51, 0.98);
}
.counter input[type=button], input[type=text] {
    display: inline-block;
    width: 20px;
    background-color: transparent;
    outline: none;
    border: none;
    text-align: center;
    cursor: pointer;
    padding: 0px;
    color: black;
    height: 33px;
    font-family: 'Open Sans';
}
#container {
    width: 100px;
    height: 100px;
    position: relative;
}
#navi,
#infoi {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}
#infoi {
    z-index: 10;
}
button {
    border-radius: 50%;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Colour counter</title>
    <link rel="stylesheet" href="css/style.css">

Colour counter

Counter Test

    <input type="button" value="-" id="minus1" onclick="minus1()">
    <input type="text" size="25" value="0" id="green">
    <input type="button" value="+" id="plus1" onclick="plus1()">

    <input type="button" value="-" id="minus2" onclick="minus2()">
    <input type="text" size="25" value="0" id="brown">
    <input type="button" value="+" id="plus2" onclick="plus2()">

```

答:
Use an array from which do the operations on the DOM and apply map to do each colour's job, which would be to programatically attach the event listener to the DOM elements. Also, ensure the DOM has fully loaded before running your JS code:

window.onload = function() {

  let colours = ["green", "brown", "blue", "yellow", "gold", "red"]
    .map(id => {
      let colour = {
        elementCount: document.getElementById(id),
        elementPlus: document.getElementById(`${id}_plus`),
        elementMinus: document.getElementById(`${id}_minus`),
        counter: 0,
      };

      colour.elementPlus.addEventListener("click", function() {
        colour.counter++;
        colour.elementCount.value = colour.counter;
      });

      colour.elementMinus.addEventListener("click", function() {
        if (colour.counter > 0) {
          colour.counter--;
          colour.elementCount.value = colour.counter;
        }
      });

      return colour;
    });

};
```
<p>Adapt the HTML so the IDs match the ones used in the JS:</p>
<ul>
<li>Instead of <code>minus1</code>, use <code>green_minus</code>. Do the same for the rest of <code>minus</code> buttons.</li>
<li>Instead of <code>plus1</code>, use <code>green_minus</code>. Do the same for the rest of <code>plus</code> buttons.</li>
</ul>
<p>Adapt the HTML removing the <code>onClick</code> attribute (it is now assigned programatically using JS).</p>
<p>As a plus, now you have the <code>colours</code> variable, where all the DOM elements and each colour counter are stored for further inspection and or modification.</p>
<p>As an example, one colour in the HTML would be like:</p>
<pre class="lang-html prettyprint-override"><code><div id="input_div">
    <input type="button" value="-" id="green_minus">
    <input type="text" size="25" value="0" id="green">
    <input type="button" value="+" id="green_plus">
</div>
<!-- Other colours... -->
<script src="js/Main.js"></script>
</code>```

window.onload = function() {

  let colours = ["green", "brown", "blue", "yellow", "gold", "red"]
    .map(id => {
      let colour = {
        elementCount: document.getElementById(id),
        elementPlus: document.getElementById(`${id}_plus`),
        elementMinus: document.getElementById(`${id}_minus`),
        counter: 0,
      };

      colour.elementPlus.addEventListener("click", function() {
        colour.counter++;
        colour.elementCount.value = colour.counter;
      });

      colour.elementMinus.addEventListener("click", function() {
        if (colour.counter > 0) {
          colour.counter--;
          colour.elementCount.value = colour.counter;
        }
      });

      return colour;
    });
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pyramid {
    clip-path: polygon(50% 0, 100% 100%, 0 100%);
    width: 100vmin;
    aspect-ratio: 9 / 15; /* 2/1 */
    background-color: white;
    display: grid;
    grid-template-columns: 1fr;

}
.pyramid > * {
    background: white;
}
.one {
    background-color: rgba(234, 27, 7, 0.97);
}
.two {
    background-color: rgba(244, 182, 0, 0.98);
    margin-top: 10px;
}
.three {
    background-color: rgba(249, 224, 41, 0.98);
    margin-top: 10px;
}
.four {
    background-color: rgba(4, 157, 252, 0.98);
}
.five {
    background-color: rgba(167, 118, 67, 0.99);
    gap: 0% !important;
}
.six {
    background-color: rgba(92, 213, 51, 0.98);
}
.counter input[type=button], input[type=text] {
    display: inline-block;
    width: 20px;
    background-color: transparent;
    outline: none;
    border: none;
    text-align: center;
    cursor: pointer;
    padding: 0px;
    color: black;
    height: 33px;
    font-family: 'Open Sans';
}
#container {
    width: 100px;
    height: 100px;
    position: relative;
}
#navi,
#infoi {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}
#infoi {
    z-index: 10;
}
button {
    border-radius: 50%;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Colour counter</title>
    <link rel="stylesheet" href="css/style.css">

Colour counter

Counter Test

    <input type="button" value="-" id="green_minus">
    <input type="text" size="25" value="0" id="green">
    <input type="button" value="+" id="green_plus">

    <input type="button" value="-" id="brown_minus">
    <input type="text" size="25" value="0" id="brown">
    <input type="button" value="+" id="brown_plus">

    <input type="button" value="-" id="blue_minus">
    <input type="text" size="25" value="0" id="blue">
    <input type="button" value="+" id="blue_plus">

    <input type="button" value="-" id="yellow_minus">
    <input type="text" size="25" value="0" id="yellow">
    <input type="button" value="+" id="yellow_plus">

    <input type="button" value="-" id="gold_minus">
    <input type="text" size="25" value="0" id="gold">
    <input type="button" value="+" id="gold_plus">

    <input type="button" value="-" id="red_minus">
    <input type="text" size="25" value="0" id="red">
    <input type="button" value="+" id="red_plus">

```

Body:
I am making a colour counter application, That has has 6 different colours.

I am currently trying to implement a pure JavaScript counter that has a individual counter for each colour.

(Correction: It is not to count the different colours displayed on the page, but when the user sees a colour in their surrounding environment that matches one of the 6 colours, they increase the counter by 1, for example the user sees the sky is blue and the grass is green, The user hovers over the blue colour, the increase and decrease buttons appear, the user increases the blue colour by 1 increment, Then for the grass the user hovers over the green colour, again the button appears and the user increases the green counter by 1.)

When a user hovers over the colour buttons must appear to increase or decrease the counter by 1, to a minimum of 0.

The count of each colour must always be displayed above the colour.

My current method seems rather long I'm sure there is a way to set up some sort of a method to handle all colours but again to have separate counters for each colour.

Please see the below image for what I am trying to achieve:
See this image

Any help would be appreciated,
I have included my current code below for reference

var green = 0;
var countEl1 = document.getElementById("green");
function plus1(){
    green++;
    countEl1.value = green;
}
function minus1(){
    if (green > 0) {
        green--;
        countEl1.value = green;
    }
}
var brown = 0;
var countEl2 = document.getElementById("brown");
function plus2(){
    brown++;
    countEl2.value = brown;
}
function minus2(){
    if (brown > 0) {
        brown--;
        countEl2.value = brown;
    }
}
var blue = 0;
var countEl3 = document.getElementById("blue");
function plus3(){
    blue++;
    countEl3.value = blue;
}
function minus3(){
    if (blue > 0) {
        blue--;
        countEl3.value = blue;
    }
}
var yellow = 0;
var countEl4 = document.getElementById("yellow");
function plus4(){
    yellow++;
    countEl4.value = yellow;
}
function minus4(){
    if (yellow > 0) {
        yellow--;
        countEl4.value = yellow;
    }
}
var gold = 0;
var countEl5 = document.getElementById("gold");
function plus5(){
    gold++;
    countEl5.value = gold;
}
function minus5(){
    if (gold > 0) {
        gold--;
        countEl5.value = gold;
    }
}
var red = 0;
var countEl6 = document.getElementById("red");
function plus6(){
    red++;
    countEl6.value = red;
}
function minus6(){
    if (red > 0) {
        red--;
        countEl6.value = red;
    }
}

.pyramid {
    clip-path: polygon(50% 0, 100% 100%, 0 100%);
    width: 100vmin;
    aspect-ratio: 9 / 15; /* 2/1 */
    background-color: white;
    display: grid;
    grid-template-columns: 1fr;

}
.pyramid > * {
    background: white;
}
.one {
    background-color: rgba(234, 27, 7, 0.97);
}
.two {
    background-color: rgba(244, 182, 0, 0.98);
    margin-top: 10px;
}
.three {
    background-color: rgba(249, 224, 41, 0.98);
    margin-top: 10px;
}
.four {
    background-color: rgba(4, 157, 252, 0.98);
}
.five {
    background-color: rgba(167, 118, 67, 0.99);
    gap: 0% !important;
}
.six {
    background-color: rgba(92, 213, 51, 0.98);
}
.counter input[type=button], input[type=text] {
    display: inline-block;
    width: 20px;
    background-color: transparent;
    outline: none;
    border: none;
    text-align: center;
    cursor: pointer;
    padding: 0px;
    color: black;
    height: 33px;
    font-family: 'Open Sans';
}
#container {
    width: 100px;
    height: 100px;
    position: relative;
}
#navi,
#infoi {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}
#infoi {
    z-index: 10;
}
button {
    border-radius: 50%;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Colour counter</title>
    <link rel="stylesheet" href="css/style.css">

Colour counter

Counter Test

    <input type="button" value="-" id="minus1" onclick="minus1()">
    <input type="text" size="25" value="0" id="green">
    <input type="button" value="+" id="plus1" onclick="plus1()">

    <input type="button" value="-" id="minus2" onclick="minus2()">
    <input type="text" size="25" value="0" id="brown">
    <input type="button" value="+" id="plus2" onclick="plus2()">

Body:
Use an array from which do the operations on the DOM and apply map to do each colour's job, which would be to programatically attach the event listener to the DOM elements. Also, ensure the DOM has fully loaded before running your JS code:

window.onload = function() {

  let colours = ["green", "brown", "blue", "yellow", "gold", "red"]
    .map(id => {
      let colour = {
        elementCount: document.getElementById(id),
        elementPlus: document.getElementById(`${id}_plus`),
        elementMinus: document.getElementById(`${id}_minus`),
        counter: 0,
      };

      colour.elementPlus.addEventListener("click", function() {
        colour.counter++;
        colour.elementCount.value = colour.counter;
      });

      colour.elementMinus.addEventListener("click", function() {
        if (colour.counter > 0) {
          colour.counter--;
          colour.elementCount.value = colour.counter;
        }
      });

      return colour;
    });

};

Adapt the HTML so the IDs match the ones used in the JS:

Instead of minus1, use green_minus. Do the same for the rest of minus buttons.

Instead of plus1, use green_minus. Do the same for the rest of plus buttons.

Adapt the HTML removing the onClick attribute (it is now assigned programatically using JS).

As a plus, now you have the colours variable, where all the DOM elements and each colour counter are stored for further inspection and or modification.

As an example, one colour in the HTML would be like:

<div id="input_div">
    <input type="button" value="-" id="green_minus">
    <input type="text" size="25" value="0" id="green">
    <input type="button" value="+" id="green_plus">
</div>
<!-- Other colours... -->
<script src="js/Main.js"></script>

window.onload = function() {

  let colours = ["green", "brown", "blue", "yellow", "gold", "red"]
    .map(id => {
      let colour = {
        elementCount: document.getElementById(id),
        elementPlus: document.getElementById(`${id}_plus`),
        elementMinus: document.getElementById(`${id}_minus`),
        counter: 0,
      };

      colour.elementPlus.addEventListener("click", function() {
        colour.counter++;
        colour.elementCount.value = colour.counter;
      });

      colour.elementMinus.addEventListener("click", function() {
        if (colour.counter > 0) {
          colour.counter--;
          colour.elementCount.value = colour.counter;
        }
      });

      return colour;
    });
};

.pyramid {
    clip-path: polygon(50% 0, 100% 100%, 0 100%);
    width: 100vmin;
    aspect-ratio: 9 / 15; /* 2/1 */
    background-color: white;
    display: grid;
    grid-template-columns: 1fr;

}
.pyramid > * {
    background: white;
}
.one {
    background-color: rgba(234, 27, 7, 0.97);
}
.two {
    background-color: rgba(244, 182, 0, 0.98);
    margin-top: 10px;
}
.three {
    background-color: rgba(249, 224, 41, 0.98);
    margin-top: 10px;
}
.four {
    background-color: rgba(4, 157, 252, 0.98);
}
.five {
    background-color: rgba(167, 118, 67, 0.99);
    gap: 0% !important;
}
.six {
    background-color: rgba(92, 213, 51, 0.98);
}
.counter input[type=button], input[type=text] {
    display: inline-block;
    width: 20px;
    background-color: transparent;
    outline: none;
    border: none;
    text-align: center;
    cursor: pointer;
    padding: 0px;
    color: black;
    height: 33px;
    font-family: 'Open Sans';
}
#container {
    width: 100px;
    height: 100px;
    position: relative;
}
#navi,
#infoi {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}
#infoi {
    z-index: 10;
}
button {
    border-radius: 50%;
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Colour counter</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="js/Main.js"></script>
</head>
<body>
<div id="container">
<h1>Colour counter</h1>
<div class="pyramid">
    <div class="one"></div>
    <div class="two"></div>
    <div class="three"></div>
    <div class="four"></div>
    <div class="five"></div>
    <div class="six"></div>
</div>

<h1>Counter Test</h1>
<div id="input_div">
    <input type="button" value="-" id="green_minus">
    <input type="text" size="25" value="0" id="green">
    <input type="button" value="+" id="green_plus">
</div>
<div id="input_div2">
    <input type="button" value="-" id="brown_minus">
    <input type="text" size="25" value="0" id="brown">
    <input type="button" value="+" id="brown_plus">
</div>
<div id="input_div3">
    <input type="button" value="-" id="blue_minus">
    <input type="text" size="25" value="0" id="blue">
    <input type="button" value="+" id="blue_plus">
</div>
<div id="input_div4">
    <input type="button" value="-" id="yellow_minus">
    <input type="text" size="25" value="0" id="yellow">
    <input type="button" value="+" id="yellow_plus">
</div>
<div id="input_div5">
    <input type="button" value="-" id="gold_minus">
    <input type="text" size="25" value="0" id="gold">
    <input type="button" value="+" id="gold_plus">
</div>
<div id="input_div6">
    <input type="button" value="-" id="red_minus">
    <input type="text" size="25" value="0" id="red">
    <input type="button" value="+" id="red_plus">
</div>

</div>
</body>
</html>


问:
C# Datetime is increasing by 3 hours
My dates are being stored in sql server.

Windows server region and timezone are correct, but when I see the date in database it's increased by 3 hours, I think it is comming from some server configuration that is overriding, but don't know where else to look.

When I send date from local project to production database, it saves correctly, but when I use production website it doesn't.

Where else should I check to solve this?

答:
The problem was in some machines of the load balance, there are several machines created from an image, the original was right but the copies were not, if I tried many times to save the registry, then I happened to be redirected to the machine with the correct configuration and then the record was saved with the correct date.

I just asked devops to correct the settings on the other machines.

Title: C# Datetime is increasing by 3 hours


问:
Find specific values in a txt file and adding them up with python
I have a txt file which looks like that:

```<code>[Chapter.Title1]
Irrevelent=90 B
Volt=0.10 ienl
Watt=2 W
Ampere=3 A
Irrevelent=91 C

[Chapter.Title2]
Irrevelent=999
Irrevelent=999

[Chapter.Title3]
Irrevelent=92 B
Volt=0.20 ienl
Watt=5 W
Ampere=6 A
Irrevelent=93 C
</code>```

What I want is that it catches "Title1" and the values "0,1", "2" and "3". Then adds them up (which would be 5.1).

I don't care about the lines with "irrevelent" at the beginning.

And then the same with the third block. Catching "Title3" and adding "0.2", "5" and "6".

The second block with "Title2" does not contain "Volt", Watt" and "Ampere" and is therefore not relevant.

Can anyone please help me out with this?

Thank you and cheers

答:
There are many ways to achieve this. Here's one:

```<code>d = dict()
V = {'Volt', 'Watt', 'Ampere'}
with open('chapter.txt', encoding='utf-8') as f:
    key = None
    for line in f:
        if line.startswith('[Chapter'):
            d[key := line.strip()] = 0
        elif key and len(t := line.split('=')) > 1 and t[0] in V:
            d[key] += float(t[1].split()[0])

for k, v in d.items():
    if v > 0:
        print(f'Total for {k} = {v}')
</code>```

Output:

```<code>Total for [Chapter.Title1] = 6
Total for [Chapter.Title2] = 15
</code>```

Body:
I have a txt file which looks like that:

[Chapter.Title1]
Irrevelent=90 B
Volt=0.10 ienl
Watt=2 W
Ampere=3 A
Irrevelent=91 C

[Chapter.Title2]
Irrevelent=999
Irrevelent=999

[Chapter.Title3]
Irrevelent=92 B
Volt=0.20 ienl
Watt=5 W
Ampere=6 A
Irrevelent=93 C

What I want is that it catches "Title1" and the values "0,1", "2" and "3". Then adds them up (which would be 5.1).

I don't care about the lines with "irrevelent" at the beginning.

And then the same with the third block. Catching "Title3" and adding "0.2", "5" and "6".

The second block with "Title2" does not contain "Volt", Watt" and "Ampere" and is therefore not relevant.

Can anyone please help me out with this?

Thank you and cheers

Body:
There are many ways to achieve this. Here's one:

d = dict()
V = {'Volt', 'Watt', 'Ampere'}
with open('chapter.txt', encoding='utf-8') as f:
    key = None
    for line in f:
        if line.startswith('[Chapter'):
            d[key := line.strip()] = 0
        elif key and len(t := line.split('=')) > 1 and t[0] in V:
            d[key] += float(t[1].split()[0])

for k, v in d.items():
    if v > 0:
        print(f'Total for {k} = {v}')

Output:

Total for [Chapter.Title1] = 6
Total for [Chapter.Title2] = 15


问:
Django Binary or BLOB model field
I have a C# program that inserts a pdf inside a MySQL database. Now I want to retrieve that pdf via django but django's models.FileField needs an "Upload To" parameter which means behind the scenes it actually stores the File on the file system rather than in the database.  Is there any way I can set up a django model so that I can store the pdf directly inside MySQL?

Regards

答: I have been dealing with this same issue, writing a pdf to a mediumblob field in mysql and retrieving via django. I have set the mysql field type to a mediumblob and the django field type to textfield. I have used a queryset and httpresponse to view the PDF objects in a browser (but not directly in django).</p>

ContentLicense: CC BY-SA 3.0

Title: Django Binary or BLOB model field


问:
Using state in other component
Hi I am learning and new to react and I want to know how to pass state from one component to other,

I have one component as

```<code>const [paneCount, setPaneCount]= useState(1);

const openPane = (paneKey) => {
  setOpeningPaneKeys(oldState => {
    if (!oldState.includes(paneKey)) {
      return [...oldState, paneKey]
    }
    return oldState
  })
  setPaneCount(paneCount+1);
  console.log(paneCount);

  setFocusingPaneKey(paneKey)
}
</code>```

where I want to use paneCount in App.js file

```<code>function App(props) {

const [inactive, setInactive] = useState(false);

return (
<div className="App">

  <Header />
  <Navbar
      onCollapse={(inactive) => {
        setInactive(!inactive);
      }}
    />

  <div class="landing-card">
    <div>

      <h4 class="headingStyle">Recorder Box</h4>
      <h4>Count:{props.paneCount}</h4>
      <img src="landing.jpg" alt="Forest" width="775" height="500"></img>
    </div>
  </div>
</code>```

How to pass paneCount to App.js

答:
You can't pass data upwards, only downwards. The reason for that is how the application and data flow is built. Luckily there are 3 ways to get it done.

1) Initialize in App.js

If you want to use state value in App.js but want to work with it somewhere else:

```<code>export default function App() {
  const [myState, setMyState] = useState();

  return <Component state={ myState } setState={ setMyState } />
}
</code>```

This way you can keep all your state in 1 place and use it everywhere, but it also means that you have to pass component by component to do so.

2) Context

This improves the previous option, because you no longer need to pass data around. Instead you can keep it in a provider and use it throughout your application.

There are multiple ways to define a provider, so I will just link you the docs for that one.

Note: Provider definitions does not differ in any way. They are not practical or impractical, simply one's preference over another!

3) Redux

This is arguably the BEST option for state management (eventhough I don't like it..). I haven't used it yet and don't want to either, because the previous option does the same with less effort IMO.

Here's the docs for that one.

Title: Using state in other component

Body:
Hi I am learning and new to react and I want to know how to pass state from one component to other,

I have one component as

const [paneCount, setPaneCount]= useState(1);

const openPane = (paneKey) => {
  setOpeningPaneKeys(oldState => {
    if (!oldState.includes(paneKey)) {
      return [...oldState, paneKey]
    }
    return oldState
  })
  setPaneCount(paneCount+1);
  console.log(paneCount);

  setFocusingPaneKey(paneKey)
}

where I want to use paneCount in App.js file

function App(props) {

const [inactive, setInactive] = useState(false);

return (

  <Navbar
      onCollapse={(inactive) => {
        setInactive(!inactive);
      }}
    />

Recorder Box

Count:{props.paneCount}

How to pass paneCount to App.js

Body:
You can't pass data upwards, only downwards. The reason for that is how the application and data flow is built. Luckily there are 3 ways to get it done.

1) Initialize in App.js

If you want to use state value in App.js but want to work with it somewhere else:

export default function App() {
  const [myState, setMyState] = useState();

  return <Component state={ myState } setState={ setMyState } />
}

This way you can keep all your state in 1 place and use it everywhere, but it also means that you have to pass component by component to do so.

2) Context

This improves the previous option, because you no longer need to pass data around. Instead you can keep it in a provider and use it throughout your application.

There are multiple ways to define a provider, so I will just link you the docs for that one.

Note: Provider definitions does not differ in any way. They are not practical or impractical, simply one's preference over another!

3) Redux

This is arguably the BEST option for state management (eventhough I don't like it..). I haven't used it yet and don't want to either, because the previous option does the same with less effort IMO.

Here's the docs for that one.


问:
Hashing raw bytes in C++?
I want to write a function that takes two types T, U such that sizeof(T)+sizeof(U)<=8 and gets a uint64_t by just reinterpreting their bytes one after the other. However this does not seem to work. I am certain there is a quicker and more elegant (and correct) way to do it but I have no clue. Any tips are greatly appreciated.

```<code>#include <cstdint>
#include <iostream>
#include <vector>

template <typename T, typename U>
constexpr auto hash8(T x, U y) {
  static_assert(sizeof(T) + sizeof(U) <= 8);

  uint64_t u = 0;
  uint64_t v = 0;
  auto px = (uint8_t*)&x;
  auto py = (uint8_t*)&y;
  for (auto i = 0; i < sizeof(T); ++i) {
    u |= (uint64_t)px[i];
    u <<= 8;
  }
  for (auto i = 0; i < sizeof(U); ++i) {
    v |= (uint64_t)py[i];
    v <<= 8;
  }

  return u << (sizeof(U) * 8) | v;
}

int main() {
  std::cout << hash8(131, 0) << '\n';
  std::cout << hash8(132, 0) << '\n';
  std::cout << hash8(500, 0) << '\n';
}
</code>```

答:
I cannot help with the problem in your code due to lack of details, but I can propose a perhaps simpler solution.

Firstly, I recommend adding a check that the argument objects have unique object representation. Unless that is satisfied, the hash would be meaningless.

Secondly, std::memcpy might make this simpler:

```<code>template <typename T, typename U>
auto
hash8(T x, U y) noexcept {
    static_assert(sizeof x + sizeof y <= sizeof(std::uint64_t));
    static_assert(std::has_unique_object_representations_v<T>);
    static_assert(std::has_unique_object_representations_v<U>);
    std::uint64_t ret{};
    auto ptr = reinterpret_cast<unsigned char*>(&ret);
    std::memcpy(ptr, std::addressof(x), sizeof x);
    ptr += sizeof x;
    std::memcpy(ptr, std::addressof(y), sizeof y);
    return ret;
}
</code>```

Next, we can generalise this to arbitrary number of arguments (so long as they fit), and different return types:

```<code>template <typename R = std::uint64_t, typename... Args>
auto
hash(Args... args) noexcept {
    static_assert((sizeof args + ...) <= sizeof(R));
    static_assert((std::has_unique_object_representations_v<Args> && ...));
    static_assert(std::has_unique_object_representations_v<R>);
    R ret{};
    auto ptr = reinterpret_cast<unsigned char*>(&ret);
    (
        (
            std::memcpy(ptr, std::addressof(args), sizeof args),
            ptr += sizeof args
        ), ...
    );
    return ret;
}
</code>```

There is a caveat that a hash such as this is not the same across different systems, even if the sizes of the objects match.

P.S. It's pointless to make your function constexpr because you use reinterpret casting which isn't allowed in constant expressions.

Title: Hashing raw bytes in C++?

Body:
I want to write a function that takes two types T, U such that sizeof(T)+sizeof(U)<=8 and gets a uint64_t by just reinterpreting their bytes one after the other. However this does not seem to work. I am certain there is a quicker and more elegant (and correct) way to do it but I have no clue. Any tips are greatly appreciated.

#include <cstdint>
#include <iostream>
#include <vector>

template <typename T, typename U>
constexpr auto hash8(T x, U y) {
  static_assert(sizeof(T) + sizeof(U) <= 8);

  uint64_t u = 0;
  uint64_t v = 0;
  auto px = (uint8_t*)&x;
  auto py = (uint8_t*)&y;
  for (auto i = 0; i < sizeof(T); ++i) {
    u |= (uint64_t)px[i];
    u <<= 8;
  }
  for (auto i = 0; i < sizeof(U); ++i) {
    v |= (uint64_t)py[i];
    v <<= 8;
  }

  return u << (sizeof(U) * 8) | v;
}

int main() {
  std::cout << hash8(131, 0) << '\n';
  std::cout << hash8(132, 0) << '\n';
  std::cout << hash8(500, 0) << '\n';
}

Body:
I cannot help with the problem in your code due to lack of details, but I can propose a perhaps simpler solution.

Firstly, I recommend adding a check that the argument objects have unique object representation. Unless that is satisfied, the hash would be meaningless.

Secondly, std::memcpy might make this simpler:

template <typename T, typename U>
auto
hash8(T x, U y) noexcept {
    static_assert(sizeof x + sizeof y <= sizeof(std::uint64_t));
    static_assert(std::has_unique_object_representations_v<T>);
    static_assert(std::has_unique_object_representations_v<U>);
    std::uint64_t ret{};
    auto ptr = reinterpret_cast<unsigned char*>(&ret);
    std::memcpy(ptr, std::addressof(x), sizeof x);
    ptr += sizeof x;
    std::memcpy(ptr, std::addressof(y), sizeof y);
    return ret;
}

Next, we can generalise this to arbitrary number of arguments (so long as they fit), and different return types:

template <typename R = std::uint64_t, typename... Args>
auto
hash(Args... args) noexcept {
    static_assert((sizeof args + ...) <= sizeof(R));
    static_assert((std::has_unique_object_representations_v<Args> && ...));
    static_assert(std::has_unique_object_representations_v<R>);
    R ret{};
    auto ptr = reinterpret_cast<unsigned char*>(&ret);
    (
        (
            std::memcpy(ptr, std::addressof(args), sizeof args),
            ptr += sizeof args
        ), ...
    );
    return ret;
}

There is a caveat that a hash such as this is not the same across different systems, even if the sizes of the objects match.

P.S. It's pointless to make your function constexpr because you use reinterpret casting which isn't allowed in constant expressions.


问:
How to declare and use a struct field which can store both string and int values?
I've the following struct:

```<code>type testCase struct {
   input   string
   isValid bool
}
</code>```

I want to use this struct in multiple tests and input could be either a string or an intetc.

I can convert the int input to string and convert it back to int while processing, or I can define two different structs e.g. testCaseInt and testCaseStruct which will solve my problem but how do I solve this by converting input to an interface?

I'm new to Go and tried Googling about this but couldn't find maybe because I don't know what to search for.

答:
How to declare and use a variable which can store both string and int values in Go?

You cannot. Go's type system (as of Go 1.17) doesn't provide sum types.

You will have to wait for Go 1.18.

Body:
I've the following struct:

type testCase struct {
   input   string
   isValid bool
}

I want to use this struct in multiple tests and input could be either a string or an intetc.

I can convert the int input to string and convert it back to int while processing, or I can define two different structs e.g. testCaseInt and testCaseStruct which will solve my problem but how do I solve this by converting input to an interface?

I'm new to Go and tried Googling about this but couldn't find maybe because I don't know what to search for.


问:
Cannot deploy Node js app to Azure ("do not have permission")
I have a Wordle-esque app that I want to deploy using Azure. Repo here. It is a fork from a popular open-source project, and I can also locally build and run the game. Locally, it runs perfectly.

I am trying to use Azure App Services to deploy it, using a Github Action. All the Actions pass, and the App can be successfully built. However, when I try to view the deployment here the only error I am receiving is

You do not have permission to view this directory or page.

Since it runs locally, and it pass its github action build, I do not know how to proceed here. I have tried restarting the app, and changing the resources I am using to host it, but that does not work. Some other answers seem to suggest the problem is about it not finding index.html, but I can access that through https://shetland-wordle.azurewebsites.net/public/index.html and the page is blank.

If i look under wwwroot/ in the Azure debugger I see the following file structure:

Any help would be appreciated

答:
turns out it was something strange with package.json. I needed to change the path to my react scripts:

"start": "node_modules/react-scripts/bin/react-scripts.js start"

Not sure if its good practise to do this, but it works now


问:
PHP redirect link only updates sql database once every minute
For tracking the number of clicks (and IP) for a website I created a php script that stores the date and IP info and only once the query was executed successfully it redirects the user to the link. Even though the following script is very minimal, it works.

However, if I click the link twice within one minute (tested both in Chrome and Edge) it does not save this as a click but it does redirect me to the correct page which I find very odd. I have tried this by clicking multiple times and only the values after +-1 min get stored.

Opening a new Chrome window does not work. Opening an incognito screen within 1 min does work and this click gets saved.

Addition info: in the SQL database there is a primary ID column with AUTO_INCREMENT.

Question: is there any reason why this happens (perhaps caching?) and would there be any way to prevent this?

The URL to redirect to link 1 is: thisphpfile.php?link=1

```<code>//---------
// Get info on which link to point to
$link = $_GET["link"];

// Check link value to prevent SQL injection
if($link =='1'){
    $link_sql = "https://www.url1.com";
}
if($link =='2'){
    $link_sql = "https://www.url2.com";
}

// If link was a valid input, continue, else back to homepage
if($link =='1' || $link == '2'){

$date = date("Y-m-d H:i:s");
$ip = $_SERVER['REMOTE_ADDR'];

$sql = "INSERT INTO tablename (DATE , IP, LINK) VALUES ('$date', '$ip','$link_sql')";

//Execute query
if ($conn->query($sql) === TRUE) {
ob_end_flush();

// Redirect link
header("Location: " . $link_sql);
}

}else{
    // Redirect link
    header("Location: https://www.default.com" );
}
</code>```

答:
Adding the following fixed the issue:</p>
```<code>    // Redirect link
header('HTTP/1.1 307 Temporary Redirect');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
header('Pragma: no-cache');
header('Location: ' . $link_sql, true, 307);
</code>```

Body:
For tracking the number of clicks (and IP) for a website I created a php script that stores the date and IP info and only once the query was executed successfully it redirects the user to the link. Even though the following script is very minimal, it works.

However, if I click the link twice within one minute (tested both in Chrome and Edge) it does not save this as a click but it does redirect me to the correct page which I find very odd. I have tried this by clicking multiple times and only the values after +-1 min get stored.

Opening a new Chrome window does not work. Opening an incognito screen within 1 min does work and this click gets saved.

Addition info: in the SQL database there is a primary ID column with AUTO_INCREMENT.

Question: is there any reason why this happens (perhaps caching?) and would there be any way to prevent this?

The URL to redirect to link 1 is: thisphpfile.php?link=1

//---------
// Get info on which link to point to
$link = $_GET["link"];

// Check link value to prevent SQL injection
if($link =='1'){
    $link_sql = "https://www.url1.com";
}
if($link =='2'){
    $link_sql = "https://www.url2.com";
}

// If link was a valid input, continue, else back to homepage
if($link =='1' || $link == '2'){

$date = date("Y-m-d H:i:s");
$ip = $_SERVER['REMOTE_ADDR'];

$sql = "INSERT INTO tablename (DATE , IP, LINK) VALUES ('$date', '$ip','$link_sql')";

//Execute query
if ($conn->query($sql) === TRUE) {
ob_end_flush();

// Redirect link
header("Location: " . $link_sql);
}

}else{
    // Redirect link
    header("Location: https://www.default.com" );
}

Body:
Adding the following fixed the issue:

    // Redirect link
header('HTTP/1.1 307 Temporary Redirect');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
header('Pragma: no-cache');
header('Location: ' . $link_sql, true, 307);


问:
Compare datetime column just year (without time-day-month) with Linq
I want to get a 2022 records. But my code is not efficient. How to compare it?</p>
```<code>> var _year = "2022"; list= query.Where(x =>
> Convert.ToDateTime(x.created_time).ToString("YYYY").Equals(_year
> )).ToList();

</code>```

答:
Is better not to change type to string, but get DateTime structure Year property.

Code example:

```<code>  var year = 2022;
  var list = query.Where(x => Convert.ToDateTime(x.created_time).Year.Equals(year)).ToList();
</code>```

Body:
I want to get a 2022 records. But my code is not efficient. How to compare it?

> var _year = "2022"; list= query.Where(x =>
> Convert.ToDateTime(x.created_time).ToString("YYYY").Equals(_year
> )).ToList();

Body:
Is better not to change type to string, but get DateTime structure Year property.

Code example:

  var year = 2022;
  var list = query.Where(x => Convert.ToDateTime(x.created_time).Year.Equals(year)).ToList();


问:
Why List<> implements RemoveAll, but IList<> does not
I'm refactoring my code to use IList instead of List. I used List.RemoveAll in a couple of places, and noticed that IList does not have this method at all. Is there any good reason for this?</p>

答:
Although a general software design reason was explained by Theodoros Chatzigiannakis you might be interested in a solution when you do need a RemoveAll (maybe you received an IList from a library and want to manipulate that in an easier way). There is an answer here that might interest readers: https://github.com/dotnet/core/issues/2199

Based on the answers from the Dotnet core team, I understand that the main reason is legacy, but as they said, you can easily write an extension method. An example of such an extension method (source:
https://www.extensionmethod.net/csharp/icollection-t/removeall)

```<code>using System;
using System.Collections.Generic;
using System.Linq;

public static class CollectionExtensions
{
    public static void RemoveAll<T>(this ICollection<T> @this, Func<T, bool> predicate)
    {
        List<T> list = @this as List<T>;

        if (list != null)
        {
            list.RemoveAll(new Predicate<T>(predicate));
        }
        else
        {
            List<T> itemsToDelete = @this
                .Where(predicate)
                .ToList();

            foreach (var item in itemsToDelete)
            {
                @this.Remove(item);
            }
        }
    }
}
</code>```

Body:
Although a general software design reason was explained by Theodoros Chatzigiannakis you might be interested in a solution when you do need a RemoveAll (maybe you received an IList from a library and want to manipulate that in an easier way). There is an answer here that might interest readers: https://github.com/dotnet/core/issues/2199

Based on the answers from the Dotnet core team, I understand that the main reason is legacy, but as they said, you can easily write an extension method. An example of such an extension method (source:
https://www.extensionmethod.net/csharp/icollection-t/removeall)

using System;
using System.Collections.Generic;
using System.Linq;

public static class CollectionExtensions
{
    public static void RemoveAll<T>(this ICollection<T> @this, Func<T, bool> predicate)
    {
        List<T> list = @this as List<T>;

        if (list != null)
        {
            list.RemoveAll(new Predicate<T>(predicate));
        }
        else
        {
            List<T> itemsToDelete = @this
                .Where(predicate)
                .ToList();

            foreach (var item in itemsToDelete)
            {
                @this.Remove(item);
            }
        }
    }
}


问:
How to move to one folder back in python
Actually need to go some path and execute some command and below is the code

code:

```<code>import os
present_working_directory = '/home/Desktop/folder'
</code>```

presently i am in folder

```<code>if some_condition == true :
    change_path = "nodes/hellofolder"
    os.chdir(change_path)
    print os.getcwd()
if another_condition  == true:
    change_another_path = "nodes"
    os.chdir(change_another_path)
    print os.getcwd()

**Result**:
'/home/Desktop/folder/nodes/hellofolder'
python: [Errno 1] No such file or directory
</code>```

Actually whats happening here is when i first used os.chdir() the directory has changed to

'/home/Desktop/folder/nodes/hellofolder',

but for the second one i need to run a file by moving to one folder back that is

```<code>'/home/Desktop/folder/nodes'
</code>```

So can anyone let me how to move one folder back in python

答:
Define this function in your script and call it whenever you want to go back just by one folder:</p>
```<code>import os

def dirback():
    m = os.getcwd()
    n = m.rfind("\\")
    d = m[0: n+1]
    os.chdir(d)
    return None
</code>```

Body:
Actually need to go some path and execute some command and below is the code

code:

import os
present_working_directory = '/home/Desktop/folder'

presently i am in folder

if some_condition == true :
    change_path = "nodes/hellofolder"
    os.chdir(change_path)
    print os.getcwd()
if another_condition  == true:
    change_another_path = "nodes"
    os.chdir(change_another_path)
    print os.getcwd()

**Result**:
'/home/Desktop/folder/nodes/hellofolder'
python: [Errno 1] No such file or directory

Actually whats happening here is when i first used os.chdir() the directory has changed to

'/home/Desktop/folder/nodes/hellofolder',

but for the second one i need to run a file by moving to one folder back that is

'/home/Desktop/folder/nodes'

So can anyone let me how to move one folder back in python

Body:
Define this function in your script and call it whenever you want to go back just by one folder:

import os

def dirback():
    m = os.getcwd()
    n = m.rfind("\\")
    d = m[0: n+1]
    os.chdir(d)
    return None


问:
How to use Subquery which returned more than one result
My SQL query

```<code>UPDATE Task SET Done = 1 WHERE (ID = (SELECT ID FROM User WHERE UserName = @UserName)
</code>```

I tried and got an error:

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression. The statement has been terminated.

Is there any possible way to do that (for example a for loop)? Thanks

答:
You can use the IN operator.

```<code>WHERE ID IN (SELECT ID FROM User WHERE UserName = @UserName)
</code>```

Body:
My SQL query

UPDATE Task SET Done = 1 WHERE (ID = (SELECT ID FROM User WHERE UserName = @UserName)

I tried and got an error:

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression. The statement has been terminated.

Is there any possible way to do that (for example a for loop)? Thanks

Body:
You can use the IN operator.

WHERE ID IN (SELECT ID FROM User WHERE UserName = @UserName)


问:
How to create many divs without actually creating them individually
I'm working on a project with html, css and js and I want to create many divs (let's say, 200) so, how can i create them without actually writing code for 200 different divs... I know I can do it with js but could I do it only with html and css..?</p>

答:
One way with js:
you can create one HTML Span Element and with js you change the content of it. I bet with that knowledge you find something


问:
Is there a way to display week numbers aside the weeks in Angular material date picker.,
I would like to know whether we have a solution to display week numbers along with date in mat-datepicker
please give answers specific to mat-datepicker(Angular material)
https://material.angular.io/components/datepicker/overview</p>

答: That is not supported natively and building a whole component would be a lot of work. However here is a link to instructions how you could do it yourself: https://github.com/angular/components/issues/20530#issuecomment-886925173</p>


问:
Why does declaring the variable outside the for loop print all the elements of an array but declaring first inside the for loop prints only the last?
Forgive me if something is wrong with my question, I am a beginner.

The first code, which has the variable "html" first declared outside the for loop, prints all the elements of the array.

```<code><p id="demo"></p>
<script>
 var fruits = ["apple", "banana", "mango", "orange", "strawberry"];

 var html = "";

for(var i = 0; i < fruits.length; i++) {
   html += "<p>" + fruits[i] + "</p>";
     }
         document.getElementById("demo").innerHTML = html;
</script>
</code>```

But when I move the variable declaration inside the for loop, only the last element of the array is printed.

```<code>    <p id="demo"></p>
<script>
 var fruits = ["apple", "banana", "mango", "orange", "strawberry"];

for(var i = 0; i < fruits.length; i++) {
    var html = "";
    html += "<p>" + fruits[i] + "</p>";
     }
         document.getElementById("demo").innerHTML = html;
</script>
</code>```

Why is this?

答: That's because, when you declare the variable inside the loop, it will be declared each time the loop is repeated. So the last run of the loop will declare an empty variable 'html' and will then push the element into this array. So there is only one element inside your array.</p>

Body:
Forgive me if something is wrong with my question, I am a beginner.

The first code, which has the variable "html" first declared outside the for loop, prints all the elements of the array.

But when I move the variable declaration inside the for loop, only the last element of the array is printed.

Why is this?


问:
Efficient way to get indexes of matched items using Lists
I've two lists A and B. I'd like to find out indexes of elements in A that match elements of listB. Something like this:

```<code>ArrayList listA = new ArrayList();
listA.add(1);listA.add(2);listA.add(3);listA.add(4);
ArrayList listB = new ArrayList();
listB.add(2);listB.add(4);
ArrayList listC = new ArrayList();
for(int i=0; i<listB.size();i++) {
   int element = listB.get(i);
   for(int j=0; j<listA.size(); j++) {
      if(listA.get(j) == element) listC.add(j);
   }
}
</code>```

I guess that's one ugly way to doing it. What is the best way to finding all the indexes of A that match all elements in B? I believe there exists a method called containsAll in collections api - don't think it returns matching indexes.

答:
If list A and list B are sorted in the same order (I'll assume ascending, but descending works as well) this problem has an O(n) solution.  Below is some (informal, and untested) code.  When the loop exits, indexMap should contain the indices of every element in list A that match an element in list B and the index of the matched element in list B.</p>

```
  int currentA;
  int currentB;
  int listAIndex = 0;
  int listBIndex = 0;
  Map<Integer, Integer> indexMap = new HashMap<Integer, Integer>();

  currentA = listA.get(listAIndex);
  currentB = listB.get(listBIndex);
  while ((listAIndex < listA.length) && (listBIndex < listB.length))
  {
    if (currentA == currentB)
    {
      indexMap.put(listAIndex, listBIndex);
      ++listAIndex;
    }
    else if (currentA < currentB)
    {
      ++listAIndex;
    }
    else // if (currentA > currentB)
    {
      ++listBIndex;
    }
  }

```

Body:
I've two lists A and B. I'd like to find out indexes of elements in A that match elements of listB. Something like this:

ArrayList listA = new ArrayList();
listA.add(1);listA.add(2);listA.add(3);listA.add(4);
ArrayList listB = new ArrayList();
listB.add(2);listB.add(4);
ArrayList listC = new ArrayList();
for(int i=0; i<listB.size();i++) {
   int element = listB.get(i);
   for(int j=0; j<listA.size(); j++) {
      if(listA.get(j) == element) listC.add(j);
   }
}

I guess that's one ugly way to doing it. What is the best way to finding all the indexes of A that match all elements in B? I believe there exists a method called containsAll in collections api - don't think it returns matching indexes.

Body:
If list A and list B are sorted in the same order (I'll assume ascending, but descending works as well) this problem has an O(n) solution.  Below is some (informal, and untested) code.  When the loop exits, indexMap should contain the indices of every element in list A that match an element in list B and the index of the matched element in list B.

  int currentA;
  int currentB;
  int listAIndex = 0;
  int listBIndex = 0;
  Map<Integer, Integer> indexMap = new HashMap<Integer, Integer>();

  currentA = listA.get(listAIndex);
  currentB = listB.get(listBIndex);
  while ((listAIndex < listA.length) && (listBIndex < listB.length))
  {
    if (currentA == currentB)
    {
      indexMap.put(listAIndex, listBIndex);
      ++listAIndex;
    }
    else if (currentA < currentB)
    {
      ++listAIndex;
    }
    else // if (currentA > currentB)
    {
      ++listBIndex;
    }
  }


问:
React Native How to avoid keyboard blocking form
I am trying to avoid the keyboard over the form, according to React Native documentation, I should be using KeyboardAwareScrollView component. the instructions are fairly simple, but I cant make it work. Am I missing anything?</p>
```<code>return (
    <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        style={{ flex: 1 }}
    >
        <View style={styles.card}>
            <View style={styles.container}>
                <Options setIpt={setIpt} />
                <View style={styles.input}>
                <ShowIpt /> // form input here
                </View>
                <Button
                    title="Create"
                    color="#841584"
                    accessibilityLabel="Create"
                    onPress={() =>
                        navigation.navigate("Result", {
                            ipt: ipt,
                        })
                    }
                />
            </View>
        </View>
    </KeyboardAvoidingView>
);
const styles = StyleSheet.create({
container: {
    margin: 10,
},
card: {
    backgroundColor: "#F2F2F2",
    margin: 10,
    marginTop: 20,
    borderRadius: 10,
    height: "90%",
    display: "flex",
},

input: {
    backgroundColor: "#FFF",
    height: 250,
    alignItems: "center",
    justifyContent: "center",
    borderRadius: 10,
    marginTop: 20,
    marginBottom: 20,
},
});
</code>```

答:
Use automaticallyAdjustContentInsets and contentContainerStyle properties and change your style like below.</p>
```<code> <KeyboardAvoidingView
        automaticallyAdjustContentInsets={false}
        behavior={null}
        contentContainerStyle={{ flex: 1 }}
        style={{
           backgroundColor: 'backgroundColor',
           flex: 1,
           height: '100%',
        }}
 >
 </KeyboardAvoidingView>
</code>```

Body:
I am trying to avoid the keyboard over the form, according to React Native documentation, I should be using KeyboardAwareScrollView component. the instructions are fairly simple, but I cant make it work. Am I missing anything?

return (
    <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        style={{ flex: 1 }}
    >
        <View style={styles.card}>
            <View style={styles.container}>
                <Options setIpt={setIpt} />
                <View style={styles.input}>
                <ShowIpt /> // form input here
                </View>
                <Button
                    title="Create"
                    color="#841584"
                    accessibilityLabel="Create"
                    onPress={() =>
                        navigation.navigate("Result", {
                            ipt: ipt,
                        })
                    }
                />
            </View>
        </View>
    </KeyboardAvoidingView>
);
const styles = StyleSheet.create({
container: {
    margin: 10,
},
card: {
    backgroundColor: "#F2F2F2",
    margin: 10,
    marginTop: 20,
    borderRadius: 10,
    height: "90%",
    display: "flex",
},

input: {
    backgroundColor: "#FFF",
    height: 250,
    alignItems: "center",
    justifyContent: "center",
    borderRadius: 10,
    marginTop: 20,
    marginBottom: 20,
},
});

Body:
Use automaticallyAdjustContentInsets and contentContainerStyle properties and change your style like below.

 <KeyboardAvoidingView
        automaticallyAdjustContentInsets={false}
        behavior={null}
        contentContainerStyle={{ flex: 1 }}
        style={{
           backgroundColor: 'backgroundColor',
           flex: 1,
           height: '100%',
        }}
 >
 </KeyboardAvoidingView>


问:
How can I convert the android resources int to a string. eg.: android.R.string.cancel?
How can I obtain the string value "cancel" from this resource int: android.R.string.cancel ?

thank you

答:
I know that's an old question, but it might help more people. What you can do is to call getIdentifier(). For that, you'll need to call it inserting after what value you want for a this variable, to make the string that you want for your resource ID. For exemple:

Your resources file:

```<code>R.string.cancel
</code>```

In java:

```<code>int resourceId = getResources().getIdentifier("cancel", "string", this.getPackageName())
println(getResources().getString(resourceId));
</code>```

Then, in your rescourceId variable, you'll have an equivalent to: R.string.cancel. And, in println, you'll have the value correspondent of your resources string.

In Kotlin:

```<code>val resourceId = this.resources.getIdentifier("cancel", "string", this.packageName)
println(resources.getString(resourceId))
</code>```

With the same explanation that I said before.

Body:
I know that's an old question, but it might help more people. What you can do is to call getIdentifier(). For that, you'll need to call it inserting after what value you want for a this variable, to make the string that you want for your resource ID. For exemple:

Your resources file:

R.string.cancel

In java:

int resourceId = getResources().getIdentifier("cancel", "string", this.getPackageName())
println(getResources().getString(resourceId));

Then, in your rescourceId variable, you'll have an equivalent to: R.string.cancel. And, in println, you'll have the value correspondent of your resources string.

In Kotlin:

val resourceId = this.resources.getIdentifier("cancel", "string", this.packageName)
println(resources.getString(resourceId))

With the same explanation that I said before.


问:
Angular: ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'forEach')
I try execute on my cards.component.ts

```<code>    notices: notice[];

    ngOnInit() {
      this.dataService.getCards().subscribe( data => { this.notices = data });
      this.notices.forEach(n => {
        console.log('test')
      });
    }
</code>```

I only want show something in console for every item is on "notices" but show me this error

ERROR Error: Uncaught (in promise): TypeError: Cannot read properties
of undefined (reading 'forEach')

答:
Array notices should be initialized in field declaration or in constructor of component

notices: notice[] = [];

or

constructor() { this.notices = [] }

Body:
I try execute on my cards.component.ts

    notices: notice[];

    ngOnInit() {
      this.dataService.getCards().subscribe( data => { this.notices = data });
      this.notices.forEach(n => {
        console.log('test')
      });
    }

I only want show something in console for every item is on "notices" but show me this error

ERROR Error: Uncaught (in promise): TypeError: Cannot read properties
of undefined (reading 'forEach')