问:
How to use an object, save the value into an arrayList, and reuse the same object to keep getting user input
I am trying to create a SavingsAccount object and then use a method create account to take user inputs (account name, account number, and starting balance) and then store that information into an arrayList to access later.

I was thinking that I could just have one instance of the object (Savings account) save the data into the arrayList and then reuse the object so that I do not have multiple objects ( was thinking this would be more memory efficient).

I am new to Java, and this is homework, I have posted my code below that I have so far.  I also am not exactly sure how I should be using the toString method in order to later print out a list of all the accounts that have been created.

The main problem I am having is how to store the objects data into the arrayList I know to use the .add() however, it seems to be overwriting all the information stored into the array with the last value entered.  So I unsure how to do this, I have read many posts here that are on the same topic or something similar and still do not understand the correct way to do this.

I would welcome any guidance or advice, thank you for taking the time to read my post.

```<code>   package bankingSystem;

/**
 *
 * @author xxxx
 *
 */
public class SavingsAccount {
    private String accountNumber;
    private String accountName;
    private double accountBalance;

    /**
     * Constructor to create a new savings account object that takes in a new
       account number and a new account name
     * @param newAccountNumber
     * @param newAccountName
     */
    public SavingsAccount(String newAccountNumber, String newAccountName){
    this.accountNumber = newAccountNumber;
    this.accountName = newAccountName;
    this.accountBalance = 0;
    }

    /**
     * Creates a new savings account with passed in data of new account name,
       number, and starting balance.
     * @param newAccountNumber
     * @param newAccountName
     * @param startingAccountBalance
     * @return true always as the information is stored in an arrayList and
       will not fill up.
     */
    public SavingsAccount(String newAccountNumber, String newAccountName,
    double startingAccountBalance){
        this.accountNumber = newAccountNumber;
        this.accountName = newAccountName;
        this.accountBalance = startingAccountBalance;
    }

    /**
     * Gets the banking account number
     * @return the bank account number
     */
    public String getAccountNumber(){
        return accountNumber;
    }

    /**
     * Gets the requested account name
     * @return
     */
    public String getAccountName(){
        return accountName;
    }

    /**
     * Gets the requsted account balance
     * @return the account balace;
     */
    public double getAccountBalance(){
        return accountBalance;
    }

    /**
     * Changes a bank account name.
     * @param updateAccountName
     * @return the updated value for accountName
     */
    public String setAccountName(String updateAccountName){
        accountName = updateAccountName;
        return accountName;
    }

    /**
     * Deposit funds into account.
     * @param depositAmount
     * @return true, as this would always be true for a realistic amount.
     */
    public boolean deposit(double depositAmount){
        accountBalance += depositAmount;
        return true;
    }

    /**
     * withdraws the specified amount of funds from the account.
     * @param withdrawlAmount
     * @return true if successful, else return false if there is an ISF
     transaction.
     */
    public boolean withdrawl(double withdrawlAmount){
        if(accountBalance - withdrawlAmount < 0){
            return false;
        }else{
            accountBalance -= withdrawlAmount;
            return true;
        }
    }

    @Override
    public String toString(){
        StringBuilder results = new StringBuilder();
        results.append("The account number is " + accountNumber + " The
    account name is " + accountName + " The account balance is " +
    accountBalance + "\n");
        return results.toString();
    }
}

package bankingSystem;
import java.util.Scanner;
import java.util.ArrayList;

/**
 *
 * @author xxxx
 *
 */
public class BankingSystem {

public static void main(String[] args) {
    ArrayList<SavingsAccount> arrayOfSavingsAccounts = new   \
ArrayList<SavingsAccount>();
    int totalNumberOfAccounts = 0;
    Scanner input = new Scanner(System.in);
    int menuSelection = 0;
    do{
        System.out.println("\nPlease select from the following options: \n1.
Create a new account\t\t\t2.  Deposit funds\n3.  Withdrawl funds\t\t\t\t4.
Transfer funds between accounts\n5.  Display all accounts\t\t\t6.  Exit
Program\n");
        if (input.hasNextInt()){
            int temp = input.nextInt();  //used a temp variable to compare the
if statement below
            if (temp > 0 && temp < 7){
                menuSelection = temp;
            }else{
                System.err.println("INVALID ENTRY, Please try again");
            }
        }else{
            System.err.println("INVALID ENTRY, Please try again");
        }
        input.nextLine();  //used this to clear the value being held in
scanner
    }
    while (menuSelection < 1 || menuSelection > 6);
    switch (menuSelection){
        case 1:  System.out.println("\t\t\t\tCREATE NEW ACCOUNT:\nPlease enter
the account holders name: \n");
            String AccountName = input.nextLine();
            System.out.println("Please enter an account number: ");
            String AccountNumber = input.nextLine();
            if (totalNumberOfAccounts == 0){
                //search for duplicate account number
            }
            System.out.println("Please enter starting account balance e.g.
2500.50 :");
            double startingAccountBalance = input.nextDouble();
            SavingsAccount createSavingsAccount = new
SavingsAccount(AccountNumber, AccountName, startingAccountBalance);
            arrayOfSavingsAccounts.add(createSavingsAccount);
            SavingsAccount createSavingsAccount = new
    }
}
</code>```

}

答:
Have you thought about just creating  an array of SavingAccounts with a fixed number of accounts?
SavingAccounts[] savingArray;
savingsArray = new SavingAccounts[10];</p>

Body:
I am trying to create a SavingsAccount object and then use a method create account to take user inputs (account name, account number, and starting balance) and then store that information into an arrayList to access later.

I was thinking that I could just have one instance of the object (Savings account) save the data into the arrayList and then reuse the object so that I do not have multiple objects ( was thinking this would be more memory efficient).

I am new to Java, and this is homework, I have posted my code below that I have so far.  I also am not exactly sure how I should be using the toString method in order to later print out a list of all the accounts that have been created.

The main problem I am having is how to store the objects data into the arrayList I know to use the .add() however, it seems to be overwriting all the information stored into the array with the last value entered.  So I unsure how to do this, I have read many posts here that are on the same topic or something similar and still do not understand the correct way to do this.

I would welcome any guidance or advice, thank you for taking the time to read my post.

   package bankingSystem;

/**
 *
 * @author xxxx
 *
 */
public class SavingsAccount {
    private String accountNumber;
    private String accountName;
    private double accountBalance;

    /**
     * Constructor to create a new savings account object that takes in a new
       account number and a new account name
     * @param newAccountNumber
     * @param newAccountName
     */
    public SavingsAccount(String newAccountNumber, String newAccountName){
    this.accountNumber = newAccountNumber;
    this.accountName = newAccountName;
    this.accountBalance = 0;
    }

    /**
     * Creates a new savings account with passed in data of new account name,
       number, and starting balance.
     * @param newAccountNumber
     * @param newAccountName
     * @param startingAccountBalance
     * @return true always as the information is stored in an arrayList and
       will not fill up.
     */
    public SavingsAccount(String newAccountNumber, String newAccountName,
    double startingAccountBalance){
        this.accountNumber = newAccountNumber;
        this.accountName = newAccountName;
        this.accountBalance = startingAccountBalance;
    }

    /**
     * Gets the banking account number
     * @return the bank account number
     */
    public String getAccountNumber(){
        return accountNumber;
    }

    /**
     * Gets the requested account name
     * @return
     */
    public String getAccountName(){
        return accountName;
    }

    /**
     * Gets the requsted account balance
     * @return the account balace;
     */
    public double getAccountBalance(){
        return accountBalance;
    }

    /**
     * Changes a bank account name.
     * @param updateAccountName
     * @return the updated value for accountName
     */
    public String setAccountName(String updateAccountName){
        accountName = updateAccountName;
        return accountName;
    }

    /**
     * Deposit funds into account.
     * @param depositAmount
     * @return true, as this would always be true for a realistic amount.
     */
    public boolean deposit(double depositAmount){
        accountBalance += depositAmount;
        return true;
    }

    /**
     * withdraws the specified amount of funds from the account.
     * @param withdrawlAmount
     * @return true if successful, else return false if there is an ISF
     transaction.
     */
    public boolean withdrawl(double withdrawlAmount){
        if(accountBalance - withdrawlAmount < 0){
            return false;
        }else{
            accountBalance -= withdrawlAmount;
            return true;
        }
    }

    @Override
    public String toString(){
        StringBuilder results = new StringBuilder();
        results.append("The account number is " + accountNumber + " The
    account name is " + accountName + " The account balance is " +
    accountBalance + "\n");
        return results.toString();
    }
}

package bankingSystem;
import java.util.Scanner;
import java.util.ArrayList;

/**
 *
 * @author xxxx
 *
 */
public class BankingSystem {

public static void main(String[] args) {
    ArrayList<SavingsAccount> arrayOfSavingsAccounts = new   \
ArrayList<SavingsAccount>();
    int totalNumberOfAccounts = 0;
    Scanner input = new Scanner(System.in);
    int menuSelection = 0;
    do{
        System.out.println("\nPlease select from the following options: \n1.
Create a new account\t\t\t2.  Deposit funds\n3.  Withdrawl funds\t\t\t\t4.
Transfer funds between accounts\n5.  Display all accounts\t\t\t6.  Exit
Program\n");
        if (input.hasNextInt()){
            int temp = input.nextInt();  //used a temp variable to compare the
if statement below
            if (temp > 0 && temp < 7){
                menuSelection = temp;
            }else{
                System.err.println("INVALID ENTRY, Please try again");
            }
        }else{
            System.err.println("INVALID ENTRY, Please try again");
        }
        input.nextLine();  //used this to clear the value being held in
scanner
    }
    while (menuSelection < 1 || menuSelection > 6);
    switch (menuSelection){
        case 1:  System.out.println("\t\t\t\tCREATE NEW ACCOUNT:\nPlease enter
the account holders name: \n");
            String AccountName = input.nextLine();
            System.out.println("Please enter an account number: ");
            String AccountNumber = input.nextLine();
            if (totalNumberOfAccounts == 0){
                //search for duplicate account number
            }
            System.out.println("Please enter starting account balance e.g.
2500.50 :");
            double startingAccountBalance = input.nextDouble();
            SavingsAccount createSavingsAccount = new
SavingsAccount(AccountNumber, AccountName, startingAccountBalance);
            arrayOfSavingsAccounts.add(createSavingsAccount);
            SavingsAccount createSavingsAccount = new
    }
}

}


来源: stackexchange

问:
Python: Newspaper Module - Downloading from multiple URLs
I hate to start a new post but I am trying to accomplish the exact thing described in this question: Python: Newspaper Module - Any way to pool getting articles straight from URLs?

In attempting to implement the solution, though, I am getting the following error:

```<code>NameError   Traceback (most recent call last)
<ipython-input-38-2707f1416873> in <module>()
----> 1 sources = [SingleSource(articleURL=u) for u in urls]
      2
      3 newspaper.news_pool.set(sources)
      4 newspaper.news_pool.join()
      5

<ipython-input-38-2707f1416873> in <listcomp>(.0)
----> 1 sources = [SingleSource(articleURL=u) for u in urls]
      2
      3 newspaper.news_pool.set(sources)
      4 newspaper.news_pool.join()
      5

<ipython-input-37-4949a9e51da5> in __init__(self, articleURL)
      1 class SingleSource(newspaper.Source):
      2     def __init__(self, articleURL):
----> 3         super(StubSource, self).__init__("http://localhost")
      4         self.articles = [newspaper.Article(url=url)]

NameError: name 'StubSource' is not defined
</code>```

Would very much appreciate a push in the right direction.

答:
Looks like a typo in the linked answer as StubSource is not defined

```<code>class SingleSource(newspaper.Source):
    def __init__(self, articleURL):
        super(StubSource, self).__init__("http://localhost")
        self.articles = [newspaper.Article(url=url)]
</code>```

It should probably be:

```<code>class SingleSource(newspaper.Source):
    def __init__(self, articleURL):
        super(SingleSource, self).__init__("http://localhost")
        self.articles = [newspaper.Article(url=url)]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I hate to start a new post but I am trying to accomplish the exact thing described in this question: Python: Newspaper Module - Any way to pool getting articles straight from URLs?

In attempting to implement the solution, though, I am getting the following error:

NameError   Traceback (most recent call last)
<ipython-input-38-2707f1416873> in <module>()
----> 1 sources = [SingleSource(articleURL=u) for u in urls]
      2
      3 newspaper.news_pool.set(sources)
      4 newspaper.news_pool.join()
      5

<ipython-input-38-2707f1416873> in <listcomp>(.0)
----> 1 sources = [SingleSource(articleURL=u) for u in urls]
      2
      3 newspaper.news_pool.set(sources)
      4 newspaper.news_pool.join()
      5

<ipython-input-37-4949a9e51da5> in __init__(self, articleURL)
      1 class SingleSource(newspaper.Source):
      2     def __init__(self, articleURL):
----> 3         super(StubSource, self).__init__("http://localhost")
      4         self.articles = [newspaper.Article(url=url)]

NameError: name 'StubSource' is not defined

Would very much appreciate a push in the right direction.

Body:
Looks like a typo in the linked answer as StubSource is not defined

class SingleSource(newspaper.Source):
    def __init__(self, articleURL):
        super(StubSource, self).__init__("http://localhost")
        self.articles = [newspaper.Article(url=url)]

It should probably be:

class SingleSource(newspaper.Source):
    def __init__(self, articleURL):
        super(SingleSource, self).__init__("http://localhost")
        self.articles = [newspaper.Article(url=url)]


问:
How to add html attributes and values for all lines quickly with vim and plugins?
My os:debian8.

```<code>uname -a
Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.39-1+deb8u2 (2017-03-07) x86_64 GNU/Linux
</code>```

Here is my base file.

```<code>home
help
variables
compatibility
modelines
searching
selection
markers
indenting
reformatting
folding
tags
makefiles
mapping
registers
spelling
plugins
etc
</code>```

I want to create a html file as bellow.

```<code><a href="home.html" id="home">home</a>
<a href="help.html" id="help">help</a>
<a href="variables.html" id="variables">variables</a>
<a href="compatibility.html" id="compatibility">compatibility</a>
<a href="modelines.html" id="modelines">modelines</a>
<a href="searching.html" id="searching">searching</a>
<a href="selection.html" id="selection">selection</a>
<a href="markers.html" id="markers">markers</a>
<a href="indenting.html" id="indenting">indenting</a>
<a href="reformatting.html" id="reformatting">reformatting</a>
<a href="folding.html" id="folding">folding</a>
<a href="tags.html" id="tags">tags</a>
<a href="makefiles.html" id="makefiles">makefiles</a>
<a href="mapping.html" id="mapping">mapping</a>
<a href="registers.html" id="registers">registers</a>
<a href="spelling.html" id="spelling">spelling</a>
<a href="plugins.html" id="plugins">plugins</a>
<a href="etc.html" id="etc">etc</a>
</code>```

Every line was added href and id  attributes,whose values are line content pasted .html  and line content itself correspondingly.

How to add html attributes and values for all lines quickly with vim and plugins?

sed,awk,sublime text 3 are all welcomed to solve the problem.

答:
```<code>list=$(cat basefile.txt)
for val in $list
do
   echo "<a href=\""$val".html\" id=\""$val"\">"$val"</a>" >> newfile.html
done
</code>```

Using bash, you can always make a script or type this into the command line.

Body:
My os:debian8.

uname -a
Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.39-1+deb8u2 (2017-03-07) x86_64 GNU/Linux

Here is my base file.

home
help
variables
compatibility
modelines
searching
selection
markers
indenting
reformatting
folding
tags
makefiles
mapping
registers
spelling
plugins
etc

I want to create a html file as bellow.

home
help
variables
compatibility
modelines
searching
selection
markers
indenting
reformatting
folding
tags
makefiles
mapping
registers
spelling
plugins
etc

Every line was added href and id  attributes,whose values are line content pasted .html  and line content itself correspondingly.

How to add html attributes and values for all lines quickly with vim and plugins?

sed,awk,sublime text 3 are all welcomed to solve the problem.

Body:
list=$(cat basefile.txt)
for val in $list
do
   echo "<a href=\""$val".html\" id=\""$val"\">"$val"</a>" >> newfile.html
done

Using bash, you can always make a script or type this into the command line.


问:
Event keypress jquery when match a special character
I'm trying to processing code when user type @ like facebook tag. When user type @abc, then event is processed. This is my code:

```<code>$("#content").keypress(function(e) {
          var tmp = $("#content").val();
          if(tmp =="@")
          {
            console.log("It working");
          }
        });
</code>```

UPDATING

Code like this:

```<code>$("#content").keypress(function(event) {
          var tmp  = $("#content").val();
          if(tmp.indexOf('@') !== -1)
          {
            console.log("It's working");
          }
        });
</code>```

It's working when i'm typing @ with anything charater, but when i type  (space), it also working, i try to stop event when user type (space) after @anything.

答:
Its working fine because the condition is:

```<code>if(tmp == "@")
{
    console.log("It working");
}
</code>```

it match for only @. If you want to match something like @abc or @def combination kind of string then use REGEX

Body:
I'm trying to processing code when user type @ like facebook tag. When user type @abc, then event is processed. This is my code:

$("#content").keypress(function(e) {
          var tmp = $("#content").val();
          if(tmp =="@")
          {
            console.log("It working");
          }
        });

UPDATING

Code like this:

$("#content").keypress(function(event) {
          var tmp  = $("#content").val();
          if(tmp.indexOf('@') !== -1)
          {
            console.log("It's working");
          }
        });

It's working when i'm typing @ with anything charater, but when i type  (space), it also working, i try to stop event when user type (space) after @anything.

Body:
Its working fine because the condition is:

if(tmp == "@")
{
    console.log("It working");
}

it match for only @. If you want to match something like @abc or @def combination kind of string then use REGEX


问:
Use find() in textarea val with HTML characters
I have a textarea that I want to get the value of and then count the number of opening and closing divs. I am having trouble with the rendered HMTL, even though it's all been escaped I still get errors like this: Uncaught Error: Syntax error, unrecognized expression:
This is a test
 when entering
This is a test
 into the textarea.

I would love to be able to keep the HTML tags in the content ie the ability to search for <div as apposed to <div

HTML

```<code><h3>Paste your code in here</h3>
<textarea name="code" id="code" cols="30" rows="10"></textarea>
<p>
    <a href="#" class="test-code-btn">Go for it!</a>
</p>
</code>```

JS

```<code>$('.test-code-btn').on('click', function(){
    function escapeHtml(unsafe) {
        return unsafe
             .replace(/&/g, "&")
             .replace(/</g, "<")
             .replace(/>/g, ">")
             .replace(/"/g, """)
             .replace(/'/g, "'");
    }

    var res = escapeHtml($('#code').val());
    console.log('res = ' + res);

    var openDivs = $(res).find('<div').length;
    var closeDivs = $(res).find('</div').length;

    console.log('openDivs: ' + openDivs + ', closeDivs: ' + closeDivs);
});
</code>```

答:
Here is something that could start you right!

It works in CodePen.

```<code>var openCounter=0;
var closeCounter=0;

var raw = $('#code').val();
for(i=0;i<raw.length;i++){
  if( raw.charAt(i)=="<" ){
    if( raw.charAt(i+1)=="\/" ){
      //console.log("One close tag");
      closeCounter++;
    }else{
      //console.log("One open tag");
      openCounter++;
    }
  }
}
console.log(openCounter+" opening tags and "+closeCounter+" closing tags.");
</code>```

Body:
I have a textarea that I want to get the value of and then count the number of opening and closing divs. I am having trouble with the rendered HMTL, even though it's all been escaped I still get errors like this: Uncaught Error: Syntax error, unrecognized expression:
This is a test
 when entering
This is a test
 into the textarea.

I would love to be able to keep the HTML tags in the content ie the ability to search for <div as apposed to <div

HTML

Paste your code in here

<textarea name="code" id="code" cols="30" rows="10"></textarea>

    Go for it!

JS

$('.test-code-btn').on('click', function(){
    function escapeHtml(unsafe) {
        return unsafe
             .replace(/&/g, "&")
             .replace(/</g, "<")
             .replace(/>/g, ">")
             .replace(/"/g, """)
             .replace(/'/g, "'");
    }

    var res = escapeHtml($('#code').val());
    console.log('res = ' + res);

    var openDivs = $(res).find('<div').length;
    var closeDivs = $(res).find('</div').length;

    console.log('openDivs: ' + openDivs + ', closeDivs: ' + closeDivs);
});

Body:
Here is something that could start you right!

It works in CodePen.

var openCounter=0;
var closeCounter=0;

var raw = $('#code').val();
for(i=0;i<raw.length;i++){
  if( raw.charAt(i)=="<" ){
    if( raw.charAt(i+1)=="\/" ){
      //console.log("One close tag");
      closeCounter++;
    }else{
      //console.log("One open tag");
      openCounter++;
    }
  }
}
console.log(openCounter+" opening tags and "+closeCounter+" closing tags.");


问:
React + Chart.js 2.0: How to put a label inside of a doughnut chart?
I am doing data visualizations with react, react-chartjs-2, and chart.js version 2.2.1. There is a possibly related answer to this question here (look for 17.06.16 update), but I'm not sure what Chart.pluginService.register is or whether it is compatible with React. So far it hasn't worked for me.

I am simply looking to place a label inside the doughnut that is the sum of all data subsets. I assume this is nested somewhere in the doughnut chart's options, but I haven't found it yet.

答:
In react-chartjs-2 you can access the datasets through chart.config.data.datasets.

So for:

```<code>data = {
    labels: [
        'Red',
        'Green',
        'Yellow'
    ],
    datasets: [{
        data: [300, 50, 100],
    ...
</code>```

Inside the draw callback in Chart.helpers.extend you can use:

```<code>var sum = 0;
for (var i = 0; i < this.chart.config.data.datasets[0].data.length; i++) {
   sum += this.chart.config.data.datasets[0].data[i];
}
</code>```

Here's an example Codepen: http://codepen.io/anon/pen/xqMQQB?editors=1010

Body:
In react-chartjs-2 you can access the datasets through chart.config.data.datasets.

So for:

data = {
    labels: [
        'Red',
        'Green',
        'Yellow'
    ],
    datasets: [{
        data: [300, 50, 100],
    ...

Inside the draw callback in Chart.helpers.extend you can use:

var sum = 0;
for (var i = 0; i < this.chart.config.data.datasets[0].data.length; i++) {
   sum += this.chart.config.data.datasets[0].data[i];
}

Here's an example Codepen: http://codepen.io/anon/pen/xqMQQB?editors=1010


问:
Fetch Post not working in redux-saga?
I have the following code by using redux-saga to send a post request:

```<code>import {put, call, fork, takeEvery} from 'redux-saga/effects';
import fetch from 'isomorphic-fetch';
const url = 'xxx/api/posts';

function* addPost(data) {
    try{
        const response = yield fetch(url, {
            method: 'POST',
            headers: {
                'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
                'Content-Type': 'application/json; charset=utf-8'
            },
            body: JSON.stringify(data)
        });
        const id = yield response.json().id;
        yield put({type: types.ADD_POST, payload: {id, title, content }});
    }catch(e) {
        yield put({type: types.ERROR, payload: e});
    }
}
</code>```

But an ajax is sent with the 'OPTION' method, what's wrong with my code? Why it doesn't work?

答:
The server you’re sending the request to must be configured to send an Access-Control-Allow-Headers response header whose value contains Content-Type.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests explains what’s happening here. Your request triggers your browser to send a CORS “preflight”.

The specific reason the browser does the preflight in this case is that the request includes a Content-Type: application/json request header. The CORS protocol requires that if a cross-origin request includes a Content-Type request header with a value other than application/x-www-form-urlencoded,
multipart/form-data,
text/plain, the browser sends an OPTIONS request and then checks the response to that to see if the response includes  an Access-Control-Allow-Headers response header whose value contains Content-Type.

If the browser finds that the response includes a response header that includes that value, then the browser will then proceed to send that actual POST request you’re trying to make with your code. But if the browser instead finds that the response doesn’t include that header, or that the header doesn’t contain Content-Type, then the browser will stop right there and not send the POST.

Title: Fetch Post not working in redux-saga?

Body:
I have the following code by using redux-saga to send a post request:

import {put, call, fork, takeEvery} from 'redux-saga/effects';
import fetch from 'isomorphic-fetch';
const url = 'xxx/api/posts';

function* addPost(data) {
    try{
        const response = yield fetch(url, {
            method: 'POST',
            headers: {
                'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
                'Content-Type': 'application/json; charset=utf-8'
            },
            body: JSON.stringify(data)
        });
        const id = yield response.json().id;
        yield put({type: types.ADD_POST, payload: {id, title, content }});
    }catch(e) {
        yield put({type: types.ERROR, payload: e});
    }
}

But an ajax is sent with the 'OPTION' method, what's wrong with my code? Why it doesn't work?


问:
function return tuple. sometimes get lists, sometimes get tuple
I write a function to return multiple lists(at least one). It is looks like below:

```<code>def get_stock_atrributes_data(stock, attrList):
    dbClient = MongoClient()
    db = dbClient.StockAnnual
    #only query the data we need
    query = {attr: 1 for attr in attrList}
    #exclude id
    query['_id'] = 0
    cursor = db[stock].find({}, query).sort([('date', pymongo.ASCENDING)])
    #tranform cursor to list so it becomes iterative
    l = list(cursor)
    res = []
    for attr in attrList:
        res.append([d[attr] for d in l])
    return tuple(res)
</code>```

In order to do it, I use tuple so I can use

```<code>list1, list2 = get_stock_atrributes_data()
</code>```

to query multiple attributes lists determined by the attrList. When I return multiple lists(more than one), it works quite well. But if I only return one list, the result is a tuple containing one list, for example:

```<code>list1 = get_stock_atrributes_data()
</code>```

The list1 is a tuple rather than a list now. I read some explanation about returning tuples. It is said that the elements in tuple will be unpacked and assigned automatically. For returned tuple with more than one elements, it works. But for tuple only containing one element, the result is not unpacked. I was confused by this and hope someone can give me explanation.

答:
Will the method return only 1 element or 2 elements?  Or is it possible for the method to return X many elements?

You could try setting the result to a variable and then creating a new list of lists:

```<code>results = get_stock_attributes_data()
arranged_results = []
arranged_results = [arranged_results + element for element in results]
</code>```

The + operator in this case performs the append operation, but since append() does not have a return value, it cannot be used here.

This should work with the case in which you are returned a tuple of the form (X,) or the form (X,Y,...).

Body:
I write a function to return multiple lists(at least one). It is looks like below:

def get_stock_atrributes_data(stock, attrList):
    dbClient = MongoClient()
    db = dbClient.StockAnnual
    #only query the data we need
    query = {attr: 1 for attr in attrList}
    #exclude id
    query['_id'] = 0
    cursor = db[stock].find({}, query).sort([('date', pymongo.ASCENDING)])
    #tranform cursor to list so it becomes iterative
    l = list(cursor)
    res = []
    for attr in attrList:
        res.append([d[attr] for d in l])
    return tuple(res)

In order to do it, I use tuple so I can use

list1, list2 = get_stock_atrributes_data()

to query multiple attributes lists determined by the attrList. When I return multiple lists(more than one), it works quite well. But if I only return one list, the result is a tuple containing one list, for example:

list1 = get_stock_atrributes_data()

The list1 is a tuple rather than a list now. I read some explanation about returning tuples. It is said that the elements in tuple will be unpacked and assigned automatically. For returned tuple with more than one elements, it works. But for tuple only containing one element, the result is not unpacked. I was confused by this and hope someone can give me explanation.

Body:
Will the method return only 1 element or 2 elements?  Or is it possible for the method to return X many elements?

You could try setting the result to a variable and then creating a new list of lists:

results = get_stock_attributes_data()
arranged_results = []
arranged_results = [arranged_results + element for element in results]

The + operator in this case performs the append operation, but since append() does not have a return value, it cannot be used here.

This should work with the case in which you are returned a tuple of the form (X,) or the form (X,Y,...).


问:
Adding 1 to elements of an empty list using another list to count up (maybe with += ?)
I'm very new to python and programming, so please keep answers simple if you can.

I'm trying to create a script that will add 1 to elements in an empty list based on an unordered other list. My inputs are shown below as well as my desired output. Since 5 appears twice in the 'data' list, element 5 in 'input' should count up to 2.

Here's the code I tried, with the error it gives:

```<code>input = [0, 0, 0, 0, 0]
data = [5, 1, 2, 5]

input[data] += 1

#desired output: [1, 1, 0, 0, 2]
</code>```

The error this gives:

TypeError: list indices must be integers, not list

I'm confused, because I have a list of integers, but I guess that doesn't count as type 'int'. I searched to try to convert a list to integers, but all the solutions I found result in still having type 'list'. I'm thinking += might not be the right operator to use in this instance, but I'm not sure what else to use.

Edit: Oops, I forgot about lists starting at 0. Thanks for pointing that out, and thanks for all the great answers! Hard to choose just one.

答:
welcome to python!

Your problems arise from a misunderstanding of how indexing works. There are two problems. The first has to do with data types, and is neatly encapsulated in your error message: TypeError: list indices must be integers, not list. Let's break this down a bit:

'Indexing' is what happens when you use square brackets after a list to access a particular element of that list. i.e. if a is a list, a[N] will return the Nth element of a, where N is an integer. You can only access one element at a time when indexing. Python doesn't know what to do if you give it a list, and your error message is basically telling you "You've asked me to index a list with another list, and I don't know how to do that. I only understand integers!".

Because you can only index one value at time, the best way of doing what you're trying to do is with a loop:

```<code>for i in data:
    input[i] += 1
</code>```

How is this different from what you've done? Using a loop goes through each element of data individually, temporarily calls it i, and uses that to index input, and then the += 1 does what you were originally trying to do.

HOWEVER, if you run the loop, you'll get a second error message, because of a different problem. This error will say IndexError: list index out of range, which tells you that you're requesting to access a part of the list that doesn't exist. But why? input has 5 items in it, and you're only asking it for indices between 1 and 5! This error arises because Python's indexing starts at zero, not one. Valid indices of the input list are therefore [0, 1, 2, 3, 4], not [1, 2, 3, 4, 5]. Because your data list contains the number 5, at some point during the loop i = 5, and you're asking to access the sixth element of index (index[5]), which does not exist.

You can get past this either by changing your data list so that it contains valid indices, or adjusting your loop so that:

```<code>for i in data:
    input[i - 1] += 1
</code>```

Hope that helps!

Body:
I'm very new to python and programming, so please keep answers simple if you can.

I'm trying to create a script that will add 1 to elements in an empty list based on an unordered other list. My inputs are shown below as well as my desired output. Since 5 appears twice in the 'data' list, element 5 in 'input' should count up to 2.

Here's the code I tried, with the error it gives:

input = [0, 0, 0, 0, 0]
data = [5, 1, 2, 5]

input[data] += 1

#desired output: [1, 1, 0, 0, 2]

The error this gives:

TypeError: list indices must be integers, not list

I'm confused, because I have a list of integers, but I guess that doesn't count as type 'int'. I searched to try to convert a list to integers, but all the solutions I found result in still having type 'list'. I'm thinking += might not be the right operator to use in this instance, but I'm not sure what else to use.

Edit: Oops, I forgot about lists starting at 0. Thanks for pointing that out, and thanks for all the great answers! Hard to choose just one.

Body:
welcome to python!

Your problems arise from a misunderstanding of how indexing works. There are two problems. The first has to do with data types, and is neatly encapsulated in your error message: TypeError: list indices must be integers, not list. Let's break this down a bit:

'Indexing' is what happens when you use square brackets after a list to access a particular element of that list. i.e. if a is a list, a[N] will return the Nth element of a, where N is an integer. You can only access one element at a time when indexing. Python doesn't know what to do if you give it a list, and your error message is basically telling you "You've asked me to index a list with another list, and I don't know how to do that. I only understand integers!".

Because you can only index one value at time, the best way of doing what you're trying to do is with a loop:

for i in data:
    input[i] += 1

How is this different from what you've done? Using a loop goes through each element of data individually, temporarily calls it i, and uses that to index input, and then the += 1 does what you were originally trying to do.

HOWEVER, if you run the loop, you'll get a second error message, because of a different problem. This error will say IndexError: list index out of range, which tells you that you're requesting to access a part of the list that doesn't exist. But why? input has 5 items in it, and you're only asking it for indices between 1 and 5! This error arises because Python's indexing starts at zero, not one. Valid indices of the input list are therefore [0, 1, 2, 3, 4], not [1, 2, 3, 4, 5]. Because your data list contains the number 5, at some point during the loop i = 5, and you're asking to access the sixth element of index (index[5]), which does not exist.

You can get past this either by changing your data list so that it contains valid indices, or adjusting your loop so that:

for i in data:
    input[i - 1] += 1

Hope that helps!


问:
Why can't I declare a friend through a typedef?
Does anyone know why typedefs of class names don't work like class names for the friend declaration?</p>

```<code>class A
{
public:
};

class B : public A
{
public:
   typedef A SUPERCLASS;
};

typedef A X;

class C
{
public:
   friend class A;             // OK
   friend class X;             // fails
   friend class B::SUPERCLASS; // fails
};
</code>```

答:
A typedef defines a type. Friend decls declare friend classes or functions (substantially scopes), which then have "access" to the non public area of the declaring class...

Primitives, i.E. a float or an int* don't define a scope with code etc.,
they don't "use" the class anyway.

Don't forget, you can also "pack" call conventions, alignment attribs and other compiler specific stuff in a typedef, i.e. multiple vector TYPES implemented by the same class but with distinct alignment attribs. => A type is not a class, but vice versa.

IMHO, declaring a friend typedef can be useful, but when "class typedefs" from anywhere can be set as friend, the friendships can become extremely incomprehensible and therefore error-prone, especially where templates are used excessively.

Invalidating a single typedef can mess up the whole project due to widespread dependencies.
Template friends and the 0x template typedefs are useful, but don't relax the rules of a friend declaration.

I don't know of any proposal concerning friend typedefs.

ContentLicense: CC BY-SA 2.5

Body:
Does anyone know why typedefs of class names don't work like class names for the friend declaration?

class A
{
public:
};

class B : public A
{
public:
   typedef A SUPERCLASS;
};

typedef A X;

class C
{
public:
   friend class A;             // OK
   friend class X;             // fails
   friend class B::SUPERCLASS; // fails
};


问:
How to ping a server only once from within a batch file?
I want to learn how to write batch scripts and tried to create a script which automatically runs this command in the command line once:

```<code>ping www.google.de -t
</code>```

and displays the ping, so it would look like this:

```<code>Reply from XXX.XXX.X.XX: time=30ms
Reply from XXX.XXX.X.XX: time=31ms
Reply from XXX.XXX.X.XX: time=29ms
</code>```

My problem is, that this will result in this when I execute this command as script:

My problem is that it will not execute the ping command at all, but just insert the command unlimited times in the console window as its shown in the screenshot.

I just created a new file, wrote ping www.google.de -t in it, saved it as ping.bat file and executed it with double clicking on it.

So how to write the batch file to start this command only once and display the ping result?

答:
Just
write the command "ping your server IP" without the double quote. save file name as filename.bat and then run the batch file as administrator</p>

Body:
I want to learn how to write batch scripts and tried to create a script which automatically runs this command in the command line once:

ping www.google.de -t

and displays the ping, so it would look like this:

Reply from XXX.XXX.X.XX: time=30ms
Reply from XXX.XXX.X.XX: time=31ms
Reply from XXX.XXX.X.XX: time=29ms

My problem is, that this will result in this when I execute this command as script:

My problem is that it will not execute the ping command at all, but just insert the command unlimited times in the console window as its shown in the screenshot.

I just created a new file, wrote ping www.google.de -t in it, saved it as ping.bat file and executed it with double clicking on it.

So how to write the batch file to start this command only once and display the ping result?


问:
How can i create a Multi-Dimensional array as the following in php?
Hi guys i am  trying to create a multi dimensional array as the format bellow but i am struggling to do so, any help would be appreciated. Thank you.

```<code>    $movies = array();
    $sql = "SELECT u.username AS Username, group_concat(v.title) AS Video_title, group_concat(r.rate) AS Rating
    FROM `rating` AS r
    JOIN `uploads` AS v ON r.video_id = v.vid_id
    JOIN `users` as u ON u.user_id = r.rater_id
    GROUP by Username" ;

    $query = mysqli_query($conn, $sql);

    while($result = mysqli_fetch_assoc($query)){
    $movies[] = $result;
    }

    foreach($movies as $k => $v){
    unset($movies[$k]);
    $movies[$v['Username']] = $v;
    }
    foreach($movies as $k => $v){
    unset($movies[$k]['Username']);
    }

    print_r($movies);
</code>```

This is what i am currently getting:

```<code>     [user1] => Array ( [Video_title] => Snakes on the Plane,
                                         Superman Returns,
                                         The Night Listner,
                                         Lady in the Water,
                                         Just my Luck,
                                         You me and Dupree
                         [Rating] => 3.5,
                                     3.5,
                                     3,
                                     2.5,
                                     3,
                                     2.5
                     ) )
</code>```

But i am aiming to output it in the following format:

```<code> 'user1' =>
          array('Lady in the Water' => 2.5,
                'Snakes on a Plane' => 3.5,
                'Just My Luck' => 3.0,
                'Superman Returns' => 3.5,
                'You, Me and Dupree' => 2.5,
                'The Night Listener' => 3.0
               )
</code>```

答:
Change the following line:

```<code>$movies[$v['Username']] = $v;
</code>```

to

```<code>$movies[$v['Username']][] = $v;
</code>```

and try again. It will create a new array under Username index for each iteration.

Body:
Hi guys i am  trying to create a multi dimensional array as the format bellow but i am struggling to do so, any help would be appreciated. Thank you.

    $movies = array();
    $sql = "SELECT u.username AS Username, group_concat(v.title) AS Video_title, group_concat(r.rate) AS Rating
    FROM `rating` AS r
    JOIN `uploads` AS v ON r.video_id = v.vid_id
    JOIN `users` as u ON u.user_id = r.rater_id
    GROUP by Username" ;

    $query = mysqli_query($conn, $sql);

    while($result = mysqli_fetch_assoc($query)){
    $movies[] = $result;
    }

    foreach($movies as $k => $v){
    unset($movies[$k]);
    $movies[$v['Username']] = $v;
    }
    foreach($movies as $k => $v){
    unset($movies[$k]['Username']);
    }

    print_r($movies);

This is what i am currently getting:

     [user1] => Array ( [Video_title] => Snakes on the Plane,
                                         Superman Returns,
                                         The Night Listner,
                                         Lady in the Water,
                                         Just my Luck,
                                         You me and Dupree
                         [Rating] => 3.5,
                                     3.5,
                                     3,
                                     2.5,
                                     3,
                                     2.5
                     ) )

But i am aiming to output it in the following format:

 'user1' =>
          array('Lady in the Water' => 2.5,
                'Snakes on a Plane' => 3.5,
                'Just My Luck' => 3.0,
                'Superman Returns' => 3.5,
                'You, Me and Dupree' => 2.5,
                'The Night Listener' => 3.0
               )

Body:
Change the following line:

$movies[$v['Username']] = $v;

to

$movies[$v['Username']][] = $v;

and try again. It will create a new array under Username index for each iteration.


问:
Xcode Storyboard Image Sizing
I cannot figure out how the image inside this imageview is behaving the way it is.  It goes out of bounds, and does not scale the way other imageviews do.

Here it is in three different fills: scale to fill, aspect fit, and aspect fill.  None of these sizings are how any other image would be sized.  I've adjusted the imageview with different constraints, no constraints, different alignments, no alignments, etc., but the image doesn't change its behavior at all.

My current Xcode version is Version 8.2.1 (8C1002)

The dimensions of that box are 374 x 266.

The natural size of the image is 320 x 569.

Here is what I'm working with:

Scale to Fill:

Aspect Fit:

Aspect Fill:

答: Looks like constraint of ImageView is not correct. Try to give Width Constraint to 374(or as per ur requirement ) and Height Constraint to 266(or as per ur requirement ), Top or Bottom, Leading or trailing constraint as per the requirement. </p>

Title: Xcode Storyboard Image Sizing


问:
Arrays not equal
I'm trying to load a csv file with d3 and am trying to create a drop-in replacement for the explicit 2D array (named iris_2).  When comparing the two 2D arrays with underscore.js (using _.isEqual), I noticed that they are not equal (check out the Codepen.io code). What's even stranger is that if I use _.isEqual to compare them when inspecting the html page, it says they are equal.

Here's the d3 code:

```<code>var iris = [];
d3.csv("data/iris.csv", function(mydata) {
    mydata.forEach(function(d) {
        d["sepal_length"] = +d["sepal_length"];
        d["sepal_width"] = +d["sepal_width"];
        d["petal_length"] = +d["petal_length"];
        d["petal_width"] = +d["petal_width"];
        iris.push([d["sepal_length"], d["sepal_width"], d["petal_length"], d["petal_width"], d["species"]]);
    });
});
</code>```

Here's the first five data lines of the iris.csv file with the header that I want to read with d3:

```<code>sepal_length,sepal_width,petal_length,petal_width,species
5.1,3.5,1.4,0.2,setosa
4.9,3,1.4,0.2,setosa
4.7,3.2,1.3,0.2,setosa
4.6,3.1,1.5,0.2,setosa
5,3.6,1.4,0.2,setosa
...
</code>```

Here's the first five lines of the "explicit" 2D array:

```<code>var iris_2 = [
  [5.1, 3.5, 1.4, 0.2, 'setosa'],
  [4.9, 3.0, 1.4, 0.2, 'setosa'],
  [4.7, 3.2, 1.3, 0.2, 'setosa'],
  [4.6, 3.1, 1.5, 0.2, 'setosa'],
  [5.0, 3.6, 1.4, 0.2, 'setosa'] ...
</code>```

This is the underscore.js code I was using to compare the two arrays:

```<code>_.isEqual(iris, iris_2);
</code>```

This returns false for the html code (see above Codepen link), but true for the Chrome html inspector console.

答:
d3.csv is asynchronous. This means that, by the time you get to...

```<code>document.getElementById("myValue").innerHTML = _.isEqual( iris, iris_2 );
</code>```

... there is still no iris array (or, more precisely, it's still empty), and the result is false.

However, if you compare the arrays inside the callback, giving time to d3.csv populating your iris array...

```<code>d3.csv("iris.csv", function(mydata) {
    mydata.forEach(function(d) {
        d["sepal_length"] = +d["sepal_length"];
        d["sepal_width"] = +d["sepal_width"];
        d["petal_length"] = +d["petal_length"];
        d["petal_width"] = +d["petal_width"];
        iris.push([d["sepal_length"],
            d["sepal_width"],
            d["petal_length"],
            d["petal_width"],
            d["species"]
        ]);
    });

    var iris_2 = [
        [5.1, 3.5, 1.4, 0.2, 'setosa'],
        ...
    ];

    document.getElementById("myValue").innerHTML = _.isEqual(iris, iris_2);
    //comparing inside the callback

});//callback ends here
</code>```

... you'll see that the result is true.

Actually, "giving time" to d3.csv populating iris array is what explains what you said:

What's even stranger is that if I use _.isEqual to compare them when inspecting the html page, it says they are equal.

That happens because, when you inspect the page, iris array has been already created.

You can check the working code here: https://plnkr.co/edit/24CypznlScazjcqGKsCq?p=preview

Title: Arrays not equal

Body:
I'm trying to load a csv file with d3 and am trying to create a drop-in replacement for the explicit 2D array (named iris_2).  When comparing the two 2D arrays with underscore.js (using _.isEqual), I noticed that they are not equal (check out the Codepen.io code). What's even stranger is that if I use _.isEqual to compare them when inspecting the html page, it says they are equal.

Here's the d3 code:

var iris = [];
d3.csv("data/iris.csv", function(mydata) {
    mydata.forEach(function(d) {
        d["sepal_length"] = +d["sepal_length"];
        d["sepal_width"] = +d["sepal_width"];
        d["petal_length"] = +d["petal_length"];
        d["petal_width"] = +d["petal_width"];
        iris.push([d["sepal_length"], d["sepal_width"], d["petal_length"], d["petal_width"], d["species"]]);
    });
});

Here's the first five data lines of the iris.csv file with the header that I want to read with d3:

sepal_length,sepal_width,petal_length,petal_width,species
5.1,3.5,1.4,0.2,setosa
4.9,3,1.4,0.2,setosa
4.7,3.2,1.3,0.2,setosa
4.6,3.1,1.5,0.2,setosa
5,3.6,1.4,0.2,setosa
...

Here's the first five lines of the "explicit" 2D array:

var iris_2 = [
  [5.1, 3.5, 1.4, 0.2, 'setosa'],
  [4.9, 3.0, 1.4, 0.2, 'setosa'],
  [4.7, 3.2, 1.3, 0.2, 'setosa'],
  [4.6, 3.1, 1.5, 0.2, 'setosa'],
  [5.0, 3.6, 1.4, 0.2, 'setosa'] ...

This is the underscore.js code I was using to compare the two arrays:

_.isEqual(iris, iris_2);

This returns false for the html code (see above Codepen link), but true for the Chrome html inspector console.

Body:
d3.csv is asynchronous. This means that, by the time you get to...

document.getElementById("myValue").innerHTML = _.isEqual( iris, iris_2 );

... there is still no iris array (or, more precisely, it's still empty), and the result is false.

However, if you compare the arrays inside the callback, giving time to d3.csv populating your iris array...

d3.csv("iris.csv", function(mydata) {
    mydata.forEach(function(d) {
        d["sepal_length"] = +d["sepal_length"];
        d["sepal_width"] = +d["sepal_width"];
        d["petal_length"] = +d["petal_length"];
        d["petal_width"] = +d["petal_width"];
        iris.push([d["sepal_length"],
            d["sepal_width"],
            d["petal_length"],
            d["petal_width"],
            d["species"]
        ]);
    });

    var iris_2 = [
        [5.1, 3.5, 1.4, 0.2, 'setosa'],
        ...
    ];

    document.getElementById("myValue").innerHTML = _.isEqual(iris, iris_2);
    //comparing inside the callback

});//callback ends here

... you'll see that the result is true.

Actually, "giving time" to d3.csv populating iris array is what explains what you said:

What's even stranger is that if I use _.isEqual to compare them when inspecting the html page, it says they are equal.

That happens because, when you inspect the page, iris array has been already created.

You can check the working code here: https://plnkr.co/edit/24CypznlScazjcqGKsCq?p=preview


问:
Firebase Admin - Uncaught exception in Firebase Database runloop (4.1.5)
I'm running an app on Firebase Admin. So this code worked the first time I ran it, but after a few weeks I tried it again and I've been getting this error after hours of debugging (RunLoop: Uncaught exception in Firebase Database runloop (4.1.5)). I've seen other ones with the runloop version as (3.0.0), but none of the errors match the one I have.

```<code>        InputStream serviceAccount = getAssets().open("<My JSON file goes here>");
        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
                .setDatabaseUrl("<My Firebase link goes here>")
                .build();

        FirebaseApp defaultApp = FirebaseApp.initializeApp(options);

        database = FirebaseDatabase.getInstance();
        database.setLogLevel(Logger.Level.DEBUG);
        database.getReference().child("test").setValue("test value");
</code>```

For my gradle files, I only have these:

```<code>compile 'com.google.firebase:firebase-admin:4.1.5'
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:design:25.2.0'
testCompile 'junit:junit:4.12'
compile 'com.android.support.constraint:constraint-layout:1.0.0-beta5'
</code>```

And here's more of the stack trace:

```<code>W/System.err: Mon Apr 03 11:39:33 GMT+08:00 2017 [ERROR] RunLoop: Uncaught exception in Firebase Database runloop (4.1.5). Please report to firebase-database-client@google.com
W/System.err: java.lang.NoSuchMethodError: No virtual method object()Lorg/json/JSONWriter; in class Lorg/json/JSONStringer; or its super classes (declaration of 'org.json.JSONStringer' appears in /system/framework/core-libart.jar)
W/System.err:     at com.google.firebase.database.util.JsonMapper.serializeJsonValue(JsonMapper.java:55)
W/System.err:     at com.google.firebase.database.util.JsonMapper.serializeJsonValue(JsonMapper.java:44)
W/System.err:     at com.google.firebase.database.util.JsonMapper.serializeJson(JsonMapper.java:24)
W/System.err:     at com.google.firebase.database.util.GAuthToken.serializeToString(GAuthToken.java:53)
W/System.err:     at com.google.firebase.database.core.JvmAuthTokenProvider.wrapOAuthToken(JvmAuthTokenProvider.java:110)
</code>```

Any ideas what might be wrong?

答: The Firebase Admin SDK is not intended to be run in an Android app.  It's only supported for standalone and server applications.  For Android apps, you're supposed to use the regular Android SDK instead.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm running an app on Firebase Admin. So this code worked the first time I ran it, but after a few weeks I tried it again and I've been getting this error after hours of debugging (RunLoop: Uncaught exception in Firebase Database runloop (4.1.5)). I've seen other ones with the runloop version as (3.0.0), but none of the errors match the one I have.

        InputStream serviceAccount = getAssets().open("<My JSON file goes here>");
        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
                .setDatabaseUrl("<My Firebase link goes here>")
                .build();

        FirebaseApp defaultApp = FirebaseApp.initializeApp(options);

        database = FirebaseDatabase.getInstance();
        database.setLogLevel(Logger.Level.DEBUG);
        database.getReference().child("test").setValue("test value");

For my gradle files, I only have these:

compile 'com.google.firebase:firebase-admin:4.1.5'
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:design:25.2.0'
testCompile 'junit:junit:4.12'
compile 'com.android.support.constraint:constraint-layout:1.0.0-beta5'

And here's more of the stack trace:

W/System.err: Mon Apr 03 11:39:33 GMT+08:00 2017 [ERROR] RunLoop: Uncaught exception in Firebase Database runloop (4.1.5). Please report to firebase-database-client@google.com
W/System.err: java.lang.NoSuchMethodError: No virtual method object()Lorg/json/JSONWriter; in class Lorg/json/JSONStringer; or its super classes (declaration of 'org.json.JSONStringer' appears in /system/framework/core-libart.jar)
W/System.err:     at com.google.firebase.database.util.JsonMapper.serializeJsonValue(JsonMapper.java:55)
W/System.err:     at com.google.firebase.database.util.JsonMapper.serializeJsonValue(JsonMapper.java:44)
W/System.err:     at com.google.firebase.database.util.JsonMapper.serializeJson(JsonMapper.java:24)
W/System.err:     at com.google.firebase.database.util.GAuthToken.serializeToString(GAuthToken.java:53)
W/System.err:     at com.google.firebase.database.core.JvmAuthTokenProvider.wrapOAuthToken(JvmAuthTokenProvider.java:110)

Any ideas what might be wrong?


问:
How to change the printed qweb filename
How to change the printed qweb filename depends on the source document field name?
Im in the model stock.picking

So when i click the print -> Delivery note, then the qweb will be printed, but te filename will be depends on the Source document field.
Here i present the picture that explain what i mean.

EXAMPLE

答:
try attachment in your reprot to change report file name as your desired name.

```<code><report
            string="Delivery Slip"
            id="action_report_delivery"
            model="stock.picking"
            report_type="qweb-pdf"
            name="stock.report_deliveryslip"
            file="stock.report_deliveryslip"
            attachment="'Custom Text...'+'.pdf')"
        />
</code>```

Title: How to change the printed qweb filename

Body:
try attachment in your reprot to change report file name as your desired name.

<report
            string="Delivery Slip"
            id="action_report_delivery"
            model="stock.picking"
            report_type="qweb-pdf"
            name="stock.report_deliveryslip"
            file="stock.report_deliveryslip"
            attachment="'Custom Text...'+'.pdf')"
        />


问:
Nodejs - Set up different api version
I have following setup for api version1 which will validate token through middle ware

```<code>var app = express();
// Auth Middleware - This will check if the token is valid
// Only the requests that start with /api/version1/* will be checked for the token.
// Any URL's that do not follow the below pattern should be avoided unless you
// are sure that authentication is not needed
app.all('/api/version1/*', [require('./middleWare/validateMyRequest')]);
app.use('/', require('./myModal'));
app.all('/*', function(req, res) {
    res.sendFile('/public/index.html', { root: __dirname });
});
</code>```

Here i want to set another api version2 in server configuation in which i dont need to validate token using middle ware.I have tried with following config

```<code>app.use('/api/version2/*', require('./myModal'));
</code>```

When i tried with baseurl with api version2. It always validate token and redirect to login page. Please advise what i am missing here to set up api version2?

答:
Put your two separate APIs each on their own router.  You can then have different middleware on each router, one that does one kind of validation/auth, the other that does something different.</p>

```<code>app.use('/api/version1', router1);
app.use('/api/version2', router2);

router1.use(require('./middleWare/validateMyRequest'));
router1.get('/whatever', function(req, res) {
    // handle /api/version1/whatever here
});

router2.get('/something', function(req, res) {
    // handle /api/version2/something here
});
</code>```

Title: Nodejs - Set up different api version

Body:
I have following setup for api version1 which will validate token through middle ware

var app = express();
// Auth Middleware - This will check if the token is valid
// Only the requests that start with /api/version1/* will be checked for the token.
// Any URL's that do not follow the below pattern should be avoided unless you
// are sure that authentication is not needed
app.all('/api/version1/*', [require('./middleWare/validateMyRequest')]);
app.use('/', require('./myModal'));
app.all('/*', function(req, res) {
    res.sendFile('/public/index.html', { root: __dirname });
});

Here i want to set another api version2 in server configuation in which i dont need to validate token using middle ware.I have tried with following config

app.use('/api/version2/*', require('./myModal'));

When i tried with baseurl with api version2. It always validate token and redirect to login page. Please advise what i am missing here to set up api version2?

Body:
Put your two separate APIs each on their own router.  You can then have different middleware on each router, one that does one kind of validation/auth, the other that does something different.

app.use('/api/version1', router1);
app.use('/api/version2', router2);

router1.use(require('./middleWare/validateMyRequest'));
router1.get('/whatever', function(req, res) {
    // handle /api/version1/whatever here
});

router2.get('/something', function(req, res) {
    // handle /api/version2/something here
});


问:
How do I pass an std::string to a function that expects char*?

Possible Duplicate:

  Can I get a non-const C string back from a C++ string?

Do I need to convert it first? I saw in another post that .c_str() can be used if the function expected const char*. What about for just char*?

答:
When a parameter is declared as char* there it is implicitly assumed that the function will have as a side effect the modification of the string that is pointed.  Based in this and the fact that c_str() does not allow modifications to the enclosed string you cannot explicitly pass an std::string to such a method.

Something like this can be achived by following the following approach:

```<code>#include <cstdlib>
#include <string>
#include <iostream>

void modify_string(char* pz)
{
    pz[0] = 'm';
}

class string_wrapper
{
    std::string& _s;
    char* _psz;
    string_wrapper(const string_wrapper&);
    string_wrapper& operator=(const string_wrapper&);
public:

    string_wrapper(std::string& s) : _s(s), _psz(0) {}

    virtual ~string_wrapper()
    {
        if(0 != _psz)
        {
            _s = _psz;
            delete[] _psz;
        }
    }

    operator char*()
    {
        _psz = new char[_s.length()+1];
        strcpy(_psz,_s.c_str());
        return _psz;
    }
};

int main(int argc, char** argv)
{
    using namespace std;
    std::string s("This is a test");
    cout << s << endl;
    modify_string(string_wrapper(s));
    cout << s << endl;
    return 0;
}
</code>```

Body:
When a parameter is declared as char* there it is implicitly assumed that the function will have as a side effect the modification of the string that is pointed.  Based in this and the fact that c_str() does not allow modifications to the enclosed string you cannot explicitly pass an std::string to such a method.

Something like this can be achived by following the following approach:

#include <cstdlib>
#include <string>
#include <iostream>

void modify_string(char* pz)
{
    pz[0] = 'm';
}

class string_wrapper
{
    std::string& _s;
    char* _psz;
    string_wrapper(const string_wrapper&);
    string_wrapper& operator=(const string_wrapper&);
public:

    string_wrapper(std::string& s) : _s(s), _psz(0) {}

    virtual ~string_wrapper()
    {
        if(0 != _psz)
        {
            _s = _psz;
            delete[] _psz;
        }
    }

    operator char*()
    {
        _psz = new char[_s.length()+1];
        strcpy(_psz,_s.c_str());
        return _psz;
    }
};

int main(int argc, char** argv)
{
    using namespace std;
    std::string s("This is a test");
    cout << s << endl;
    modify_string(string_wrapper(s));
    cout << s << endl;
    return 0;
}


答:
Here I make fiddle for you </p>

```<code>$("#content").keypress(function(e) {
          var tmp = $("#content").val();
          if(tmp.charAt(0) ==="@")
          {
            console.log("It working");
          }
        });
</code>```

Title: Event keypress jquery when match a special character

Body:
I'm trying to processing code when user type @ like facebook tag. When user type @abc, then event is processed. This is my code:

$("#content").keypress(function(e) {
          var tmp = $("#content").val();
          if(tmp =="@")
          {
            console.log("It working");
          }
        });

UPDATING

Code like this:

$("#content").keypress(function(event) {
          var tmp  = $("#content").val();
          if(tmp.indexOf('@') !== -1)
          {
            console.log("It's working");
          }
        });

It's working when i'm typing @ with anything charater, but when i type  (space), it also working, i try to stop event when user type (space) after @anything.

Body:
Here I make fiddle for you

$("#content").keypress(function(e) {
          var tmp = $("#content").val();
          if(tmp.charAt(0) ==="@")
          {
            console.log("It working");
          }
        });


问:
Bootstrap-modal: Partial view displayed in modal-body
I'm attempting to load a partial view inside a bootstrap model. Since I have an existing form in the parent page and another in the partial view. I cannot decide to put the forms on one pages, because then there will be a form within a form.

Below is my checkbox in the parent page, when checked it will display the model dialog:

```<code><input type="checkbox" name="inputNewBornKMC" value="inputNewBornKMC" id="inputNewBornKMCCheckbox"> New Born
</code>```

Below is the modal dialog in the parent page:

```<code>                        <div Class="modal fade" id="inputNewBornKMC" role="dialog">
                        <div class="modal-dialog">
                            <!-- Modal content-->
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close modal-close-btn" data-dismiss="modal">×</button>
                                    <h4 class="modal-title">Search Newborn's Mother</h4>
                                </div>
                                <div class="modal-body">
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                    @*<button type="button" class="btn btn-default" id="AddGP">Save changes</button>*@
                                </div>
                            </div> <!-- Modal content-->
                        </div>
                    </div> <!-- Modal -->
</code>```

In the javascript, I put the following code to load the modal dialog:

```<code>        $('#inputNewBornKMCCheckbox').on('change', function (e) {
        var _this = $(this);

        // if checked
        if (_this.is(':checked')) {
            $('#inputNewBornKMC').modal({
                keyboard: false,
                remote: '/controller/AddPartialRegistration'
            }).show();

        $('#inputNewBornKMCCheckbox').on('click', '.modal-link', function (e) {
                e.preventDefault();
                $(this).attr('data-target', '#inputNewBornKMC');
                $(this).attr('data-toggle', 'modal');

            });

       }
</code>```

Which will call an action in controller to display the partial view:

```<code>public ActionResult AddPartialRegistration()
    {
        return PartialView("_PartialRegistration");
    }
</code>```

In _PartialRegistration page:

```<code>            <div class="modal-body">
                <form class="form-horizontal" id="frmSearchMother" role="form" >

                    Mother's MRN
                    <input type="text" class="form-control input-sm" id="popupMotherMRN" name="popupMotherMRN" />
                    IC/ID No
                    <input type="text" class="form-control input-sm" id="popupICNo" name="popupICNo" />
                    Mother's Name
                    <input type="text" class="form-control input-sm" id="popupMotherName" name="popupMotherName" />
                    <button type="button" class="btn btn-default" id="SearchMother" >Search</button>
                </form>
                <br />
                <table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="LoadMotherDetailsTable">
                    <thead>
                        <tr>
                            <th>No.</th>
                            <th>Mother's MRN</th>
                            <th>Mother's IC No</th>
                            <th>Mother's Name</th>
                            <th></th>
                        </tr>
                    </thead>

                    <tbody>

                    </tbody>

                </table>
            </div>
</code>```

I've tried numerous ways in which people apply partial views, but none have worked. I'm unsure as to how to make the partial view be inserted in the modal-body inside of the modal dialog. This dialog can be displayed when checking the checkbox, but I'm unsure as to how to load the partial view in the modal-body.

Any help would be much appreciated.

答:
This is my first answer so dont expect much.

I would say the best way to inject a partial view is the way you are trying as well.

I would say you call AJAX and return the partial view data via the controller.
This is an code taken from a use case I wrote:

```<code>function showVideo(e) {
        alert('#' + $(e).attr("id"));
        $.ajax({
            url: '/Games/_GameModal/' + $(e).attr("id"),
            dataType: 'html',
            success: function (data) {
                alert('#' + $(e).attr("id"));
                $('#deleteConfirmation').html(data);
                $('#deleteConfirmation').modal();
            }
        });

    }
</code>```

This is my Partial View cshtml:

```<code> <div class="modal-dialog modal-lg">
 <div class="modal-content">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-
          hidden="true">×</button>
        <h2 class="modal-title text-center">@Model.gameName</h2>
        <h4 class="text-center">By @Model.publisher</h4>
        <h5 class="text-center">Content Rating: @Model.Contentrating</h5>
    </div>
    <div class="modal-body">
        <h4 class="text-center">Trailer</h4>
        <iframe width="560" height="315" src="@Model.trailerLink"
        frameborder="0" allowfullscreen></iframe>
        <h4 class="text-center">Description</h4>
        <p>@Model.description</p>
    </div>
</div>
</code>```

This is the container I am injecting into:

```<code><div class="modal fade" id="deleteConfirmation" tabindex="-1" role="dialog"
   aria-labelledby="myModalLabel" aria-hidden="true">
</div>
</code>```

If you want to inject into the modal body you would replace the '#deleteConfirmation' with the id of you div of the modal-body and inject HTML data into it.

I hope this was helpful and I am sorry if it wasnt. Just trying to help

Thanks,
Narendran P

Body:
I'm attempting to load a partial view inside a bootstrap model. Since I have an existing form in the parent page and another in the partial view. I cannot decide to put the forms on one pages, because then there will be a form within a form.

Below is my checkbox in the parent page, when checked it will display the model dialog:

<input type="checkbox" name="inputNewBornKMC" value="inputNewBornKMC" id="inputNewBornKMCCheckbox"> New Born

Below is the modal dialog in the parent page:

                                    <button type="button" class="close modal-close-btn" data-dismiss="modal">×</button>

Search Newborn's Mother

                                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                    @*<button type="button" class="btn btn-default" id="AddGP">Save changes</button>*@

In the javascript, I put the following code to load the modal dialog:

        $('#inputNewBornKMCCheckbox').on('change', function (e) {
        var _this = $(this);

        // if checked
        if (_this.is(':checked')) {
            $('#inputNewBornKMC').modal({
                keyboard: false,
                remote: '/controller/AddPartialRegistration'
            }).show();

        $('#inputNewBornKMCCheckbox').on('click', '.modal-link', function (e) {
                e.preventDefault();
                $(this).attr('data-target', '#inputNewBornKMC');
                $(this).attr('data-toggle', 'modal');

            });

       }

Which will call an action in controller to display the partial view:

public ActionResult AddPartialRegistration()
    {
        return PartialView("_PartialRegistration");
    }

In _PartialRegistration page:

                <form class="form-horizontal" id="frmSearchMother" role="form" >

                    Mother's MRN
                    <input type="text" class="form-control input-sm" id="popupMotherMRN" name="popupMotherMRN" />
                    IC/ID No
                    <input type="text" class="form-control input-sm" id="popupICNo" name="popupICNo" />
                    Mother's Name
                    <input type="text" class="form-control input-sm" id="popupMotherName" name="popupMotherName" />
                    <button type="button" class="btn btn-default" id="SearchMother" >Search</button>
                </form>

                            No.
                            Mother's MRN
                            Mother's IC No
                            Mother's Name

I've tried numerous ways in which people apply partial views, but none have worked. I'm unsure as to how to make the partial view be inserted in the modal-body inside of the modal dialog. This dialog can be displayed when checking the checkbox, but I'm unsure as to how to load the partial view in the modal-body.

Any help would be much appreciated.

Body:
This is my first answer so dont expect much.

I would say the best way to inject a partial view is the way you are trying as well.

I would say you call AJAX and return the partial view data via the controller.
This is an code taken from a use case I wrote:

function showVideo(e) {
        alert('#' + $(e).attr("id"));
        $.ajax({
            url: '/Games/_GameModal/' + $(e).attr("id"),
            dataType: 'html',
            success: function (data) {
                alert('#' + $(e).attr("id"));
                $('#deleteConfirmation').html(data);
                $('#deleteConfirmation').modal();
            }
        });

    }

This is my Partial View cshtml:

 <div class="modal-dialog modal-lg">
 <div class="modal-content">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-
          hidden="true">&times;</button>
        <h2 class="modal-title text-center">@Model.gameName</h2>
        <h4 class="text-center">By @Model.publisher</h4>
        <h5 class="text-center">Content Rating: @Model.Contentrating</h5>
    </div>
    <div class="modal-body">
        <h4 class="text-center">Trailer</h4>
        <iframe width="560" height="315" src="@Model.trailerLink"
        frameborder="0" allowfullscreen></iframe>
        <h4 class="text-center">Description</h4>
        <p>@Model.description</p>
    </div>
</div>

This is the container I am injecting into:

<div class="modal fade" id="deleteConfirmation" tabindex="-1" role="dialog"
   aria-labelledby="myModalLabel" aria-hidden="true">
</div>

If you want to inject into the modal body you would replace the '#deleteConfirmation' with the id of you div of the modal-body and inject HTML data into it.

I hope this was helpful and I am sorry if it wasnt. Just trying to help

Thanks,
Narendran P


问:
My android application suddenly stopped working
I've been bugged by this problem and I got to make a quick fix to this. Please help me. So currently im experiencing crashes everytime I paste some new codes that I find online. [P.S. Im a newb in android programming]

This is my AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="birada1.tulungatung.ph.myapplication2">

<application
    android:allowBackup="true"
    android:icon="@mipmap/chess_icon"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>
</code>```

I made some minor changes to MainActivity.java

```<code>import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener {

private Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Button one = (Button) findViewById(R.id.button2);
    Button two = (Button) findViewById(R.id.button3);
    Button three = (Button) findViewById(R.id.button4);

    one.setOnClickListener(this);
    two.setOnClickListener(this);
    three.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch (view.getId()) {

        case R.id.button2:
            Intent intenthistory = new Intent(this, ChessHistoryActivity.class);
            startActivity(intenthistory);
            // do your code
            break;

        case R.id.button3:
            Intent intenthistory2 = new Intent(this, LearnChessActivity.class);
            startActivity(intenthistory2);
            break;
        case R.id.button4:
            Intent intenthistory3 = new Intent(this, GrandmastersActivity.class);
            startActivity(intenthistory3);
            break;

        default:
    }

}
}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<ImageView
android:id="@+id/img_view3"
android:layout_width="wrap_content"
android:layout_height="95dp"
android:contentDescription="@string/hellow"
app:srcCompat="@drawable/boom" />

<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark"
android:onClick="btnClick1"
android:text="@string/c_history" />

<ImageView
android:id="@+id/img_view4"
android:layout_width="wrap_content"
android:layout_height="101dp"
android:contentDescription="@string/hellow"
app:srcCompat="@drawable/chess_moves_three" />

<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="btnClick2"
android:background="@color/colorPrimaryDark"
android:text="@string/c_moves" />

<ImageView
android:id="@+id/imageView5"
android:layout_width="wrap_content"
android:layout_height="113dp"
android:contentDescription="@string/hellow"
app:srcCompat="@drawable/grandmasters" />

<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
android:onClick="btnClick3"
android:text="@string/c_grandmasters" />
</LinearLayout>
</code>```

答:
Remove your application tag from manifest and paste this application tag and try it your problem will be solved.</p>

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/chess_icon"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">

       <intent-filter>
           <action android:name="android.intent.action.MAIN" />

           <category android:name="android.intent.category.LAUNCHER" />
       </intent-filter>
    </activity>
    <activity android:name=".ChessHistoryActivity"/>
    <activity android:name=".LearnChessActivity"/>
    <activity android:name=".GrandmastersActivity"/>
</application>
</code>```

Body:
I've been bugged by this problem and I got to make a quick fix to this. Please help me. So currently im experiencing crashes everytime I paste some new codes that I find online. [P.S. Im a newb in android programming]

This is my AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="birada1.tulungatung.ph.myapplication2">

<application
    android:allowBackup="true"
    android:icon="@mipmap/chess_icon"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

I made some minor changes to MainActivity.java

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener {

private Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Button one = (Button) findViewById(R.id.button2);
    Button two = (Button) findViewById(R.id.button3);
    Button three = (Button) findViewById(R.id.button4);

    one.setOnClickListener(this);
    two.setOnClickListener(this);
    three.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch (view.getId()) {

        case R.id.button2:
            Intent intenthistory = new Intent(this, ChessHistoryActivity.class);
            startActivity(intenthistory);
            // do your code
            break;

        case R.id.button3:
            Intent intenthistory2 = new Intent(this, LearnChessActivity.class);
            startActivity(intenthistory2);
            break;
        case R.id.button4:
            Intent intenthistory3 = new Intent(this, GrandmastersActivity.class);
            startActivity(intenthistory3);
            break;

        default:
    }

}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<ImageView
android:id="@+id/img_view3"
android:layout_width="wrap_content"
android:layout_height="95dp"
android:contentDescription="@string/hellow"
app:srcCompat="@drawable/boom" />

<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark"
android:onClick="btnClick1"
android:text="@string/c_history" />

<ImageView
android:id="@+id/img_view4"
android:layout_width="wrap_content"
android:layout_height="101dp"
android:contentDescription="@string/hellow"
app:srcCompat="@drawable/chess_moves_three" />

<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="btnClick2"
android:background="@color/colorPrimaryDark"
android:text="@string/c_moves" />

<ImageView
android:id="@+id/imageView5"
android:layout_width="wrap_content"
android:layout_height="113dp"
android:contentDescription="@string/hellow"
app:srcCompat="@drawable/grandmasters" />

<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
android:onClick="btnClick3"
android:text="@string/c_grandmasters" />
</LinearLayout>

Body:
Remove your application tag from manifest and paste this application tag and try it your problem will be solved.

<application
    android:allowBackup="true"
    android:icon="@mipmap/chess_icon"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">

       <intent-filter>
           <action android:name="android.intent.action.MAIN" />

           <category android:name="android.intent.category.LAUNCHER" />
       </intent-filter>
    </activity>
    <activity android:name=".ChessHistoryActivity"/>
    <activity android:name=".LearnChessActivity"/>
    <activity android:name=".GrandmastersActivity"/>
</application>