问:
Getline not reading from file correctly?
Working on a project where I need to fill a file with numbers and use a getline to read those numbers line by line and then display the total, average, max, and min from each line. Everything's in place except my getline doesn't seem to be working as the output for the total, average, etc, is always 0. Any help at all is appreciated. Thanks!</p>

```<code>#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ofstream myfile;
    myfile.open("file.txt");
    if(!myfile)
    {
        cout << "Unable to open file\n";
        return 0;
    }
    if(myfile.is_open())
    {
        myfile << "Numbers: \n";
        myfile << "90 63 84 52 21 93 77 46\n";
        myfile << "90 22 26 34 39 44 75 98\n";
        myfile << "28 28 85 57 28 33 66 100\n";
        myfile << "16 80 74 62 42 84 42 56\n";
        myfile << "85 44 76 97 16 64 80 14\n";
        myfile << "41 85 13 88 78 8 18 38\n";
        myfile << "53 49 71 79 75 57 93 62\n";

        fstream infile;
        infile.open("file.txt");
        int total, average, max=0, min=0, num;
        while(!infile.eof())
        {
            string line;
            getline(infile, line);
            int a, b, c, d, e, f, g, h, i;
            infile >> a >> b >> c >> d >> e >> f >> g >> h >> i;
            total = a+b+c+d+e+f+g+h+i;
            average = total/7;
            while(infile>>num)
            {
                max = num;
                min = num;
                if(max<num)
                {
                    max = num;
                }
                if(min > num)
                {
                    min = num;
                }
            }
            myfile << "                               TOTAL        AVERAGE      MAX      MIN\n";
            myfile << "90 63 84 52 21 93 77 46    " << total << "  " << average << "  " << max << "  " << min << endl;
            myfile << "90 22 26 34 39 44 75 98\n";
            myfile << "28 28 85 57 28 33 66 100\n";
            myfile << "16 80 74 62 42 84 42 56\n";
            myfile << "85 44 76 97 16 64 80 14\n";
            myfile << "41 85 13 88 78 8 18 38\n";
            myfile << "53 49 71 79 75 57 93 62\n";
        }
        infile.close();
    }
    myfile.close();
    return 0;
}
</code>```

答:
There are many problems with your code.

You are not closing myfile before opening infile (which should be a std::ifstream instead).  While not strictly an error, it is unusual.  If you are trying to modify the file while you are reading from it, that is not safe.  Write to a new file first, and then replace the old file with the new file when finished, if needed.

You are not doing any error handling on infile at all.

You are misusing eof().

Your reading of infile is just WAY off and makes no sense at all.  It needs to be completely re-written.

You are outputting 8 numbers per line, but you are reading in 9 numbers per line, and averaging 7 of them.

I think what you are trying to do is produce an output file where you display stats for each line of numbers.  If so, try something more like this:

```<code>#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;

int main()
{
    ofstream myfile("numbers.txt");
    if (!myfile)
    {
        cout << "Unable to create numbers file\n";
        return 0;
    }

    myfile << "90 63 84 52 21 93 77 46\n";
    myfile << "90 22 26 34 39 44 75 98\n";
    myfile << "28 28 85 57 28 33 66 100\n";
    myfile << "16 80 74 62 42 84 42 56\n";
    myfile << "85 44 76 97 16 64 80 14\n";
    myfile << "41 85 13 88 78 8 18 38\n";
    myfile << "53 49 71 79 75 57 93 62\n";
    myfile.close();

    ifstream infile("numbers.txt");
    if (!infile)
    {
        cout << "Unable to open numbers file\n";
        return 0;
    }

    myfile.open("output.txt");
    if (!myfile)
    {
        cout << "Unable to create output file\n";
        return 0;
    }

    myfile << "Numbers:                       TOTAL        AVERAGE      MAX      MIN\n";

    string line;
    while (getline(infile, line))
    {
        istringstream iss(line);
        ostringstream oss;

        int num, total = 0, count = 0, average = 0, max = 0, min = 0;

        if (iss >> num)
        {
            max = min = num;

            do
            {
                total += num;
                ++count;

                if (num > max)
                    max = num;

                if (num < min)
                    min = num;

                oss << num << ' ';
            }
            while (iss >> num);

            average = total / count;
        }

        myfile << left << setw(30) << setfill(' ') << oss.str() << " ";
        myfile << left << setw(12) << setfill(' ') << total << " ";
        myfile << left << setw(12) << setfill(' ') << average << " ";
        myfile << left << setw(8) << setfill(' ') << max << " ";
        myfile << min << endl;
    }

    infile.close();
    myfile.close();

    return 0;
}
</code>```

numbers.txt

```
90 63 84 52 21 93 77 46
90 22 26 34 39 44 75 98
28 28 85 57 28 33 66 100
16 80 74 62 42 84 42 56
85 44 76 97 16 64 80 14
41 85 13 88 78 8 18 38
53 49 71 79 75 57 93 62
```

output.txt

```
Numbers:                       TOTAL        AVERAGE      MAX      MIN
90 63 84 52 21 93 77 46        526          65           93       21
90 22 26 34 39 44 75 98        428          53           98       22
28 28 85 57 28 33 66 100       425          53           100      28
16 80 74 62 42 84 42 56        456          57           84       16
85 44 76 97 16 64 80 14        476          59           97       14
41 85 13 88 78 8 18 38         369          46           88       8
53 49 71 79 75 57 93 62        539          67           93       49
```

Alternatively, you can remove numbers.txt altogether if you use an in-memory array instead of a file:

```<code>#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;

const int numbers[7][8] = {
    {90, 63, 84, 52, 21, 93, 77, 46},
    {90, 22, 26, 34, 39, 44, 75, 98},
    {28, 28, 85, 57, 28, 33, 66, 100},
    {16, 80, 74, 62, 42, 84, 42, 56},
    {85, 44, 76, 97, 16, 64, 80, 14},
    {41, 85, 13, 88, 78, 8 , 18, 38},
    {53, 49, 71, 79, 75, 57, 93, 62}
};

int main()
{
    ofstream myfile("output.txt");
    if (!myfile)
    {
        cout << "Unable to create output file\n";
        return 0;
    }

    myfile << "Numbers:                       TOTAL        AVERAGE      MAX      MIN\n";

    for(int i = 0; i < 7; ++i)
    {
        int num = numbers[i][0];
        int total = num, max = num, min = num;

        ostringstream oss;
        oss << num << ' ';

        for(int j = 1; j < 8; ++j)
        {
            num = numbers[i][j];
            total += num;

            if (max < num)
                max = num;

            if (min > num)
                min = num;

            oss << num << ' ';
        }

        int average = total / 8;

        myfile << left << setw(30) << setfill(' ') << oss.str() << " ";
        myfile << left << setw(12) << setfill(' ') << total << " ";
        myfile << left << setw(12) << setfill(' ') << average << " ";
        myfile << left << setw(8) << setfill(' ') << max << " ";
        myfile << min << endl;
    }

    myfile.close();

    return 0;
}
</code>```

output.txt

```
Numbers:                       TOTAL        AVERAGE      MAX      MIN
90 63 84 52 21 93 77 46        526          65           93       21
90 22 26 34 39 44 75 98        428          53           98       22
28 28 85 57 28 33 66 100       425          53           100      28
16 80 74 62 42 84 42 56        456          57           84       16
85 44 76 97 16 64 80 14        476          59           97       14
41 85 13 88 78 8 18 38         369          46           88       8
53 49 71 79 75 57 93 62        539          67           93       49
```

Body:
Working on a project where I need to fill a file with numbers and use a getline to read those numbers line by line and then display the total, average, max, and min from each line. Everything's in place except my getline doesn't seem to be working as the output for the total, average, etc, is always 0. Any help at all is appreciated. Thanks!

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ofstream myfile;
    myfile.open("file.txt");
    if(!myfile)
    {
        cout << "Unable to open file\n";
        return 0;
    }
    if(myfile.is_open())
    {
        myfile << "Numbers: \n";
        myfile << "90 63 84 52 21 93 77 46\n";
        myfile << "90 22 26 34 39 44 75 98\n";
        myfile << "28 28 85 57 28 33 66 100\n";
        myfile << "16 80 74 62 42 84 42 56\n";
        myfile << "85 44 76 97 16 64 80 14\n";
        myfile << "41 85 13 88 78 8 18 38\n";
        myfile << "53 49 71 79 75 57 93 62\n";

        fstream infile;
        infile.open("file.txt");
        int total, average, max=0, min=0, num;
        while(!infile.eof())
        {
            string line;
            getline(infile, line);
            int a, b, c, d, e, f, g, h, i;
            infile >> a >> b >> c >> d >> e >> f >> g >> h >> i;
            total = a+b+c+d+e+f+g+h+i;
            average = total/7;
            while(infile>>num)
            {
                max = num;
                min = num;
                if(max<num)
                {
                    max = num;
                }
                if(min > num)
                {
                    min = num;
                }
            }
            myfile << "                               TOTAL        AVERAGE      MAX      MIN\n";
            myfile << "90 63 84 52 21 93 77 46    " << total << "  " << average << "  " << max << "  " << min << endl;
            myfile << "90 22 26 34 39 44 75 98\n";
            myfile << "28 28 85 57 28 33 66 100\n";
            myfile << "16 80 74 62 42 84 42 56\n";
            myfile << "85 44 76 97 16 64 80 14\n";
            myfile << "41 85 13 88 78 8 18 38\n";
            myfile << "53 49 71 79 75 57 93 62\n";
        }
        infile.close();
    }
    myfile.close();
    return 0;
}

Body:
There are many problems with your code.

You are not closing myfile before opening infile (which should be a std::ifstream instead).  While not strictly an error, it is unusual.  If you are trying to modify the file while you are reading from it, that is not safe.  Write to a new file first, and then replace the old file with the new file when finished, if needed.

You are not doing any error handling on infile at all.

You are misusing eof().

Your reading of infile is just WAY off and makes no sense at all.  It needs to be completely re-written.

You are outputting 8 numbers per line, but you are reading in 9 numbers per line, and averaging 7 of them.

I think what you are trying to do is produce an output file where you display stats for each line of numbers.  If so, try something more like this:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;

int main()
{
    ofstream myfile("numbers.txt");
    if (!myfile)
    {
        cout << "Unable to create numbers file\n";
        return 0;
    }

    myfile << "90 63 84 52 21 93 77 46\n";
    myfile << "90 22 26 34 39 44 75 98\n";
    myfile << "28 28 85 57 28 33 66 100\n";
    myfile << "16 80 74 62 42 84 42 56\n";
    myfile << "85 44 76 97 16 64 80 14\n";
    myfile << "41 85 13 88 78 8 18 38\n";
    myfile << "53 49 71 79 75 57 93 62\n";
    myfile.close();

    ifstream infile("numbers.txt");
    if (!infile)
    {
        cout << "Unable to open numbers file\n";
        return 0;
    }

    myfile.open("output.txt");
    if (!myfile)
    {
        cout << "Unable to create output file\n";
        return 0;
    }

    myfile << "Numbers:                       TOTAL        AVERAGE      MAX      MIN\n";

    string line;
    while (getline(infile, line))
    {
        istringstream iss(line);
        ostringstream oss;

        int num, total = 0, count = 0, average = 0, max = 0, min = 0;

        if (iss >> num)
        {
            max = min = num;

            do
            {
                total += num;
                ++count;

                if (num > max)
                    max = num;

                if (num < min)
                    min = num;

                oss << num << ' ';
            }
            while (iss >> num);

            average = total / count;
        }

        myfile << left << setw(30) << setfill(' ') << oss.str() << " ";
        myfile << left << setw(12) << setfill(' ') << total << " ";
        myfile << left << setw(12) << setfill(' ') << average << " ";
        myfile << left << setw(8) << setfill(' ') << max << " ";
        myfile << min << endl;
    }

    infile.close();
    myfile.close();

    return 0;
}

numbers.txt

90 63 84 52 21 93 77 46
90 22 26 34 39 44 75 98
28 28 85 57 28 33 66 100
16 80 74 62 42 84 42 56
85 44 76 97 16 64 80 14
41 85 13 88 78 8 18 38
53 49 71 79 75 57 93 62

output.txt

Numbers:                       TOTAL        AVERAGE      MAX      MIN
90 63 84 52 21 93 77 46        526          65           93       21
90 22 26 34 39 44 75 98        428          53           98       22
28 28 85 57 28 33 66 100       425          53           100      28
16 80 74 62 42 84 42 56        456          57           84       16
85 44 76 97 16 64 80 14        476          59           97       14
41 85 13 88 78 8 18 38         369          46           88       8
53 49 71 79 75 57 93 62        539          67           93       49

Alternatively, you can remove numbers.txt altogether if you use an in-memory array instead of a file:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;

const int numbers[7][8] = {
    {90, 63, 84, 52, 21, 93, 77, 46},
    {90, 22, 26, 34, 39, 44, 75, 98},
    {28, 28, 85, 57, 28, 33, 66, 100},
    {16, 80, 74, 62, 42, 84, 42, 56},
    {85, 44, 76, 97, 16, 64, 80, 14},
    {41, 85, 13, 88, 78, 8 , 18, 38},
    {53, 49, 71, 79, 75, 57, 93, 62}
};

int main()
{
    ofstream myfile("output.txt");
    if (!myfile)
    {
        cout << "Unable to create output file\n";
        return 0;
    }

    myfile << "Numbers:                       TOTAL        AVERAGE      MAX      MIN\n";

    for(int i = 0; i < 7; ++i)
    {
        int num = numbers[i][0];
        int total = num, max = num, min = num;

        ostringstream oss;
        oss << num << ' ';

        for(int j = 1; j < 8; ++j)
        {
            num = numbers[i][j];
            total += num;

            if (max < num)
                max = num;

            if (min > num)
                min = num;

            oss << num << ' ';
        }

        int average = total / 8;

        myfile << left << setw(30) << setfill(' ') << oss.str() << " ";
        myfile << left << setw(12) << setfill(' ') << total << " ";
        myfile << left << setw(12) << setfill(' ') << average << " ";
        myfile << left << setw(8) << setfill(' ') << max << " ";
        myfile << min << endl;
    }

    myfile.close();

    return 0;
}

output.txt

Numbers:                       TOTAL        AVERAGE      MAX      MIN
90 63 84 52 21 93 77 46        526          65           93       21
90 22 26 34 39 44 75 98        428          53           98       22
28 28 85 57 28 33 66 100       425          53           100      28
16 80 74 62 42 84 42 56        456          57           84       16
85 44 76 97 16 64 80 14        476          59           97       14
41 85 13 88 78 8 18 38         369          46           88       8
53 49 71 79 75 57 93 62        539          67           93       49


来源: stackexchange

问:
Dynamically Displaying Text with TextView (Android)
Basically what I want to do in my Android app is use TextView to display two different pieces of text at once. So in code, I want to be able to do something like this:

```<code>    LinearLayout ll = new LinearLayout(this);
    TextView text = new TextView(this);
    text.setTextColor(0xFF000000);
    text.setGravity(Gravity.CENTER_HORIZONTAL);
    text.setTextSize(20f);
    text.setText("Text1");
    text.setTextSize(14f);
    text.setColor(0xFF0000FF);
    text.setText("\nText2");
    ll.addView(text);
</code>```

To clarify, I am trying to display a black "Text1" and a blue "Text2" at once using only a single TextView. Obviously this doesn't work out using the code above. I've considered using a second TextView but that seems like a waste of effort and memory to me. I'm sure the brilliant minds here can come up with the best solution to this.

Thank you very much in advance for your time and your assistance.

答:
I think with the current version of the code, you can see only the latest text (Text2).
If you want to have multiple look and feel for two texts, I would suggest use 2 separate TextViews. It would add more flexibility.

If you are not going to change this UI code later, then you can consider Html.toHtml() in setText() call.

ContentLicense: CC BY-SA 2.5

Body:
Basically what I want to do in my Android app is use TextView to display two different pieces of text at once. So in code, I want to be able to do something like this:

    LinearLayout ll = new LinearLayout(this);
    TextView text = new TextView(this);
    text.setTextColor(0xFF000000);
    text.setGravity(Gravity.CENTER_HORIZONTAL);
    text.setTextSize(20f);
    text.setText("Text1");
    text.setTextSize(14f);
    text.setColor(0xFF0000FF);
    text.setText("\nText2");
    ll.addView(text);

To clarify, I am trying to display a black "Text1" and a blue "Text2" at once using only a single TextView. Obviously this doesn't work out using the code above. I've considered using a second TextView but that seems like a waste of effort and memory to me. I'm sure the brilliant minds here can come up with the best solution to this.

Thank you very much in advance for your time and your assistance.


问:
How to find points inside, where sphere intersects with cylinder in MATLAB?
I am trying to identify points of sphere that are inside union of both sphere and cylinder, I have generated random points in side a cylinder as below

```<code>pts = 3000;
r= 3*((rand(pts,1)).^(1/3));
theta = 2*pi*rand(pts,1);
x= r.*cos(theta);
y= r.*sin(theta);
z=50*rand(size(x));
</code>```

and generated random points inside a sphere as below

```<code>radius=10;
rvals = (2)*rand(pts,1)-(1);
elevation = asin(rvals);
azimuth = 2*pi*rand(pts,1);
radii =(rand(pts,1).^(1/3))*radius;
[point_x,point_y,point_z] = sph2cart(azimuth,elevation,radii);
</code>```

The result will be as below

I need to find sphere points that is in intersection with cylinder and cylinder points that are in intersection with sphere.

Is there any general method to identify points inside intersection of different volumes ??

Can anyone help me? Thanks in advance,
Manu

答:
Apparently, you have a sphere with center at (0, 0, 0) and radius 10. To check whether points of the cylinder are in the sphere, you can use:

```<code>cylinder_in_sphere = (x.^2 + y.^2 + z.^2) < 100
</code>```

Your cylinder has radius 3 and a height of 50, so to check whether points of the sphere are in the cylinder, you can use:

```<code>sphere_in_cylinder = ((points_x.^2 + points_y.^2) < 9) & (points_z >= 0) & (points_z < 50)
</code>```

Note that in this particular case points_z < 50 is always satisfied, so you can remove it in this particular case.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to identify points of sphere that are inside union of both sphere and cylinder, I have generated random points in side a cylinder as below

pts = 3000;
r= 3*((rand(pts,1)).^(1/3));
theta = 2*pi*rand(pts,1);
x= r.*cos(theta);
y= r.*sin(theta);
z=50*rand(size(x));

and generated random points inside a sphere as below

radius=10;
rvals = (2)*rand(pts,1)-(1);
elevation = asin(rvals);
azimuth = 2*pi*rand(pts,1);
radii =(rand(pts,1).^(1/3))*radius;
[point_x,point_y,point_z] = sph2cart(azimuth,elevation,radii);

The result will be as below

I need to find sphere points that is in intersection with cylinder and cylinder points that are in intersection with sphere.

Is there any general method to identify points inside intersection of different volumes ??

Can anyone help me? Thanks in advance,
Manu

Body:
Apparently, you have a sphere with center at (0, 0, 0) and radius 10. To check whether points of the cylinder are in the sphere, you can use:

cylinder_in_sphere = (x.^2 + y.^2 + z.^2) < 100

Your cylinder has radius 3 and a height of 50, so to check whether points of the sphere are in the cylinder, you can use:

sphere_in_cylinder = ((points_x.^2 + points_y.^2) < 9) & (points_z >= 0) & (points_z < 50)

Note that in this particular case points_z < 50 is always satisfied, so you can remove it in this particular case.


问:
Why can pointers be NULL
In C or C++, isn't NULL just the constant integer 0? Why are we allowed to assign some pointer to the value NULL if it a constant integer? Wouldn't a compiler say that the two types don't match? </p>

答:
There are two issues:

A type can have a "special", out-of-band, exceptional value.  For example, floating-point numbers have the value NaN.  And pointers have a special, not-a-valid-pointer value, the null pointer.

What's the name of the null pointer?  In C, for better or worse, its name is 0.  (It would avoid all kinds of confusion if its name were a separate keyword like null or nil, but that's not the way the language definition came out.)

But yes, you're right, the ability to assign the constant 0 to a pointer variable is a special case, enshrined in the language definition.

Title: Why can pointers be NULL


问:
Docker glide not found
Docker is not able to find glide, which was installed successfully in steps 3 and 4 (below). I ran

```<code>docker build .
</code>```

This is the first part of the Dockerfile:

```<code>FROM golang:latest as builder

# Set up workdir
WORKDIR /go/src/github.com/cayleygraph/cayley

# Restore vendored dependencies
RUN sh -c "curl https://glide.sh/get | sh"
COPY glide.* ./
RUN glide install
</code>```

But it failed on step 5 with this error:

```<code>docker build .
Sending build context to Docker daemon  65.18MB
Step 1/29 : FROM golang:latest as builder
 ---> 1a34fad76b34
Step 2/29 : WORKDIR /go/src/github.com/cayleygraph/cayley
 ---> Using cache
 ---> dd9a295edeed
Step 3/29 : RUN sh -c "curl https://glide.sh/get | sh"
 ---> Using cache
 ---> b432efdb0630
Step 4/29 : COPY glide.* ./
 ---> Using cache
 ---> 936b9f7837eb
Step 5/29 : RUN glide install
 ---> Running in b244dcff6576
/bin/sh: 1: glide: not found
The command '/bin/sh -c glide install' returned a non-zero code: 127
</code>```

Installing glide worked, not sure why it's not finding the actual executable though. Any ideas?

答:
Make glide executable as well, in the Dockerfile. And skip the / in your COPY statement. Try to add this before you try to run it.

```<code>RUN chmod +x <file>
</code>```

Seems like the install process only download the executable

Title: Docker glide not found

Body:
Docker is not able to find glide, which was installed successfully in steps 3 and 4 (below). I ran

docker build .

This is the first part of the Dockerfile:

FROM golang:latest as builder

# Set up workdir
WORKDIR /go/src/github.com/cayleygraph/cayley

# Restore vendored dependencies
RUN sh -c "curl https://glide.sh/get | sh"
COPY glide.* ./
RUN glide install

But it failed on step 5 with this error:

docker build .
Sending build context to Docker daemon  65.18MB
Step 1/29 : FROM golang:latest as builder
 ---> 1a34fad76b34
Step 2/29 : WORKDIR /go/src/github.com/cayleygraph/cayley
 ---> Using cache
 ---> dd9a295edeed
Step 3/29 : RUN sh -c "curl https://glide.sh/get | sh"
 ---> Using cache
 ---> b432efdb0630
Step 4/29 : COPY glide.* ./
 ---> Using cache
 ---> 936b9f7837eb
Step 5/29 : RUN glide install
 ---> Running in b244dcff6576
/bin/sh: 1: glide: not found
The command '/bin/sh -c glide install' returned a non-zero code: 127

Installing glide worked, not sure why it's not finding the actual executable though. Any ideas?

Body:
Make glide executable as well, in the Dockerfile. And skip the / in your COPY statement. Try to add this before you try to run it.

RUN chmod +x <file>

Seems like the install process only download the executable

ContentLicense: CC BY-SA 4.0


问:
Bootstrap - Why is my navbar background color being overwritten even when I specify it?
Why does my navbar both side have a white background color?

I used the developer tool to try and help me and the part that change it white was the navbar default. I try to change the css inside the developer tool using this and it work.

This is the part that I changed inside the developer tool:

```<code>.navbar-default {
    background-color: blue;
}
</code>```

I also tried to change in the app.css and change the navbar-default to blue but the problem is still occurring, and when I check inside the developer tool, the color code is white instead of the blue that I had just changed. But it works if I change it inside the developer tool.

I tried following this question, but it doesn't work as well:

Background color in navbar laravel.

My page consists of an HTML table, and I have used @extends to put the navbar inside this page. When I try doing it for other pages, the navbar works.

htmlTable.blade.php:

```<code>@extends('layouts.app')
@section('title', 'Summary')
    @section('content')
        <div class="container" style="background-color:#ADD8E8">
            //content of my html table
        </div>
    @endsection
</code>```

app.blade.php (navbar):

```<code><!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

   <title>@yield('title')</title>

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <link href="{{ asset('css/title.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-default navbar-static-top">
            <div class="container">
                <div class="navbar-header">

                    <!-- Collapsed Hamburger -->
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse" aria-expanded="false">
                        <span class="sr-only">Toggle Navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    @include('layouts.testSidebar')

                    <!-- Branding Image -->
                    <a class="navbar-brand" href="{{ url('/') }}" style="color: white">
                        @yield('title')
                    </a>
                </div>
                <div class="collapse navbar-collapse" id="app-navbar-collapse">
                    <!-- Left Side Of Navbar -->
                    <ul class="nav navbar-nav">

                    </ul>
                    <!-- Right Side Of Navbar -->
                    <ul class="nav navbar-nav navbar-right">
                        <!-- Authentication Links -->
                        @guest
                            <li><a href="{{ route('login') }}">Login</a></li>
                            <li><a href="{{ route('register') }}">Register</a></li>
                        @else
                            <li class="dropdown">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true" style="background-color:blue">
                                    <b style="color: white">{{ Auth::user()->name }}</b> <span class="caret"></span>
                                </a>

                                <ul class="dropdown-menu" style="background-color: blue">
                                    <li>
                                        <a href="{{ route('logout') }}"
                                            onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();" style="background-color: blue">
                                            <b style="color: white">Logout</b>
                                        </a>

                                        <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                            {{ csrf_field() }}
                                        </form>
                                    </li>
                                </ul>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        @yield('content')
    </div>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>

</body>
</html>
</code>```

test.css (this is the CSS that I used):

```<code>body{
    margin:0px;
    padding:0px;
    font-family:"Helvetica Neue", Helvetica, Arial;
}

#sidebar{
    background:blue;
    width:200px;
    height:100%;
    display:block;
    position:fixed;
    left:-200px;
    top:0px;
    transition:left 0.3s linear;
}

#sidebar.visible{
    left:0px;
    transition:left 0.3s linear;
}

ul{
    margin:0px;
    padding:0px;
}

ul li{
    list-style:none;
}

ul li a{
    background:#0000FF ;
    color:white;
    border-bottom:1px solid #111;
    display:block;
    width:180px;
    padding:10px;
    text-decoration: none;
}

#sidebar-btn{
    display:inline-block;
    vertical-align: middle;
    width:20px;
    height:15px;
    cursor:pointer;
    margin:20px;
    position:absolute;
    top:0px;
    right:-60px;
}

#sidebar-btn span{
    height:1px;
    background:white;
    margin-bottom:5px;
    display:block;
}

#sidebar-btn span:nth-child(2){
    width:75%;
}

#sidebar-btn span:nth-child(3){
    width:50%;
}

#navbar-toggle collapsed{
    background:#0000FF ;

}

.navbar {background:#0000FF ;}

 nav.sidebar .navbar-nav .open .dropdown-menu>li>a:hover, nav.sidebar .navbar-nav .open .dropdown-menu>li>a:focus {
    color: white;
    background-color: transparent;
}
.dropdown-menu {
    position: absolute;
    top: 0;
    left: 180px;
    min-width: 180px;
}
</code>```

This is what happens:

答:
change this:

```<code><div id="app">
    <nav class="navbar navbar-default navbar-static-top">
        <div class="container">
            <div class="navbar-header">
</code>```

to:

```<code><div id="app">
    <nav class="navbar navbar-default navbar-static-top">
        <div class="container-fluid">
            <div class="navbar-header">
</code>```

The container-fluid class is the one you want

Body:
Why does my navbar both side have a white background color?

I used the developer tool to try and help me and the part that change it white was the navbar default. I try to change the css inside the developer tool using this and it work.

This is the part that I changed inside the developer tool:

.navbar-default {
    background-color: blue;
}

I also tried to change in the app.css and change the navbar-default to blue but the problem is still occurring, and when I check inside the developer tool, the color code is white instead of the blue that I had just changed. But it works if I change it inside the developer tool.

I tried following this question, but it doesn't work as well:

Background color in navbar laravel.

My page consists of an HTML table, and I have used @extends to put the navbar inside this page. When I try doing it for other pages, the navbar works.

htmlTable.blade.php:

@extends('layouts.app')
@section('title', 'Summary')
    @section('content')

            //content of my html table

    @endsection

app.blade.php (navbar):

<!DOCTYPE html>
getLocale() }}">

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="csrf-token" content="{{ csrf_token() }}">

   <title>@yield('title')</title>

    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <link href="{{ asset('css/title.css') }}" rel="stylesheet">

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse" aria-expanded="false">
                        Toggle Navigation

                    </button>
                    @include('layouts.testSidebar')

                        @yield('title')

                        @guest

Login

Register

                        @else

                                    {{ Auth::user()->name }}

                                            Logout

                                        <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                            {{ csrf_field() }}
                                        </form>

                        @endguest

        @yield('content')

test.css (this is the CSS that I used):

body{
    margin:0px;
    padding:0px;
    font-family:"Helvetica Neue", Helvetica, Arial;
}

#sidebar{
    background:blue;
    width:200px;
    height:100%;
    display:block;
    position:fixed;
    left:-200px;
    top:0px;
    transition:left 0.3s linear;
}

#sidebar.visible{
    left:0px;
    transition:left 0.3s linear;
}

ul{
    margin:0px;
    padding:0px;
}

ul li{
    list-style:none;
}

ul li a{
    background:#0000FF ;
    color:white;
    border-bottom:1px solid #111;
    display:block;
    width:180px;
    padding:10px;
    text-decoration: none;
}

#sidebar-btn{
    display:inline-block;
    vertical-align: middle;
    width:20px;
    height:15px;
    cursor:pointer;
    margin:20px;
    position:absolute;
    top:0px;
    right:-60px;
}

#sidebar-btn span{
    height:1px;
    background:white;
    margin-bottom:5px;
    display:block;
}

#sidebar-btn span:nth-child(2){
    width:75%;
}

#sidebar-btn span:nth-child(3){
    width:50%;
}

#navbar-toggle collapsed{
    background:#0000FF ;

}

.navbar {background:#0000FF ;}

 nav.sidebar .navbar-nav .open .dropdown-menu>li>a:hover, nav.sidebar .navbar-nav .open .dropdown-menu>li>a:focus {
    color: white;
    background-color: transparent;
}
.dropdown-menu {
    position: absolute;
    top: 0;
    left: 180px;
    min-width: 180px;
}

This is what happens:

Body:
change this:

<div id="app">
    <nav class="navbar navbar-default navbar-static-top">
        <div class="container">
            <div class="navbar-header">

to:

<div id="app">
    <nav class="navbar navbar-default navbar-static-top">
        <div class="container-fluid">
            <div class="navbar-header">

The container-fluid class is the one you want


问:
Assessing variables outside scope of a function declaration
I have several functions that work together to accomplish one task. Each of those functions live in their own file. In my main file, I compose these functions to accomplish my task.

Because of this, many functions need access to the same variables. My initial approach was to declare these variables in my main file with the expectation that I could call them within my functions.

However, when I run them I get reference errors inside my functions. My current alternative includes passing these variables into each function but it doesn't seem too elegant. I also considered making a class but I run into the issue of not being able to separate the functions into different files (for organizational purposes).

```<code>// doSomething.ts
declare outerVariable

function doSomething() {
  console.log(outerVariable)
}

// main
import doSomething from './doSomething.ts'

let outerVariable = 5
doSomething() // Reference Error: outerVariable is not defined
</code>```

I don't think variable shadowing is an issue because I never create variables with those names in my functions.

Any idea on what's going on or a better way to structure the code?

答: Try es6 export const variable = somevalue

Body:
I have several functions that work together to accomplish one task. Each of those functions live in their own file. In my main file, I compose these functions to accomplish my task.

Because of this, many functions need access to the same variables. My initial approach was to declare these variables in my main file with the expectation that I could call them within my functions.

However, when I run them I get reference errors inside my functions. My current alternative includes passing these variables into each function but it doesn't seem too elegant. I also considered making a class but I run into the issue of not being able to separate the functions into different files (for organizational purposes).

// doSomething.ts
declare outerVariable

function doSomething() {
  console.log(outerVariable)
}

// main
import doSomething from './doSomething.ts'

let outerVariable = 5
doSomething() // Reference Error: outerVariable is not defined

I don't think variable shadowing is an issue because I never create variables with those names in my functions.

Any idea on what's going on or a better way to structure the code?


问:
Naming convention of v-model for Vuejs and Axios in a POST request (Issues encoding a Vue Object into JSON)
this is going to be super long winded!

Admittedly I am not a good frontend designer and my Javascript skills leave much to be improved upon.

TL:DR - How is the working code different from the JSON encoded data object (merchant) in the non-working code, in regards to the Axios POST request? Shouldn't they produce the same result?

Some background first: I am building a Laravel REST backend that is feature complete, form validators, policies, the works. I have tested the backend with the ARC REST client for Chrome and have verified my backend is fully functional.

The problem: While designing my frontend using Vuejs, Vue-Router and Axios, I am having issues POSTing data to my backend. Specifically it is failing form validation with an HTTP error 422. I have narrowed down this issue to be relating to object encapsulation in either Vue or Axios.

Here is the non-working Vue component:

```<code>    <div class="panel panel-default">
        <div class="panel-heading">Create Merchant</div>
        <div class="panel-body">
            <form action="#" @submit.prevent="createMerchant()">
                Primary
                <input v-model="merchant.primary" type="text" name="primary" class="form-control" autofocus>
                Alternate
                <input v-model="merchant.alternate" type="text" name="alternate" class="form-control">
                Contact
                <input v-model="merchant.contact" type="text" name="contact" class="form-control">
                Street
                <input v-model="merchant.street" type="text" name="street" class="form-control">
                City
                <input v-model="merchant.city" type="text" name="city" class="form-control">
                State
                <input v-model="merchant.state" type="text" name="state" class="form-control">
                Country
                <input v-model="merchant.country" type="text" name="country" class="form-control">
                Postal Code
                <input v-model="merchant.postalCode" type="text" name="postalCode" class="form-control">
                <button type="submit" class="btn btn-primary">Create Merchant</button>
            </form>
        </div>
    </div>

    <div v-if='errors && errors.length' class="panel panel-default">
        <div class="panel-heading">Error</div>
        <div class="panel-body">
            <ul>
                <li v-for='error of errors'>
                    {{error.message}}
                </li>
            </ul>
        </div>
    </div>

</div>
</template>

<script>
export default {
    data() {
        return {
            merchant: {
                primary: '',
                alternate: '',
                contact: '',
                street: '',
                city: '',
                state: '',
                country: '',
                postalCode: ''
            },
            errors: []
        };
    },

    methods: {
        createMerchant() { console.log(JSON.stringify(this.merchant));
            axios.post('/payment-gateway/public/api/v1/merchant', JSON.stringify(this.merchant))
            .then((response) => {
                console.log(response.data.id);
                this.$router.push({ name: 'merchantList' });
            })
            .catch(e => {
                this.errors.push(e);
            });
        }
    }
}
</script>
</code>```

The data being posted, from my point of view appears to be correct:

{"primary":"Widget Company","alternate":"Widget Co","contact":"555-555-0055","street":"123 Main St","city":"Olympia","state":"WA","country":"USA","postalCode":"98501"}

But the above code always results in a HTTP 422 error.

Now for the part that is confusing me, this is working code:

```<code>    <div class="panel panel-default">
        <div class="panel-heading">Create Merchant</div>
        <div class="panel-body">
            <form action="#" @submit.prevent="createMerchant()">
                Primary
                <input v-model="merchant.primary" type="text" name="primary" class="form-control" autofocus>
                Alternate
                <input v-model="merchant.alternate" type="text" name="alternate" class="form-control">
                Contact
                <input v-model="merchant.contact" type="text" name="contact" class="form-control">
                Street
                <input v-model="merchant.street" type="text" name="street" class="form-control">
                City
                <input v-model="merchant.city" type="text" name="city" class="form-control">
                State
                <input v-model="merchant.state" type="text" name="state" class="form-control">
                Country
                <input v-model="merchant.country" type="text" name="country" class="form-control">
                Postal Code
                <input v-model="merchant.postalCode" type="text" name="postalCode" class="form-control">
                <button type="submit" class="btn btn-primary">Create Merchant</button>
            </form>
        </div>
    </div>

    <div v-if='errors && errors.length' class="panel panel-default">
        <div class="panel-heading">Error</div>
        <div class="panel-body">
            <ul>
                <li v-for='error of errors'>
                    {{error.message}}
                </li>
            </ul>
        </div>
    </div>

</div>
</template>

<script>
export default {
    data() {
        return {
            merchant: {
                primary: '',
                alternate: '',
                contact: '',
                street: '',
                city: '',
                state: '',
                country: '',
                postalCode: ''
            },
            errors: []
        };
    },

    methods: {
        createMerchant() { console.log(JSON.stringify(this.merchant));
            axios.post('/payment-gateway/public/api/v1/merchant', {
                primary: this.merchant.primary,
                alternate: this.merchant.alternate,
                contact: this.merchant.contact,
                street: this.merchant.street,
                city: this.merchant.city,
                state: this.merchant.state,
                country: this.merchant.country,
                postalCode: this.merchant.postalCode
            })
            .then((response) => {
                console.log(response.data.id);
                this.$router.push({ name: 'merchantList' });
            })
            .catch(e => {
                this.errors.push(e);
            });
        }
    }
}
</script>
</code>```

So my question is, how is the working code different from the JSON encoded data object (merchant) in the non-working code?

答:
In one instance you're sending an object, in the other a string. Although they will both be transferred as a string eventually, when you pass the object, the ContentType is set under the hood to application/json.

That being said, if you set the ContentType to application/json for the one you're passing as a string, it will sort the issue.

Body:
this is going to be super long winded!

Admittedly I am not a good frontend designer and my Javascript skills leave much to be improved upon.

TL:DR - How is the working code different from the JSON encoded data object (merchant) in the non-working code, in regards to the Axios POST request? Shouldn't they produce the same result?

Some background first: I am building a Laravel REST backend that is feature complete, form validators, policies, the works. I have tested the backend with the ARC REST client for Chrome and have verified my backend is fully functional.

The problem: While designing my frontend using Vuejs, Vue-Router and Axios, I am having issues POSTing data to my backend. Specifically it is failing form validation with an HTTP error 422. I have narrowed down this issue to be relating to object encapsulation in either Vue or Axios.

Here is the non-working Vue component:

Create Merchant

            <form action="#" @submit.prevent="createMerchant()">
                Primary
                <input v-model="merchant.primary" type="text" name="primary" class="form-control" autofocus>
                Alternate
                <input v-model="merchant.alternate" type="text" name="alternate" class="form-control">
                Contact
                <input v-model="merchant.contact" type="text" name="contact" class="form-control">
                Street
                <input v-model="merchant.street" type="text" name="street" class="form-control">
                City
                <input v-model="merchant.city" type="text" name="city" class="form-control">
                State
                <input v-model="merchant.state" type="text" name="state" class="form-control">
                Country
                <input v-model="merchant.country" type="text" name="country" class="form-control">
                Postal Code
                <input v-model="merchant.postalCode" type="text" name="postalCode" class="form-control">
                <button type="submit" class="btn btn-primary">Create Merchant</button>
            </form>

Error

                    {{error.message}}

</template>

The data being posted, from my point of view appears to be correct:

{"primary":"Widget Company","alternate":"Widget Co","contact":"555-555-0055","street":"123 Main St","city":"Olympia","state":"WA","country":"USA","postalCode":"98501"}

But the above code always results in a HTTP 422 error.

Now for the part that is confusing me, this is working code:

Create Merchant

            <form action="#" @submit.prevent="createMerchant()">
                Primary
                <input v-model="merchant.primary" type="text" name="primary" class="form-control" autofocus>
                Alternate
                <input v-model="merchant.alternate" type="text" name="alternate" class="form-control">
                Contact
                <input v-model="merchant.contact" type="text" name="contact" class="form-control">
                Street
                <input v-model="merchant.street" type="text" name="street" class="form-control">
                City
                <input v-model="merchant.city" type="text" name="city" class="form-control">
                State
                <input v-model="merchant.state" type="text" name="state" class="form-control">
                Country
                <input v-model="merchant.country" type="text" name="country" class="form-control">
                Postal Code
                <input v-model="merchant.postalCode" type="text" name="postalCode" class="form-control">
                <button type="submit" class="btn btn-primary">Create Merchant</button>
            </form>

Error

                    {{error.message}}

</template>

So my question is, how is the working code different from the JSON encoded data object (merchant) in the non-working code?


问:
Join with Multiple Tables
I am getting a syntax error with the following problem and can't seem to figure out, hope you guys can help me!

I have these tables (they are populated):

I am trying to retrieve the first and last name of all the passengers scheduled in a certain flight number so what I have is this:

```<code>SELECT PassFName, PassLName
FROM Passenger
INNER JOIN PassID ON Passenger.PassID = Reservation.PassID
INNER JOIN FlightNum ON FlightNum.Reservation = FlightNum.ScheduledFlight
WHERE ScheduledFlight.FlightNum = [Enter Flight Number];
</code>```

However, I am getting error:

Not sure why and I have also noticed in the last line it is misspelling FlightNum.ScheduledFlight. Any idea what am I doing wrong?

Thank you!

答:
MS Access has a strange syntax for joins.  It requires parentheses around each JOIN pair.  So:

```<code>SELECT PassFName, PassLName
FROM (Passenger INNER JOIN
      Reservation
     ) ON Passenger.PassID = Reservation.PassID INNER JOIN
     FlightNum
     ON FlightNum.Reservation = FlightNum.ScheduledFlight
WHERE ScheduledFlight.FlightNum = [Enter Flight Number];
</code>```

Although other databases support this syntax, it is only required in MS Access.

Title: Join with Multiple Tables

Body:
I am getting a syntax error with the following problem and can't seem to figure out, hope you guys can help me!

I have these tables (they are populated):

I am trying to retrieve the first and last name of all the passengers scheduled in a certain flight number so what I have is this:

SELECT PassFName, PassLName
FROM Passenger
INNER JOIN PassID ON Passenger.PassID = Reservation.PassID
INNER JOIN FlightNum ON FlightNum.Reservation = FlightNum.ScheduledFlight
WHERE ScheduledFlight.FlightNum = [Enter Flight Number];

However, I am getting error:

Not sure why and I have also noticed in the last line it is misspelling FlightNum.ScheduledFlight. Any idea what am I doing wrong?

Thank you!

Body:
MS Access has a strange syntax for joins.  It requires parentheses around each JOIN pair.  So:

SELECT PassFName, PassLName
FROM (Passenger INNER JOIN
      Reservation
     ) ON Passenger.PassID = Reservation.PassID INNER JOIN
     FlightNum
     ON FlightNum.Reservation = FlightNum.ScheduledFlight
WHERE ScheduledFlight.FlightNum = [Enter Flight Number];

Although other databases support this syntax, it is only required in MS Access.


答:
For example, you could pass your variables into functions as arguments
Maybe it's worth considering reorganising them into a class, so they could access common class fields

It's generally good to decouple your code entities from each other, so passing them as arguments is better than declaring globals usually

Title: Assessing variables outside scope of a function declaration


问:
ListView with horizontally scrollable views
I'm currently developing an app in android.
I have a really basic listview that has 3 elements in his adapter:
1 imageview and 2 textviews.
These 3 items are inside a constraint layout.

All i ask is if i can make this layout (imgview + 2 tview) scrollable horizontally.

I've tried adding the layout to a horizontalscrollview, it works but i can't take the list onclicklistener.

答: Use RecyclerView instead, you can add the onClickListener inside the adapter itself, or if you want the clickListener to be more interactive between your adapter and your activity/fragment, you can try using interface inside the adapter.</p>


问:
Python counting characters in a line
It's supposed to count the amount of lines and the amount of characters  in the line.

I cannot add any more variables to my display function, as the professor said to use 2.

I've gotten it to count the characters in the line correctly if I change the zXX= zXX + 1
to zXX = w
but if i do that it will not count the number of lines, if someone could help I'd greatly appreciate it.

Currently I have:

```<code>def display(x, y):
     y = str(y)
     varx = str(len(y))
     vary = y + "#" + x + "#" + varx

     return vary.rjust(3)

def main():
     script = '''Grandson|Cough, cough, cough. Cough, cough, cough. {Grandson is on the bed, playing video game.} Mother|{Enters.} Hi, honey. Grandson|Hi, Mom. Mother|{Kisses son and feels his forehead.} You feeling any better? Grandson|A little bit. Mother|Guess what? Grandson|What? Mother|Your Grandfather's here. {Opens curtains.} Grandson|Mom, can't you tell him I'm sick? Mother|You're sick? That's why he's here. Grandson|He'll pinch my cheek. I hate that. Mother|Maybe he won't. Grandfather|{Entering with a flourish.} Heyyyy!! How's the sickie? Heh? {Pinches boy's cheek.  Boy looks at mother accusingly.} Mother|I think I'll leave you two pals alone. {Exits.} Grandfather|I brought you a special present. Grandson|What is it? Grandfather|Open it up. Grandson|{Opens the package. Disappointed.} A book? Grandfather|That's right. When I was your age, television was called books. And this is a special book. It was the book my father used to read to me when I was sick, {takes book} and I used to read it to your father. And today I'm gonna read it to you. Grandson|Has it got any sports in it? Grandfather|Are you kidding? Fencing, fighting, torture, revenge, giants, monsters, chases, escapes, true love, miracles... Grandson|Doesn't sound too bad. I'll try to stay awake. {Turns off TV.} Grandfather|Oh, well, thank you very much, very nice of you. Your vote of confidence is overwhelming. All right. {Puts glasses on.} The Princess Bride, by S. Morgenstern. Chapter One. Buttercup was raised on a small farm in the country of Florin.'''

     zX = script.split('\n')
     #print(zX)
     zXX = 0
     for w in zX:
         #print(zX[zXX:(zXX + 1)])
         zXXXX = w.split('|')
         #print(zXXXX)
         zXXX = zXXXX[0].upper() + " " + zXXXX[1]
         #print(zXXX)
         zXX = zXX + 1
         print(display(zXXX, zXX))
main()
</code>```

The output is:

1#GRANDSON Cough, cough, cough. Cough, cough, cough. {Grandson is on the bed, playing video game.}#1

2#MOTHER {Enters.} Hi, honey.#1

3#GRANDSON Hi, Mom.#1

4#MOTHER {Kisses son and feels his forehead.} You feeling any better?#1

5#GRANDSON A little bit.#1

6#MOTHER Guess what?#1

7#GRANDSON What?#1

8#MOTHER Your Grandfather's here. {Opens curtains.}#1

9#GRANDSON Mom, can't you tell him I'm sick?#1

10#MOTHER You're sick? That's why he's here.#2

11#GRANDSON He'll pinch my cheek. I hate that.#2

12#MOTHER Maybe he won't.#2

13#GRANDFATHER {Entering with a flourish.} Heyyyy!! How's the sickie? Heh?
{Pinches boy's cheek.  Boy looks at mother accusingly.}#2

14#MOTHER I think I'll leave you two pals alone. {Exits.}#2

15#GRANDFATHER I brought you a special present.#2

16#GRANDSON What is it?#2

17#GRANDFATHER Open it up.#2

18#GRANDSON {Opens the package. Disappointed.} A book?#2

19#GRANDFATHER That's right. When I was your age, television was called books. And this is a special book. It was the book my father used to read to me when I was sick, {takes book} and I used to read it to your father. And today I'm gonna read it to you.#2

20#GRANDSON Has it got any sports in it?#2

21#GRANDFATHER Are you kidding? Fencing, fighting, torture, revenge, giants, monsters, chases, escapes, true love, miracles...#2

22#GRANDSON Doesn't sound too bad. I'll try to stay awake. {Turns off TV.}#2

23#GRANDFATHER Oh, well, thank you very much, very nice of you. Your vote of confidence is overwhelming. All right. {Puts glasses on.} The Princess Bride, by S. Morgenstern. Chapter One. Buttercup was raised on a small farm in the country of Florin.#2

答:
Once I got past the formatting, and variable names, and that you didn't include the line breaks in 'script', I'm pretty sure that the issue is that you have:

```<code>varx = str(len(y))
</code>```

Instead of:

```<code>varx = str(len(x))
</code>```

Though that is based on my interpretation of what you provided

Title: Python counting characters in a line

Body:
It's supposed to count the amount of lines and the amount of characters  in the line.

I cannot add any more variables to my display function, as the professor said to use 2.

I've gotten it to count the characters in the line correctly if I change the zXX= zXX + 1
to zXX = w
but if i do that it will not count the number of lines, if someone could help I'd greatly appreciate it.

Currently I have:

def display(x, y):
     y = str(y)
     varx = str(len(y))
     vary = y + "#" + x + "#" + varx

     return vary.rjust(3)

def main():
     script = '''Grandson|Cough, cough, cough. Cough, cough, cough. {Grandson is on the bed, playing video game.} Mother|{Enters.} Hi, honey. Grandson|Hi, Mom. Mother|{Kisses son and feels his forehead.} You feeling any better? Grandson|A little bit. Mother|Guess what? Grandson|What? Mother|Your Grandfather's here. {Opens curtains.} Grandson|Mom, can't you tell him I'm sick? Mother|You're sick? That's why he's here. Grandson|He'll pinch my cheek. I hate that. Mother|Maybe he won't. Grandfather|{Entering with a flourish.} Heyyyy!! How's the sickie? Heh? {Pinches boy's cheek.  Boy looks at mother accusingly.} Mother|I think I'll leave you two pals alone. {Exits.} Grandfather|I brought you a special present. Grandson|What is it? Grandfather|Open it up. Grandson|{Opens the package. Disappointed.} A book? Grandfather|That's right. When I was your age, television was called books. And this is a special book. It was the book my father used to read to me when I was sick, {takes book} and I used to read it to your father. And today I'm gonna read it to you. Grandson|Has it got any sports in it? Grandfather|Are you kidding? Fencing, fighting, torture, revenge, giants, monsters, chases, escapes, true love, miracles... Grandson|Doesn't sound too bad. I'll try to stay awake. {Turns off TV.} Grandfather|Oh, well, thank you very much, very nice of you. Your vote of confidence is overwhelming. All right. {Puts glasses on.} The Princess Bride, by S. Morgenstern. Chapter One. Buttercup was raised on a small farm in the country of Florin.'''

     zX = script.split('\n')
     #print(zX)
     zXX = 0
     for w in zX:
         #print(zX[zXX:(zXX + 1)])
         zXXXX = w.split('|')
         #print(zXXXX)
         zXXX = zXXXX[0].upper() + " " + zXXXX[1]
         #print(zXXX)
         zXX = zXX + 1
         print(display(zXXX, zXX))
main()

The output is:

1#GRANDSON Cough, cough, cough. Cough, cough, cough. {Grandson is on the bed, playing video game.}#1

2#MOTHER {Enters.} Hi, honey.#1

3#GRANDSON Hi, Mom.#1

4#MOTHER {Kisses son and feels his forehead.} You feeling any better?#1

5#GRANDSON A little bit.#1

6#MOTHER Guess what?#1

7#GRANDSON What?#1

8#MOTHER Your Grandfather's here. {Opens curtains.}#1

9#GRANDSON Mom, can't you tell him I'm sick?#1

10#MOTHER You're sick? That's why he's here.#2

11#GRANDSON He'll pinch my cheek. I hate that.#2

12#MOTHER Maybe he won't.#2

13#GRANDFATHER {Entering with a flourish.} Heyyyy!! How's the sickie? Heh?
{Pinches boy's cheek.  Boy looks at mother accusingly.}#2

14#MOTHER I think I'll leave you two pals alone. {Exits.}#2

15#GRANDFATHER I brought you a special present.#2

16#GRANDSON What is it?#2

17#GRANDFATHER Open it up.#2

18#GRANDSON {Opens the package. Disappointed.} A book?#2

19#GRANDFATHER That's right. When I was your age, television was called books. And this is a special book. It was the book my father used to read to me when I was sick, {takes book} and I used to read it to your father. And today I'm gonna read it to you.#2

20#GRANDSON Has it got any sports in it?#2

21#GRANDFATHER Are you kidding? Fencing, fighting, torture, revenge, giants, monsters, chases, escapes, true love, miracles...#2

22#GRANDSON Doesn't sound too bad. I'll try to stay awake. {Turns off TV.}#2

23#GRANDFATHER Oh, well, thank you very much, very nice of you. Your vote of confidence is overwhelming. All right. {Puts glasses on.} The Princess Bride, by S. Morgenstern. Chapter One. Buttercup was raised on a small farm in the country of Florin.#2

Body:
Once I got past the formatting, and variable names, and that you didn't include the line breaks in 'script', I'm pretty sure that the issue is that you have:

varx = str(len(y))

Instead of:

varx = str(len(x))

Though that is based on my interpretation of what you provided


问:
How to shift side-by-side box?
I'm trying for hours now do to this

and I can do that slightly shifted box at the left, and because of this I can't put the image above properly either. I keep deforming the website, or have stacked boxes... I tried with position:absolute, with float, and basically everything I know, but I can't seem to get it right.
Can you help me?

答:
As stated by @snoof, this can be solved with flexbox. That guide on css-tricks is very useful, definitely give it a read.

I tried to create your layout, hopefully this can help you understand how to solve it. Warning, this code is not pretty.

https://codepen.io/anon/pen/RjLVWE

HTML:

```<code><div class="wrapper">
    <div class="left">
        <div id="circle-1" class="circle">
            <div class="circle-inner"></div>
        </div>
        <div id="box-1" class="box">
            <div class="box-inner"></div>
        </div>
    </div>
    <div class="right">
        <div id="box-2" class="box">
            <div class="box-inner"></div>
        </div>
        <div id="circle-2" class="circle">
            <div class="circle-inner"></div>
        </div>
        <div id="box-3" class="box">
            <div class="box-inner"></div>
        </div>
    </div>
</div>
</code>```

CSS:

```<code>.wrapper,
.left,
.right {
    display: flex;
}

.left,
.right {
    position: relative;
}

.left {
    width: 20%;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
}

.right {
    width: 80%;
    flex-wrap: wrap;
    flex-basis: auto;
}

.box,
.circle {
    padding: 1em;
}

.box {
    flex-grow: 1;
}

.box-inner {
    background-color: #000;
}

.circle-inner {
    padding: 7em;
    background-color: #aaa;
    border-radius: 100%;
}

#box-1 {
    width: 100%;
    height: 100%;
}

#circle-2 {
    align-self: flex-end;
}

#box-1 .box-inner {
    width: 100%;
    height: 100%;
}

#box-2 .box-inner {
    padding: 10em;
}

#box-3 {
    width: 100%;
}

#box-3 .box-inner {
    padding: 20em;
}
</code>```

Title: How to shift side-by-side box?

Body:
As stated by @snoof, this can be solved with flexbox. That guide on css-tricks is very useful, definitely give it a read.

I tried to create your layout, hopefully this can help you understand how to solve it. Warning, this code is not pretty.

https://codepen.io/anon/pen/RjLVWE

HTML:

<div class="wrapper">
    <div class="left">
        <div id="circle-1" class="circle">
            <div class="circle-inner"></div>
        </div>
        <div id="box-1" class="box">
            <div class="box-inner"></div>
        </div>
    </div>
    <div class="right">
        <div id="box-2" class="box">
            <div class="box-inner"></div>
        </div>
        <div id="circle-2" class="circle">
            <div class="circle-inner"></div>
        </div>
        <div id="box-3" class="box">
            <div class="box-inner"></div>
        </div>
    </div>
</div>

CSS:

.wrapper,
.left,
.right {
    display: flex;
}

.left,
.right {
    position: relative;
}

.left {
    width: 20%;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
}

.right {
    width: 80%;
    flex-wrap: wrap;
    flex-basis: auto;
}

.box,
.circle {
    padding: 1em;
}

.box {
    flex-grow: 1;
}

.box-inner {
    background-color: #000;
}

.circle-inner {
    padding: 7em;
    background-color: #aaa;
    border-radius: 100%;
}

#box-1 {
    width: 100%;
    height: 100%;
}

#circle-2 {
    align-self: flex-end;
}

#box-1 .box-inner {
    width: 100%;
    height: 100%;
}

#box-2 .box-inner {
    padding: 10em;
}

#box-3 {
    width: 100%;
}

#box-3 .box-inner {
    padding: 20em;
}


问:
Error in svd(x, nu = 0, nv = k) : infinite or missing values in 'x' : Error in R
There are no NA values in my data, though im still getting this error for the following code:

```<code>my_data=read.csv("airfoil_self_noise.csv")
attach(my_data)
log.dat=log(my_data[,1:5])
dat.sspressure=my_data[,6]
dat.pca=prcomp(log.dat,center=TRUE,scale=TRUE)
</code>```

error:

dat.pca=prcomp(log.dat,center=TRUE,scale=TRUE)
  Error in svd(x, nu = 0, nv = k) : infinite or missing values in 'x'

答:
As the error says, you have infinite or missing values. The log transformation can cause this, if your original data has no missing ones.

For example:

```<code>> data <- c(-1:3)
> l.data <- log(data)
Warning message:
In log(data) : NaNs produced
> l.data
[1]       NaN      -Inf 0.0000000 0.6931472 1.0986123
> dat.pca=prcomp(l.data,center=TRUE,scale=TRUE)
Error in svd(x, nu = 0, nv = k) : infinite or missing values in 'x'
</code>```

Body:
There are no NA values in my data, though im still getting this error for the following code:

my_data=read.csv("airfoil_self_noise.csv")
attach(my_data)
log.dat=log(my_data[,1:5])
dat.sspressure=my_data[,6]
dat.pca=prcomp(log.dat,center=TRUE,scale=TRUE)

error:

dat.pca=prcomp(log.dat,center=TRUE,scale=TRUE)
  Error in svd(x, nu = 0, nv = k) : infinite or missing values in 'x'

Body:
As the error says, you have infinite or missing values. The log transformation can cause this, if your original data has no missing ones.

For example:

> data <- c(-1:3)
> l.data <- log(data)
Warning message:
In log(data) : NaNs produced
> l.data
[1]       NaN      -Inf 0.0000000 0.6931472 1.0986123
> dat.pca=prcomp(l.data,center=TRUE,scale=TRUE)
Error in svd(x, nu = 0, nv = k) : infinite or missing values in 'x'


问:
How to make an image static rather than relative to an element in the same row?
https://codepen.io/Mike-was-here123/full/MOmKzO/ is my codepen.

Notice how the online or offline image moves with the name? Is their anyway to prevent this?

Its .icon in the code:

```<code>.icon {
  margin: 2% 1% 1% 4.5%;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  border: 3px solid black;

}
</code>```

The name:

```<code>#name {
  text-decoration: underline;
  font-size: 30px;
}
</code>```

答:
position absolute on the image, and position relative on the container.</p>

```<code>.columnMain {
  position: relative;
}
#status {
  position: absolute;
  top: 0;
  right: 0;
}
</code>```

Body:
https://codepen.io/Mike-was-here123/full/MOmKzO/ is my codepen.

Notice how the online or offline image moves with the name? Is their anyway to prevent this?

Its .icon in the code:

.icon {
  margin: 2% 1% 1% 4.5%;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  border: 3px solid black;

}

The name:

#name {
  text-decoration: underline;
  font-size: 30px;
}

Body:
position absolute on the image, and position relative on the container.

.columnMain {
  position: relative;
}
#status {
  position: absolute;
  top: 0;
  right: 0;
}


问:
Localstorage giving Undefined result when I try to save values from a submitted form
I was trying to save submitted  values  from the form and add them into a table using Js.I am also trying to save those values in localStorage However the localStorage throws "Undefined" error, Which I have no clue where is the problem as I am quite new to try localStorage.

Please take a look to my code give me some advice. Appreciate in advance.

HTML

if (localStorage) {

  document.getElementById('form2').addEventListener('click', function() {
    //save the values in localStorage
    localStorage.setItem('location', location);
    localStorage.setItem('activity', activity);
    localStorage.setItem('startTime', startTime);
    localStorage.setItem('endTime', endTime);
    localStorage.setItem('date', date);
    localStorage.setItem('distance', distance);

    //Retrive Workout History
    var location = localStorage.getItem('location');
    var activity = localStorage.getItem('activity');
    var startTime = localStorage.getItem('startTime');
    var endTime = localStorage.getItem('endTime');
    var date = localStorage.getItem('date');
    var distance = localStorage.getItem('distance');

    if (location != "undefined" || location != "null" || activity != "undefined" || activity != "null" || startTime != "undefined" || startTime != "null" || endTime != "undefined" || endTime != "null" || date != "undefined" || date != "null" || distance != "undefined" || distance != "null") {

      var table = document.getElementById('data');

      var row = table.insertRow();
      var cell1 = row.insertCell();
      var cell2 = row.insertCell();
      var cell3 = row.insertCell();
      var cell4 = row.insertCell();
      var cell5 = row.insertCell();
      var cell6 = row.insertCell();

      cell1.innerHTML = location;
      cell2.innerHTML = activity;
      cell3.innerHTML = startTime;
      cell4.innerHTML = endTime;
      cell5.innerHTML = date;
      cell6.innerHTML = distance;
      console.log(localStorage.getItem('location'));
    }
  });

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="form2" id="form2" action="#" method="post" onclick="return secondFormValidation();">
  <div class="form-group row">
    <label for="location" class="col-md-2 col-form-label">Location</label>
    <div class="col-md-10">
      <input type="text" class="form-control" id="location" name="location" placeholder="Location">

    </div>
  </div>
  <div class="form-group row">
    <label for="activity" class="col-md-2 col-form-label"> Select Activity</label>

    <div class=" col-md-10">
      <select class="form-control" id="activity">
                      <option value="-1" selected required>Select Activity</option>
                      <option value="1">Cycling</option>
                      <option value="2">Nordic Walking</option>
                      <option value="3">Road Bike</option>
                      <option value="4">Running</option>
                      <option value="5">Swimming</option>
                      <option value="6">Walking</option>

                    </select>
    </div>

  </div>
  <div class="form-group row">
    <label for="startTime" class="col-md-2 col-form-label">Start Time</label>
    <div class="col-md-10">
      <input type="time" class="form-control" id="startTime" name="startTime" placeholder="startTime">

    </div>
  </div>
  <div class="form-group row">
    <label for="endTime" class="col-md-2 col-form-label">End Time</label>
    <div class="col-md-10">
      <input type="time" class="form-control" id="endTime" name="endTime" placeholder="endTime">

    </div>
  </div>

  <div class="form-group row">
    <label for="date" class="col-md-2 col-form-label">Date</label>
    <div class="col-md-10">
      <input type="date" class="form-control" id="date" name="date" placeholder="Date ">
    </div>
  </div>
  <div class="form-group row">
    <label for="distance" class="col-md-2 col-form-label">Distance</label>
    <div class="col-md-10">
      <input type="distance" class="form-control" id="distance" name="distance" placeholder="Distance ">
    </div>
  </div>

  <div class="form-group row">
    <div class="offset-md-2 col-md-10">
      <button id="saveWork" type="button" class="btn btn-warning" onclick=" insertWorkout()">
                      Save workout
                    </button>

    </div>
  </div>
</form></code>```

Error

答:
Your code attempts to save the values to localStorage, but you haven't retrieved them from the form, yet:

```<code>document.getElementById('form2').addEventListener('click' , function () {

    localStorage.setItem('location' , location);
    console.log(location); // <- undefined

    ...
}
</code>```

You need to retrieve the values from the inputs.

```<code>var location = document.querySelector('input[name="location"]').value
localStorage.setItem('location' , location);
</code>```

If you add 'use strict'; at the top of your code, you will see several helpful ReferenceErrors.

Body:
I was trying to save submitted  values  from the form and add them into a table using Js.I am also trying to save those values in localStorage However the localStorage throws "Undefined" error, Which I have no clue where is the problem as I am quite new to try localStorage.

Please take a look to my code give me some advice. Appreciate in advance.

HTML

if (localStorage) {

  document.getElementById('form2').addEventListener('click', function() {
    //save the values in localStorage
    localStorage.setItem('location', location);
    localStorage.setItem('activity', activity);
    localStorage.setItem('startTime', startTime);
    localStorage.setItem('endTime', endTime);
    localStorage.setItem('date', date);
    localStorage.setItem('distance', distance);

    //Retrive Workout History
    var location = localStorage.getItem('location');
    var activity = localStorage.getItem('activity');
    var startTime = localStorage.getItem('startTime');
    var endTime = localStorage.getItem('endTime');
    var date = localStorage.getItem('date');
    var distance = localStorage.getItem('distance');

    if (location != "undefined" || location != "null" || activity != "undefined" || activity != "null" || startTime != "undefined" || startTime != "null" || endTime != "undefined" || endTime != "null" || date != "undefined" || date != "null" || distance != "undefined" || distance != "null") {

      var table = document.getElementById('data');

      var row = table.insertRow();
      var cell1 = row.insertCell();
      var cell2 = row.insertCell();
      var cell3 = row.insertCell();
      var cell4 = row.insertCell();
      var cell5 = row.insertCell();
      var cell6 = row.insertCell();

      cell1.innerHTML = location;
      cell2.innerHTML = activity;
      cell3.innerHTML = startTime;
      cell4.innerHTML = endTime;
      cell5.innerHTML = date;
      cell6.innerHTML = distance;
      console.log(localStorage.getItem('location'));
    }
  });

}

<form name="form2" id="form2" action="#" method="post" onclick="return secondFormValidation();">

    Location

      <input type="text" class="form-control" id="location" name="location" placeholder="Location">

     Select Activity

      <select class="form-control" id="activity">
                      <option value="-1" selected required>Select Activity</option>
                      <option value="1">Cycling</option>
                      <option value="2">Nordic Walking</option>
                      <option value="3">Road Bike</option>
                      <option value="4">Running</option>
                      <option value="5">Swimming</option>
                      <option value="6">Walking</option>

                    </select>

    Start Time

      <input type="time" class="form-control" id="startTime" name="startTime" placeholder="startTime">

    End Time

      <input type="time" class="form-control" id="endTime" name="endTime" placeholder="endTime">

    Date

      <input type="date" class="form-control" id="date" name="date" placeholder="Date ">

    Distance

      <input type="distance" class="form-control" id="distance" name="distance" placeholder="Distance ">

      <button id="saveWork" type="button" class="btn btn-warning" onclick=" insertWorkout()">
                      Save workout
                    </button>

</form>

Error

Body:
Your code attempts to save the values to localStorage, but you haven't retrieved them from the form, yet:

document.getElementById('form2').addEventListener('click' , function () {

    localStorage.setItem('location' , location);
    console.log(location); // <- undefined

    ...
}

You need to retrieve the values from the inputs.

var location = document.querySelector('input[name="location"]').value
localStorage.setItem('location' , location);

If you add 'use strict'; at the top of your code, you will see several helpful ReferenceErrors.


问:
How to feed a list of unquoted column names into `lapply` (so that I can use it with a `dplyr` function)
I am trying to write a function in tidyverse/dplyr that I want to eventually use with lapply (or map). (I had been working on it to answer this question, but came upon an interesting result/dead-end. Please don't mark this as a duplicate - this question is an extension/departure from the answers that you see there.)

Is there

1) a way to get a list of quoted variables to work inside a dplyr function

(and not use the deprecated SE_ functions)  or is there

2) some way to feed a list of unquoted strings through an lapply or map

I have used the Programming in Dplyr vignette to construct what I believe is a function most in line with the current standard
for working with the NSE.

The sample data:

```<code>sample_data <-
    read.table(text = "REVENUEID AMOUNT  YEAR REPORT_CODE PAYMENT_METHOD INBOUND_CHANNEL  AMOUNT_CAT
               1 rev-24985629     30  FY18           S          Check            Mail     25,50
               2 rev-22812413      1  FY16           Q          Other      Canvassing   0.01,10
               3 rev-23508794    100  FY17           Q    Credit_card             Web   100,250
               4 rev-23506121    300  FY17           S    Credit_card            Mail   250,500
               5 rev-23550444    100  FY17           S    Credit_card             Web   100,250
               6 rev-21508672     25  FY14           J          Check            Mail     25,50
               7 rev-24981769    500  FY18           S    Credit_card             Web 500,1e+03
               8 rev-23503684     50  FY17           R          Check            Mail     50,75
               9 rev-24982087     25  FY18           R          Check            Mail     25,50
               10 rev-24979834     50  FY18           R    Credit_card             Web    50,75
                      ", header = TRUE, stringsAsFactors = FALSE)
</code>```

A report generating function

```<code>report <- function(report_cat){
    report_cat <- enquo(report_cat)
    sample_data %>%
    group_by(!!report_cat, YEAR) %>%
    summarize(num=n(),total=sum(AMOUNT)) %>%
    rename(REPORT_VALUE = !!report_cat) %>%
    mutate(REPORT_CATEGORY := as.character(quote(!!report_cat))[2])
}
</code>```

Which works fine for generating a single report:

```<code>> report(REPORT_CODE)
# A tibble: 7 x 5
# Groups:   REPORT_VALUE [4]
  REPORT_VALUE  YEAR   num total REPORT_CATEGORY
         <chr> <chr> <int> <int>           <chr>
1            J  FY14     1    25     REPORT_CODE
2            Q  FY16     1     1     REPORT_CODE
3            Q  FY17     1   100     REPORT_CODE
4            R  FY17     1    50     REPORT_CODE
5            R  FY18     2    75     REPORT_CODE
6            S  FY17     2   400     REPORT_CODE
7            S  FY18     2   530     REPORT_CODE
</code>```

It is when I try and set up a list of all 4 of the reports to generate, that everything breaks down. (Though admittedly the code required in that last line of the function - to return a string with which to then fill the column - should be clue enough that I have wandered off in the wrong direction.)

```<code>#the other reports
cat.list <- c("REPORT_CODE","PAYMENT_METHOD","INBOUND_CHANNEL","AMOUNT_CAT")

# Applying and Mapping attempts
lapply(cat.list, report)
map_df(cat.list, report)
</code>```

Which results in:

```<code>> lapply(cat.list, report)
 Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated

> map_df(cat.list, report)
 Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated
</code>```

I have also tried to convert the list of strings to names before handing it over to apply and map:

```<code>library(rlang)
cat.names <- lapply(cat.list, sym)
lapply(cat.names, report)
map_df(cat.names, report)
</code>```

```<code>> lapply(cat.names, report)
 Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated
> map_df(cat.names, report)
 Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated
</code>```

In any case, the reason I am asking this question is that I think that I have written the function to the currently documented standards, but ultimately I can then see no way to utilize a member of the apply or even of the purrr::map family with such a function. Short of rewriting the function to use names like useR has done here https://stackoverflow.com/a/47316151/5088194 is there a way to get this function to work with apply or map?

I am hoping to see this as a result:

```<code># A tibble: 27 x 5
# Groups:   REPORT_VALUE [16]
   REPORT_VALUE  YEAR   num total REPORT_CATEGORY
          <chr> <chr> <int> <int>           <chr>
 1            J  FY14     1    25     REPORT_CODE
 2            Q  FY16     1     1     REPORT_CODE
 3            Q  FY17     1   100     REPORT_CODE
 4            R  FY17     1    50     REPORT_CODE
 5            R  FY18     2    75     REPORT_CODE
 6            S  FY17     2   400     REPORT_CODE
 7            S  FY18     2   530     REPORT_CODE
 8        Check  FY14     1    25  PAYMENT_METHOD
 9        Check  FY17     1    50  PAYMENT_METHOD
10        Check  FY18     2    55  PAYMENT_METHOD
# ... with 17 more rows
</code>```

答:
I'm not really a dplyr afficionado, but for what its worth here is how you could achieve this using library(data.table) instead:

```<code>setDT(sample_data)

gen_report <- function(report_cat){
  sample_data[ , .(num = .N, total = sum(AMOUNT), REPORT_CATEGORY = report_cat),
               by = .(REPORT_VALUE = get(report_cat), YEAR)]
}

gen_report('REPORT_CODE')
lapply(cat.list, gen_report)
</code>```

Body:
I am trying to write a function in tidyverse/dplyr that I want to eventually use with lapply (or map). (I had been working on it to answer this question, but came upon an interesting result/dead-end. Please don't mark this as a duplicate - this question is an extension/departure from the answers that you see there.)

Is there

1) a way to get a list of quoted variables to work inside a dplyr function

(and not use the deprecated SE_ functions)  or is there

2) some way to feed a list of unquoted strings through an lapply or map

I have used the Programming in Dplyr vignette to construct what I believe is a function most in line with the current standard
for working with the NSE.

The sample data:

sample_data <-
    read.table(text = "REVENUEID AMOUNT  YEAR REPORT_CODE PAYMENT_METHOD INBOUND_CHANNEL  AMOUNT_CAT
               1 rev-24985629     30  FY18           S          Check            Mail     25,50
               2 rev-22812413      1  FY16           Q          Other      Canvassing   0.01,10
               3 rev-23508794    100  FY17           Q    Credit_card             Web   100,250
               4 rev-23506121    300  FY17           S    Credit_card            Mail   250,500
               5 rev-23550444    100  FY17           S    Credit_card             Web   100,250
               6 rev-21508672     25  FY14           J          Check            Mail     25,50
               7 rev-24981769    500  FY18           S    Credit_card             Web 500,1e+03
               8 rev-23503684     50  FY17           R          Check            Mail     50,75
               9 rev-24982087     25  FY18           R          Check            Mail     25,50
               10 rev-24979834     50  FY18           R    Credit_card             Web    50,75
                      ", header = TRUE, stringsAsFactors = FALSE)

A report generating function

report <- function(report_cat){
    report_cat <- enquo(report_cat)
    sample_data %>%
    group_by(!!report_cat, YEAR) %>%
    summarize(num=n(),total=sum(AMOUNT)) %>%
    rename(REPORT_VALUE = !!report_cat) %>%
    mutate(REPORT_CATEGORY := as.character(quote(!!report_cat))[2])
}

Which works fine for generating a single report:

> report(REPORT_CODE)
# A tibble: 7 x 5
# Groups:   REPORT_VALUE [4]
  REPORT_VALUE  YEAR   num total REPORT_CATEGORY
         <chr> <chr> <int> <int>           <chr>
1            J  FY14     1    25     REPORT_CODE
2            Q  FY16     1     1     REPORT_CODE
3            Q  FY17     1   100     REPORT_CODE
4            R  FY17     1    50     REPORT_CODE
5            R  FY18     2    75     REPORT_CODE
6            S  FY17     2   400     REPORT_CODE
7            S  FY18     2   530     REPORT_CODE

It is when I try and set up a list of all 4 of the reports to generate, that everything breaks down. (Though admittedly the code required in that last line of the function - to return a string with which to then fill the column - should be clue enough that I have wandered off in the wrong direction.)

#the other reports
cat.list <- c("REPORT_CODE","PAYMENT_METHOD","INBOUND_CHANNEL","AMOUNT_CAT")

# Applying and Mapping attempts
lapply(cat.list, report)
map_df(cat.list, report)

Which results in:

> lapply(cat.list, report)
 Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated

> map_df(cat.list, report)
 Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated

I have also tried to convert the list of strings to names before handing it over to apply and map:

library(rlang)
cat.names <- lapply(cat.list, sym)
lapply(cat.names, report)
map_df(cat.names, report)

> lapply(cat.names, report)
 Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated
> map_df(cat.names, report)
 Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated

In any case, the reason I am asking this question is that I think that I have written the function to the currently documented standards, but ultimately I can then see no way to utilize a member of the apply or even of the purrr::map family with such a function. Short of rewriting the function to use names like useR has done here https://stackoverflow.com/a/47316151/5088194 is there a way to get this function to work with apply or map?

I am hoping to see this as a result:

# A tibble: 27 x 5
# Groups:   REPORT_VALUE [16]
   REPORT_VALUE  YEAR   num total REPORT_CATEGORY
          <chr> <chr> <int> <int>           <chr>
 1            J  FY14     1    25     REPORT_CODE
 2            Q  FY16     1     1     REPORT_CODE
 3            Q  FY17     1   100     REPORT_CODE
 4            R  FY17     1    50     REPORT_CODE
 5            R  FY18     2    75     REPORT_CODE
 6            S  FY17     2   400     REPORT_CODE
 7            S  FY18     2   530     REPORT_CODE
 8        Check  FY14     1    25  PAYMENT_METHOD
 9        Check  FY17     1    50  PAYMENT_METHOD
10        Check  FY18     2    55  PAYMENT_METHOD
# ... with 17 more rows

Body:
I'm not really a dplyr afficionado, but for what its worth here is how you could achieve this using library(data.table) instead:

setDT(sample_data)

gen_report <- function(report_cat){
  sample_data[ , .(num = .N, total = sum(AMOUNT), REPORT_CATEGORY = report_cat),
               by = .(REPORT_VALUE = get(report_cat), YEAR)]
}

gen_report('REPORT_CODE')
lapply(cat.list, gen_report)