问:
Trying to figure out how to use recursions to get the same answer as another function
I could use some help with my programming assignment. I need to use a recursion in order to make arithmetic_series = arithmetic_series_recursive. Right now my recursive function is not working properly. It only works up until the number three. The functions are supposed to take the input from the user and form a number based on the number of integers inside the number. IE if the user entered 3 it would be 1*2*3 = 6. </p>

```<code>int arithmetic_series(int n){
    int total = ((n+1) * n )/ 2;
    cout << total << endl;
    return total;
}

int arithmetic_series_recursive(int n){
    if(n==1){
            return 1;
    }else{
    return n*arithmetic_series_recursive(n-1);
    }

}
</code>```

答:
Your first function finds the sum of integers from 1 to n. Your second function finds the product of the that range, or !n. I don't know of any simplification you could use in your first function.

If you meant to find the sum of the numbers, you can change the your second function to preform an addition :

```<code>int arithmetic_series_recursive(int n) {
    if (n == 1) {
        return 1;
    }
    else {
        return n + arithmetic_series_recursive(n - 1);
    }

}
</code>```

Body:
I could use some help with my programming assignment. I need to use a recursion in order to make arithmetic_series = arithmetic_series_recursive. Right now my recursive function is not working properly. It only works up until the number three. The functions are supposed to take the input from the user and form a number based on the number of integers inside the number. IE if the user entered 3 it would be 1*2*3 = 6.

int arithmetic_series(int n){
    int total = ((n+1) * n )/ 2;
    cout << total << endl;
    return total;
}

int arithmetic_series_recursive(int n){
    if(n==1){
            return 1;
    }else{
    return n*arithmetic_series_recursive(n-1);
    }

}

Body:
Your first function finds the sum of integers from 1 to n. Your second function finds the product of the that range, or !n. I don't know of any simplification you could use in your first function.

If you meant to find the sum of the numbers, you can change the your second function to preform an addition :

int arithmetic_series_recursive(int n) {
    if (n == 1) {
        return 1;
    }
    else {
        return n + arithmetic_series_recursive(n - 1);
    }

}


来源: stackexchange

问:
Getting Error while sending post request in flask (python)
I am sending a post request to function which is coroutine but I am getting below error.

```<code>    Traceback (most recent call last):
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1994, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.4/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1615, in full_dispatch_request
    return self.finalize_request(rv)
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1630, in finalize_request
    response = self.make_response(rv)
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1740, in make_response
    rv = self.response_class.force_type(rv, request.environ)
  File "/usr/local/lib/python3.4/site-packages/werkzeug/wrappers.py", line 885, in force_type
    response = BaseResponse(*_run_wsgi_app(response, environ))
  File "/usr/local/lib/python3.4/site-packages/werkzeug/wrappers.py", line 57, in _run_wsgi_app
    return _run_wsgi_app(*args)
  File "/usr/local/lib/python3.4/site-packages/werkzeug/test.py", line 884, in run_wsgi_app
    app_rv = app(environ, start_response)
TypeError: 'generator' object is not callable
</code>```

Below is function which call after submit button:
and function f() is fetching some data from a get request and return the json from response.

```<code>    @app.route('/submit', methods=['POST'])
    @asyncio.coroutine
    def submit():
       result = yield from f()
       return  render_template('test.html', result=result)

def f()
  response = yield from request('get',...)
  ....
</code>```

答:
You can't use coroutines as Flask routes, that's not how Flask, or the WSGI protocol, work. WSGI handles one request/response per thread/process/eventlet. If you need to do background tasks, spawn a thread or use a task queue like Celery.

You can return a response containing a generator to stream the response. It will still run synchronously in one thread though.

```<code>def stream():
    yield 'thing one'
    yield from other_thing()
    yield 'thing two'

return current_app.response_class(stream())
</code>```

If you use gevent, you can use eventlets instead of threads to handle each request, in which case you can spawn other eventlets. This comes with it's own performance issues, since all eventlets run in a loop in one thread (this is true of asyncio too). Gunicorn also supports aiohttp, but Flask does not, although it may be possible to get it to work.

ContentLicense: CC BY-SA 3.0

Body:
I am sending a post request to function which is coroutine but I am getting below error.

    Traceback (most recent call last):
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1994, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.4/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1615, in full_dispatch_request
    return self.finalize_request(rv)
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1630, in finalize_request
    response = self.make_response(rv)
  File "/usr/local/lib/python3.4/site-packages/flask/app.py", line 1740, in make_response
    rv = self.response_class.force_type(rv, request.environ)
  File "/usr/local/lib/python3.4/site-packages/werkzeug/wrappers.py", line 885, in force_type
    response = BaseResponse(*_run_wsgi_app(response, environ))
  File "/usr/local/lib/python3.4/site-packages/werkzeug/wrappers.py", line 57, in _run_wsgi_app
    return _run_wsgi_app(*args)
  File "/usr/local/lib/python3.4/site-packages/werkzeug/test.py", line 884, in run_wsgi_app
    app_rv = app(environ, start_response)
TypeError: 'generator' object is not callable

Below is function which call after submit button:
and function f() is fetching some data from a get request and return the json from response.

    @app.route('/submit', methods=['POST'])
    @asyncio.coroutine
    def submit():
       result = yield from f()
       return  render_template('test.html', result=result)

def f()
  response = yield from request('get',...)
  ....

Body:
You can't use coroutines as Flask routes, that's not how Flask, or the WSGI protocol, work. WSGI handles one request/response per thread/process/eventlet. If you need to do background tasks, spawn a thread or use a task queue like Celery.

You can return a response containing a generator to stream the response. It will still run synchronously in one thread though.

def stream():
    yield 'thing one'
    yield from other_thing()
    yield 'thing two'

return current_app.response_class(stream())

If you use gevent, you can use eventlets instead of threads to handle each request, in which case you can spawn other eventlets. This comes with it's own performance issues, since all eventlets run in a loop in one thread (this is true of asyncio too). Gunicorn also supports aiohttp, but Flask does not, although it may be possible to get it to work.


问:
python string splitting with multiple splitting points
Ok so ill get straight to the point here is my code

```<code>def digestfragmentwithenzyme(seqs, enzymes):

fragment = []
for seq in seqs:
    for enzyme in enzymes:
        results = []
        prog = re.compile(enzyme[0])
        for dingen in prog.finditer(seq):
           results.append(dingen.start() + enzyme[1])
        results.reverse()
        #result = 0
        for result in results:
            fragment.append(seq[result:])
            seq = seq[:result]
        fragment.append(seq[:result])
fragment.reverse()
return fragment
</code>```

Input for this function is a list of multiple strings (seq) e.g. :

```<code>List = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]
</code>```

And enzymes as input:

```<code>[["TC", 1],["GC",1]]
</code>```

(note: there can be multiple given but most of them are in this matter of letters with ATCG)

The function should return a list that, in this example, contain 2 lists:

```<code>Outputlist = [["AATT","CCGGT","CGGGG","CT","CGGGGG"],["AAAG","CAAAAT","CAAAAAAG","CAAAAAAT","C"]]
</code>```

Right now i am having troubles with splitting it twice and getting the right output.

Little bit more information about the function. It looks through the string (seq) for the recognizion point. in this case TC or GC and splits it on the 2nd index of enzymes. it should do that for both strings in the list with both enzymes.

答:
The simplest answer I can think of:</p>

```<code>input_list = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]
enzymes = ['TC', 'GC']
output = []
for string in input_list:
    parts = []
    left = 0
    for right in range(1,len(string)):
        if string[right-1:right+1] in enzymes:
            parts.append(string[left:right])
            left = right
    parts.append(string[left:])
    output.append(parts)
print(output)
</code>```

Body:
Ok so ill get straight to the point here is my code

def digestfragmentwithenzyme(seqs, enzymes):

fragment = []
for seq in seqs:
    for enzyme in enzymes:
        results = []
        prog = re.compile(enzyme[0])
        for dingen in prog.finditer(seq):
           results.append(dingen.start() + enzyme[1])
        results.reverse()
        #result = 0
        for result in results:
            fragment.append(seq[result:])
            seq = seq[:result]
        fragment.append(seq[:result])
fragment.reverse()
return fragment

Input for this function is a list of multiple strings (seq) e.g. :

List = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]

And enzymes as input:

[["TC", 1],["GC",1]]

(note: there can be multiple given but most of them are in this matter of letters with ATCG)

The function should return a list that, in this example, contain 2 lists:

Outputlist = [["AATT","CCGGT","CGGGG","CT","CGGGGG"],["AAAG","CAAAAT","CAAAAAAG","CAAAAAAT","C"]]

Right now i am having troubles with splitting it twice and getting the right output.

Little bit more information about the function. It looks through the string (seq) for the recognizion point. in this case TC or GC and splits it on the 2nd index of enzymes. it should do that for both strings in the list with both enzymes.

Body:
The simplest answer I can think of:

input_list = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]
enzymes = ['TC', 'GC']
output = []
for string in input_list:
    parts = []
    left = 0
    for right in range(1,len(string)):
        if string[right-1:right+1] in enzymes:
            parts.append(string[left:right])
            left = right
    parts.append(string[left:])
    output.append(parts)
print(output)


问:
Synchronized unordered_map in C++
I am using unordered_map from Boost. Are there any synchronized version of unordered_map? This is because I have quite a large number of unordered_map and manually synchronizing it using lock would be very messy.

Thanks.

答:
Are you sure that is what you need ?

```<code>while (!stack.empty())
{
  Element const e = stack.top();

  stack.pop();
}
</code>```

In a single thread, this code looks right. If you wish to go multi-thread however, simply having a synchronized stack just doesn't cut it.

What happens if anyone else pops the last element AFTER you tested for emptiness ?

There is more than container synchronization to go multi-thread. That said, you could try TBB out.

ContentLicense: CC BY-SA 2.5

Title: Synchronized unordered_map in C++

Body:
Are you sure that is what you need ?

while (!stack.empty())
{
  Element const e = stack.top();

  stack.pop();
}

In a single thread, this code looks right. If you wish to go multi-thread however, simply having a synchronized stack just doesn't cut it.

What happens if anyone else pops the last element AFTER you tested for emptiness ?

There is more than container synchronization to go multi-thread. That said, you could try TBB out.


问:
Visual studio 2017 installer won't run after extracting
visual studio 2017 community.exe won't run after extracting to the temp.

OS: windows 10 x64bit

Setup : community version

in the temp folder bootstrapper log says,

Beginning of the log. Start Time: 3/26/2017 1:14:54 AM
VisualStudio Bootstrapper:3/26/2017 1:14:54 AM: Current Optin root path does not exists

VisualStudio Bootstrapper:3/26/2017 1:14:55 AM: Commandline arguments =

and the dd_vs_community_decompression_log says

[3/26/2017, 11:17:47] === Logging started: 2017/03/26 11:17:47 ===

[3/26/2017, 11:17:47] Executable: C:\Users\Sameera\Downloads\Programs\vs_community.exe v15.0.26228.0

[3/26/2017, 11:17:47] --- logging level: standard ---

[3/26/2017, 11:17:47] Directory
'C:\Users\Sameera\AppData\Local\Temp\4ceac4b7b9cd9fdf2489526c66\' has been selected for file extraction

[3/26/2017, 11:17:48] Extracting files to: C:\Users\Sameera\AppData\Local\Temp\4ceac4b7b9cd9fdf2489526c66\

[3/26/2017, 11:17:48] Extraction took 360 milliseconds

[3/26/2017, 11:17:48] Executing extracted package: 'vs_bootstrapper_d15\vs_setup_bootstrapper.exe ' with commandline ' '

[3/26/2017, 11:18:10] The entire Box execution exiting with result code: 0x0

[3/26/2017, 11:18:10] Launched extracted application exiting with result code: 0xc000000d

[3/26/2017, 11:18:10] === Logging stopped: 2017/03/26 11:18:10 ===

can't find proper solution..

答:
I was able to resolve my problem after 4 days of troubleshooting with Microsoft support. I'm developing on a Dell laptop and the support technician believes one of the Dell services was causing issues with the winmgmt service.

Below is a command that failed to run. Then after making sure we had an OS restore point saved, we issued the /resetRepository command. After that, the VS 2017 Pro installer was able to execute without error.

EDIT: Adding the exact steps and code sample below:

Step 1: Create a Windows system restore point.

Step 2: From the command prompt with administrative rights or elevated privileges, execute the following command: net stop winmgmt

Step 3: Open a Windows Explorer and locate the path to C:\windows\system32\WBEM\ folder and rename the Repository folder to something else like RepositoryOLD (right click and choose 'Rename Folder').

Step 4: restart the computer

Step 5: From the command prompt with administrative rights or elevated privileges, execute the following command: net stop winmgmt

```<code>C:\>net stop winmgmt
The Windows Management Instrumentation service is stopping.
The Windows Management Instrumentation service could not be stopped.
</code>```

Step 6: From the command prompt with administrative rights or elevated privileges, execute the following command: winmgmt /resetRepository

```<code>C:\>winmgmt /resetRepository
WMI repository has been reset
</code>```

Step 7: restart the computer.

Hope this helps anyone with a similar Visual Studio 2017 installer issue.

Body:
I was able to resolve my problem after 4 days of troubleshooting with Microsoft support. I'm developing on a Dell laptop and the support technician believes one of the Dell services was causing issues with the winmgmt service.

Below is a command that failed to run. Then after making sure we had an OS restore point saved, we issued the /resetRepository command. After that, the VS 2017 Pro installer was able to execute without error.

EDIT: Adding the exact steps and code sample below:

Step 1: Create a Windows system restore point.

Step 2: From the command prompt with administrative rights or elevated privileges, execute the following command: net stop winmgmt

Step 3: Open a Windows Explorer and locate the path to C:\windows\system32\WBEM\ folder and rename the Repository folder to something else like RepositoryOLD (right click and choose 'Rename Folder').

Step 4: restart the computer

Step 5: From the command prompt with administrative rights or elevated privileges, execute the following command: net stop winmgmt

C:\>net stop winmgmt
The Windows Management Instrumentation service is stopping.
The Windows Management Instrumentation service could not be stopped.

Step 6: From the command prompt with administrative rights or elevated privileges, execute the following command: winmgmt /resetRepository

C:\>winmgmt /resetRepository
WMI repository has been reset

Step 7: restart the computer.

Hope this helps anyone with a similar Visual Studio 2017 installer issue.


问:
C Resizing BMP File by Factor of N, what am I doing wrong?
new to C.  Have been having troubles resizing a 24 bit uncompressed bitmap with my code.  I am trying to scale this image up by a factor of n, I feel that I am close to having it work properly but my outputted image is still not correct.

I can post pictures of the input 24 bit uncompressed BMP (small.bmp) I am using for testing, the picture my program is outputting (resized.bmp), and what the correct image of small.bmp scaled by a factor of 4 SHOULD look like, if that would be helpful.  Just ask.

resize.c

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

#include "bmp.h"

int main(int argc, char *argv[])
{
    // ensure proper usage
    if (argc != 4)
    {
        fprintf(stderr, "Usage: ./resize scale infile outfile\n");
        return 1;
    }

    int n = atoi(argv[1]);
    // remember filenames
    char *infile = argv[2];
    char *outfile = argv[3];

    // open input file
    FILE *inptr = fopen(infile, "r");
    if (inptr == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", infile);
        return 2;
    }

    // open output file
    FILE *outptr = fopen(outfile, "w");
    if (outptr == NULL)
    {
        fclose(inptr);
        fprintf(stderr, "Could not create %s.\n", outfile);
        return 3;
    }

    // read infile's BITMAPFILEHEADER
    BITMAPFILEHEADER bf;
    fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);

    // read infile's BITMAPINFOHEADER
    BITMAPINFOHEADER bi;
    fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr);

    // ensure infile is (likely) a 24-bit uncompressed BMP 4.0
    if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 ||
        bi.biBitCount != 24 || bi.biCompression != 0)
    {
        fclose(outptr);
        fclose(inptr);
        fprintf(stderr, "Unsupported file format.\n");
        return 4;
    }
    int oldpadding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;
    bi.biWidth = bi.biWidth * n;
    bi.biHeight = bi.biHeight * n;

    // determine padding for scanlines
    int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;

bi.biSizeImage = ((sizeof(RGBTRIPLE) * bi.biWidth) + padding) * abs(bi.biHeight);
bf.bfSize = bi.biSizeImage + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
// write outfile's BITMAPFILEHEADER
fwrite(&bf, sizeof(BITMAPFILEHEADER), 1, outptr);

    // write outfile's BITMAPINFOHEADER
    fwrite(&bi, sizeof(BITMAPINFOHEADER), 1, outptr);

    // iterate over infile's scanlines
    for (int i = 0, biHeight = abs(oldHeight); i < biHeight; i++)
    {

        // store scanline in an array pixel by pixel for vertical scaling.
        RGBTRIPLE scanline[bi.biWidth - 1];

        // iterate over pixels in scanline
        for (int j = 0; j < bi.biWidth; j++)
        {
            //check if we've hit padding in original bmp.
            if (j % oldpadding == 0 && j != 0)
            {
                //skip the padding.
                fseek(inptr, oldpadding, SEEK_CUR);
            }

            // temporary storage
            RGBTRIPLE triple;

            fread(&triple, sizeof(RGBTRIPLE), 1, inptr);

            for (int h = 0; h < n; h++)
            {
                //scale horizontally, save each scanline pixel to our array.
                scanline[j] = triple;
            }

        }

        for (int x = 0; x < n; x++)
        {
            //write scanlines n - 1 times.
            for (int y = 0; y < bi.biWidth; y++)
            {
                    fwrite(&scanline[y], sizeof(RGBTRIPLE), 1, outptr);
            }

            //write padding if any for current scanline.
            for (int z = 0; z < padding; z++)
            {
                fputc(0x00, outptr);
            }
        }

    }

    // close infile
    fclose(inptr);

    // close outfile
    fclose(outptr);

    // success
    return 0;
}
</code>```

bmp.h

```<code>/**
 * BMP-related data types based on Microsoft's own.
 */

#include <stdint.h>

/**
 * Common Data Types
 *
 * The data types in this section are essentially aliases for C/C++
 * primitive data types.
 *
 * Adapted from https://msdn.microsoft.com/en-us/library/cc230309.aspx.
 * See http://en.wikipedia.org/wiki/Stdint.h for more on stdint.h.
 */
typedef uint8_t  BYTE;
typedef uint32_t DWORD;
typedef int32_t  LONG;
typedef uint16_t WORD;

/**
 * BITMAPFILEHEADER
 *
 * The BITMAPFILEHEADER structure contains information about the type, size,
 * and layout of a file that contains a DIB [device-independent bitmap].
 *
 * Adapted from https://msdn.microsoft.com/en-us/library/dd183374(v=vs.85).aspx.
 */
typedef struct
{
    WORD bfType;
    DWORD bfSize;
    WORD bfReserved1;
    WORD bfReserved2;
    DWORD bfOffBits;
} __attribute__((__packed__))
BITMAPFILEHEADER;

/**
 * BITMAPINFOHEADER
 *
 * The BITMAPINFOHEADER structure contains information about the
 * dimensions and color format of a DIB [device-independent bitmap].
 *
 * Adapted from https://msdn.microsoft.com/en-us/library/dd183376(v=vs.85).aspx.
 */
typedef struct
{
    DWORD biSize;
    LONG biWidth;
    LONG biHeight;
    WORD biPlanes;
    WORD biBitCount;
    DWORD biCompression;
    DWORD biSizeImage;
    LONG biXPelsPerMeter;
    LONG biYPelsPerMeter;
    DWORD biClrUsed;
    DWORD biClrImportant;
} __attribute__((__packed__))
BITMAPINFOHEADER;

/**
 * RGBTRIPLE
 *
 * This structure describes a color consisting of relative intensities of
 * red, green, and blue.
 *
 * Adapted from https://msdn.microsoft.com/en-us/library/dd162939(v=vs.85).aspx.
 */
typedef struct
{
    BYTE rgbtBlue;
    BYTE rgbtGreen;
    BYTE rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;
</code>```

答:
Your code has a mixture of two techniques for scaling: 1) scaling in an array and then writing it out, and 2) reading the array in it's original size and scaling while writing it out. However, your implementation of the first technique doesn't actually do any scaling:

```<code>for (int h = 0; h < n; h++)
{
    //scale horizontally, save each scanline pixel to our array.
    scanline[j] = triple;
}
</code>```

Because you don't increment j, you're just overwriting the same triple to the same location n times. It doesn't do any scaling at all. I suggest abandoning the first technique and just focusing on the second. For starters, fix your array declaration:

```<code>RGBTRIPLE scanline[bi.biWidth];
</code>```

Then when you read in, just write the triple to the correct location without any loop:

```<code>scanline[j] = triple;
</code>```

When you write it out, you have the loops around the wrong way. You want to loop over the pixels and write each one out n times, not loop over the image n times and write out all the pixels (which will repeat the image n times rather than scaling it by n). Then wrap this all in a loop to output each row n times.

```<code>for (int y = 0; y < n; y++) // repeat each row n times
{
    for (int x = 0; x < bi.biWidth; x++) // iterate over pixels
    {
         for (int r = 0; r < n; r++) // repeat each pixel n times
             fwrite(&scanline[x], sizeof(RGBTRIPLE), 1, outptr);
    }
    // write padding if any for current scanline.
    for (int z = 0; z < padding; z++)
    {
        fputc(0x00, outptr);
    }
}
</code>```

This is the basic algorithm for scaling the image. You could improve the speed by doing block I/O reads and writes rather than calling fwrite in a loop but as you indicated in a comment, correctness > efficiency. You might also have some issues with padding, I haven't addressed that.

Body:
new to C.  Have been having troubles resizing a 24 bit uncompressed bitmap with my code.  I am trying to scale this image up by a factor of n, I feel that I am close to having it work properly but my outputted image is still not correct.

I can post pictures of the input 24 bit uncompressed BMP (small.bmp) I am using for testing, the picture my program is outputting (resized.bmp), and what the correct image of small.bmp scaled by a factor of 4 SHOULD look like, if that would be helpful.  Just ask.

resize.c

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

#include "bmp.h"

int main(int argc, char *argv[])
{
    // ensure proper usage
    if (argc != 4)
    {
        fprintf(stderr, "Usage: ./resize scale infile outfile\n");
        return 1;
    }

    int n = atoi(argv[1]);
    // remember filenames
    char *infile = argv[2];
    char *outfile = argv[3];

    // open input file
    FILE *inptr = fopen(infile, "r");
    if (inptr == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", infile);
        return 2;
    }

    // open output file
    FILE *outptr = fopen(outfile, "w");
    if (outptr == NULL)
    {
        fclose(inptr);
        fprintf(stderr, "Could not create %s.\n", outfile);
        return 3;
    }

    // read infile's BITMAPFILEHEADER
    BITMAPFILEHEADER bf;
    fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);

    // read infile's BITMAPINFOHEADER
    BITMAPINFOHEADER bi;
    fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr);

    // ensure infile is (likely) a 24-bit uncompressed BMP 4.0
    if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 ||
        bi.biBitCount != 24 || bi.biCompression != 0)
    {
        fclose(outptr);
        fclose(inptr);
        fprintf(stderr, "Unsupported file format.\n");
        return 4;
    }
    int oldpadding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;
    bi.biWidth = bi.biWidth * n;
    bi.biHeight = bi.biHeight * n;

    // determine padding for scanlines
    int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;

bi.biSizeImage = ((sizeof(RGBTRIPLE) * bi.biWidth) + padding) * abs(bi.biHeight);
bf.bfSize = bi.biSizeImage + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
// write outfile's BITMAPFILEHEADER
fwrite(&bf, sizeof(BITMAPFILEHEADER), 1, outptr);

    // write outfile's BITMAPINFOHEADER
    fwrite(&bi, sizeof(BITMAPINFOHEADER), 1, outptr);

    // iterate over infile's scanlines
    for (int i = 0, biHeight = abs(oldHeight); i < biHeight; i++)
    {

        // store scanline in an array pixel by pixel for vertical scaling.
        RGBTRIPLE scanline[bi.biWidth - 1];

        // iterate over pixels in scanline
        for (int j = 0; j < bi.biWidth; j++)
        {
            //check if we've hit padding in original bmp.
            if (j % oldpadding == 0 && j != 0)
            {
                //skip the padding.
                fseek(inptr, oldpadding, SEEK_CUR);
            }

            // temporary storage
            RGBTRIPLE triple;

            fread(&triple, sizeof(RGBTRIPLE), 1, inptr);

            for (int h = 0; h < n; h++)
            {
                //scale horizontally, save each scanline pixel to our array.
                scanline[j] = triple;
            }

        }

        for (int x = 0; x < n; x++)
        {
            //write scanlines n - 1 times.
            for (int y = 0; y < bi.biWidth; y++)
            {
                    fwrite(&scanline[y], sizeof(RGBTRIPLE), 1, outptr);
            }

            //write padding if any for current scanline.
            for (int z = 0; z < padding; z++)
            {
                fputc(0x00, outptr);
            }
        }

    }

    // close infile
    fclose(inptr);

    // close outfile
    fclose(outptr);

    // success
    return 0;
}

bmp.h

/**
 * BMP-related data types based on Microsoft's own.
 */

#include <stdint.h>

/**
 * Common Data Types
 *
 * The data types in this section are essentially aliases for C/C++
 * primitive data types.
 *
 * Adapted from https://msdn.microsoft.com/en-us/library/cc230309.aspx.
 * See http://en.wikipedia.org/wiki/Stdint.h for more on stdint.h.
 */
typedef uint8_t  BYTE;
typedef uint32_t DWORD;
typedef int32_t  LONG;
typedef uint16_t WORD;

/**
 * BITMAPFILEHEADER
 *
 * The BITMAPFILEHEADER structure contains information about the type, size,
 * and layout of a file that contains a DIB [device-independent bitmap].
 *
 * Adapted from https://msdn.microsoft.com/en-us/library/dd183374(v=vs.85).aspx.
 */
typedef struct
{
    WORD bfType;
    DWORD bfSize;
    WORD bfReserved1;
    WORD bfReserved2;
    DWORD bfOffBits;
} __attribute__((__packed__))
BITMAPFILEHEADER;

/**
 * BITMAPINFOHEADER
 *
 * The BITMAPINFOHEADER structure contains information about the
 * dimensions and color format of a DIB [device-independent bitmap].
 *
 * Adapted from https://msdn.microsoft.com/en-us/library/dd183376(v=vs.85).aspx.
 */
typedef struct
{
    DWORD biSize;
    LONG biWidth;
    LONG biHeight;
    WORD biPlanes;
    WORD biBitCount;
    DWORD biCompression;
    DWORD biSizeImage;
    LONG biXPelsPerMeter;
    LONG biYPelsPerMeter;
    DWORD biClrUsed;
    DWORD biClrImportant;
} __attribute__((__packed__))
BITMAPINFOHEADER;

/**
 * RGBTRIPLE
 *
 * This structure describes a color consisting of relative intensities of
 * red, green, and blue.
 *
 * Adapted from https://msdn.microsoft.com/en-us/library/dd162939(v=vs.85).aspx.
 */
typedef struct
{
    BYTE rgbtBlue;
    BYTE rgbtGreen;
    BYTE rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;

Body:
Your code has a mixture of two techniques for scaling: 1) scaling in an array and then writing it out, and 2) reading the array in it's original size and scaling while writing it out. However, your implementation of the first technique doesn't actually do any scaling:

for (int h = 0; h < n; h++)
{
    //scale horizontally, save each scanline pixel to our array.
    scanline[j] = triple;
}

Because you don't increment j, you're just overwriting the same triple to the same location n times. It doesn't do any scaling at all. I suggest abandoning the first technique and just focusing on the second. For starters, fix your array declaration:

RGBTRIPLE scanline[bi.biWidth];

Then when you read in, just write the triple to the correct location without any loop:

scanline[j] = triple;

When you write it out, you have the loops around the wrong way. You want to loop over the pixels and write each one out n times, not loop over the image n times and write out all the pixels (which will repeat the image n times rather than scaling it by n). Then wrap this all in a loop to output each row n times.

for (int y = 0; y < n; y++) // repeat each row n times
{
    for (int x = 0; x < bi.biWidth; x++) // iterate over pixels
    {
         for (int r = 0; r < n; r++) // repeat each pixel n times
             fwrite(&scanline[x], sizeof(RGBTRIPLE), 1, outptr);
    }
    // write padding if any for current scanline.
    for (int z = 0; z < padding; z++)
    {
        fputc(0x00, outptr);
    }
}

This is the basic algorithm for scaling the image. You could improve the speed by doing block I/O reads and writes rather than calling fwrite in a loop but as you indicated in a comment, correctness > efficiency. You might also have some issues with padding, I haven't addressed that.


问:
ini file not being ready properly
I keep getting this error:

Warning: mysql_connect(): Unknown MySQL server host 'elephant' (1) 4

My ini file is this:

```<code>[Database]
DBHostName = "localhost"
DatabaseName = "elephant"
DBUserName = "elephant"
DBPassword = "practice"

[Config]
ConfigTableName = "stage2_config"
Skin="purple"
</code>```

My file that reads the ini file and gives the error is this on the line with the double bold stars. I have no idea what is going on here and why it says the host isn't localhost.

```<code><?php
 $gv_SystemTest = "<h2>system.php has been included</h2>";

 $gv_SystemFileInfo = pathinfo(__FILE__);
 $gv_SystemDirectory = $gv_SystemFileInfo['dirname'] . '/';
 $gv_SystemINIpath = $gv_SystemDirectory . '';

 $gv_SiteGlobals = parse_ini_file($gv_SystemINIpath . $_SERVER['WIA_SYSTEM_INI'], true);

 function echoContent($p_ContentID) {
 global $gv_SiteGlobals;

 $fv_dbLink = mysql_connect($gv_SiteGlobals['Database']['DBHostName'],
 $gv_SiteGlobals['Database']['DBUserName'],
 $gv_SiteGlobals['Database']['DBPassword']);
 **mysql_connect($gv_SiteGlobals['Database']['DatabaseName']);**

 $fv_TheQuery = "select *from wia_content where content_id = $p_ContentID";
</code>```

答:
The function mysql_connect does not allow to select a database as you tried on this line.

```<code>mysql_connect($gv_SiteGlobals['Database']['DatabaseName']);
</code>```

To connect and select a database, you need to use the function mysql_select_db in addition to mysql_connect.

```<code>$link = mysql_connect('host','username','password');
$selected = mysql_select_db('database_name', $link);
</code>```

http://php.net/manual/en/function.mysql-select-db.php

Title: ini file not being ready properly

Body:
I keep getting this error:

Warning: mysql_connect(): Unknown MySQL server host 'elephant' (1) 4

My ini file is this:

[Database]
DBHostName = "localhost"
DatabaseName = "elephant"
DBUserName = "elephant"
DBPassword = "practice"

[Config]
ConfigTableName = "stage2_config"
Skin="purple"

My file that reads the ini file and gives the error is this on the line with the double bold stars. I have no idea what is going on here and why it says the host isn't localhost.

<?php
 $gv_SystemTest = "
system.php has been included
";

 $gv_SystemFileInfo = pathinfo(__FILE__);
 $gv_SystemDirectory = $gv_SystemFileInfo['dirname'] . '/';
 $gv_SystemINIpath = $gv_SystemDirectory . '';

 $gv_SiteGlobals = parse_ini_file($gv_SystemINIpath . $_SERVER['WIA_SYSTEM_INI'], true);

 function echoContent($p_ContentID) {
 global $gv_SiteGlobals;

 $fv_dbLink = mysql_connect($gv_SiteGlobals['Database']['DBHostName'],
 $gv_SiteGlobals['Database']['DBUserName'],
 $gv_SiteGlobals['Database']['DBPassword']);
 **mysql_connect($gv_SiteGlobals['Database']['DatabaseName']);**

 $fv_TheQuery = "select *from wia_content where content_id = $p_ContentID";

Body:
The function mysql_connect does not allow to select a database as you tried on this line.

mysql_connect($gv_SiteGlobals['Database']['DatabaseName']);

To connect and select a database, you need to use the function mysql_select_db in addition to mysql_connect.

$link = mysql_connect('host','username','password');
$selected = mysql_select_db('database_name', $link);

http://php.net/manual/en/function.mysql-select-db.php


问:
How to avoid dynamic cast in polymorphism with derived class of template type
I have this architecture(in short version):

```<code>class BaseBatch {
    virtual ~BaseBatch(){};
};

template<class T>
class Batch : public BaseBatch
{

    void draw(T* data) {
       do something..
    }
};

class BatchManager
{
private:
   static std::vector<BaseBatch*> batches;
public:

    template <class T>
    static void placeData(T* data){

        //Loop through the entire container
        bool found = false;
        for (auto&& b: batches())
            if (b->get_type() == typeid(T)) {

                dynamic_cast<Batch<T>*>(b)->draw(data);
                found = true;
            }

        //If no bach found, create a new One
        if (not found) {
            batches.push_back(new Batch<T>);
        }
    }
};
</code>```

Problem is that the placeData function is called multiple (many) times per 1 loop and I think that the dynamic casting is a real pain for the performance but cannot figure out how can I solve this without using it. Is it really that problematic or I shouldn´t bother with it and keep using it? If i should avoid it, what would you suggest? Thanks

答:
Instead of using std::vector<Batch*> use a std::unordered_map<std::type_index, std::unique_ptr<BaseBatch>>. To access a batch use batches.find(std::type_index(typeid(T))), then static_cast it to a Batch<T>*. static_cast has no runtime overhead. To create a new batch, use std::type_index(typeid(T)) as the key.

The performance of dynamic_cast likely isn't the issue here. In fact, with this solution calling typeid is likely just as bad as dynamic_cast. The real potential gain is the lookup speed of the unordered_map vs iterating through every element of a who-knows-how-big vector and trying a dynamic_cast.

Body:
I have this architecture(in short version):

class BaseBatch {
    virtual ~BaseBatch(){};
};

template<class T>
class Batch : public BaseBatch
{

    void draw(T* data) {
       do something..
    }
};

class BatchManager
{
private:
   static std::vector<BaseBatch*> batches;
public:

    template <class T>
    static void placeData(T* data){

        //Loop through the entire container
        bool found = false;
        for (auto&& b: batches())
            if (b->get_type() == typeid(T)) {

                dynamic_cast<Batch<T>*>(b)->draw(data);
                found = true;
            }

        //If no bach found, create a new One
        if (not found) {
            batches.push_back(new Batch<T>);
        }
    }
};

Problem is that the placeData function is called multiple (many) times per 1 loop and I think that the dynamic casting is a real pain for the performance but cannot figure out how can I solve this without using it. Is it really that problematic or I shouldn´t bother with it and keep using it? If i should avoid it, what would you suggest? Thanks


问:
Get all calendars in Google Apps Scripts CalendarApp class
So Google Apps Scripts allow you to getCalendarByID, getCalendarsByName and getDefaultCalendar, which works great when you need to target a specific calendar. However, I was wondering if there's a way for me to get ALL the Calendars that is associated with the account?

I've tried getCalendarsByName(), getCalendarsByName('') and getCalendarsByName('*'), none of which works.

答:
This works for me:</p>

```<code>function get_calendars() {
var calendars = CalendarApp.getAllCalendars();
for (var i = 0; i < calendars.length; i++) {
var calendar = calendars[i];
Logger.log(calendar.getName());
}
}
</code>```

Body:
This works for me:

function get_calendars() {
var calendars = CalendarApp.getAllCalendars();
for (var i = 0; i < calendars.length; i++) {
var calendar = calendars[i];
Logger.log(calendar.getName());
}
}


问:
Navigation drawer on all activities
I have two activities the first one is 'Navigation drawer activity' (MainActivity) and the second activity I have created is a 'Tabbed activity' (OverView). How can I add Navigation drawer menu on Tabbed activity.

Your help and suggestion are very helpful.

Thanks
Rao

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout

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:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />

   </android.support.v4.widget.DrawerLayout>
</code>```

app_bar_main.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"
android:fitsSystemWindows="true"
tools:context="com.raoburugula.mytable.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

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

<include layout="@layout/content_main" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

 </android.support.design.widget.CoordinatorLayout>
</code>```

content_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.raoburugula.mytable.MainActivity"
tools:showIn="@layout/app_bar_main">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!" />
 </RelativeLayout>
</code>```

nav_header_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    app:srcCompat="@android:drawable/sym_def_app_icon" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:text="Android Studio"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="android.studio@android.com" />

 </LinearLayout>
</code>```

MainActivity.java

```<code>package com.raoburugula.mytable;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton)
     findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action",
     Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open,
    R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView)
    findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.overview) {
        Intent overviewIntent = new Intent(getApplicationContext(),
    OverView.class);
        startActivity(overviewIntent);
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
   }
 }
</code>```

Overview activity where I want navigation menu is

activity_over_view.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:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.raoburugula.mytable.OverView">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

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

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

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

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

 </android.support.design.widget.CoordinatorLayout>
</code>```

fragment_over_view.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.raoburugula.mytable.OverView$PlaceholderFragment">

<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

 </RelativeLayout>
</code>```

OverView.Java

```<code>package com.raoburugula.mytable;

 import android.support.design.widget.TabLayout;
 import android.support.design.widget.FloatingActionButton;
 import android.support.design.widget.Snackbar;
 import android.support.v7.app.AppCompatActivity;
 import android.support.v7.widget.Toolbar;

 import android.support.v4.app.Fragment;
 import android.support.v4.app.FragmentManager;
 import android.support.v4.app.FragmentPagerAdapter;
 import android.support.v4.view.ViewPager;
 import android.os.Bundle;
 import android.view.LayoutInflater;
 import android.view.Menu;
 import android.view.MenuItem;
  import android.view.View;
  import android.view.ViewGroup;

  import android.widget.TextView;

 public class OverView extends AppCompatActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_over_view);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new
     SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    FloatingActionButton fab = (FloatingActionButton)
      findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action",
    Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_over_view, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_over_view,
          container, false);
        TextView textView = (TextView)
          rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format,
        getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class
    below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "SECTION 1";
            case 1:
                return "SECTION 2";
            case 2:
                return "SECTION 3";
        }
        return null;
    }
   }
}
</code>```

答:
Right click anywhere in your project tab in left sidebar, choose New -> Activity -> Navigation Drawer Activity

then modify content_main.xml, add the following

```<code><android.support.v4.view.ViewPager
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/view_pager">

    <android.support.design.widget.TabLayout
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:id="@+id/tab_layout"/>

</android.support.v4.view.ViewPager>
</code>```

Title: Navigation drawer on all activities

Body:
I have two activities the first one is 'Navigation drawer activity' (MainActivity) and the second activity I have created is a 'Tabbed activity' (OverView). How can I add Navigation drawer menu on Tabbed activity.

Your help and suggestion are very helpful.

Thanks
Rao

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout

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:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />

   </android.support.v4.widget.DrawerLayout>

app_bar_main.xml

<?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"
android:fitsSystemWindows="true"
tools:context="com.raoburugula.mytable.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

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

<include layout="@layout/content_main" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

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

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.raoburugula.mytable.MainActivity"
tools:showIn="@layout/app_bar_main">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!" />
 </RelativeLayout>

nav_header_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    app:srcCompat="@android:drawable/sym_def_app_icon" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:text="Android Studio"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="android.studio@android.com" />

 </LinearLayout>

MainActivity.java

package com.raoburugula.mytable;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton)
     findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action",
     Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open,
    R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView)
    findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.overview) {
        Intent overviewIntent = new Intent(getApplicationContext(),
    OverView.class);
        startActivity(overviewIntent);
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
   }
 }

Overview activity where I want navigation menu is

activity_over_view.xml

<?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:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.raoburugula.mytable.OverView">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay">

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

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

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

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

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

fragment_over_view.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.raoburugula.mytable.OverView$PlaceholderFragment">

<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

 </RelativeLayout>

OverView.Java

package com.raoburugula.mytable;

 import android.support.design.widget.TabLayout;
 import android.support.design.widget.FloatingActionButton;
 import android.support.design.widget.Snackbar;
 import android.support.v7.app.AppCompatActivity;
 import android.support.v7.widget.Toolbar;

 import android.support.v4.app.Fragment;
 import android.support.v4.app.FragmentManager;
 import android.support.v4.app.FragmentPagerAdapter;
 import android.support.v4.view.ViewPager;
 import android.os.Bundle;
 import android.view.LayoutInflater;
 import android.view.Menu;
 import android.view.MenuItem;
  import android.view.View;
  import android.view.ViewGroup;

  import android.widget.TextView;

 public class OverView extends AppCompatActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_over_view);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new
     SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    FloatingActionButton fab = (FloatingActionButton)
      findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action",
    Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_over_view, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_over_view,
          container, false);
        TextView textView = (TextView)
          rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format,
        getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class
    below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "SECTION 1";
            case 1:
                return "SECTION 2";
            case 2:
                return "SECTION 3";
        }
        return null;
    }
   }
}

Body:
Right click anywhere in your project tab in left sidebar, choose New -> Activity -> Navigation Drawer Activity

then modify content_main.xml, add the following

<android.support.v4.view.ViewPager
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/view_pager">

    <android.support.design.widget.TabLayout
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:id="@+id/tab_layout"/>

</android.support.v4.view.ViewPager>


问:
how to configure Ngnix as reverse proxy for Phabricator ( Unhandled Exception ("AphrontMalformedRequestException"))
I am using phabricator by Docker image (https://hub.docker.com/r/hachque/phabricator/).
Because my phabricator server is in the LAN of a company, I cannot access it from the outside. I'm trying to use Ngnix as reverse proxy. I can access the login page, but when I try to login, following message was displayed:

Unhandled Exception ("AphrontMalformedRequestException")   You are
  trying to save some data to Phabricator, but the request your browser
  made included an incorrect token. Reload the page and try again. You
  may need to clear your cookies. This was a Web request. This request
  had an invalid CSRF token.

Here is part of my Nginx reverse proxy configuration:

```<code># phabricator proxy.
#
server {
    listen       8080;
    server_name  0.0.0.0;

    location / {
    proxy_pass http://193.177.1.238/;
    proxy_redirect     off;
    proxy_set_header   Host             $host;
    proxy_set_header   X-Real-IP        $remote_addr;
    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    }
}
</code>```

答:
I'm not using the same image as you, but what i've installed PHP 7.1 with Nginx and the Phabricator sources on the Docker image, then the Nginx from docker listen to the 9000 port (in my case).

Then i run this image using the 8081:9000 port mapping, and the following VirtualHost config on the Nginx from the host machine:

```<code>upstream api_upstream {
    server 0.0.0.0:8080;
}

server {
    listen 80;
    server_name phabricator.local.com;

    location / {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
        proxy_pass http://api_upstream;
    }
}
</code>```

the phabricator.local.com host only works if you add this entry to the /etc/hosts file:

```<code>127.0.0.1   phabricator.local.com
</code>```

Body:
I am using phabricator by Docker image (https://hub.docker.com/r/hachque/phabricator/).
Because my phabricator server is in the LAN of a company, I cannot access it from the outside. I'm trying to use Ngnix as reverse proxy. I can access the login page, but when I try to login, following message was displayed:

Unhandled Exception ("AphrontMalformedRequestException")   You are
  trying to save some data to Phabricator, but the request your browser
  made included an incorrect token. Reload the page and try again. You
  may need to clear your cookies. This was a Web request. This request
  had an invalid CSRF token.

Here is part of my Nginx reverse proxy configuration:

# phabricator proxy.
#
server {
    listen       8080;
    server_name  0.0.0.0;

    location / {
    proxy_pass http://193.177.1.238/;
    proxy_redirect     off;
    proxy_set_header   Host             $host;
    proxy_set_header   X-Real-IP        $remote_addr;
    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    }
}

Body:
I'm not using the same image as you, but what i've installed PHP 7.1 with Nginx and the Phabricator sources on the Docker image, then the Nginx from docker listen to the 9000 port (in my case).

Then i run this image using the 8081:9000 port mapping, and the following VirtualHost config on the Nginx from the host machine:

upstream api_upstream {
    server 0.0.0.0:8080;
}

server {
    listen 80;
    server_name phabricator.local.com;

    location / {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
        proxy_pass http://api_upstream;
    }
}

the phabricator.local.com host only works if you add this entry to the /etc/hosts file:

127.0.0.1   phabricator.local.com


问:
WindowsService don´t execute while
I'm doing a small windows service, it reads from a web service and stores the data in a local database, however, it does not finish executing the while (while it's a service), when I'm debugging it in vs 15 it works perfectly , Follow the code below.

PS: The code I used to debug I comment it before it starts, it arrives to enter the while, but only the first line and does not check the rest.

Program.cs

```<code>using System.ServiceProcess;

namespace rdi_server.service
{
static class Program
{
    static void Main()
    {

        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new Service1()
        };
        ServiceBase.Run(ServicesToRun);
    }
}
}
</code>```

Service1.CS

```<code>using System;
using System.Configuration;
using System.ServiceProcess;
using System.Threading;

namespace rdi_server.service
{
    public partial class Service1 : ServiceBase
{

    private Thread _thread;

    private Updater _updater = new Updater();

    private readonly int Interval = Convert.ToInt32(ConfigurationManager.AppSettings["timer"]);
    private readonly string Connection = ConfigurationManager.AppSettings["connection"];

    private readonly Connector _usuarioConnector;
    private readonly Connector _bandaConnector;
    private readonly Connector _generoConnector;
    private readonly Connector _musicaConnector;

    public Service1()
    {
        _usuarioConnector = new Connector("UsuarioBase");
        _bandaConnector = new Connector("BandaBase");
        _generoConnector = new Connector("GeneroBase");
        _musicaConnector = new Connector("MusicaBase");

        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        StartDebug();
    }

    public void StartDebug()
    {
        _thread = new Thread(OnTime);
        _thread.Name = "My Worker Thread";
        _thread.Start();
    }

    protected override void OnStop()
    {

    }

    protected void OnTime()
    {
        while (true)
        {
            EventLog.WriteEntry("Dentro do WHILE foi executado!");
            _updater.Do(Connection, _usuarioConnector, _generoConnector, _bandaConnector, _musicaConnector);
            EventLog.WriteEntry("Fim do while");
            Thread.Sleep(Interval);
        }
    }
}
}
</code>```

Updater.CS

```<code>using rdi_musica.core;
using System.Collections.Generic;
using System.Data.SqlClient;

    namespace rdi_server.service
    {
    class Updater
    {
    public void Do(string Connection,
                        Connector usuario,
                        Connector genero,
                        Connector banda,
                        Connector musica)
    {

        var usuarios = Loader.LoadUsuarios(usuario);
        var generos = Loader.LoadGeneros(genero);
        var bandas = Loader.LoadBandas(banda);
        var musicas = Loader.LoadMusicas(musica);

        using (var connection = new SqlConnection(Connection))
        {
            connection.Open();

            foreach (var _usuario in usuarios)
            {
                DomainDAO.InsertUsuario(connection, _usuario);
            }
            foreach (var _genero in generos)
            {
                DomainDAO.InsertGenero(connection, _genero);
            }
            foreach (var _banda in bandas)
            {
                DomainDAO.InsertBanda(connection, _banda);
            }
            foreach (var _musica in musicas)
            {
                DomainDAO.InsertMusica(connection, _musica);
            }
        }
    }
}
}
</code>```

答:
What's probably happening is you have an unhandled exception happening somewhere, which is breaking out of your while loop.

You can use the windows event log in combination with try-catch to log your errors, without breaking your infinite loop:

```<code>protected void OnTime()
{
    while (true)
    {
        try
        {
            EventLog.WriteEntry("Dentro do WHILE foi executado!");
            _updater.Do(Connection, _usuarioConnector, _generoConnector, _bandaConnector, _musicaConnector);
            EventLog.WriteEntry("Fim do while");
        }
        catch (Exception ex)
        {
            this.EventLog.WriteEntry("ERROR: " + ex.GetType().ToString() + " : " + ex.Message + " : " + ex.StackTrace, EventLogEntryType.Error);
        }

        Thread.Sleep(Interval);
    }
}
</code>```

Title: WindowsService don´t execute while

Body:
I'm doing a small windows service, it reads from a web service and stores the data in a local database, however, it does not finish executing the while (while it's a service), when I'm debugging it in vs 15 it works perfectly , Follow the code below.

PS: The code I used to debug I comment it before it starts, it arrives to enter the while, but only the first line and does not check the rest.

Program.cs

using System.ServiceProcess;

namespace rdi_server.service
{
static class Program
{
    static void Main()
    {

        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new Service1()
        };
        ServiceBase.Run(ServicesToRun);
    }
}
}

Service1.CS

using System;
using System.Configuration;
using System.ServiceProcess;
using System.Threading;

namespace rdi_server.service
{
    public partial class Service1 : ServiceBase
{

    private Thread _thread;

    private Updater _updater = new Updater();

    private readonly int Interval = Convert.ToInt32(ConfigurationManager.AppSettings["timer"]);
    private readonly string Connection = ConfigurationManager.AppSettings["connection"];

    private readonly Connector _usuarioConnector;
    private readonly Connector _bandaConnector;
    private readonly Connector _generoConnector;
    private readonly Connector _musicaConnector;

    public Service1()
    {
        _usuarioConnector = new Connector("UsuarioBase");
        _bandaConnector = new Connector("BandaBase");
        _generoConnector = new Connector("GeneroBase");
        _musicaConnector = new Connector("MusicaBase");

        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        StartDebug();
    }

    public void StartDebug()
    {
        _thread = new Thread(OnTime);
        _thread.Name = "My Worker Thread";
        _thread.Start();
    }

    protected override void OnStop()
    {

    }

    protected void OnTime()
    {
        while (true)
        {
            EventLog.WriteEntry("Dentro do WHILE foi executado!");
            _updater.Do(Connection, _usuarioConnector, _generoConnector, _bandaConnector, _musicaConnector);
            EventLog.WriteEntry("Fim do while");
            Thread.Sleep(Interval);
        }
    }
}
}

Updater.CS

using rdi_musica.core;
using System.Collections.Generic;
using System.Data.SqlClient;

    namespace rdi_server.service
    {
    class Updater
    {
    public void Do(string Connection,
                        Connector usuario,
                        Connector genero,
                        Connector banda,
                        Connector musica)
    {

        var usuarios = Loader.LoadUsuarios(usuario);
        var generos = Loader.LoadGeneros(genero);
        var bandas = Loader.LoadBandas(banda);
        var musicas = Loader.LoadMusicas(musica);

        using (var connection = new SqlConnection(Connection))
        {
            connection.Open();

            foreach (var _usuario in usuarios)
            {
                DomainDAO.InsertUsuario(connection, _usuario);
            }
            foreach (var _genero in generos)
            {
                DomainDAO.InsertGenero(connection, _genero);
            }
            foreach (var _banda in bandas)
            {
                DomainDAO.InsertBanda(connection, _banda);
            }
            foreach (var _musica in musicas)
            {
                DomainDAO.InsertMusica(connection, _musica);
            }
        }
    }
}
}

Body:
What's probably happening is you have an unhandled exception happening somewhere, which is breaking out of your while loop.

You can use the windows event log in combination with try-catch to log your errors, without breaking your infinite loop:

protected void OnTime()
{
    while (true)
    {
        try
        {
            EventLog.WriteEntry("Dentro do WHILE foi executado!");
            _updater.Do(Connection, _usuarioConnector, _generoConnector, _bandaConnector, _musicaConnector);
            EventLog.WriteEntry("Fim do while");
        }
        catch (Exception ex)
        {
            this.EventLog.WriteEntry("ERROR: " + ex.GetType().ToString() + " : " + ex.Message + " : " + ex.StackTrace, EventLogEntryType.Error);
        }

        Thread.Sleep(Interval);
    }
}


问:
React Navigation- How to Navigate to a specific index in a Datasource
I am brand new to React Native, and I'm trying to create a simple recipe app. I have the app functioning properly right until I need to navigate to a specific recipe from my dataset. I'd like to have a singleRecipe.js component that I can just pass the data and index into, and once the user click on that recipe item in the list view, it navigates to the correct data.

I have seen this done on NavigatorIOS but I can't quite figure out how to do it on the new React Navigation. Any help I would really appreciate.

Here is my Recipe List View file:

```<code>class RecipeScreen extends Component {
  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows(RecipeListData)
    };
  }
  render() {
    return (
      <View style={styles.container}>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={(RecipeListData) => <RecipeListItem {...RecipeListData} />}
        />
      </View>
    );
  }
}
</code>```

RecipeListItem.js

```<code>const RecipeListItem = props => (
  <TouchableOpacity onPress={Actions.singleRecipe}>
    <View style={styles.container}>

      <Text>
        {`${props.name}`}
      </Text>
      <Text>
        {`${props.time}`}
      </Text>

    </View>
  </TouchableOpacity>
);
</code>```

This is the single recipe page I am looking to pass the data into.

```<code>class SingleRecipe extends Component {
  render() {
    return (
      <View style={styles.container}>
        {/*// This is a single recipe I need to fill with the data from DataSource*/}
        <Text>
          This is a single recipe!
        </Text>

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

My very basic data set:

```<code>export default RecipeListData = [
  {
    "name": 'Breakfast Burritos',
    'time': "90 Minutes"
  },
  {
    "name": 'Peanut Butter Chicken',
    'time': "30 Minutes"
  },
  {
    "name": 'Sweet Potato Mash',
    'time': "20 Minutes"
  },
  {
    "name": 'Korma Curry',
    'time': "45 Minutes"
  },
  {
    "name": 'Protein Smoothie',
    'time': "20 Minutes"
  },
]
</code>```

答:
Try: Actions.singleRecipe({ data: rowData })

Then at SingleRecipe.js you should be able to access it like:

<Text>{this.props.data.name}</Text> or <Text>{this.props.data.time}</Text>

Body:
I am brand new to React Native, and I'm trying to create a simple recipe app. I have the app functioning properly right until I need to navigate to a specific recipe from my dataset. I'd like to have a singleRecipe.js component that I can just pass the data and index into, and once the user click on that recipe item in the list view, it navigates to the correct data.

I have seen this done on NavigatorIOS but I can't quite figure out how to do it on the new React Navigation. Any help I would really appreciate.

Here is my Recipe List View file:

class RecipeScreen extends Component {
  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows(RecipeListData)
    };
  }
  render() {
    return (
      <View style={styles.container}>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={(RecipeListData) => <RecipeListItem {...RecipeListData} />}
        />
      </View>
    );
  }
}

RecipeListItem.js

const RecipeListItem = props => (
  <TouchableOpacity onPress={Actions.singleRecipe}>
    <View style={styles.container}>

      <Text>
        {`${props.name}`}
      </Text>
      <Text>
        {`${props.time}`}
      </Text>

    </View>
  </TouchableOpacity>
);

This is the single recipe page I am looking to pass the data into.

class SingleRecipe extends Component {
  render() {
    return (
      <View style={styles.container}>
        {/*// This is a single recipe I need to fill with the data from DataSource*/}
        <Text>
          This is a single recipe!
        </Text>

      </View>
    );
  }
}

My very basic data set:

export default RecipeListData = [
  {
    "name": 'Breakfast Burritos',
    'time': "90 Minutes"
  },
  {
    "name": 'Peanut Butter Chicken',
    'time': "30 Minutes"
  },
  {
    "name": 'Sweet Potato Mash',
    'time': "20 Minutes"
  },
  {
    "name": 'Korma Curry',
    'time': "45 Minutes"
  },
  {
    "name": 'Protein Smoothie',
    'time': "20 Minutes"
  },
]


问:
Drools Fusion 'variablename' unexpected
I am working on making a CEP using Drools Fusion. I have two classes of events ExpectedEvent and ActualEvent. I need to make sure ActualEvent objects occur before ExpectedEvent objects. However, I cannot get the before key word to work. This is in stream mode.

```<code>import hellodrools.ExpectedEvent
import hellodrools.ActualEvent

dialect "java"

rule "On Time"

when
    ExpectedEvent($expectedtime : getStart_time()) from entry-point entry one
    $actual:ActualEvent( this after[ 1m ] $expected ) from entry-point entryone

then

    System.out.println("ON TIME expected time: " + $expectedtime + " actual time " + $actualtime);

end
</code>```

In IntelliJ I keep getting errors on $actual saying '$actual' unexpected. I cannot solve this syntax error.

答:
I don't think this is related to IntelliJ, although IntelliJ here appears not be reporting the correct error.

I believe the actual problem here is that from entry-point expects a String literal or a valid identifier, which will be used for the entry point ID (which is a String)

In your rule the "entry one" is not a valid identifier because it contains a space, and it's not a String literal because it's not enclosed in double-quotes characters (").

You can try replacing from entry-point entry one

with from entry-point "entry one"

Title: Drools Fusion 'variablename' unexpected

Body:
I am working on making a CEP using Drools Fusion. I have two classes of events ExpectedEvent and ActualEvent. I need to make sure ActualEvent objects occur before ExpectedEvent objects. However, I cannot get the before key word to work. This is in stream mode.

import hellodrools.ExpectedEvent
import hellodrools.ActualEvent

dialect "java"

rule "On Time"

when
    ExpectedEvent($expectedtime : getStart_time()) from entry-point entry one
    $actual:ActualEvent( this after[ 1m ] $expected ) from entry-point entryone

then

    System.out.println("ON TIME expected time: " + $expectedtime + " actual time " + $actualtime);

end

In IntelliJ I keep getting errors on $actual saying '$actual' unexpected. I cannot solve this syntax error.


问:
Scrolling using Selenium WebDriver with Java
I am using Selenium WebDriver to automate my browser tests.  My browser header is floating and is always present irrespective of the browser scroll.

So when  I click on certain elements that are present below the current visible region of the browser, selenium tries to scroll the element into view and click them.

But because of the auto scrolling as such the elements are scrolled behind the floating header and when any action is performed on them, the elements in the page header get clicked.

is there any way to limit the default scroll  of the WebDriver?

答:
I recently had this problem due to a Drupal menu blocking the element when I ran this code:

```<code>public void scrollTo(WebElement x) {
        ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", x);
        }
</code>```

After referencing this page, I updated to set the boolean to false using this code, and it works great:

```<code>public void scrollTo(WebElement x) {
        ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(false);", x);
        }
</code>```

Body:
I recently had this problem due to a Drupal menu blocking the element when I ran this code:

public void scrollTo(WebElement x) {
        ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", x);
        }

After referencing this page, I updated to set the boolean to false using this code, and it works great:

public void scrollTo(WebElement x) {
        ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(false);", x);
        }


问:
Why can't HTTP process write into directory with group permissions?
I'm running into an issue on both, an Amazon instance and my Mac.

I have the two users

ec2-user:ec2-user (myuser:staff for the mac)

apache:ec2-user  (_www:staff for the mac)

.

If I have a directory created by apache, the ec2-user can write perfectly underneath it

```<code>drwxrwsr-x 3 apache ec2-user 4.0K Mar 27 20:37 /path/to/sample/dir
// ec2-user can write here
</code>```

But on the reverse scenario, if ec2-user is the owner of the directory, when apache tries to write underneath it, it throws an error saying it doesn't have enough permissions.

```<code>drwxrwsr-x 3 ec2-user ec2-user 4.0K Mar 27 20:37 /path/to/sample/dir
// apache CANNOT write here
</code>```

But if I change the permissions to 777, then `apache is able to write inside it

```<code>drwxrwsrwx 3 ec2-user ec2-user 4.0K Mar 27 20:37 /path/to/sample/dir
// apache CAN write here
// file created would have `664 apache:ec2-user` permissions
</code>```

So the question is

Why though the two users have the same group, is apache not able to write into a directory that clearly has write permissions to the group?

Additional:

Though apache writes with ec2-user as group, when I execute the following, I realized that apache does not belong to the ec2-user group, so how come when it writes, files and directories created by it have such group?

```<code>sudo -u apache id
uid=48(apache) gid=48(apache) groups=48(apache)
</code>```

答:
After further research and talking with some SysAdmins, the answer was straight into the groups that apache belongs to.

Regardless of the factor that the directories files by apache had the ec2-user group, didn't mean that apache belonged to that group.

So, to address this specific request, all I had to do, is add Apache to the ec2-user group.

```<code>sudo usermod -a -G ec2-user apache
</code>```

I haven't very well figured out the mac version, but it goes along the ways of using the dseditgroup command.

Body:
I'm running into an issue on both, an Amazon instance and my Mac.

I have the two users

ec2-user:ec2-user (myuser:staff for the mac)

apache:ec2-user  (_www:staff for the mac)

.

If I have a directory created by apache, the ec2-user can write perfectly underneath it

drwxrwsr-x 3 apache ec2-user 4.0K Mar 27 20:37 /path/to/sample/dir
// ec2-user can write here

But on the reverse scenario, if ec2-user is the owner of the directory, when apache tries to write underneath it, it throws an error saying it doesn't have enough permissions.

drwxrwsr-x 3 ec2-user ec2-user 4.0K Mar 27 20:37 /path/to/sample/dir
// apache CANNOT write here

But if I change the permissions to 777, then `apache is able to write inside it

drwxrwsrwx 3 ec2-user ec2-user 4.0K Mar 27 20:37 /path/to/sample/dir
// apache CAN write here
// file created would have `664 apache:ec2-user` permissions

So the question is

Why though the two users have the same group, is apache not able to write into a directory that clearly has write permissions to the group?

Additional:

Though apache writes with ec2-user as group, when I execute the following, I realized that apache does not belong to the ec2-user group, so how come when it writes, files and directories created by it have such group?

sudo -u apache id
uid=48(apache) gid=48(apache) groups=48(apache)

Body:
After further research and talking with some SysAdmins, the answer was straight into the groups that apache belongs to.

Regardless of the factor that the directories files by apache had the ec2-user group, didn't mean that apache belonged to that group.

So, to address this specific request, all I had to do, is add Apache to the ec2-user group.

sudo usermod -a -G ec2-user apache

I haven't very well figured out the mac version, but it goes along the ways of using the dseditgroup command.


问:
How do I install cakephp bake on my hosting
I've managed to install and use cake bake with xampp, but I have no idea how to install bake with my command line on the hosting.

The error I get is:

CakePHP 3.4.4 Red Velvet already installed.

Can anyone give me some directions? Thanks.

答: Just cd to your /path/to/project/bin/ and execute the Cake command line tool with ./cake bake model Products, for example. ✌