问:
Jquery .click function for getting subcat of id element
I try to build a car search plugin, with 3 category levels.
Like: 1 row = Maincat, 2 row = Subcat, 3 row = Subsubcat...

Here is an example of what i want to do:
https://www.aez-wheels.com/3DKonfigurator/index.php?lcs=onz2sm13at&lng=en

in my code the first level appears and the second level loads. but the third level is not loading.
I Think the problem is, that the second row is created dynamicaly.
Can somebody tell me where i have a wrong code?

```<code>   // Loading WordPress hooks
    function __construct()
    {
        add_action( 'avada_after_header_wrapper', array($this, 'llm_car_conf_list') );

        // Register ajax action
        add_action( 'wp_ajax_get_cat', array($this, 'getCat') );

        // Register ajax action for non loged in user
        add_action('wp_ajax_nopriv_get_cat', array($this, 'getCat') );

    }

// function for the maincat
function llm_car_conf_list() {
            if ( is_front_page() ) {?>

            <div class="llm_car_container">
                <div class="car_wrapper">
                    <div class="car_row">
                        <div class="car_title"><h2>1. Fahrzeug wählen</h2></div>
                        <ul id="maincat" class="car_conf"><?php

            $categories = get_categories(array (
            'taxonomy'      => 'product_cat',
            'parent'        => 0
            ));

            foreach ( $categories as $category ) {
            printf( '<li class="car_list_item"><a id="%1$s">%2$s</a></li>',
                esc_html ($category->term_id ),
                esc_html( $category->cat_name )
                  );
            }
?></ul></div>

// Jquery to load first subcat
<script type="text/javascript">
                (function($){
                    $("#maincat li").click(function(){
                        $("#second_row").empty();
                        $.ajax({
                            type: "post",
                            url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
                            data: { action: 'get_cat', cat_id: $(this).find('a').attr('id') },
                            success: function(data) {
                                $("#second_row").append(data);
                            }
                        });
                    });
                })(jQuery);
            </script>
    <div class="car_row">
    <div class="car_title"><h2>2. Typ wählen</h2></div>
    <ul id="second_row" class="car_conf"></ul>
    </div>

    // Jquery to load subsubcat
 <script type="text/javascript">
                (function($){
                    $("#second_row li").click(function(){
                        $("#third_row").empty();
                        $.ajax({
                            type: "post",
                            url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
                            data: { action: 'get_cat', cat_id: $(this).find('a').attr('id') },
                            success: function(data) {
                                $("#third_row").append(data);
                            }
                        });

                    });
                })(jQuery);
            </script>
    <div class="car_row">
    <div class="car_title"><h2>3. Jahrgang wählen</h2></div>
    <ul id="third_row" class="car_conf"></ul>
    </div>

 </div>
 </div>
 <?php
            }
 }

    // Function to load the subcats

    function getCat() {
        $categories = get_categories(array (
            'taxonomy'      => 'product_cat',
            'child_of'      => $_POST['cat_id'],
            'parent'        => $_POST['cat_id']
        ));

        foreach ( $categories as $category ) {
            printf( '<li id="%1$s" class="car_list_item"><a id="%1$s">%2$s</a></li>',
                esc_html ($category->term_id ),
                esc_html( $category->cat_name )
                  );
            }
        die();
    }
</code>```

答:
Here is my full code, that works in my plugin</p>

```<code><?php
defined('ABSPATH') or die("Thanks for visting");

if ( ! class_exists( 'frontendAjaxDdown' ) ):
    class frontendAjaxDdown
    {

         // Loading WordPress hooks
        function __construct()
        {
            add_action( 'avada_after_header_wrapper', array($this, 'llm_car_conf_list') );

            // Register ajax action
            add_action( 'wp_ajax_get_cat', array($this, 'getCat') );
            add_action( 'wp_ajax_get_subcat', array($this, 'getSubCat') );
            add_action( 'wp_ajax_get_subsubcat', array($this, 'getSubSubCat') );

            // Register ajax action for non loged in user
            add_action('wp_ajax_nopriv_get_cat', array($this, 'getCat') );
            add_action('wp_ajax_nopriv_get_subcat', array($this, 'getSubCat') );
            add_action('wp_ajax_nopriv_get_subsubcat', array($this, 'getSubSubCat') );

        }

function llm_car_conf_list() {
    if ( is_front_page() ) {?>

        <div class="llm_car_container">
           <div class="car_wrapper">
             <div class="car_row">
                 <div class="car_title"><h2>1. Fahrzeug wählen</h2></div>
                 <ul id="maincat" class="car_conf"><?php

                    $categories = get_categories(array (
                    'taxonomy'      => 'product_cat',
                    'hide_empty'    => 1,
                    'parent'        => 0
                    ));

                    foreach ( $categories as $category ) {
                    printf( '<li class="car_list_item"><a id="%1$s"><img src="http://climair-schweiz.ch.185-117-169-242.srv201.webpreview.ch/wp-content/uploads/carbrands/%2$s.png" width="20px">%2$s</a></li>',
                        esc_html ($category->term_id ),
                        esc_html( $category->cat_name )
                    );
                    } ?>
                </ul>
                </div>

                <script type="text/javascript">
                        (function($){
                            $("#maincat li").click(function(){
                                $("#second_row, #third_row, #fourth_row").empty();
                                $.ajax({
                                    type: "post",
                                    url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
                                    data: { action: 'get_cat', cat_id: $(this).find('a').attr('id') },
                                    success: function(data) {
                                        $("#second_row").append(data);
                                    }
                                });
                            });
                        })(jQuery);
                </script>
                <div class="car_row">
                  <div class="car_title"><h2>2. Model wählen</h2></div>
<ul id="second_row" class="car_conf"></ul>
                </div>

                <div class="car_row">
                  <div class="car_title"><h2>3. Baujahr | Typ wählen</h2></div>
                  <ul id="third_row" class="car_conf"></ul>
                </div>

                <div class="car_row">
                  <div class="car_title"><h2>4. Form | Türen wählen</h2></div>
                  <ul id="fourth_row" class="car_conf"></ul>
                </div>

           </div>
        </div> <?php
    }
}

function getCat() {

    $categories = get_categories(array (
        'taxonomy'      => 'product_cat',
        'hide_empty'    => 1,
        'child_of'      => $_POST['cat_id'],
        'parent'        => $_POST['cat_id']
    ));

    foreach ( $categories as $category ) {
        printf( '<li id="%1$s" class="car_list_item"><a id="%1$s">%2$s</a></li>',
            esc_html ($category->term_id ),
            esc_html( $category->cat_name )
        );
    } ?>
    <script type="text/javascript">
        (function($){
            $("#second_row li").click(function(){
                $("#third_row, #fourth_row").empty();
                $.ajax({
                    type: "post",
                    url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
                    data: { action: 'get_subcat', cat_id: $(this).find('a').attr('id') },
                    success: function(data) {
                        $("#third_row").append(data);
                    }
                });

            });
        })(jQuery);
    </script> <?php
    die();
}

function getSubCat() {
    $categories = get_categories(array (
        'taxonomy'      => 'product_cat',
        'hide_empty'    => 1,
        'child_of'      => $_POST['cat_id'],
        'parent'        => $_POST['cat_id']
    ));

    foreach ( $categories as $category ) {
        printf( '<li id="%1$s" class="car_list_item"><a id="%1$s">%2$s</a></li>',
            esc_html ($category->term_id ),
            esc_html( $category->cat_name )
              );
        }
    ?> <script type="text/javascript">
            (function($){
                $("#third_row li").click(function(){
                    $("#fourth_row").empty();
                    $.ajax({
                        type: "post",
                        url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
                        data: { action: 'get_subsubcat', cat_id: $(this).find('a').attr('id') },
                        success: function(data) {
                            $("#fourth_row").append(data);
                        }
                    });

                });
            })(jQuery);
        </script> <?php
    die();
}

function getSubSubCat() {
    $categories = get_categories(array (
        'taxonomy'      => 'product_cat',
        'hide_empty'    => 1,
        'child_of'      => $_POST['cat_id'],
        'parent'        => $_POST['cat_id']
    ));

    foreach ( $categories as $category ) {
        printf( '<li class="car_list_item"><a href="%1$s">%2$s</a></li>',
        esc_url( get_category_link( $category->term_id ) ),
            esc_html( $category->cat_name )
              );
        }

    die();
}

}
endif;
new frontendAjaxDdown();
?>
</code>```

Body:
I try to build a car search plugin, with 3 category levels.
Like: 1 row = Maincat, 2 row = Subcat, 3 row = Subsubcat...

Here is an example of what i want to do:
https://www.aez-wheels.com/3DKonfigurator/index.php?lcs=onz2sm13at&lng=en

in my code the first level appears and the second level loads. but the third level is not loading.
I Think the problem is, that the second row is created dynamicaly.
Can somebody tell me where i have a wrong code?

   // Loading WordPress hooks
    function __construct()
    {
        add_action( 'avada_after_header_wrapper', array($this, 'llm_car_conf_list') );

        // Register ajax action
        add_action( 'wp_ajax_get_cat', array($this, 'getCat') );

        // Register ajax action for non loged in user
        add_action('wp_ajax_nopriv_get_cat', array($this, 'getCat') );

    }

// function for the maincat
function llm_car_conf_list() {
            if ( is_front_page() ) {?>

1. Fahrzeug wählen

<?php

            $categories = get_categories(array (
            'taxonomy'      => 'product_cat',
            'parent'        => 0
            ));

            foreach ( $categories as $category ) {
            printf( '
%2$s
',
                esc_html ($category->term_id ),
                esc_html( $category->cat_name )
                  );
            }
?>

// Jquery to load first subcat

2. Typ wählen

    // Jquery to load subsubcat

3. Jahrgang wählen

 <?php
            }
 }

    // Function to load the subcats

    function getCat() {
        $categories = get_categories(array (
            'taxonomy'      => 'product_cat',
            'child_of'      => $_POST['cat_id'],
            'parent'        => $_POST['cat_id']
        ));

        foreach ( $categories as $category ) {
            printf( '
%2$s
',
                esc_html ($category->term_id ),
                esc_html( $category->cat_name )
                  );
            }
        die();
    }

Body:
Here is my full code, that works in my plugin

<?php
defined('ABSPATH') or die("Thanks for visting");

if ( ! class_exists( 'frontendAjaxDdown' ) ):
    class frontendAjaxDdown
    {

         // Loading WordPress hooks
        function __construct()
        {
            add_action( 'avada_after_header_wrapper', array($this, 'llm_car_conf_list') );

            // Register ajax action
            add_action( 'wp_ajax_get_cat', array($this, 'getCat') );
            add_action( 'wp_ajax_get_subcat', array($this, 'getSubCat') );
            add_action( 'wp_ajax_get_subsubcat', array($this, 'getSubSubCat') );

            // Register ajax action for non loged in user
            add_action('wp_ajax_nopriv_get_cat', array($this, 'getCat') );
            add_action('wp_ajax_nopriv_get_subcat', array($this, 'getSubCat') );
            add_action('wp_ajax_nopriv_get_subsubcat', array($this, 'getSubSubCat') );

        }

function llm_car_conf_list() {
    if ( is_front_page() ) {?>

        <div class="llm_car_container">
           <div class="car_wrapper">
             <div class="car_row">
                 <div class="car_title"><h2>1. Fahrzeug wählen</h2></div>
                 <ul id="maincat" class="car_conf"><?php

                    $categories = get_categories(array (
                    'taxonomy'      => 'product_cat',
                    'hide_empty'    => 1,
                    'parent'        => 0
                    ));

                    foreach ( $categories as $category ) {
                    printf( '<li class="car_list_item"><a id="%1$s"><img src="http://climair-schweiz.ch.185-117-169-242.srv201.webpreview.ch/wp-content/uploads/carbrands/%2$s.png" width="20px">%2$s</a></li>',
                        esc_html ($category->term_id ),
                        esc_html( $category->cat_name )
                    );
                    } ?>
                </ul>
                </div>

                <script type="text/javascript">
                        (function($){
                            $("#maincat li").click(function(){
                                $("#second_row, #third_row, #fourth_row").empty();
                                $.ajax({
                                    type: "post",
                                    url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
                                    data: { action: 'get_cat', cat_id: $(this).find('a').attr('id') },
                                    success: function(data) {
                                        $("#second_row").append(data);
                                    }
                                });
                            });
                        })(jQuery);
                </script>
                <div class="car_row">
                  <div class="car_title"><h2>2. Model wählen</h2></div>
<ul id="second_row" class="car_conf"></ul>
                </div>

                <div class="car_row">
                  <div class="car_title"><h2>3. Baujahr | Typ wählen</h2></div>
                  <ul id="third_row" class="car_conf"></ul>
                </div>

                <div class="car_row">
                  <div class="car_title"><h2>4. Form | Türen wählen</h2></div>
                  <ul id="fourth_row" class="car_conf"></ul>
                </div>

           </div>
        </div> <?php
    }
}

function getCat() {

    $categories = get_categories(array (
        'taxonomy'      => 'product_cat',
        'hide_empty'    => 1,
        'child_of'      => $_POST['cat_id'],
        'parent'        => $_POST['cat_id']
    ));

    foreach ( $categories as $category ) {
        printf( '<li id="%1$s" class="car_list_item"><a id="%1$s">%2$s</a></li>',
            esc_html ($category->term_id ),
            esc_html( $category->cat_name )
        );
    } ?>
    <script type="text/javascript">
        (function($){
            $("#second_row li").click(function(){
                $("#third_row, #fourth_row").empty();
                $.ajax({
                    type: "post",
                    url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
                    data: { action: 'get_subcat', cat_id: $(this).find('a').attr('id') },
                    success: function(data) {
                        $("#third_row").append(data);
                    }
                });

            });
        })(jQuery);
    </script> <?php
    die();
}

function getSubCat() {
    $categories = get_categories(array (
        'taxonomy'      => 'product_cat',
        'hide_empty'    => 1,
        'child_of'      => $_POST['cat_id'],
        'parent'        => $_POST['cat_id']
    ));

    foreach ( $categories as $category ) {
        printf( '<li id="%1$s" class="car_list_item"><a id="%1$s">%2$s</a></li>',
            esc_html ($category->term_id ),
            esc_html( $category->cat_name )
              );
        }
    ?> <script type="text/javascript">
            (function($){
                $("#third_row li").click(function(){
                    $("#fourth_row").empty();
                    $.ajax({
                        type: "post",
                        url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
                        data: { action: 'get_subsubcat', cat_id: $(this).find('a').attr('id') },
                        success: function(data) {
                            $("#fourth_row").append(data);
                        }
                    });

                });
            })(jQuery);
        </script> <?php
    die();
}

function getSubSubCat() {
    $categories = get_categories(array (
        'taxonomy'      => 'product_cat',
        'hide_empty'    => 1,
        'child_of'      => $_POST['cat_id'],
        'parent'        => $_POST['cat_id']
    ));

    foreach ( $categories as $category ) {
        printf( '<li class="car_list_item"><a href="%1$s">%2$s</a></li>',
        esc_url( get_category_link( $category->term_id ) ),
            esc_html( $category->cat_name )
              );
        }

    die();
}

}
endif;
new frontendAjaxDdown();
?>


来源: stackexchange

问:
Getting 3 full years in json format
What would be the best way to create a json object with a 3 full years.

For example:

```<code>{
    2017:{
        jan:[
            {day:'monday', timestamp:12512421},
            {day:'tuseday', timestamp:151512}
        ]...
    },
    2018:{
        jan:[
                {day:'monday', timestamp:12512421},
                {day:'tuseday', timestamp:151512}
        ]...
    }
    2019:{
        jan:[
            {day:'monday', timestamp:12512421},
            {day:'tuseday', timestamp:151512}
        ]...
    }
}
</code>```

I need to be able to display a week’s in the future. That is for example: what dates are in week 8 on the year 2019. I need some idea of where to start to start formulating the json object… or if it already exists in some kind of library.

But I’m not sure what would be the start to start trying out.

答:
I don't know if this is a good way of achieving this... but anyways this is how i have it now.</p>

```<code>setYearObject(yearStart, yearEnd) {
    let obj = {};
    let start = new Date(yearStart,0);
    let currentYear = yearStart;
    let currentDay = start;
    let week = [];

    while(currentYear <= yearEnd){
        obj[currentYear] = [];
        currentYear++;
    }
    currentYear = yearStart;
    console.log(currentDay.getDate());
    while(currentYear !== parseInt(yearEnd) +1){
        week[currentDay.getDay()] = {day: currentDay.getDate(), month:currentDay.getMonth(), dayOfWeek: this.getWeekday(currentDay.getDay())}

        if(currentDay.getDay() >= 6){
            obj[currentYear].push(week);
            week = [];
        }
        currentDay.setDate(currentDay.getDate() + 1);
        currentYear = currentDay.getFullYear();
    }

    for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
            let tmpYear = parseInt(property);
            if(obj[property].length <=52 && obj[property].length >= 1){
                // obj[(tmpYear)].push(obj[(tmpYear + 1)][0])
                console.log(obj[tmpYear + 1])
                if( obj[tmpYear + 1] !== undefined){
                    if((obj[tmpYear +1]).length >= 1){
                        obj[tmpYear].push(obj[tmpYear + 1 ][0]);
                    }
                }
            }
        }
      }
    console.log(obj);
    return obj;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Getting 3 full years in json format

Body:
What would be the best way to create a json object with a 3 full years.

For example:

{
    2017:{
        jan:[
            {day:'monday', timestamp:12512421},
            {day:'tuseday', timestamp:151512}
        ]...
    },
    2018:{
        jan:[
                {day:'monday', timestamp:12512421},
                {day:'tuseday', timestamp:151512}
        ]...
    }
    2019:{
        jan:[
            {day:'monday', timestamp:12512421},
            {day:'tuseday', timestamp:151512}
        ]...
    }
}

I need to be able to display a week’s in the future. That is for example: what dates are in week 8 on the year 2019. I need some idea of where to start to start formulating the json object… or if it already exists in some kind of library.

But I’m not sure what would be the start to start trying out.

Body:
I don't know if this is a good way of achieving this... but anyways this is how i have it now.

setYearObject(yearStart, yearEnd) {
    let obj = {};
    let start = new Date(yearStart,0);
    let currentYear = yearStart;
    let currentDay = start;
    let week = [];

    while(currentYear <= yearEnd){
        obj[currentYear] = [];
        currentYear++;
    }
    currentYear = yearStart;
    console.log(currentDay.getDate());
    while(currentYear !== parseInt(yearEnd) +1){
        week[currentDay.getDay()] = {day: currentDay.getDate(), month:currentDay.getMonth(), dayOfWeek: this.getWeekday(currentDay.getDay())}

        if(currentDay.getDay() >= 6){
            obj[currentYear].push(week);
            week = [];
        }
        currentDay.setDate(currentDay.getDate() + 1);
        currentYear = currentDay.getFullYear();
    }

    for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
            let tmpYear = parseInt(property);
            if(obj[property].length <=52 && obj[property].length >= 1){
                // obj[(tmpYear)].push(obj[(tmpYear + 1)][0])
                console.log(obj[tmpYear + 1])
                if( obj[tmpYear + 1] !== undefined){
                    if((obj[tmpYear +1]).length >= 1){
                        obj[tmpYear].push(obj[tmpYear + 1 ][0]);
                    }
                }
            }
        }
      }
    console.log(obj);
    return obj;
}


问:
Remove character from dynamic string
I have a file with some junk values and i need to get rid of them while loading that file into a table.
Giving here some example. File is semicolon separated, and last column has those junk values.

```<code>2019-02-20;05377378;ABC+xY+++Rohit Anita Chicago
2019-02-20;05201343;ABC+xY++Gustav Russia
2019-02-20;07348738;ABC+xy+++Jain Ram Ambarnath
</code>```

Now the last column I have to load without ABC+xY+++  value.
but some row i have ABC+xY+++ and some ABC+xY++. any suggestion to get rid of this. which means 2 times or 3 times + is available

I am using informatica powercenter for loading this file.
in expression i need to create some substr/instr function. which i can put test here in oracle sql as well to understand quickly if the value coming is properly.

and my expected output is

Any suggestion please.

Thanks,
Bithun

答:
I think you are searching for the following:</p>

```<code>WITH dat AS (SELECT '2019-02-20;05373487378;ABC+xY++Rohit Anita Chicago' AS adress FROM dual)
SELECT regexp_REPLACE(adress, '(.*);ABC\+x[yY]\+{2,3}(.*)','\1;\2') FROM dat
</code>```

Title: Remove character from dynamic string

Body:
I have a file with some junk values and i need to get rid of them while loading that file into a table.
Giving here some example. File is semicolon separated, and last column has those junk values.

2019-02-20;05377378;ABC+xY+++Rohit Anita Chicago
2019-02-20;05201343;ABC+xY++Gustav Russia
2019-02-20;07348738;ABC+xy+++Jain Ram Ambarnath

Now the last column I have to load without ABC+xY+++  value.
but some row i have ABC+xY+++ and some ABC+xY++. any suggestion to get rid of this. which means 2 times or 3 times + is available

I am using informatica powercenter for loading this file.
in expression i need to create some substr/instr function. which i can put test here in oracle sql as well to understand quickly if the value coming is properly.

and my expected output is

Any suggestion please.

Thanks,
Bithun

Body:
I think you are searching for the following:

WITH dat AS (SELECT '2019-02-20;05373487378;ABC+xY++Rohit Anita Chicago' AS adress FROM dual)
SELECT regexp_REPLACE(adress, '(.*);ABC\+x[yY]\+{2,3}(.*)','\1;\2') FROM dat


问:
How to mount a kubernetes.io/dockerconfigjson
I have a secret of type kubernetes.io/dockerconfigjson:

```<code>$ kubectl describe secrets dockerjson

Name:         dockerjson
Namespace:    my-prd
Labels:       <none>
Annotations:  <none>

Type:  kubernetes.io/dockerconfigjson

Data
====
.dockerconfigjson:  1335 bytes
</code>```

When I try to mount this secret into a container - I cannot find a config.json:

```<code>- name: dump
  image: kaniko-executor:debug
  imagePullPolicy: Always
  command: ["/busybox/find", "/", "-name", "config.json"]
  volumeMounts:
  - name: docker-config
    mountPath: /foobar
volumes:
- name: docker-config
  secret:
    secretName: dockerjson
      defaultMode: 256
</code>```

which only prints:

```<code>/kaniko/.docker/config.json
</code>```

Is this supported at all or am I doing something wrong?

Am using OpenShift 3.9 - which should be Kubernetes 1.9.

答:
```<code>apiVersion: v1
kind: Pod
metadata:
  name: kaniko
spec:
  containers:
  - name: kaniko
    image: gcr.io/kaniko-project/executor:debug-v0.9.0
    command:
    - /busybox/cat
    resources:
      limits:
        cpu: 2
        memory: 2Gi
      requests:
        cpu: 0.5
        memory: 500Mi
    tty: true
    volumeMounts:
      - name: docker-config
        mountPath: /kaniko/.docker/
  volumes:
    - name: docker-config
      secret:
        secretName: dockerjson
        items:
          - key: .dockerconfigjson
            path: config.json
</code>```

Body:
I have a secret of type kubernetes.io/dockerconfigjson:

$ kubectl describe secrets dockerjson

Name:         dockerjson
Namespace:    my-prd
Labels:       <none>
Annotations:  <none>

Type:  kubernetes.io/dockerconfigjson

Data
====
.dockerconfigjson:  1335 bytes

When I try to mount this secret into a container - I cannot find a config.json:

- name: dump
  image: kaniko-executor:debug
  imagePullPolicy: Always
  command: ["/busybox/find", "/", "-name", "config.json"]
  volumeMounts:
  - name: docker-config
    mountPath: /foobar
volumes:
- name: docker-config
  secret:
    secretName: dockerjson
      defaultMode: 256

which only prints:

/kaniko/.docker/config.json

Is this supported at all or am I doing something wrong?

Am using OpenShift 3.9 - which should be Kubernetes 1.9.


问:
Python turtle color changing and fill
This code draws a shape when the user inputs the number of squares to draw and the size of those squares. I want the color to change for every square that is drawn, and for it to get filled in.  But the code gets stuck:</p>

```<code>import turtle
t = turtle.Turtle()

size = int(input("How long do you want the side lengths to be?"))
number = int(input("How many squares do you want in the image?"))
red = 40.0
blue = 30.0
green = 10.0

def square (size):
 count = 0
 while count < 4:
  t.forward(size)
  t.right(90)
  count = count + 1

def drawing(number):
  times = 0
  while times < number:
    t.pencolor(red, blue, green)
    t.fillcolor(red, blue, green)
    t.begin_fill()
    square(size)
    t.right(360/number)
    if t.filling():
      t.pensize(5)
    else:
      t.pensize(3)
    t.color()
    (red + 1, blue + 1, green + 1)
    times = times + 1

drawing(number)
</code>```

答:
There are several problems with your code -- the primary one is you're using the wrong color model.  By default, turtle colors are specified as floating point values between 0.0 and 1.0.  However, you want to use values like those in your code, we can switch this via colormode(255) which allows values from 0 to 255.

Next, a begin_fill() has to have a matching end_fill() which you are missing.  Colors are specified in the order (red, green, blue), not (red, blue, green).  Also, if you set both pencolor() and fillcolor() to the same color, you can simply use the one call color().

Finally, these two statements don't do anything:

```<code>t.color()
(red + 1, blue + 1, green + 1)
</code>```

as far as your code is concerned.  You need to rethink them.  Below is my rework of your code which addresses the above issues and some other details:

```<code>from turtle import Screen, Turtle

def square(size):
    count = 0

    if turtle.filling():
        turtle.pensize(5)
    else:
        turtle.pensize(3)

    while count < 4:
        turtle.forward(size)
        turtle.right(90)
        count += 1

def drawing(number):
    red = 30
    green = 10
    blue = 20

    times = 0

    while times < number:
        turtle.color(red % 255, green % 255, blue % 255)

        turtle.begin_fill()
        square(size)
        turtle.end_fill()

        turtle.right(360 / number)

        red, green, blue = red + 20, green + 30, blue + 10
        times += 1

size = int(input("How long do you want the side lengths to be? "))
number = int(input("How many squares do you want in the image? "))

screen = Screen()
screen.colormode(255)

turtle = Turtle()
turtle.speed('fastest')  # because I have no patience

drawing(number)

screen.exitonclick()
</code>```

Title: Python turtle color changing and fill

Body:
This code draws a shape when the user inputs the number of squares to draw and the size of those squares. I want the color to change for every square that is drawn, and for it to get filled in.  But the code gets stuck:

import turtle
t = turtle.Turtle()

size = int(input("How long do you want the side lengths to be?"))
number = int(input("How many squares do you want in the image?"))
red = 40.0
blue = 30.0
green = 10.0

def square (size):
 count = 0
 while count < 4:
  t.forward(size)
  t.right(90)
  count = count + 1

def drawing(number):
  times = 0
  while times < number:
    t.pencolor(red, blue, green)
    t.fillcolor(red, blue, green)
    t.begin_fill()
    square(size)
    t.right(360/number)
    if t.filling():
      t.pensize(5)
    else:
      t.pensize(3)
    t.color()
    (red + 1, blue + 1, green + 1)
    times = times + 1

drawing(number)

Body:
There are several problems with your code -- the primary one is you're using the wrong color model.  By default, turtle colors are specified as floating point values between 0.0 and 1.0.  However, you want to use values like those in your code, we can switch this via colormode(255) which allows values from 0 to 255.

Next, a begin_fill() has to have a matching end_fill() which you are missing.  Colors are specified in the order (red, green, blue), not (red, blue, green).  Also, if you set both pencolor() and fillcolor() to the same color, you can simply use the one call color().

Finally, these two statements don't do anything:

t.color()
(red + 1, blue + 1, green + 1)

as far as your code is concerned.  You need to rethink them.  Below is my rework of your code which addresses the above issues and some other details:

from turtle import Screen, Turtle

def square(size):
    count = 0

    if turtle.filling():
        turtle.pensize(5)
    else:
        turtle.pensize(3)

    while count < 4:
        turtle.forward(size)
        turtle.right(90)
        count += 1

def drawing(number):
    red = 30
    green = 10
    blue = 20

    times = 0

    while times < number:
        turtle.color(red % 255, green % 255, blue % 255)

        turtle.begin_fill()
        square(size)
        turtle.end_fill()

        turtle.right(360 / number)

        red, green, blue = red + 20, green + 30, blue + 10
        times += 1

size = int(input("How long do you want the side lengths to be? "))
number = int(input("How many squares do you want in the image? "))

screen = Screen()
screen.colormode(255)

turtle = Turtle()
turtle.speed('fastest')  # because I have no patience

drawing(number)

screen.exitonclick()


问:
Android query for contact content provider in two android platform(1.6) and android platform(2.2)
I am looking for the solution to get contact details (Phone,Email) from the device. I have implemented code for OS 1.6 as well as for 2.2. I am building an application with API level 4 (1.6), but when I run the build in 2.2 device I am getting email and phone string null.
                    do you have a proper solution for this? please replay...</p>

答:
Use the following method to get the calendar base uri, Since it has been changed from Os Version 2.2.

private String getCalendarUriBase() {

```<code>String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor managedCursor = null;
try {
    managedCursor = managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
    // eat
}

if (managedCursor != null) {
    calendarUriBase = "content://calendar/";
} else {
    calendars = Uri.parse("content://com.android.calendar/calendars");
    try {
        managedCursor = managedQuery(calendars, null, null, null, null);
    } catch (Exception e) {
        // eat
    }

    if (managedCursor != null) {
        calendarUriBase = "content://com.android.calendar/";
    }

}

return calendarUriBase;
</code>```

}

ContentLicense: CC BY-SA 3.0

Body:
Use the following method to get the calendar base uri, Since it has been changed from Os Version 2.2.

private String getCalendarUriBase() {

String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor managedCursor = null;
try {
    managedCursor = managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
    // eat
}

if (managedCursor != null) {
    calendarUriBase = "content://calendar/";
} else {
    calendars = Uri.parse("content://com.android.calendar/calendars");
    try {
        managedCursor = managedQuery(calendars, null, null, null, null);
    } catch (Exception e) {
        // eat
    }

    if (managedCursor != null) {
        calendarUriBase = "content://com.android.calendar/";
    }

}

return calendarUriBase;

}


问:
How to change language of Dynamic Android App?
I want to setup language switcher for android app which is complete build already, i want solution for localizing android dynamic app.</p>

答: If you call Locale.setDefault(Locale.GERMAN) it loads German as default locale in your app.  You can select any locale that you want and your device supports.


问:
Segmentation fault in llvm pass when using RegisterStandardPasses
I am trying to run an LLVM pass, but I get segmentation fault. Below is the code for my LLVM pass.

The compiler runs and produces the output. runOnBasicBlock works, but afterwards we get this error:

Segmentation fault (core dumped)

When I remove RegisterStandardPasses and loadPass (last lines), the code works fine. Any idea what causes this? Thanks

We load the compiler pass using the following line.

```<code>opt -load ./plugin_build/NvmInstrumenter.so -NvmInstrumenter -stats < simple.bc
</code>```

We use LLVM and Clang version 5.0.0 both downloaded and built at the same time.

The code from the compiler pass:

```<code>#include "llvm/Pass.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/PassRegistry.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
// For output
#include "llvm/Support/raw_ostream.h"

using namespace llvm;

namespace {
  struct NvmInstrumenter : public BasicBlockPass {
    static char ID;
    NvmInstrumenter() : BasicBlockPass(ID) {}
    virtual bool runOnBasicBlock(BasicBlock &BB) {
      BasicBlock::iterator i;
      errs() << "Basic Block\n";
      for( i=BB.begin(); i!=BB.end(); i++ ) {
    errs() << "  " << i->getOpcodeName() << "\n";
      }
      return false;
    }
  };
}

// Pass info
char NvmInstrumenter::ID = 0; // LLVM ignores the actual value
static RegisterPass<NvmInstrumenter> X("NvmInstrumenter", "Example pass", false, false);

static void loadPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM) {
  PM.add(new NvmInstrumenter());
}

static RegisterStandardPasses clangtoolLoader_Ox(PassManagerBuilder::EP_OptimizerLast, loadPass);
static RegisterStandardPasses clangtoolLoader_O0(PassManagerBuilder::EP_EnabledOnOptLevel0, loadPass);
</code>```

Here is the backtrace:

```<code>Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7ff4900 in ?? ()
(gdb) bt
#0  0x00007ffff7ff4900 in ?? ()
#1  0x00007ffff58fb4ab in llvm::object_deleter<llvm::SmallVector<std::pair<llvm::PassManagerBuilder::ExtensionPointTy, std::function<void (llvm::PassManagerBuilder const&, llvm::legacy::PassManagerBase&)> >, 8u> >::call(void*) () from /usr/lib/llvm-5.0/bin/../lib/libLLVM-5.0.so.1
#2  0x00007ffff4cef87d in llvm::ManagedStaticBase::destroy() const () from /usr/lib/llvm-5.0/bin/../lib/libLLVM-5.0.so.1
#3  0x00007ffff4cefa15 in llvm::llvm_shutdown() () from /usr/lib/llvm-5.0/bin/../lib/libLLVM-5.0.so.1
#4  0x00005555555f0ddf in main ()
</code>```

答:
You're not alone with this error (https://bugs.llvm.org/show_bug.cgi?id=34573), LLVM seems to crash at the end of the program when RegisterStandardPasses is used since LLVM 5.

According to this answer: https://github.com/sampsyo/llvm-pass-skeleton/issues/7#issuecomment-401834287 a solution is to add -Wl,-znodelete to the compiler flags when you link your program. It worked for me.

Body:
I am trying to run an LLVM pass, but I get segmentation fault. Below is the code for my LLVM pass.

The compiler runs and produces the output. runOnBasicBlock works, but afterwards we get this error:

Segmentation fault (core dumped)

When I remove RegisterStandardPasses and loadPass (last lines), the code works fine. Any idea what causes this? Thanks

We load the compiler pass using the following line.

opt -load ./plugin_build/NvmInstrumenter.so -NvmInstrumenter -stats < simple.bc

We use LLVM and Clang version 5.0.0 both downloaded and built at the same time.

The code from the compiler pass:

#include "llvm/Pass.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/PassRegistry.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
// For output
#include "llvm/Support/raw_ostream.h"

using namespace llvm;

namespace {
  struct NvmInstrumenter : public BasicBlockPass {
    static char ID;
    NvmInstrumenter() : BasicBlockPass(ID) {}
    virtual bool runOnBasicBlock(BasicBlock &BB) {
      BasicBlock::iterator i;
      errs() << "Basic Block\n";
      for( i=BB.begin(); i!=BB.end(); i++ ) {
    errs() << "  " <getOpcodeName() << "\n";
      }
      return false;
    }
  };
}

// Pass info
char NvmInstrumenter::ID = 0; // LLVM ignores the actual value
static RegisterPass<NvmInstrumenter> X("NvmInstrumenter", "Example pass", false, false);

static void loadPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM) {
  PM.add(new NvmInstrumenter());
}

static RegisterStandardPasses clangtoolLoader_Ox(PassManagerBuilder::EP_OptimizerLast, loadPass);
static RegisterStandardPasses clangtoolLoader_O0(PassManagerBuilder::EP_EnabledOnOptLevel0, loadPass);

Here is the backtrace:

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7ff4900 in ?? ()
(gdb) bt
#0  0x00007ffff7ff4900 in ?? ()
#1  0x00007ffff58fb4ab in llvm::object_deleter<llvm::SmallVector<std::pair<llvm::PassManagerBuilder::ExtensionPointTy, std::function<void (llvm::PassManagerBuilder const&, llvm::legacy::PassManagerBase&)> >, 8u> >::call(void*) () from /usr/lib/llvm-5.0/bin/../lib/libLLVM-5.0.so.1
#2  0x00007ffff4cef87d in llvm::ManagedStaticBase::destroy() const () from /usr/lib/llvm-5.0/bin/../lib/libLLVM-5.0.so.1
#3  0x00007ffff4cefa15 in llvm::llvm_shutdown() () from /usr/lib/llvm-5.0/bin/../lib/libLLVM-5.0.so.1
#4  0x00005555555f0ddf in main ()


问:
Tuple swap with indexOf
I'm trying to swap positions of elements in this array with a tuple swap and indexOf()

```<code>array1 = [1, 2, 3, 4, 5, 6, 7, 8]
</code>```

should equal:  [1, 2, 4, 3, 5, 6, 7, 8]

```<code>[ array1[array1.indexOf(3)], array1[array1.indexOf(4)] ] =

[ array1[array1.indexOf(4)], array1[array1.indexOf(3)] ]

</code>```

the evaluated result is simply the swapped elements and not the array itself..

```<code>[4, 3]
</code>```

How can I get the whole array back?

答:
You can use array map function and check the index. map will return a new array

let array1 = [1, 2, 3, 4, 5, 6, 7, 8];
let newArray = array1.map(function(item, index) {
  if (index === 2) {
    return array1[index + 1]
  } else if (index === 3) {
    return array1[index - 1]
  } else {
    return item
  }

})

console.log(newArray)```

Title: Tuple swap with indexOf

Body:
I'm trying to swap positions of elements in this array with a tuple swap and indexOf()

array1 = [1, 2, 3, 4, 5, 6, 7, 8]

should equal:  [1, 2, 4, 3, 5, 6, 7, 8]

[ array1[array1.indexOf(3)], array1[array1.indexOf(4)] ] =

[ array1[array1.indexOf(4)], array1[array1.indexOf(3)] ]

the evaluated result is simply the swapped elements and not the array itself..

[4, 3]

How can I get the whole array back?


问:
overloaded method not seen in subclass

Possible Duplicates:

  C++ overload resolution

  Why does an overridden function in the derived class hide other overloads of the base class?

Why the following example:

```<code>class A {
    public:
        void f(int x){ }
};

class B : public A {
    public:
        void f(float a, int b){ }
};

int main(){
    B *b = new B;
    b->f(1);
};
</code>```

causes:

test.cpp: In function ‘int main()’:
test.cpp:13: error: no matching function for call to ‘B::f(int)’
test.cpp:8: note: candidates are: void B::f(float, int)

f(int) and f(float, int) have different signatures. Why is it causing an error?

EDIT

I understand it's hiding. I am asking why is this happening?

答:
void f(float a, int b){ } defined in the derived class hides void f(int x){ } in the base class.

Why?

Read this answer.

Solution

```<code> using A::f; // add this above f's definition in the derived class
</code>```

Title: overloaded method not seen in subclass

Body:
Possible Duplicates:

  C++ overload resolution

  Why does an overridden function in the derived class hide other overloads of the base class?

Why the following example:

class A {
    public:
        void f(int x){ }
};

class B : public A {
    public:
        void f(float a, int b){ }
};

int main(){
    B *b = new B;
    b->f(1);
};

causes:

test.cpp: In function ‘int main()’:
test.cpp:13: error: no matching function for call to ‘B::f(int)’
test.cpp:8: note: candidates are: void B::f(float, int)

f(int) and f(float, int) have different signatures. Why is it causing an error?

EDIT

I understand it's hiding. I am asking why is this happening?

Body:
void f(float a, int b){ } defined in the derived class hides void f(int x){ } in the base class.

Why?

Read this answer.

Solution

 using A::f; // add this above f's definition in the derived class


问:
How do I find the name of soccer players with same first name but different surnames?
I need to find the names of players from soccer team A that have the same first name but different surname as players from soccer team B. I need to produce the full names of all players from Team A, not just 'John'. I am able to use an additional column with Player IDs unique across all teams.

Basically table looks like this:

```<code>FirstName  LastName     Team
John       Snow         A
Batman     Dies         B
John       Dies         B
</code>```

I can produce a list of Team A names with the same first name as Team B players.

```<code>SELECT firstname, lastname FROM table
</code>```

Even though surname can't be used for one entry, it should be considered for other entries.

答:
As simple as:

```<code>SELECT DISTINCT A.* FROM Table A
INNER JOIN Table B
ON A.FirstName = B.FirstName AND A.LastName <> B.LastName
WHERE A.Team = 'A' AND B.Team = 'B'```

Body:
I need to find the names of players from soccer team A that have the same first name but different surname as players from soccer team B. I need to produce the full names of all players from Team A, not just 'John'. I am able to use an additional column with Player IDs unique across all teams.

Basically table looks like this:

FirstName  LastName     Team
John       Snow         A
Batman     Dies         B
John       Dies         B

I can produce a list of Team A names with the same first name as Team B players.

SELECT firstname, lastname FROM table

Even though surname can't be used for one entry, it should be considered for other entries.

Body:
As simple as:

SELECT DISTINCT A.* FROM Table A
INNER JOIN Table B
ON A.FirstName = B.FirstName AND A.LastName <> B.LastName
WHERE A.Team = 'A' AND B.Team = 'B'


问:
Kafka shutdown with zookeeper timeout
I am trying to install Kafka setup with 3 Kafka Brokers in single zookeeper node but i am seeing Kafka process getting down in fraction of minutes and throwing error in Kafka logs:</p>

```<code>2019-05-29 14:06:42,508] INFO Opening socket connection to server kafka3/192.168.1.103:2181. Will not attempt to authenticate using SASL (unknown error) (org.apache.zookeeper.ClientCnxn)
[2019-05-29 14:06:44,511] WARN Client session timed out, have not heard from server in 2003ms for sessionid 0x0 (org.apache.zookeeper.ClientCnxn)
[2019-05-29 14:06:44,511] INFO Client session timed out, have not heard from server in 2003ms for sessionid 0x0, closing socket connection and attempting reconnect (org.apache.zookeeper.ClientCnxn)
[2019-05-29 14:06:45,613] INFO Opening socket connection to server kafka2/192.168.1.102:2181. Will not attempt to authenticate using SASL (unknown error) (org.apache.zookeeper.ClientCnxn)
[2019-05-29 14:06:47,617] WARN Client session timed out, have not heard from server in 3004ms for sessionid 0x0 (org.apache.zookeeper.ClientCnxn)
[2019-05-29 14:06:47,617] INFO Client session timed out, have not heard from server in 3004ms for sessionid 0x0, closing socket connection and attempting reconnect (org.apache.zookeeper.ClientCnxn)
[2019-05-29 14:06:47,718] INFO Opening socket connection to server kafka1/192.168.1.101:2181. Will not attempt to authenticate using SASL (unknown error) (org.apache.zookeeper.ClientCnxn)
[2019-05-29 14:06:48,988] INFO [ZooKeeperClient] Closing. (kafka.zookeeper.ZooKeeperClient)
[2019-05-29 14:06:49,720] WARN Client session timed out, have not heard from server in 2002ms for sessionid 0x0 (org.apache.zookeeper.ClientCnxn)
[2019-05-29 14:06:49,825] INFO Session: 0x0 closed (org.apache.zookeeper.ZooKeeper)
[2019-05-29 14:06:49,827] INFO [ZooKeeperClient] Closed. (kafka.zookeeper.ZooKeeperClient)
[2019-05-29 14:06:49,830] ERROR Fatal error during KafkaServer startup. Prepare to shutdown (kafka.server.KafkaServer)
kafka.zookeeper.ZooKeeperClientTimeoutException: Timed out waiting for connection while in state: CONNECTING
        at kafka.zookeeper.ZooKeeperClient$$anonfun$kafka$zookeeper$ZooKeeperClient$$waitUntilConnected$1.apply$mcV$sp(ZooKeeperClient.scala:268)
        at kafka.zookeeper.ZooKeeperClient$$anonfun$kafka$zookeeper$ZooKeeperClient$$waitUntilConnected$1.apply(ZooKeeperClient.scala:264)
        at kafka.zookeeper.ZooKeeperClient$$anonfun$kafka$zookeeper$ZooKeeperClient$$waitUntilConnected$1.apply(ZooKeeperClient.scala:264)
        at kafka.utils.CoreUtils$.inLock(CoreUtils.scala:251)
        at kafka.zookeeper.ZooKeeperClient.kafka$zookeeper$ZooKeeperClient$$waitUntilConnected(ZooKeeperClient.scala:264)
        at kafka.zookeeper.ZooKeeperClient.<init>(ZooKeeperClient.scala:97)
        at kafka.zk.KafkaZkClient$.apply(KafkaZkClient.scala:1693)
        at kafka.server.KafkaServer.kafka$server$KafkaServer$$createZkClient$1(KafkaServer.scala:348)
        at kafka.server.KafkaServer.initZkClient(KafkaServer.scala:372)
        at kafka.server.KafkaServer.startup(KafkaServer.scala:202)
        at kafka.server.KafkaServerStartable.startup(KafkaServerStartable.scala:38)
        at kafka.Kafka$.main(Kafka.scala:75)
        at kafka.Kafka.main(Kafka.scala)
[2019-05-29 14:06:49,833] INFO shutting down (kafka.server.KafkaServer)
[2019-05-29 14:06:49,836] INFO shut down completed (kafka.server.KafkaServer)
[2019-05-29 14:06:49,837] ERROR Exiting Kafka. (kafka.server.KafkaServerStartable)
[2019-05-29 14:06:49,841] INFO EventThread shut down for session: 0x0 (org.apache.zookeeper.ClientCnxn)
[2019-05-29 14:06:49,843] INFO shutting down (kafka.server.KafkaServer)
</code>```

答:
Did you start Zookeeper on that port? It seems like the Kafka server can't connect to the zookeeper.
If you are using linux, you may check the net status of the port using  netstat -anlp | grep 2181

Title: Kafka shutdown with zookeeper timeout

Body:
I am trying to install Kafka setup with 3 Kafka Brokers in single zookeeper node but i am seeing Kafka process getting down in fraction of minutes and throwing error in Kafka logs:

2019-05-29 14:06:42,508] INFO Opening socket connection to server kafka3/192.168.1.103:2181. Will not attempt to authenticate using SASL (unknown error) (org.apache.zookeeper.ClientCnxn)
[2019-05-29 14:06:44,511] WARN Client session timed out, have not heard from server in 2003ms for sessionid 0x0 (org.apache.zookeeper.ClientCnxn)
[2019-05-29 14:06:44,511] INFO Client session timed out, have not heard from server in 2003ms for sessionid 0x0, closing socket connection and attempting reconnect (org.apache.zookeeper.ClientCnxn)
[2019-05-29 14:06:45,613] INFO Opening socket connection to server kafka2/192.168.1.102:2181. Will not attempt to authenticate using SASL (unknown error) (org.apache.zookeeper.ClientCnxn)
[2019-05-29 14:06:47,617] WARN Client session timed out, have not heard from server in 3004ms for sessionid 0x0 (org.apache.zookeeper.ClientCnxn)
[2019-05-29 14:06:47,617] INFO Client session timed out, have not heard from server in 3004ms for sessionid 0x0, closing socket connection and attempting reconnect (org.apache.zookeeper.ClientCnxn)
[2019-05-29 14:06:47,718] INFO Opening socket connection to server kafka1/192.168.1.101:2181. Will not attempt to authenticate using SASL (unknown error) (org.apache.zookeeper.ClientCnxn)
[2019-05-29 14:06:48,988] INFO [ZooKeeperClient] Closing. (kafka.zookeeper.ZooKeeperClient)
[2019-05-29 14:06:49,720] WARN Client session timed out, have not heard from server in 2002ms for sessionid 0x0 (org.apache.zookeeper.ClientCnxn)
[2019-05-29 14:06:49,825] INFO Session: 0x0 closed (org.apache.zookeeper.ZooKeeper)
[2019-05-29 14:06:49,827] INFO [ZooKeeperClient] Closed. (kafka.zookeeper.ZooKeeperClient)
[2019-05-29 14:06:49,830] ERROR Fatal error during KafkaServer startup. Prepare to shutdown (kafka.server.KafkaServer)
kafka.zookeeper.ZooKeeperClientTimeoutException: Timed out waiting for connection while in state: CONNECTING
        at kafka.zookeeper.ZooKeeperClient$$anonfun$kafka$zookeeper$ZooKeeperClient$$waitUntilConnected$1.apply$mcV$sp(ZooKeeperClient.scala:268)
        at kafka.zookeeper.ZooKeeperClient$$anonfun$kafka$zookeeper$ZooKeeperClient$$waitUntilConnected$1.apply(ZooKeeperClient.scala:264)
        at kafka.zookeeper.ZooKeeperClient$$anonfun$kafka$zookeeper$ZooKeeperClient$$waitUntilConnected$1.apply(ZooKeeperClient.scala:264)
        at kafka.utils.CoreUtils$.inLock(CoreUtils.scala:251)
        at kafka.zookeeper.ZooKeeperClient.kafka$zookeeper$ZooKeeperClient$$waitUntilConnected(ZooKeeperClient.scala:264)
        at kafka.zookeeper.ZooKeeperClient.<init>(ZooKeeperClient.scala:97)
        at kafka.zk.KafkaZkClient$.apply(KafkaZkClient.scala:1693)
        at kafka.server.KafkaServer.kafka$server$KafkaServer$$createZkClient$1(KafkaServer.scala:348)
        at kafka.server.KafkaServer.initZkClient(KafkaServer.scala:372)
        at kafka.server.KafkaServer.startup(KafkaServer.scala:202)
        at kafka.server.KafkaServerStartable.startup(KafkaServerStartable.scala:38)
        at kafka.Kafka$.main(Kafka.scala:75)
        at kafka.Kafka.main(Kafka.scala)
[2019-05-29 14:06:49,833] INFO shutting down (kafka.server.KafkaServer)
[2019-05-29 14:06:49,836] INFO shut down completed (kafka.server.KafkaServer)
[2019-05-29 14:06:49,837] ERROR Exiting Kafka. (kafka.server.KafkaServerStartable)
[2019-05-29 14:06:49,841] INFO EventThread shut down for session: 0x0 (org.apache.zookeeper.ClientCnxn)
[2019-05-29 14:06:49,843] INFO shutting down (kafka.server.KafkaServer)


答:
I'm not positive I understand your question, but this would do what I think you're asking, would work in SQL and in an Infa expression as well.</p>

```<code>with myrecs as
(select '2019-02-20;870789789707;ABC+xY++Gustav Russia' as myfield from dual union
all
 select '2019-02-20;870789789707;ABC+xY+++Carroll Iowa' as myfield from dual)

 select myfield,

    substr(myfield,1, instr(myfield,';',-1)) ---will select everything up to, and including the final semicolon
    ||--concatenate
    substr(myfield,instr(myfield,'+',-1)+1) as yourfield --will select everything after the final plus sign
 from myrecs;

OUTPUT:
myfield                                         yourfield
2019-02-20;870789789707;ABC+xY++Gustav Russia   2019-02-20;870789789707;Gustav Russia
2019-02-20;870789789707;ABC+xY+++Carroll Iowa   2019-02-20;870789789707;Carroll Iowa
</code>```

Title: Remove character from dynamic string

Body:
I'm not positive I understand your question, but this would do what I think you're asking, would work in SQL and in an Infa expression as well.

with myrecs as
(select '2019-02-20;870789789707;ABC+xY++Gustav Russia' as myfield from dual union
all
 select '2019-02-20;870789789707;ABC+xY+++Carroll Iowa' as myfield from dual)

 select myfield,

    substr(myfield,1, instr(myfield,';',-1)) ---will select everything up to, and including the final semicolon
    ||--concatenate
    substr(myfield,instr(myfield,'+',-1)+1) as yourfield --will select everything after the final plus sign
 from myrecs;

OUTPUT:
myfield                                         yourfield
2019-02-20;870789789707;ABC+xY++Gustav Russia   2019-02-20;870789789707;Gustav Russia
2019-02-20;870789789707;ABC+xY+++Carroll Iowa   2019-02-20;870789789707;Carroll Iowa


问:
Custom Event Receiver - Copy To Folder
I am in the process of writing a custom event receiver. The basic flow is as follows:

Document is added to Library

Based on metadata of document, we check to see if a folder within another document    library exists.

If the folder does not exist, it is created.

The newly added document is copied to the folder residing in another document library.

I have got myself to the point, where I can copy newly added files, from one document library to another when they are added. However I cannot figure out how to copy to a specific directory (by name) within a document library. Any help would be greatly received.

Here is my code so far:

```<code>SPFile sourceFile = properties.ListItem.File;
SPFile destFile; // Copy file from source library to destination
using (Stream stream = sourceFile.OpenBinaryStream())
{
    var destLib = (SPDocumentLibrary) properties.ListItem.Web.Lists[listName];
    destFile = destLib.RootFolder.Files.Add(sourceFile.Name, stream);
    stream.Close();
}
// Update item properties
SPListItem destItem = destFile.Item;
SPListItem sourceItem = sourceFile.Item;
// Copy meta data
destItem["Title"] = sourceItem["Title"];
//...
//... destItem["FieldX"] = sourceItem["FieldX"];
//...
destItem.UpdateOverwriteVersion();
</code>```

答:
Answer</p>

```<code>//Ensure folder here

var destFolder = destLib.RootFolder.SubFolders["name"];

destFile = destFolder.Files.Add(sourceFile.Name, stream);
</code>```

Title: Custom Event Receiver - Copy To Folder

Body:
I am in the process of writing a custom event receiver. The basic flow is as follows:

Document is added to Library

Based on metadata of document, we check to see if a folder within another document    library exists.

If the folder does not exist, it is created.

The newly added document is copied to the folder residing in another document library.

I have got myself to the point, where I can copy newly added files, from one document library to another when they are added. However I cannot figure out how to copy to a specific directory (by name) within a document library. Any help would be greatly received.

Here is my code so far:

SPFile sourceFile = properties.ListItem.File;
SPFile destFile; // Copy file from source library to destination
using (Stream stream = sourceFile.OpenBinaryStream())
{
    var destLib = (SPDocumentLibrary) properties.ListItem.Web.Lists[listName];
    destFile = destLib.RootFolder.Files.Add(sourceFile.Name, stream);
    stream.Close();
}
// Update item properties
SPListItem destItem = destFile.Item;
SPListItem sourceItem = sourceFile.Item;
// Copy meta data
destItem["Title"] = sourceItem["Title"];
//...
//... destItem["FieldX"] = sourceItem["FieldX"];
//...
destItem.UpdateOverwriteVersion();

Body:
Answer

//Ensure folder here

var destFolder = destLib.RootFolder.SubFolders["name"];

destFile = destFolder.Files.Add(sourceFile.Name, stream);


问:
Pandoc: Different outputs to docx and LaTeX formats
In LaTeX one could for example have a nice inline equation like $x^2=4$, which in docx format I would be glad to have as italic text.
Is there a way to tell Pandoc to use one of these solutions depending on the output format?

When searching for a possible solution, I realized pandoc has filters and templates. I would not really understand, which direction to follow.

But I would really like to arrive with a more general solution, that would also work for analogous tasks like, for example, smaller spaces between a number and units: In LaTeX straightforward $\;$, but including this in my Markdown document would not give me a satisfactory result in DOCX or ODT output.

答:
This is what I found from the pandoc manual

```<code>For docx output, styles will be defined in the output file as inheriting from normal
text, if the styles are not yet in your reference.docx. If they are already defined,
pandoc will not alter the definition.
</code>```

and please read the --reference-doc=FILE part of the maunal

```<code>--reference-doc=FILE
Use the specified file as a style reference in producing a docx or ODT file.
...
</code>```

how to use the reference-doc in pandoc???

create a empty docx file and rename it (eg. refer.docx)

define the styles you want to display

add "--reference-doc=(refer.docx path)" into your pandoc command line .

Body:
This is what I found from the pandoc manual

For docx output, styles will be defined in the output file as inheriting from normal
text, if the styles are not yet in your reference.docx. If they are already defined,
pandoc will not alter the definition.

and please read the --reference-doc=FILE part of the maunal

--reference-doc=FILE
Use the specified file as a style reference in producing a docx or ODT file.
...

how to use the reference-doc in pandoc???

create a empty docx file and rename it (eg. refer.docx)

define the styles you want to display

add "--reference-doc=(refer.docx path)" into your pandoc command line .


问:
Matplotlib heatmap for multiple timeseries to show distribution over time
I have n_series recordings with the same frames 0, 1, 2, 3,... and would like to make a 2D contour out of it.

I've found that I can very easily do the following:

```<code>import matplotlib.pyplot as plt
import numpy as np

series_len = 1000
n_series = 10

y = np.random.normal(0, 0.15, series_len * n_series)
x = np.tile(np.arange(0, series_len, 1), n_series)

heatmap, xbins, ybins = np.histogram2d(x, y, bins=20)

plt.contourf(heatmap.T)
plt.show()
</code>```

But since this just gives a 20x20 histogram, I have no idea how my intensities are distributed in the outputted plot (e.g. roughly zero-centered), nor how to fix the ticks.

What I'd like is this ('shopped):

答:
Okay, found an answer myself which makes the process much simpler than it appears to be. Simply resize the heatmap by 1 in both directions using skimage will make everything follow along nicely.

```<code>import matplotlib.pyplot as plt
import numpy as np
import skimage.transform

series_len = 1000
n_series = 10
bins = 20
y = np.random.normal(0, 0.15, series_len * n_series)
x = np.tile(np.arange(0, series_len, 1), n_series)

heatmap, xlabels, ylabels = np.histogram2d(x, y, bins=bins)
heatmap = skimage.transform.resize(heatmap, output_shape = (bins+1, bins+1), mode = "symmetric")

plt.contourf(xlabels, ylabels, heatmap.T)
plt.xlim(0, 1000)
plt.ylim(-0.5, 0.5)
plt.show()
</code>```

Body:
I have n_series recordings with the same frames 0, 1, 2, 3,... and would like to make a 2D contour out of it.

I've found that I can very easily do the following:

import matplotlib.pyplot as plt
import numpy as np

series_len = 1000
n_series = 10

y = np.random.normal(0, 0.15, series_len * n_series)
x = np.tile(np.arange(0, series_len, 1), n_series)

heatmap, xbins, ybins = np.histogram2d(x, y, bins=20)

plt.contourf(heatmap.T)
plt.show()

But since this just gives a 20x20 histogram, I have no idea how my intensities are distributed in the outputted plot (e.g. roughly zero-centered), nor how to fix the ticks.

What I'd like is this ('shopped):

Body:
Okay, found an answer myself which makes the process much simpler than it appears to be. Simply resize the heatmap by 1 in both directions using skimage will make everything follow along nicely.

import matplotlib.pyplot as plt
import numpy as np
import skimage.transform

series_len = 1000
n_series = 10
bins = 20
y = np.random.normal(0, 0.15, series_len * n_series)
x = np.tile(np.arange(0, series_len, 1), n_series)

heatmap, xlabels, ylabels = np.histogram2d(x, y, bins=bins)
heatmap = skimage.transform.resize(heatmap, output_shape = (bins+1, bins+1), mode = "symmetric")

plt.contourf(xlabels, ylabels, heatmap.T)
plt.xlim(0, 1000)
plt.ylim(-0.5, 0.5)
plt.show()


问:
Java multiple function call
If in Java , I am making an object of class P and then I am calling two function of that class like this -

P pop=new pop()

pop.getfit().fitness()

I wanted to know what will happen, will both functions be called? or will they be called one by one?

答:
Both function will be called one by one, but call to the fitness() will depend on the output of the pop.getfit() function. Call to fitness() function will give compilation error if the output of pop.getfit() is not an object of the class, the function fitness() belongs to.

Let's understand this with a different example:

```<code>class MainTest{
    Test t;
    public Test test_object(){
        t = new Test();
        return t;
    }
}
class Test{
    int x;
    public Test(){
        x = 10;
    }
    public int getX(){
        return x;
    }
    public int sum(int a, int b){
        return (a+b);
    }
    public void printHello(){
        System.out.println("Hello!!");
    }
}
class multiple_call{
    public static void main(String[] args){
        MainTest t = new MainTest();
        int sum = t.test_object().sum(1, 3);
        System.out.println(sum); // runs perfectly as output of t.test_object() is an object of Test class, then its sum function is called.

        // Test test = new Test();
        // test.getX().printHello(); // compilation error: void cannot be dereferenced

    }
}
</code>```

Title: Java multiple function call

Body:
Both function will be called one by one, but call to the fitness() will depend on the output of the pop.getfit() function. Call to fitness() function will give compilation error if the output of pop.getfit() is not an object of the class, the function fitness() belongs to.

Let's understand this with a different example:

class MainTest{
    Test t;
    public Test test_object(){
        t = new Test();
        return t;
    }
}
class Test{
    int x;
    public Test(){
        x = 10;
    }
    public int getX(){
        return x;
    }
    public int sum(int a, int b){
        return (a+b);
    }
    public void printHello(){
        System.out.println("Hello!!");
    }
}
class multiple_call{
    public static void main(String[] args){
        MainTest t = new MainTest();
        int sum = t.test_object().sum(1, 3);
        System.out.println(sum); // runs perfectly as output of t.test_object() is an object of Test class, then its sum function is called.

        // Test test = new Test();
        // test.getX().printHello(); // compilation error: void cannot be dereferenced

    }
}


问:
FCM - Not registered
I'm trying to send a message through FCM to my web app. Unfortunately, I've the following error message and I'm unable to solve it alone...

Through POSTMAN I receive that JSON :

```<code> {
    "multicast_id": 7441926471010389687,
    "success": 0,
    "failure": 1,
    "canonical_ids": 0,
    "results": [
        {
            "error": "NotRegistered"
        }
    ]
}
</code>```

This is the only error message I have. See bellow POSTMAN config POST message I send to FCM

Is someone have already facing the same problem ? I unable to find any response to solve my problem on internet...

See also bellow my Firebase.java

```<code>package com.inovans.backend.web.rest.firebase;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Service;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.Message;

@Service
public class Firebase {

    @PostConstruct
    void initialierMyFirebase() {
        this.initializeFirebase();
    }

    private void initializeFirebase() {

        // if(this.firebaseApp.getApps().isEmpty()) {

        FileInputStream serviceAccount = null;
        try {
            serviceAccount = new FileInputStream(
                    "src/main/java/com/inovans/backend/web/rest/firebase/emergency-manager-57773-firebase-adminsdk-x4p6o-c2ea07c8f4.json");
        } catch (FileNotFoundException e) {
            System.out.println(
                    "Impossible de récupérer le fichier JSON de configuration de FIREBASE. Le chemin n'est pas valide. "
                            + serviceAccount);
            e.printStackTrace();
        }

        FirebaseOptions options = null;
        try {
            options = new FirebaseOptions.Builder().setCredentials(GoogleCredentials.fromStream(serviceAccount))
                    .setDatabaseUrl("https://emergency-manager-57773.firebaseio.com").build();
        } catch (IOException e) {
            System.out.println("Impossible d'initialiser l'application FIREBASE : " + options);
            e.printStackTrace();
        }

        System.out.println("OPT : " + options);

        FirebaseApp.initializeApp(options);

        // }
    }

    public void sendMessage(String token) {

        // See documentation on defining a message payload.
        /*
        Message message = Message.builder()
                .setWebpushConfig(WebpushConfig.builder()
                        .setNotification(new WebpushNotification("$GOOG up 1.43% on the day",
                                "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
                                "https://my-server/icon.png"))
                        .build())
                .setToken(
                        "fh4Jcwe3vhg:APA91bGvw6crsojSroBE31aeR32ZRjfJyCisHNUWiR6froP53c0YpQ7uG-EtkiPIQ0ZUnY2fYW_TF4T6NFhQ7W002Q2MBW8-4ONedruIWMpw8BXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                .build();
        */

        // See documentation on defining a message payload.
        Message message = Message.builder()
                .putData("score", "850")
                .putData("time", "2:45")
                .setToken("fh4Jcwe3vhg:APA91bGvw6crsojSroBE31aeR32ZRjfJyCisHNUWiR6froP53c0YpQ7uG-EtkiPIQ0ZUnY2fYW_TF4T6NFhQ7W002Q2MBW8-4ONedruIWMpw8BXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                .build();

        // Send a message to the device corresponding to the provided
        // registration token.
        String response = null;
        try {
            System.out.println("TEST : " + FirebaseMessaging.getInstance());
            response = FirebaseMessaging.getInstance().sendAsync(message).get();
            // Response is a message ID string.
            System.out.println("Successfully sent message: " + response);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
</code>```

Help please

答:
I was facing the same issue. Here is how I fixed it (iOS specific, android was working out of the box)-

Uninstall the app from your phone

Clear ALL the tokens stored in your database for this particular account(or however you have set it up in your backend. In my case, tokens are tied to the account)

In componentDidmount-

async componentDidMount() {
    this.checkPermission();
    this.createNotificationListeners();
  }

4.

```<code>  async checkPermission() {
    const enabled = await firebase.messaging().hasPermission();
    if (enabled) {
      this.getToken();
    } else {
      this.requestPermission();
    }
  }

  async requestPermission() {
    try {
      await firebase.messaging().requestPermission();
      // User has authorised
      this.getToken();
    } catch (error) {
      // User has rejected permissions
      console.log('permission rejected');
    }
  }

  async getToken() {
    try {
      const enabled = await firebase.messaging().hasPermission();
      if (!enabled) {
        await firebase.messaging().requestPermission();
      }

      const fcmToken = await firebase.messaging().getToken();
      if (fcmToken) {
        console.log("got token");
        console.log('fcm token:', fcmToken); //-->use this token from the console to send a post request via postman
        this.setState({ fcmToken });
        return fcmToken;
      }
    } catch (error) {
      console.warn('notification token error', error);
    }
  }
</code>```

5.

```<code> async createNotificationListeners() {
    /*
    * Triggered when a particular notification has been received in foreground
    * */
    this.notificationListener = firebase.notifications().onNotification((notification) => {
        const { title, body } = notification;
        this.showAlert(title, body);
    });

    /*
    * If your app is in background, you can listen for when a notification is clicked / tapped / opened as follows:
    * */
    this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
        const { title, body } = notificationOpen.notification;
        this.showAlert(title, body);
    });

    /*
    * If your app is closed, you can check if it was opened by a notification being clicked / tapped / opened as follows:
    * */
    const notificationOpen = await firebase.notifications().getInitialNotification();
    if (notificationOpen) {
        const { title, body } = notificationOpen.notification;
        this.showAlert(title, body);
    }
    /*
    * Triggered for data only payload in foreground
    * */
    this.messageListener = firebase.messaging().onMessage((message) => {
      //process data message
      console.log(JSON.stringify(message));
    });
  }
</code>```

Finally, use the token that you see in the console as a value for the "to" key in your post request. You should no longer see the "notRegistered" error and should be getting push notifications.
Done!!

Citations-https://medium.com/@anum.amin/react-native-integrating-push-notifications-using-fcm-349fff071591

Title: FCM - Not registered

Body:
I'm trying to send a message through FCM to my web app. Unfortunately, I've the following error message and I'm unable to solve it alone...

Through POSTMAN I receive that JSON :

 {
    "multicast_id": 7441926471010389687,
    "success": 0,
    "failure": 1,
    "canonical_ids": 0,
    "results": [
        {
            "error": "NotRegistered"
        }
    ]
}

This is the only error message I have. See bellow POSTMAN config POST message I send to FCM

Is someone have already facing the same problem ? I unable to find any response to solve my problem on internet...

See also bellow my Firebase.java

package com.inovans.backend.web.rest.firebase;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Service;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.Message;

@Service
public class Firebase {

    @PostConstruct
    void initialierMyFirebase() {
        this.initializeFirebase();
    }

    private void initializeFirebase() {

        // if(this.firebaseApp.getApps().isEmpty()) {

        FileInputStream serviceAccount = null;
        try {
            serviceAccount = new FileInputStream(
                    "src/main/java/com/inovans/backend/web/rest/firebase/emergency-manager-57773-firebase-adminsdk-x4p6o-c2ea07c8f4.json");
        } catch (FileNotFoundException e) {
            System.out.println(
                    "Impossible de récupérer le fichier JSON de configuration de FIREBASE. Le chemin n'est pas valide. "
                            + serviceAccount);
            e.printStackTrace();
        }

        FirebaseOptions options = null;
        try {
            options = new FirebaseOptions.Builder().setCredentials(GoogleCredentials.fromStream(serviceAccount))
                    .setDatabaseUrl("https://emergency-manager-57773.firebaseio.com").build();
        } catch (IOException e) {
            System.out.println("Impossible d'initialiser l'application FIREBASE : " + options);
            e.printStackTrace();
        }

        System.out.println("OPT : " + options);

        FirebaseApp.initializeApp(options);

        // }
    }

    public void sendMessage(String token) {

        // See documentation on defining a message payload.
        /*
        Message message = Message.builder()
                .setWebpushConfig(WebpushConfig.builder()
                        .setNotification(new WebpushNotification("$GOOG up 1.43% on the day",
                                "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
                                "https://my-server/icon.png"))
                        .build())
                .setToken(
                        "fh4Jcwe3vhg:APA91bGvw6crsojSroBE31aeR32ZRjfJyCisHNUWiR6froP53c0YpQ7uG-EtkiPIQ0ZUnY2fYW_TF4T6NFhQ7W002Q2MBW8-4ONedruIWMpw8BXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                .build();
        */

        // See documentation on defining a message payload.
        Message message = Message.builder()
                .putData("score", "850")
                .putData("time", "2:45")
                .setToken("fh4Jcwe3vhg:APA91bGvw6crsojSroBE31aeR32ZRjfJyCisHNUWiR6froP53c0YpQ7uG-EtkiPIQ0ZUnY2fYW_TF4T6NFhQ7W002Q2MBW8-4ONedruIWMpw8BXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                .build();

        // Send a message to the device corresponding to the provided
        // registration token.
        String response = null;
        try {
            System.out.println("TEST : " + FirebaseMessaging.getInstance());
            response = FirebaseMessaging.getInstance().sendAsync(message).get();
            // Response is a message ID string.
            System.out.println("Successfully sent message: " + response);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

Help please

Body:
I was facing the same issue. Here is how I fixed it (iOS specific, android was working out of the box)-

Uninstall the app from your phone

Clear ALL the tokens stored in your database for this particular account(or however you have set it up in your backend. In my case, tokens are tied to the account)

In componentDidmount-

async componentDidMount() {
    this.checkPermission();
    this.createNotificationListeners();
  }

4.

  async checkPermission() {
    const enabled = await firebase.messaging().hasPermission();
    if (enabled) {
      this.getToken();
    } else {
      this.requestPermission();
    }
  }

  async requestPermission() {
    try {
      await firebase.messaging().requestPermission();
      // User has authorised
      this.getToken();
    } catch (error) {
      // User has rejected permissions
      console.log('permission rejected');
    }
  }

  async getToken() {
    try {
      const enabled = await firebase.messaging().hasPermission();
      if (!enabled) {
        await firebase.messaging().requestPermission();
      }

      const fcmToken = await firebase.messaging().getToken();
      if (fcmToken) {
        console.log("got token");
        console.log('fcm token:', fcmToken); //-->use this token from the console to send a post request via postman
        this.setState({ fcmToken });
        return fcmToken;
      }
    } catch (error) {
      console.warn('notification token error', error);
    }
  }

5.

 async createNotificationListeners() {
    /*
    * Triggered when a particular notification has been received in foreground
    * */
    this.notificationListener = firebase.notifications().onNotification((notification) => {
        const { title, body } = notification;
        this.showAlert(title, body);
    });

    /*
    * If your app is in background, you can listen for when a notification is clicked / tapped / opened as follows:
    * */
    this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
        const { title, body } = notificationOpen.notification;
        this.showAlert(title, body);
    });

    /*
    * If your app is closed, you can check if it was opened by a notification being clicked / tapped / opened as follows:
    * */
    const notificationOpen = await firebase.notifications().getInitialNotification();
    if (notificationOpen) {
        const { title, body } = notificationOpen.notification;
        this.showAlert(title, body);
    }
    /*
    * Triggered for data only payload in foreground
    * */
    this.messageListener = firebase.messaging().onMessage((message) => {
      //process data message
      console.log(JSON.stringify(message));
    });
  }

Finally, use the token that you see in the console as a value for the "to" key in your post request. You should no longer see the "notRegistered" error and should be getting push notifications.
Done!!

Citations-https://medium.com/@anum.amin/react-native-integrating-push-notifications-using-fcm-349fff071591