问:
FFmpeg.AutoGen use avfilter_graph_create_filter return -22
all

i used FFmpeg.AutoGen 3.2 ,vs2015 in win7,copy a Example from FFmpeg(http://ffmpeg.org/doxygen/trunk/filtering_video_8c-example.html),

when run

```<code> string video = @"e:\\1.avi";
 FilterVideo fv = new FilterVideo();
 fv.filtertest(video);
</code>```

return  errorcode -22:
args:video_size=640x480:pix_fmt=AV_PIX_FMT_YUV420P:time_base=1/25:pixel_aspect=1/1
Cannot create buffer source
-22

thanks for any rep.

blow is code :

```<code>using FFmpeg.AutoGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace videoFFmpegAutoGen.tool
{
    public unsafe class FilterVideo
    {

        public int open_input_file(string filename)
        {
            try
            {
                int ret;
                AVCodec* dec;
                fixed (AVFormatContext** at = &fmt_ctx)
                {
                    ret = ffmpeg.avformat_open_input(at, filename, null, null);
                }

                if (ret < 0)
                {
                    Console.WriteLine("Cannot open input file\n");
                    return ret;
                }
                ret = ffmpeg.avformat_find_stream_info(fmt_ctx, null);
                if (ret < 0)
                {
                    Console.WriteLine("Cannot find stream information\n");
                    return ret;
                }
                ret = ffmpeg.av_find_best_stream(fmt_ctx, AVMediaType.AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0);
                if (ret < 0)
                {
                    Console.WriteLine("Cannot find a video stream in the input file\n");
                    return ret;
                }

                video_stream_index = ret;

                /* create decoding context */
                dec_ctx = ffmpeg.avcodec_alloc_context3(dec);

                ffmpeg.avcodec_parameters_to_context(dec_ctx, fmt_ctx->streams[video_stream_index]->codecpar);
                ffmpeg.av_opt_set_int(dec_ctx, "refcounted_frames", 1, 0);
                /* init the video decoder */
                if ((ret = ffmpeg.avcodec_open2(dec_ctx, dec, null)) < 0)
                {
                    Console.WriteLine("Cannot open video decoder\n");
                    return ret;
                }

                return ret;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {

            }

            return -1;
        }

        private string filters_descr = "scale=78:24,transpose=cclock";
        private int video_stream_index = -1;
        private AVFormatContext* fmt_ctx;
        private AVFilterGraph* filter_graph;

        AVFilterContext* buffersrc_ctx;
        private AVCodecContext* dec_ctx;
        AVFilterContext* buffersink_ctx;
        public unsafe int init_filters(string filters_descr)
        {

            int ret = 0;
            AVFilterInOut* outputs = null;
            AVFilterInOut* inputs = null;
            try
            {
                AVFilter* buffersrc = ffmpeg.avfilter_get_by_name("buffer");
                AVFilter* buffersink = ffmpeg.avfilter_get_by_name("buffersink");
                outputs = ffmpeg.avfilter_inout_alloc();
                inputs = ffmpeg.avfilter_inout_alloc();
                AVRational time_base = fmt_ctx->streams[video_stream_index]->time_base;
                filter_graph = ffmpeg.avfilter_graph_alloc();
                //string args = string.Format("video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d", dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt, time_base.num, time_base.den, dec_ctx->sample_aspect_ratio.num, dec_ctx->sample_aspect_ratio.den);
                string args = string.Format("video_size={0}x{1}:pix_fmt={2}:time_base={3}/{4}:pixel_aspect={5}/{6}", dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt, time_base.num, time_base.den, dec_ctx->sample_aspect_ratio.num, dec_ctx->sample_aspect_ratio.den);
                // string args = string.Format("video_size={0}x{1}:time_base={2}/{3}:pixel_aspect={4}/{5}", dec_ctx->width, dec_ctx->height, time_base.num, time_base.den, dec_ctx->sample_aspect_ratio.num, dec_ctx->sample_aspect_ratio.den);
               // string args = string.Format("video_size={0}x{1}", dec_ctx->width, dec_ctx->height);
                Console.WriteLine("args:" + args);
                fixed (AVFilterContext** at= &buffersrc_ctx)
                {
                    ret = ffmpeg.avfilter_graph_create_filter(at, buffersrc, "in", args, null, filter_graph);
                }

                if (ret < 0)
                {
                    Console.WriteLine("Cannot create buffer source\n"+ret);
                    return ret;
                }
                fixed (AVFilterContext** at = &buffersink_ctx)
                {
                    ret = ffmpeg.avfilter_graph_create_filter(at, buffersink, "out", null, null, filter_graph);
                }

                if (ret < 0)
                {
                    Console.WriteLine("Cannot create buffer sink\n");
                    return ret;
                }
               // ret = ffmpeg.av_opt_set_int_list(buffersink_ctx, "pix_fmts", pix_fmts,AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN);

                /*
                * The buffer source output must be connected to the input pad of
                * the first filter described by filters_descr; since the first
                * filter input label is not specified, it is set to "in" by
                * default.
                */
                outputs->name = ffmpeg.av_strdup("in");
                outputs->filter_ctx = buffersrc_ctx;
                outputs->pad_idx = 0;
                outputs->next = null;
                /*
                 * The buffer sink input must be connected to the output pad of
                 * the last filter described by filters_descr; since the last
                 * filter output label is not specified, it is set to "out" by
                 * default.
                 */
                inputs->name = ffmpeg.av_strdup("out");
                inputs->filter_ctx = buffersink_ctx;
                inputs->pad_idx = 0;
                inputs->next = null;

                ret = ffmpeg.avfilter_graph_parse_ptr(filter_graph, filters_descr, &inputs, &outputs, null);
                if (ret < 0)
                {
                    return ret;
                }
                ret = ffmpeg.avfilter_graph_config(filter_graph, null);
                if (ret < 0)
                {
                    return ret;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                ffmpeg.avfilter_inout_free(&inputs);
                ffmpeg.avfilter_inout_free(&outputs);
            }

            return ret;

        }

        long AV_NOPTS_VALUE = 1;
        //int last_pts = AV_NOPTS_VALUE;
        long last_pts = 1;

        public void display_frame(AVFrame* frame, AVRational time_base)
        {
            int x, y;
            long delay;
            sbyte* p0;
            sbyte* p;
            AVRational cq = new AVRational();
            cq.num = 1;
            cq.den = 1000000;
            if (frame->pts != AV_NOPTS_VALUE)
            {
                if (last_pts != AV_NOPTS_VALUE)
                {
                    /* sleep roughly the right amount of time;
                     * usleep is in microseconds, just like AV_TIME_BASE. */
                    delay = ffmpeg.av_rescale_q(frame->pts - last_pts, time_base, cq);
                    if (delay > 0 && delay < 1000000)
                        Thread.Sleep((int)delay);
                }
                last_pts = frame->pts;
            }

            /* Trivial ASCII grayscale display. */
            p0 = frame->data0;
            //puts("\033c");
            for (y = 0; y < frame->height; y++)
            {
                p = p0;
                //for (x = 0; x < frame->width; x++)
                //putchar(" .-+#"[*(p++) / 52]);
                //putchar('\n');
                p0 += frame->linesize[0];
            }

            //fflush(stdout);

        }

        private int AV_BUFFERSRC_FLAG_KEEP_REF = 8 ;

        public unsafe void filtertest(string inputvideo)
        {
            AVFrame* frame = ffmpeg.av_frame_alloc();
            AVFrame* filt_frame = ffmpeg.av_frame_alloc();
            try
            {

                int ret;
                AVPacket packet;

                ffmpeg.av_register_all();
                ffmpeg.avfilter_register_all();

                ret = open_input_file(inputvideo);
                if (ret < 0)
                {
                    return;
                }
                ret = init_filters(filters_descr);
                if (ret < 0)
                {
                    return;
                }

                while (true)
                {
                    ret = ffmpeg.av_read_frame(fmt_ctx, &packet);
                    if (ret < 0)
                    {
                        Console.WriteLine("Error while sending a packet to the decoder\n");
                        break;
                    }
                    if (packet.stream_index == video_stream_index)
                    {
                        ret = ffmpeg.avcodec_send_packet(dec_ctx, &packet);
                        if (ret < 0)
                        {
                            Console.WriteLine( "Error while sending a packet to the decoder\n");
                            break;
                        }
                        while (ret >= 0)
                        {
                            ret = ffmpeg.avcodec_receive_frame(dec_ctx, frame);
                            //if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                            if (ret == 999)
                            {
                                break;
                            }
                            else if (ret < 0)
                            {
                                Console.WriteLine("Error while receiving a frame from the decoder\n");
                                return;
                            } else
                            {
                                Console.WriteLine("ret::"+ret);
                            }
                            if (ret >= 0)
                            {
                                frame->pts = frame->best_effort_timestamp;
                                /* push the decoded frame into the filtergraph */
                                if (ffmpeg.av_buffersrc_add_frame_flags(buffersrc_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF) < 0)
                                {
                                    Console.WriteLine("Error while feeding the filtergraph\n");
                                    break;
                                }
                                /* pull filtered frames from the filtergraph */
                                while (true)
                                {
                                    ret = ffmpeg.av_buffersink_get_frame(buffersink_ctx, filt_frame);
                                    //if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                                    if (ret == 999)
                                    {
                                        break;
                                    }
                                    else if (ret < 0)
                                    {
                                        return;
                                    }else
                                    {
                                        Console.WriteLine("ret2:" + ret);
                                    }

                                    display_frame(filt_frame, buffersink_ctx->inputs[0]->time_base);
                                    ffmpeg.av_frame_unref(filt_frame);
                                }
                                ffmpeg.av_frame_unref(frame);
                            }
                        }

                    }
                    ffmpeg.av_packet_unref(&packet);
                }

            }
            catch(Exception e)
            {
                Console.WriteLine(e.ToString());

            }
            finally
            {

                fixed (AVFilterGraph** at = &filter_graph)
                {
                    ffmpeg.avfilter_graph_free(at);
                }

                ffmpeg.avcodec_close(dec_ctx);

                fixed (AVFormatContext** at = &fmt_ctx)
                {
                    ffmpeg.avformat_close_input(at);
                }
                ffmpeg.av_frame_free(&frame);
                ffmpeg.av_frame_free(&filt_frame);
            }

        }

    }
}
</code>```

答:
I would bet the problem is in this line:

```<code>string args = string.Format("video_size={0}x{1}:pix_fmt={2}:time_base={3}/{4}:pixel_aspect={5}/{6}", dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt, time_base.num, time_base.den, dec_ctx->sample_aspect_ratio.num, dec_ctx->sample_aspect_ratio.den);
</code>```

The pix_fmt is most certainly an int instead of being passed as a string.

So get the integer value of dec_ctx->pix_fmt and it should work.

Body:
all

i used FFmpeg.AutoGen 3.2 ,vs2015 in win7,copy a Example from FFmpeg(http://ffmpeg.org/doxygen/trunk/filtering_video_8c-example.html),

when run

 string video = @"e:\\1.avi";
 FilterVideo fv = new FilterVideo();
 fv.filtertest(video);

return  errorcode -22:
args:video_size=640x480:pix_fmt=AV_PIX_FMT_YUV420P:time_base=1/25:pixel_aspect=1/1
Cannot create buffer source
-22

thanks for any rep.

blow is code :

using FFmpeg.AutoGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace videoFFmpegAutoGen.tool
{
    public unsafe class FilterVideo
    {

        public int open_input_file(string filename)
        {
            try
            {
                int ret;
                AVCodec* dec;
                fixed (AVFormatContext** at = &fmt_ctx)
                {
                    ret = ffmpeg.avformat_open_input(at, filename, null, null);
                }

                if (ret < 0)
                {
                    Console.WriteLine("Cannot open input file\n");
                    return ret;
                }
                ret = ffmpeg.avformat_find_stream_info(fmt_ctx, null);
                if (ret < 0)
                {
                    Console.WriteLine("Cannot find stream information\n");
                    return ret;
                }
                ret = ffmpeg.av_find_best_stream(fmt_ctx, AVMediaType.AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0);
                if (ret < 0)
                {
                    Console.WriteLine("Cannot find a video stream in the input file\n");
                    return ret;
                }

                video_stream_index = ret;

                /* create decoding context */
                dec_ctx = ffmpeg.avcodec_alloc_context3(dec);

                ffmpeg.avcodec_parameters_to_context(dec_ctx, fmt_ctx->streams[video_stream_index]->codecpar);
                ffmpeg.av_opt_set_int(dec_ctx, "refcounted_frames", 1, 0);
                /* init the video decoder */
                if ((ret = ffmpeg.avcodec_open2(dec_ctx, dec, null)) < 0)
                {
                    Console.WriteLine("Cannot open video decoder\n");
                    return ret;
                }

                return ret;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {

            }

            return -1;
        }

        private string filters_descr = "scale=78:24,transpose=cclock";
        private int video_stream_index = -1;
        private AVFormatContext* fmt_ctx;
        private AVFilterGraph* filter_graph;

        AVFilterContext* buffersrc_ctx;
        private AVCodecContext* dec_ctx;
        AVFilterContext* buffersink_ctx;
        public unsafe int init_filters(string filters_descr)
        {

            int ret = 0;
            AVFilterInOut* outputs = null;
            AVFilterInOut* inputs = null;
            try
            {
                AVFilter* buffersrc = ffmpeg.avfilter_get_by_name("buffer");
                AVFilter* buffersink = ffmpeg.avfilter_get_by_name("buffersink");
                outputs = ffmpeg.avfilter_inout_alloc();
                inputs = ffmpeg.avfilter_inout_alloc();
                AVRational time_base = fmt_ctx->streams[video_stream_index]->time_base;
                filter_graph = ffmpeg.avfilter_graph_alloc();
                //string args = string.Format("video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d", dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt, time_base.num, time_base.den, dec_ctx->sample_aspect_ratio.num, dec_ctx->sample_aspect_ratio.den);
                string args = string.Format("video_size={0}x{1}:pix_fmt={2}:time_base={3}/{4}:pixel_aspect={5}/{6}", dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt, time_base.num, time_base.den, dec_ctx->sample_aspect_ratio.num, dec_ctx->sample_aspect_ratio.den);
                // string args = string.Format("video_size={0}x{1}:time_base={2}/{3}:pixel_aspect={4}/{5}", dec_ctx->width, dec_ctx->height, time_base.num, time_base.den, dec_ctx->sample_aspect_ratio.num, dec_ctx->sample_aspect_ratio.den);
               // string args = string.Format("video_size={0}x{1}", dec_ctx->width, dec_ctx->height);
                Console.WriteLine("args:" + args);
                fixed (AVFilterContext** at= &buffersrc_ctx)
                {
                    ret = ffmpeg.avfilter_graph_create_filter(at, buffersrc, "in", args, null, filter_graph);
                }

                if (ret < 0)
                {
                    Console.WriteLine("Cannot create buffer source\n"+ret);
                    return ret;
                }
                fixed (AVFilterContext** at = &buffersink_ctx)
                {
                    ret = ffmpeg.avfilter_graph_create_filter(at, buffersink, "out", null, null, filter_graph);
                }

                if (ret < 0)
                {
                    Console.WriteLine("Cannot create buffer sink\n");
                    return ret;
                }
               // ret = ffmpeg.av_opt_set_int_list(buffersink_ctx, "pix_fmts", pix_fmts,AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN);

                /*
                * The buffer source output must be connected to the input pad of
                * the first filter described by filters_descr; since the first
                * filter input label is not specified, it is set to "in" by
                * default.
                */
                outputs->name = ffmpeg.av_strdup("in");
                outputs->filter_ctx = buffersrc_ctx;
                outputs->pad_idx = 0;
                outputs->next = null;
                /*
                 * The buffer sink input must be connected to the output pad of
                 * the last filter described by filters_descr; since the last
                 * filter output label is not specified, it is set to "out" by
                 * default.
                 */
                inputs->name = ffmpeg.av_strdup("out");
                inputs->filter_ctx = buffersink_ctx;
                inputs->pad_idx = 0;
                inputs->next = null;

                ret = ffmpeg.avfilter_graph_parse_ptr(filter_graph, filters_descr, &inputs, &outputs, null);
                if (ret < 0)
                {
                    return ret;
                }
                ret = ffmpeg.avfilter_graph_config(filter_graph, null);
                if (ret < 0)
                {
                    return ret;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                ffmpeg.avfilter_inout_free(&inputs);
                ffmpeg.avfilter_inout_free(&outputs);
            }

            return ret;

        }

        long AV_NOPTS_VALUE = 1;
        //int last_pts = AV_NOPTS_VALUE;
        long last_pts = 1;

        public void display_frame(AVFrame* frame, AVRational time_base)
        {
            int x, y;
            long delay;
            sbyte* p0;
            sbyte* p;
            AVRational cq = new AVRational();
            cq.num = 1;
            cq.den = 1000000;
            if (frame->pts != AV_NOPTS_VALUE)
            {
                if (last_pts != AV_NOPTS_VALUE)
                {
                    /* sleep roughly the right amount of time;
                     * usleep is in microseconds, just like AV_TIME_BASE. */
                    delay = ffmpeg.av_rescale_q(frame->pts - last_pts, time_base, cq);
                    if (delay > 0 && delay < 1000000)
                        Thread.Sleep((int)delay);
                }
                last_pts = frame->pts;
            }

            /* Trivial ASCII grayscale display. */
            p0 = frame->data0;
            //puts("\033c");
            for (y = 0; y < frame->height; y++)
            {
                p = p0;
                //for (x = 0; x < frame->width; x++)
                //putchar(" .-+#"[*(p++) / 52]);
                //putchar('\n');
                p0 += frame->linesize[0];
            }

            //fflush(stdout);

        }

        private int AV_BUFFERSRC_FLAG_KEEP_REF = 8 ;

        public unsafe void filtertest(string inputvideo)
        {
            AVFrame* frame = ffmpeg.av_frame_alloc();
            AVFrame* filt_frame = ffmpeg.av_frame_alloc();
            try
            {

                int ret;
                AVPacket packet;

                ffmpeg.av_register_all();
                ffmpeg.avfilter_register_all();

                ret = open_input_file(inputvideo);
                if (ret < 0)
                {
                    return;
                }
                ret = init_filters(filters_descr);
                if (ret < 0)
                {
                    return;
                }

                while (true)
                {
                    ret = ffmpeg.av_read_frame(fmt_ctx, &packet);
                    if (ret < 0)
                    {
                        Console.WriteLine("Error while sending a packet to the decoder\n");
                        break;
                    }
                    if (packet.stream_index == video_stream_index)
                    {
                        ret = ffmpeg.avcodec_send_packet(dec_ctx, &packet);
                        if (ret < 0)
                        {
                            Console.WriteLine( "Error while sending a packet to the decoder\n");
                            break;
                        }
                        while (ret >= 0)
                        {
                            ret = ffmpeg.avcodec_receive_frame(dec_ctx, frame);
                            //if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                            if (ret == 999)
                            {
                                break;
                            }
                            else if (ret < 0)
                            {
                                Console.WriteLine("Error while receiving a frame from the decoder\n");
                                return;
                            } else
                            {
                                Console.WriteLine("ret::"+ret);
                            }
                            if (ret >= 0)
                            {
                                frame->pts = frame->best_effort_timestamp;
                                /* push the decoded frame into the filtergraph */
                                if (ffmpeg.av_buffersrc_add_frame_flags(buffersrc_ctx, frame, AV_BUFFERSRC_FLAG_KEEP_REF) < 0)
                                {
                                    Console.WriteLine("Error while feeding the filtergraph\n");
                                    break;
                                }
                                /* pull filtered frames from the filtergraph */
                                while (true)
                                {
                                    ret = ffmpeg.av_buffersink_get_frame(buffersink_ctx, filt_frame);
                                    //if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                                    if (ret == 999)
                                    {
                                        break;
                                    }
                                    else if (ret < 0)
                                    {
                                        return;
                                    }else
                                    {
                                        Console.WriteLine("ret2:" + ret);
                                    }

                                    display_frame(filt_frame, buffersink_ctx->inputs[0]->time_base);
                                    ffmpeg.av_frame_unref(filt_frame);
                                }
                                ffmpeg.av_frame_unref(frame);
                            }
                        }

                    }
                    ffmpeg.av_packet_unref(&packet);
                }

            }
            catch(Exception e)
            {
                Console.WriteLine(e.ToString());

            }
            finally
            {

                fixed (AVFilterGraph** at = &filter_graph)
                {
                    ffmpeg.avfilter_graph_free(at);
                }

                ffmpeg.avcodec_close(dec_ctx);

                fixed (AVFormatContext** at = &fmt_ctx)
                {
                    ffmpeg.avformat_close_input(at);
                }
                ffmpeg.av_frame_free(&frame);
                ffmpeg.av_frame_free(&filt_frame);
            }

        }

    }
}

Body:
I would bet the problem is in this line:

string args = string.Format("video_size={0}x{1}:pix_fmt={2}:time_base={3}/{4}:pixel_aspect={5}/{6}", dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt, time_base.num, time_base.den, dec_ctx->sample_aspect_ratio.num, dec_ctx->sample_aspect_ratio.den);

The pix_fmt is most certainly an int instead of being passed as a string.

So get the integer value of dec_ctx->pix_fmt and it should work.


来源: stackexchange

问:
Attach LocalDB to microsoft sql server management studio corrupts database
After complicated migration to LocalDB I got strange issue. Currently console application reads data from local DB. But I decided to attach this DB in Managment Studio. Got strange error after which none - application and Studio cant connect to DB and only SQL server restart helps. Error:

```<code>TITLE: Microsoft SQL Server Management Studio
------------------------------

Failed to retrieve data for this request. (Microsoft.SqlServer.Management.Sdk.Sfc)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&LinkId=20476

------------------------------
ADDITIONAL INFORMATION:

The database 'LearnCSharp' cannot be opened because it is version 706. This server supports version 655 and earlier. A downgrade path is not supported. (Microsoft SQL Server, Error: 948)
</code>```

Database was created wit the same Management Studio and version is not issue.

What does it means and how to have both connections application and Management Studio for LocalDB?

答:
There is no corruption here - so let's not over-exaggerate the situation. Next time just web search "sql server version 655" to understand version numbers. You are attempting to use a database that was created in a newer version of sql server (2012) in an older (and obsolete) version - 2008. So your claim to the contrary is mistaken unfortunately

Do not confuse the version of SSMS with the version of the database instance you are using. If you are not sure, open a query window in SSMS and run the statement "select @@version" to see the instance version. "About SSMS" only shows you the version information of the SSMS application.

ContentLicense: CC BY-SA 3.0

Body:
After complicated migration to LocalDB I got strange issue. Currently console application reads data from local DB. But I decided to attach this DB in Managment Studio. Got strange error after which none - application and Studio cant connect to DB and only SQL server restart helps. Error:

TITLE: Microsoft SQL Server Management Studio
------------------------------

Failed to retrieve data for this request. (Microsoft.SqlServer.Management.Sdk.Sfc)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&LinkId=20476

------------------------------
ADDITIONAL INFORMATION:

The database 'LearnCSharp' cannot be opened because it is version 706. This server supports version 655 and earlier. A downgrade path is not supported. (Microsoft SQL Server, Error: 948)

Database was created wit the same Management Studio and version is not issue.

What does it means and how to have both connections application and Management Studio for LocalDB?


问:
Adding random weighted point
Let's say I have a blank canvas with 2 red points in it.

Is there an algorithm to randomly add a point in the canvas but in a way where it's more bias to the red points with a supplied radius?

Here's a crude image as an example:

Even though this question is for Python it really applies for any language.

答:
Sure. Select first point or second point randomly, then generate some distribution with single scale parameter in polar coordinates, then shift by
center point position. Select some reasonable radial distribution (gaussian in the code below, exponential or Cauchy might work as well)

```<code>import math
import random

import matplotlib.pyplot as plt

def select_point():
    p = random.random()
    if p < 0.5:
        return 0
    return 1

def sample_point(R):
    """
    Sample point inpolar coordinates
    """
    phi = 2.0 * math.pi * random.random() # angle
    r   = R * random.gauss(0.0, 1.0)      # might try different radial distribution, R*random.expovariate(1.0)

    return (r * math.cos(phi), r * math.sin(phi))

def sample(R, points):
    idx = select_point()

    x, y = sample_point(R)

    return (x + points[idx][0], y + points[idx][1])

R = 1.0
points = [(7.1, 3.3), (4.8, -1.4)]

random.seed(12345)

xx = []
yy = []
cc = []

xx.append(points[0][0])
xx.append(points[1][0])

yy.append(points[0][1])
yy.append(points[1][1])

cc.append(0.8)
cc.append(0.8)

for k in range(0, 50):
    x, y = sample(R, points)
    xx.append(x)
    yy.append(y)
    cc.append(0.3)

plt.scatter(xx, yy, c=cc)
plt.show()
</code>```

Picture

Title: Adding random weighted point

Body:
Sure. Select first point or second point randomly, then generate some distribution with single scale parameter in polar coordinates, then shift by
center point position. Select some reasonable radial distribution (gaussian in the code below, exponential or Cauchy might work as well)

import math
import random

import matplotlib.pyplot as plt

def select_point():
    p = random.random()
    if p < 0.5:
        return 0
    return 1

def sample_point(R):
    """
    Sample point inpolar coordinates
    """
    phi = 2.0 * math.pi * random.random() # angle
    r   = R * random.gauss(0.0, 1.0)      # might try different radial distribution, R*random.expovariate(1.0)

    return (r * math.cos(phi), r * math.sin(phi))

def sample(R, points):
    idx = select_point()

    x, y = sample_point(R)

    return (x + points[idx][0], y + points[idx][1])

R = 1.0
points = [(7.1, 3.3), (4.8, -1.4)]

random.seed(12345)

xx = []
yy = []
cc = []

xx.append(points[0][0])
xx.append(points[1][0])

yy.append(points[0][1])
yy.append(points[1][1])

cc.append(0.8)
cc.append(0.8)

for k in range(0, 50):
    x, y = sample(R, points)
    xx.append(x)
    yy.append(y)
    cc.append(0.3)

plt.scatter(xx, yy, c=cc)
plt.show()

Picture


问:
DB Design: Table Inheritance and Hierarchy
The example used does not represent the domain I am actually solving for; it's just for example.

Background

I am defining table inheritance. Planning to use Table API packages & views to handle the necessary logic & presentation.

I also need to define multiple multi-level named hierarchies with disparate attributes.

Combining table inheritance (Location > State, City) & named hierarchies (State <- City), however, is where I've come across a design snag.

The Problem

I want to define a Unique Key enforcing Name of City is Unique within State, but the abstraction of the Name field is preventing that. I can handle it in PL/SQL if needed, but I would like to enforce it at the SQL level (ideally without an additional table) if at all possible.

Constraints

Other tables need to be able to refer to any level of the hierarchy generically (location).

Other tables also need to be able to refer to a specific level of the hierarchy.

Thoughts

I cannot do single table inheritance due to the complexity of the graph of relations.

I have thought about duplicating the Name field for ease, though I'd rather not violate Normal Forms.

Example

```<code>CREATE TABLE location
( id      NUMBER  (  38) PRIMARY KEY
, name    VARCHAR2(1000) NOT NULL
, type_id NUMBER  (  38) NOT NULL
--, other common/super attributes
);

CREATE TABLE state
( id NUMBER(38) PRIMARY KEY
                REFERENCES location (id)
--, child attributes
);

CREATE TABLE city
( id       NUMBER(38) PRIMARY KEY
                      REFERENCES location (id)
, state_id NUMBER(38) NOT NULL
                      REFERENCES state    (id)
--, child attributes
);
</code>```

答: I don't see why requiring city and state names to be unique (and therefore holding them in the relevant table) would violate any normal form. city name is not the same attribute as state name "New York" city != "New York" state for example.    </p>

Body:
The example used does not represent the domain I am actually solving for; it's just for example.

Background

I am defining table inheritance. Planning to use Table API packages & views to handle the necessary logic & presentation.

I also need to define multiple multi-level named hierarchies with disparate attributes.

Combining table inheritance (Location > State, City) & named hierarchies (State <- City), however, is where I've come across a design snag.

The Problem

I want to define a Unique Key enforcing Name of City is Unique within State, but the abstraction of the Name field is preventing that. I can handle it in PL/SQL if needed, but I would like to enforce it at the SQL level (ideally without an additional table) if at all possible.

Constraints

Other tables need to be able to refer to any level of the hierarchy generically (location).

Other tables also need to be able to refer to a specific level of the hierarchy.

Thoughts

I cannot do single table inheritance due to the complexity of the graph of relations.

I have thought about duplicating the Name field for ease, though I'd rather not violate Normal Forms.

Example

CREATE TABLE location
( id      NUMBER  (  38) PRIMARY KEY
, name    VARCHAR2(1000) NOT NULL
, type_id NUMBER  (  38) NOT NULL
--, other common/super attributes
);

CREATE TABLE state
( id NUMBER(38) PRIMARY KEY
                REFERENCES location (id)
--, child attributes
);

CREATE TABLE city
( id       NUMBER(38) PRIMARY KEY
                      REFERENCES location (id)
, state_id NUMBER(38) NOT NULL
                      REFERENCES state    (id)
--, child attributes
);


问:
Sql query to add Zero between string with character and digits
What will be the generic sql query to update id by adding zeros in id. containing alphabets as well as numbers? In between the character and digits 00 needs to be padded e.g QTX23675  should turn into QTX0023675

```<code>UPDATE Table
    SET QID = 'QTX0023675'
    WHERE QID='QTX23675';
</code>```

There are many records to update and i found query with leading zeros.
Tried with spliting the string.

答:
Try This to make the result Dynamic

```<code>WITH CTE
AS
(
    SELECT Val = 'XTP231'
)
SELECT
    *,
    NewVal = SUBSTRING(Val,1,PATINDEX('%[0-9]%',Val)-1)+'00'+SUBSTRING(Val,PATINDEX('%[0-9]%',Val),LEN(Val))
    FROM CTE
</code>```

THe Output is as follows

Body:
What will be the generic sql query to update id by adding zeros in id. containing alphabets as well as numbers? In between the character and digits 00 needs to be padded e.g QTX23675  should turn into QTX0023675

UPDATE Table
    SET QID = 'QTX0023675'
    WHERE QID='QTX23675';

There are many records to update and i found query with leading zeros.
Tried with spliting the string.

Body:
Try This to make the result Dynamic

WITH CTE
AS
(
    SELECT Val = 'XTP231'
)
SELECT
    *,
    NewVal = SUBSTRING(Val,1,PATINDEX('%[0-9]%',Val)-1)+'00'+SUBSTRING(Val,PATINDEX('%[0-9]%',Val),LEN(Val))
    FROM CTE

THe Output is as follows


问:
Where is microsoft.interop.security.azroles on Server 2008 R2?
As far as I can recall, on Server 2003, microsoft.interop.security.azroles used to live in "C:\Windows\Microsoft.NET\authman".  On Server 2008 R2, that folder is empty.

Anyone know where it's hiding?

答: I found a copy in a subfolder of C:\Windows\winsxs. I have SQL Server 2008 loaded on this box.</p>

ContentLicense: CC BY-SA 2.5


问:
Basic understanding of calling kernel functions in NSIS
In NSIS, I was going through some API which calls some functions of Windows.

For example:

Kernel32::SetEnvironmentVariable(t, t)i ("VAR1", "$R0").r0

Kernel32::GetLocaleInfo(i,i,t,i)i(2048,0x2,.r0,${NSIS_MAX_STRLEN})i

As I am a newbie, can anyone please explain what is happening here ? What is t , i , .ro etc. ?

I know that kernel32 is a DLL and SetEnvironmentVariable & GetLocaleInfo are the functions defined in this DLL.

答:
The documentation will tell you what t and i are.

The basic syntax for System::Call is module::function(parameters)return. Parameters and return are optional and they both follow the same basic format: type input output. Type is not optional if you need input and/or output.

Parameters and return can be repeated multiple times, this is only useful when the function prototype exists as a define but you sometimes see this syntax on the NSIS Wiki as well. Kernel32::SetEnvironmentVariable(t, t)i ("VAR1", "$R0").r0 is exactly the same as Kernel32::SetEnvironmentVariable(t "VAR1", t "$R0")i.r0. When using a define it would look like this:

```<code>!define SetEnvironmentVariable "Kernel32::SetEnvironmentVariable(t, t)i"
System::Call '${SetEnvironmentVariable}("VAR1", "$R0").r0'
</code>```

It is helpful if you know a language like C/C++ or Delphi when using the System plug-in because you need to understand the basic Windows types and how functions are typically used.

If for example you wanted to call the GetWindowsDirectory function you would first look at the function on MSDN:

```<code>UINT WINAPI GetWindowsDirectory(_Out_ LPTSTR lpBuffer, _In_ UINT uSize);
</code>```

Translating this to NSIS gives you a initial skeleton of Kernel32::GetWindowsDirectory(t, i)i (WINAPI is the default calling convention). t maps to the Windows TCHAR* type and i is a 32-bit integer, the same as ULONG, LONG, DWORD, INT, UINT, INT32 and UINT32 in the Windows SDK.
The only missing piece is the input and output. The MSDN declaration is decorated with SAL annotations so it is easy to see which parameters are input and which are output.

A working example might look something like this:

```<code>System::Call 'Kernel32::GetWindowsDirectory(t .r1, i ${NSIS_MAX_STRLEN})i .r0'
DetailPrint "Return=$0 Output1=$1"
</code>```

. can be used as a "nothing" placeholder when there is no input. In this case we use it twice. The return value never has input when using System::Call and we also have one output-only parameter.

r1 and r0 are aliases for the $1 and $0 NSIS registers and these aliases must be used when you need the output of something. The plain NSIS register can be used as input but then the variable expansion happens inside NSIS and not in the plug-in and this can cause issues with quotes in strings and is not really recommended if the string might contain quotes or legal System plug-in syntax. I would therefore recommend that your first example is rewritten as Kernel32::SetEnvironmentVariable(t "VAR1", t R0)i.r0.

In C your second example would look something like

```<code>char mybuf[1024];
GetLocaleInfo(MAKELCID(LANG_NEUTRAL,SUBLANG_SYS_DEFAULT), LOCALE_SLANGUAGE, mybuf, sizeof(mybuf));
</code>```

Body:
The documentation will tell you what t and i are.

The basic syntax for System::Call is module::function(parameters)return. Parameters and return are optional and they both follow the same basic format: type input output. Type is not optional if you need input and/or output.

Parameters and return can be repeated multiple times, this is only useful when the function prototype exists as a define but you sometimes see this syntax on the NSIS Wiki as well. Kernel32::SetEnvironmentVariable(t, t)i ("VAR1", "$R0").r0 is exactly the same as Kernel32::SetEnvironmentVariable(t "VAR1", t "$R0")i.r0. When using a define it would look like this:

!define SetEnvironmentVariable "Kernel32::SetEnvironmentVariable(t, t)i"
System::Call '${SetEnvironmentVariable}("VAR1", "$R0").r0'

It is helpful if you know a language like C/C++ or Delphi when using the System plug-in because you need to understand the basic Windows types and how functions are typically used.

If for example you wanted to call the GetWindowsDirectory function you would first look at the function on MSDN:

UINT WINAPI GetWindowsDirectory(_Out_ LPTSTR lpBuffer, _In_ UINT uSize);

Translating this to NSIS gives you a initial skeleton of Kernel32::GetWindowsDirectory(t, i)i (WINAPI is the default calling convention). t maps to the Windows TCHAR* type and i is a 32-bit integer, the same as ULONG, LONG, DWORD, INT, UINT, INT32 and UINT32 in the Windows SDK.
The only missing piece is the input and output. The MSDN declaration is decorated with SAL annotations so it is easy to see which parameters are input and which are output.

A working example might look something like this:

System::Call 'Kernel32::GetWindowsDirectory(t .r1, i ${NSIS_MAX_STRLEN})i .r0'
DetailPrint "Return=$0 Output1=$1"

. can be used as a "nothing" placeholder when there is no input. In this case we use it twice. The return value never has input when using System::Call and we also have one output-only parameter.

r1 and r0 are aliases for the $1 and $0 NSIS registers and these aliases must be used when you need the output of something. The plain NSIS register can be used as input but then the variable expansion happens inside NSIS and not in the plug-in and this can cause issues with quotes in strings and is not really recommended if the string might contain quotes or legal System plug-in syntax. I would therefore recommend that your first example is rewritten as Kernel32::SetEnvironmentVariable(t "VAR1", t R0)i.r0.

In C your second example would look something like

char mybuf[1024];
GetLocaleInfo(MAKELCID(LANG_NEUTRAL,SUBLANG_SYS_DEFAULT), LOCALE_SLANGUAGE, mybuf, sizeof(mybuf));


问:
Entity Framework Core 2.0: Error when enumerating over query with group
I have the following method which simply iterates over orders grouped by client ID.

```<code>static void LinqWithInto()
{

    using (var db = new EFContext())
    {
        var orders = db.Orders.Include(o => o.Client);
        orders.Load();

        var query = from order in orders
                    group order by order.ClientId into g
                    select new { ClientId = g.Key, Count = g.Count(), Orders = g };

        foreach (var group in query)
        {
            WriteLine($"Client Id: {group.ClientId}, Number of orders: {group.Count}");
            foreach (var order in group.Orders)
                WriteLine($"\tOrder Id: {order.OrderId}, Client Id: {order.Client.ClientId}, Client Name: " +
                    $"{order.Client.Name} Payment: {order.Payment}");
        }

    }
}
</code>```

The query fetches orders with associated clients:

```<code>[Table("Order")]
public class Order
{
    public int OrderId { get; set; }
    public int ClientId { get; set; }
    public double Payment { get; set; }

    [ForeignKey("ClientId")]
    public Client Client { get; set; }
}

[Table("Client")]
public class Client
{
    public int ClientId { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }

    public List<Order> Orders { get; set; }
}
</code>```

The code works well in EF6, but in EF Core I get the following error (the variable query in foreach loop is highlighted):

System.ArgumentException: 'Expression of type 'System.Object' cannot be used for parameter of type 'Microsoft.EntityFrameworkCore.Metadata.IEntityType' of method 'Void StartTracking(System.Object, Microsoft.EntityFrameworkCore.Metadata.IEntityType)''

I wonder what's wrong here?

答:
This seems to be a bug in EF Core 2.0 which got addressed in this issue (Contains workaround):

https://github.com/aspnet/EntityFrameworkCore/issues/9551

You can get the testfeed 2.0.3 here (Contains fix):

https://github.com/aspnet/Announcements/issues/274

Body:
I have the following method which simply iterates over orders grouped by client ID.

static void LinqWithInto()
{

    using (var db = new EFContext())
    {
        var orders = db.Orders.Include(o => o.Client);
        orders.Load();

        var query = from order in orders
                    group order by order.ClientId into g
                    select new { ClientId = g.Key, Count = g.Count(), Orders = g };

        foreach (var group in query)
        {
            WriteLine($"Client Id: {group.ClientId}, Number of orders: {group.Count}");
            foreach (var order in group.Orders)
                WriteLine($"\tOrder Id: {order.OrderId}, Client Id: {order.Client.ClientId}, Client Name: " +
                    $"{order.Client.Name} Payment: {order.Payment}");
        }

    }
}

The query fetches orders with associated clients:

[Table("Order")]
public class Order
{
    public int OrderId { get; set; }
    public int ClientId { get; set; }
    public double Payment { get; set; }

    [ForeignKey("ClientId")]
    public Client Client { get; set; }
}

[Table("Client")]
public class Client
{
    public int ClientId { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }

    public List<Order> Orders { get; set; }
}

The code works well in EF6, but in EF Core I get the following error (the variable query in foreach loop is highlighted):

System.ArgumentException: 'Expression of type 'System.Object' cannot be used for parameter of type 'Microsoft.EntityFrameworkCore.Metadata.IEntityType' of method 'Void StartTracking(System.Object, Microsoft.EntityFrameworkCore.Metadata.IEntityType)''

I wonder what's wrong here?


问:
TypeError: conversion from Series to Decimal is not supported
Any ideas on how to convert a series (column) from float to decimal? I am on Python 3.6. I have read the Decimal documentation, but it offers no help.</p>

```<code>df['rate'].dtype
Out[158]: dtype('float64')
Decimal(df['rate'])
Traceback (most recent call last):
  File "C:\Users\user\Anaconda3\lib\site-packages\IPython
   \core\interactiveshell.py", line 2862, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
    File "<ipython-input-159-88710e11f7cd>", line 1, in <module>
    Decimal(df['rate'])
 TypeError: conversion from Series to Decimal is not supported
</code>```

答:
You can't cast like this, you will need to do

```<code>df['rate'] = df['rate'].apply(Decimal)
</code>```

pandas does support Decimal but you can't cast like that

Example:

```<code>In[28]:
from decimal import *
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
df['a'] = df['a'].apply(Decimal)
df

Out[28]:
                                                   a         b         c
0  -1.6122557830197199457700207858579233288764953... -1.865243 -0.836893
1  0.96962430214434858211092205237946473062038421... -0.105823 -0.842267
2  -0.9113389075755260471112251252634450793266296... -0.351389 -0.183489
3  1.22765470106414120721183280693367123603820800... -1.232627 -0.067909
4  -0.0376339704393285762185072940155805554240942... -0.445606 -0.080623
</code>```

the dtype will still show object but the dtype really is Decimal:

```<code>In[29]:
type(df['a'].iloc[0])

Out[29]: decimal.Decimal
</code>```

If you use astype(Decimal) it will look like it worked but it doesn't:

```<code>In[38]:
df['b'].astype(Decimal)

Out[38]:
0    -1.86524
1   -0.105823
2   -0.351389
3    -1.23263
4   -0.445606
Name: b, dtype: object
</code>```

If we try to assign this back:

```<code>In[39]:
df['b'] = df['b'].astype(Decimal)
type(df['b'].iloc[0])

Out[39]: float
</code>```

As pointed out by @JonClements and I agree it is ill-advised to use non-native numpy types as you lose any vectorisation in particular with arithmetic operations, additionally the dtype may be converted when you perform some operation on it which then loses your original intention

Body:
Any ideas on how to convert a series (column) from float to decimal? I am on Python 3.6. I have read the Decimal documentation, but it offers no help.

df['rate'].dtype
Out[158]: dtype('float64')
Decimal(df['rate'])
Traceback (most recent call last):
  File "C:\Users\user\Anaconda3\lib\site-packages\IPython
   \core\interactiveshell.py", line 2862, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
    File "<ipython-input-159-88710e11f7cd>", line 1, in <module>
    Decimal(df['rate'])
 TypeError: conversion from Series to Decimal is not supported

Body:
You can't cast like this, you will need to do

df['rate'] = df['rate'].apply(Decimal)

pandas does support Decimal but you can't cast like that

Example:

In[28]:
from decimal import *
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
df['a'] = df['a'].apply(Decimal)
df

Out[28]:
                                                   a         b         c
0  -1.6122557830197199457700207858579233288764953... -1.865243 -0.836893
1  0.96962430214434858211092205237946473062038421... -0.105823 -0.842267
2  -0.9113389075755260471112251252634450793266296... -0.351389 -0.183489
3  1.22765470106414120721183280693367123603820800... -1.232627 -0.067909
4  -0.0376339704393285762185072940155805554240942... -0.445606 -0.080623

the dtype will still show object but the dtype really is Decimal:

In[29]:
type(df['a'].iloc[0])

Out[29]: decimal.Decimal

If you use astype(Decimal) it will look like it worked but it doesn't:

In[38]:
df['b'].astype(Decimal)

Out[38]:
0    -1.86524
1   -0.105823
2   -0.351389
3    -1.23263
4   -0.445606
Name: b, dtype: object

If we try to assign this back:

In[39]:
df['b'] = df['b'].astype(Decimal)
type(df['b'].iloc[0])

Out[39]: float

As pointed out by @JonClements and I agree it is ill-advised to use non-native numpy types as you lose any vectorisation in particular with arithmetic operations, additionally the dtype may be converted when you perform some operation on it which then loses your original intention


问:
Android 7.0 Toggle Airplane Mode Programatically
I have tried all solutions already provided on StackOverflow but they are all quite old and no one seem to have tried it for nougat. I am making a utility tool which allows a user to toggle airplane mode on nougat, Someone please share a way to do that programatically. Also I have not been able to find any help regarding notification pull down programatically.</p>

答:
Also tried all the older suggestions, the only thing i have in mind is to open the airplane mode screen with :

```<code>Intent airPlaneModeIntent = new        Intent(android.provider.Settings.ACTION_AIRPLANE_MODE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(airPlaneModeIntent);
</code>```

and then use adb commands to tap on the radio button with the on/off setting.

Body:
Also tried all the older suggestions, the only thing i have in mind is to open the airplane mode screen with :

Intent airPlaneModeIntent = new        Intent(android.provider.Settings.ACTION_AIRPLANE_MODE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(airPlaneModeIntent);

and then use adb commands to tap on the radio button with the on/off setting.


问:
c# Excel Application File Format issue
I have a small issues which i was not able to find any solution on StackOverFlow.
The Situation:
I have an application that automatically opens up EXCEL application. When it opens it right away gives a dialog box that says "The file format and extension of xxx don't match. The file could be corrupted or unsafe..."
I am trying to create an application that focus on this running EXCEL application and hit the "YES" and resave the excel with VERSION 2007 so this error message will not come up again.

Here is what i have so far:

```<code>var excelApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
var c = excelApp.ActiveDialog;
</code>```

Not sure how to do a click event on the YES using the excelApp variable.
I also tried through

```<code>foreach (Process proc in Process.GetProcesses())
        {
            if (proc.MainWindowTitle.Contains("Excel"))
                ....
        }
</code>```

Nov. 06 2017:
This is what i have so far now:

```<code>        var oExcelApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application");

        Process[] processlist = Process.GetProcessesByName("Excel"); //Shows number of running Excel apps
        foreach (Process theprocess in processlist) //foreach Excel app running
        {

            if (oExcelApp.Workbooks.Count >= 0) //for worbooks in each Excel app
            {
                foreach (Excel.Workbook wkb in oExcelApp.Application.Workbooks)
                {
                    wkb.SaveAs(filePath, Excel.XlFileFormat.xlExcel8);
                    wkb.Close(true, null, null);
                    Marshal.FinalReleaseComObject(wkb);
                }
                oExcelApp.Workbooks.Close();
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();

            oExcelApp.Quit();
            Marshal.ReleaseComObject(oExcelApp);
        }
</code>```

This works ONLY If there was no error message at the beginning. If the process automatically opens excel and has error message showing this will throw an exception because the application is busy on the error message.

答:
Thanks all for your help. I was able to go around this and disable all alerts for Microsoft Excel Application using the REGEDIT. This was the only way to go around this situation. Just posting an answer to help others in the same situation:

REGEDIT Solution (Read near the bottom)

Title: c# Excel Application File Format issue

Body:
I have a small issues which i was not able to find any solution on StackOverFlow.
The Situation:
I have an application that automatically opens up EXCEL application. When it opens it right away gives a dialog box that says "The file format and extension of xxx don't match. The file could be corrupted or unsafe..."
I am trying to create an application that focus on this running EXCEL application and hit the "YES" and resave the excel with VERSION 2007 so this error message will not come up again.

Here is what i have so far:

var excelApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
var c = excelApp.ActiveDialog;

Not sure how to do a click event on the YES using the excelApp variable.
I also tried through

foreach (Process proc in Process.GetProcesses())
        {
            if (proc.MainWindowTitle.Contains("Excel"))
                ....
        }

Nov. 06 2017:
This is what i have so far now:

        var oExcelApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application");

        Process[] processlist = Process.GetProcessesByName("Excel"); //Shows number of running Excel apps
        foreach (Process theprocess in processlist) //foreach Excel app running
        {

            if (oExcelApp.Workbooks.Count >= 0) //for worbooks in each Excel app
            {
                foreach (Excel.Workbook wkb in oExcelApp.Application.Workbooks)
                {
                    wkb.SaveAs(filePath, Excel.XlFileFormat.xlExcel8);
                    wkb.Close(true, null, null);
                    Marshal.FinalReleaseComObject(wkb);
                }
                oExcelApp.Workbooks.Close();
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();

            oExcelApp.Quit();
            Marshal.ReleaseComObject(oExcelApp);
        }

This works ONLY If there was no error message at the beginning. If the process automatically opens excel and has error message showing this will throw an exception because the application is busy on the error message.


问:
Visual bug in Windows title bar with VCL Styles enabled application and display scaling
Currently I am testing various aspects of VCL styles enabled applications.

I noticed, that with Windows scaling higher than the default 96 dpi/100%,
the icon and the title bar text of the VCL Form are too big in size - and both are to close together -, please see attached screenshots. This is especially true with higher scalings like 200% or 250% (e.g. used on 4K displays and Windows 10), but even with a scaling of 144 dpi/150%, the problem is already visible.

This is true for all styles delivered with RAD Studio. High Dpi awareness for manifest is enabled via project settings.
If I disable VCL Styles in the App, the icon and title bar text is correct in size.

Am I missing something here? Shouldn't the delivered styles work without such display errors out of the box with display scaling enabled? Or is there some setting somewhere I can adjust to fix this.

Thanks,

答:
Here is a unit that allows VCL styles in DPI-aware applications.

VCL.Styles.DPIAware.pas

To use the unit just add it to the implementation uses statement of the main form and add the following code to the FormCreate handler.

```<code>procedure TFrmMain.FormCreate(Sender: TObject);
Var
  StyleDPIAwareness : TStyleDPIAwareness;
begin
  StyleDPIAwareness := TStyleDPIAwareness.Create(Self);
  StyleDPIAwareness.Parent := Self;
</code>```

By default the component scales the styles at multiples of 100%. You can change that, by adding the line:

```<code>StyleDPIAwareness.RoundScalingFactor := False;
</code>```

With this statement styles are scaled to whatever scaling factor results for Screen.PixelsPerInch. Most of the styles would work fine, but a few may show some visual defects.

Body:
Here is a unit that allows VCL styles in DPI-aware applications.

VCL.Styles.DPIAware.pas

To use the unit just add it to the implementation uses statement of the main form and add the following code to the FormCreate handler.

procedure TFrmMain.FormCreate(Sender: TObject);
Var
  StyleDPIAwareness : TStyleDPIAwareness;
begin
  StyleDPIAwareness := TStyleDPIAwareness.Create(Self);
  StyleDPIAwareness.Parent := Self;

By default the component scales the styles at multiples of 100%. You can change that, by adding the line:

StyleDPIAwareness.RoundScalingFactor := False;

With this statement styles are scaled to whatever scaling factor results for Screen.PixelsPerInch. Most of the styles would work fine, but a few may show some visual defects.


问:
Android Change Spinner theme/style with bottom border
I have a spinner after i loaded data into it. the style is not as my expected.

Spinner code

```<code><Spinner
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/spinnerGender"
                android:spinnerMode="dropdown"
                android:layout_marginLeft="-5dp"
                android:layout_marginTop="5dp"/>
</code>```

Current style.

My expected

How can i change theme/style the spinner

答:
Another approach is using the styles.xml file</p>

```<code><!-- Application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:spinnerStyle">@android:style/Widget.Holo.Light.Spinner</item>
</style>
</code>```

Body:
I have a spinner after i loaded data into it. the style is not as my expected.

Spinner code

<Spinner
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/spinnerGender"
                android:spinnerMode="dropdown"
                android:layout_marginLeft="-5dp"
                android:layout_marginTop="5dp"/>

Current style.

My expected

How can i change theme/style the spinner

Body:
Another approach is using the styles.xml file

<!-- Application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:spinnerStyle">@android:style/Widget.Holo.Light.Spinner</item>
</style>


问:
error: invalid operands (*UND* and *UND* sections) for `*'
Time to time when I try to compile some libraries such as OpenCV or OpenBLAS under linux I encounter error: invalid operands (*UND* and *UND* sections) for '*'.
I know this is an assembly error however most of the time when this issue appear it is related to temporary assembly filed generated by the compiler (gcc, g++, gfortran depending on the library).
I am not familiar with assembly and have absolutely no idea how to fix it.

Can you help me to have a better understanding on how to fix it ?

Note I am working on a Debian Jessy, but I also encounter this issue in several other Debian based distros (such as Ubuntu, and Mint).

When I write these line I face that error trying to compile OpenCV's librariry.
I message send by g++ is:

More precisely:

*

```<code>/tmp/ccL3rvH2.s: Assembler messages:
/tmp/ccL3rvH2.s:533: Error: invalid operands (*UND* and *UND* sections) for `*'
modules/imgproc/CMakeFiles/opencv_imgproc.dir/build.make:592: recipe for target 'modules/imgproc/CMakeFiles/opencv_imgproc.dir/src/gabor.cpp.o' failed
make[2]: *** [modules/imgproc/CMakeFiles/opencv_imgproc.dir/src/gabor.cpp.o] Error 1
make[2]: *** Waiting for unfinished jobs....
/tmp/cciiML9T.s: Assembler messages:
/tmp/cciiML9T.s:88450: Error: invalid operands (*UND* and *UND* sections) for `*'
/tmp/cciiML9T.s:105860: Error: invalid operands (*UND* and *UND* sections) for `*'
modules/imgproc/CMakeFiles/opencv_imgproc.dir/build.make:760: recipe for target 'modules/imgproc/CMakeFiles/opencv_imgproc.dir/src/imgwarp.cpp.o' failed
make[2]: *** [modules/imgproc/CMakeFiles/opencv_imgproc.dir/src/imgwarp.cpp.o] Error 1
CMakeFiles/Makefile2:2378: recipe for target 'modules/imgproc/CMakeFiles/opencv_imgproc.dir/all' failed
make[1]: *** [modules/imgproc/CMakeFiles/opencv_imgproc.dir/all] Error 2
make[1]: *** Waiting for unfinished jobs....
</code>```

*

Thanks in advance for any help

答:
After updated my compiler I retried to compile the version of OpenCV that I had my error message and it worked perfectly.
I change the compiler to go back to the previous version I used (g++ 4.9.2) and the issue re-happen.
I am still interested by the reason why this issue happen, but it seem the compiler version had an influence on it.</p>

Body:
Time to time when I try to compile some libraries such as OpenCV or OpenBLAS under linux I encounter error: invalid operands (*UND* and *UND* sections) for '*'.
I know this is an assembly error however most of the time when this issue appear it is related to temporary assembly filed generated by the compiler (gcc, g++, gfortran depending on the library).
I am not familiar with assembly and have absolutely no idea how to fix it.

Can you help me to have a better understanding on how to fix it ?

Note I am working on a Debian Jessy, but I also encounter this issue in several other Debian based distros (such as Ubuntu, and Mint).

When I write these line I face that error trying to compile OpenCV's librariry.
I message send by g++ is:

More precisely:

*

/tmp/ccL3rvH2.s: Assembler messages:
/tmp/ccL3rvH2.s:533: Error: invalid operands (*UND* and *UND* sections) for `*'
modules/imgproc/CMakeFiles/opencv_imgproc.dir/build.make:592: recipe for target 'modules/imgproc/CMakeFiles/opencv_imgproc.dir/src/gabor.cpp.o' failed
make[2]: *** [modules/imgproc/CMakeFiles/opencv_imgproc.dir/src/gabor.cpp.o] Error 1
make[2]: *** Waiting for unfinished jobs....
/tmp/cciiML9T.s: Assembler messages:
/tmp/cciiML9T.s:88450: Error: invalid operands (*UND* and *UND* sections) for `*'
/tmp/cciiML9T.s:105860: Error: invalid operands (*UND* and *UND* sections) for `*'
modules/imgproc/CMakeFiles/opencv_imgproc.dir/build.make:760: recipe for target 'modules/imgproc/CMakeFiles/opencv_imgproc.dir/src/imgwarp.cpp.o' failed
make[2]: *** [modules/imgproc/CMakeFiles/opencv_imgproc.dir/src/imgwarp.cpp.o] Error 1
CMakeFiles/Makefile2:2378: recipe for target 'modules/imgproc/CMakeFiles/opencv_imgproc.dir/all' failed
make[1]: *** [modules/imgproc/CMakeFiles/opencv_imgproc.dir/all] Error 2
make[1]: *** Waiting for unfinished jobs....

*

Thanks in advance for any help

ContentLicense: CC BY-SA 4.0


问:
Groovy: Accessing class fields via list
First, I'm sorry for asking such a dumb question, but quick googling didn't help me much...

I'm a Java delevoper and very new to Groovy. Consider the following code snippet:

```<code>class Person {
    public String name
}

def jack = new Person()
jack.name = "Jack"

def bob = new Person()
bob.name = "Bob"

def list = new java.util.ArrayList()

list.add(jack)
list.add(bob)

println list.name
</code>```

Executing it gives the following output (list of name field values for each Person in the list):

```<code>[Jack, Bob]
</code>```

So my question is what the corresponding java code for calling list.name?
My assumption is that it translates to something like:

list.stream().map(person -> person.name).collect(Collectors.toList())

Can somebody explain what exactly happens when i call list.name?

Thanks in advance!

答:
Your code

```<code>list.property
</code>```

is the shortest way to write this.  What groovy implies here is the use of the spread operator:

```<code>list*.property
</code>```

(note the * there).  And .property could be short here for .getProperty(), for an implicit call to the getter).

So your assumption is correct, that this is the eager collection of the values .getProperty() returns into an ArrayList.

Title: Groovy: Accessing class fields via list

Body:
First, I'm sorry for asking such a dumb question, but quick googling didn't help me much...

I'm a Java delevoper and very new to Groovy. Consider the following code snippet:

class Person {
    public String name
}

def jack = new Person()
jack.name = "Jack"

def bob = new Person()
bob.name = "Bob"

def list = new java.util.ArrayList()

list.add(jack)
list.add(bob)

println list.name

Executing it gives the following output (list of name field values for each Person in the list):

[Jack, Bob]

So my question is what the corresponding java code for calling list.name?
My assumption is that it translates to something like:

list.stream().map(person -> person.name).collect(Collectors.toList())

Can somebody explain what exactly happens when i call list.name?

Thanks in advance!

Body:
Your code

list.property

is the shortest way to write this.  What groovy implies here is the use of the spread operator:

list*.property

(note the * there).  And .property could be short here for .getProperty(), for an implicit call to the getter).

So your assumption is correct, that this is the eager collection of the values .getProperty() returns into an ArrayList.


问:
Why does C manage the heap, instead of the operating system?
In other words, why doesn't free() just return the memory to the operating system, and malloc simply request memory from the operating system?

This unpacks to three closely related questions:

Why does C need to manage its own heap? (Is it because the OS will only allow you to allocate and free contiguous memory of a minimum size?)

Assuming what I wrote in parentheses is true, why is it?

Can this problem affect the operating system itself, so that it's unable to allocate blocks of memory to any running processes?

答:
malloc is a C method itself. You are using a standard library that provides it for you, but in the end, it is C code just like yours is.

In some operating systems, you can only get memory from the OS in the size of pages (using mmap). This is too big for your regular data structure.

Doing a system call every time you need memory is way too expensive.


问:
Split a string (cell) in Excel without VBA (e.g. for array formula)
I have data in an Excel spreadsheet with delimited strings. For simplicity, think of something like "4#8#10", with an arbitrary number of pieces.

Is there any way to split this into an array for use with an array formula? For example, something like SUM(SplitStr(A1,"#")). (This does not work - it just returns "4".)

Is there a good way of approaching this? My ideal solution would end up with an array, as if the user entered {4,8,10} for use in array formulas.

The application of my sheet does not allow for delimiter-based text to columns and summing that. I would prefer to not use VBA if possible as I will not be the primary consumer of the sheet.

Thanks,
Terry

答:
Use XML functionality:

```<code>={SUM(FILTERXML("<t><s>" & SUBSTITUTE(A1, "#", "</s><s>") & "</s></t>", "//s"))}
</code>```

Update April 2022: Use new TEXTSPLIT function.

Body:
Use XML functionality:

={SUM(FILTERXML("<t><s>" & SUBSTITUTE(A1, "#", "</s><s>") & "</s></t>", "//s"))}

Update April 2022: Use new TEXTSPLIT function.


问:
How to send a notification to another PC?
Is there a way i can send a notification/message to another PC in C/C++? I think something like net send, but i don't know if there is another way to send a notification/message. I created an application which will run on every PC, and i want, that if my application has finished it should send a notification to my PC, that it has finished running. I don't know if there is a solution for my question, but if yes, could someone tell me, how to do that?

Thanks,

kampi

答:
Start by learning about WCF.  http://msdn.microsoft.com/en-us/netframework/aa663324.aspx

We ended up building a system for alerting all of our retail locations of emergency situations by building a service that opens up a TCP channel using .NET Remoting.  It just sits there and listens for notifications.  Our command center has a program that can send out notifications to this service.  The service is responsible for displaying the message.

The code is proprietary, so I can't share it, but that's the general idea.  Remoting has been rolled into WCF, which is why I started by suggesting learning that.

It has been working very well for us for many years, and works just fine on newer versions of Windows (unlike Net Send) and it's faster than Net Send.

Edit - added

I hadn't heard of this until now but you could also look into msg.exe.  it looks easier.

http://www.appscout.com/2009/03/vistas_msgexe_replaces_net_sen.php


问:
OpenClover not Running - Error
I am trying to integrate OpenClover into my project.
I have a Java based webapp and I use maven
I have setup the plugin as follows

```<code>        <plugin>
            <groupId>org.openclover</groupId>
            <artifactId>clover-maven-plugin</artifactId>
            <version>4.2.0</version>
            <configuration>
                <targetPercentage>50%</targetPercentage>
            </configuration>
            <executions>
                <execution>
                    <phase>verify</phase>
                    <goals>
                        <goal>check</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
</code>```

When I run the following command

```<code>mvn clean test clover:aggregate clover:clover -Dsurefire.skip.tests=false;
</code>```

I get this error

```<code>[ERROR] Failed to execute goal org.openclover:clover-maven-plugin:4.2.0:setup (default-cli) on project fcservices-web: Execution default-cli of goal org.openclover:clover-maven-plugin:4.2.0:setup failed: Unable to load the mojo 'setup' (or one of its required components) from the plugin 'org.openclover:clover-maven-plugin:4.2.0': com.google.inject.ProvisionException: Guice provision errors:
[ERROR]
[ERROR] 1) No implementation for org.apache.maven.execution.MavenSession was bound.
[ERROR] while locating com.atlassian.maven.plugin.clover.CloverSetupMojo
[ERROR] at ClassRealm[plugin>org.openclover:clover-maven-plugin:4.2.0, parent: sun.misc.Launcher$AppClassLoader@55f96302]
[ERROR] while locating org.apache.maven.plugin.Mojo annotated with @com.google.inject.name.Named(value=org.openclover:clover-maven-plugin:4.2.0:setup)
[ERROR]
[ERROR] 1 error
[ERROR] role: org.apache.maven.plugin.Mojo
[ERROR] roleHint: org.openclover:clover-maven-plugin:4.2.0:setup
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginContainerException
</code>```

Any ideas what is up here?

Thank you
Damien

答: From error it looks like you need higher version of Maven or older version of Clover plugin.</p>

Title: OpenClover not Running - Error

Body:
I am trying to integrate OpenClover into my project.
I have a Java based webapp and I use maven
I have setup the plugin as follows

        <plugin>
            <groupId>org.openclover</groupId>
            <artifactId>clover-maven-plugin</artifactId>
            <version>4.2.0</version>
            <configuration>
                <targetPercentage>50%</targetPercentage>
            </configuration>
            <executions>
                <execution>
                    <phase>verify</phase>
                    <goals>
                        <goal>check</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

When I run the following command

mvn clean test clover:aggregate clover:clover -Dsurefire.skip.tests=false;

I get this error

[ERROR] Failed to execute goal org.openclover:clover-maven-plugin:4.2.0:setup (default-cli) on project fcservices-web: Execution default-cli of goal org.openclover:clover-maven-plugin:4.2.0:setup failed: Unable to load the mojo 'setup' (or one of its required components) from the plugin 'org.openclover:clover-maven-plugin:4.2.0': com.google.inject.ProvisionException: Guice provision errors:
[ERROR]
[ERROR] 1) No implementation for org.apache.maven.execution.MavenSession was bound.
[ERROR] while locating com.atlassian.maven.plugin.clover.CloverSetupMojo
[ERROR] at ClassRealm[plugin>org.openclover:clover-maven-plugin:4.2.0, parent: sun.misc.Launcher$AppClassLoader@55f96302]
[ERROR] while locating org.apache.maven.plugin.Mojo annotated with @com.google.inject.name.Named(value=org.openclover:clover-maven-plugin:4.2.0:setup)
[ERROR]
[ERROR] 1 error
[ERROR] role: org.apache.maven.plugin.Mojo
[ERROR] roleHint: org.openclover:clover-maven-plugin:4.2.0:setup
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginContainerException

Any ideas what is up here?

Thank you
Damien


问:
Restoring data from Amazon Glacier
Is there a command line way to restore data from Glacier?
So far I have tried:

```<code>s3cmd restore --recursive s3://mybucketname/folder/

aws s3 ls s3://<bucket_name> | awk '{print $4}' | xargs -L 1 aws s3api restore-object --restore-request Days=<days> --bucket <bucket_name> --key
</code>```

But, no help there.
PS: I know we can do this via the console.

答:
You can use the python code below to restore glacier data to s3.

```<code>import boto3, botocore
import subprocess, os, shutil, tempfile, argparse, sys, time, codecs
from pprint import pprint

sys.stdout = codecs.getwriter('utf8')(sys.stdout)

parser = argparse.ArgumentParser()
parser.add_argument('--max-rate-mb', action='store', type=int, default=10000, help='The maximum rate in MB/h to restore files at.  Files larger than this will not be restored.')
parser.add_argument('--restore-days', action='store', type=int, default=30, help='How many days restored objects will remain in S3.')
parser.add_argument('--restore-path', action='store', help='The bucket/prefix to restore from')
parser.add_argument('--pretend', action='store_true', help='Do not execute restores')
parser.add_argument('--estimate', action='store_true', help='When pretending, do not check for already-restored files')
args = parser.parse_args()

if not args.restore_path:
    print 'No restore path specified.'
    sys.exit(1)

BUCKET = None
PREFIX = None
if '/' in args.restore_path:
    BUCKET, PREFIX = args.restore_path.split('/',1)
else:
    BUCKET = args.restore_path
    PREFIX = ''

RATE_LIMIT_BYTES = args.max_rate_mb * 1024 * 1024

s3 = boto3.Session(aws_access_key_id='<ACCESS_KEY>', aws_secret_access_key='<SECRET_KEY>').resource('s3')
bucket = s3.Bucket(BUCKET)

totalsize = 0
objects = []

objcount = 0
for objpage in bucket.objects.filter(Prefix=PREFIX).page_size(100).pages():
    for obj in objpage:
        objcount += 1
        print obj
        objects.append(obj)
    print u'Found {} objects.'.format(objcount)
print

objects.sort(key=lambda x: x.size, reverse=True)

objects = filter(lambda x: x.storage_class == 'GLACIER', objects)

if objects:
    obj = objects[0]
    print u'The largest object found is of {} size: {:14,d}  {:1s}  {}'.format(('a restorable' if obj.size <= RATE_LIMIT_BYTES else 'an UNRESTORABLE'), obj.size, obj.storage_class[0], obj.key)
    print

while objects:
    current_set = []
    current_set_total = 0
    unreported_unrestoreable_objects = []
    i = 0
    while i < len(objects):
        obj = objects[i]

        if obj.size > RATE_LIMIT_BYTES:
            unreported_unrestoreable_objects.append(obj)
        elif unreported_unrestoreable_objects:
            # No longer accumulating these.  Print the ones we found.
            print u'Some objects could not be restored due to exceeding the hourly rate limit:'
            for obj in unreported_unrestoreable_objects:
                print u'- {:14,d}  {:1s}  {}'.format(obj.size, obj.storage_class[0], obj.key)
            print

        if current_set_total + obj.size <= RATE_LIMIT_BYTES:
            if not args.pretend or not args.estimate:
                if obj.Object().restore is not None:
                    objects.pop(i)
                    continue
            current_set.append(obj)
            current_set_total += obj.size
            objects.pop(i)
            continue
        i += 1

    for obj in current_set:
        print u'{:14,d}  {:1s}  {}'.format(obj.size, obj.storage_class[0], obj.key)
        #pprint(obj.Object().restore)
        if not args.pretend:
            obj.restore_object(RestoreRequest={'Days': args.restore_days})
        #sys.exit(0)

    print u'{:s} Requested restore of {:d} objects consisting of {:,d} bytes.  {:d} objects remaining.  {:,d} bytes of hourly restore rate wasted'.format(time.strftime('%Y-%m-%d %H:%M:%S'), len(current_set), current_set_total, len(objects), RATE_LIMIT_BYTES - current_set_total)
    print
    if not objects:
        break
    if not args.pretend:
        time.sleep(3690)
</code>```

Command to run the script:

```<code>python restore_glacier_data_to_s3.py --restore-path s3-bucket-name/folder-name/
</code>```

Title: Restoring data from Amazon Glacier

Body:
Is there a command line way to restore data from Glacier?
So far I have tried:

s3cmd restore --recursive s3://mybucketname/folder/

aws s3 ls s3://<bucket_name> | awk '{print $4}' | xargs -L 1 aws s3api restore-object --restore-request Days=<days> --bucket <bucket_name> --key

But, no help there.
PS: I know we can do this via the console.

Body:
You can use the python code below to restore glacier data to s3.

import boto3, botocore
import subprocess, os, shutil, tempfile, argparse, sys, time, codecs
from pprint import pprint

sys.stdout = codecs.getwriter('utf8')(sys.stdout)

parser = argparse.ArgumentParser()
parser.add_argument('--max-rate-mb', action='store', type=int, default=10000, help='The maximum rate in MB/h to restore files at.  Files larger than this will not be restored.')
parser.add_argument('--restore-days', action='store', type=int, default=30, help='How many days restored objects will remain in S3.')
parser.add_argument('--restore-path', action='store', help='The bucket/prefix to restore from')
parser.add_argument('--pretend', action='store_true', help='Do not execute restores')
parser.add_argument('--estimate', action='store_true', help='When pretending, do not check for already-restored files')
args = parser.parse_args()

if not args.restore_path:
    print 'No restore path specified.'
    sys.exit(1)

BUCKET = None
PREFIX = None
if '/' in args.restore_path:
    BUCKET, PREFIX = args.restore_path.split('/',1)
else:
    BUCKET = args.restore_path
    PREFIX = ''

RATE_LIMIT_BYTES = args.max_rate_mb * 1024 * 1024

s3 = boto3.Session(aws_access_key_id='<ACCESS_KEY>', aws_secret_access_key='<SECRET_KEY>').resource('s3')
bucket = s3.Bucket(BUCKET)

totalsize = 0
objects = []

objcount = 0
for objpage in bucket.objects.filter(Prefix=PREFIX).page_size(100).pages():
    for obj in objpage:
        objcount += 1
        print obj
        objects.append(obj)
    print u'Found {} objects.'.format(objcount)
print

objects.sort(key=lambda x: x.size, reverse=True)

objects = filter(lambda x: x.storage_class == 'GLACIER', objects)

if objects:
    obj = objects[0]
    print u'The largest object found is of {} size: {:14,d}  {:1s}  {}'.format(('a restorable' if obj.size <= RATE_LIMIT_BYTES else 'an UNRESTORABLE'), obj.size, obj.storage_class[0], obj.key)
    print

while objects:
    current_set = []
    current_set_total = 0
    unreported_unrestoreable_objects = []
    i = 0
    while i < len(objects):
        obj = objects[i]

        if obj.size > RATE_LIMIT_BYTES:
            unreported_unrestoreable_objects.append(obj)
        elif unreported_unrestoreable_objects:
            # No longer accumulating these.  Print the ones we found.
            print u'Some objects could not be restored due to exceeding the hourly rate limit:'
            for obj in unreported_unrestoreable_objects:
                print u'- {:14,d}  {:1s}  {}'.format(obj.size, obj.storage_class[0], obj.key)
            print

        if current_set_total + obj.size <= RATE_LIMIT_BYTES:
            if not args.pretend or not args.estimate:
                if obj.Object().restore is not None:
                    objects.pop(i)
                    continue
            current_set.append(obj)
            current_set_total += obj.size
            objects.pop(i)
            continue
        i += 1

    for obj in current_set:
        print u'{:14,d}  {:1s}  {}'.format(obj.size, obj.storage_class[0], obj.key)
        #pprint(obj.Object().restore)
        if not args.pretend:
            obj.restore_object(RestoreRequest={'Days': args.restore_days})
        #sys.exit(0)

    print u'{:s} Requested restore of {:d} objects consisting of {:,d} bytes.  {:d} objects remaining.  {:,d} bytes of hourly restore rate wasted'.format(time.strftime('%Y-%m-%d %H:%M:%S'), len(current_set), current_set_total, len(objects), RATE_LIMIT_BYTES - current_set_total)
    print
    if not objects:
        break
    if not args.pretend:
        time.sleep(3690)

Command to run the script:

python restore_glacier_data_to_s3.py --restore-path s3-bucket-name/folder-name/


问:
How to replace specific column numbers with values contained in an array
I have a matrix 'pnl12'(x rows, y columns) and two vectors: 'ttd' and 'ttm'.

```<code>no. of columns in 'pnl12' = length of ttd = length of ttm
</code>```

Now I wish to select certain columns of pnl12 as:

```<code>pnl12[,(ttm < 1) & (ttd < 1) & (ttd<ttm) ]
</code>```

or I can also have columns of pnl12 to be replaced as:

```<code>which((ttm < 1) & (ttd < 1) & (ttd<ttm))
</code>```

Let's say , 3 columns gets selected satisfying above condition as 796th, 799th and 904th column.

Now I wish to replace all the values of these columns by a values in vector b

```<code>b = c(19, 26, 43)
</code>```

So all values in 796th column of pnl12  will be replace by 19. All Values in 799th column will be replaced by 26. And all values in 904th column will be replaced by 43.

This vector b is generated as :

```<code>b = ead[(ttm < 1) & (ttd < 1) & (ttd<ttm)]*(1-rr[(ttm < 1) & (ttd < 1) & (ttd<ttm)]))
</code>```

So, length of 'b' is same as no of columns selected in pnl12.

Can anybody please help me as how to do above replacement?

For example, I have a matrix:

```<code>1 2 3
4 5 6
7 8 9
</code>```

Then column 2 and 3 are to be replace by 40 and 50, So result will be:

```<code>1 40 50
4 40 50
7 40 50
</code>```

How to achieve this in R?

Thanks

答:
I would expand your replacement up to the right dimensions:

```<code># setting up one of your examples
mm = matrix(1:9, 3)
b = c(2, 3)
x = c(40, 50)

# expand the replacement appropriately, then assign
xx = matrix(x, nrow = nrow(mm), ncol = length(x), byrow = TRUE)
mm[, b] = xx
mm
#      [,1] [,2] [,3]
# [1,]    1   40   50
# [2,]    2   40   50
# [3,]    3   40   50
</code>```

Alternatively, there's nothing wrong with a simple for loop:

```<code>for (i in seq_along(b)) {
    mm[, i] = x[i]
}
</code>```

Body:
I have a matrix 'pnl12'(x rows, y columns) and two vectors: 'ttd' and 'ttm'.

no. of columns in 'pnl12' = length of ttd = length of ttm

Now I wish to select certain columns of pnl12 as:

pnl12[,(ttm < 1) & (ttd < 1) & (ttd<ttm) ]

or I can also have columns of pnl12 to be replaced as:

which((ttm < 1) & (ttd < 1) & (ttd<ttm))

Let's say , 3 columns gets selected satisfying above condition as 796th, 799th and 904th column.

Now I wish to replace all the values of these columns by a values in vector b

b = c(19, 26, 43)

So all values in 796th column of pnl12  will be replace by 19. All Values in 799th column will be replaced by 26. And all values in 904th column will be replaced by 43.

This vector b is generated as :

b = ead[(ttm < 1) & (ttd < 1) & (ttd<ttm)]*(1-rr[(ttm < 1) & (ttd < 1) & (ttd<ttm)]))

So, length of 'b' is same as no of columns selected in pnl12.

Can anybody please help me as how to do above replacement?

For example, I have a matrix:

1 2 3
4 5 6
7 8 9

Then column 2 and 3 are to be replace by 40 and 50, So result will be:

1 40 50
4 40 50
7 40 50

How to achieve this in R?

Thanks

Body:
I would expand your replacement up to the right dimensions:

# setting up one of your examples
mm = matrix(1:9, 3)
b = c(2, 3)
x = c(40, 50)

# expand the replacement appropriately, then assign
xx = matrix(x, nrow = nrow(mm), ncol = length(x), byrow = TRUE)
mm[, b] = xx
mm
#      [,1] [,2] [,3]
# [1,]    1   40   50
# [2,]    2   40   50
# [3,]    3   40   50

Alternatively, there's nothing wrong with a simple for loop:

for (i in seq_along(b)) {
    mm[, i] = x[i]
}


问:
How can I add notification timer like whatsapp call notification?
I have a notification builder. I want to add notification timer like whatsapp call notification. So if I call updateNotifTime function, is not working.

```<code>NotificationCompat.Builder builder = new NotificationCompat.Builder(context, callChannelId)
                .setSmallIcon(R.drawable.call_icon)
                .setContentIntent(pendingIntent)
                .setOngoing(true)
                .setShowWhen(true)
                .setWhen(System.currentTimeMillis())
                .setPriority(NotificationCompat.PRIORITY_HIGH);

public void updateNotifTime() {
    this.callingElapsedRunnable = new Runnable() {
                @Override
                public void run() {

                    elapsedTime += 1000;

                    String timer = DateUtils.calculateTime(elapsedTime);

                    builder.setWhen(elapsedTime);

                    callingElapsedHandler.postDelayed(this, 1000);
                }
            };

callingElapsedHandler.postDelayed(callingElapsedRunnable, 1000);
    }
</code>```

答:
I have added custom layout for <5.0 sdk versions:

< 5.0

```<code>public void startChronometer(String elapsedTime) {

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && builder != null) {
            RemoteViews mContentView = new RemoteViews(context.getPackageName(), R.layout.call_notification);
            //timerTxt
            TextView timerTxt = new TextView(context);
            timerTxt.setId(R.id.timerTxt);

            //callTypeTxt
            TextView callTypeTxt = new TextView(context);
            callTypeTxt.setId(R.id.callType);

            //calleeNameTxt
            TextView calleeNameTxt = new TextView(context);
            calleeNameTxt.setId(R.id.calleeName);

            mContentView.setTextViewText(timerTxt.getId(), elapsedTime);
            mContentView.setTextViewText(callTypeTxt.getId(), context.getString(R.string.call_in_progress));

            builder.setCustomBigContentView(mContentView);
            notificationManager.notify(CALL_NOTIFICATION_ID, builder.build());
        }
    }
</code>```

other versions

```<code>builder.setUsesChronometer(true);
</code>```

@Kishore Jethava Question:

```<code>Intent intent = new Intent(mContext, YourActivity.class);
intent.putExtra("tappedTime", System.currentTimeMillis());

PendingIntent pendingIntent = PendingIntent.getActivity(mContext, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
</code>```

Body:
I have a notification builder. I want to add notification timer like whatsapp call notification. So if I call updateNotifTime function, is not working.

NotificationCompat.Builder builder = new NotificationCompat.Builder(context, callChannelId)
                .setSmallIcon(R.drawable.call_icon)
                .setContentIntent(pendingIntent)
                .setOngoing(true)
                .setShowWhen(true)
                .setWhen(System.currentTimeMillis())
                .setPriority(NotificationCompat.PRIORITY_HIGH);

public void updateNotifTime() {
    this.callingElapsedRunnable = new Runnable() {
                @Override
                public void run() {

                    elapsedTime += 1000;

                    String timer = DateUtils.calculateTime(elapsedTime);

                    builder.setWhen(elapsedTime);

                    callingElapsedHandler.postDelayed(this, 1000);
                }
            };

callingElapsedHandler.postDelayed(callingElapsedRunnable, 1000);
    }

Body:
I have added custom layout for <5.0 sdk versions:

< 5.0

public void startChronometer(String elapsedTime) {

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && builder != null) {
            RemoteViews mContentView = new RemoteViews(context.getPackageName(), R.layout.call_notification);
            //timerTxt
            TextView timerTxt = new TextView(context);
            timerTxt.setId(R.id.timerTxt);

            //callTypeTxt
            TextView callTypeTxt = new TextView(context);
            callTypeTxt.setId(R.id.callType);

            //calleeNameTxt
            TextView calleeNameTxt = new TextView(context);
            calleeNameTxt.setId(R.id.calleeName);

            mContentView.setTextViewText(timerTxt.getId(), elapsedTime);
            mContentView.setTextViewText(callTypeTxt.getId(), context.getString(R.string.call_in_progress));

            builder.setCustomBigContentView(mContentView);
            notificationManager.notify(CALL_NOTIFICATION_ID, builder.build());
        }
    }

other versions

builder.setUsesChronometer(true);

@Kishore Jethava Question:

Intent intent = new Intent(mContext, YourActivity.class);
intent.putExtra("tappedTime", System.currentTimeMillis());

PendingIntent pendingIntent = PendingIntent.getActivity(mContext, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);


问:
Toggle page content from spanish to englishwith a click, how to approach this?
I have a span element, if that span element is clicked I want to dinamically toggle the content from spanish to english and viceversa, how can I approach this?</p>

```<code><li style="font-size:22px; margin-top:8px;">Language:  <span id="" style="cursor:pointer;" onclick="" >english</span></li>
</code>```

答:
You need to reload your webpage with parameters like "index.php?lang=eng".

$(".selectLang li").click(function(event) {
  event.preventDefault();
  var getLang = $(this).data('lang');

  window.location.href + "?lang=" + getLang;
  console.log(window.location.href + "?lang=" + getLang);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul { list-style-type : none }
li { cursor:pointer }</code>```

Language:  english

Language:  spanish

```
</div>
</div>
</p>

<p>Or with ajax with two text files (text-eng.txt and text-spa.txt).</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(".selectLang li").click(function(event) {
  event.preventDefault();
  var getLang = $(this).data('lang');

  $.ajax({
      url : "text-" + getLang + ".txt",
      dataType: "text",
      success : function (data) {
          $(".text").html(data);
      }
  });
});</code>```

ul { list-style-type : none }
li { cursor:pointer }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="selectLang">
  <li style="font-size:22px; margin-top:8px;" data-lang="eng">Language:  <span>english</span></li>
  <li style="font-size:22px; margin-top:8px;" data-lang="spa">Language:  <span>spanish</span></li>
</ul>

<div class="text"></div></code>```

Body:
I have a span element, if that span element is clicked I want to dinamically toggle the content from spanish to english and viceversa, how can I approach this?

Language:  english

Body:
You need to reload your webpage with parameters like "index.php?lang=eng".

$(".selectLang li").click(function(event) {
  event.preventDefault();
  var getLang = $(this).data('lang');

  window.location.href + "?lang=" + getLang;
  console.log(window.location.href + "?lang=" + getLang);
});

ul { list-style-type : none }
li { cursor:pointer }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="selectLang">
  <li style="font-size:22px; margin-top:8px;" data-lang="eng">Language:  <span>english</span></li>
  <li style="font-size:22px; margin-top:8px;" data-lang="spa">Language:  <span>spanish</span></li>
</ul>

Or with ajax with two text files (text-eng.txt and text-spa.txt).

$(".selectLang li").click(function(event) {
  event.preventDefault();
  var getLang = $(this).data('lang');

  $.ajax({
      url : "text-" + getLang + ".txt",
      dataType: "text",
      success : function (data) {
          $(".text").html(data);
      }
  });
});

ul { list-style-type : none }
li { cursor:pointer }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="selectLang">
  <li style="font-size:22px; margin-top:8px;" data-lang="eng">Language:  <span>english</span></li>
  <li style="font-size:22px; margin-top:8px;" data-lang="spa">Language:  <span>spanish</span></li>
</ul>

<div class="text"></div>