问:
FFMPEG: AV out of sync when writing a part of a video to a new file
I'm developing a data preprocessing program for a computer vision project using FFMPEG and Face detection API. In this program, I need to extract the shots that contain human faces from a given input video file and output them into a new file. But when I played the output video file generated by that program, the video and audio track was out of sync. I think a possible reason is that the timestamp of video frame or audio frame is set incorrectly, but I can't fix it by myself as I'm not very familiar with FFMPEG library, Please help me solving this out-of-sync issue.

To simplify the code shown below, I have removed all face detection code and use an empty function called faceDetect to represent it instead.

```<code>// ffmpegAPI.cpp : Defines the entry point for the console application.
//
    #include "stdafx.h"
    #include <iostream>

    extern "C" {
    #include <libavutil/opt.h>
    #include <libavcodec/avcodec.h>
    #include <libavformat/avformat.h>
    #include <libavutil/avutil.h>
    #include <libavutil/channel_layout.h>
    #include <libavutil/common.h>
    #include <libavutil/imgutils.h>
    #include <libavutil/mathematics.h>
    #include <libavutil/samplefmt.h>
    #include <libavutil/pixdesc.h>
    #include <libswscale/swscale.h>

}
bool faceDetect(AVFrame *frame)
{
    /*...*/
    return true;
}
int main(int argc, char **argv)
{
    int64_t videoPts = 0, audioPts = 0;
    int samples_count = 0;
    AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;
    AVOutputFormat *ofmt = NULL;
    AVPacket pkt;
    AVFrame *frame = NULL;
    int videoindex = -1; int audioindex = -1;
    double videoTime = DBL_MAX;
    const char *in_filename, *out_filename;
    int ret, i;
    in_filename = "C:\\input.flv";//Input file name
    out_filename = "C:\\output.avi";//Output file name
    av_register_all();
    //Open input file
    if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0) {
        fprintf(stderr, "Could not open input file '%s'", in_filename);
        goto end;
    }
    //Find input streams
    if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {
        fprintf(stderr, "Failed to retrieve input stream information");
        goto end;
    }
    //Retrive AV stream information
    for (i = 0; i < ifmt_ctx->nb_streams; i++)
    {
        AVStream *stream;
        AVCodecContext *codec_ctx;
        stream = ifmt_ctx->streams[i];//Get current stream
        codec_ctx = stream->codec;//Get current stream codec
        if (codec_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
        {
            videoindex = i;//video stream index
        }
        else if (codec_ctx->codec_type == AVMEDIA_TYPE_AUDIO)
        {
            audioindex = i;//audio stream index
        }
        if (videoindex == -1)//no video stream is found
        {
            printf("can't find video stream\n");
            goto end;

        }
    }
    av_dump_format(ifmt_ctx, 0, in_filename, 0);
    //Configure output
    avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename);
    if (!ofmt_ctx) {
        fprintf(stderr, "Could not create output context\n");
        ret = AVERROR_UNKNOWN;
        goto end;
    }
    ofmt = ofmt_ctx->oformat;
    //Configure output streams
    for (i = 0; i < ifmt_ctx->nb_streams; i++) {//Traversal input streams
        AVStream *in_stream = ifmt_ctx->streams[i];//Get current stream
        AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec);//Create a corresponding output stream
        if (!out_stream) {
            fprintf(stderr, "Failed allocating output stream\n");
            ret = AVERROR_UNKNOWN;
            goto end;
        }
        //Copy codec from current input stream to corresponding output stream
        ret = avcodec_copy_context(out_stream->codec, in_stream->codec);
        if (ret < 0) {
            fprintf(stderr, "Failed to copy context from input to output stream codec context\n");
            goto end;
        }
        if (i == videoindex)//Video stream
        {
            if (out_stream->codec->codec_id == AV_CODEC_ID_H264)
            {
                out_stream->codec->me_range = 16;
                out_stream->codec->max_qdiff = 4;
                out_stream->codec->qmin = 10;
                out_stream->codec->qmax = 51;
                out_stream->codec->qcompress = 1;

            }
        }
        AVCodecContext *codec_ctx = out_stream->codec;
        if (codec_ctx->codec_type == AVMEDIA_TYPE_VIDEO
            || codec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
            //Find codec encoder
            AVCodec *encoder = avcodec_find_encoder(codec_ctx->codec_id);
            if (!encoder) {
                av_log(NULL, AV_LOG_FATAL, "Necessary encoder not found\n");
                ret = AVERROR_INVALIDDATA;
                goto end;
            }
            //Open encoder
            ret = avcodec_open2(codec_ctx, encoder, NULL);
            if (ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Cannot open video encoder for stream #%u\n", i);
                goto end;
            }
            out_stream->codec->codec_tag = 0;
            if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
                out_stream->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
        }
        //Open the decoder for input stream
        codec_ctx = in_stream->codec;
        if (codec_ctx->codec_type == AVMEDIA_TYPE_VIDEO
            || codec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
            ret = avcodec_open2(codec_ctx,
                avcodec_find_decoder(codec_ctx->codec_id), NULL);
            if (ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Failed to open decoder for stream #%u\n", i);
            }
        }
    }
    av_dump_format(ofmt_ctx, 0, out_filename, 1);
    //Open output file for writing
    if (!(ofmt->flags & AVFMT_NOFILE)) {
        ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);
        if (ret < 0) {
            fprintf(stderr, "Could not open output file '%s'", out_filename);
            goto end;
        }
    }

    //Write video header
    ret = avformat_write_header(ofmt_ctx, NULL);
    if (ret < 0) {
        fprintf(stderr, "Error occurred when opening output file\n");
        goto end;
    }
    //Write frames in a loop
    while (1) {
        AVStream *in_stream, *out_stream;
        //Read one frame from the input file
        ret = av_read_frame(ifmt_ctx, &pkt);
        if (ret < 0)
            break;
        in_stream = ifmt_ctx->streams[pkt.stream_index];//Get current input stream
        out_stream = ofmt_ctx->streams[pkt.stream_index];//Get current output stream
        if (pkt.stream_index == videoindex)//video frame
        {
            int got_frame;
            frame = av_frame_alloc();
            if (!frame) {
                ret = AVERROR(ENOMEM);
                break;
            }
            //Readjust packet timestamp for decoding
            av_packet_rescale_ts(&pkt,
                in_stream->time_base,
                in_stream->codec->time_base);
            //Decode video frame
            int len = avcodec_decode_video2(in_stream->codec, frame, &got_frame, &pkt);
            if (len < 0)
            {
                av_frame_free(&frame);
                av_log(NULL, AV_LOG_ERROR, "Decoding failed\n");
                break;
            }
            if (got_frame)//Got a decoded video frame
            {
                int64_t pts = av_frame_get_best_effort_timestamp(frame);
                //determine if the frame image contains human face
                bool result = faceDetect(frame);
                if (result) //face contained
                {
                    videoTime = pts* av_q2d(out_stream->time_base);
                    frame->pts = videoPts++;//Set pts of video frame
                    AVPacket enc_pkt;
                    av_log(NULL, AV_LOG_INFO, "Encoding video frame\n");
                    //Create packet for encoding
                    enc_pkt.data = NULL;
                    enc_pkt.size = 0;
                    av_init_packet(&enc_pkt);
                    //Encoding frame
                    ret = avcodec_encode_video2(out_stream->codec, &enc_pkt,
                        frame, &got_frame);
                    av_frame_free(&frame);
                    if (!(got_frame))
                        ret = 0;
                    /* Configure encoding properties */
                    enc_pkt.stream_index = videoindex;
                    av_packet_rescale_ts(&enc_pkt,
                        out_stream->codec->time_base,
                        out_stream->time_base);
                    av_log(NULL, AV_LOG_DEBUG, "Muxing frame\n");
                    /* Write encoded frame */
                    ret = av_interleaved_write_frame(ofmt_ctx, &enc_pkt);
                    if (ret < 0)
                        break;
                }
                else //no face contained
                {
                    //Set the videoTime as maximum double value,
                    //making the corresponding audio frame not been processed
                    if (videoTime < DBL_MAX)
                        videoTime = DBL_MAX;
                }

            }
            else
            {
                av_frame_free(&frame);
            }
        }
        else//Audio frame
        {
            //Get current frame time
            double audioTime = pkt.pts * av_q2d(in_stream->time_base);
            if (audioTime >= videoTime)
            {//The current frame should be written into output file
                int got_frame;
                frame = av_frame_alloc();
                if (!frame) {
                    ret = AVERROR(ENOMEM);
                    break;
                }
                //Readjust packet timestamp for decoding
                av_packet_rescale_ts(&pkt,
                    in_stream->time_base,
                    in_stream->codec->time_base);
                //Decode audio frame
                int len = avcodec_decode_audio4(in_stream->codec, frame, &got_frame, &pkt);
                if (len < 0)
                {
                    av_frame_free(&frame);
                    av_log(NULL, AV_LOG_ERROR, "Decoding failed\n");
                    break;
                }
                if (got_frame)//Got a decoded audio frame
                {
                    //Set pts of audio frame
                    frame->pts = audioPts;
                    audioPts += frame->nb_samples;
                    AVPacket enc_pkt;
                    av_log(NULL, AV_LOG_INFO, "Encoding audio frame");
                    //Create packet for encoding
                    enc_pkt.data = NULL;
                    enc_pkt.size = 0;
                    av_init_packet(&enc_pkt);
                    //Encode audio frame
                    ret = avcodec_encode_audio2(out_stream->codec, &enc_pkt,
                        frame, &got_frame);
                    av_frame_free(&frame);
                    if (!(got_frame))
                        ret = 0;
                    /* Configure encoding properties */
                    enc_pkt.stream_index = audioindex;
                    av_packet_rescale_ts(&enc_pkt,
                        out_stream->codec->time_base,
                        out_stream->time_base);
                    av_log(NULL, AV_LOG_DEBUG, "Muxing frame\n");
                    /* Write encoded frame */
                    ret = av_interleaved_write_frame(ofmt_ctx, &enc_pkt);
                    if (ret < 0)
                        break;
                }
                else //Shouldn't be written
                {
                    av_frame_free(&frame);
                }
            }
        }
        av_packet_unref(&pkt);
    }
    //Write video trailer
    av_write_trailer(ofmt_ctx);
end://Clean up
    av_log(NULL, AV_LOG_INFO, "Clean up\n");
    av_frame_free(&frame);
    for (i = 0; i < ifmt_ctx->nb_streams; i++) {
        avcodec_close(ifmt_ctx->streams[i]->codec);
        if (ofmt_ctx && ofmt_ctx->nb_streams > i && ofmt_ctx->streams[i] && ofmt_ctx->streams[i]->codec)
            avcodec_close(ofmt_ctx->streams[i]->codec);
    }
    avformat_close_input(&ifmt_ctx);
    /* Close output file */
    if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE))
        avio_closep(&ofmt_ctx->pb);
    avformat_free_context(ofmt_ctx);
    if (ret < 0 && ret != AVERROR_EOF) {
        char buf[256];
        av_strerror(ret, buf, sizeof(buf));
        av_log(NULL, AV_LOG_ERROR, "Error occurred:%s\n", buf);
        system("Pause");
        return 1;
    }
    //Program end
    printf("The End.\n");
    system("Pause");
    return 0;
}
</code>```

答:
In the original code, I have set the pts this way.

```<code> frame->pts = videoPts++;//Set pts of video frame
</code>```

This means that I assume the pts increment between each video frame is 1. But it's actually not the case when I inspected the video stream of the input file under Debug mode, finding that its pts increment is 2. After some observation, I found that the pkt_duration property of the decoded frame may stands for the pts increment in the input video stream because it has the same value with the pts increment. So I changed the above code to

```<code>frame->pts = videoPts += frame->pkt_duration;
</code>```

When I tested the modified code, the video stream and audio stream was not out of sync anymore. So far I cannot ensure that the pkt_duration and pts increment is actually the same thing, but in my case it seems like that. Anyway, using pkt_duration has solved my out-of-sync problem.

Body:
I'm developing a data preprocessing program for a computer vision project using FFMPEG and Face detection API. In this program, I need to extract the shots that contain human faces from a given input video file and output them into a new file. But when I played the output video file generated by that program, the video and audio track was out of sync. I think a possible reason is that the timestamp of video frame or audio frame is set incorrectly, but I can't fix it by myself as I'm not very familiar with FFMPEG library, Please help me solving this out-of-sync issue.

To simplify the code shown below, I have removed all face detection code and use an empty function called faceDetect to represent it instead.

// ffmpegAPI.cpp : Defines the entry point for the console application.
//
    #include "stdafx.h"
    #include <iostream>

    extern "C" {
    #include <libavutil/opt.h>
    #include <libavcodec/avcodec.h>
    #include <libavformat/avformat.h>
    #include <libavutil/avutil.h>
    #include <libavutil/channel_layout.h>
    #include <libavutil/common.h>
    #include <libavutil/imgutils.h>
    #include <libavutil/mathematics.h>
    #include <libavutil/samplefmt.h>
    #include <libavutil/pixdesc.h>
    #include <libswscale/swscale.h>

}
bool faceDetect(AVFrame *frame)
{
    /*...*/
    return true;
}
int main(int argc, char **argv)
{
    int64_t videoPts = 0, audioPts = 0;
    int samples_count = 0;
    AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;
    AVOutputFormat *ofmt = NULL;
    AVPacket pkt;
    AVFrame *frame = NULL;
    int videoindex = -1; int audioindex = -1;
    double videoTime = DBL_MAX;
    const char *in_filename, *out_filename;
    int ret, i;
    in_filename = "C:\\input.flv";//Input file name
    out_filename = "C:\\output.avi";//Output file name
    av_register_all();
    //Open input file
    if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0) {
        fprintf(stderr, "Could not open input file '%s'", in_filename);
        goto end;
    }
    //Find input streams
    if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {
        fprintf(stderr, "Failed to retrieve input stream information");
        goto end;
    }
    //Retrive AV stream information
    for (i = 0; i < ifmt_ctx->nb_streams; i++)
    {
        AVStream *stream;
        AVCodecContext *codec_ctx;
        stream = ifmt_ctx->streams[i];//Get current stream
        codec_ctx = stream->codec;//Get current stream codec
        if (codec_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
        {
            videoindex = i;//video stream index
        }
        else if (codec_ctx->codec_type == AVMEDIA_TYPE_AUDIO)
        {
            audioindex = i;//audio stream index
        }
        if (videoindex == -1)//no video stream is found
        {
            printf("can't find video stream\n");
            goto end;

        }
    }
    av_dump_format(ifmt_ctx, 0, in_filename, 0);
    //Configure output
    avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename);
    if (!ofmt_ctx) {
        fprintf(stderr, "Could not create output context\n");
        ret = AVERROR_UNKNOWN;
        goto end;
    }
    ofmt = ofmt_ctx->oformat;
    //Configure output streams
    for (i = 0; i < ifmt_ctx->nb_streams; i++) {//Traversal input streams
        AVStream *in_stream = ifmt_ctx->streams[i];//Get current stream
        AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec);//Create a corresponding output stream
        if (!out_stream) {
            fprintf(stderr, "Failed allocating output stream\n");
            ret = AVERROR_UNKNOWN;
            goto end;
        }
        //Copy codec from current input stream to corresponding output stream
        ret = avcodec_copy_context(out_stream->codec, in_stream->codec);
        if (ret < 0) {
            fprintf(stderr, "Failed to copy context from input to output stream codec context\n");
            goto end;
        }
        if (i == videoindex)//Video stream
        {
            if (out_stream->codec->codec_id == AV_CODEC_ID_H264)
            {
                out_stream->codec->me_range = 16;
                out_stream->codec->max_qdiff = 4;
                out_stream->codec->qmin = 10;
                out_stream->codec->qmax = 51;
                out_stream->codec->qcompress = 1;

            }
        }
        AVCodecContext *codec_ctx = out_stream->codec;
        if (codec_ctx->codec_type == AVMEDIA_TYPE_VIDEO
            || codec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
            //Find codec encoder
            AVCodec *encoder = avcodec_find_encoder(codec_ctx->codec_id);
            if (!encoder) {
                av_log(NULL, AV_LOG_FATAL, "Necessary encoder not found\n");
                ret = AVERROR_INVALIDDATA;
                goto end;
            }
            //Open encoder
            ret = avcodec_open2(codec_ctx, encoder, NULL);
            if (ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Cannot open video encoder for stream #%u\n", i);
                goto end;
            }
            out_stream->codec->codec_tag = 0;
            if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
                out_stream->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
        }
        //Open the decoder for input stream
        codec_ctx = in_stream->codec;
        if (codec_ctx->codec_type == AVMEDIA_TYPE_VIDEO
            || codec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
            ret = avcodec_open2(codec_ctx,
                avcodec_find_decoder(codec_ctx->codec_id), NULL);
            if (ret < 0) {
                av_log(NULL, AV_LOG_ERROR, "Failed to open decoder for stream #%u\n", i);
            }
        }
    }
    av_dump_format(ofmt_ctx, 0, out_filename, 1);
    //Open output file for writing
    if (!(ofmt->flags & AVFMT_NOFILE)) {
        ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);
        if (ret < 0) {
            fprintf(stderr, "Could not open output file '%s'", out_filename);
            goto end;
        }
    }

    //Write video header
    ret = avformat_write_header(ofmt_ctx, NULL);
    if (ret < 0) {
        fprintf(stderr, "Error occurred when opening output file\n");
        goto end;
    }
    //Write frames in a loop
    while (1) {
        AVStream *in_stream, *out_stream;
        //Read one frame from the input file
        ret = av_read_frame(ifmt_ctx, &pkt);
        if (ret < 0)
            break;
        in_stream = ifmt_ctx->streams[pkt.stream_index];//Get current input stream
        out_stream = ofmt_ctx->streams[pkt.stream_index];//Get current output stream
        if (pkt.stream_index == videoindex)//video frame
        {
            int got_frame;
            frame = av_frame_alloc();
            if (!frame) {
                ret = AVERROR(ENOMEM);
                break;
            }
            //Readjust packet timestamp for decoding
            av_packet_rescale_ts(&pkt,
                in_stream->time_base,
                in_stream->codec->time_base);
            //Decode video frame
            int len = avcodec_decode_video2(in_stream->codec, frame, &got_frame, &pkt);
            if (len < 0)
            {
                av_frame_free(&frame);
                av_log(NULL, AV_LOG_ERROR, "Decoding failed\n");
                break;
            }
            if (got_frame)//Got a decoded video frame
            {
                int64_t pts = av_frame_get_best_effort_timestamp(frame);
                //determine if the frame image contains human face
                bool result = faceDetect(frame);
                if (result) //face contained
                {
                    videoTime = pts* av_q2d(out_stream->time_base);
                    frame->pts = videoPts++;//Set pts of video frame
                    AVPacket enc_pkt;
                    av_log(NULL, AV_LOG_INFO, "Encoding video frame\n");
                    //Create packet for encoding
                    enc_pkt.data = NULL;
                    enc_pkt.size = 0;
                    av_init_packet(&enc_pkt);
                    //Encoding frame
                    ret = avcodec_encode_video2(out_stream->codec, &enc_pkt,
                        frame, &got_frame);
                    av_frame_free(&frame);
                    if (!(got_frame))
                        ret = 0;
                    /* Configure encoding properties */
                    enc_pkt.stream_index = videoindex;
                    av_packet_rescale_ts(&enc_pkt,
                        out_stream->codec->time_base,
                        out_stream->time_base);
                    av_log(NULL, AV_LOG_DEBUG, "Muxing frame\n");
                    /* Write encoded frame */
                    ret = av_interleaved_write_frame(ofmt_ctx, &enc_pkt);
                    if (ret < 0)
                        break;
                }
                else //no face contained
                {
                    //Set the videoTime as maximum double value,
                    //making the corresponding audio frame not been processed
                    if (videoTime < DBL_MAX)
                        videoTime = DBL_MAX;
                }

            }
            else
            {
                av_frame_free(&frame);
            }
        }
        else//Audio frame
        {
            //Get current frame time
            double audioTime = pkt.pts * av_q2d(in_stream->time_base);
            if (audioTime >= videoTime)
            {//The current frame should be written into output file
                int got_frame;
                frame = av_frame_alloc();
                if (!frame) {
                    ret = AVERROR(ENOMEM);
                    break;
                }
                //Readjust packet timestamp for decoding
                av_packet_rescale_ts(&pkt,
                    in_stream->time_base,
                    in_stream->codec->time_base);
                //Decode audio frame
                int len = avcodec_decode_audio4(in_stream->codec, frame, &got_frame, &pkt);
                if (len < 0)
                {
                    av_frame_free(&frame);
                    av_log(NULL, AV_LOG_ERROR, "Decoding failed\n");
                    break;
                }
                if (got_frame)//Got a decoded audio frame
                {
                    //Set pts of audio frame
                    frame->pts = audioPts;
                    audioPts += frame->nb_samples;
                    AVPacket enc_pkt;
                    av_log(NULL, AV_LOG_INFO, "Encoding audio frame");
                    //Create packet for encoding
                    enc_pkt.data = NULL;
                    enc_pkt.size = 0;
                    av_init_packet(&enc_pkt);
                    //Encode audio frame
                    ret = avcodec_encode_audio2(out_stream->codec, &enc_pkt,
                        frame, &got_frame);
                    av_frame_free(&frame);
                    if (!(got_frame))
                        ret = 0;
                    /* Configure encoding properties */
                    enc_pkt.stream_index = audioindex;
                    av_packet_rescale_ts(&enc_pkt,
                        out_stream->codec->time_base,
                        out_stream->time_base);
                    av_log(NULL, AV_LOG_DEBUG, "Muxing frame\n");
                    /* Write encoded frame */
                    ret = av_interleaved_write_frame(ofmt_ctx, &enc_pkt);
                    if (ret < 0)
                        break;
                }
                else //Shouldn't be written
                {
                    av_frame_free(&frame);
                }
            }
        }
        av_packet_unref(&pkt);
    }
    //Write video trailer
    av_write_trailer(ofmt_ctx);
end://Clean up
    av_log(NULL, AV_LOG_INFO, "Clean up\n");
    av_frame_free(&frame);
    for (i = 0; i < ifmt_ctx->nb_streams; i++) {
        avcodec_close(ifmt_ctx->streams[i]->codec);
        if (ofmt_ctx && ofmt_ctx->nb_streams > i && ofmt_ctx->streams[i] && ofmt_ctx->streams[i]->codec)
            avcodec_close(ofmt_ctx->streams[i]->codec);
    }
    avformat_close_input(&ifmt_ctx);
    /* Close output file */
    if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE))
        avio_closep(&ofmt_ctx->pb);
    avformat_free_context(ofmt_ctx);
    if (ret < 0 && ret != AVERROR_EOF) {
        char buf[256];
        av_strerror(ret, buf, sizeof(buf));
        av_log(NULL, AV_LOG_ERROR, "Error occurred:%s\n", buf);
        system("Pause");
        return 1;
    }
    //Program end
    printf("The End.\n");
    system("Pause");
    return 0;
}

Body:
In the original code, I have set the pts this way.

 frame->pts = videoPts++;//Set pts of video frame

This means that I assume the pts increment between each video frame is 1. But it's actually not the case when I inspected the video stream of the input file under Debug mode, finding that its pts increment is 2. After some observation, I found that the pkt_duration property of the decoded frame may stands for the pts increment in the input video stream because it has the same value with the pts increment. So I changed the above code to

frame->pts = videoPts += frame->pkt_duration;

When I tested the modified code, the video stream and audio stream was not out of sync anymore. So far I cannot ensure that the pkt_duration and pts increment is actually the same thing, but in my case it seems like that. Anyway, using pkt_duration has solved my out-of-sync problem.


来源: stackexchange

问:
How to set a delay on a method
When i currently call my method

```<code>public void flip() {
    Image change = new ImageIcon(this.getClass().getResource(imageName[0])).getImage();

    ImageIcon card = new ImageIcon(change);

    imagelbl.setIcon(card);
}
</code>```

Currently when the method is called the code runs and the method works. This is perfect however i need there to be a delay of 1 second before the method runs.
I have tried using setTimeout() but i was unsuccessful. How would i get this method to have a 1 sec delay before running?

答:
Use the Timer class for timing.</p>

```<code>public void callerMethod() {
    System.out.println("Start");
     Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            public void run() {
                delayedMethod();
            }
        }, 1000);
}

public void delayedMethod() {
    System.out.println("Test");
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to set a delay on a method

Body:
When i currently call my method

public void flip() {
    Image change = new ImageIcon(this.getClass().getResource(imageName[0])).getImage();

    ImageIcon card = new ImageIcon(change);

    imagelbl.setIcon(card);
}

Currently when the method is called the code runs and the method works. This is perfect however i need there to be a delay of 1 second before the method runs.
I have tried using setTimeout() but i was unsuccessful. How would i get this method to have a 1 sec delay before running?

Body:
Use the Timer class for timing.

public void callerMethod() {
    System.out.println("Start");
     Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            public void run() {
                delayedMethod();
            }
        }, 1000);
}

public void delayedMethod() {
    System.out.println("Test");
}


问:
how to protect download link using html and javascript?
i have two download links.  after right click on this link it showing option link "open in new tab" "save link as" "copy link location" and so on. but i want to protect this link. there should not showing this option when right click on download link. please help

Thanks in advance

答:
Use context menu event to prevent the menu from showing:</p>

```<code>document.getElementById('downloadThisPage').addEventListener('contextmenu', function (event) {
    event.preventDefault();

    return false;
});
</code>```

Body:
Use context menu event to prevent the menu from showing:

document.getElementById('downloadThisPage').addEventListener('contextmenu', function (event) {
    event.preventDefault();

    return false;
});


问:
Symfony liipimaginebundle: set request context scheme to https
I have done following things:

```<code>img_path = 'abc.jpg'
<img src="{{ img_path | imagine_filter(filter) }}">
</code>```

So I want to have url with https. Currently I am getting url with http.

I have set router.request_context.scheme: https in parameters. But didn't work.

So actually I want to set vendor/symfony/symfony/src/Symfony/Component/Routing/RequestContext.php
scheme property to https.

答:
Sets the HTTP host to use for future requests. You must call this before issuing any HTTP requests.
host is the name of the host, optionally with port (e.g. 'google.com' or 'localhost:5984') scheme the protocol scheme to use. Valid values are 'http', 'https'</p>

Body:
I have done following things:

img_path = 'abc.jpg'

So I want to have url with https. Currently I am getting url with http.

I have set router.request_context.scheme: https in parameters. But didn't work.

So actually I want to set vendor/symfony/symfony/src/Symfony/Component/Routing/RequestContext.php
scheme property to https.


问:
Angular 2 - Is there an event, when UI binding is finished
If I change the value of a bounded object in my component, angular automatically updates the value on the UI. This update-process takes some milliseconds (depend on the device). Is there an event when the UI-update-process finished?

At the moment I use following code:

```<code>// refresh binding
boundedItem = newValue;

// wait 100 milliseconds and the open the browsers print view
setTimeout(() => {
    // open browser print view
}, 100);
</code>```

On slow devices (smartphones) the process could be take more than 100 milliseconds, so the code is not really clean.

答:
Just invoke change detection explicitely, then you know the view is updated before further code is executed:

constructor(private cdRef:ChangeDetectorRef)  {}

someMethod() {
  boundedItem = newValue;
  this.cdRef.detectChanges();
  // view update is completed here
}
```

Body:
If I change the value of a bounded object in my component, angular automatically updates the value on the UI. This update-process takes some milliseconds (depend on the device). Is there an event when the UI-update-process finished?

At the moment I use following code:

// refresh binding
boundedItem = newValue;

// wait 100 milliseconds and the open the browsers print view
setTimeout(() => {
    // open browser print view
}, 100);

On slow devices (smartphones) the process could be take more than 100 milliseconds, so the code is not really clean.


答: Use  Thread.sleep(1000) as the first line in flip() method.

Title: How to set a delay on a method


问:
How to get unique id in iOS device?
I have used mac address to identify iOS devices in server side. When run my application with iOS 7 unable to retrieve the correct mac address. Alternately i used

```<code>NSUUID *oNSUUID = [[UIDevice currentDevice] identifierForVendor];
[strApplicationUUID setString:[oNSUUID UUIDString]];
</code>```

property. But this value also changed after every new installation of application. Now i want detect particular device in server side? How can i get some unique id per device in iOS?

答:
Getting Device Id in Swift 3.x

```<code>let deviceId = UIDevice.current.identifierForVendor?.uuidString
</code>```

Title: How to get unique id in iOS device?

Body:
I have used mac address to identify iOS devices in server side. When run my application with iOS 7 unable to retrieve the correct mac address. Alternately i used

NSUUID *oNSUUID = [[UIDevice currentDevice] identifierForVendor];
[strApplicationUUID setString:[oNSUUID UUIDString]];

property. But this value also changed after every new installation of application. Now i want detect particular device in server side? How can i get some unique id per device in iOS?

Body:
Getting Device Id in Swift 3.x

let deviceId = UIDevice.current.identifierForVendor?.uuidString


问:
Lowercase script in sql files
I have to update all words from some sql files from uppercase to lowercase except the values, which are quoted words.

The simplest solution would be a regex and I tried to create one, but since I do not have much experience, its getting to difficult

```<code>search: ([\w]+?)('[\s\S]+?')
replace: $1\L$2
</code>```

so far I did this.
There is a strange behavior happening here, in that some lines are duplicated.

the regex has to convert sql statements like this:

```<code>Insert into AAAA (FIELD1, FIELD2, FIELD3, FIELD4) values (1, 'BBB', null, 'AAA');
</code>```

to this:

```<code>insert into aaaa (field1, field2, field3, field4) values (1, 'BBB', null, 'AAA');
</code>```

答:
In Notepad++, you may also find and replace text in multiple files in folders and even subfolders. Press Ctrl+H, click Find In Files, fill out the necessary fields, and click Replace in Files.

You may match all '...' substrings and match and capture all the word character chunks, and then check what group matched. If Group 1 matched, turn it to lowercase, else, paste back as is.

Find What:      '[^']+'|(\w+)

Replace With: (?{1}\L$1:$0)

Regex details:

'[^']+' - match ', then 1+ chars other than ' and again a '

| - or

(\w+) - match and capture into Group 1 one or more word chars

Replacement pattern details:

(?{1} - if Group 1 matched...

\L$1 - return the Group 1 value in lower case

: - else...

$0 - return the whole match (the '...' substring)

) - end of the conditional replacement pattern.

Title: Lowercase script in sql files

Body:
I have to update all words from some sql files from uppercase to lowercase except the values, which are quoted words.

The simplest solution would be a regex and I tried to create one, but since I do not have much experience, its getting to difficult

search: ([\w]+?)('[\s\S]+?')
replace: $1\L$2

so far I did this.
There is a strange behavior happening here, in that some lines are duplicated.

the regex has to convert sql statements like this:

Insert into AAAA (FIELD1, FIELD2, FIELD3, FIELD4) values (1, 'BBB', null, 'AAA');

to this:

insert into aaaa (field1, field2, field3, field4) values (1, 'BBB', null, 'AAA');


问:
How to get SLF4J "Hello World" working with log4j?
The "Hello World" example from SLF4J is not working for me. I guess this is because I added slf4j-log4 to my classpath. Should I configure log4j directly for the hello world to work?

```<code>log4j:WARN No appenders could be found for logger (HelloWorld).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
</code>```

Update: I added log4j initialization, and it still doesn't work:

```<code>public static void main(String[] params) {
        org.apache.log4j.Logger.getRootLogger().addAppender(new ConsoleAppender());
        Logger logger = org.slf4j.LoggerFactory.getLogger(TestBase.class);
        logger.info("Hello World");
    }
</code>```

And I'm getting:

```<code>log4j:ERROR No output stream or file set for the appender named [null].
</code>```

答:
If you want to use slf4j simple, you need these jar files on your classpath:

slf4j-api-1.6.1.jar

slf4j-simple-1.6.1.jar

If you want to use slf4j and log4j, you need these jar files on your classpath:

slf4j-api-1.6.1.jar

slf4j-log4j12-1.6.1.jar

log4j-1.2.16.jar

No more, no less. Using slf4j simple, you'll get basic logging to your console at INFO level or higher. Using log4j, you must configure it accordingly.

ContentLicense: CC BY-SA 2.5

Body:
The "Hello World" example from SLF4J is not working for me. I guess this is because I added slf4j-log4 to my classpath. Should I configure log4j directly for the hello world to work?

log4j:WARN No appenders could be found for logger (HelloWorld).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

Update: I added log4j initialization, and it still doesn't work:

public static void main(String[] params) {
        org.apache.log4j.Logger.getRootLogger().addAppender(new ConsoleAppender());
        Logger logger = org.slf4j.LoggerFactory.getLogger(TestBase.class);
        logger.info("Hello World");
    }

And I'm getting:

log4j:ERROR No output stream or file set for the appender named [null].


问:
Prevent link to be opened in external browser with WebChromeClient
I've developed a small group of .html pages that are stored in a server.
My android app, using a webview with: setWebChromeClient loads these pages.
minSdkVersion 19
targetSdkVersion 24

The problem:
Everytime I need to load a new page, using a link in my .html page, the new page is opened in an external browser.

Url Overriding
I know about the shouldOverrideUrlLoading() method, when we're using the setWebViewClient().
But unfortunately I can't use the normal webview. I need to use the WebChromeClient() because of some feature that only work with this one. (Like the input file)

My doubt is...
How can I override my URL to force them to load inside of the webChromeClient?
I tried this but with no luck:

```<code>webView.setWebChromeClient(new WebChromeClient() {
        // (...)
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

    });
</code>```

答:
You can use following code to achieve this.</p>

```<code>WebView web = (WebView)findViewById(R.id.web);
WebSettings webSettings = web.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportMultipleWindows(true); // This forces ChromeClient enabled.

web.setWebChromeClient(new WebChromeClient(){
    @Override
    public void onReceivedTitle(WebView view, String title) {
         getWindow().setTitle(title); //Set Activity tile to page title.
    }
});

web.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return false;
    }
});
</code>```

Body:
I've developed a small group of .html pages that are stored in a server.
My android app, using a webview with: setWebChromeClient loads these pages.
minSdkVersion 19
targetSdkVersion 24

The problem:
Everytime I need to load a new page, using a link in my .html page, the new page is opened in an external browser.

Url Overriding
I know about the shouldOverrideUrlLoading() method, when we're using the setWebViewClient().
But unfortunately I can't use the normal webview. I need to use the WebChromeClient() because of some feature that only work with this one. (Like the input file)

My doubt is...
How can I override my URL to force them to load inside of the webChromeClient?
I tried this but with no luck:

webView.setWebChromeClient(new WebChromeClient() {
        // (...)
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

    });

Body:
You can use following code to achieve this.

WebView web = (WebView)findViewById(R.id.web);
WebSettings webSettings = web.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportMultipleWindows(true); // This forces ChromeClient enabled.

web.setWebChromeClient(new WebChromeClient(){
    @Override
    public void onReceivedTitle(WebView view, String title) {
         getWindow().setTitle(title); //Set Activity tile to page title.
    }
});

web.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return false;
    }
});


问:
How to use insert statement for a Hive partitioned table?
I have a hive table dynpart.

```<code>id                      int
name                    char(30)
city                    char(30)
thisday                 string

# Partition Information
# col_name              data_type               comment
thisday                 string
</code>```

It is partitioned by 'thisday' whose datatype is STRING.
How can I insert a single record into the table in a particular partition. I know there is load command to load an entire file data into hive table. I just want to know how an Insert statement can be written for a partitioned table. I tried to write command like below but this is taking data from another table.

```<code>insert into droplater partition(thisday='30/03/2017') select * from dynpart;
</code>```

The table: Droplater has the same structure as dynpart. But the above command is to insert the data from another table. What I'd like to learn is to write a simple insert command into a partition, like: insert into tabname values(1,"abcd","efgh");into the table.

答:
This will work for primitive types only (no arrays, structs etc.)

```<code>insert into tabname partition (thisday='30/03/2017') values (1,"abcd","efgh");
</code>```

This will work for all types

```<code>insert into tabname partition (thisday='30/03/2017') select 1,"abcd","efgh";
</code>```

P.s.

By all means, partition your table by date ((thisday date) )

```<code>insert into tabname partition (thisday=date '2017-03-30') ...
</code>```

or at least use the ISO date format

```<code>insert into tabname partition (thisday='2017-03-30') ...
</code>```

Body:
I have a hive table dynpart.

id                      int
name                    char(30)
city                    char(30)
thisday                 string

# Partition Information
# col_name              data_type               comment
thisday                 string

It is partitioned by 'thisday' whose datatype is STRING.
How can I insert a single record into the table in a particular partition. I know there is load command to load an entire file data into hive table. I just want to know how an Insert statement can be written for a partitioned table. I tried to write command like below but this is taking data from another table.

insert into droplater partition(thisday='30/03/2017') select * from dynpart;

The table: Droplater has the same structure as dynpart. But the above command is to insert the data from another table. What I'd like to learn is to write a simple insert command into a partition, like: insert into tabname values(1,"abcd","efgh");into the table.

Body:
This will work for primitive types only (no arrays, structs etc.)

insert into tabname partition (thisday='30/03/2017') values (1,"abcd","efgh");

This will work for all types

insert into tabname partition (thisday='30/03/2017') select 1,"abcd","efgh";

P.s.

By all means, partition your table by date ((thisday date) )

insert into tabname partition (thisday=date '2017-03-30') ...

or at least use the ISO date format

insert into tabname partition (thisday='2017-03-30') ...


问:
Treating a 1 dimensional array as a 2 d
I am working on an assignment for my school and I have an array with buttons that goes all the way from 0 to 42 and the form is something like this: ( I show it to you with letters so the format is easier to understand, keep in mind  a = 0):

a b c d e f g

h i j k l m n

o p q r s t u

I want to perform operations like getting the values of x,y coordinates, setting the values of x,y. I've already tried some things but none of them seem to work the way I want them to. And I don't know if it is worth transitioning my assignment to 2D at this point.

```<code> public partial class Form1 : Form
{
    Button[] Buttons = new Button[42];
    bool one1 = true;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.BackColor = Color.Red;
        this.Width = 500;
        this.Height = 500;

        for (int i = 0; i < Buttons.Length; i++)
        {
            int index = i;
            this.Buttons[i] = new Button();
            int x = 50 + (i % 7) * 50;
            int y = 50 + (i / 7) * 50;

            this.Buttons[i].Location = new System.Drawing.Point(x, y);
            this.Buttons[i].Name = "btn" + (index + 1);
            this.Buttons[i].Size = new System.Drawing.Size(50, 50);
            this.Buttons[i].TabIndex = i;
            this.Buttons[i].Text = Convert.ToString(index);
            this.Buttons[i].UseVisualStyleBackColor = true;
            this.Buttons[i].Visible = true;

            Buttons[i].Click += (sender1, ex) => this.buttonHasBeenPressed(sender1, index);
            this.Controls.Add(Buttons[i]);
        }
    }
</code>```

Edit: I added the code that generates the array. I tried using something like this:

```<code>  var startValue = (Button)sender;
int xCenter = startValue.Location.X
int yCenter = startValue.Location.Y
</code>```

But for some reason it didn't work as I wanted. Basically I want to generate code that when the user clicks a button, the code can check the surrounding buttons for information.

答:
If you define how many entries you have per row, you can calculate the offset inside the onedimensional array

```<code>public static void Main() {

    const int elementsPerRow = 5;
    var data = new [] {"A", "B", "C", "D", "E",
                       "F", "G", "H", "I", "J",
                       "K", "L", "M", "N", "O",
                       "P", "Q", "R", "S", "T"
                      };

    var aIndex = GetIndex(0, 0, elementsPerRow);
    var eIndex = GetIndex(0, 4, elementsPerRow);
    var pIndex = GetIndex(3, 0, elementsPerRow);
    var tIndex = GetIndex(3, 4, elementsPerRow);

    Console.WriteLine(data[aIndex]); // A
    Console.WriteLine(data[eIndex]); // E
    Console.WriteLine(data[pIndex]); // P
    Console.WriteLine(data[tIndex]); // T
}

public static int GetIndex(int rowIndex, int columnIndex, int elementsPerRow) {
    var index = rowIndex * elementsPerRow + columnIndex;
    return index;
}
</code>```

.net Fiddle

Title: Treating a 1 dimensional array as a 2 d

Body:
I am working on an assignment for my school and I have an array with buttons that goes all the way from 0 to 42 and the form is something like this: ( I show it to you with letters so the format is easier to understand, keep in mind  a = 0):

a b c d e f g

h i j k l m n

o p q r s t u

I want to perform operations like getting the values of x,y coordinates, setting the values of x,y. I've already tried some things but none of them seem to work the way I want them to. And I don't know if it is worth transitioning my assignment to 2D at this point.

 public partial class Form1 : Form
{
    Button[] Buttons = new Button[42];
    bool one1 = true;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.BackColor = Color.Red;
        this.Width = 500;
        this.Height = 500;

        for (int i = 0; i < Buttons.Length; i++)
        {
            int index = i;
            this.Buttons[i] = new Button();
            int x = 50 + (i % 7) * 50;
            int y = 50 + (i / 7) * 50;

            this.Buttons[i].Location = new System.Drawing.Point(x, y);
            this.Buttons[i].Name = "btn" + (index + 1);
            this.Buttons[i].Size = new System.Drawing.Size(50, 50);
            this.Buttons[i].TabIndex = i;
            this.Buttons[i].Text = Convert.ToString(index);
            this.Buttons[i].UseVisualStyleBackColor = true;
            this.Buttons[i].Visible = true;

            Buttons[i].Click += (sender1, ex) => this.buttonHasBeenPressed(sender1, index);
            this.Controls.Add(Buttons[i]);
        }
    }

Edit: I added the code that generates the array. I tried using something like this:

  var startValue = (Button)sender;
int xCenter = startValue.Location.X
int yCenter = startValue.Location.Y

But for some reason it didn't work as I wanted. Basically I want to generate code that when the user clicks a button, the code can check the surrounding buttons for information.

Body:
If you define how many entries you have per row, you can calculate the offset inside the onedimensional array

public static void Main() {

    const int elementsPerRow = 5;
    var data = new [] {"A", "B", "C", "D", "E",
                       "F", "G", "H", "I", "J",
                       "K", "L", "M", "N", "O",
                       "P", "Q", "R", "S", "T"
                      };

    var aIndex = GetIndex(0, 0, elementsPerRow);
    var eIndex = GetIndex(0, 4, elementsPerRow);
    var pIndex = GetIndex(3, 0, elementsPerRow);
    var tIndex = GetIndex(3, 4, elementsPerRow);

    Console.WriteLine(data[aIndex]); // A
    Console.WriteLine(data[eIndex]); // E
    Console.WriteLine(data[pIndex]); // P
    Console.WriteLine(data[tIndex]); // T
}

public static int GetIndex(int rowIndex, int columnIndex, int elementsPerRow) {
    var index = rowIndex * elementsPerRow + columnIndex;
    return index;
}

.net Fiddle


问:
Powershell - rename folder in C:\Windows\
I need some help. I need to rename a few folder in c:\Windows\ but it keeps saying that access is denied. I'm running poweshell as admin.

```<code>Rename-Item -path 'C:\Windows\SoftwareDistribution' -NewName 'C:\Windows\SoftwareDistribution.bak'
</code>```

I get the return:

```<code>Rename-Item : Access to the path 'C:\Windows\SoftwareDistribution' is denied.
At line:1 char:2
+  Rename-Item -path 'C:\Windows\SoftwareDistribution' -NewName 'C:\Win ...
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (C:\Windows\SoftwareDistribution:String) [Rename-Item], IOException
    + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand
</code>```

答:
I think the significant part of the error is where it says IOException:

```<code>+ CategoryInfo          : WriteError: (C:\Windows\SoftwareDistribution:String) [Rename-Item], IOException
</code>```

Check that the folder is not in use, just in case.

Body:
I need some help. I need to rename a few folder in c:\Windows\ but it keeps saying that access is denied. I'm running poweshell as admin.

Rename-Item -path 'C:\Windows\SoftwareDistribution' -NewName 'C:\Windows\SoftwareDistribution.bak'

I get the return:

Rename-Item : Access to the path 'C:\Windows\SoftwareDistribution' is denied.
At line:1 char:2
+  Rename-Item -path 'C:\Windows\SoftwareDistribution' -NewName 'C:\Win ...
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (C:\Windows\SoftwareDistribution:String) [Rename-Item], IOException
    + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand

Body:
I think the significant part of the error is where it says IOException:

+ CategoryInfo          : WriteError: (C:\Windows\SoftwareDistribution:String) [Rename-Item], IOException

Check that the folder is not in use, just in case.


问:
mdx calculated measure versus measure
just wondering if you could explain to me why these two mdx statements yield different results, and how I would alter the calculated measure to be correct. I am assuming the calculated measure is incorrectly using the sum function.

```<code>SELECT
{
[Measures].[PPPH]
}
ON COLUMNS,
{
[Matter].[Parent Matter Lawyer - Responsible].&[qnas]
}
ON ROWS
FROM [Expert Hypercube]
WHERE
(
[Date].[Fiscal].[Month].&[201702],
[Relative Period].[Relative Period].&[YTD]
)
</code>```

versus

```<code>with
member measures.[PPPHx] as
  sum({{linkmember([Timekeeper].[Person].currentmember,[Matter].[Parent Matter Lawyer - Responsible])}},measures.[PPPH])
select
{
measures.[PPPHx]
} on columns,
{
[Timekeeper].[Person].&[qnas]
} on rows
from [Expert Hypercube]
where
(
[Date].[Fiscal].[Month].&[201702],
[Relative Period].[Relative Period].&[YTD]
)
</code>```

答:
It's unclear why do you use Sum function at all. LinkMember function returns a member, no need to cover it with {...} like a set. Also you need to use the All member, since it returns [Timekeeper].[Person].CurrentMember + LinkMember([Timekeeper].[Person].CurrentMember,[Matter].[Parent Matter Lawyer - Responsible]).

```<code>With
Member [Measures].[PPPHx] as
(
    LinkMember([Timekeeper].[Person].CurrentMember,[Matter].[Parent Matter Lawyer - Responsible]),
    [Timekeeper].[Person].[All],
    [Measures].[PPPH]
)
</code>```

See a Richard Lees's article about it.

Title: mdx calculated measure versus measure

Body:
just wondering if you could explain to me why these two mdx statements yield different results, and how I would alter the calculated measure to be correct. I am assuming the calculated measure is incorrectly using the sum function.

SELECT
{
[Measures].[PPPH]
}
ON COLUMNS,
{
[Matter].[Parent Matter Lawyer - Responsible].&[qnas]
}
ON ROWS
FROM [Expert Hypercube]
WHERE
(
[Date].[Fiscal].[Month].&[201702],
[Relative Period].[Relative Period].&[YTD]
)

versus

with
member measures.[PPPHx] as
  sum({{linkmember([Timekeeper].[Person].currentmember,[Matter].[Parent Matter Lawyer - Responsible])}},measures.[PPPH])
select
{
measures.[PPPHx]
} on columns,
{
[Timekeeper].[Person].&[qnas]
} on rows
from [Expert Hypercube]
where
(
[Date].[Fiscal].[Month].&[201702],
[Relative Period].[Relative Period].&[YTD]
)

Body:
It's unclear why do you use Sum function at all. LinkMember function returns a member, no need to cover it with {...} like a set. Also you need to use the All member, since it returns [Timekeeper].[Person].CurrentMember + LinkMember([Timekeeper].[Person].CurrentMember,[Matter].[Parent Matter Lawyer - Responsible]).

With
Member [Measures].[PPPHx] as
(
    LinkMember([Timekeeper].[Person].CurrentMember,[Matter].[Parent Matter Lawyer - Responsible]),
    [Timekeeper].[Person].[All],
    [Measures].[PPPH]
)

See a Richard Lees's article about it.


问:
I have multiple records against an ID, I want to collapse the data as a single record in select statment
I have data as below:

```<code>COMPANY_ID  DATA
17           A
17           B
17           C
16           X
16           Y
16           X
</code>```

And i want to select it as below:

```<code>COMPANY_ID  DATA
17          A,B,C
16          X,Y,Z
</code>```

答:
You may need LISTAGG and aggregation:

```<code>select company_id, listagg(data, ',') within group ( order by data) as data
from yourTable
group by company_id
</code>```

Which gives, with your input data:

```<code>COMPANY_ID DATA
---------- ----------
        16 X,X,Y
        17 A,B,C
</code>```

Notice that I assumed that your needed result (or the input data) contains a typo.

Body:
I have data as below:

COMPANY_ID  DATA
17           A
17           B
17           C
16           X
16           Y
16           X

And i want to select it as below:

COMPANY_ID  DATA
17          A,B,C
16          X,Y,Z

Body:
You may need LISTAGG and aggregation:

select company_id, listagg(data, ',') within group ( order by data) as data
from yourTable
group by company_id

Which gives, with your input data:

COMPANY_ID DATA
---------- ----------
        16 X,X,Y
        17 A,B,C

Notice that I assumed that your needed result (or the input data) contains a typo.


问:
List of Slaves connected to master - Hudson
Is there a way to find it programatically? I need this as part of an automated run; So this would be very helpful if there is an existing remote API call which can give this.</p>

答:
Groovy script to get all computers:</p>

```<code>def jenkins = Jenkins.instance
def computers = jenkins.computers

computers.each{
  println "${it.displayName} ${it.hostName}"
}
</code>```

Body:
Groovy script to get all computers:

def jenkins = Jenkins.instance
def computers = jenkins.computers

computers.each{
  println "${it.displayName} ${it.hostName}"
}


问:
Android: Layout is broken after return from fullscreen activity
I'm developing an application which looks like a launcher but for books.

On main Activity I have book images and I can open them in specific reader application by tap. It works fine.

But when I go back from reader application I have a broken layout, upside of activity covered by a status bar. If I open the reader application one more time and return to main Activity again - all fine!

This is the code I use for open book with intent:

```<code>Intent intent = new Intent(Intent.ACTION_VIEW);

Uri bookFileUri = Uri.fromFile(new File(book.getFilePath()));
String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(bookFileUri.toString());
String mimeType = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);

intent.setDataAndType(bookFileUri, mimeType);

try {
    startActivity(intent);
} catch (ActivityNotFoundException ex) {
    Log.d("Onyx", ex.getMessage());
    Toast.makeText(getApplicationContext(), getResources().getString(R.string.error_opening_book_message), Toast.LENGTH_LONG).show();
}
</code>```

and after first time when i'm got back, i see this (look to top of activity)

How it can be fixed?

答: Try initializing views in OnResume(). When you press back then onCreate() is not called.</p>

Body:
I'm developing an application which looks like a launcher but for books.

On main Activity I have book images and I can open them in specific reader application by tap. It works fine.

But when I go back from reader application I have a broken layout, upside of activity covered by a status bar. If I open the reader application one more time and return to main Activity again - all fine!

This is the code I use for open book with intent:

Intent intent = new Intent(Intent.ACTION_VIEW);

Uri bookFileUri = Uri.fromFile(new File(book.getFilePath()));
String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(bookFileUri.toString());
String mimeType = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);

intent.setDataAndType(bookFileUri, mimeType);

try {
    startActivity(intent);
} catch (ActivityNotFoundException ex) {
    Log.d("Onyx", ex.getMessage());
    Toast.makeText(getApplicationContext(), getResources().getString(R.string.error_opening_book_message), Toast.LENGTH_LONG).show();
}

and after first time when i'm got back, i see this (look to top of activity)

How it can be fixed?


问:
How can we display ModelAndView model value in a jsp page in a popup
I have a jsp submit-cot.jsp from where I hit the controller below and the form is sucessfully submitted, and I am redirected to the submit-cot.jsp page again.

```<code>@RequestMapping(value = "/submitform", method = RequestMethod.POST)
    public ModelAndView submitform(
            ModelAndView model,
            @ModelAttribute("cot") Cot cot,
            @ModelAttribute("platformUrl") PlatformUrlView platformUrl,
            final HttpServletRequest request)
    {
        cotService.save(cot,platformUrl);
        model.setViewName("redirect:/submit-cot");
        model.addObject("msg", resource.getMsg("A45"));
        return model;
    }
</code>```

The problem is that the message 'msg' comes in the url, as
    http://localhost:8080/submit-cot?msg=Cot+is+submitted+successfully.
I need to display the message 'msg' in a popup.

Can anybody please suggest how to get the message in a popup.
Thanks in advance.

答:
Since you are performing a redirect from your Controller, the default redirect mechanism will add the attribute's value to be appended to the url as that is the only way to be able to maintain the value across a request-response-request cycle without maintaining a server side session.

The solution to your problem is to use Spring's flash attributes feature which is specifically meant to solve this.

You can change your controller code as below

```<code>@RequestMapping(value = "/submitform", method = RequestMethod.POST)
public RedirectView submitform(
        ModelAndView model,
        @ModelAttribute("cot") Cot cot,
        @ModelAttribute("platformUrl") PlatformUrlView platformUrl,
        final HttpServletRequest request
        final RedirectAttributes redirAttr)
{
    cotService.save(cot,platformUrl);

    RedirectView redirectView = new RedirectView();
    redirectView.setContextRelative(true);
    redirectView.setUrl("/submit-cot");
    redirAttr.addAttribute("msg", resource.getMsg("A45"));

    return redirectView;
}
</code>```

In your Controller code for processing the "/submit-cot" url, you can retrieve the value using RequestContextUtils and set it in the ModelAndView for further processing. Example below

```<code>@RequestMapping(value = "/submit-cot", method = RequestMethod.GET)
public ModelAndView submitCot(
        ModelAndView model,
        final HttpServletRequest request)
{
    model.setViewName("popup-view");

    Map<String, ?> flashMap = RequestContextUtils.getInputFlashMap(request);
    if (flashMap != null) {
        model.addAttribute("msg", msg);
    }

    return model;
}
</code>```

Finally, in your view, you can place your logic for conditionally displaying the popup.

Documentation link for further reading - https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-flash-attributes

Body:
I have a jsp submit-cot.jsp from where I hit the controller below and the form is sucessfully submitted, and I am redirected to the submit-cot.jsp page again.

@RequestMapping(value = "/submitform", method = RequestMethod.POST)
    public ModelAndView submitform(
            ModelAndView model,
            @ModelAttribute("cot") Cot cot,
            @ModelAttribute("platformUrl") PlatformUrlView platformUrl,
            final HttpServletRequest request)
    {
        cotService.save(cot,platformUrl);
        model.setViewName("redirect:/submit-cot");
        model.addObject("msg", resource.getMsg("A45"));
        return model;
    }

The problem is that the message 'msg' comes in the url, as
    http://localhost:8080/submit-cot?msg=Cot+is+submitted+successfully.
I need to display the message 'msg' in a popup.

Can anybody please suggest how to get the message in a popup.
Thanks in advance.

Body:
Since you are performing a redirect from your Controller, the default redirect mechanism will add the attribute's value to be appended to the url as that is the only way to be able to maintain the value across a request-response-request cycle without maintaining a server side session.

The solution to your problem is to use Spring's flash attributes feature which is specifically meant to solve this.

You can change your controller code as below

@RequestMapping(value = "/submitform", method = RequestMethod.POST)
public RedirectView submitform(
        ModelAndView model,
        @ModelAttribute("cot") Cot cot,
        @ModelAttribute("platformUrl") PlatformUrlView platformUrl,
        final HttpServletRequest request
        final RedirectAttributes redirAttr)
{
    cotService.save(cot,platformUrl);

    RedirectView redirectView = new RedirectView();
    redirectView.setContextRelative(true);
    redirectView.setUrl("/submit-cot");
    redirAttr.addAttribute("msg", resource.getMsg("A45"));

    return redirectView;
}

In your Controller code for processing the "/submit-cot" url, you can retrieve the value using RequestContextUtils and set it in the ModelAndView for further processing. Example below

@RequestMapping(value = "/submit-cot", method = RequestMethod.GET)
public ModelAndView submitCot(
        ModelAndView model,
        final HttpServletRequest request)
{
    model.setViewName("popup-view");

    Map<String, ?> flashMap = RequestContextUtils.getInputFlashMap(request);
    if (flashMap != null) {
        model.addAttribute("msg", msg);
    }

    return model;
}

Finally, in your view, you can place your logic for conditionally displaying the popup.

Documentation link for further reading - https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-flash-attributes


问:
CSS overflow: visible not working
Don't properties overflow-y: scroll; overflow-x: visible; to one element. Help solve the problem. If the left menu is collapsed, when you hover over the li with a child element with class submenu, the submenu doesn't appear because of overflow-y scroll. How to get around the problem?

.fixed-leftmenu .col-left-nano {
   position : relative;
   width    : 100%;
   height   : 100%;
   overflow : visible;
 }
 .fixed-leftmenu .col-left-nano > .col-left-nano-content {
   position      : absolute;
   overflow-y    : scroll;
   overflow-x    : visible;
   top           : 0;
   right         : 0;
   bottom        : 0;
   left          : 0;
 }
 .fixed-leftmenu #nav-col {
  height: 100%;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="col-left" class="col-left-nano">
    <div id="col-left-inner" class="col-left-nano-content" style="padding-right: 12px">

        <div class="collapse navbar-collapse navbar-ex1-collapse" id="sidebar-nav">
            <ul class="nav nav-pills nav-stacked">
                <li>

                        <i class="fa fa-home"></i>
                        <span>blabla</span>

                </li>
                <li>
                    {% url 'calendar' as calendar_url %}

                        <i class="fa fa-calendar"></i>
                        <span>blabla</span>

                </li>

                <li>
                    {% url 'lesson_list' as lesson_list_url %}

                        <i class="fa fa-mortar-board "></i>
                        <span>blabla</span>

                </li>

                {% if user.is_admin %}

                <li class="active  open">

                        <i class="fa fa-send-o"></i>
                        <span>blabla</span>
                        <i class="fa fa-chevron-circle-right drop-icon"></i>

                    <ul class="submenu">
                       <li>

                                <i class="fa fa-send-o"></i>
                                <span>blabla</span>

                        </li>
                        <li>

                                <i class="fa glyphicon-envelope"></i>
                                <span>blabla</span>

                        </li>
                        <li>

                                <i class="fa fa-cogs"></i>
                                <span>blabla</span>

                        </li>
                    </ul>
                </li>

                <li>
                    {% url 'user_answer_list' as user_answer_list %}

                        <i class="fa glyphicon-pencil"></i>
                        <span>blabla</span>

                </li>
                <li>
                    {% url 'docs_list' as docs_list %}

                        <i class="fa fa-briefcase"></i>
                        <span>blabla</span>

                </li>
                <li>
                    {% url 'news_list' as news_list %}

                        <i class="fa fa-list"></i>
                        <span>news</span>

                </li>

                <li class="active  open">

                        <i class="fa fa-pencil-square-o"></i>
                        <span>blabla</span>
                        <i class="fa fa-chevron-circle-right drop-icon"></i>

                    <ul class="submenu">
                       <li>

                                <i class="fa fa-pencil-square-o"></i>
                                <span>blabla</span>

                        </li>
                        <li>

                            <i class="fa fa-phone"></i>
                            <span>blabla</span>

                        </li>
                    </ul>
                </li>

                <li>
                    {% url 'feedback_list' as feedback_list %}

                        <i class="fa fa-comments"></i>
                        <span>blabla</span>

                </li>

                 <li class="active  open">

                        <i class="fa fa-users"></i>
                        <span>blabla</span>
                        <i class="fa fa-chevron-circle-right drop-icon"></i>

                    <ul class="submenu">
                        <li>

                                <i class="fa fa-users"></i>
                                <span>blabla</span>

                        </li>
                        <li>

                                <i class="fa fa-male"></i>
                                <span>blabla</span>

                        </li>
                    </ul>
                </li>

                <li class="{% if direction_url == request.path %}active  open{% endif %}
                   {% if course_list == request.path %}active  open{% endif %}">
                    {% url 'direction_list' as direction_url %}

                        <i class="fa fa-university"></i>
                        <span>blabla</span>
                        <i class="fa fa-chevron-circle-right drop-icon"></i>

                    <ul class="submenu">
                        <li>

                                <i class="fa fa-university"></i>
                                <span>blabla</span>

                        </li>
                        <li>

                                <i class="fa fa-mortar-board"></i>
                                <span>blabla</span>

                        </li>

                    </ul>
                </li>

                {% endif %}

                <li>
                    {% url 'certify' as certify_url %}

                        <i class="fa fa-file-text-o"></i>
                        <span>blabla</span>

                </li>
                </ul>
        </div>
    </div>
</section></code>```

答: Property overflow: scroll overlaps the overflow: visible. Therefore, the problem to solve in this way it is impossible.</p>

Title: CSS overflow: visible not working

Body:
Don't properties overflow-y: scroll; overflow-x: visible; to one element. Help solve the problem. If the left menu is collapsed, when you hover over the li with a child element with class submenu, the submenu doesn't appear because of overflow-y scroll. How to get around the problem?

.fixed-leftmenu .col-left-nano {
   position : relative;
   width    : 100%;
   height   : 100%;
   overflow : visible;
 }
 .fixed-leftmenu .col-left-nano > .col-left-nano-content {
   position      : absolute;
   overflow-y    : scroll;
   overflow-x    : visible;
   top           : 0;
   right         : 0;
   bottom        : 0;
   left          : 0;
 }
 .fixed-leftmenu #nav-col {
  height: 100%;
 }

                        blabla

                    {% url 'calendar' as calendar_url %}

                        blabla

                    {% url 'lesson_list' as lesson_list_url %}

                        blabla

                {% if user.is_admin %}

                        blabla

                                blabla

                                blabla

                                blabla

                    {% url 'user_answer_list' as user_answer_list %}

                        blabla

                    {% url 'docs_list' as docs_list %}

                        blabla

                    {% url 'news_list' as news_list %}

                        news

                        blabla

                                blabla

                            blabla

                    {% url 'feedback_list' as feedback_list %}

                        blabla

                        blabla

                                blabla

                                blabla

                    {% url 'direction_list' as direction_url %}

                        blabla

                                blabla

                                blabla

                {% endif %}

                    {% url 'certify' as certify_url %}

                        blabla


问:
Trying to exec javac.exe from a php script
i have a php script with the line:

```<code>exec( "javac Test.java" );
</code>```

I get this error in the apache error log when I execute the script from the browser:

'javac' is not recognized as an internal or external command,
  operable program or batch file.

but I am pretty sure it's not a path issue, executing the java command works - it's in the same dir as javac - and executing javac works if I run the php script from the shell, not the browser.

The directory that Test.java resides in is generated by the script, with full permissions - 777

I am running xampp on Windows 10 on a Surface Notebook.  Any help would be appreciated.

答:
You need to use the full path to javac for it to work correctly, e.g.

```<code>exec( "C:\path\to\javac Test.java" );
</code>```

Depending on your system and Java version, the path could be similar to:

```<code>C:\Program Files\Java\jdkx.x.x\bin
</code>```

Body:
i have a php script with the line:

exec( "javac Test.java" );

I get this error in the apache error log when I execute the script from the browser:

'javac' is not recognized as an internal or external command,
  operable program or batch file.

but I am pretty sure it's not a path issue, executing the java command works - it's in the same dir as javac - and executing javac works if I run the php script from the shell, not the browser.

The directory that Test.java resides in is generated by the script, with full permissions - 777

I am running xampp on Windows 10 on a Surface Notebook.  Any help would be appreciated.

Body:
You need to use the full path to javac for it to work correctly, e.g.

exec( "C:\path\to\javac Test.java" );

Depending on your system and Java version, the path could be similar to:

C:\Program Files\Java\jdkx.x.x\bin


问:
What is the best way to avoid getting "Emacs Pinky"?
I just started using GNU Emacs as my text editor and I am concerned about getting afflicted with "Emacs Pinky" by having to constantly press the control key with my pinky finger as is required when using Emacs. How can I avoid potentially getting this type of repetitive strain injury?</p>

答:
Consider a Kinesis Contoured keyboard.  It took me about a month to get up to speed with mine and I now consider it to be the ideal Emacs keyboard, even without the foot-pedal.

No joke. I ordered my first one with a food-pedal, but found I wasn't actually capable of coordinating the timing of my feet and my hands sufficiently to make much use of it for modifier keys. For a while I used it to toggle the integrated number pad, but I gave that up when I realized I wasn't using it because the number row on the Kinesis is so easy to reach.

OwnerDisplayName: Ray Vega

OwnerDisplayName: bendin


问:
How do I make a text input non-editable?
So I have a text input

```<code><input type="text" value="3" class="field left">
</code>```

Here is my CSS for it

```<code>background:url("images/number-bg.png") no-repeat scroll 0 0 transparent;
border:0 none;
color:#FFFFFF;
height:17px;
margin:0 13px 0 0;
text-align:center;
width:17px;
</code>```

Is there a setting or a trick to this, I was thinking of doing a label instead but how about the styling. How do I convert them and is there a better way or is that the only way?

答:
```<code><input type="text" value="3" class="field left" readonly>
</code>```

You could see  in https://www.w3schools.com/tags/att_input_readonly.asp

The method to set "readonly":

```<code>$("input").attr("readonly", true)
</code>```

to cancel "readonly"(work in jQuery):

```<code>$("input").attr("readonly", false)
</code>```

Body:
So I have a text input

<input type="text" value="3" class="field left">

Here is my CSS for it

background:url("images/number-bg.png") no-repeat scroll 0 0 transparent;
border:0 none;
color:#FFFFFF;
height:17px;
margin:0 13px 0 0;
text-align:center;
width:17px;

Is there a setting or a trick to this, I was thinking of doing a label instead but how about the styling. How do I convert them and is there a better way or is that the only way?

Body:
<input type="text" value="3" class="field left" readonly>

You could see  in https://www.w3schools.com/tags/att_input_readonly.asp

The method to set "readonly":

$("input").attr("readonly", true)

to cancel "readonly"(work in jQuery):

$("input").attr("readonly", false)


问:
Specify 'PATH' environment does not work when running Gradle 'exec'
I tried to call npm in my Gradle build. The npm is installed via homebrew into /usr/local/bin. The gradle will fail to find npm when executing it.

However it always failed after I added PATH environment variable when executing npm command.

The only workaround for me is using absolute path for npm, it does not make sense to use same gradle script in Linux.

Did anyone meet the similar issue? Should I open ticket for gradle?

Below is my build.gradle,

```<code>import org.gradle.api.tasks.Exec
import org.apache.tools.ant.taskdefs.condition.Os

ext {
        npmCommand = Os.isFamily(Os.FAMILY_WINDOWS) ? 'npm.cmd' : 'npm'
        npmPath = Os.isFamily(Os.FAMILY_WINDOWS) ? '' : '/bin/:/usr/bin/:/usr/local/bin/'
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.4'
}
// Install packages from package.json
task npm(type: Exec) {
        description = "Grab NodeJS dependencies (from package.json)"
        environment PATH: npmPath
        workingDir = 'src/webapp'
        commandLine = [npmCommand, "install"]
        inputs.file "src/webapp/package.json"
}
</code>```

Below is complete output of gradle,

```<code>./gradlew npm -S
:npm FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':npm'.
> A problem occurred starting process 'command 'npm''

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':npm'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:310)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:90)
    at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:49)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.health.DaemonHealthTracker.execute(DaemonHealthTracker.java:47)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:66)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:71)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.health.HintGCAfterBuild.execute(HintGCAfterBuild.java:41)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:246)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.process.internal.ExecException: A problem occurred starting process 'command 'npm''
    at org.gradle.process.internal.DefaultExecHandle.setEndStateInfo(DefaultExecHandle.java:196)
    at org.gradle.process.internal.DefaultExecHandle.failed(DefaultExecHandle.java:325)
    at org.gradle.process.internal.ExecHandleRunner.run(ExecHandleRunner.java:83)
    ... 5 more
Caused by: net.rubygrapefruit.platform.NativeException: Could not start 'npm'
    at net.rubygrapefruit.platform.internal.DefaultProcessLauncher.start(DefaultProcessLauncher.java:27)
    at net.rubygrapefruit.platform.internal.WrapperProcessLauncher.start(WrapperProcessLauncher.java:36)
    at org.gradle.process.internal.ExecHandleRunner.run(ExecHandleRunner.java:65)
    ... 5 more
Caused by: java.io.IOException: Cannot run program "npm" (in directory "/Users/kane/git/videome/wechat/src/webapp"): error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at net.rubygrapefruit.platform.internal.DefaultProcessLauncher.start(DefaultProcessLauncher.java:25)
    ... 7 more
Caused by: java.io.IOException: error=2, No such file or directory
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:248)
    at java.lang.ProcessImpl.start(ProcessImpl.java:134)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    ... 8 more

BUILD FAILED

Total time: 1.139 secs
</code>```

The task will run fine if changing to the absolute path of npm,

npmCommand = Os.isFamily(Os.FAMILY_WINDOWS) ? 'npm.cmd' : '/usr/local/bin/npm'

答:
Just change to this</p>

```<code>ext {
    npmCommand = Os.isFamily(Os.FAMILY_WINDOWS) ? 'npm.cmd' : '/usr/local/bin/npm'
    npmPath = Os.isFamily(Os.FAMILY_WINDOWS) ? '' : '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin'
}
</code>```

Body:
I tried to call npm in my Gradle build. The npm is installed via homebrew into /usr/local/bin. The gradle will fail to find npm when executing it.

However it always failed after I added PATH environment variable when executing npm command.

The only workaround for me is using absolute path for npm, it does not make sense to use same gradle script in Linux.

Did anyone meet the similar issue? Should I open ticket for gradle?

Below is my build.gradle,

import org.gradle.api.tasks.Exec
import org.apache.tools.ant.taskdefs.condition.Os

ext {
        npmCommand = Os.isFamily(Os.FAMILY_WINDOWS) ? 'npm.cmd' : 'npm'
        npmPath = Os.isFamily(Os.FAMILY_WINDOWS) ? '' : '/bin/:/usr/bin/:/usr/local/bin/'
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.4'
}
// Install packages from package.json
task npm(type: Exec) {
        description = "Grab NodeJS dependencies (from package.json)"
        environment PATH: npmPath
        workingDir = 'src/webapp'
        commandLine = [npmCommand, "install"]
        inputs.file "src/webapp/package.json"
}

Below is complete output of gradle,

./gradlew npm -S
:npm FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':npm'.
> A problem occurred starting process 'command 'npm''

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':npm'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:310)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:90)
    at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:49)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.health.DaemonHealthTracker.execute(DaemonHealthTracker.java:47)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:66)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:71)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.health.HintGCAfterBuild.execute(HintGCAfterBuild.java:41)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:246)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.process.internal.ExecException: A problem occurred starting process 'command 'npm''
    at org.gradle.process.internal.DefaultExecHandle.setEndStateInfo(DefaultExecHandle.java:196)
    at org.gradle.process.internal.DefaultExecHandle.failed(DefaultExecHandle.java:325)
    at org.gradle.process.internal.ExecHandleRunner.run(ExecHandleRunner.java:83)
    ... 5 more
Caused by: net.rubygrapefruit.platform.NativeException: Could not start 'npm'
    at net.rubygrapefruit.platform.internal.DefaultProcessLauncher.start(DefaultProcessLauncher.java:27)
    at net.rubygrapefruit.platform.internal.WrapperProcessLauncher.start(WrapperProcessLauncher.java:36)
    at org.gradle.process.internal.ExecHandleRunner.run(ExecHandleRunner.java:65)
    ... 5 more
Caused by: java.io.IOException: Cannot run program "npm" (in directory "/Users/kane/git/videome/wechat/src/webapp"): error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at net.rubygrapefruit.platform.internal.DefaultProcessLauncher.start(DefaultProcessLauncher.java:25)
    ... 7 more
Caused by: java.io.IOException: error=2, No such file or directory
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:248)
    at java.lang.ProcessImpl.start(ProcessImpl.java:134)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    ... 8 more

BUILD FAILED

Total time: 1.139 secs

The task will run fine if changing to the absolute path of npm,

npmCommand = Os.isFamily(Os.FAMILY_WINDOWS) ? 'npm.cmd' : '/usr/local/bin/npm'

Body:
Just change to this

ext {
    npmCommand = Os.isFamily(Os.FAMILY_WINDOWS) ? 'npm.cmd' : '/usr/local/bin/npm'
    npmPath = Os.isFamily(Os.FAMILY_WINDOWS) ? '' : '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin'
}


问:
Query_while in Laravel
How would I do such a similar query with laravel?

```<code>$GLOBALS['db']->query_while("SELECT * FROM games
WHERE id_gioco='".$id_gioco."' AND id_utente='".$USER['id']."'");
</code>```

In the documentation of laravel and Eloquent, I found nothing on query_while.

答:
Not sure what a while query is , but the following should work. If you chain 2 where clauses it will make it an AND where()</p>

```<code>$games = Game::where('id_gioco', $id_gioco)->where('id_utente', $user->id)->get()
</code>```

Title: Query_while in Laravel

Body:
How would I do such a similar query with laravel?

$GLOBALS['db']->query_while("SELECT * FROM games
WHERE id_gioco='".$id_gioco."' AND id_utente='".$USER['id']."'");

In the documentation of laravel and Eloquent, I found nothing on query_while.

Body:
Not sure what a while query is , but the following should work. If you chain 2 where clauses it will make it an AND where()

$games = Game::where('id_gioco', $id_gioco)->where('id_utente', $user->id)->get()