问:
Plot graph from the bunch of selected excel sheet
There are lot of csv excel sheets in a folder. All excel sheet contains data only in first 3 columns. I will select corresponding csv sheet from a lot of csv sheets and then plot it.Here is the code

```<code>import os
path = "F:\\Users\\Desktop\\Data\\Summary"
files = []
test_folders = os.listdir(path)
folder_data = os.listdir(path)
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
    for file in f:
        if '.csv' in file:
            files.append(file)
for i, f in enumerate(files):
    print("%d-%s"%( i,f))
    csv_code = int(input("Enter corresponding code to plot: "))
    csv_path = folder_data + "\\" + folder_data[csv_code]

    df = pd.read_csv(csv_path, header=None)
    df1 = df.iloc[:,0:2]
    plt.plot(df1[0], df1[1])
</code>```

When i run the code i want the Output to be displayed as follows (i mean i want all csv files from the folder to be displayed so that i can select what i want):

```<code>0-Test_Summary_1.csv
1-Test_Summary_2.csv
2-Test_Summary_3.csv
3-Test_Summary_4.csv
4-Test_Summary_5.csv
5-Test_Summary_6.csv etc
</code>```

so that i select the corresponding code like 1 or 2 or 3 to plot.

Here is the error

```<code>   csv_path = folder_data + "\\" + folder_data[csv_code]

TypeError: can only concatenate list (not "str") to list
</code>```

答:
folder_data is not a defined variable in the code you have provided? By extensions folder_data[csv_code] isn't either.
Is the line you're receiveing an error on supposed to be:

csv_path = path + "\\" + csv_code

Body:
There are lot of csv excel sheets in a folder. All excel sheet contains data only in first 3 columns. I will select corresponding csv sheet from a lot of csv sheets and then plot it.Here is the code

import os
path = "F:\\Users\\Desktop\\Data\\Summary"
files = []
test_folders = os.listdir(path)
folder_data = os.listdir(path)
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
    for file in f:
        if '.csv' in file:
            files.append(file)
for i, f in enumerate(files):
    print("%d-%s"%( i,f))
    csv_code = int(input("Enter corresponding code to plot: "))
    csv_path = folder_data + "\\" + folder_data[csv_code]

    df = pd.read_csv(csv_path, header=None)
    df1 = df.iloc[:,0:2]
    plt.plot(df1[0], df1[1])

When i run the code i want the Output to be displayed as follows (i mean i want all csv files from the folder to be displayed so that i can select what i want):

0-Test_Summary_1.csv
1-Test_Summary_2.csv
2-Test_Summary_3.csv
3-Test_Summary_4.csv
4-Test_Summary_5.csv
5-Test_Summary_6.csv etc

so that i select the corresponding code like 1 or 2 or 3 to plot.

Here is the error

   csv_path = folder_data + "\\" + folder_data[csv_code]

TypeError: can only concatenate list (not "str") to list


来源: stackexchange

问:
WooCommerce Payment Gateway not showing on checkout page
I have enabled the PayPal standard gateway. This is currently the showing payment method on the checkout page. I have installed an SSL and have an HTTPS:// how ever when i try to enable the PayPal Pro Payment Gateway (in sandbox mode) the Checkout page only displays the Paypal standard method and does not give the familiar radio buttons to select the method. Only method available is the paypal standard.

I also tried enabling the Cheque payment gateway but that also does not display on checkout page

Is there any way to fix this so the credit card input Paypal pro payment method displays on the checkout page?

The site is https://www.dowelmax.com

答:
I was also face this type of problem but I was resolve with these instruction.

Enable define ( 'WP_DEBUG', true);

Goto checkout page and refresh page.

Now showing some warning and fatal error.

Solve fatal error and refresh again checkout page and now it's showing payment option and order place button.

I hope this instruction will help you.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Getting xy data from matplotlib fig object
I need to retrieve XY data from a fig object with 2 subplots.

Here is the way I made the fig object:

```<code>f, axarr = plt.subplots(1,2)
axarr[0].imshow(labels_map,vmax=28)
axarr[1].imshow(Y_predictions,vmax=28)
np.save('fig.npy', f)
</code>```

I can't remake the fig objects, because I no longer have access to the machine.

from a previous stackoverflow post:

```<code>fig = numpy.load("fig.npy").item()
ax = fig.gca()
xy_data = ax.get_lines()
print(xy_data[0])
</code>```

printing fails: "list index out of range"

I need to get the 2d array for both the subplots in order to make a confusion matrix.

答:
Try the following</p>

```<code>xy_data = ax.get_lines()[0].get_data()
print (xy_data)
</code>```

Body:
I need to retrieve XY data from a fig object with 2 subplots.

Here is the way I made the fig object:

f, axarr = plt.subplots(1,2)
axarr[0].imshow(labels_map,vmax=28)
axarr[1].imshow(Y_predictions,vmax=28)
np.save('fig.npy', f)

I can't remake the fig objects, because I no longer have access to the machine.

from a previous stackoverflow post:

fig = numpy.load("fig.npy").item()
ax = fig.gca()
xy_data = ax.get_lines()
print(xy_data[0])

printing fails: "list index out of range"

I need to get the 2d array for both the subplots in order to make a confusion matrix.

Body:
Try the following

xy_data = ax.get_lines()[0].get_data()
print (xy_data)


问:
Can we replace "return" with "throw new Exception"?
I'm trying to write a matrix calculator for decomposition. However, there are some cases in the matrix calculator where I don't want the system to return anything, but just print out an error message.

I have tried to do this by replacing the return call with a throw new Exception method, but it clearly doesn't seem to be working because: 1. there needs to be some sort of catch/throws implemented and 2. there is still a need for a return statement.

```<code>public double[][] multiply(Matrix other) {
  if(getCols() == other.getRows()) {
     double[][] mult = new double[getRows()][other.getCols()];

     for(int r = 0; r < mult.length; r++) {
        for(int c = 0; c < mult[0].length; c++) {
           mult[r][c] = mult(m1[r],findCol(other,c));
        }
     }

     return mult;
  }

  else {
     throw new MatrixException("Multiply");
  }

}
</code>```

So as can be seen by the else statement, in place of a return statement, it is replaced with throw new MatrixException("Multiply"). This simply returns a String statement, but the code will not compile. Is there any way to use a try-catch method to throw the Exception without needing to implement a return? Also, yes this is the first time I'm asking a question, so I'm still not fully familiar with the question formatting techniques.

答:
You could inform the caller of multiply that an exception can be thrown by changing your method like this:

public double[][] multiply(Matrix other)throws MatrixException{}

So the method now would be:

```<code>public double[][] multiply(Matrix other) throws MatrixException {  // tells the method throws an exception
    if(getCols() == other.getRows()) {
        // ...
        return <your_valid_return_here>
    }
    throw new MatrixException("Multiply");  // inform the caller there is an exception if the previous condition is not met
}
</code>```

Also, bear in mind what type of exception is MatrixException (checked or unchecked) in order to follow this approach. If checked, the caller will be forced to handle it in the calling code (or report its code can throw the exception), not being like this if it is unchecked.

Additional reading:

When to choose checked and unchecked exceptions

Body:
I'm trying to write a matrix calculator for decomposition. However, there are some cases in the matrix calculator where I don't want the system to return anything, but just print out an error message.

I have tried to do this by replacing the return call with a throw new Exception method, but it clearly doesn't seem to be working because: 1. there needs to be some sort of catch/throws implemented and 2. there is still a need for a return statement.

public double[][] multiply(Matrix other) {
  if(getCols() == other.getRows()) {
     double[][] mult = new double[getRows()][other.getCols()];

     for(int r = 0; r < mult.length; r++) {
        for(int c = 0; c < mult[0].length; c++) {
           mult[r][c] = mult(m1[r],findCol(other,c));
        }
     }

     return mult;
  }

  else {
     throw new MatrixException("Multiply");
  }

}

So as can be seen by the else statement, in place of a return statement, it is replaced with throw new MatrixException("Multiply"). This simply returns a String statement, but the code will not compile. Is there any way to use a try-catch method to throw the Exception without needing to implement a return? Also, yes this is the first time I'm asking a question, so I'm still not fully familiar with the question formatting techniques.

Body:
You could inform the caller of multiply that an exception can be thrown by changing your method like this:

public double[][] multiply(Matrix other)throws MatrixException{}

So the method now would be:

public double[][] multiply(Matrix other) throws MatrixException {  // tells the method throws an exception
    if(getCols() == other.getRows()) {
        // ...
        return <your_valid_return_here>
    }
    throw new MatrixException("Multiply");  // inform the caller there is an exception if the previous condition is not met
}

Also, bear in mind what type of exception is MatrixException (checked or unchecked) in order to follow this approach. If checked, the caller will be forced to handle it in the calling code (or report its code can throw the exception), not being like this if it is unchecked.

Additional reading:

When to choose checked and unchecked exceptions


问:
What's the fastest way to test the validity of a large number of well-formed URLs
My project requires me to validate a large number of web URLs. These URLs have been captured by a very unreliable process which I do not control. All of the URLs have already been regexp validated and are known to be well-formed. I also know that they all have valid TLDs

I want to be able to filter these URLs quickly in order to determine which of these are incorrect. At this point I do not care what content is on the pages - I'd just like to know as quickly as possible which of the pages are inaccessible (e.g. produce a 404 error).

Given that there are a lot of these I do not want to download the entire page, just the HTTP header and then take a good guess from the content of the header whether the page is likely to exist.

Can it be done?

答:
To really make this fast you might also use eventlet which uses non-blocking IO to speed things up.

You can use a head request like this:

```<code>from eventlet import httpc
try:
    res = httpc.head(url)
except httpc.NotFound:
    # handle 404
</code>```

You can then put this into some simple script like that example script here. With that you should get pretty much concurrency by using a coroutines pool.

OwnerDisplayName: Salim Fadhley

ContentLicense: CC BY-SA 2.5

Body:
To really make this fast you might also use eventlet which uses non-blocking IO to speed things up.

You can use a head request like this:

from eventlet import httpc
try:
    res = httpc.head(url)
except httpc.NotFound:
    # handle 404

You can then put this into some simple script like that example script here. With that you should get pretty much concurrency by using a coroutines pool.

OwnerDisplayName: MrTopf


问:
Jquery - Header banner rotator
Can anybody recommend a decent cross-browser jquery banner rotator that I can use to dynamically fade between click-able banners?

Thanks for your help
Paul

答:
Use Jquery Cycle. You can create paged banners with navigation and it takes 2 minutes to get it working.

There are loads of settings for effects and lots more.

Here is a demo:

http://jquery.malsup.com/cycle/pager-over.html

More demos here too: http://jquery.malsup.com/cycle/more.html

Title: Jquery - Header banner rotator


问:
Principal value is zero after calculating emi based on loan amount using python?
I'm working on financial project and I want to prepare an api for amortization schedule. The interest and payment is working well but principal amount starts from zero, I tried many websites but I was not able to get exact answer. Can any one help me? Below is my python code which I tried. Thanks in advance.

```<code>import pandas as pd
import numpy as np
from datetime import date

Interest_Rate = 10
Years = 5
Payments_Year = 12
Principal = 100000
Addl_Princ = 50
start_date = (date(2019,5,28))

pmt = np.pmt(Interest_Rate/Payments_Year, Years*Payments_Year, Principal)
per = 1

# Calculate the interest
ipmt = np.ipmt(Interest_Rate/Payments_Year, per, Years*Payments_Year, Principal)

# Calculate the principal
ppmt = np.ppmt(Interest_Rate/Payments_Year, per, Years*Payments_Year, Principal)

rng = pd.date_range(start_date, periods=Years * Payments_Year, freq='MS')
rng.name = "Payment_Date"
df = pd.DataFrame(index=rng, columns=['Payment', 'Principal', 'Interest'], dtype='float')
df.reset_index(inplace=True)
df.index += 1
df.index.name = "Period"

df["Payment"] = np.pmt(Interest_Rate/Payments_Year, Years*Payments_Year, Principal)
df["Principal"] = np.ppmt(Interest_Rate/Payments_Year, df.index, Years*Payments_Year, Principal)
df["Interest"] = np.ipmt(Interest_Rate/Payments_Year, df.index, Years*Payments_Year, Principal)
# df["Addl_Principal"] = -Addl_Principal
df = df.round(2)
print(df)
</code>```

my output is :

```<code>       Payment_Date   Payment  Principal  Interest    Balance
Period
1        2019-06-01 -83333.33       0.00 -83333.33  100000.00
2        2019-07-01 -83333.33      -0.00 -83333.33  100000.00
3        2019-08-01 -83333.33       0.00 -83333.33  100000.00
4        2019-09-01 -83333.33      -0.00 -83333.33  100000.00
5        2019-10-01 -83333.33      -0.00 -83333.33  100000.00
6        2019-11-01 -83333.33      -0.00 -83333.33  100000.00
7        2019-12-01 -83333.33       0.00 -83333.33  100000.00
8        2020-01-01 -83333.33      -0.00 -83333.33  100000.00
9        2020-02-01 -83333.33      -0.00 -83333.33  100000.00
10       2020-03-01 -83333.33      -0.00 -83333.33  100000.00
11       2020-04-01 -83333.33       0.00 -83333.33  100000.00
12       2020-05-01 -83333.33       0.00 -83333.33  100000.00
13       2020-06-01 -83333.33       0.00 -83333.33  100000.00
14       2020-07-01 -83333.33      -0.00 -83333.33  100000.00
15       2020-08-01 -83333.33      -0.00 -83333.33  100000.00
16       2020-09-01 -83333.33       0.00 -83333.33  100000.00
17       2020-10-01 -83333.33      -0.00 -83333.33  100000.00
18       2020-11-01 -83333.33       0.00 -83333.33  100000.00
19       2020-12-01 -83333.33       0.00 -83333.33  100000.00
20       2021-01-01 -83333.33       0.00 -83333.33  100000.00
21       2021-02-01 -83333.33       0.00 -83333.33  100000.00
22       2021-03-01 -83333.33       0.00 -83333.33  100000.00
23       2021-04-01 -83333.33      -0.00 -83333.33  100000.00
24       2021-05-01 -83333.33      -0.00 -83333.33  100000.00
25       2021-06-01 -83333.33      -0.00 -83333.33  100000.00
26       2021-07-01 -83333.33      -0.00 -83333.33  100000.00
27       2021-08-01 -83333.33      -0.00 -83333.33  100000.00
28       2021-09-01 -83333.33       0.00 -83333.33  100000.00
29       2021-10-01 -83333.33      -0.00 -83333.33  100000.00
30       2021-11-01 -83333.33       0.00 -83333.33  100000.00
31       2021-12-01 -83333.33       0.00 -83333.33  100000.00
32       2022-01-01 -83333.33       0.00 -83333.33  100000.00
33       2022-02-01 -83333.33      -0.00 -83333.33  100000.00
34       2022-03-01 -83333.33      -0.01 -83333.33   99999.99
35       2022-04-01 -83333.33       0.00 -83333.33   99999.99
36       2022-05-01 -83333.33       0.00 -83333.33   99999.99
37       2022-06-01 -83333.33       0.00 -83333.33   99999.99
38       2022-07-01 -83333.33       0.00 -83333.33   99999.99
39       2022-08-01 -83333.33      -0.10 -83333.23   99999.89
40       2022-09-01 -83333.33      -0.21 -83333.12   99999.68
41       2022-10-01 -83333.33      -0.42 -83332.92   99999.26
42       2022-11-01 -83333.33      -0.83 -83332.50   99998.43
43       2022-12-01 -83333.33       0.00 -83333.33   99998.43
44       2023-01-01 -83333.33       0.00 -83333.33   99998.43
45       2023-02-01 -83333.33      -6.67 -83326.67   99991.76
46       2023-03-01 -83333.33      -6.67 -83326.67   99985.09
47       2023-04-01 -83333.33     -13.33 -83320.00   99971.76
48       2023-05-01 -83333.33     -26.67 -83306.67   99945.09
49       2023-06-01 -83333.33     -26.67 -83306.67   99918.42
50       2023-07-01 -83333.33     -26.67 -83306.67   99891.75
51       2023-08-01 -83333.33    -133.33 -83200.00   99758.42
52       2023-09-01 -83333.33    -133.33 -83200.00   99625.09
53       2023-10-01 -83333.33    -560.00 -82773.33   99065.09
54       2023-11-01 -83333.33    -560.00 -82773.33   98505.09
55       2023-12-01 -83333.33   -1413.33 -81920.00   97091.76
56       2024-01-01 -83333.33   -4826.67 -78506.67   92265.09
57       2024-02-01 -83333.33   -1413.33 -81920.00   90851.76
58       2024-03-01 -83333.33   -1413.33 -81920.00   89438.43
59       2024-04-01 -83333.33  -28720.00 -54613.33   60718.43
60       2024-05-01 -83333.33  -28720.00 -54613.33   31998.43
</code>```

答:
yea...finally i think a lot and i got output.

Code:

```<code>Interest_Rate = 0.10
    Years = 5
    Payments_Year = 12
    Principal = 200000

    start_date = (date(2019, 5, 28))

    pmt = np.pmt(Interest_Rate / Payments_Year, Years * Payments_Year, Principal)
    per = 1

    ipmt = np.ipmt(Interest_Rate / Payments_Year, per, Years * Payments_Year, Principal)

    ppmt = np.ppmt(Interest_Rate / Payments_Year, per, Years * Payments_Year, Principal)

    rng = pd.date_range(start_date, periods=Years * Payments_Year, freq='MS')
    rng.name = "Payment_Date"

    df = pd.DataFrame(index=rng, columns=['Payment', 'Principal', 'Interest', 'Balance'],
                      dtype='float')
    df.reset_index(inplace=True)
    df.index += 1
    df.index.name = "Period"
    print(df.index)
    df["Payment"] = np.pmt(Interest_Rate / Payments_Year, Years * Payments_Year, Principal)
    df["Principal"] = np.ppmt(Interest_Rate / Payments_Year, df.index, Years * Payments_Year, Principal)
    df["Interest"] = np.ipmt(Interest_Rate / Payments_Year, df.index, Years * Payments_Year, Principal)

    df = df.round(2)

    df["Balance"] = 0
    df.loc[1, "Balance"] = Principal + df.loc[1, "Principal"]

    for i in range(2, len(df) + 1):
        prev_balance = df.ix[i - 1, 'Balance']
        principal = df.ix[i, 'Principal']

        if prev_balance == 0:
            df.ix[i, ['Payment', 'Principal', 'Interest', 'Balance']] = 0
            continue

        if abs(principal) <= prev_balance:
            df.ix[i, 'Balance'] = principal + prev_balance
        else:

            if prev_balance <= abs(principal):
                principal = -prev_balance
                addl_principal = 0
            else:
                print('else')
            df.ix[i, 'Balance'] = 0
            df.ix[i, 'Principal'] = principal
            df.ix[i, "Payment"] = principal + df.ix[i, "Interest"]

    df = df.round(2)
    print(df)
</code>```

Body:
I'm working on financial project and I want to prepare an api for amortization schedule. The interest and payment is working well but principal amount starts from zero, I tried many websites but I was not able to get exact answer. Can any one help me? Below is my python code which I tried. Thanks in advance.

import pandas as pd
import numpy as np
from datetime import date

Interest_Rate = 10
Years = 5
Payments_Year = 12
Principal = 100000
Addl_Princ = 50
start_date = (date(2019,5,28))

pmt = np.pmt(Interest_Rate/Payments_Year, Years*Payments_Year, Principal)
per = 1

# Calculate the interest
ipmt = np.ipmt(Interest_Rate/Payments_Year, per, Years*Payments_Year, Principal)

# Calculate the principal
ppmt = np.ppmt(Interest_Rate/Payments_Year, per, Years*Payments_Year, Principal)

rng = pd.date_range(start_date, periods=Years * Payments_Year, freq='MS')
rng.name = "Payment_Date"
df = pd.DataFrame(index=rng, columns=['Payment', 'Principal', 'Interest'], dtype='float')
df.reset_index(inplace=True)
df.index += 1
df.index.name = "Period"

df["Payment"] = np.pmt(Interest_Rate/Payments_Year, Years*Payments_Year, Principal)
df["Principal"] = np.ppmt(Interest_Rate/Payments_Year, df.index, Years*Payments_Year, Principal)
df["Interest"] = np.ipmt(Interest_Rate/Payments_Year, df.index, Years*Payments_Year, Principal)
# df["Addl_Principal"] = -Addl_Principal
df = df.round(2)
print(df)

my output is :

       Payment_Date   Payment  Principal  Interest    Balance
Period
1        2019-06-01 -83333.33       0.00 -83333.33  100000.00
2        2019-07-01 -83333.33      -0.00 -83333.33  100000.00
3        2019-08-01 -83333.33       0.00 -83333.33  100000.00
4        2019-09-01 -83333.33      -0.00 -83333.33  100000.00
5        2019-10-01 -83333.33      -0.00 -83333.33  100000.00
6        2019-11-01 -83333.33      -0.00 -83333.33  100000.00
7        2019-12-01 -83333.33       0.00 -83333.33  100000.00
8        2020-01-01 -83333.33      -0.00 -83333.33  100000.00
9        2020-02-01 -83333.33      -0.00 -83333.33  100000.00
10       2020-03-01 -83333.33      -0.00 -83333.33  100000.00
11       2020-04-01 -83333.33       0.00 -83333.33  100000.00
12       2020-05-01 -83333.33       0.00 -83333.33  100000.00
13       2020-06-01 -83333.33       0.00 -83333.33  100000.00
14       2020-07-01 -83333.33      -0.00 -83333.33  100000.00
15       2020-08-01 -83333.33      -0.00 -83333.33  100000.00
16       2020-09-01 -83333.33       0.00 -83333.33  100000.00
17       2020-10-01 -83333.33      -0.00 -83333.33  100000.00
18       2020-11-01 -83333.33       0.00 -83333.33  100000.00
19       2020-12-01 -83333.33       0.00 -83333.33  100000.00
20       2021-01-01 -83333.33       0.00 -83333.33  100000.00
21       2021-02-01 -83333.33       0.00 -83333.33  100000.00
22       2021-03-01 -83333.33       0.00 -83333.33  100000.00
23       2021-04-01 -83333.33      -0.00 -83333.33  100000.00
24       2021-05-01 -83333.33      -0.00 -83333.33  100000.00
25       2021-06-01 -83333.33      -0.00 -83333.33  100000.00
26       2021-07-01 -83333.33      -0.00 -83333.33  100000.00
27       2021-08-01 -83333.33      -0.00 -83333.33  100000.00
28       2021-09-01 -83333.33       0.00 -83333.33  100000.00
29       2021-10-01 -83333.33      -0.00 -83333.33  100000.00
30       2021-11-01 -83333.33       0.00 -83333.33  100000.00
31       2021-12-01 -83333.33       0.00 -83333.33  100000.00
32       2022-01-01 -83333.33       0.00 -83333.33  100000.00
33       2022-02-01 -83333.33      -0.00 -83333.33  100000.00
34       2022-03-01 -83333.33      -0.01 -83333.33   99999.99
35       2022-04-01 -83333.33       0.00 -83333.33   99999.99
36       2022-05-01 -83333.33       0.00 -83333.33   99999.99
37       2022-06-01 -83333.33       0.00 -83333.33   99999.99
38       2022-07-01 -83333.33       0.00 -83333.33   99999.99
39       2022-08-01 -83333.33      -0.10 -83333.23   99999.89
40       2022-09-01 -83333.33      -0.21 -83333.12   99999.68
41       2022-10-01 -83333.33      -0.42 -83332.92   99999.26
42       2022-11-01 -83333.33      -0.83 -83332.50   99998.43
43       2022-12-01 -83333.33       0.00 -83333.33   99998.43
44       2023-01-01 -83333.33       0.00 -83333.33   99998.43
45       2023-02-01 -83333.33      -6.67 -83326.67   99991.76
46       2023-03-01 -83333.33      -6.67 -83326.67   99985.09
47       2023-04-01 -83333.33     -13.33 -83320.00   99971.76
48       2023-05-01 -83333.33     -26.67 -83306.67   99945.09
49       2023-06-01 -83333.33     -26.67 -83306.67   99918.42
50       2023-07-01 -83333.33     -26.67 -83306.67   99891.75
51       2023-08-01 -83333.33    -133.33 -83200.00   99758.42
52       2023-09-01 -83333.33    -133.33 -83200.00   99625.09
53       2023-10-01 -83333.33    -560.00 -82773.33   99065.09
54       2023-11-01 -83333.33    -560.00 -82773.33   98505.09
55       2023-12-01 -83333.33   -1413.33 -81920.00   97091.76
56       2024-01-01 -83333.33   -4826.67 -78506.67   92265.09
57       2024-02-01 -83333.33   -1413.33 -81920.00   90851.76
58       2024-03-01 -83333.33   -1413.33 -81920.00   89438.43
59       2024-04-01 -83333.33  -28720.00 -54613.33   60718.43
60       2024-05-01 -83333.33  -28720.00 -54613.33   31998.43

Body:
yea...finally i think a lot and i got output.

Code:

Interest_Rate = 0.10
    Years = 5
    Payments_Year = 12
    Principal = 200000

    start_date = (date(2019, 5, 28))

    pmt = np.pmt(Interest_Rate / Payments_Year, Years * Payments_Year, Principal)
    per = 1

    ipmt = np.ipmt(Interest_Rate / Payments_Year, per, Years * Payments_Year, Principal)

    ppmt = np.ppmt(Interest_Rate / Payments_Year, per, Years * Payments_Year, Principal)

    rng = pd.date_range(start_date, periods=Years * Payments_Year, freq='MS')
    rng.name = "Payment_Date"

    df = pd.DataFrame(index=rng, columns=['Payment', 'Principal', 'Interest', 'Balance'],
                      dtype='float')
    df.reset_index(inplace=True)
    df.index += 1
    df.index.name = "Period"
    print(df.index)
    df["Payment"] = np.pmt(Interest_Rate / Payments_Year, Years * Payments_Year, Principal)
    df["Principal"] = np.ppmt(Interest_Rate / Payments_Year, df.index, Years * Payments_Year, Principal)
    df["Interest"] = np.ipmt(Interest_Rate / Payments_Year, df.index, Years * Payments_Year, Principal)

    df = df.round(2)

    df["Balance"] = 0
    df.loc[1, "Balance"] = Principal + df.loc[1, "Principal"]

    for i in range(2, len(df) + 1):
        prev_balance = df.ix[i - 1, 'Balance']
        principal = df.ix[i, 'Principal']

        if prev_balance == 0:
            df.ix[i, ['Payment', 'Principal', 'Interest', 'Balance']] = 0
            continue

        if abs(principal) <= prev_balance:
            df.ix[i, 'Balance'] = principal + prev_balance
        else:

            if prev_balance <= abs(principal):
                principal = -prev_balance
                addl_principal = 0
            else:
                print('else')
            df.ix[i, 'Balance'] = 0
            df.ix[i, 'Principal'] = principal
            df.ix[i, "Payment"] = principal + df.ix[i, "Interest"]

    df = df.round(2)
    print(df)


问:
TextField uppercase and lowercase validation
I am working on textfields validations and getting confused how to validate textfield must contain at least 1 character from all of the following categories:
English uppercase characters (A - Z).
English lowercase characters (a - z).</p>

答:
```<code>func isValidPassword(testStr:String?) -> Bool {
    guard testStr != nil else { return false }

    // at least one uppercase,
    // at least one lowercase
    // 8 characters total
    let passwordTest = NSPredicate(format: "SELF MATCHES %@", "(?=.*[A-Z])(?=.*[a-z]).{8,}")
    return passwordTest.evaluate(with: testStr)
}
</code>```


问:
Disable single ALT type to activate the menu
I'm trying to disable the default behavior of the ALT key in Windows Look and Feel when a JTextArea is focused and the frame has a JMenu installed. What happens by default is that the menu gets the keyboard focus and therefore you can't continue typing there.

My first attempt was to capture single ALT presses by adding the key to the JTextArea InputMap:

//Disable ALT key presses when the textarea is focused
jta.getInputMap(javax.swing.JComponent.WHEN_FOCUSED).put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ALT, 0, true), "ALTKEY");
jta.getActionMap().put("ALTKEY", new javax.swing.AbstractAction() {
    private static final long serialVersionUID = 1L;
    @Override
    public void actionPerformed(java.awt.event.ActionEvent e) {
        System.out.println("Performed");
    }
});
```

<p>I noticed this worked as expected in some third party VMs but not in the latest from Oracle 1.8.0_211</p>

<p>Then I tried using key listeners from the AWT component and consume the event before it reaches other components.</p>

<pre class="lang-java prettyprint-override"><code>//Disable ALT key presses when the textarea is focused, second attempt
jta.addKeyListener(new java.awt.event.KeyListener(){
    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == java.awt.event.KeyEvent.VK_ALT){
            System.out.println("Pressed");
            e.consume();
        }
    }
    @Override
    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode() == java.awt.event.KeyEvent.VK_ALT){
            System.out.println("Released");
            e.consume();
        }
    }
    @Override
    public void keyTyped(KeyEvent e) {
        if(e.getKeyCode() == java.awt.event.KeyEvent.VK_ALT){
            System.out.println("Typed");
            e.consume();
        }
    }
});
</code>```

No luck.

Finally, I tried to change the key used to create the menu shortcuts and get completely rid of that annoying ALT behavior:

//Disable the ALT for the Mnemonic and put CTRL:
int[] ints = {java.awt.event.KeyEvent.CTRL_MASK};
javax.swing.UIManager.put("Menu.shortcutKeys", ints);
```

<p>This avoided the use of shortcuts with ALT key (and CTRL worked perfectly), but didn't prevent the standard behavior when a single ALT press is done.</p>

<p>Changing the L&F to other platforms, or not setting it to the Windows one solves the problem, but of course, it changes the look of the whole Program.</p>

<p>I guess I'm doing something wrong, but changing the InputMap or adding the KeyListeners worked for a third party VM, so I'm starting to think this might be a bug.</p>

<p><strong>Any ideas on how to find who is listening to ALT key presses and avoid it?
Is there a way to customize the L&F or see what is its configuration?</strong></p>

<p>Here is the complete code of the test:</p>

<pre class="lang-java prettyprint-override"><code>public class JMenubarAltTest extends javax.swing.JFrame{
    private static final long serialVersionUID = 1L;

    public JMenubarAltTest(){
        super();

        //Disable the ALT for the Mnemonic and put CTRL key instead:
        int[] ints = {java.awt.event.KeyEvent.CTRL_MASK};
        javax.swing.UIManager.put("Menu.shortcutKeys", ints);

        //Put the platform L&F, in my case I need this to work in Windows
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException e1) {
            e1.printStackTrace();
        }

        this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);

        //Create a random menu with some random items
        javax.swing.JMenuBar jmb = new javax.swing.JMenuBar();
        javax.swing.JMenu jm1 = new javax.swing.JMenu("menu1");
        jm1.setMnemonic(java.awt.event.KeyEvent.VK_M);
        jm1.add(new javax.swing.JMenuItem("item1"));
        jm1.add(new javax.swing.JMenuItem("item2"));
        jm1.add(new javax.swing.JMenuItem("item3"));

        javax.swing.JMenu jm2 = new javax.swing.JMenu("menu1");
        jm2.setMnemonic(java.awt.event.KeyEvent.VK_E);
        jm2.add(new javax.swing.JMenuItem("item1"));
        jm2.add(new javax.swing.JMenuItem("item2"));
        jm2.add(new javax.swing.JMenuItem("item3"));

        jmb.add(jm1);
        jmb.add(jm2);
        this.setJMenuBar(jmb);

        //Get a JTextArea to show what happens with the focus
        javax.swing.JTextArea jta = new javax.swing.JTextArea();

        //Disable ALT key presses when the textarea is focused
        jta.getInputMap(javax.swing.JComponent.WHEN_FOCUSED).put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ALT, 0, true), "ALTKEY");
        jta.getActionMap().put("ALTKEY", new javax.swing.AbstractAction() {
            private static final long serialVersionUID = 1L;
            @Override
            public void actionPerformed(java.awt.event.ActionEvent e) {
                System.out.println("Performed");
            }
        });

        //Disable ALT key presses when the textarea is focused, second attempt
        jta.addKeyListener(new java.awt.event.KeyListener(){
            @Override
            public void keyPressed(java.awt.event.KeyEvent e) {
                if(e.getKeyCode() == java.awt.event.KeyEvent.VK_ALT){
                    System.out.println("Pressed");
                    e.consume();
                }
            }
            @Override
            public void keyReleased(java.awt.event.KeyEvent e) {
                if(e.getKeyCode() == java.awt.event.KeyEvent.VK_ALT){
                    System.out.println("Released");
                    e.consume();
                }
            }
            @Override
            public void keyTyped(java.awt.event.KeyEvent e) {
                if(e.getKeyCode() == java.awt.event.KeyEvent.VK_ALT){
                    System.out.println("Typed");
                    e.consume();
                }
            }
        });

        this.getContentPane().add(jta);
        this.pack();
        this.setSize(200, 200);
        this.setVisible(true);
    }

    public static void main(java.lang.String[] args){
        new JMenubarAltTest();
    }
}

</code>```

答:
Unfortunatelly the alt processor in Windows L&F for some reasons ignores the consumed flag. So we need to remove it using reflection API.

```<code>import java.awt.BorderLayout;
import java.awt.KeyEventPostProcessor;
import java.awt.KeyboardFocusManager;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.lang.reflect.Method;
import java.util.List;

import javax.swing.JScrollPane;
import javax.swing.JTextField;

public class JMenubarAltTest extends javax.swing.JFrame {
    private static final long serialVersionUID = 1L;

    private KeyEventPostProcessor altPostprocessor;

    public JMenubarAltTest() {
        super();

        // Disable the ALT for the Mnemonic and put CTRL key instead:
        int[] ints = {java.awt.event.KeyEvent.CTRL_MASK};
        javax.swing.UIManager.put("Menu.shortcutKeys", ints);

        // Put the platform L&F, in my case I need this to work in Windows
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | javax.swing.UnsupportedLookAndFeelException e1) {
            e1.printStackTrace();
        }

        this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);

        // Create a random menu with some random items
        javax.swing.JMenuBar jmb = new javax.swing.JMenuBar();
        javax.swing.JMenu jm1 = new javax.swing.JMenu("menu1");
        jm1.setMnemonic(java.awt.event.KeyEvent.VK_M);
        jm1.add(new javax.swing.JMenuItem("item1"));
        jm1.add(new javax.swing.JMenuItem("item2"));
        jm1.add(new javax.swing.JMenuItem("item3"));

        javax.swing.JMenu jm2 = new javax.swing.JMenu("menu1");
        jm2.setMnemonic(java.awt.event.KeyEvent.VK_E);
        jm2.add(new javax.swing.JMenuItem("item1"));
        jm2.add(new javax.swing.JMenuItem("item2"));
        jm2.add(new javax.swing.JMenuItem("item3"));

        jmb.add(jm1);
        jmb.add(jm2);
        this.setJMenuBar(jmb);

        // Get a JTextArea to show what happens with the focus
        javax.swing.JTextArea jta = new javax.swing.JTextArea();

        // Disable ALT key presses when the textarea is focused
        jta.addFocusListener(new FocusListener() {

            @Override
            public void focusLost(FocusEvent e) {
                addAltPostprocessor();
            }

            @Override
            public void focusGained(FocusEvent e) {
                removeAltProcessor();
            }
        });

        this.getContentPane().add(new JScrollPane(jta));
        this.getContentPane().add(new JTextField(), BorderLayout.SOUTH);
        this.setSize(400, 300);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    // use reflection to remove the Windows L&F ALT processor.
    private void removeAltProcessor() {
        if (altPostprocessor == null) {
            try {
                Method method = KeyboardFocusManager.class.getDeclaredMethod("getKeyEventPostProcessors");
                method.setAccessible(true);
                @SuppressWarnings("unchecked")
                List<KeyEventPostProcessor> list =
                        (List<KeyEventPostProcessor>) method.invoke(KeyboardFocusManager.getCurrentKeyboardFocusManager());
                for (KeyEventPostProcessor pp : list) {
                    if (pp.getClass().getName().contains("WindowsRootPaneUI")) {
                        KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventPostProcessor(pp);
                        altPostprocessor = pp;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventPostProcessor(altPostprocessor);
        }
    }

    private void addAltPostprocessor() {
        if (altPostprocessor != null) {
            KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventPostProcessor(altPostprocessor);
        }
    }

    public static void main(java.lang.String[] args) {
        new JMenubarAltTest();
    }
}
</code>```

In this example ALT processing is disabled when text area is focused. For text field is alt processing still enabled.

Body:
I'm trying to disable the default behavior of the ALT key in Windows Look and Feel when a JTextArea is focused and the frame has a JMenu installed. What happens by default is that the menu gets the keyboard focus and therefore you can't continue typing there.

My first attempt was to capture single ALT presses by adding the key to the JTextArea InputMap:

//Disable ALT key presses when the textarea is focused
jta.getInputMap(javax.swing.JComponent.WHEN_FOCUSED).put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ALT, 0, true), "ALTKEY");
jta.getActionMap().put("ALTKEY", new javax.swing.AbstractAction() {
    private static final long serialVersionUID = 1L;
    @Override
    public void actionPerformed(java.awt.event.ActionEvent e) {
        System.out.println("Performed");
    }
});

I noticed this worked as expected in some third party VMs but not in the latest from Oracle 1.8.0_211

Then I tried using key listeners from the AWT component and consume the event before it reaches other components.

//Disable ALT key presses when the textarea is focused, second attempt
jta.addKeyListener(new java.awt.event.KeyListener(){
    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == java.awt.event.KeyEvent.VK_ALT){
            System.out.println("Pressed");
            e.consume();
        }
    }
    @Override
    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode() == java.awt.event.KeyEvent.VK_ALT){
            System.out.println("Released");
            e.consume();
        }
    }
    @Override
    public void keyTyped(KeyEvent e) {
        if(e.getKeyCode() == java.awt.event.KeyEvent.VK_ALT){
            System.out.println("Typed");
            e.consume();
        }
    }
});

No luck.

Finally, I tried to change the key used to create the menu shortcuts and get completely rid of that annoying ALT behavior:

//Disable the ALT for the Mnemonic and put CTRL:
int[] ints = {java.awt.event.KeyEvent.CTRL_MASK};
javax.swing.UIManager.put("Menu.shortcutKeys", ints);

This avoided the use of shortcuts with ALT key (and CTRL worked perfectly), but didn't prevent the standard behavior when a single ALT press is done.

Changing the L&F to other platforms, or not setting it to the Windows one solves the problem, but of course, it changes the look of the whole Program.

I guess I'm doing something wrong, but changing the InputMap or adding the KeyListeners worked for a third party VM, so I'm starting to think this might be a bug.

Any ideas on how to find who is listening to ALT key presses and avoid it?
Is there a way to customize the L&F or see what is its configuration?

Here is the complete code of the test:

public class JMenubarAltTest extends javax.swing.JFrame{
    private static final long serialVersionUID = 1L;

    public JMenubarAltTest(){
        super();

        //Disable the ALT for the Mnemonic and put CTRL key instead:
        int[] ints = {java.awt.event.KeyEvent.CTRL_MASK};
        javax.swing.UIManager.put("Menu.shortcutKeys", ints);

        //Put the platform L&F, in my case I need this to work in Windows
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException e1) {
            e1.printStackTrace();
        }

        this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);

        //Create a random menu with some random items
        javax.swing.JMenuBar jmb = new javax.swing.JMenuBar();
        javax.swing.JMenu jm1 = new javax.swing.JMenu("menu1");
        jm1.setMnemonic(java.awt.event.KeyEvent.VK_M);
        jm1.add(new javax.swing.JMenuItem("item1"));
        jm1.add(new javax.swing.JMenuItem("item2"));
        jm1.add(new javax.swing.JMenuItem("item3"));

        javax.swing.JMenu jm2 = new javax.swing.JMenu("menu1");
        jm2.setMnemonic(java.awt.event.KeyEvent.VK_E);
        jm2.add(new javax.swing.JMenuItem("item1"));
        jm2.add(new javax.swing.JMenuItem("item2"));
        jm2.add(new javax.swing.JMenuItem("item3"));

        jmb.add(jm1);
        jmb.add(jm2);
        this.setJMenuBar(jmb);

        //Get a JTextArea to show what happens with the focus
        javax.swing.JTextArea jta = new javax.swing.JTextArea();

        //Disable ALT key presses when the textarea is focused
        jta.getInputMap(javax.swing.JComponent.WHEN_FOCUSED).put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ALT, 0, true), "ALTKEY");
        jta.getActionMap().put("ALTKEY", new javax.swing.AbstractAction() {
            private static final long serialVersionUID = 1L;
            @Override
            public void actionPerformed(java.awt.event.ActionEvent e) {
                System.out.println("Performed");
            }
        });

        //Disable ALT key presses when the textarea is focused, second attempt
        jta.addKeyListener(new java.awt.event.KeyListener(){
            @Override
            public void keyPressed(java.awt.event.KeyEvent e) {
                if(e.getKeyCode() == java.awt.event.KeyEvent.VK_ALT){
                    System.out.println("Pressed");
                    e.consume();
                }
            }
            @Override
            public void keyReleased(java.awt.event.KeyEvent e) {
                if(e.getKeyCode() == java.awt.event.KeyEvent.VK_ALT){
                    System.out.println("Released");
                    e.consume();
                }
            }
            @Override
            public void keyTyped(java.awt.event.KeyEvent e) {
                if(e.getKeyCode() == java.awt.event.KeyEvent.VK_ALT){
                    System.out.println("Typed");
                    e.consume();
                }
            }
        });

        this.getContentPane().add(jta);
        this.pack();
        this.setSize(200, 200);
        this.setVisible(true);
    }

    public static void main(java.lang.String[] args){
        new JMenubarAltTest();
    }
}

Body:
Unfortunatelly the alt processor in Windows L&F for some reasons ignores the consumed flag. So we need to remove it using reflection API.

import java.awt.BorderLayout;
import java.awt.KeyEventPostProcessor;
import java.awt.KeyboardFocusManager;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.lang.reflect.Method;
import java.util.List;

import javax.swing.JScrollPane;
import javax.swing.JTextField;

public class JMenubarAltTest extends javax.swing.JFrame {
    private static final long serialVersionUID = 1L;

    private KeyEventPostProcessor altPostprocessor;

    public JMenubarAltTest() {
        super();

        // Disable the ALT for the Mnemonic and put CTRL key instead:
        int[] ints = {java.awt.event.KeyEvent.CTRL_MASK};
        javax.swing.UIManager.put("Menu.shortcutKeys", ints);

        // Put the platform L&F, in my case I need this to work in Windows
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | javax.swing.UnsupportedLookAndFeelException e1) {
            e1.printStackTrace();
        }

        this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);

        // Create a random menu with some random items
        javax.swing.JMenuBar jmb = new javax.swing.JMenuBar();
        javax.swing.JMenu jm1 = new javax.swing.JMenu("menu1");
        jm1.setMnemonic(java.awt.event.KeyEvent.VK_M);
        jm1.add(new javax.swing.JMenuItem("item1"));
        jm1.add(new javax.swing.JMenuItem("item2"));
        jm1.add(new javax.swing.JMenuItem("item3"));

        javax.swing.JMenu jm2 = new javax.swing.JMenu("menu1");
        jm2.setMnemonic(java.awt.event.KeyEvent.VK_E);
        jm2.add(new javax.swing.JMenuItem("item1"));
        jm2.add(new javax.swing.JMenuItem("item2"));
        jm2.add(new javax.swing.JMenuItem("item3"));

        jmb.add(jm1);
        jmb.add(jm2);
        this.setJMenuBar(jmb);

        // Get a JTextArea to show what happens with the focus
        javax.swing.JTextArea jta = new javax.swing.JTextArea();

        // Disable ALT key presses when the textarea is focused
        jta.addFocusListener(new FocusListener() {

            @Override
            public void focusLost(FocusEvent e) {
                addAltPostprocessor();
            }

            @Override
            public void focusGained(FocusEvent e) {
                removeAltProcessor();
            }
        });

        this.getContentPane().add(new JScrollPane(jta));
        this.getContentPane().add(new JTextField(), BorderLayout.SOUTH);
        this.setSize(400, 300);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    // use reflection to remove the Windows L&F ALT processor.
    private void removeAltProcessor() {
        if (altPostprocessor == null) {
            try {
                Method method = KeyboardFocusManager.class.getDeclaredMethod("getKeyEventPostProcessors");
                method.setAccessible(true);
                @SuppressWarnings("unchecked")
                List<KeyEventPostProcessor> list =
                        (List<KeyEventPostProcessor>) method.invoke(KeyboardFocusManager.getCurrentKeyboardFocusManager());
                for (KeyEventPostProcessor pp : list) {
                    if (pp.getClass().getName().contains("WindowsRootPaneUI")) {
                        KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventPostProcessor(pp);
                        altPostprocessor = pp;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventPostProcessor(altPostprocessor);
        }
    }

    private void addAltPostprocessor() {
        if (altPostprocessor != null) {
            KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventPostProcessor(altPostprocessor);
        }
    }

    public static void main(java.lang.String[] args) {
        new JMenubarAltTest();
    }
}

In this example ALT processing is disabled when text area is focused. For text field is alt processing still enabled.


问:
Passing the attached data frame to a function
I am working on a function that combines information about a particular variable with some basic information about the data frame it comes from. Here is an example of what I'm talking about:

```<code>fcn <- function(var,data) {
  return(ncol(data)*mean(var))
}

df <- data.frame(a=1:10,b=1:10)

df %>% dplyr::mutate(c=fcn(a,df))
</code>```

This works fine! However, it would be really neat if, in cases where the function is used with with or inside a dplyr verb, I can just nab the data frame/tibble object without it being explicitly passed. So ideally something like

```<code>fcn <- function(var,data=attached_data_object) {
  return(ncol(data)*mean(var))
}

df <- data.frame(a=1:10,b=1:10)

df %>% dplyr::mutate(c=fcn(a))
</code>```

I've been reading up on the various environment functions - seems like I should be able to reach into the environment that with/dplyr creates from the data frame and pluck the whole thing out wholesale. As of yet I have been unable to figure out how to make this happen. Any tips appreciated! Thank you.

答:
(With apologies to Hadley if I get terms slightly wrong). You might find the chapters on Environments and NSE (non-standard evaluation) from Advanced R useful.

Within dplyr verbs, such as mutate, the dataframe/tibble being manipulated is called ".". Hence the "." in another answer here to refer to the dataframe. The dplyr verbs automatically look in "." for the specified column name. When you call a function from within mutate(), as you are doing here, you are wanting to access this object called "." that lives in the execution environment of your function. So how do we do that?

```<code>fcn <- function(var) {
  dat <- get(".", env=parent.frame())
  return(ncol(dat) * mean(var))
}

notacol <- 8
df <- data.frame(a=1:10, b=seq(10, 100, 10))
df
    a   b
1   1  10
2   2  20
3   3  30
4   4  40
5   5  50
6   6  60
7   7  70
8   8  80
9   9  90
10 10 100

df %>% mutate(c = fcn(a), d = fcn(b), e = fcn(notacol))
    a   b  c   d  e
1   1  10 11 110 16
2   2  20 11 110 16
3   3  30 11 110 16
4   4  40 11 110 16
5   5  50 11 110 16
6   6  60 11 110 16
7   7  70 11 110 16
8   8  80 11 110 16
9   9  90 11 110 16
10 10 100 11 110 16
</code>```

I think this is the behaviour you were after. Note that notacol isn't found in the execution environment as it isn't in the dataframe, but the Global Env is on the search path so it's found there.

Body:
I am working on a function that combines information about a particular variable with some basic information about the data frame it comes from. Here is an example of what I'm talking about:

fcn <- function(var,data) {
  return(ncol(data)*mean(var))
}

df <- data.frame(a=1:10,b=1:10)

df %>% dplyr::mutate(c=fcn(a,df))

This works fine! However, it would be really neat if, in cases where the function is used with with or inside a dplyr verb, I can just nab the data frame/tibble object without it being explicitly passed. So ideally something like

fcn <- function(var,data=attached_data_object) {
  return(ncol(data)*mean(var))
}

df <- data.frame(a=1:10,b=1:10)

df %>% dplyr::mutate(c=fcn(a))

I've been reading up on the various environment functions - seems like I should be able to reach into the environment that with/dplyr creates from the data frame and pluck the whole thing out wholesale. As of yet I have been unable to figure out how to make this happen. Any tips appreciated! Thank you.

Body:
(With apologies to Hadley if I get terms slightly wrong). You might find the chapters on Environments and NSE (non-standard evaluation) from Advanced R useful.

Within dplyr verbs, such as mutate, the dataframe/tibble being manipulated is called ".". Hence the "." in another answer here to refer to the dataframe. The dplyr verbs automatically look in "." for the specified column name. When you call a function from within mutate(), as you are doing here, you are wanting to access this object called "." that lives in the execution environment of your function. So how do we do that?

fcn <- function(var) {
  dat <- get(".", env=parent.frame())
  return(ncol(dat) * mean(var))
}

notacol <- 8
df <- data.frame(a=1:10, b=seq(10, 100, 10))
df
    a   b
1   1  10
2   2  20
3   3  30
4   4  40
5   5  50
6   6  60
7   7  70
8   8  80
9   9  90
10 10 100

df %>% mutate(c = fcn(a), d = fcn(b), e = fcn(notacol))
    a   b  c   d  e
1   1  10 11 110 16
2   2  20 11 110 16
3   3  30 11 110 16
4   4  40 11 110 16
5   5  50 11 110 16
6   6  60 11 110 16
7   7  70 11 110 16
8   8  80 11 110 16
9   9  90 11 110 16
10 10 100 11 110 16

I think this is the behaviour you were after. Note that notacol isn't found in the execution environment as it isn't in the dataframe, but the Global Env is on the search path so it's found there.


问:
iloc'ing one level of a multiindex
I have multiindex dataframe, something like:

```<code>df = pd.DataFrame(index = pd.MultiIndex.from_product([['mike', 'matt', 'dave', 'frank', 'larry'], range(10)]))
df['foo']="bar"
df.index.names=['people', 'socket']
</code>```

What I'd like to do is iloc-slice all the rows associated with the first three people in the index.  IE: retrieve all the rows where people is either matt mike or dave.

As far as I can tell, though, this is not at all supported by pandas. Saw some gross levels-related hacks, but they didn't even work.  get_level_values(0) doesn't give distinct level values,  and levels() returns an unsorted frozenset.

edit:  I should have said  that .loc-based solutions won't work for me.

答:
Here you go:

```<code>df = pd.DataFrame(index = pd.MultiIndex.from_product([['mike', 'matt', 'dave', 'frank', 'larry'], range(10)], names=['people', 'socket']))
df['foo']="bar"
df.index.names=['people', 'socket']
# get rows
select_rows = df.loc[['mike', 'matt', 'dave']]
</code>```

Output:

```<code>people socket
mike   0       bar
       1       bar
       2       bar
       3       bar
       4       bar
       5       bar
       6       bar
       7       bar
       8       bar
       9       bar
matt   0       bar
       1       bar
       2       bar
       3       bar
       4       bar
       5       bar
       6       bar
       7       bar
       8       bar
       9       bar
dave   0       bar
       1       bar
       2       bar
       3       bar
       4       bar
       5       bar
       6       bar
       7       bar
       8       bar
       9       bar
</code>```

Title: iloc'ing one level of a multiindex

Body:
I have multiindex dataframe, something like:

df = pd.DataFrame(index = pd.MultiIndex.from_product([['mike', 'matt', 'dave', 'frank', 'larry'], range(10)]))
df['foo']="bar"
df.index.names=['people', 'socket']

What I'd like to do is iloc-slice all the rows associated with the first three people in the index.  IE: retrieve all the rows where people is either matt mike or dave.

As far as I can tell, though, this is not at all supported by pandas. Saw some gross levels-related hacks, but they didn't even work.  get_level_values(0) doesn't give distinct level values,  and levels() returns an unsorted frozenset.

edit:  I should have said  that .loc-based solutions won't work for me.

Body:
Here you go:

df = pd.DataFrame(index = pd.MultiIndex.from_product([['mike', 'matt', 'dave', 'frank', 'larry'], range(10)], names=['people', 'socket']))
df['foo']="bar"
df.index.names=['people', 'socket']
# get rows
select_rows = df.loc[['mike', 'matt', 'dave']]

Output:

people socket
mike   0       bar
       1       bar
       2       bar
       3       bar
       4       bar
       5       bar
       6       bar
       7       bar
       8       bar
       9       bar
matt   0       bar
       1       bar
       2       bar
       3       bar
       4       bar
       5       bar
       6       bar
       7       bar
       8       bar
       9       bar
dave   0       bar
       1       bar
       2       bar
       3       bar
       4       bar
       5       bar
       6       bar
       7       bar
       8       bar
       9       bar


问:
Print Html template in Angular 2 (ng-print in Angular 2)
I want to print HTML template in angular 2. I had explored about this I got solution in angularjs 1 Print Html Template in Angularjs 1 </p>

<p>Any suggestion would be appreciated </p>

答:
Windows applications usually come with build in print capability, but for a web application, I would choose to simply generate a PDF file.

The simplest way that I found is to generate a PDf file using PDFMake (www.pdfmake.org). You can then offer the user the choice to open or download the generated PDF file.

Body:
I want to print HTML template in angular 2. I had explored about this I got solution in angularjs 1 Print Html Template in Angularjs 1

Any suggestion would be appreciated


问:
collapsing toolbar layout won't collapse
I have a collapsing toolbar layout that has 2 issues with it:

1) it is static and does not collapse and I can't find the reason why

2) the last row in the recyclerview is being shown half way offscreen, I think it should be fixed one the collapsing is fixed?

XML code:

```<code>
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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="match_parent"
    tools:context=".Controllers.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/AppBarLayout"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_scrollFlags="scroll|snap|exitUntilCollapsed"
            app:contentScrim="@color/colorPrimary"
            app:title="Hero Title">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#000000" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Hero Title"
                android:textStyle="bold"
                android:textSize="20dp"
                android:textColor="#ffffff"/>

            <android.support.v7.widget.Toolbar
                android:layout_width="match_parent"
                android:layout_height="150dp"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Dark">

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/herosRecyclerView"
        android:layout_width="395dp"
        android:layout_height="715dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</android.support.design.widget.CoordinatorLayout>

</code>```

and here is an image of what I mean by half offscreen:

https://imgur.com/Fz8TmKK

答:
Please add this to your ImageView:</p>

```<code>app:layout_collapseMode="parallax"
</code>```

Body:
I have a collapsing toolbar layout that has 2 issues with it:

1) it is static and does not collapse and I can't find the reason why

2) the last row in the recyclerview is being shown half way offscreen, I think it should be fixed one the collapsing is fixed?

XML code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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="match_parent"
    tools:context=".Controllers.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/AppBarLayout"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_scrollFlags="scroll|snap|exitUntilCollapsed"
            app:contentScrim="@color/colorPrimary"
            app:title="Hero Title">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#000000" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Hero Title"
                android:textStyle="bold"
                android:textSize="20dp"
                android:textColor="#ffffff"/>

            <android.support.v7.widget.Toolbar
                android:layout_width="match_parent"
                android:layout_height="150dp"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Dark">

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/herosRecyclerView"
        android:layout_width="395dp"
        android:layout_height="715dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</android.support.design.widget.CoordinatorLayout>

and here is an image of what I mean by half offscreen:

https://imgur.com/Fz8TmKK

Body:
Please add this to your ImageView:

app:layout_collapseMode="parallax"


问:
Unable to display API call result to WebPage
I have react App.js page from where i am calling Django Rest API and i am getting response as an array now this array i have nested components and i want that nested component to be listed in my code.

If i can showcase single record given by single person name when i try to do with more than one i am getting following error.
Warning: Each child in an array or iterator should have a unique "key" prop.

Now if i change API URL as below
https://e2isaop.rokuapp.com/api/perns/1

I can able to view data in HTML but when it comes to all persons it fails.

I am sorry i am new react not sure how to iterate over sub array of result.
Kindly guide me here for best practice for this.

Here is API Response in JSON

```<code>{
    "count": 2,
    "next": null,
    "previous": null,
    "results": [
        {
            "uri": "/api/Persons/1",
            "PersonId": 1,
            "PersonName": "Nirav Joshi",
            "Person_Image": "https://ja.amazonaws.com/media/persons/None/51e1257926f3cb184089c41fa54b8f8e1b65a98f1e35d39e55f2b6b335e83cf4.jpg",
            "Person_sex": "M",
            "Person_BDate": "2019-04-19",
            "Person_CDate": "2019-04-23"
        },
        {
            "uri": "/api/Persons/2",
            "PersonId": 2,
            "PersonName": "New Joshi",
            "Person_Image": "https://ja.amazonaws.com/media/persons/None/cc08baaad2ccc918bc87e14cac01032bade23a0733b4e313088d61ee78d77d64.jpg",
            "Person_sex": "F",
            "Person_BDate": "2011-11-21",
            "Person_CDate": "2019-04-27"
        },

    ]
}
</code>```

Here is react App.js code.

```<code>import React from "react";
import ReactDOM from "react-dom";
import Persons from "./Persons";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      persons: []
    };
  }

  componentDidMount() {
    fetch("https://e2isen.okuapp.com/api/psons/")
      .then(response => response.json())
      .then(data => {
        let apipersons;
        if (data.isNull) {
          apipersons = [];
        } else {
          apipersons = [data];
          console.log(apipersons);
        }

        this.setState({ persons: apipersons });
      });
  }

  render() {
    return (
      <div>
        <h1>Welcome to PersonAPI</h1>
        <div>
          {this.state.persons.map(pers => {
            return (
              <Persons
                PersonName={pers.PersonName}
                key={pers.PersonId}
                Person_Image={pers.Person_Image}
                Person_BDate={pers.Person_BDate}
                Person_sex={pers.Person_sex}
              />
            );
          })}
        </div>
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));
</code>```

It should give me result for Four person with their details
PersonName
PersonImage
PersonBdate
PersonSex

答:
You should do :</p>

```<code>// apipersons = [data];
apipersons = data.results
</code>```

Body:
I have react App.js page from where i am calling Django Rest API and i am getting response as an array now this array i have nested components and i want that nested component to be listed in my code.

If i can showcase single record given by single person name when i try to do with more than one i am getting following error.
Warning: Each child in an array or iterator should have a unique "key" prop.

Now if i change API URL as below
https://e2isaop.rokuapp.com/api/perns/1

I can able to view data in HTML but when it comes to all persons it fails.

I am sorry i am new react not sure how to iterate over sub array of result.
Kindly guide me here for best practice for this.

Here is API Response in JSON

{
    "count": 2,
    "next": null,
    "previous": null,
    "results": [
        {
            "uri": "/api/Persons/1",
            "PersonId": 1,
            "PersonName": "Nirav Joshi",
            "Person_Image": "https://ja.amazonaws.com/media/persons/None/51e1257926f3cb184089c41fa54b8f8e1b65a98f1e35d39e55f2b6b335e83cf4.jpg",
            "Person_sex": "M",
            "Person_BDate": "2019-04-19",
            "Person_CDate": "2019-04-23"
        },
        {
            "uri": "/api/Persons/2",
            "PersonId": 2,
            "PersonName": "New Joshi",
            "Person_Image": "https://ja.amazonaws.com/media/persons/None/cc08baaad2ccc918bc87e14cac01032bade23a0733b4e313088d61ee78d77d64.jpg",
            "Person_sex": "F",
            "Person_BDate": "2011-11-21",
            "Person_CDate": "2019-04-27"
        },

    ]
}

Here is react App.js code.

import React from "react";
import ReactDOM from "react-dom";
import Persons from "./Persons";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      persons: []
    };
  }

  componentDidMount() {
    fetch("https://e2isen.okuapp.com/api/psons/")
      .then(response => response.json())
      .then(data => {
        let apipersons;
        if (data.isNull) {
          apipersons = [];
        } else {
          apipersons = [data];
          console.log(apipersons);
        }

        this.setState({ persons: apipersons });
      });
  }

  render() {
    return (

Welcome to PersonAPI

          {this.state.persons.map(pers => {
            return (
              <Persons
                PersonName={pers.PersonName}
                key={pers.PersonId}
                Person_Image={pers.Person_Image}
                Person_BDate={pers.Person_BDate}
                Person_sex={pers.Person_sex}
              />
            );
          })}

    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));

It should give me result for Four person with their details
PersonName
PersonImage
PersonBdate
PersonSex

Body:
You should do :

// apipersons = [data];
apipersons = data.results


问:
React Drag & Drop Event propagation problem
I have a simple Drag & Drop setup. What's special is that there can be dropzones inside dropzones. My problem is, that whenever I drop something in my child component, the parent event gets fired as well but only under certain circumstances.

For example (this works, no event propagation):

```<code>export default class Folder extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dragActive: false
        };
    }

    onDragOver = (e) => {
        e.preventDefault();
        this.setState({ dragActive: true });
    }

    onDragLeave = () => {
        this.setState({ dragActive: false });
    }

    onDrop = (e) => {
        e.stopPropagation();
        alert("test");
    }

    render() {
        return (
            <div className="col-6 col-sm-4 col-md-3 col-lg-2 col-xl-8ths" onDragOver={this.onDragOver} onDragLeave={this.onDragLeave} onDrop={this.onDrop}>

            </div>
        );
    }
}
</code>```

The important part is this line here:

```<code>onDrop={this.onDrop}
</code>```

If my drop event is inside the same component everything works as expected.

As soon as I change the line to this:

```<code>onDrop={() => this.props.onDropFunction(event, this.props.folder.id)}
</code>```

The event propagation stops working. This is the onDrop function I am calling inside the parent:

```<code>onDrop = (e, folderId) => {
    e.stopPropagation();
    e.preventDefault();
    var files = this.fileListToArray(e.dataTransfer.files);
    this.setState({
        dragActive: false,
        uploadFiles: files
    }, () => {
        this.uploadFiles(folderId);
    });
}
</code>```

答:
```<code>onDrop={(event) => this.props.onDropFunction(event, this.props.folder.id)}
</code>```

<p>pass event like this and try </p>

Body:
I have a simple Drag & Drop setup. What's special is that there can be dropzones inside dropzones. My problem is, that whenever I drop something in my child component, the parent event gets fired as well but only under certain circumstances.

For example (this works, no event propagation):

export default class Folder extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dragActive: false
        };
    }

    onDragOver = (e) => {
        e.preventDefault();
        this.setState({ dragActive: true });
    }

    onDragLeave = () => {
        this.setState({ dragActive: false });
    }

    onDrop = (e) => {
        e.stopPropagation();
        alert("test");
    }

    render() {
        return (

        );
    }
}

The important part is this line here:

onDrop={this.onDrop}

If my drop event is inside the same component everything works as expected.

As soon as I change the line to this:

onDrop={() => this.props.onDropFunction(event, this.props.folder.id)}

The event propagation stops working. This is the onDrop function I am calling inside the parent:

onDrop = (e, folderId) => {
    e.stopPropagation();
    e.preventDefault();
    var files = this.fileListToArray(e.dataTransfer.files);
    this.setState({
        dragActive: false,
        uploadFiles: files
    }, () => {
        this.uploadFiles(folderId);
    });
}

Body:
onDrop={(event) => this.props.onDropFunction(event, this.props.folder.id)}

pass event like this and try