问:
Output errors on advancved parameters panel
I have no idea if the issue is regarding a update on php version on the server or some kind of attack I got in my store, but in my "advanced parameters" panel is outputting some errors, above I leave the information. Does anybody had some kind of similar issue?</p>

```<code>PrestaShop™ 1.5.4.1

Verify Settings
Parameters required: OK
Optional parameters: Please fix the following errors
pdo_mysql

List of changed files

Changed/missing files have been detected.
Ficheiros em falta (6)
modules/blocknewsletter/mails/en/index.php
modules/blockwishlist/mails/en/index.php
modules/followup/mails/en/index.php
modules/mailalerts/mails/en/index.php
modules/referralprogram/mails/en/index.php
modules/sendtoafriend/mails/en/index.php

Ficheiros actualizados (64)
classes/controller/FrontController.php
modules/bankwire/bankwire.jpg
modules/bankwire/views/templates/hook/payment.tpl
modules/blocknewsletter/blocknewsletter.css
modules/blocknewsletter/blocknewsletter.php
modules/blocknewsletter/index.php
modules/blocknewsletter/controllers/index.php
modules/blocknewsletter/controllers/front/index.php
modules/blocknewsletter/controllers/front/verification.php
modules/blocknewsletter/img/index.php
modules/blocknewsletter/img/icon/index.php
modules/blocknewsletter/mails/index.php
modules/blocknewsletter/mails/en/newsletter_conf.html
modules/blocknewsletter/mails/en/newsletter_verif.html
modules/blocknewsletter/mails/en/newsletter_voucher.html
modules/blocknewsletter/translations/index.php
modules/blocknewsletter/views/index.php
modules/blocknewsletter/views/templates/index.php
modules/blocknewsletter/views/templates/front/index.php
modules/blocknewsletter/views/templates/front/verification_execution.tpl
modules/blocknewsletter/views/templates/hook/blocknewsletter.tpl
modules/blocknewsletter/views/templates/hook/index.php
modules/blockwishlist/mails/en/wishlink.html
modules/blockwishlist/mails/en/wishlist.html
modules/cashondelivery/cashondelivery.jpg
modules/cashondelivery/views/templates/hook/payment.tpl
modules/editorial/EditorialClass.php
modules/editorial/editorial.css
modules/editorial/editorial.php
modules/editorial/editorial.tpl
modules/editorial/index.php
modules/editorial/translations/index.php
modules/followup/mails/en/followup_1.html
modules/followup/mails/en/followup_2.html
modules/followup/mails/en/followup_3.html
modules/followup/mails/en/followup_4.html
modules/mailalerts/MailAlert.php
modules/mailalerts/index.php
modules/mailalerts/mailalerts-account.php
modules/mailalerts/mailalerts-ajax.php
modules/mailalerts/mailalerts-extra.php
modules/mailalerts/mailalerts.php
modules/mailalerts/controllers/index.php
modules/mailalerts/controllers/front/account.php
modules/mailalerts/controllers/front/actions.php
modules/mailalerts/controllers/front/index.php
modules/mailalerts/img/index.php
modules/mailalerts/mails/index.php
modules/mailalerts/mails/en/customer_qty.html
modules/mailalerts/mails/en/new_order.html
modules/mailalerts/mails/en/productcoverage.html
modules/mailalerts/mails/en/productoutofstock.html
modules/mailalerts/translations/index.php
modules/mailalerts/views/index.php
modules/mailalerts/views/templates/index.php
modules/mailalerts/views/templates/front/index.php
modules/mailalerts/views/templates/front/mailalerts-account.tpl
modules/mailalerts/views/templates/hook/index.php
modules/mailalerts/views/templates/hook/my-account.tpl
modules/mailalerts/views/templates/hook/product.tpl
modules/referralprogram/mails/en/referralprogram-congratulations.html
modules/referralprogram/mails/en/referralprogram-invitation.html
modules/referralprogram/mails/en/referralprogram-voucher.html
modules/sendtoafriend/mails/en/send_to_a_friend.html
</code>```

答:
Please check if _PS_DEBUG_PROFILING_ is enabled on your store. You can check the same in the following file on your store:

/config/defines.inc.php

Search for _PS_DEBUG_PROFILING_ and see if the value for it is 'true' or 'false'

It should be 'false', change it if it is not and see if the problem is solved.

Body:
I have no idea if the issue is regarding a update on php version on the server or some kind of attack I got in my store, but in my "advanced parameters" panel is outputting some errors, above I leave the information. Does anybody had some kind of similar issue?

PrestaShop™ 1.5.4.1

Verify Settings
Parameters required: OK
Optional parameters: Please fix the following errors
pdo_mysql

List of changed files

Changed/missing files have been detected.
Ficheiros em falta (6)
modules/blocknewsletter/mails/en/index.php
modules/blockwishlist/mails/en/index.php
modules/followup/mails/en/index.php
modules/mailalerts/mails/en/index.php
modules/referralprogram/mails/en/index.php
modules/sendtoafriend/mails/en/index.php

Ficheiros actualizados (64)
classes/controller/FrontController.php
modules/bankwire/bankwire.jpg
modules/bankwire/views/templates/hook/payment.tpl
modules/blocknewsletter/blocknewsletter.css
modules/blocknewsletter/blocknewsletter.php
modules/blocknewsletter/index.php
modules/blocknewsletter/controllers/index.php
modules/blocknewsletter/controllers/front/index.php
modules/blocknewsletter/controllers/front/verification.php
modules/blocknewsletter/img/index.php
modules/blocknewsletter/img/icon/index.php
modules/blocknewsletter/mails/index.php
modules/blocknewsletter/mails/en/newsletter_conf.html
modules/blocknewsletter/mails/en/newsletter_verif.html
modules/blocknewsletter/mails/en/newsletter_voucher.html
modules/blocknewsletter/translations/index.php
modules/blocknewsletter/views/index.php
modules/blocknewsletter/views/templates/index.php
modules/blocknewsletter/views/templates/front/index.php
modules/blocknewsletter/views/templates/front/verification_execution.tpl
modules/blocknewsletter/views/templates/hook/blocknewsletter.tpl
modules/blocknewsletter/views/templates/hook/index.php
modules/blockwishlist/mails/en/wishlink.html
modules/blockwishlist/mails/en/wishlist.html
modules/cashondelivery/cashondelivery.jpg
modules/cashondelivery/views/templates/hook/payment.tpl
modules/editorial/EditorialClass.php
modules/editorial/editorial.css
modules/editorial/editorial.php
modules/editorial/editorial.tpl
modules/editorial/index.php
modules/editorial/translations/index.php
modules/followup/mails/en/followup_1.html
modules/followup/mails/en/followup_2.html
modules/followup/mails/en/followup_3.html
modules/followup/mails/en/followup_4.html
modules/mailalerts/MailAlert.php
modules/mailalerts/index.php
modules/mailalerts/mailalerts-account.php
modules/mailalerts/mailalerts-ajax.php
modules/mailalerts/mailalerts-extra.php
modules/mailalerts/mailalerts.php
modules/mailalerts/controllers/index.php
modules/mailalerts/controllers/front/account.php
modules/mailalerts/controllers/front/actions.php
modules/mailalerts/controllers/front/index.php
modules/mailalerts/img/index.php
modules/mailalerts/mails/index.php
modules/mailalerts/mails/en/customer_qty.html
modules/mailalerts/mails/en/new_order.html
modules/mailalerts/mails/en/productcoverage.html
modules/mailalerts/mails/en/productoutofstock.html
modules/mailalerts/translations/index.php
modules/mailalerts/views/index.php
modules/mailalerts/views/templates/index.php
modules/mailalerts/views/templates/front/index.php
modules/mailalerts/views/templates/front/mailalerts-account.tpl
modules/mailalerts/views/templates/hook/index.php
modules/mailalerts/views/templates/hook/my-account.tpl
modules/mailalerts/views/templates/hook/product.tpl
modules/referralprogram/mails/en/referralprogram-congratulations.html
modules/referralprogram/mails/en/referralprogram-invitation.html
modules/referralprogram/mails/en/referralprogram-voucher.html
modules/sendtoafriend/mails/en/send_to_a_friend.html


来源: stackexchange

问:
How to grab json data and store in a database
I am trying to get data from a json and i want to save it in a database.
I got errors, kindly put me through. Below is me code.

```<code><?php

//My connection was ok

//read the json file contents
$url = ('http://api.football-data.org/v1/teams/61/players/');
$jsondata = file_get_contents($url);

//convert json object to php associative array
$data = json_decode($jsondata, true);
//print_r($data);

//get the employee details
foreach ($data['_links']['players'] as $myp) {
    $name = $myp['name'];
    $posi = $myp['position'];
    $nation = $myp['nationality'];
    $market = $myp['marketValue'];
}

//    //insert into mysql table
mysql_select_db($db, $conn); //database and connection

$date = date('Y-m-d H:m:s'); //date stamp formatting
//sql query that insert the user info into the database
$sql = "INSERT INTO player ( Name, Position, Nationality, Market, Created)
        VALUES( ?,?,?,?,?)";
// bind variables to insert query params
    mysqli_stmt_bind_param($sql, 'sss', $name, $posi, $nation, $market, $date);
//if the connection is sucessful, display regards message
if (mysql_query($sql, $conn)) {
    echo "Thank you <br/>";
} else {   //if the connection is not established
    die('Error: ' . mysql_error());
}

mysql_close($conn); //close of process or connection
?>
</code>```

I have tried to first print the values/datas that I want so that am sure the foreach loop is working but I also got errors:

Notice: Undefined index: players in C:\xampp\htdocs\lab4\apitest.php on line 22

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\lab4\apitest.php on line 22

Warning: mysql_select_db() expects parameter 2 to be resource, object given in C:\xampp\htdocs\lab4\apitest.php on line 31

Warning: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, string given in C:\xampp\htdocs\lab4\apitest.php on line 38

Warning: mysql_query() expects parameter 2 to be resource, object given in C:\xampp\htdocs\lab4\apitest.php on line 40
Error:

Here is my json:

```<code>{

    "_links": {
        "self": {
            "href": "http://api.football-data.org/v1/teams/61/players"
        },
        "team": {
            "href": "http://api.football-data.org/v1/teams/61"
        }
    },
    "count": 25,
    "players": [
        {
            "name": "Marcos Alonso",
            "position": "Left-Back",
            "jerseyNumber": 3,
            "dateOfBirth": "1990-12-28",
            "nationality": "Spain",
            "contractUntil": "2021-06-30",
            "marketValue": "9,000,000 €"
        },
        {
            "name": "Marco van Ginkel",
            "position": "Central Midfield",
            "jerseyNumber": null,
            "dateOfBirth": "1992-12-01",
            "nationality": "Netherlands",
            "contractUntil": "2018-06-30",
            "marketValue": "7,000,000 €"
        },
</code>```

Kindly help me on how to read the wanted data and store in a database successfully.

Many thanks!

答:
there is a problem with your data access method. You write:

```<code>foreach ($data['_links']['players'] as $myp) {
</code>```

you must change into this to get the right structure:

```<code>foreach ($data['players'] as $myp) {
</code>```

Because players key is not child of _links.

And second problem is if you want to insert all players into database. You must move and insert and execute statement into foreach loop.

Hope this help you!

ContentLicense: CC BY-SA 3.0

Body:
I am trying to get data from a json and i want to save it in a database.
I got errors, kindly put me through. Below is me code.

<?php

//My connection was ok

//read the json file contents
$url = ('http://api.football-data.org/v1/teams/61/players/');
$jsondata = file_get_contents($url);

//convert json object to php associative array
$data = json_decode($jsondata, true);
//print_r($data);

//get the employee details
foreach ($data['_links']['players'] as $myp) {
    $name = $myp['name'];
    $posi = $myp['position'];
    $nation = $myp['nationality'];
    $market = $myp['marketValue'];
}

//    //insert into mysql table
mysql_select_db($db, $conn); //database and connection

$date = date('Y-m-d H:m:s'); //date stamp formatting
//sql query that insert the user info into the database
$sql = "INSERT INTO player ( Name, Position, Nationality, Market, Created)
        VALUES( ?,?,?,?,?)";
// bind variables to insert query params
    mysqli_stmt_bind_param($sql, 'sss', $name, $posi, $nation, $market, $date);
//if the connection is sucessful, display regards message
if (mysql_query($sql, $conn)) {
    echo "Thank you
";
} else {   //if the connection is not established
    die('Error: ' . mysql_error());
}

mysql_close($conn); //close of process or connection
?>

I have tried to first print the values/datas that I want so that am sure the foreach loop is working but I also got errors:

Notice: Undefined index: players in C:\xampp\htdocs\lab4\apitest.php on line 22

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\lab4\apitest.php on line 22

Warning: mysql_select_db() expects parameter 2 to be resource, object given in C:\xampp\htdocs\lab4\apitest.php on line 31

Warning: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, string given in C:\xampp\htdocs\lab4\apitest.php on line 38

Warning: mysql_query() expects parameter 2 to be resource, object given in C:\xampp\htdocs\lab4\apitest.php on line 40
Error:

Here is my json:

{

    "_links": {
        "self": {
            "href": "http://api.football-data.org/v1/teams/61/players"
        },
        "team": {
            "href": "http://api.football-data.org/v1/teams/61"
        }
    },
    "count": 25,
    "players": [
        {
            "name": "Marcos Alonso",
            "position": "Left-Back",
            "jerseyNumber": 3,
            "dateOfBirth": "1990-12-28",
            "nationality": "Spain",
            "contractUntil": "2021-06-30",
            "marketValue": "9,000,000 €"
        },
        {
            "name": "Marco van Ginkel",
            "position": "Central Midfield",
            "jerseyNumber": null,
            "dateOfBirth": "1992-12-01",
            "nationality": "Netherlands",
            "contractUntil": "2018-06-30",
            "marketValue": "7,000,000 €"
        },

Kindly help me on how to read the wanted data and store in a database successfully.

Many thanks!

Body:
there is a problem with your data access method. You write:

foreach ($data['_links']['players'] as $myp) {

you must change into this to get the right structure:

foreach ($data['players'] as $myp) {

Because players key is not child of _links.

And second problem is if you want to insert all players into database. You must move and insert and execute statement into foreach loop.

Hope this help you!


问:
purrr::discard How to delete elements in a vector containing one or more specific strings
I would like to remove the elements containing '_1' and '_3' in the vector using the discard function from purrr. Here the example:

```<code>library(purrr)
x <- c("ABAC_13", "ZDRF73", "UYDS_12", "FGSH41", "GFSC_35" , "JHSC_29")
</code>```

答:
This task can be performed using grepl(). Basically we want to find such occurrences that contains _1 or _3. The grepl output is a logical vector of TRUE/FALSE. Following that we remove those elements from x vector by using a subset and negating opearator i.e. x[!grepl("_1|_3", x)].

```<code>x <- c("ABAC_13", "ZDRF73", "UYDS_12", "FGSH41", "GFSC_35" , "JHSC_29")
x[!grepl("_1|_3", x)]
</code>```

Body:
I would like to remove the elements containing '_1' and '_3' in the vector using the discard function from purrr. Here the example:

library(purrr)
x <- c("ABAC_13", "ZDRF73", "UYDS_12", "FGSH41", "GFSC_35" , "JHSC_29")

Body:
This task can be performed using grepl(). Basically we want to find such occurrences that contains _1 or _3. The grepl output is a logical vector of TRUE/FALSE. Following that we remove those elements from x vector by using a subset and negating opearator i.e. x[!grepl("_1|_3", x)].

x <- c("ABAC_13", "ZDRF73", "UYDS_12", "FGSH41", "GFSC_35" , "JHSC_29")
x[!grepl("_1|_3", x)]


问:
Getting "cannot find symbol" error in Java
I am writing some code to read static stock numbers from a text pad. I ran it to see what was wrong and I cannot seem to fix this cannot find symbol error.</p>

```<code>import java.io.*;
import java.util.*;

public class StockMarket
{
    public static void main(String[] args) throws IOException
    {

        Scanner keyboard = new Scanner(System.in);

        System.out.println("Enter the filename: ");
        String filename = keyboard.nextLine();

        File file = new File(filename);
        Scanner inputFile = new Scanner(file);

        while (inputFile.hasNext())
        {
            checkValidity();
        }

        inputFile.close();

    }

    public static boolean checkValidity()
    {

    String line = inputFile.nextLine();
    double numberOfShares = inputFile.nextDouble();
    double buyPricePerShare = inputFile.nextDouble();
    double buyComissionRate = inputFile.nextDouble();
    double sellPricePerShare = inputFile.nextDouble();
    double sellComissionRate = inputFile.nextDouble();

    }

}
</code>```

答:
Your method checkValidity cannot work. You try to access to variable inputFile which is not known in the method. You have to pass is as parameter.

```<code>public static boolean checkValidity(Scanner inputFile)

{

String line = inputFile.nextLine();
double numberOfShares = inputFile.nextDouble();
double buyPricePerShare = inputFile.nextDouble();
double buyComissionRate = inputFile.nextDouble();
double sellPricePerShare = inputFile.nextDouble();
double sellComissionRate = inputFile.nextDouble();

}
</code>```

Body:
I am writing some code to read static stock numbers from a text pad. I ran it to see what was wrong and I cannot seem to fix this cannot find symbol error.

import java.io.*;
import java.util.*;

public class StockMarket
{
    public static void main(String[] args) throws IOException
    {

        Scanner keyboard = new Scanner(System.in);

        System.out.println("Enter the filename: ");
        String filename = keyboard.nextLine();

        File file = new File(filename);
        Scanner inputFile = new Scanner(file);

        while (inputFile.hasNext())
        {
            checkValidity();
        }

        inputFile.close();

    }

    public static boolean checkValidity()
    {

    String line = inputFile.nextLine();
    double numberOfShares = inputFile.nextDouble();
    double buyPricePerShare = inputFile.nextDouble();
    double buyComissionRate = inputFile.nextDouble();
    double sellPricePerShare = inputFile.nextDouble();
    double sellComissionRate = inputFile.nextDouble();

    }

}

Body:
Your method checkValidity cannot work. You try to access to variable inputFile which is not known in the method. You have to pass is as parameter.

public static boolean checkValidity(Scanner inputFile)

{

String line = inputFile.nextLine();
double numberOfShares = inputFile.nextDouble();
double buyPricePerShare = inputFile.nextDouble();
double buyComissionRate = inputFile.nextDouble();
double sellPricePerShare = inputFile.nextDouble();
double sellComissionRate = inputFile.nextDouble();

}


问:
how to send form data with fileupload image in php using ajax
I am trying to send form data with attachment to php via ajax.

My code is :

```<code>var company_name = $('#companyname').val();
    var company_type = $('#companytype').val();
    var industry_sector = $('#industrysector').val();
    var email = $('#email').val();
    var mobile = $('#mobile').val();
    var logo = $("#logo").prop("files")[0];
    var company_description = $('#company_description').val();
    var password = $('#password').val();
    var rePassword = $('#rePassword').val();

    var data = {
        company_name: company_name,
        company_type: company_type,
        industry_sector: industry_sector,
        email: email,
        mobile: mobile,
        logo: logo,
        company_description: company_description,
        password: password
    }

    $.ajax({
        type: "POST",
        async: false,
        data: {companyregister: data},
        url: "ajax/loginvia.php",
        processData: false,  // tell jQuery not to process the data
        contentType: false,
        beforeSend:function(){

        },
</code>```

i am getting empty data to php controller. i tried in many ways, im unable to resolve the issue.

答:
With simple ajax it is some complex to perform you can use ajaxForm for this. It is easy to implement. Here is plugin url : http://jquery.malsup.com/form/

It is so easy to implement have a look at this.

```<code><script>
    // wait for the DOM to be loaded
    $(document).ready(function() {
        // bind 'myForm' and provide a simple callback function
        $('#myForm').ajaxForm(function() {
            alert("Thank you for your comment!");
        });
    });
</script>
</code>```

Body:
I am trying to send form data with attachment to php via ajax.

My code is :

var company_name = $('#companyname').val();
    var company_type = $('#companytype').val();
    var industry_sector = $('#industrysector').val();
    var email = $('#email').val();
    var mobile = $('#mobile').val();
    var logo = $("#logo").prop("files")[0];
    var company_description = $('#company_description').val();
    var password = $('#password').val();
    var rePassword = $('#rePassword').val();

    var data = {
        company_name: company_name,
        company_type: company_type,
        industry_sector: industry_sector,
        email: email,
        mobile: mobile,
        logo: logo,
        company_description: company_description,
        password: password
    }

    $.ajax({
        type: "POST",
        async: false,
        data: {companyregister: data},
        url: "ajax/loginvia.php",
        processData: false,  // tell jQuery not to process the data
        contentType: false,
        beforeSend:function(){

        },

i am getting empty data to php controller. i tried in many ways, im unable to resolve the issue.

Body:
With simple ajax it is some complex to perform you can use ajaxForm for this. It is easy to implement. Here is plugin url : http://jquery.malsup.com/form/

It is so easy to implement have a look at this.

<script>
    // wait for the DOM to be loaded
    $(document).ready(function() {
        // bind 'myForm' and provide a simple callback function
        $('#myForm').ajaxForm(function() {
            alert("Thank you for your comment!");
        });
    });
</script>


问:
how do I map over a nested array of objects which contains a nested array of objects in react, redux
I have a mongodb document that I'm pulling with an axios ajax call. The document has an array of objects which also contains a nested array of objects. Every object has a mongo id assigned to it. The top most data is displayed in the corresponding top most Presentation component, but subsequent arrays of objects are not displayed in their relative Presentation components. The error I am getting is. "TypeError: this.props.card.rdfts is undefined", yet it's non array siblings are displayed. Yet, when I look in react dev tools and redux dev tools the array of objects is infact there and as an array of objects which contains an array of objects.

I've searched countless stackoverflow artiles as well as countless github articles. I've tried many different approaches but nothing seems to work.

My mongodb docuent is...

```<code>{
"_id" : ObjectId("58d93a23a62fdfa37438b4ca"),
"url" : "/api/Rationale/Restraint/Model/1",
"type" : "body",
"title" : "title",
"vid" : {
    "_id" : ObjectId("58d93a23a62fdfa37438b4c3"),
    "type" : "video",
    "src" : "somesrc",
    "border" : "1",
    "width" : "400",
    "height" : "200",
    "frameborder" : "0",
    "allowfullscreen" : false
},
"topic" : "Topic?",
"rdfts" : [
    {
        "_id" : ObjectId("58d93a23a62fdfa37438b4c4"),
        "rdft" : "ReasonDetailFactTransition",
        "explainations" : [
            {
                "_id" : ObjectId("58d93a23a62fdfa37438b4c5"),
                "explaination" : "Explaination1"
            },
            {
                "_id" : ObjectId("58d93a23a62fdfa37438b4c6"),
                "explaination" : "Explaination2"
            }
        ]
    },
    {
        "_id" : ObjectId("58d93a23a62fdfa37438b4c7"),
        "rdft" : "Reason Detail Fact Transition 2",
        "explainations" : [
            {
                "_id" : ObjectId("58d93a23a62fdfa37438b4c8"),
                "explaination" : "Explaination1"
            },
            {
                "_id" : ObjectId("58d93a23a62fdfa37438b4c9"),
                "explaination" : "Explaination2"
            }
        ]
    }
],
"conclusion" : "Conclusion of Card"
</code>```

}

I'm making my ajax call from componentwillmount

```<code>componentWillMount() {
    console.log("componentDidMount")
    let myURI = ''; {
        let { api, page, section, subsection, card } = this.props.match.params;
        myURI = `/${api}/${page}/${section}/${subsection}/${card}`;
    }
    console.log("json call 1")
    this.props.dispatch(asyncSetCard(myURI));

}
</code>```

This is my thunk that doesn't seem to be halting flow of control.

```<code>asyncSetCard(uri) {
  return dispatch => {

    return axios.get(uri).then(response => {

      dispatch(setCardSuccess(response.data[0]));

    }).catch(error => {

      throw (error);
    });
  }
}
</code>```

So the ajax call seems to work but when I try to render nested arrays of objects with other nested arrays of objects I get the above TypeError.

This happens in the render function

```<code>render() {
    return (
        <div>
            <h2>Title: {this.props.card.title}</h2>
            <h3>Topic: {this.props.card.topic}</h3>
                       {this.props.card.rdfts.map(RDFTs)}
            <h3>Conclusion: {this.props.card.conclusion}</h3>
        </div>
    );
}
</code>```

If I delete {this.props.card.rdfts.map(RDFTs)} then the first level of my documents is displayed. If I put this back in, then subsequent nested arrays of documents do not get displayed and I get the following error. "TypeError: this.props.card.rdfts is undefined"

I've tried to work with 1 level of array of objects at a time but that doesn't seem to work ether.

Also, It doesn't seem that my axios promise is stopping halting flow of control. I originally wanted for the promise to be resolved then render but it seems that the then just falls through and render is called immediately. I wonder if the array of objects isn't instantiated in time or what but it doesn't seem to work.

If you take a look at my console you will see that I'm getting there error before the promise is resolved, but that shouldn't matter since react is reading straight from the state tree. Once the state tree is updated, then react is supposed to update. right?

15:40:24.978 GET mybuldleyadabundle.js [HTTP/1.1 200 OK 117ms]

15:40:26.855 componentDidMount  CardCC.jsx:42:13

15:40:26.867 TypeError: this.props.card.rdfts is undefined[Learn More]
  ...

15:40:27.327 GET XHR
  myhttpurl.herokuapp.com/api/Rationale/Restraint/Model/1 [HTTP/1.1 200
  OK 143ms]

15:40:27.800 GET XHR mylocalhost:3001/sockjs-node/info [HTTP/1.1 200
  OK 2ms]

答: Dan Abramov already figured this out. https://github.com/paularmstrong/normalizr. Normalizer is what I needed. :) Thanks Dan.Also had help from Cory.</p>

Body:
I have a mongodb document that I'm pulling with an axios ajax call. The document has an array of objects which also contains a nested array of objects. Every object has a mongo id assigned to it. The top most data is displayed in the corresponding top most Presentation component, but subsequent arrays of objects are not displayed in their relative Presentation components. The error I am getting is. "TypeError: this.props.card.rdfts is undefined", yet it's non array siblings are displayed. Yet, when I look in react dev tools and redux dev tools the array of objects is infact there and as an array of objects which contains an array of objects.

I've searched countless stackoverflow artiles as well as countless github articles. I've tried many different approaches but nothing seems to work.

My mongodb docuent is...

{
"_id" : ObjectId("58d93a23a62fdfa37438b4ca"),
"url" : "/api/Rationale/Restraint/Model/1",
"type" : "body",
"title" : "title",
"vid" : {
    "_id" : ObjectId("58d93a23a62fdfa37438b4c3"),
    "type" : "video",
    "src" : "somesrc",
    "border" : "1",
    "width" : "400",
    "height" : "200",
    "frameborder" : "0",
    "allowfullscreen" : false
},
"topic" : "Topic?",
"rdfts" : [
    {
        "_id" : ObjectId("58d93a23a62fdfa37438b4c4"),
        "rdft" : "ReasonDetailFactTransition",
        "explainations" : [
            {
                "_id" : ObjectId("58d93a23a62fdfa37438b4c5"),
                "explaination" : "Explaination1"
            },
            {
                "_id" : ObjectId("58d93a23a62fdfa37438b4c6"),
                "explaination" : "Explaination2"
            }
        ]
    },
    {
        "_id" : ObjectId("58d93a23a62fdfa37438b4c7"),
        "rdft" : "Reason Detail Fact Transition 2",
        "explainations" : [
            {
                "_id" : ObjectId("58d93a23a62fdfa37438b4c8"),
                "explaination" : "Explaination1"
            },
            {
                "_id" : ObjectId("58d93a23a62fdfa37438b4c9"),
                "explaination" : "Explaination2"
            }
        ]
    }
],
"conclusion" : "Conclusion of Card"

}

I'm making my ajax call from componentwillmount

componentWillMount() {
    console.log("componentDidMount")
    let myURI = ''; {
        let { api, page, section, subsection, card } = this.props.match.params;
        myURI = `/${api}/${page}/${section}/${subsection}/${card}`;
    }
    console.log("json call 1")
    this.props.dispatch(asyncSetCard(myURI));

}

This is my thunk that doesn't seem to be halting flow of control.

asyncSetCard(uri) {
  return dispatch => {

    return axios.get(uri).then(response => {

      dispatch(setCardSuccess(response.data[0]));

    }).catch(error => {

      throw (error);
    });
  }
}

So the ajax call seems to work but when I try to render nested arrays of objects with other nested arrays of objects I get the above TypeError.

This happens in the render function

render() {
    return (

Title: {this.props.card.title}

Topic: {this.props.card.topic}

                       {this.props.card.rdfts.map(RDFTs)}

Conclusion: {this.props.card.conclusion}

    );
}

If I delete {this.props.card.rdfts.map(RDFTs)} then the first level of my documents is displayed. If I put this back in, then subsequent nested arrays of documents do not get displayed and I get the following error. "TypeError: this.props.card.rdfts is undefined"

I've tried to work with 1 level of array of objects at a time but that doesn't seem to work ether.

Also, It doesn't seem that my axios promise is stopping halting flow of control. I originally wanted for the promise to be resolved then render but it seems that the then just falls through and render is called immediately. I wonder if the array of objects isn't instantiated in time or what but it doesn't seem to work.

If you take a look at my console you will see that I'm getting there error before the promise is resolved, but that shouldn't matter since react is reading straight from the state tree. Once the state tree is updated, then react is supposed to update. right?

15:40:24.978 GET mybuldleyadabundle.js [HTTP/1.1 200 OK 117ms]

15:40:26.855 componentDidMount  CardCC.jsx:42:13

15:40:26.867 TypeError: this.props.card.rdfts is undefined[Learn More]
  ...

15:40:27.327 GET XHR
  myhttpurl.herokuapp.com/api/Rationale/Restraint/Model/1 [HTTP/1.1 200
  OK 143ms]

15:40:27.800 GET XHR mylocalhost:3001/sockjs-node/info [HTTP/1.1 200
  OK 2ms]


问:
Why shouldn't I use ioremap on system memory for ARMv6+?
I need to reserve a large buffer of physically contiguous RAM from the kernel and be able to gaurantee that the buffer will always use a specific, hard-coded physical address. This buffer should remain reserved for the kernel's entire lifetime. I have written a chardev driver as an interface for accessing this buffer in userspace. My platform is an embedded system with ARMv7 architecture running a 2.6 Linux kernel.

Chapter 15 of Linux Device Drivers, Third Edition has the following to say on the topic (page 443):

Reserving the top of RAM is accomplished by passing a mem= argument to the kernel at boot time. For example, if you have 256 MB, the argument mem=255M keeps the kernel from using the top megabyte. Your module could later use the following code to gain access to such memory:
      dmabuf = ioremap (0xFF00000 /* 255M */, 0x100000 /* 1M */);

I've done that plus a couple of other things:

I'm using the memmap bootarg in addition to the mem one. The kernel boot parameters documentation suggests always using memmap whenever you use mem to avoid address collisions.

I used request_mem_region before calling ioremap and, of course, I check that it succeeds before moving ahead.

This is what the system looks like after I've done all that:

```<code># cat /proc/cmdline
root=/dev/mtdblock2 console=ttyS0,115200 init=/sbin/preinit earlyprintk debug <strong>mem=255M memmap=1M$255M</strong>
# cat /proc/iomem
08000000-0fffffff : PCIe Outbound Window, Port 0
  08000000-082fffff : PCI Bus 0001:01
    08000000-081fffff : 0001:01:00.0
    08200000-08207fff : 0001:01:00.0
18000300-18000307 : serial
18000400-18000407 : serial
1800c000-1800cfff : dmu_regs
18012000-18012fff : pcie0
18013000-18013fff : pcie1
18014000-18014fff : pcie2
19000000-19000fff : cru_regs
1e000000-1fffffff : norflash
40000000-47ffffff : PCIe Outbound Window, Port 1
  40000000-403fffff : PCI Bus 0002:01
    40000000-403fffff : 0002:01:00.0
  40400000-409fffff : PCI Bus 0002:01
    40400000-407fffff : 0002:01:00.0
    40800000-40807fff : 0002:01:00.0
80000000-8fefffff : System RAM
  80052000-8045dfff : Kernel text
  80478000-80500143 : Kernel data
<strong>8ff00000-8fffffff : foo</strong>
</code>```

Everything so far looks good, and my driver is working perfectly. I'm able to read and write directly to the specific physical address I've chosen.

However, during bootup, a big scary warning (™) was triggered:

```<code>BUG: Your driver calls ioremap() on system memory.  This leads
to architecturally unpredictable behaviour on ARMv6+, and ioremap()
will fail in the next kernel release.  Please fix your driver.
------------[ cut here ]------------
WARNING: at arch/arm/mm/ioremap.c:211 __arm_ioremap_pfn_caller+0x8c/0x144()
Modules linked in:
[] (unwind_backtrace+0x0/0xf8) from [] (warn_slowpath_common+0x4c/0x64)
[] (warn_slowpath_common+0x4c/0x64) from [] (warn_slowpath_null+0x1c/0x24)
[] (warn_slowpath_null+0x1c/0x24) from [] (__arm_ioremap_pfn_caller+0x8c/0x144)
[] (__arm_ioremap_pfn_caller+0x8c/0x144) from [] (__arm_ioremap_caller+0x50/0x58)
[] (__arm_ioremap_caller+0x50/0x58) from [] (foo_init+0x204/0x2b0)
[] (foo_init+0x204/0x2b0) from [] (do_one_initcall+0x30/0x19c)
[] (do_one_initcall+0x30/0x19c) from [] (kernel_init+0x154/0x218)
[] (kernel_init+0x154/0x218) from [] (kernel_thread_exit+0x0/0x8)
---[ end trace 1a4cab5dbc05c3e7 ]---</code>```

Triggered from: arc/arm/mm/ioremap.c

```<code>/*
 * Don't allow RAM to be mapped - this causes problems with ARMv6+
 */
if (pfn_valid(pfn)) {
    printk(KERN_WARNING "BUG: Your driver calls ioremap() on system memory.  This leads\n"
           KERN_WARNING "to architecturally unpredictable behaviour on ARMv6+, and ioremap()\n"
           KERN_WARNING "will fail in the next kernel release.  Please fix your driver.\n");
    WARN_ON(1);
}
</code>```

What problems, exactly, could this cause? Can they be mitigated? What are my alternatives?

答:
So I've done exactly that, and it's working.

Provide the kernel command line (e.g. /proc/cmdline) and the resulting memory map (i.e. /proc/iomem) to verify this.

What problems, exactly, could this cause?

The problem with using ioremap() on system memory is that you end up assigning conflicting attributes to the memory which causes "unpredictable" behavior.

See the article "ARM's multiply-mapped memory mess", which provides a history to the warning that you are triggering.

The ARM kernel maps RAM as normal memory with writeback caching; it's also marked non-shared on uniprocessor systems. The ioremap() system call, used to map I/O memory for CPU use, is different: that memory is mapped as device memory, uncached, and, maybe, shared. These different mappings give the expected behavior for both types of memory. Where things get tricky is when somebody calls ioremap() to create a new mapping for system RAM.

The problem with these multiple mappings is that they will have differing attributes. As of version 6 of the ARM architecture, the specified behavior in that situation is "unpredictable."

Note that "system memory" is the RAM that is managed by the kernel.

The fact that you trigger the warning indicates that your code is generating multiple mappings for a region of memory.

Can they be mitigated?

You have to ensure that the RAM you want to ioremap() is not "system memory", i.e. managed by the kernel.

See also this answer.

ADDENDUM

This warning that concerns you is the result of pfn_valid(pfn) returning TRUE rather than FALSE.

Based on the Linux cross-reference link that you provided for version 2.6.37,
pfn_valid() is simply returning the result of

```<code>memblock_is_memory(pfn << PAGE_SHIFT);
</code>```

which in turn is simply returning the result of

```<code>memblock_search(&memblock.memory, addr) != -1;
</code>```

I suggest that the kernel code be hacked so that the conflict is revealed.

Before the call to ioremap(), assign TRUE to the global variable memblock_debug.

The following patch should display the salient information about the memory conflict.

(The memblock list is ordered by base-address, so memblock_search() performs a binary search on this list, hence the use of mid as the index.)

```<code> static int __init_memblock memblock_search(struct memblock_type *type, phys_addr_t addr)
 {
         unsigned int left = 0, right = type->cnt;

         do {
                 unsigned int mid = (right + left) / 2;

                 if (addr < type->regions[mid].base)
                         right = mid;
                 else if (addr >= (type->regions[mid].base +
                                   type->regions[mid].size))
                         left = mid + 1;
-                else
+                else {
+                        if (memblock_debug)
+                                pr_info("MATCH for 0x%x: m=0x%x b=0x%x s=0x%x\n",
+                                                addr, mid,
+                                                type->regions[mid].base,
+                                                type->regions[mid].size);
                         return mid;
+                }
         } while (left < right);
         return -1;
 }
</code>```

If you want to see all the memory blocks, then call memblock_dump_all() with the variable memblock_debug is TRUE.

[Interesting that this is essentially a programming question, yet we haven't seen any of your code.]

ADDENDUM 2

Since you're probably using ATAGs (instead of Device Tree), and you want to dedicate a memory region, fix up the ATAG_MEM to reflect this smaller size of physical memory.

Assuming you have made zero changes to your boot code, the ATAG_MEM is still specifying the full RAM, so perhaps this could be the source of the system memory conflict that causes the warning.

See this answer about ATAGs and this related answer.

Body:
I need to reserve a large buffer of physically contiguous RAM from the kernel and be able to gaurantee that the buffer will always use a specific, hard-coded physical address. This buffer should remain reserved for the kernel's entire lifetime. I have written a chardev driver as an interface for accessing this buffer in userspace. My platform is an embedded system with ARMv7 architecture running a 2.6 Linux kernel.

Chapter 15 of Linux Device Drivers, Third Edition has the following to say on the topic (page 443):

Reserving the top of RAM is accomplished by passing a mem= argument to the kernel at boot time. For example, if you have 256 MB, the argument mem=255M keeps the kernel from using the top megabyte. Your module could later use the following code to gain access to such memory:
      dmabuf = ioremap (0xFF00000 /* 255M */, 0x100000 /* 1M */);

I've done that plus a couple of other things:

I'm using the memmap bootarg in addition to the mem one. The kernel boot parameters documentation suggests always using memmap whenever you use mem to avoid address collisions.

I used request_mem_region before calling ioremap and, of course, I check that it succeeds before moving ahead.

This is what the system looks like after I've done all that:

# cat /proc/cmdline
root=/dev/mtdblock2 console=ttyS0,115200 init=/sbin/preinit earlyprintk debug mem=255M memmap=1M$255M
# cat /proc/iomem
08000000-0fffffff : PCIe Outbound Window, Port 0
  08000000-082fffff : PCI Bus 0001:01
    08000000-081fffff : 0001:01:00.0
    08200000-08207fff : 0001:01:00.0
18000300-18000307 : serial
18000400-18000407 : serial
1800c000-1800cfff : dmu_regs
18012000-18012fff : pcie0
18013000-18013fff : pcie1
18014000-18014fff : pcie2
19000000-19000fff : cru_regs
1e000000-1fffffff : norflash
40000000-47ffffff : PCIe Outbound Window, Port 1
  40000000-403fffff : PCI Bus 0002:01
    40000000-403fffff : 0002:01:00.0
  40400000-409fffff : PCI Bus 0002:01
    40400000-407fffff : 0002:01:00.0
    40800000-40807fff : 0002:01:00.0
80000000-8fefffff : System RAM
  80052000-8045dfff : Kernel text
  80478000-80500143 : Kernel data
8ff00000-8fffffff : foo

Everything so far looks good, and my driver is working perfectly. I'm able to read and write directly to the specific physical address I've chosen.

However, during bootup, a big scary warning (™) was triggered:

BUG: Your driver calls ioremap() on system memory.  This leads
to architecturally unpredictable behaviour on ARMv6+, and ioremap()
will fail in the next kernel release.  Please fix your driver.
------------[ cut here ]------------
WARNING: at arch/arm/mm/ioremap.c:211 __arm_ioremap_pfn_caller+0x8c/0x144()
Modules linked in:
[] (unwind_backtrace+0x0/0xf8) from [] (warn_slowpath_common+0x4c/0x64)
[] (warn_slowpath_common+0x4c/0x64) from [] (warn_slowpath_null+0x1c/0x24)
[] (warn_slowpath_null+0x1c/0x24) from [] (__arm_ioremap_pfn_caller+0x8c/0x144)
[] (__arm_ioremap_pfn_caller+0x8c/0x144) from [] (__arm_ioremap_caller+0x50/0x58)
[] (__arm_ioremap_caller+0x50/0x58) from [] (foo_init+0x204/0x2b0)
[] (foo_init+0x204/0x2b0) from [] (do_one_initcall+0x30/0x19c)
[] (do_one_initcall+0x30/0x19c) from [] (kernel_init+0x154/0x218)
[] (kernel_init+0x154/0x218) from [] (kernel_thread_exit+0x0/0x8)
---[ end trace 1a4cab5dbc05c3e7 ]---

Triggered from: arc/arm/mm/ioremap.c

/*
 * Don't allow RAM to be mapped - this causes problems with ARMv6+
 */
if (pfn_valid(pfn)) {
    printk(KERN_WARNING "BUG: Your driver calls ioremap() on system memory.  This leads\n"
           KERN_WARNING "to architecturally unpredictable behaviour on ARMv6+, and ioremap()\n"
           KERN_WARNING "will fail in the next kernel release.  Please fix your driver.\n");
    WARN_ON(1);
}

What problems, exactly, could this cause? Can they be mitigated? What are my alternatives?

Body:
So I've done exactly that, and it's working.

Provide the kernel command line (e.g. /proc/cmdline) and the resulting memory map (i.e. /proc/iomem) to verify this.

What problems, exactly, could this cause?

The problem with using ioremap() on system memory is that you end up assigning conflicting attributes to the memory which causes "unpredictable" behavior.

See the article "ARM's multiply-mapped memory mess", which provides a history to the warning that you are triggering.

The ARM kernel maps RAM as normal memory with writeback caching; it's also marked non-shared on uniprocessor systems. The ioremap() system call, used to map I/O memory for CPU use, is different: that memory is mapped as device memory, uncached, and, maybe, shared. These different mappings give the expected behavior for both types of memory. Where things get tricky is when somebody calls ioremap() to create a new mapping for system RAM.

The problem with these multiple mappings is that they will have differing attributes. As of version 6 of the ARM architecture, the specified behavior in that situation is "unpredictable."

Note that "system memory" is the RAM that is managed by the kernel.

The fact that you trigger the warning indicates that your code is generating multiple mappings for a region of memory.

Can they be mitigated?

You have to ensure that the RAM you want to ioremap() is not "system memory", i.e. managed by the kernel.

See also this answer.

ADDENDUM

This warning that concerns you is the result of pfn_valid(pfn) returning TRUE rather than FALSE.

Based on the Linux cross-reference link that you provided for version 2.6.37,
pfn_valid() is simply returning the result of

memblock_is_memory(pfn << PAGE_SHIFT);

which in turn is simply returning the result of

memblock_search(&memblock.memory, addr) != -1;

I suggest that the kernel code be hacked so that the conflict is revealed.

Before the call to ioremap(), assign TRUE to the global variable memblock_debug.

The following patch should display the salient information about the memory conflict.

(The memblock list is ordered by base-address, so memblock_search() performs a binary search on this list, hence the use of mid as the index.)

 static int __init_memblock memblock_search(struct memblock_type *type, phys_addr_t addr)
 {
         unsigned int left = 0, right = type->cnt;

         do {
                 unsigned int mid = (right + left) / 2;

                 if (addr < type->regions[mid].base)
                         right = mid;
                 else if (addr >= (type->regions[mid].base +
                                   type->regions[mid].size))
                         left = mid + 1;
-                else
+                else {
+                        if (memblock_debug)
+                                pr_info("MATCH for 0x%x: m=0x%x b=0x%x s=0x%x\n",
+                                                addr, mid,
+                                                type->regions[mid].base,
+                                                type->regions[mid].size);
                         return mid;
+                }
         } while (left < right);
         return -1;
 }

If you want to see all the memory blocks, then call memblock_dump_all() with the variable memblock_debug is TRUE.

[Interesting that this is essentially a programming question, yet we haven't seen any of your code.]

ADDENDUM 2

Since you're probably using ATAGs (instead of Device Tree), and you want to dedicate a memory region, fix up the ATAG_MEM to reflect this smaller size of physical memory.

Assuming you have made zero changes to your boot code, the ATAG_MEM is still specifying the full RAM, so perhaps this could be the source of the system memory conflict that causes the warning.

See this answer about ATAGs and this related answer.


问:
query to Extract from Json in Postgres
I've a json object in my postgres db, which looks like as given below

{"Actor":[{"personName":"Shashi Kapoor","characterName":"Prem"},{"personName":"Sharmila Tagore","characterName":"Preeti"},{"personName":"Shatrughan Sinha","characterName":"Dr. Amar"]}

Edited (from editor: left the original because it is an invalid json, in my edit I fixed it)

```<code>{
   "Actor":[
      {
         "personName":"Shashi Kapoor",
         "characterName":"Prem"
      },
      {
         "personName":"Sharmila Tagore",
         "characterName":"Preeti"
      },
      {
         "personName":"Shatrughan Sinha",
         "characterName":"Dr. Amar"
      }
   ]
}
</code>```

the name of the column be xyz and I've a corresponding content_id.

I need to retrieve content_ids that have Actor & personName =  Sharmila Tagore.

I tried many queries, among those these two where very possible query to get but still i didn't get.

```<code>SELECT content_id
  FROM content_table
 WHERE cast_and_crew #>> '{Actor,personName}' = '"C. R. Simha"'
</code>```

.

```<code>SELECT cast_and_crew ->> 'content_id' AS content_id
  FROM content_table
 WHERE cast_and_crew ->> 'Actor' -> 'personName' = 'C. R. Simha'
</code>```

答:
You should use jsonb_array_elements() to search in a nested jsonb array:

```<code>select content_id, value
from content_table,
lateral jsonb_array_elements(cast_and_crew->'Actor');

 content_id |                              value
------------+-----------------------------------------------------------------
          1 | {"personName": "Shashi Kapoor", "characterName": "Prem"}
          1 | {"personName": "Sharmila Tagore", "characterName": "Preeti"}
          1 | {"personName": "Shatrughan Sinha", "characterName": "Dr. Amar"}
(3 rows)
</code>```

Column value is of the type jsonb so you can use ->> operator for it:

```<code>select content_id, value
from content_table,
lateral jsonb_array_elements(cast_and_crew->'Actor')
where value->>'personName' = 'Sharmila Tagore';

 content_id |                            value
------------+--------------------------------------------------------------
          1 | {"personName": "Sharmila Tagore", "characterName": "Preeti"}
(1 row)
</code>```

Note, if you are using json (not jsonb) use json_array_elements() of course.

Title: query to Extract from Json in Postgres

Body:
I've a json object in my postgres db, which looks like as given below

{"Actor":[{"personName":"Shashi Kapoor","characterName":"Prem"},{"personName":"Sharmila Tagore","characterName":"Preeti"},{"personName":"Shatrughan Sinha","characterName":"Dr. Amar"]}

Edited (from editor: left the original because it is an invalid json, in my edit I fixed it)

{
   "Actor":[
      {
         "personName":"Shashi Kapoor",
         "characterName":"Prem"
      },
      {
         "personName":"Sharmila Tagore",
         "characterName":"Preeti"
      },
      {
         "personName":"Shatrughan Sinha",
         "characterName":"Dr. Amar"
      }
   ]
}

the name of the column be xyz and I've a corresponding content_id.

I need to retrieve content_ids that have Actor & personName =  Sharmila Tagore.

I tried many queries, among those these two where very possible query to get but still i didn't get.

SELECT content_id
  FROM content_table
 WHERE cast_and_crew #>> '{Actor,personName}' = '"C. R. Simha"'

.

SELECT cast_and_crew ->> 'content_id' AS content_id
  FROM content_table
 WHERE cast_and_crew ->> 'Actor' -> 'personName' = 'C. R. Simha'

Body:
You should use jsonb_array_elements() to search in a nested jsonb array:

select content_id, value
from content_table,
lateral jsonb_array_elements(cast_and_crew->'Actor');

 content_id |                              value
------------+-----------------------------------------------------------------
          1 | {"personName": "Shashi Kapoor", "characterName": "Prem"}
          1 | {"personName": "Sharmila Tagore", "characterName": "Preeti"}
          1 | {"personName": "Shatrughan Sinha", "characterName": "Dr. Amar"}
(3 rows)

Column value is of the type jsonb so you can use ->> operator for it:

select content_id, value
from content_table,
lateral jsonb_array_elements(cast_and_crew->'Actor')
where value->>'personName' = 'Sharmila Tagore';

 content_id |                            value
------------+--------------------------------------------------------------
          1 | {"personName": "Sharmila Tagore", "characterName": "Preeti"}
(1 row)

Note, if you are using json (not jsonb) use json_array_elements() of course.


问:
Bluetooth keeps disconnecting after being connected to another Android device for a while
I have an Xperia Z3C, Android 5.1.1 and I'm trying to connect it to a Nexus 4 Android 6.0.1 via Bluetooth. Pairing them is OK, but when I try to connect them, it says 'Connected' for less than a second and automatically disconnects.

Is this a known issue? I haven't found anything about this.

Here's what logcat says:

```<code>03-14 17:25:55.308: E/bt-btif(14245): bte_scan_filt_param_cfg_evt, 1
03-14 17:25:55.308: E/bt-btif(14245): bte_scan_filt_param_cfg_evt, 1
03-14 17:25:55.990: E/bt-btm(14245): new address: xx:xx:xx:xx:xx:xx
03-14 17:25:55.990: E/bt-btm(14245): new address: xx:xx:xx:xx:xx:xx
03-14 17:25:56.712: E/bt-btm(14245): new address: xx:xx:xx:xx:xx:xx
03-14 17:25:57.464: E/bt-btif(14245): bte_scan_filt_param_cfg_evt, 1
03-14 17:25:57.814: E/bt-btm(14245): Ignoring RNR as the state is not BTM_SEC_STATE_GETTING_NAME
03-14 17:25:57.933: E/NetlinkEvent(318): Unknown ifindex 41 in RTM_DELADDR
03-14 17:25:57.963: E/dhcpcd(15974): bt-pan: interface not found or invalid
03-14 17:25:57.986: E/BluetoothPanServiceJni(14245): ## ERROR : disconnectPanNative(L224): Failed disconnect pan channel, status: 1##
03-14 17:25:58.139: E/BluetoothTetheringNetworkFactory(14245): DHCP request error:DHCP result was failed
03-14 17:26:01.382: E/bt-btm(14245): btm_sec_disconnected - Clearing Pending flag
</code>```

答:
I had the same problem while trying to scan for Bluetooth devices from my Android application. The interesting thing is that it does not throw any exception (caught or uncaught) and fails silently! The problem occurs for devices with API Level >= 23 (Android 6.0). Here is an extract of my Logcat logs :

```<code>03-30 14:07:52.099 192-211/? I/BufferQueueProducer: [org.manios.testbt/org.manios.testbt.printing.BluetoothPrinterDiscovery](this:0x7fa16de400,id:1467,api:1,p:26262,c:192) queueBuffer: fps=0.19 dur=5154.29 max=5154.29 min=5154.29
03-30 14:07:52.114 192-192/? I/SurfaceFlinger: [Built-in Screen (type:0)] fps:1.091767,dur:1831.89,max:999.66,min:832.23
03-30 14:07:52.137 774-1001/? D/InputReader: AP_PROF:AppLaunch_dispatchPtr:Up:89556864, ID:0, Index:2056797440
03-30 14:07:52.137 774-1001/? I/PerfService: PerfServiceNative_boostEnableTimeoutMsAsync:3, 100
03-30 14:07:52.138 26262-26262/org.manios.testbt D/SettingsInterface:  from settings cache , name = sound_effects_enabled , value = 0
03-30 14:07:52.138 26262-26262/org.manios.testbt D/BluetoothAdapter: isEnabled
03-30 14:07:52.140 26262-26262/org.manios.testbt D/BluetoothAdapter: getName
03-30 14:07:52.141 774-1636/? D/BluetoothManagerService: checkIfCallerIsForegroundUser: valid=true callingUser=0 parentUser=-10000 foregroundUser=0
03-30 14:07:52.142 21807-21818/? D/BluetoothAdapterProperties: getName: mName = Lenovo TAB3 8
03-30 14:07:52.144 26262-666/org.manios.testbt D/BluetoothAdapter: isEnabled
03-30 14:07:52.146 26262-666/org.manios.testbt D/BluetoothAdapter: isDiscovering
03-30 14:07:52.148 26262-666/org.manios.testbt D/BluetoothAdapter: 109507751: getState(). Returning 12
03-30 14:07:52.152 21807-21817/? D/BluetoothAdapterProperties: isDiscovering: mDiscovering = false
03-30 14:07:52.156 26262-666/org.manios.testbt D/BluetoothAdapter: startDiscovery
03-30 14:07:52.158 26262-666/org.manios.testbt D/BluetoothAdapter: 109507751: getState(). Returning 12
03-30 14:07:52.160 21807-21830/? W/bt_btif: bta_dm_check_av:0
03-30 14:07:52.172 21807-21830/? E/bt_btif: bte_scan_filt_param_cfg_evt, 1
03-30 14:07:52.181 21807-21823/? I/BluetoothAdapterProperties: Callback:discoveryStateChangeCallback with state:1
03-30 14:07:52.182 774-2924/? V/ActivityManager: Broadcast: Intent { act=android.bluetooth.adapter.action.DISCOVERY_STARTED flg=0x10 } ordered=false userid=0 callerApp=ProcessRecord{c376192 21807:com.android.bluetooth/1002}
03-30 14:07:52.184 1057-1265/? V/BluetoothEventManager: Received android.bluetooth.adapter.action.DISCOVERY_STARTED
03-30 14:07:52.185 1057-1265/? D/BluetoothEventManager: scanning state change to true
03-30 14:07:52.186 21983-21983/? D/ActivityThread: BDC-Calling onReceive: intent=Intent { act=android.bluetooth.adapter.action.DISCOVERY_STARTED flg=0x10 cmp=com.android.settings/.bluetooth.BluetoothDiscoveryReceiver }, receiver=com.android.settings.bluetooth.BluetoothDiscoveryReceiver@b02fe63
03-30 14:07:52.186 21983-21983/? V/BluetoothDiscoveryReceiver: Received: android.bluetooth.adapter.action.DISCOVERY_STARTED
03-30 14:07:52.187 21983-21983/? D/ActivityThread: BDC-RECEIVER handled : 0 / ReceiverData{intent=Intent { act=android.bluetooth.adapter.action.DISCOVERY_STARTED flg=0x10 cmp=com.android.settings/.bluetooth.BluetoothDiscoveryReceiver } packageName=com.android.settings resultCode=-1 resultData=null resultExtras=null}
03-30 14:07:52.218 774-1001/? D/InputReader: AP_PROF:AppLaunch_dispatchPtr:Down:89556946, ID:0, Index:2056794048
03-30 14:07:52.219 774-1001/? I/PerfService: PerfServiceNative_boostEnableAsync:3
</code>```

I found after some searching using this issue, that in API Level >= 23 (Android 6.0) we have to add the following permission to AndroidManifext.xml

```<code><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</code>```

so that scanning and other Bluetooth actions function properly.

In Android documentation it states in BluetoothAdapter.startDiscovery() that it requires BLUETOOTH_ADMIN permission with no further details. But if we take a look into BluetoothLeScanner.startScan(),it states clearly that:

Requires BLUETOOTH_ADMIN permission. An app must hold ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission in order to get results.

Hope this helps!

Body:
I have an Xperia Z3C, Android 5.1.1 and I'm trying to connect it to a Nexus 4 Android 6.0.1 via Bluetooth. Pairing them is OK, but when I try to connect them, it says 'Connected' for less than a second and automatically disconnects.

Is this a known issue? I haven't found anything about this.

Here's what logcat says:

03-14 17:25:55.308: E/bt-btif(14245): bte_scan_filt_param_cfg_evt, 1
03-14 17:25:55.308: E/bt-btif(14245): bte_scan_filt_param_cfg_evt, 1
03-14 17:25:55.990: E/bt-btm(14245): new address: xx:xx:xx:xx:xx:xx
03-14 17:25:55.990: E/bt-btm(14245): new address: xx:xx:xx:xx:xx:xx
03-14 17:25:56.712: E/bt-btm(14245): new address: xx:xx:xx:xx:xx:xx
03-14 17:25:57.464: E/bt-btif(14245): bte_scan_filt_param_cfg_evt, 1
03-14 17:25:57.814: E/bt-btm(14245): Ignoring RNR as the state is not BTM_SEC_STATE_GETTING_NAME
03-14 17:25:57.933: E/NetlinkEvent(318): Unknown ifindex 41 in RTM_DELADDR
03-14 17:25:57.963: E/dhcpcd(15974): bt-pan: interface not found or invalid
03-14 17:25:57.986: E/BluetoothPanServiceJni(14245): ## ERROR : disconnectPanNative(L224): Failed disconnect pan channel, status: 1##
03-14 17:25:58.139: E/BluetoothTetheringNetworkFactory(14245): DHCP request error:DHCP result was failed
03-14 17:26:01.382: E/bt-btm(14245): btm_sec_disconnected - Clearing Pending flag

Body:
I had the same problem while trying to scan for Bluetooth devices from my Android application. The interesting thing is that it does not throw any exception (caught or uncaught) and fails silently! The problem occurs for devices with API Level >= 23 (Android 6.0). Here is an extract of my Logcat logs :

03-30 14:07:52.099 192-211/? I/BufferQueueProducer: [org.manios.testbt/org.manios.testbt.printing.BluetoothPrinterDiscovery](this:0x7fa16de400,id:1467,api:1,p:26262,c:192) queueBuffer: fps=0.19 dur=5154.29 max=5154.29 min=5154.29
03-30 14:07:52.114 192-192/? I/SurfaceFlinger: [Built-in Screen (type:0)] fps:1.091767,dur:1831.89,max:999.66,min:832.23
03-30 14:07:52.137 774-1001/? D/InputReader: AP_PROF:AppLaunch_dispatchPtr:Up:89556864, ID:0, Index:2056797440
03-30 14:07:52.137 774-1001/? I/PerfService: PerfServiceNative_boostEnableTimeoutMsAsync:3, 100
03-30 14:07:52.138 26262-26262/org.manios.testbt D/SettingsInterface:  from settings cache , name = sound_effects_enabled , value = 0
03-30 14:07:52.138 26262-26262/org.manios.testbt D/BluetoothAdapter: isEnabled
03-30 14:07:52.140 26262-26262/org.manios.testbt D/BluetoothAdapter: getName
03-30 14:07:52.141 774-1636/? D/BluetoothManagerService: checkIfCallerIsForegroundUser: valid=true callingUser=0 parentUser=-10000 foregroundUser=0
03-30 14:07:52.142 21807-21818/? D/BluetoothAdapterProperties: getName: mName = Lenovo TAB3 8
03-30 14:07:52.144 26262-666/org.manios.testbt D/BluetoothAdapter: isEnabled
03-30 14:07:52.146 26262-666/org.manios.testbt D/BluetoothAdapter: isDiscovering
03-30 14:07:52.148 26262-666/org.manios.testbt D/BluetoothAdapter: 109507751: getState(). Returning 12
03-30 14:07:52.152 21807-21817/? D/BluetoothAdapterProperties: isDiscovering: mDiscovering = false
03-30 14:07:52.156 26262-666/org.manios.testbt D/BluetoothAdapter: startDiscovery
03-30 14:07:52.158 26262-666/org.manios.testbt D/BluetoothAdapter: 109507751: getState(). Returning 12
03-30 14:07:52.160 21807-21830/? W/bt_btif: bta_dm_check_av:0
03-30 14:07:52.172 21807-21830/? E/bt_btif: bte_scan_filt_param_cfg_evt, 1
03-30 14:07:52.181 21807-21823/? I/BluetoothAdapterProperties: Callback:discoveryStateChangeCallback with state:1
03-30 14:07:52.182 774-2924/? V/ActivityManager: Broadcast: Intent { act=android.bluetooth.adapter.action.DISCOVERY_STARTED flg=0x10 } ordered=false userid=0 callerApp=ProcessRecord{c376192 21807:com.android.bluetooth/1002}
03-30 14:07:52.184 1057-1265/? V/BluetoothEventManager: Received android.bluetooth.adapter.action.DISCOVERY_STARTED
03-30 14:07:52.185 1057-1265/? D/BluetoothEventManager: scanning state change to true
03-30 14:07:52.186 21983-21983/? D/ActivityThread: BDC-Calling onReceive: intent=Intent { act=android.bluetooth.adapter.action.DISCOVERY_STARTED flg=0x10 cmp=com.android.settings/.bluetooth.BluetoothDiscoveryReceiver }, receiver=com.android.settings.bluetooth.BluetoothDiscoveryReceiver@b02fe63
03-30 14:07:52.186 21983-21983/? V/BluetoothDiscoveryReceiver: Received: android.bluetooth.adapter.action.DISCOVERY_STARTED
03-30 14:07:52.187 21983-21983/? D/ActivityThread: BDC-RECEIVER handled : 0 / ReceiverData{intent=Intent { act=android.bluetooth.adapter.action.DISCOVERY_STARTED flg=0x10 cmp=com.android.settings/.bluetooth.BluetoothDiscoveryReceiver } packageName=com.android.settings resultCode=-1 resultData=null resultExtras=null}
03-30 14:07:52.218 774-1001/? D/InputReader: AP_PROF:AppLaunch_dispatchPtr:Down:89556946, ID:0, Index:2056794048
03-30 14:07:52.219 774-1001/? I/PerfService: PerfServiceNative_boostEnableAsync:3

I found after some searching using this issue, that in API Level >= 23 (Android 6.0) we have to add the following permission to AndroidManifext.xml

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

so that scanning and other Bluetooth actions function properly.

In Android documentation it states in BluetoothAdapter.startDiscovery() that it requires BLUETOOTH_ADMIN permission with no further details. But if we take a look into BluetoothLeScanner.startScan(),it states clearly that:

Requires BLUETOOTH_ADMIN permission. An app must hold ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission in order to get results.

Hope this helps!


问:
why use of deleted rvalue reference constructor function?
This is a very simple example with class A and B.
I want allow only deep copy, so I disabled the rvalue reference constructor.

```<code>#include <iostream>

class B;

class A {
public:
    A();
    ~A();
    A(const A & other);
    A& operator=(const A & other);
    A(A && ) = delete;
    A& operator=(A && ) = delete;
    B toB() const;

private:
    int a_;
};

class B {
public:
    B();
    ~B();
    B(const B & other);
    B& operator=(const B & other);
    B(B && ) = delete;
    B& operator=(B && ) = delete;
    A toA() const;

private:
    int b_;
};

A::A()
{
}

A::~A()
{
}
A::A(const A & other)
        : a_(other.a_)
{
}
A& A::operator=(const A & other)
{
    a_ = other.a_;
    return *this;
}

B A::toB() const
{
    return B();
}

B::B()
{
}
B::~B()
{
}
B::B(const B & other)
        : b_(other.b_)
{
}
B& B::operator=(const B & other)
{
    b_ = other.b_;
    return *this;
}

A B::toA() const
{
    return A();
}

int main()
{
    A a();
    B b();

    return 0;
}
</code>```

the gcc compiler report bugs like this:

```<code>In member function 'B A::toB() const':
error: use of deleted function 'B::B(B&&)'
     return B();
              ^
note: declared here
     B(B && ) = delete;
</code>```

I'm wandering why it use B(B && ) function, not the B(const B &) function instead.

答:
Because you added the move-constructor. Deleted but declared functions are still part of the interface of a class. That means it will be considered by the compiler, but since it's marked as deleted you get the error. If you want to force the copy-constructor to be called then remove the move-constructor declaration.

From this deleted functions reference:

Any use of a deleted function is ill-formed (the program will not compile). This includes calls, both explicit (with a function call operator) and implicit (a call to deleted overloaded operator, special member function, ...

[Emphasis mine]

Since the deleted functions are part of the interface, the compiler will try to use them. So when there is a deleted move constructor, the compiler will see that and try to use it, but since it is deleted there will be an error.

Since no move constructor will be created by the compiler if there is an explicit copy constructor (as per this move constructor reference) simply having a defaulted copy constructor will inhibit moving of object.

All of that means your classes can be very much simplified:

```<code>class A {
public:
    A() : a_() {}

    A(const A & other) = default;

    B toB() const;

private:
    int a_;
};

class B {
public:
    B() : b_() {}

    B(const B & other) = default;

    A toA() const;

private:
    int b_;
};
</code>```

Because the classes above have user-declared copy constructors no movement constructor will be created, and the class can't be moved only copied.

Body:
This is a very simple example with class A and B.
I want allow only deep copy, so I disabled the rvalue reference constructor.

#include <iostream>

class B;

class A {
public:
    A();
    ~A();
    A(const A & other);
    A& operator=(const A & other);
    A(A && ) = delete;
    A& operator=(A && ) = delete;
    B toB() const;

private:
    int a_;
};

class B {
public:
    B();
    ~B();
    B(const B & other);
    B& operator=(const B & other);
    B(B && ) = delete;
    B& operator=(B && ) = delete;
    A toA() const;

private:
    int b_;
};

A::A()
{
}

A::~A()
{
}
A::A(const A & other)
        : a_(other.a_)
{
}
A& A::operator=(const A & other)
{
    a_ = other.a_;
    return *this;
}

B A::toB() const
{
    return B();
}

B::B()
{
}
B::~B()
{
}
B::B(const B & other)
        : b_(other.b_)
{
}
B& B::operator=(const B & other)
{
    b_ = other.b_;
    return *this;
}

A B::toA() const
{
    return A();
}

int main()
{
    A a();
    B b();

    return 0;
}

the gcc compiler report bugs like this:

In member function 'B A::toB() const':
error: use of deleted function 'B::B(B&&)'
     return B();
              ^
note: declared here
     B(B && ) = delete;

I'm wandering why it use B(B && ) function, not the B(const B &) function instead.

Body:
Because you added the move-constructor. Deleted but declared functions are still part of the interface of a class. That means it will be considered by the compiler, but since it's marked as deleted you get the error. If you want to force the copy-constructor to be called then remove the move-constructor declaration.

From this deleted functions reference:

Any use of a deleted function is ill-formed (the program will not compile). This includes calls, both explicit (with a function call operator) and implicit (a call to deleted overloaded operator, special member function, ...

[Emphasis mine]

Since the deleted functions are part of the interface, the compiler will try to use them. So when there is a deleted move constructor, the compiler will see that and try to use it, but since it is deleted there will be an error.

Since no move constructor will be created by the compiler if there is an explicit copy constructor (as per this move constructor reference) simply having a defaulted copy constructor will inhibit moving of object.

All of that means your classes can be very much simplified:

class A {
public:
    A() : a_() {}

    A(const A & other) = default;

    B toB() const;

private:
    int a_;
};

class B {
public:
    B() : b_() {}

    B(const B & other) = default;

    A toA() const;

private:
    int b_;
};

Because the classes above have user-declared copy constructors no movement constructor will be created, and the class can't be moved only copied.


问:
constraint on static fields and type inference
Is it possible to have constraint on static fields in Haxe? For example we may have classes which have static field instance of type of corresponding class. And we may want a function that will return an instance of class passed as parameter. This is my attempt:

```<code>class Foo {
    static public var instance = new Foo();
    function new() {}
}

class Test {
    // get instance from every class that have static field instance
    static function getInstance<T, ClassT:({instance:T}, Class<T>)>(t:ClassT):T {
        return t.instance;
    }

    static function main() {
        var a = getInstance(Foo);
        $type(a); //Test.hx:14: characters 14-15 : Warning : Unknown<0>
    }
}
</code>```

but it fails, because type parameter constraints are checked lazily. Any ideas on how do this?

答:
If you don't mind using macro, here is a possible solution:
http://try-haxe.mrcdk.com/#7d650

Foo.hx

```<code>class Foo {
    static public var instance = new Foo();
    public var foo:Int;
    function new() {}
}

class Test {

    macro static function getInstance(e) return Macro.getInstance(e);

    static function _getInstance<T, ClassT:({instance:T}, Class<T>)>(t:ClassT):T
        return t.instance;

    static function main() {
        var a = getInstance(Foo);
        $type(a);
    }
}
</code>```

Macro.hx

```<code>import haxe.macro.Expr;
import haxe.macro.Context.*;
using tink.MacroApi;

class Macro {
    public static function getInstance(e:Expr) {
        var ct = TPath(e.toString().asTypePath());
        return macro (Test._getInstance($e):$ct);
    }
}
</code>```

Body:
Is it possible to have constraint on static fields in Haxe? For example we may have classes which have static field instance of type of corresponding class. And we may want a function that will return an instance of class passed as parameter. This is my attempt:

class Foo {
    static public var instance = new Foo();
    function new() {}
}

class Test {
    // get instance from every class that have static field instance
    static function getInstance<T, ClassT:({instance:T}, Class<T>)>(t:ClassT):T {
        return t.instance;
    }

    static function main() {
        var a = getInstance(Foo);
        $type(a); //Test.hx:14: characters 14-15 : Warning : Unknown<0>
    }
}

but it fails, because type parameter constraints are checked lazily. Any ideas on how do this?

Body:
If you don't mind using macro, here is a possible solution:
http://try-haxe.mrcdk.com/#7d650

Foo.hx

class Foo {
    static public var instance = new Foo();
    public var foo:Int;
    function new() {}
}

class Test {

    macro static function getInstance(e) return Macro.getInstance(e);

    static function _getInstance<T, ClassT:({instance:T}, Class<T>)>(t:ClassT):T
        return t.instance;

    static function main() {
        var a = getInstance(Foo);
        $type(a);
    }
}

Macro.hx

import haxe.macro.Expr;
import haxe.macro.Context.*;
using tink.MacroApi;

class Macro {
    public static function getInstance(e:Expr) {
        var ct = TPath(e.toString().asTypePath());
        return macro (Test._getInstance($e):$ct);
    }
}


问:
NemoJs vs NightWatchJS ? Advantages and Disadvantages
i'm pretty much new to both the frameworks. seems like nightwatch has better documentation and extensive api compared to Nemo ?

What are major advantages in using one over another ?

答: Nemo has no BDD tool inbuilt. You need to use something like Cucumber. Whereas Nightwatch comes along with its own BDD. There is even an option to pair it with Cucumber.</p>


问:
Even with "voip" present in "UIBackgroundModes" in "plist", iOS App does not auto start after device reboot in iOS10
I need my VoIP App to auto start after rebooting the device.

Apple docs clearly mention that :-

(=========EDIT: This is from official Apple docs please have a look at this before commenting or answering that the App cannot be launched without user interaction or silent push notification. Also have a look at Github project below, people have verified this behaviour)

Values for the UIBackgroundModes array

Value : voip Description : The app provides Voice-over-IP services.
  Apps with this key are automatically launched after system boot so
  that the app can reestablish VoIP services. Apps with this key are
  also allowed to play background audio.

https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/iPhoneOSKeys.html#//apple_ref/doc/uid/TP40009252-SW1

I have ensured that :-

The App was running when the device was powered off.

VoIP is present in the plist and Capabilities section.

Ensured that app the certainly not launched after device reboot by adding logs to a file in the main method and the application:didFinishLaunchingWithOptions: method.

Screen of the device is unlocked at least once, after the device has been rebooted.

I even tried executing this GitHub example App with 36 stars to test
  Boot Launch. https://github.com/lithium3141/BootLaunch

  But even this App does not restart on reboot when I tried on device.

Hence, this leads me to think if something has been changed recently in iOS10 or am I still missing something here?

答:
App will invoke in background when it is in terminated mode only with push kit silent notification and certificates has to be generate for push kit, not with normal APNS notification and normal push notification certificates.

From back end, your payload has to be like this.

```<code>$body['aps'] = array(
'content-available'=> 1,
'alert' => $message,
'sound' => 'default',
'badge' => 0,
);
</code>```

Once you get pushkit payload, then schedule local notification with sound file, your app will be invoked in background upto your sound file plays.( Max 30 seconds ) Til then you have to complete your background task.

Kindly do refer some important details about push kit integration step by step process

https://github.com/hasyapanchasara/PushKit_SilentPushNotification

Life cycle of app - when app is in terminated and push kit payload comes

First of all

didFinishLaunchingWithOptions // will invoke

Then

didReceiveIncomingPushWithPayload // payload method gets invoke

Then if you have local notification

didReceiveLocalNotification  // receive local notification

Then

handleActionWithIdentifier // handler method if you have action buttons ( local )

Then if you have remote notification

didReceiveRemoteNotification // receive remote notification

Then

handleActionWithIdentifier // handler method if you have action buttons ( remote )

Note - Without tapping on app icon or receiving push kit payload, your app will never gets revoke/open/repoen automatically. If you want your app is VOIP based and app gets revoke after device reboot. Not possible.

Body:
App will invoke in background when it is in terminated mode only with push kit silent notification and certificates has to be generate for push kit, not with normal APNS notification and normal push notification certificates.

From back end, your payload has to be like this.

$body['aps'] = array(
'content-available'=> 1,
'alert' => $message,
'sound' => 'default',
'badge' => 0,
);

Once you get pushkit payload, then schedule local notification with sound file, your app will be invoked in background upto your sound file plays.( Max 30 seconds ) Til then you have to complete your background task.

Kindly do refer some important details about push kit integration step by step process

https://github.com/hasyapanchasara/PushKit_SilentPushNotification

Life cycle of app - when app is in terminated and push kit payload comes

First of all

didFinishLaunchingWithOptions // will invoke

Then

didReceiveIncomingPushWithPayload // payload method gets invoke

Then if you have local notification

didReceiveLocalNotification  // receive local notification

Then

handleActionWithIdentifier // handler method if you have action buttons ( local )

Then if you have remote notification

didReceiveRemoteNotification // receive remote notification

Then

handleActionWithIdentifier // handler method if you have action buttons ( remote )

Note - Without tapping on app icon or receiving push kit payload, your app will never gets revoke/open/repoen automatically. If you want your app is VOIP based and app gets revoke after device reboot. Not possible.


问:
parallelize data processing on multiple cores using pthreads
My goal is to process data on multiple cores by using multiple worker threads, and then further process the results in a master thread. I'm working on linux and I'd like to use pthreads. I'm created a simple example to learn how to do this properly. I have one main thread named "callback" and 4 worker threads. The idea is that the main thread signals the worker threads to start processing, and the 4 threads then signal the main thread when they are done, and the main thread quits after it has been notified by all 4 threads that they are done. I want the 4 worker threads to be able to run in parallel, so I don't want any of those threads waiting for the others. In my example I've tried to just let each of the threads sleep for a different duration (1, 2, 3 and 4 seconds), with the idea that the code would exit after 4 seconds (i.e. when worker thread 4 has done waiting 4 seconds).

For some reason, my code is incorrect, and it always exits immediately, printing this:

```<code>thread 3 start (sleeping 3000 ms)
thread 2 start (sleeping 2000 ms)
thread 1 start (sleeping 1000 ms)
thread 4 start (sleeping 4000 ms)
    thread 1 stop
    thread 2 stop
    thread 3 stop
    thread 4 stop
Main(): Waited on 5  threads. Done.
</code>```

So the threads do seem to exit in the correct order but the program doesn't take 4 seconds to run.

What is going on here? I've pasted the code below

```<code>#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

// based on https://computing.llnl.gov/tutorials/pthreads/#ConditionVariables

#define DUR 1000
#define NUM_THREADS 5
int state = 0;

pthread_mutex_t mutex;
pthread_cond_t conddone;
pthread_cond_t condwork;

void* callback(void* t) {

    // signal worker threads to start work

        pthread_mutex_lock(&mutex);
        pthread_cond_broadcast(&condwork);
        pthread_mutex_unlock(&mutex);

    // wait for worker threads to finish

        pthread_mutex_lock(&mutex);
        while (state < 4)
            pthread_cond_wait(&conddone, &mutex);
        pthread_mutex_unlock(&mutex);

   pthread_exit(NULL);

}

void* worker(void* t) {

   long id = (long)t;

    // wait for signal from callback to start doing work

    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&condwork, &mutex);
    pthread_mutex_unlock(&mutex);

    // do work

    printf("thread %d start (sleeping %d ms)\n", id, id * DUR);
    usleep(id * DUR);
    printf("    thread %d stop\n", id);

    // tell callback we're done

    pthread_mutex_lock(&mutex);
    state++;
    pthread_cond_signal(&conddone);
    pthread_mutex_unlock(&mutex);

   pthread_exit(NULL);

}

int main (int argc, char *argv[])
{
   int i, rc;

   pthread_t threads[5];
   pthread_attr_t attr;

   pthread_mutex_init(&mutex, NULL);
   pthread_cond_init (&condwork, NULL);
   pthread_cond_init (&conddone, NULL);

   pthread_attr_init(&attr);
   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

   pthread_create(&threads[0], &attr, callback, (void *)0);
   pthread_create(&threads[1], &attr, worker, (void *)1);
   pthread_create(&threads[2], &attr, worker, (void *)2);
   pthread_create(&threads[3], &attr, worker, (void *)3);
   pthread_create(&threads[4], &attr, worker, (void *)4);

   for (i=0; i<NUM_THREADS; i++) {
     pthread_join(threads[i], NULL);
   }
   printf ("Main(): Waited on %d  threads. Done.\n", NUM_THREADS);

   pthread_attr_destroy(&attr);
   pthread_mutex_destroy(&mutex);
   pthread_cond_destroy(&condwork);
   pthread_cond_destroy(&conddone);
   pthread_exit(NULL);
}
</code>```

答:
Your immediate problem is just that usleep() sleeps for microseconds not milliseconds so your threads are sleeping for a thousandth of the time that you intend them to.

You do have another problem, though: your condwork condition variable is not paired with a predicate over shared state (eg the predicate state < 4 for the conddone variable).  If one of your worker threads executes the pthread_cond_wait() after the "callback" thread has executed the pthread_cond_broadcast(), the worker will wait indefinitely.

You could fix this by initialising the state variable to -1:

```<code>int state = -1;
</code>```

and having your workers wait on the predicate state < 0:

```<code>// wait for signal from callback to start doing work

pthread_mutex_lock(&mutex);
while (state < 0)
    pthread_cond_wait(&condwork, &mutex);
pthread_mutex_unlock(&mutex);
</code>```

and having the "callback" signal the workers by setting state to 0:

```<code>// signal worker threads to start work

pthread_mutex_lock(&mutex);
state = 0;
pthread_cond_broadcast(&condwork);
pthread_mutex_unlock(&mutex);
</code>```

Body:
My goal is to process data on multiple cores by using multiple worker threads, and then further process the results in a master thread. I'm working on linux and I'd like to use pthreads. I'm created a simple example to learn how to do this properly. I have one main thread named "callback" and 4 worker threads. The idea is that the main thread signals the worker threads to start processing, and the 4 threads then signal the main thread when they are done, and the main thread quits after it has been notified by all 4 threads that they are done. I want the 4 worker threads to be able to run in parallel, so I don't want any of those threads waiting for the others. In my example I've tried to just let each of the threads sleep for a different duration (1, 2, 3 and 4 seconds), with the idea that the code would exit after 4 seconds (i.e. when worker thread 4 has done waiting 4 seconds).

For some reason, my code is incorrect, and it always exits immediately, printing this:

thread 3 start (sleeping 3000 ms)
thread 2 start (sleeping 2000 ms)
thread 1 start (sleeping 1000 ms)
thread 4 start (sleeping 4000 ms)
    thread 1 stop
    thread 2 stop
    thread 3 stop
    thread 4 stop
Main(): Waited on 5  threads. Done.

So the threads do seem to exit in the correct order but the program doesn't take 4 seconds to run.

What is going on here? I've pasted the code below

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

// based on https://computing.llnl.gov/tutorials/pthreads/#ConditionVariables

#define DUR 1000
#define NUM_THREADS 5
int state = 0;

pthread_mutex_t mutex;
pthread_cond_t conddone;
pthread_cond_t condwork;

void* callback(void* t) {

    // signal worker threads to start work

        pthread_mutex_lock(&mutex);
        pthread_cond_broadcast(&condwork);
        pthread_mutex_unlock(&mutex);

    // wait for worker threads to finish

        pthread_mutex_lock(&mutex);
        while (state < 4)
            pthread_cond_wait(&conddone, &mutex);
        pthread_mutex_unlock(&mutex);

   pthread_exit(NULL);

}

void* worker(void* t) {

   long id = (long)t;

    // wait for signal from callback to start doing work

    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&condwork, &mutex);
    pthread_mutex_unlock(&mutex);

    // do work

    printf("thread %d start (sleeping %d ms)\n", id, id * DUR);
    usleep(id * DUR);
    printf("    thread %d stop\n", id);

    // tell callback we're done

    pthread_mutex_lock(&mutex);
    state++;
    pthread_cond_signal(&conddone);
    pthread_mutex_unlock(&mutex);

   pthread_exit(NULL);

}

int main (int argc, char *argv[])
{
   int i, rc;

   pthread_t threads[5];
   pthread_attr_t attr;

   pthread_mutex_init(&mutex, NULL);
   pthread_cond_init (&condwork, NULL);
   pthread_cond_init (&conddone, NULL);

   pthread_attr_init(&attr);
   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

   pthread_create(&threads[0], &attr, callback, (void *)0);
   pthread_create(&threads[1], &attr, worker, (void *)1);
   pthread_create(&threads[2], &attr, worker, (void *)2);
   pthread_create(&threads[3], &attr, worker, (void *)3);
   pthread_create(&threads[4], &attr, worker, (void *)4);

   for (i=0; i<NUM_THREADS; i++) {
     pthread_join(threads[i], NULL);
   }
   printf ("Main(): Waited on %d  threads. Done.\n", NUM_THREADS);

   pthread_attr_destroy(&attr);
   pthread_mutex_destroy(&mutex);
   pthread_cond_destroy(&condwork);
   pthread_cond_destroy(&conddone);
   pthread_exit(NULL);
}

Body:
Your immediate problem is just that usleep() sleeps for microseconds not milliseconds so your threads are sleeping for a thousandth of the time that you intend them to.

You do have another problem, though: your condwork condition variable is not paired with a predicate over shared state (eg the predicate state < 4 for the conddone variable).  If one of your worker threads executes the pthread_cond_wait() after the "callback" thread has executed the pthread_cond_broadcast(), the worker will wait indefinitely.

You could fix this by initialising the state variable to -1:

int state = -1;

and having your workers wait on the predicate state < 0:

// wait for signal from callback to start doing work

pthread_mutex_lock(&mutex);
while (state < 0)
    pthread_cond_wait(&condwork, &mutex);
pthread_mutex_unlock(&mutex);

and having the "callback" signal the workers by setting state to 0:

// signal worker threads to start work

pthread_mutex_lock(&mutex);
state = 0;
pthread_cond_broadcast(&condwork);
pthread_mutex_unlock(&mutex);


答:
You have got few issues with your checkValidity() method as explained below:

(1) Your Scanner object scope exists only inside main method, so pass that object to checkValidity method

(2) Validate the inputs inside checkValidity method

(3) Your checkValidity method has got return type of boolean, so you need to return a boolean value from it i.e., if validation is successful, return true or if validation fails, return false

You refer the below code with inline comments:

```<code>public static boolean checkValidity(Scanner inputFile) {
        String line = inputFile.nextLine();
        double numberOfShares = inputFile.nextDouble();
        double buyPricePerShare = inputFile.nextDouble();
        double buyComissionRate = inputFile.nextDouble();
        double sellPricePerShare = inputFile.nextDouble();
        double sellComissionRate = inputFile.nextDouble();
        boolean validationSuccess = false;
        //validate your inputs
        // If validations are successful  then set validationSuccess = true;
        return validationSuccess;//return boolean
    }
</code>```

Also, pass the scanner object from main() as shown below:

```<code>while (inputFile.hasNext()) {
     checkValidity(inputFile);//pass scanner object
}
</code>```

Title: Getting "cannot find symbol" error in Java

Body:
I am writing some code to read static stock numbers from a text pad. I ran it to see what was wrong and I cannot seem to fix this cannot find symbol error.

import java.io.*;
import java.util.*;

public class StockMarket
{
    public static void main(String[] args) throws IOException
    {

        Scanner keyboard = new Scanner(System.in);

        System.out.println("Enter the filename: ");
        String filename = keyboard.nextLine();

        File file = new File(filename);
        Scanner inputFile = new Scanner(file);

        while (inputFile.hasNext())
        {
            checkValidity();
        }

        inputFile.close();

    }

    public static boolean checkValidity()
    {

    String line = inputFile.nextLine();
    double numberOfShares = inputFile.nextDouble();
    double buyPricePerShare = inputFile.nextDouble();
    double buyComissionRate = inputFile.nextDouble();
    double sellPricePerShare = inputFile.nextDouble();
    double sellComissionRate = inputFile.nextDouble();

    }

}

Body:
You have got few issues with your checkValidity() method as explained below:

(1) Your Scanner object scope exists only inside main method, so pass that object to checkValidity method

(2) Validate the inputs inside checkValidity method

(3) Your checkValidity method has got return type of boolean, so you need to return a boolean value from it i.e., if validation is successful, return true or if validation fails, return false

You refer the below code with inline comments:

public static boolean checkValidity(Scanner inputFile) {
        String line = inputFile.nextLine();
        double numberOfShares = inputFile.nextDouble();
        double buyPricePerShare = inputFile.nextDouble();
        double buyComissionRate = inputFile.nextDouble();
        double sellPricePerShare = inputFile.nextDouble();
        double sellComissionRate = inputFile.nextDouble();
        boolean validationSuccess = false;
        //validate your inputs
        // If validations are successful  then set validationSuccess = true;
        return validationSuccess;//return boolean
    }

Also, pass the scanner object from main() as shown below:

while (inputFile.hasNext()) {
     checkValidity(inputFile);//pass scanner object
}


问:
Microsoft Azure Active Directory: Expand manager NullReferenceException
Microsoft Azure Active Directory 2.1.1 graph client has a bug:
In Azure AD we have user without manager.
When do batch requests to get specific users and expand manager we get Object null reference exception during response deserialization in case where no manager set:

    at Microsoft.Azure.ActiveDirectory.GraphClient.Internal.DirectoryObject.set_manager(DirectoryObject value)
    at lambda_method(Closure , Object , Object )
    at System.Data.Services.Client.Metadata.ClientPropertyAnnotation.SetValue(Object instance, Object value, String propertyName, Boolean allowAdd)
   at System.Data.Services.Client.Materialization.EntryValueMaterializationPolicy.MaterializeResolvedEntry(MaterializerEntry entry, Boolean includeLinks)
   ....

Seems this graph client is not open source we cannot fix that directly.

The code cause the problem:

```<code>//No manager for this user.
var query1 = activeDirectoryClient.Users.Where(t => t.ObjectId == "id1")
.Expand(t=>t.Manager);
var query2 = activeDirectoryClient.Users.Where(t => t.ObjectId == "id2")
.Expand(t => t.Manager);
var query3 = activeDirectoryClient.Users.Where(t => t.ObjectId == "id3")
.Expand(t=>t.Manager);
var query4 = activeDirectoryClient.Users.Where(t => t.ObjectId == "id4")
.Expand(t=>t.Manager);
// this line will throw exception.
var result = await activeDirectoryClient.Context.ExecuteBatchAsync(query1, query2, query3, query4);
</code>```

Because ExecuteBatchAsync gets OperationResopnce and create pagedcollection for each response but initialization of this collection is not lazy.
so if some error in one collection all responces will be blocked

Does anyone know how to workaround this?

答:
To get the manager of user via Microsoft Graph, you can refer the code below:

```<code>var manager = (Microsoft.Graph.User)graphserviceClient.Me.Manager.Request().GetAsync().Result;
</code>```

And if there is no manager for the user, this library also throw the exception. We need to catch and handle the exception. For example, the code below prints the user's manager and if no manger just print the message like user has no manager:

```<code>var accessToken = "";
var graphserviceClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
(requestMessage) =>
{
   requestMessage.Headers.Authorization = new  AuthenticationHeaderValue("bearer", accessToken);
   return Task.FromResult(0);
}));

string[] userIds = { "fe989a2b-81d1-48ca-aa15-0ac52688f65b", "c2ca48ba-1608-4254-b377-ba514276fe75" };
foreach(var id in userIds)
{
    try
    {
        var manager = (Microsoft.Graph.User)graphserviceClient.Users[id].Manager.Request().GetAsync().Result;
        Console.WriteLine($"user {id}'s manager is {manager.DisplayName}!");
    }
    catch(Exception ex) {

        Console.WriteLine($"user {id} has no manager!");
    }
}
</code>```

Body:
Microsoft Azure Active Directory 2.1.1 graph client has a bug:
In Azure AD we have user without manager.
When do batch requests to get specific users and expand manager we get Object null reference exception during response deserialization in case where no manager set:

    at Microsoft.Azure.ActiveDirectory.GraphClient.Internal.DirectoryObject.set_manager(DirectoryObject value)
    at lambda_method(Closure , Object , Object )
    at System.Data.Services.Client.Metadata.ClientPropertyAnnotation.SetValue(Object instance, Object value, String propertyName, Boolean allowAdd)
   at System.Data.Services.Client.Materialization.EntryValueMaterializationPolicy.MaterializeResolvedEntry(MaterializerEntry entry, Boolean includeLinks)
   ....

Seems this graph client is not open source we cannot fix that directly.

The code cause the problem:

//No manager for this user.
var query1 = activeDirectoryClient.Users.Where(t => t.ObjectId == "id1")
.Expand(t=>t.Manager);
var query2 = activeDirectoryClient.Users.Where(t => t.ObjectId == "id2")
.Expand(t => t.Manager);
var query3 = activeDirectoryClient.Users.Where(t => t.ObjectId == "id3")
.Expand(t=>t.Manager);
var query4 = activeDirectoryClient.Users.Where(t => t.ObjectId == "id4")
.Expand(t=>t.Manager);
// this line will throw exception.
var result = await activeDirectoryClient.Context.ExecuteBatchAsync(query1, query2, query3, query4);

Because ExecuteBatchAsync gets OperationResopnce and create pagedcollection for each response but initialization of this collection is not lazy.
so if some error in one collection all responces will be blocked

Does anyone know how to workaround this?

Body:
To get the manager of user via Microsoft Graph, you can refer the code below:

var manager = (Microsoft.Graph.User)graphserviceClient.Me.Manager.Request().GetAsync().Result;

And if there is no manager for the user, this library also throw the exception. We need to catch and handle the exception. For example, the code below prints the user's manager and if no manger just print the message like user has no manager:

var accessToken = "";
var graphserviceClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
(requestMessage) =>
{
   requestMessage.Headers.Authorization = new  AuthenticationHeaderValue("bearer", accessToken);
   return Task.FromResult(0);
}));

string[] userIds = { "fe989a2b-81d1-48ca-aa15-0ac52688f65b", "c2ca48ba-1608-4254-b377-ba514276fe75" };
foreach(var id in userIds)
{
    try
    {
        var manager = (Microsoft.Graph.User)graphserviceClient.Users[id].Manager.Request().GetAsync().Result;
        Console.WriteLine($"user {id}'s manager is {manager.DisplayName}!");
    }
    catch(Exception ex) {

        Console.WriteLine($"user {id} has no manager!");
    }
}


问:
How to connect local machine with Docker Container?
I'm trying to use kafka on my local computer (Windows 10) as producer and a spark streaming on a docker container (ubuntu) as a consumer. My examples work together in the container but i need to create the stream on my local computer.

I'm running zookeeper at port 2181 in the host (local computer) and kafka server at 9092.

And i start a broker at 9092 to create the stream (local computer)

producer = KafkaProducer(bootstrap_servers='localhost:9092')
while True:
    message='Hola'
    producer.send(1,'test', message)
    time.sleep(1)

On the other side in the container i'm listen to port 2181 to recieve the stream.

```<code>ssc = StreamingContext(sc, 5)
</code>```

kvs = KafkaUtils.createStream(ssc, "127.0.0.1:2181", "spark-streaming-consumer", {'test': 1})

The problem is that i don't know how to link both (Windows Kafka and Ubuntu)

I hope you can help me.
Thanks.

答:
while starting the docker container expose port 8080 to 8080 and 7077 to 7077 , which can be done by providing -p 8080:8080 -p 7070:7070 in docker run command.

Then In kafka you can configure using localhost or 127.0.0.1

Body:
I'm trying to use kafka on my local computer (Windows 10) as producer and a spark streaming on a docker container (ubuntu) as a consumer. My examples work together in the container but i need to create the stream on my local computer.

I'm running zookeeper at port 2181 in the host (local computer) and kafka server at 9092.

And i start a broker at 9092 to create the stream (local computer)

producer = KafkaProducer(bootstrap_servers='localhost:9092')
while True:
    message='Hola'
    producer.send(1,'test', message)
    time.sleep(1)

On the other side in the container i'm listen to port 2181 to recieve the stream.

ssc = StreamingContext(sc, 5)

kvs = KafkaUtils.createStream(ssc, "127.0.0.1:2181", "spark-streaming-consumer", {'test': 1})

The problem is that i don't know how to link both (Windows Kafka and Ubuntu)

I hope you can help me.
Thanks.


答:
For more controls about how your text should be use np.savetxt with additional parameters as required:

```<code>arr = np.ones((3, 3))
with open("test.txt" , 'wb') as f:
    np.savetxt(f, arr, delimiter=' ', newline='\n', header='', footer='', comments='# ')
</code>```

Title: saving numpy array to a file without brackets and white spaces

Body:
I have been trying to save numpy array to a file without brackets and white spaces at the beginning of each line. Unfortunately the last one does not work.
Array:

[[ 6.         -2.86751284 -0.35808319  1.79360812]
 [ 6.         -1.59351284 -0.02808319 -0.47039188]
 [ 6.          0.51848716  0.21791681  0.17060812]
 [ 6.         -1.63251284 -0.12208319  0.90460812]
 [ 6.         -0.26051284  0.03991681  1.33660812]
 [ 6.          1.87948716  0.43391681  0.21960812]
 [ 6.          2.52048716  0.45191681  1.44760812]
 [ 6.          0.40448716  0.04591681  2.58360812]
 [ 6.          1.81248716  0.30391681  2.62260812]]

Code:

f = open('result.txt','a')
f.write(str(geometry.shape[0]))
f.write(re.sub('[\[\]]', '', np.array_str(geometry))).lstrip()
f.write('\n')
f.close()

How can I fix it up?

Body:
For more controls about how your text should be use np.savetxt with additional parameters as required:

arr = np.ones((3, 3))
with open("test.txt" , 'wb') as f:
    np.savetxt(f, arr, delimiter=' ', newline='\n', header='', footer='', comments='# ')


问:
How to get child-index of element in prototype
If I have a structure like this:

```<code><ul>
   <li class="golden-delicious">Golden Delicious</li>
   <li class="mutsu">Mutsu</li>
   <li class="mcintosh">McIntosh</li>
   <li class="ida-red">Ida Red</li>
</ul>
</code>```

and a selector

```<code>$$('li.mutsu')[0]
</code>```

that returns an element, how can I get the index of this element within its parent child collection? I need the index value "1" of li.mutsu.

答: You could use .previousSiblings().size()

ContentLicense: CC BY-SA 2.5

Body:
If I have a structure like this:

Golden Delicious

Mutsu

McIntosh

Ida Red

and a selector

$$('li.mutsu')[0]

that returns an element, how can I get the index of this element within its parent child collection? I need the index value "1" of li.mutsu.