问:
Values are duplicated in Rails form for PostgreSQL array
If I save an array to the database, it is persisted properly, but when I look at the form, it puts concatenated values in the array in all array input fields.

E.g. in the form below I have 2 input fields, so you can store 2 nicknames for a Pet inside the array column. I put "a" in field 1 and "b" in field 2 and press save. I inspect in the Rails console and it's stored correctly: nicknames: ["a", "b"]. But when I open up the form, both input fields contain "a b". So the values are concatenated somehow. What am I doing wrong?

To reproduce:

```<code>rails g scaffold Pets
</code>```

Then in the new migration:

```<code>class CreatePets < ActiveRecord::Migration
  def change
    create_table :pets do |t|
      t.string :nicknames, array: true
      t.timestamps null: false
    end
  end
end
</code>```

In the controller:

```<code>def pet_params
  params[:pet].permit(nicknames: [])
end
</code>```

In the form:

```<code><%= simple_form_for(@pet) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.text_field :nicknames, name: 'pet[nicknames][]' %>
    <%= f.text_field :nicknames, name: 'pet[nicknames][]' %>
  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>
</code>```

Create a new Pet with nicknames "a" and "b". Go to edit the Pet and the inputs now contain "a b" and "a b", but it's stored as 'nicknames: ["a", "b"]' in the database according to the Rails console.

答:
You have the same a b in each field because you have the same field: :nicknames

What you should do, is generate multiple fields for each one, almost as Paul here said, but with a slightly different approach.

In your view:

```<code><div class="form-inputs">
  <% @pet.nicknames.each do |nickname| %>
    <%= f.text_field :nicknames, name: 'pet[nicknames][]', value: nickname %>
  <% end %>
  <%= f.text_field :nicknames, name: 'pet[nicknames][]' %>
  <%= f.hidden_field :nicknames, name: 'pet[nicknames][]', disabled: true, class: 'js-nickname-input-template' %>
</div>
</code>```

This will render one field for nickname even on new record, where there are no nicknames present yet. If you edit, there will be field for each nickname, and one empty for a new one.

There is also one hidden disabled field, for the next task presented to you.

What you should do to make this fully functional is add javascript functionality for adding or destroying fields for nicknames.

In your javascript assets:

```<code>$('#some-button-for-new').click(function(e){
  $templ = $('.js-nickname-input-template');
  $el = $templ.clone();
  $el.removeClass('.js-nickname-input-template');
  $el.removeAttr('disabled');
  $el.attr('type', 'text');
  $templ.before($el);
});

$('.some-button-for-destroy').click(function(e){
  $el = $($(e.target).data('identifier'));
  $el.remove();
});
</code>```

So, first handler adds new field for nicknames, and the second removes element. Pay attention: this is not copypaste-ready, especially removal. You might want to work on which element should be removed (maybe some li or div containing field and remove button itself).

tl;dr: the idea is creating fields for each existing array element server-side, plus one empty, plus template.
You can add and remove fields with javascript, using template.

Body:
If I save an array to the database, it is persisted properly, but when I look at the form, it puts concatenated values in the array in all array input fields.

E.g. in the form below I have 2 input fields, so you can store 2 nicknames for a Pet inside the array column. I put "a" in field 1 and "b" in field 2 and press save. I inspect in the Rails console and it's stored correctly: nicknames: ["a", "b"]. But when I open up the form, both input fields contain "a b". So the values are concatenated somehow. What am I doing wrong?

To reproduce:

rails g scaffold Pets

Then in the new migration:

class CreatePets < ActiveRecord::Migration
  def change
    create_table :pets do |t|
      t.string :nicknames, array: true
      t.timestamps null: false
    end
  end
end

In the controller:

def pet_params
  params[:pet].permit(nicknames: [])
end

In the form:

<%= simple_form_for(@pet) do |f| %>
  <%= f.error_notification %>

    <%= f.text_field :nicknames, name: 'pet[nicknames][]' %>
    <%= f.text_field :nicknames, name: 'pet[nicknames][]' %>

    <%= f.button :submit %>

<% end %>

Create a new Pet with nicknames "a" and "b". Go to edit the Pet and the inputs now contain "a b" and "a b", but it's stored as 'nicknames: ["a", "b"]' in the database according to the Rails console.

Body:
You have the same a b in each field because you have the same field: :nicknames

What you should do, is generate multiple fields for each one, almost as Paul here said, but with a slightly different approach.

In your view:

<div class="form-inputs">
  <% @pet.nicknames.each do |nickname| %>
    <%= f.text_field :nicknames, name: 'pet[nicknames][]', value: nickname %>
  <% end %>
  <%= f.text_field :nicknames, name: 'pet[nicknames][]' %>
  <%= f.hidden_field :nicknames, name: 'pet[nicknames][]', disabled: true, class: 'js-nickname-input-template' %>
</div>

This will render one field for nickname even on new record, where there are no nicknames present yet. If you edit, there will be field for each nickname, and one empty for a new one.

There is also one hidden disabled field, for the next task presented to you.

What you should do to make this fully functional is add javascript functionality for adding or destroying fields for nicknames.

In your javascript assets:

$('#some-button-for-new').click(function(e){
  $templ = $('.js-nickname-input-template');
  $el = $templ.clone();
  $el.removeClass('.js-nickname-input-template');
  $el.removeAttr('disabled');
  $el.attr('type', 'text');
  $templ.before($el);
});

$('.some-button-for-destroy').click(function(e){
  $el = $($(e.target).data('identifier'));
  $el.remove();
});

So, first handler adds new field for nicknames, and the second removes element. Pay attention: this is not copypaste-ready, especially removal. You might want to work on which element should be removed (maybe some li or div containing field and remove button itself).

tl;dr: the idea is creating fields for each existing array element server-side, plus one empty, plus template.
You can add and remove fields with javascript, using template.


来源: stackexchange

问:
g++ Difference Between Bash For Windows and Ubuntu
Simple question: Why is the version of g++ lower in the Bash For Windows subsystem than in Ubuntu proper?

Complicated question: Is there a way to fast forward the version of g++ on the Bash For Windows subsystem to what is pushed to normal Ubuntu systems?

Specifically, this question is stemming out of my need to use the c++17 filesystem implementation/support:
With the same compile command (g++ -Wall -std=c++1y main.cpp -o main), the same file will not compile on Windows but will in Ubuntu:

```<code>#include <experimental/filesystem>

int main() {}
</code>```

Any suggestions?

答: As pointed out by in the comments of the original post, g++ in the Linux For Windows Subsystem is maintained by Windows, here, and is not as current as it could possibly be..  So, to compile a newer version of gcc for the Linux Subsystem, this guide can be followed (works for me, just needed to add -lstdc++fs to the end of my compile command, and everything works perfectly).

ContentLicense: CC BY-SA 3.0

Body:
Simple question: Why is the version of g++ lower in the Bash For Windows subsystem than in Ubuntu proper?

Complicated question: Is there a way to fast forward the version of g++ on the Bash For Windows subsystem to what is pushed to normal Ubuntu systems?

Specifically, this question is stemming out of my need to use the c++17 filesystem implementation/support:
With the same compile command (g++ -Wall -std=c++1y main.cpp -o main), the same file will not compile on Windows but will in Ubuntu:

#include <experimental/filesystem>

int main() {}

Any suggestions?


问:
Resume download after killing or putting on background the application
I have some issues when I want to resume a download operation. I am using Alamofire 4.4 and I made my tests on iOS 9 and 10.
Here is my use cases:

1- A download operation is in progress, I cancel the request (resumeData is generated and saved) and then I put the application on background. After relaunching the application, I resume the download (using the resumeData) some times the download is being resumed and sometimes is being restarted.
Is it a normal behaviour ? And are there any solution if not ?

2- A download operation is in progress, and i kill the application. Downloaded data seems to be lost and I can't resume the download.
Is there any solution to get the resumeData and resume the download after restarting the application ?

Thank you.

答: Finally I have reimplemented the download module using URLSession. My application is more stable now.</p>


问:
Clustering with Apache Solr and Carrot2
I am very new to both Apache Solr and Carrot2. I am trying to index lot of input files using Solr. The end goal is to cluster the documents.

I am not clear if the clustering is done by Solr or by carrot2 workbench?

Can anyone guide me in this?

答:
It can be done both ways.

In one setting, Carrot2 Workbench can fetch search results from Solr (just like from any other search engine) and cluster them. This route is probably the easiest to start with, you just need to provide the URL to Solr service and names of fields to provide content for clustering.

Alternatively, you can configure a search results clustering plugin in Solr, which will perform clustering inside your Solr server and include search results clusters as part of Solr search response.

In both cases clustering is applied to the stored content of the documents (raw text), so there's not much performance benefit from having the documents clustered inside Solr, apart perhaps from reducing the serialization/deserialization overhead.

Finally, there is a somewhat outdated document clarifying the two Carrot2-Solr integration strategies.

Title: Clustering with Apache Solr and Carrot2


问:
Why does my Promise seem to be blocking execution
Below is a simplification of my code, I'm basicly running a function, that creates a Promise inside the function and returns it. For some reason though, testing with console.time(), it would appear that the code is actually blocking. The x.root function takes roughly 200ms to run and both console.time() tests give pretty much 200ms. Now if I did the age old trick of wrapping the function in setTimeout, the problem disappears, but I'd like to know what I'm doing wrong here?

I'd really prefer being able to create, resolve and reject the promises inside my helper function and then just call my function followed by then and catch without having to create Promises on an earlier level. What's the malfunction here?

```<code>parseroot = function(params) {
    return new Promise(function(resolve, reject) {
        try {
            var parsed_html = x.root(params);
            x.replacecontents(params.target, parsed_html);
            resolve(true);
        }
        catch(e) {
            reject(e);
        }
    });
}

console.time("Test 1");
console.time("Test 2");
var el = document.querySelector("#custom-element");
el.parseroot({
    section:"list",
    target: "#list-container",
}).then(function(response) {
    console.info("searchresult > list() success");
    console.timeEnd("Test 2");
});
console.timeEnd("Test 1");
</code>```

答:
Promises don't turn synchronous code into asynchronous code.

If the function you pass to Promise blocks, then the promise will block too.

Body:
Below is a simplification of my code, I'm basicly running a function, that creates a Promise inside the function and returns it. For some reason though, testing with console.time(), it would appear that the code is actually blocking. The x.root function takes roughly 200ms to run and both console.time() tests give pretty much 200ms. Now if I did the age old trick of wrapping the function in setTimeout, the problem disappears, but I'd like to know what I'm doing wrong here?

I'd really prefer being able to create, resolve and reject the promises inside my helper function and then just call my function followed by then and catch without having to create Promises on an earlier level. What's the malfunction here?

parseroot = function(params) {
    return new Promise(function(resolve, reject) {
        try {
            var parsed_html = x.root(params);
            x.replacecontents(params.target, parsed_html);
            resolve(true);
        }
        catch(e) {
            reject(e);
        }
    });
}

console.time("Test 1");
console.time("Test 2");
var el = document.querySelector("#custom-element");
el.parseroot({
    section:"list",
    target: "#list-container",
}).then(function(response) {
    console.info("searchresult > list() success");
    console.timeEnd("Test 2");
});
console.timeEnd("Test 1");


问:
This code to write video+audio through AVAssetWriter and AVAssetWriterInputs is not working. Why?
I've been trying to write a video+audio using AVAssetWriter and AVAssetWriterInputs.

I read multiple posts in this forum of people saying they were able to accomplish that, but it is not working for me.
If I just write video then the code is doing its job very well. When I add audio the output file is corrupted and cannot be reproduced.

Here is part of my code:

Setting up AVCaptureVideoDataOutput and AVCaptureAudioDataOutput:

```<code>NSError *error = nil;

// Setup the video input
AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType: AVMediaTypeVideo];
// Create a device input with the device and add it to the session.
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
// Setup the video output
_videoOutput = [[AVCaptureVideoDataOutput alloc] init];
_videoOutput.alwaysDiscardsLateVideoFrames = NO;
_videoOutput.videoSettings =
[NSDictionary dictionaryWithObject:
[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey];

// Setup the audio input
AVCaptureDevice *audioDevice     = [AVCaptureDevice defaultDeviceWithMediaType: AVMediaTypeAudio];
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&error ];
// Setup the audio output
_audioOutput = [[AVCaptureAudioDataOutput alloc] init];

// Create the session
_capSession = [[AVCaptureSession alloc] init];
[_capSession addInput:videoInput];
[_capSession addInput:audioInput];
[_capSession addOutput:_videoOutput];
[_capSession addOutput:_audioOutput];

_capSession.sessionPreset = AVCaptureSessionPresetLow;

// Setup the queue
dispatch_queue_t queue = dispatch_queue_create("MyQueue", NULL);
[_videoOutput setSampleBufferDelegate:self queue:queue];
[_audioOutput setSampleBufferDelegate:self queue:queue];
dispatch_release(queue);
</code>```

Setting up AVAssetWriter and associating both audio and video AVAssetWriterInputs to it:

```<code>- (BOOL)setupWriter {
    NSError *error = nil;
    _videoWriter = [[AVAssetWriter alloc] initWithURL:videoURL
                                             fileType:AVFileTypeQuickTimeMovie
                                                error:&error];
    NSParameterAssert(_videoWriter);

    // Add video input
    NSDictionary *videoCompressionProps = [NSDictionary dictionaryWithObjectsAndKeys:
                                                 [NSNumber numberWithDouble:128.0*1024.0], AVVideoAverageBitRateKey,
                                                        nil ];

    NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                              AVVideoCodecH264, AVVideoCodecKey,
                                              [NSNumber numberWithInt:192], AVVideoWidthKey,
                                              [NSNumber numberWithInt:144], AVVideoHeightKey,
                                              videoCompressionProps, AVVideoCompressionPropertiesKey,
                                              nil];

    _videoWriterInput = [[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo
                                                            outputSettings:videoSettings] retain];

    NSParameterAssert(_videoWriterInput);
    _videoWriterInput.expectsMediaDataInRealTime = YES;

    // Add the audio input
    AudioChannelLayout acl;
    bzero( &acl, sizeof(acl));
    acl.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;

    NSDictionary* audioOutputSettings = nil;
    // Both type of audio inputs causes output video file to be corrupted.
    if (NO) {
        // should work from iphone 3GS on and from ipod 3rd generation
        audioOutputSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                              [ NSNumber numberWithInt: kAudioFormatMPEG4AAC ], AVFormatIDKey,
                                     [ NSNumber numberWithInt: 1 ], AVNumberOfChannelsKey,
                              [ NSNumber numberWithFloat: 44100.0 ], AVSampleRateKey,
                              [ NSNumber numberWithInt: 64000 ], AVEncoderBitRateKey,
                              [ NSData dataWithBytes: &acl length: sizeof( acl ) ], AVChannelLayoutKey,
                              nil];
    } else {
        // should work on any device requires more space
        audioOutputSettings = [ NSDictionary dictionaryWithObjectsAndKeys:
                              [ NSNumber numberWithInt: kAudioFormatAppleLossless ], AVFormatIDKey,
                                    [ NSNumber numberWithInt: 16 ], AVEncoderBitDepthHintKey,
                              [ NSNumber numberWithFloat: 44100.0 ], AVSampleRateKey,
                              [ NSNumber numberWithInt: 1 ], AVNumberOfChannelsKey,
                              [ NSData dataWithBytes: &acl length: sizeof( acl ) ], AVChannelLayoutKey,
                                 nil ];
    }

    _audioWriterInput = [[AVAssetWriterInput
                            assetWriterInputWithMediaType: AVMediaTypeAudio
                  outputSettings: audioOutputSettings ] retain];

    _audioWriterInput.expectsMediaDataInRealTime = YES;

    // add input
    [_videoWriter addInput:_videoWriterInput];
    [_videoWriter addInput:_audioWriterInput];

    return YES;
}
</code>```

here are functions to start/stop video recording

```<code>- (void)startVideoRecording
{
    if (!_isRecording) {
        NSLog(@"start video recording...");
        if (![self setupWriter]) {
             return;
        }
        _isRecording = YES;
    }
}

- (void)stopVideoRecording
{
    if (_isRecording) {
        _isRecording = NO;

        [_videoWriterInput markAsFinished];
        [_videoWriter endSessionAtSourceTime:lastSampleTime];

        [_videoWriter finishWriting];

        NSLog(@"video recording stopped");
    }
}
</code>```

And finally the CaptureOutput code

```<code>- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
       fromConnection:(AVCaptureConnection *)connection
{
    if (!CMSampleBufferDataIsReady(sampleBuffer)) {
        NSLog( @"sample buffer is not ready. Skipping sample" );
        return;
    }

    if (_isRecording == YES) {
        lastSampleTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
        if (_videoWriter.status != AVAssetWriterStatusWriting ) {
            [_videoWriter startWriting];
            [_videoWriter startSessionAtSourceTime:lastSampleTime];
        }

        if (captureOutput == _videoOutput) {
            [self newVideoSample:sampleBuffer];
        }

        /*
        // If I add audio to the video, then the output file gets corrupted and it cannot be reproduced
        } else {
            [self newAudioSample:sampleBuffer];
        }
    */
    }
}

- (void)newVideoSample:(CMSampleBufferRef)sampleBuffer
{
    if (_isRecording) {
        if (_videoWriter.status > AVAssetWriterStatusWriting) {
             NSLog(@"Warning: writer status is %d", _videoWriter.status);
             if (_videoWriter.status == AVAssetWriterStatusFailed)
                  NSLog(@"Error: %@", _videoWriter.error);
             return;
        }

        if (![_videoWriterInput appendSampleBuffer:sampleBuffer]) {
             NSLog(@"Unable to write to video input");
        }
    }
}

- (void)newAudioSample:(CMSampleBufferRef)sampleBuffer
{
    if (_isRecording) {
        if (_videoWriter.status > AVAssetWriterStatusWriting) {
             NSLog(@"Warning: writer status is %d", _videoWriter.status);
             if (_videoWriter.status == AVAssetWriterStatusFailed)
                  NSLog(@"Error: %@", _videoWriter.error);
             return;
        }

        if (![_audioWriterInput appendSampleBuffer:sampleBuffer]) {
             NSLog(@"Unable to write to audio input");
        }
    }
}
</code>```

I would be very glad if someone could find which is the problem in this code.

答:
In startVideoRecording I call (I assume you are calling this at some point)

```<code>[_capSession startRunning] ;
</code>```

In stopVideoRecording I do not call

```<code>[_videoWriterInput markAsFinished];
[_videoWriter endSessionAtSourceTime:lastSampleTime];
</code>```

The markAsFinished is more for use with the block style pull method. See requestMediaDataWhenReadyOnQueue:usingBlock in AVAssetWriterInput for an explanation. The library should calculate the proper timing for interleaving the buffers.

You do not need to call endSessionAtSrouceTime. The last time stamp in the sample data will be used after the call to

```<code>[_videoWriter finishWriting];
</code>```

I also explicitly check for the type of capture output.

```<code>else if( captureOutput == _audioOutput) {
    [self newAudioSample:sampleBuffer];
}
</code>```

Here is what I have. The audio and video come through for me. It is possible I changed something. If this does not work for you then I will post everything I have.

```<code>-(void) startVideoRecording
    {
        if( !_isRecording )
         {
            NSLog(@"start video recording...");
            if( ![self setupWriter] ) {
                NSLog(@"Setup Writer Failed") ;

                return;
            }

            [_capSession startRunning] ;
            _isRecording = YES;
         }
    }

    -(void) stopVideoRecording
    {
        if( _isRecording )
         {
            _isRecording = NO;

            [_capSession stopRunning] ;

            if(![_videoWriter finishWriting]) {
                NSLog(@"finishWriting returned NO") ;
            }
            //[_videoWriter endSessionAtSourceTime:lastSampleTime];
            //[_videoWriterInput markAsFinished];
            //[_audioWriterInput markAsFinished];

            NSLog(@"video recording stopped");
         }
    }
</code>```

Body:
I've been trying to write a video+audio using AVAssetWriter and AVAssetWriterInputs.

I read multiple posts in this forum of people saying they were able to accomplish that, but it is not working for me.
If I just write video then the code is doing its job very well. When I add audio the output file is corrupted and cannot be reproduced.

Here is part of my code:

Setting up AVCaptureVideoDataOutput and AVCaptureAudioDataOutput:

NSError *error = nil;

// Setup the video input
AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType: AVMediaTypeVideo];
// Create a device input with the device and add it to the session.
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
// Setup the video output
_videoOutput = [[AVCaptureVideoDataOutput alloc] init];
_videoOutput.alwaysDiscardsLateVideoFrames = NO;
_videoOutput.videoSettings =
[NSDictionary dictionaryWithObject:
[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey];

// Setup the audio input
AVCaptureDevice *audioDevice     = [AVCaptureDevice defaultDeviceWithMediaType: AVMediaTypeAudio];
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&error ];
// Setup the audio output
_audioOutput = [[AVCaptureAudioDataOutput alloc] init];

// Create the session
_capSession = [[AVCaptureSession alloc] init];
[_capSession addInput:videoInput];
[_capSession addInput:audioInput];
[_capSession addOutput:_videoOutput];
[_capSession addOutput:_audioOutput];

_capSession.sessionPreset = AVCaptureSessionPresetLow;

// Setup the queue
dispatch_queue_t queue = dispatch_queue_create("MyQueue", NULL);
[_videoOutput setSampleBufferDelegate:self queue:queue];
[_audioOutput setSampleBufferDelegate:self queue:queue];
dispatch_release(queue);

Setting up AVAssetWriter and associating both audio and video AVAssetWriterInputs to it:

- (BOOL)setupWriter {
    NSError *error = nil;
    _videoWriter = [[AVAssetWriter alloc] initWithURL:videoURL
                                             fileType:AVFileTypeQuickTimeMovie
                                                error:&error];
    NSParameterAssert(_videoWriter);

    // Add video input
    NSDictionary *videoCompressionProps = [NSDictionary dictionaryWithObjectsAndKeys:
                                                 [NSNumber numberWithDouble:128.0*1024.0], AVVideoAverageBitRateKey,
                                                        nil ];

    NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                              AVVideoCodecH264, AVVideoCodecKey,
                                              [NSNumber numberWithInt:192], AVVideoWidthKey,
                                              [NSNumber numberWithInt:144], AVVideoHeightKey,
                                              videoCompressionProps, AVVideoCompressionPropertiesKey,
                                              nil];

    _videoWriterInput = [[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo
                                                            outputSettings:videoSettings] retain];

    NSParameterAssert(_videoWriterInput);
    _videoWriterInput.expectsMediaDataInRealTime = YES;

    // Add the audio input
    AudioChannelLayout acl;
    bzero( &acl, sizeof(acl));
    acl.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;

    NSDictionary* audioOutputSettings = nil;
    // Both type of audio inputs causes output video file to be corrupted.
    if (NO) {
        // should work from iphone 3GS on and from ipod 3rd generation
        audioOutputSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                              [ NSNumber numberWithInt: kAudioFormatMPEG4AAC ], AVFormatIDKey,
                                     [ NSNumber numberWithInt: 1 ], AVNumberOfChannelsKey,
                              [ NSNumber numberWithFloat: 44100.0 ], AVSampleRateKey,
                              [ NSNumber numberWithInt: 64000 ], AVEncoderBitRateKey,
                              [ NSData dataWithBytes: &acl length: sizeof( acl ) ], AVChannelLayoutKey,
                              nil];
    } else {
        // should work on any device requires more space
        audioOutputSettings = [ NSDictionary dictionaryWithObjectsAndKeys:
                              [ NSNumber numberWithInt: kAudioFormatAppleLossless ], AVFormatIDKey,
                                    [ NSNumber numberWithInt: 16 ], AVEncoderBitDepthHintKey,
                              [ NSNumber numberWithFloat: 44100.0 ], AVSampleRateKey,
                              [ NSNumber numberWithInt: 1 ], AVNumberOfChannelsKey,
                              [ NSData dataWithBytes: &acl length: sizeof( acl ) ], AVChannelLayoutKey,
                                 nil ];
    }

    _audioWriterInput = [[AVAssetWriterInput
                            assetWriterInputWithMediaType: AVMediaTypeAudio
                  outputSettings: audioOutputSettings ] retain];

    _audioWriterInput.expectsMediaDataInRealTime = YES;

    // add input
    [_videoWriter addInput:_videoWriterInput];
    [_videoWriter addInput:_audioWriterInput];

    return YES;
}

here are functions to start/stop video recording

- (void)startVideoRecording
{
    if (!_isRecording) {
        NSLog(@"start video recording...");
        if (![self setupWriter]) {
             return;
        }
        _isRecording = YES;
    }
}

- (void)stopVideoRecording
{
    if (_isRecording) {
        _isRecording = NO;

        [_videoWriterInput markAsFinished];
        [_videoWriter endSessionAtSourceTime:lastSampleTime];

        [_videoWriter finishWriting];

        NSLog(@"video recording stopped");
    }
}

And finally the CaptureOutput code

- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
       fromConnection:(AVCaptureConnection *)connection
{
    if (!CMSampleBufferDataIsReady(sampleBuffer)) {
        NSLog( @"sample buffer is not ready. Skipping sample" );
        return;
    }

    if (_isRecording == YES) {
        lastSampleTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
        if (_videoWriter.status != AVAssetWriterStatusWriting ) {
            [_videoWriter startWriting];
            [_videoWriter startSessionAtSourceTime:lastSampleTime];
        }

        if (captureOutput == _videoOutput) {
            [self newVideoSample:sampleBuffer];
        }

        /*
        // If I add audio to the video, then the output file gets corrupted and it cannot be reproduced
        } else {
            [self newAudioSample:sampleBuffer];
        }
    */
    }
}

- (void)newVideoSample:(CMSampleBufferRef)sampleBuffer
{
    if (_isRecording) {
        if (_videoWriter.status > AVAssetWriterStatusWriting) {
             NSLog(@"Warning: writer status is %d", _videoWriter.status);
             if (_videoWriter.status == AVAssetWriterStatusFailed)
                  NSLog(@"Error: %@", _videoWriter.error);
             return;
        }

        if (![_videoWriterInput appendSampleBuffer:sampleBuffer]) {
             NSLog(@"Unable to write to video input");
        }
    }
}

- (void)newAudioSample:(CMSampleBufferRef)sampleBuffer
{
    if (_isRecording) {
        if (_videoWriter.status > AVAssetWriterStatusWriting) {
             NSLog(@"Warning: writer status is %d", _videoWriter.status);
             if (_videoWriter.status == AVAssetWriterStatusFailed)
                  NSLog(@"Error: %@", _videoWriter.error);
             return;
        }

        if (![_audioWriterInput appendSampleBuffer:sampleBuffer]) {
             NSLog(@"Unable to write to audio input");
        }
    }
}

I would be very glad if someone could find which is the problem in this code.

Body:
In startVideoRecording I call (I assume you are calling this at some point)

[_capSession startRunning] ;

In stopVideoRecording I do not call

[_videoWriterInput markAsFinished];
[_videoWriter endSessionAtSourceTime:lastSampleTime];

The markAsFinished is more for use with the block style pull method. See requestMediaDataWhenReadyOnQueue:usingBlock in AVAssetWriterInput for an explanation. The library should calculate the proper timing for interleaving the buffers.

You do not need to call endSessionAtSrouceTime. The last time stamp in the sample data will be used after the call to

[_videoWriter finishWriting];

I also explicitly check for the type of capture output.

else if( captureOutput == _audioOutput) {
    [self newAudioSample:sampleBuffer];
}

Here is what I have. The audio and video come through for me. It is possible I changed something. If this does not work for you then I will post everything I have.

-(void) startVideoRecording
    {
        if( !_isRecording )
         {
            NSLog(@"start video recording...");
            if( ![self setupWriter] ) {
                NSLog(@"Setup Writer Failed") ;

                return;
            }

            [_capSession startRunning] ;
            _isRecording = YES;
         }
    }

    -(void) stopVideoRecording
    {
        if( _isRecording )
         {
            _isRecording = NO;

            [_capSession stopRunning] ;

            if(![_videoWriter finishWriting]) {
                NSLog(@"finishWriting returned NO") ;
            }
            //[_videoWriter endSessionAtSourceTime:lastSampleTime];
            //[_videoWriterInput markAsFinished];
            //[_audioWriterInput markAsFinished];

            NSLog(@"video recording stopped");
         }
    }

ContentLicense: CC BY-SA 2.5


问:
RegExp to test Full Name not working as expected
I'm writing a VBA function to evaluate whether a String is a Valid Full Name or not. For example:

Válid Full Name:

David Gilmour

Juan Munoz

Claudio Alberto da Silva

Invalid Full Name:

David Gilm01ur Jr.

Juan Muñoz

Cláudio Alberto da Silva

So the code of my function is this:

```<code>Function isVálidoNome(ByVal Texto As String) As Boolean
isVálidoNome = False
'
Dim strPattern As String: strPattern = "(^[a-zA-Z]+(\s?[a-zA-Z])*)*"
'Dim strPattern As String: strPattern = "\d"
Dim regularExpressions As New RegExp
'
regularExpressions.Pattern = strPattern
regularExpressions.Global = True
'
If (regularExpressions.Test(Texto)) Then
    isVálidoNome = True
End If

End Function
</code>```

The pattern I used (^[a-zA-Z]+(\s?[a-zA-Z])*)* works fine in an app I used to test it (RegexPal), but when I run the code in VBA, Strings with digits, accents returns true

Why this problem or Did I make any mistake?

答:
You need to use

```<code>^[a-zA-Z]+(?:\s[a-zA-Z]+)*$
</code>```

See the regex demo

Set regularExpressions.Global = False.

Details:

^ - start of string

[a-zA-Z]+ - 1 or more ASCII letters

(?: -  start of a non-capturing group matching zero or more (*) sequences of:

\s - a single whitespace (add + after it to match 1 or more whitespaces)

[a-zA-Z]+

)* - end of the non-capturing group

$ - end of string.

Body:
I'm writing a VBA function to evaluate whether a String is a Valid Full Name or not. For example:

Válid Full Name:

David Gilmour

Juan Munoz

Claudio Alberto da Silva

Invalid Full Name:

David Gilm01ur Jr.

Juan Muñoz

Cláudio Alberto da Silva

So the code of my function is this:

Function isVálidoNome(ByVal Texto As String) As Boolean
isVálidoNome = False
'
Dim strPattern As String: strPattern = "(^[a-zA-Z]+(\s?[a-zA-Z])*)*"
'Dim strPattern As String: strPattern = "\d"
Dim regularExpressions As New RegExp
'
regularExpressions.Pattern = strPattern
regularExpressions.Global = True
'
If (regularExpressions.Test(Texto)) Then
    isVálidoNome = True
End If

End Function

The pattern I used (^[a-zA-Z]+(\s?[a-zA-Z])*)* works fine in an app I used to test it (RegexPal), but when I run the code in VBA, Strings with digits, accents returns true

Why this problem or Did I make any mistake?

Body:
You need to use

^[a-zA-Z]+(?:\s[a-zA-Z]+)*$

See the regex demo

Set regularExpressions.Global = False.

Details:

^ - start of string

[a-zA-Z]+ - 1 or more ASCII letters

(?: -  start of a non-capturing group matching zero or more (*) sequences of:

\s - a single whitespace (add + after it to match 1 or more whitespaces)

[a-zA-Z]+

)* - end of the non-capturing group

$ - end of string.


问:
Close download bar
I am using Java and Selenium to write a test. Somewhere in my test, I download a file but then need to click on a button under the download bar which appears at the bottom of the chrome browser page. I search a lot but the only solution was here which is not my case as I don't have a scroll.

I also use:

```<code>action.sendKeys(Keys.CONTROL+ "j").build().perform();
action.keyUp(Keys.CONTROL).build().perform();
Thread.sleep(500);
ArrayList<String> tabs2 = new ArrayList<String> (driverChrome.getWindowHandles());
driverChrome.switchTo().window(tabs2.get(1));
Thread.sleep(500);
driverChrome.close();
driverChrome.switchTo().window(tabs2.get(0));
Thread.sleep(500);
</code>```

but it doesn't open the download page.

Anyway that I can close the download bar?

答:
This method did not work for me either, but I developed a workaround. I do any download test in a new window, then close the download window, the original window does not have the download bar. It must be a new window, if you do a new tab it will transfer over, to get this I use JavaScript. Switch to the new window, run download test and then switch to the original window when done. </p>

```<code>string javascript = $"$(window.open('', '_blank', 'location=yes'))";

((IJavaScriptExecutor)Driver).ExecuteScript(javascript); //create new window

Driver.SwitchTo().Window(Driver.WindowHandles.Last())); //switch to new window

//do download test here

Driver.Close(); //close created window

Driver.SwitchTo().Window(Driver.WindowHandles.First()); //back to original window with no download bar
</code>```

Title: Close download bar

Body:
I am using Java and Selenium to write a test. Somewhere in my test, I download a file but then need to click on a button under the download bar which appears at the bottom of the chrome browser page. I search a lot but the only solution was here which is not my case as I don't have a scroll.

I also use:

action.sendKeys(Keys.CONTROL+ "j").build().perform();
action.keyUp(Keys.CONTROL).build().perform();
Thread.sleep(500);
ArrayList<String> tabs2 = new ArrayList<String> (driverChrome.getWindowHandles());
driverChrome.switchTo().window(tabs2.get(1));
Thread.sleep(500);
driverChrome.close();
driverChrome.switchTo().window(tabs2.get(0));
Thread.sleep(500);

but it doesn't open the download page.

Anyway that I can close the download bar?

Body:
This method did not work for me either, but I developed a workaround. I do any download test in a new window, then close the download window, the original window does not have the download bar. It must be a new window, if you do a new tab it will transfer over, to get this I use JavaScript. Switch to the new window, run download test and then switch to the original window when done.

string javascript = $"$(window.open('', '_blank', 'location=yes'))";

((IJavaScriptExecutor)Driver).ExecuteScript(javascript); //create new window

Driver.SwitchTo().Window(Driver.WindowHandles.Last())); //switch to new window

//do download test here

Driver.Close(); //close created window

Driver.SwitchTo().Window(Driver.WindowHandles.First()); //back to original window with no download bar


问:
Basic authentication for REST API using spring restTemplate
I am completely new in RestTemplate and basically in the REST APIs also. I want to retrieve some data in my application via Jira REST API, but getting back 401 Unauthorised. Found and article on jira rest api documentation but don't really know how to rewrite this into java as the example uses the command line way with curl. I would appreciate any suggestion or advice how to rewrite:

```<code>curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" "http://kelpie9:8081/rest/api/2/issue/QA-31"
</code>```

into java using spring rest template. Where the ZnJlZDpmcmVk is a base64 encoded string of username:password. Thank you very much.

答:
You may use spring-boot RestTemplateBuilder

```<code>@Bean
RestOperations rest(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder.basicAuthentication("user", "password").build();
}
</code>```

See documentation

(before SB 2.1.0 it was #basicAuthorization)

Body:
I am completely new in RestTemplate and basically in the REST APIs also. I want to retrieve some data in my application via Jira REST API, but getting back 401 Unauthorised. Found and article on jira rest api documentation but don't really know how to rewrite this into java as the example uses the command line way with curl. I would appreciate any suggestion or advice how to rewrite:

curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" "http://kelpie9:8081/rest/api/2/issue/QA-31"

into java using spring rest template. Where the ZnJlZDpmcmVk is a base64 encoded string of username:password. Thank you very much.

Body:
You may use spring-boot RestTemplateBuilder

@Bean
RestOperations rest(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder.basicAuthentication("user", "password").build();
}

See documentation

(before SB 2.1.0 it was #basicAuthorization)

ContentLicense: CC BY-SA 4.0


问:
Performing A Query On Field Generated From Sub Query
I have two tables, Clients and Jobs.

I am doing a report on clients, and as part of the query, I also return a count of how many jobs we have done for each client. The code is as follows:

```<code>SELECT * ,
(SELECT COUNT(*) FROM Jobs WHERE ClientID = Clients.ID) AS JobsCount
FROM Clients
</code>```

I now need to modify this to allow conditional queries based on the JobsCount, such as "return all clients with more than 100 jobs". Simply adding a where clause on JobsCount doesnt seem to work - Invalid column name 'JobsCount'.

How can i query on a column that is generated through a sub query?

答:
You can add where condition as below:

```<code>Select *, (select count(*) from Jobs where ClientId = t.Id ) as JobsCount
    from Clients t where (select count(*) from Jobs where ClientId = t.Id) > 100
</code>```

Or other simple way to wrap it into another subquery as below:

```<code>Select * from (
    Select *, (select count(*) from Jobs where ClientId = t.Id ) as JobsCount
    from Clients t
    ) a Where JobsCount > 100
</code>```

Body:
I have two tables, Clients and Jobs.

I am doing a report on clients, and as part of the query, I also return a count of how many jobs we have done for each client. The code is as follows:

SELECT * ,
(SELECT COUNT(*) FROM Jobs WHERE ClientID = Clients.ID) AS JobsCount
FROM Clients

I now need to modify this to allow conditional queries based on the JobsCount, such as "return all clients with more than 100 jobs". Simply adding a where clause on JobsCount doesnt seem to work - Invalid column name 'JobsCount'.

How can i query on a column that is generated through a sub query?

Body:
You can add where condition as below:

Select *, (select count(*) from Jobs where ClientId = t.Id ) as JobsCount
    from Clients t where (select count(*) from Jobs where ClientId = t.Id) > 100

Or other simple way to wrap it into another subquery as below:

Select * from (
    Select *, (select count(*) from Jobs where ClientId = t.Id ) as JobsCount
    from Clients t
    ) a Where JobsCount > 100


问:
Web Api 2 ConnectionString
I'm having the below error when trying to connect to an SQL DB:

```<code>"Data Source=***.***.***.***; Initial Catalog=DbName;Persist Security Info=True;User ID=****;Password=****;"
</code>```

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: Named
  Pipes Provider, error: 40 - Could not open a connection to SQL Server)

```<code>"Network Library=DBMSSOCN; Data Source=***.***.***.***,1433; Initial Catalog=DbName;Persist Security Info=True;User ID=****;Password=****;"
</code>```

A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: TCP
  Provider, error: 0 - The wait operation timed out.)

I've looked through plenty of resources online though still unable to resolve this
Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

The top connection string is obtained from Server Explorer and has fully expected connectivity, the latter to ensure it wasn't looking for a local DB.

We've this connection string as shows and working in other non-WebApi 2.0 projects which has connectivity to the DB

I've created a new DB using RDS in AWS too and having the same errors.

I've tried recreating the whole project as shown here (without any models) with the same errors too.

Any help in getting this resolved would be greatly appreciated

Edit, for clarity:

Console App, ConnectionString1 : Connects

Console App, ConnectionString2 : Connects

Web API, ConnectionString1 : Errors
"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"

Web API, ConnectionString2 : Errors
"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - The wait operation timed out.)"

.

```<code>var connectionString1 = "Server=***.***.***.***;Persist Security Info=True;User Id=****;Password=****"; //just for convenience
var connectionString2 = "Server=***.***.***.***,1433;Persist Security Info=True;User Id=****;Password=****";

var connection = new System.Data.SqlClient.SqlConnection(connectionString);

try
{
    connection.Open();
}
catch (Exception ex)
{ }
finally
{
    connection.Close();
}
</code>```

答: Having BitDefender installed locally restricted traffic and the 500's when using IIS. You can white-list ports though this needs to be done through requests to BitDefender or get a decent AV where you can do this yourself.

Title: Web Api 2 ConnectionString

Body:
I'm having the below error when trying to connect to an SQL DB:

"Data Source=***.***.***.***; Initial Catalog=DbName;Persist Security Info=True;User ID=****;Password=****;"

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: Named
  Pipes Provider, error: 40 - Could not open a connection to SQL Server)

"Network Library=DBMSSOCN; Data Source=***.***.***.***,1433; Initial Catalog=DbName;Persist Security Info=True;User ID=****;Password=****;"

A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: TCP
  Provider, error: 0 - The wait operation timed out.)

I've looked through plenty of resources online though still unable to resolve this
Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

The top connection string is obtained from Server Explorer and has fully expected connectivity, the latter to ensure it wasn't looking for a local DB.

We've this connection string as shows and working in other non-WebApi 2.0 projects which has connectivity to the DB

I've created a new DB using RDS in AWS too and having the same errors.

I've tried recreating the whole project as shown here (without any models) with the same errors too.

Any help in getting this resolved would be greatly appreciated

Edit, for clarity:

Console App, ConnectionString1 : Connects

Console App, ConnectionString2 : Connects

Web API, ConnectionString1 : Errors
"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"

Web API, ConnectionString2 : Errors
"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - The wait operation timed out.)"

.

var connectionString1 = "Server=***.***.***.***;Persist Security Info=True;User Id=****;Password=****"; //just for convenience
var connectionString2 = "Server=***.***.***.***,1433;Persist Security Info=True;User Id=****;Password=****";

var connection = new System.Data.SqlClient.SqlConnection(connectionString);

try
{
    connection.Open();
}
catch (Exception ex)
{ }
finally
{
    connection.Close();
}


问:
How can I return the current action in an ASP.NET MVC view?
I wanted to set a CSS class in my master page, which depends on the current controller and action. I can get to the current controller via ViewContext.Controller.GetType().Name, but how do I get the current action (e.g. Index, Show etc.)?

答:
I saw different answers and came up with a class helper:

```<code>using System;
using System.Web.Mvc;

namespace MyMvcApp.Helpers {
    public class LocationHelper {
        public static bool IsCurrentControllerAndAction(string controllerName, string actionName, ViewContext viewContext) {
            bool result = false;
            string normalizedControllerName = controllerName.EndsWith("Controller") ? controllerName : String.Format("{0}Controller", controllerName);

            if(viewContext == null) return false;
            if(String.IsNullOrEmpty(actionName)) return false;

            if (viewContext.Controller.GetType().Name.Equals(normalizedControllerName, StringComparison.InvariantCultureIgnoreCase) &&
                viewContext.Controller.ValueProvider.GetValue("action").AttemptedValue.Equals(actionName, StringComparison.InvariantCultureIgnoreCase)) {
                result = true;
            }

            return result;
        }
    }
}
</code>```

So in View (or master/layout) you can use it like so (Razor syntax):

```<code>            <div id="menucontainer">

                <ul id="menu">
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("home", "index", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("account","logon", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("Logon", "Logon", "Account")</li>
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("home","about", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("About", "About", "Home")</li>
                </ul>

            </div>
</code>```

Hope it helps.

OwnerDisplayName: buggs

LastEditorDisplayName: Simucal

Body:
I saw different answers and came up with a class helper:

using System;
using System.Web.Mvc;

namespace MyMvcApp.Helpers {
    public class LocationHelper {
        public static bool IsCurrentControllerAndAction(string controllerName, string actionName, ViewContext viewContext) {
            bool result = false;
            string normalizedControllerName = controllerName.EndsWith("Controller") ? controllerName : String.Format("{0}Controller", controllerName);

            if(viewContext == null) return false;
            if(String.IsNullOrEmpty(actionName)) return false;

            if (viewContext.Controller.GetType().Name.Equals(normalizedControllerName, StringComparison.InvariantCultureIgnoreCase) &&
                viewContext.Controller.ValueProvider.GetValue("action").AttemptedValue.Equals(actionName, StringComparison.InvariantCultureIgnoreCase)) {
                result = true;
            }

            return result;
        }
    }
}

So in View (or master/layout) you can use it like so (Razor syntax):

            <div id="menucontainer">

                <ul id="menu">
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("home", "index", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("account","logon", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("Logon", "Logon", "Account")</li>
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("home","about", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("About", "About", "Home")</li>
                </ul>

            </div>

Hope it helps.


问:
Emgu AccessViolationException randomly occurring after upgrading from Emgu 2 to Emgu 3.1.0.1
I was using Emgu 2 (the one using opencv 2.4.10.1) and that was running pretty stable and would run without crashing. I have now upgrade to Emgu 3.1.0.1 and my app will crash sometimes within hours or a day with an AccessViolationException. I have seen it crash at two different locations now. See the two locations marked in the source code below (CRASH1 & CRASH2). So I think there is something fundamentally wrong here.

I am running a Release version of the software. Any one got any ideas what might be going on here?

The CRASH1 exception is:

```<code>Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
   at Emgu.CV.CvInvoke.cveSubtract(IntPtr, IntPtr, IntPtr, IntPtr, Emgu.CV.CvEnum.DepthType)
   at Emgu.CV.CvInvoke.Subtract(Emgu.CV.IInputArray, Emgu.CV.IInputArray, Emgu.CV.IOutputArray, Emgu.CV.IInputArray, Emgu.CV.CvEnum.DepthType)
   at Emgu.CV.RotationMatrix2D.CreateRotationMatrix(System.Drawing.PointF, Double, System.Drawing.Size, System.Drawing.Size ByRef)
   at Emgu.CV.Image`2[[Emgu.CV.Structure.Bgr, Emgu.CV.World, Version=3.1.0.2282, Culture=neutral, PublicKeyToken=7281126722ab4438],[System.Byte, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].Rotate(Double, System.Drawing.PointF, Emgu.CV.CvEnum.Inter, Emgu.CV.Structure.Bgr, Boolean)
   at Emgu.CV.Image`2[[Emgu.CV.Structure.Bgr, Emgu.CV.World, Version=3.1.0.2282, Culture=neutral, PublicKeyToken=7281126722ab4438],[System.Byte, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].Rotate(Double, Emgu.CV.Structure.Bgr, Boolean)
   at XXXX.ProcessFrames()
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.ThreadHelper.ThreadStart()
</code>```

The CRASH2 exception is:

```<code>Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
   at Emgu.CV.Util.VectorOfMat.VectorOfMatPush(IntPtr, IntPtr)
   at Emgu.CV.Util.VectorOfMat..ctor(Emgu.CV.Mat[])
   at XXXX.ProcessFrames()
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.ThreadHelper.ThreadStart()
</code>```

The source code is:

```<code>    public void start()
    {
        started = true;
        // start processing camera frames
        cameraThread = new Thread(new ThreadStart(ProcessFrames));
        cameraThread.IsBackground = true;
        cameraThread.Start();
    }

    private void ProcessFrames()
    {
        Bgr frameBg = new Bgr(0,0,0);
        while (true)
        {
            // try to open the camera device
            if (capture == null)
            {
                try
                {
                    int index;
                    bool isNumeric = int.TryParse(ConfigurationManager.AppSettings["CameraSource"], out index);
                    capture = isNumeric ? new Capture(index) : new Capture(ConfigurationManager.AppSettings["CameraSource"]);
                    capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameWidth, 640);
                    capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameHeight, 480);
                    capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.FourCC, Emgu.CV.VideoWriter.Fourcc('M', 'J', 'P', 'G'));
                }
                catch
                {
                    frameObservers.ForEach(a => a.frame(cameraNotConnectedBitmap, new List<Person>(), recognizer.isActive()));
                }
                Task.Delay(1000).Wait();
                continue;
            }

            // read a frame from the camera
            Mat matFrame = capture.QueryFrame();
            Image<Bgr, byte> frame = null;
            if (matFrame != null)
            {
                frame = matFrame.ToImage<Bgr, byte>();
            }
            if (frame == null)
            {
                frameObservers.ForEach(a => a.frame(cameraNotConnectedBitmap, new List<Person>(), recognizer.isActive()));
                capture = null; // force to reconnect to camera again
                Task.Delay(1000).Wait();
                continue;
            }

            try
            {
                CRASH1 >>>frame = frame.Rotate(Convert.ToInt32(ConfigurationManager.AppSettings["CameraRotation"]), frameBg, false);
                double scale = Convert.ToDouble(ConfigurationManager.AppSettings["CameraScale"]);
                if (scale > 0)
                {
                    frame = frame.Resize(scale, Emgu.CV.CvEnum.Inter.Linear);
                }

                Global.FRAME_HEIGHT = frame.Height;
                Global.FRAME_WIDTH = frame.Width;
                rawCameraFeedFrameObservers.ForEach(a => a.frame(frame));

                if (autoBrightness)
                {
                    Image<Lab, Byte> lab = frame.Convert<Lab, Byte>();
                    Image<Gray, Byte>[] planes = lab.Split();
                    CvInvoke.CLAHE(planes[0], claheClipLimit, new Size(8, 8), planes[0]);
                    CRASH2 >>>VectorOfMat vm = new VectorOfMat(planes[0].Mat, planes[1].Mat, planes[2].Mat);
                    CvInvoke.Merge(vm, lab);
                    frame = lab.Convert<Bgr, Byte>();
                }
            }
            catch
            {
                // not the end of the world
                Log.INFO("INFO", "Processing the frame failed, skipping this frame");
                continue;
            }
        }
    }
</code>```

答:
Maybe one thread would access system device while the initialisation is done by another concurrent thread...

As both Crash1 & Crash2 exception show this line

```<code>at System.Threading.ThreadHelper.ThreadStart()
</code>```

Did you try to catch exception directly on cameraThread.Start() ?

```<code>public void start()
{
    started = true;
    // start processing camera frames
    cameraThread = new Thread(new ThreadStart(ProcessFrames));
    cameraThread.IsBackground = true;
    try
    {
       cameraThread.Start();
    }
    catch
    {
       started = false;
       /* HERE ACCESS VIOLATION APPEAR, SO DELAY  */
       Task.Delay(1000).Wait();
       /* AND RETRY  */
    }
    continue;
}
</code>```

Body:
I was using Emgu 2 (the one using opencv 2.4.10.1) and that was running pretty stable and would run without crashing. I have now upgrade to Emgu 3.1.0.1 and my app will crash sometimes within hours or a day with an AccessViolationException. I have seen it crash at two different locations now. See the two locations marked in the source code below (CRASH1 & CRASH2). So I think there is something fundamentally wrong here.

I am running a Release version of the software. Any one got any ideas what might be going on here?

The CRASH1 exception is:

Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
   at Emgu.CV.CvInvoke.cveSubtract(IntPtr, IntPtr, IntPtr, IntPtr, Emgu.CV.CvEnum.DepthType)
   at Emgu.CV.CvInvoke.Subtract(Emgu.CV.IInputArray, Emgu.CV.IInputArray, Emgu.CV.IOutputArray, Emgu.CV.IInputArray, Emgu.CV.CvEnum.DepthType)
   at Emgu.CV.RotationMatrix2D.CreateRotationMatrix(System.Drawing.PointF, Double, System.Drawing.Size, System.Drawing.Size ByRef)
   at Emgu.CV.Image`2[[Emgu.CV.Structure.Bgr, Emgu.CV.World, Version=3.1.0.2282, Culture=neutral, PublicKeyToken=7281126722ab4438],[System.Byte, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].Rotate(Double, System.Drawing.PointF, Emgu.CV.CvEnum.Inter, Emgu.CV.Structure.Bgr, Boolean)
   at Emgu.CV.Image`2[[Emgu.CV.Structure.Bgr, Emgu.CV.World, Version=3.1.0.2282, Culture=neutral, PublicKeyToken=7281126722ab4438],[System.Byte, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].Rotate(Double, Emgu.CV.Structure.Bgr, Boolean)
   at XXXX.ProcessFrames()
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.ThreadHelper.ThreadStart()

The CRASH2 exception is:

Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
   at Emgu.CV.Util.VectorOfMat.VectorOfMatPush(IntPtr, IntPtr)
   at Emgu.CV.Util.VectorOfMat..ctor(Emgu.CV.Mat[])
   at XXXX.ProcessFrames()
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.ThreadHelper.ThreadStart()

The source code is:

    public void start()
    {
        started = true;
        // start processing camera frames
        cameraThread = new Thread(new ThreadStart(ProcessFrames));
        cameraThread.IsBackground = true;
        cameraThread.Start();
    }

    private void ProcessFrames()
    {
        Bgr frameBg = new Bgr(0,0,0);
        while (true)
        {
            // try to open the camera device
            if (capture == null)
            {
                try
                {
                    int index;
                    bool isNumeric = int.TryParse(ConfigurationManager.AppSettings["CameraSource"], out index);
                    capture = isNumeric ? new Capture(index) : new Capture(ConfigurationManager.AppSettings["CameraSource"]);
                    capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameWidth, 640);
                    capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameHeight, 480);
                    capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.FourCC, Emgu.CV.VideoWriter.Fourcc('M', 'J', 'P', 'G'));
                }
                catch
                {
                    frameObservers.ForEach(a => a.frame(cameraNotConnectedBitmap, new List<Person>(), recognizer.isActive()));
                }
                Task.Delay(1000).Wait();
                continue;
            }

            // read a frame from the camera
            Mat matFrame = capture.QueryFrame();
            Image<Bgr, byte> frame = null;
            if (matFrame != null)
            {
                frame = matFrame.ToImage<Bgr, byte>();
            }
            if (frame == null)
            {
                frameObservers.ForEach(a => a.frame(cameraNotConnectedBitmap, new List<Person>(), recognizer.isActive()));
                capture = null; // force to reconnect to camera again
                Task.Delay(1000).Wait();
                continue;
            }

            try
            {
                CRASH1 >>>frame = frame.Rotate(Convert.ToInt32(ConfigurationManager.AppSettings["CameraRotation"]), frameBg, false);
                double scale = Convert.ToDouble(ConfigurationManager.AppSettings["CameraScale"]);
                if (scale > 0)
                {
                    frame = frame.Resize(scale, Emgu.CV.CvEnum.Inter.Linear);
                }

                Global.FRAME_HEIGHT = frame.Height;
                Global.FRAME_WIDTH = frame.Width;
                rawCameraFeedFrameObservers.ForEach(a => a.frame(frame));

                if (autoBrightness)
                {
                    Image<Lab, Byte> lab = frame.Convert<Lab, Byte>();
                    Image<Gray, Byte>[] planes = lab.Split();
                    CvInvoke.CLAHE(planes[0], claheClipLimit, new Size(8, 8), planes[0]);
                    CRASH2 >>>VectorOfMat vm = new VectorOfMat(planes[0].Mat, planes[1].Mat, planes[2].Mat);
                    CvInvoke.Merge(vm, lab);
                    frame = lab.Convert<Bgr, Byte>();
                }
            }
            catch
            {
                // not the end of the world
                Log.INFO("INFO", "Processing the frame failed, skipping this frame");
                continue;
            }
        }
    }

Body:
Maybe one thread would access system device while the initialisation is done by another concurrent thread...

As both Crash1 & Crash2 exception show this line

at System.Threading.ThreadHelper.ThreadStart()

Did you try to catch exception directly on cameraThread.Start() ?

public void start()
{
    started = true;
    // start processing camera frames
    cameraThread = new Thread(new ThreadStart(ProcessFrames));
    cameraThread.IsBackground = true;
    try
    {
       cameraThread.Start();
    }
    catch
    {
       started = false;
       /* HERE ACCESS VIOLATION APPEAR, SO DELAY  */
       Task.Delay(1000).Wait();
       /* AND RETRY  */
    }
    continue;
}


问:
Roles.userIsInRole returns FALSE - Meteor
Im using FlowRouter with FlowTemplate and in both/router/router.js I am checking is it user in role admin:

```<code>....
action: function () {
    if(Roles.userIsInRole(Meteor.userId(), 'admin')){
        FlowLayout.render('layout', {
            sidebar: 'sidebar', main:'admin', cart:'cart'
        })
    } else {
        FlowLayout.render('layout', {
            sidebar: 'sidebar', main:'unauthorised', cart:'cart'
        })
    }

    console.log(Meteor.userId());

}
....
</code>```

and returns FALSE, but when I use it in the WEB console is TRUE . This line console.log(Meteor.userId()); output the correct userID and when I am logged in, if I do this in the WEB console Roles.userIsInRole(Meteor.userId(), 'admin'), it is TRUE. If I do this Meteor.user().roles, the result is ['admin']

If I check in the template is it user in role:

```<code>{{#if isInRole 'admin' }}
    ADMIN
{{/if}}
</code>```

It is TRUE, but in the router.js returns FALSE.

How to fix it ?

答:
yep, sounds like the timing issues i encountered. 2 race conditions i had to solve (one with AccountsTemplates, the other with the roles being ready). it's discussed here:

https://github.com/kadirahq/flow-router/issues/608

here is my solution. it goes at the top of the routes.js:

```<code>import {Tracker} from 'meteor/tracker';

if (Meteor.isClient) {
    FlowRouter.wait();

    let tracker;
    let self = this;

    self.getATReady = () => AccountsTemplates._initialized;

    let timer = Meteor.setInterval(function() {
        if (self.getATReady()) {
            tracker.invalidate();
            clearInterval(timer);
        }
    }, 500);

    tracker = Tracker.autorun(function() {
        if (!FlowRouter._initialized && Roles.subscription.ready() && self.getATReady()) {
            clearInterval(timer);
            FlowRouter.initialize();
        }
    });
}
</code>```

basically, this code prevents the initialization of FlowRouter until both the roles and AccountsTemplates are ready. once they're both ready, FR is initialized and you can use your routes knowing you can check roles.

i've had this fix in since August 2016, across several Meteor versions, and i've not seen the problem recur.

Body:
Im using FlowRouter with FlowTemplate and in both/router/router.js I am checking is it user in role admin:

....
action: function () {
    if(Roles.userIsInRole(Meteor.userId(), 'admin')){
        FlowLayout.render('layout', {
            sidebar: 'sidebar', main:'admin', cart:'cart'
        })
    } else {
        FlowLayout.render('layout', {
            sidebar: 'sidebar', main:'unauthorised', cart:'cart'
        })
    }

    console.log(Meteor.userId());

}
....

and returns FALSE, but when I use it in the WEB console is TRUE . This line console.log(Meteor.userId()); output the correct userID and when I am logged in, if I do this in the WEB console Roles.userIsInRole(Meteor.userId(), 'admin'), it is TRUE. If I do this Meteor.user().roles, the result is ['admin']

If I check in the template is it user in role:

{{#if isInRole 'admin' }}
    ADMIN
{{/if}}

It is TRUE, but in the router.js returns FALSE.

How to fix it ?

Body:
yep, sounds like the timing issues i encountered. 2 race conditions i had to solve (one with AccountsTemplates, the other with the roles being ready). it's discussed here:

https://github.com/kadirahq/flow-router/issues/608

here is my solution. it goes at the top of the routes.js:

import {Tracker} from 'meteor/tracker';

if (Meteor.isClient) {
    FlowRouter.wait();

    let tracker;
    let self = this;

    self.getATReady = () => AccountsTemplates._initialized;

    let timer = Meteor.setInterval(function() {
        if (self.getATReady()) {
            tracker.invalidate();
            clearInterval(timer);
        }
    }, 500);

    tracker = Tracker.autorun(function() {
        if (!FlowRouter._initialized && Roles.subscription.ready() && self.getATReady()) {
            clearInterval(timer);
            FlowRouter.initialize();
        }
    });
}

basically, this code prevents the initialization of FlowRouter until both the roles and AccountsTemplates are ready. once they're both ready, FR is initialized and you can use your routes knowing you can check roles.

i've had this fix in since August 2016, across several Meteor versions, and i've not seen the problem recur.


问:
Writing file properties with spring boot
I've used the @PropertySource and @Value annotations for reading external file properties and it works great. But if I want to write the same @Value annotated properties out to an external file, can that be done? I've done some searching but can't seem to find a way of doing it. Is there native support for this?</p>

答: You should have a look at the DefaultPropertiesPersister. An example is provided here.</p>


问:
extract structs values into variable named as the field
I have a 1x1 Matlab struct with 5 fields ('a', 'b', 'c', 'd', 'e'). Each field contains some sort of data (which doesn't really matter for my question) and I would like to extract each value out of the struct and assign it to a variable named as the field. Any idea for a code that will do it?</p>

答:
assuming s is your structure

```<code>cellfun(@(x) assignin('base', x, s.(x)), fieldnames(s));
</code>```

However, I do not see a good use-case for this as already mentioned by gnovice.

Body:
assuming s is your structure

cellfun(@(x) assignin('base', x, s.(x)), fieldnames(s));

However, I do not see a good use-case for this as already mentioned by gnovice.


问:
Facebook Graph API: Getting the total number of posts
I've been using the Facebook Graph API to display user posts.  When I get the initial "page" of posts, the resulting data object has a paging property object with a previous and next URL property.  I was hoping to generate navigation links based on this available paging information.  However, sometimes these URLs point to an empty set of data, so I obviously don't want to navigate the user to an empty page.

Is there a way to find the total count of objects in a collection so that better navigation can be derived?  Is there any way to get smarter paging data?

Update:
Sorry if my post isn't clear.  To illustrate, look at the data at https://graph.facebook.com/7901103/posts and its paging property URLs.  Then follow those URLs to see the issue: empty pages of data.

答:
Why be dependent of Facebook?

Why don't you preload all data for a user and save into a database. Then you fetch the posts from db and show to user. This way you have all the control on how many posts there are and how to manage next and prev.


问:
Two different variables getting same value
I am currently working on a small Java application and I ran into a problem. I create two different variables, but after I run the code, the first variable is getting the same value as the second one. They should be different.

Here is my custom file class:

```<code>public class MyFile {

    private static String path;
    private static String name;

    private static final String FILE_SEPARATOR = "/";

    public MyFile(String path) {
        System.out.println(path);
        this.path = "";
        this.name = "";
        this.path = /*FILE_SEPARATOR*/path;
        String[] dirs = path.split(FILE_SEPARATOR);
        this.name = dirs[dirs.length - 1];
    }

    public static String getPath() {
        return path;
    }

    public static String getName() {
        return name;
    }

    public String toString() {
        return "Path: " + path + ", Name: " + name;
    }
}
</code>```

Here I am using the variables:

```<code>MyFile modelFile = new MyFile("res\\model.dae");
MyFile textureFile = new MyFile("res\\diffuse.png");
System.out.println(modelFile.toString());
System.out.println(textureFile.toString());
</code>```

The output is the following: http://imgur.com/a/Nu3N6

答:
When Defining an Entity class the class variable show be private period. Unless you want to access these variable statically, as in without having to instantiate the class or using getters and setter. If you use getters and setters as you have done above, and clearly made an instance of the class you want  use ensure you don't use static access modifiers for the class variables.

The modified code is-as below.
    package StackOverflowProblemSets;

/**
 * Created by HACKER on 05/06/2017.
 * Two different variables getting same value
 */
public class MyFile {

```<code>private  String path;
private  String name;

private static final String FILE_SEPARATOR = "/";

public MyFile(String path) {
    System.out.println(path);
    this.path = "";
    this.name = "";
    this.path = /*FILE_SEPARATOR*/path;
    String[] dirs = path.split(FILE_SEPARATOR);
    this.name = dirs[dirs.length - 1];
}

public  String getPath() {
    return path;
}

public  String getName() {
    return name;
}

public String toString() {
    return "Path: " + path + ", Name: " + name;
}

public static void main(String[] args) {
    MyFile modelFile = new MyFile("res\\model.dae");
    MyFile textureFile = new MyFile("res\\diffuse.png");
    System.out.println(modelFile.toString());
    System.out.println(textureFile.toString());
}
</code>```

}

Body:
I am currently working on a small Java application and I ran into a problem. I create two different variables, but after I run the code, the first variable is getting the same value as the second one. They should be different.

Here is my custom file class:

public class MyFile {

    private static String path;
    private static String name;

    private static final String FILE_SEPARATOR = "/";

    public MyFile(String path) {
        System.out.println(path);
        this.path = "";
        this.name = "";
        this.path = /*FILE_SEPARATOR*/path;
        String[] dirs = path.split(FILE_SEPARATOR);
        this.name = dirs[dirs.length - 1];
    }

    public static String getPath() {
        return path;
    }

    public static String getName() {
        return name;
    }

    public String toString() {
        return "Path: " + path + ", Name: " + name;
    }
}

Here I am using the variables:

MyFile modelFile = new MyFile("res\\model.dae");
MyFile textureFile = new MyFile("res\\diffuse.png");
System.out.println(modelFile.toString());
System.out.println(textureFile.toString());

The output is the following: http://imgur.com/a/Nu3N6

Body:
When Defining an Entity class the class variable show be private period. Unless you want to access these variable statically, as in without having to instantiate the class or using getters and setter. If you use getters and setters as you have done above, and clearly made an instance of the class you want  use ensure you don't use static access modifiers for the class variables.

The modified code is-as below.
    package StackOverflowProblemSets;

/**
 * Created by HACKER on 05/06/2017.
 * Two different variables getting same value
 */
public class MyFile {

private  String path;
private  String name;

private static final String FILE_SEPARATOR = "/";

public MyFile(String path) {
    System.out.println(path);
    this.path = "";
    this.name = "";
    this.path = /*FILE_SEPARATOR*/path;
    String[] dirs = path.split(FILE_SEPARATOR);
    this.name = dirs[dirs.length - 1];
}

public  String getPath() {
    return path;
}

public  String getName() {
    return name;
}

public String toString() {
    return "Path: " + path + ", Name: " + name;
}

public static void main(String[] args) {
    MyFile modelFile = new MyFile("res\\model.dae");
    MyFile textureFile = new MyFile("res\\diffuse.png");
    System.out.println(modelFile.toString());
    System.out.println(textureFile.toString());
}

}


问:
How to save the button state using NSUserDefaults
I am new to iphone.I have small doubt that is I have a button with name Sync off when we click that button the below action executes :

```<code>- (IBAction)syncOffClickedInRegisterUserScreen:(id)sender {
    if ([syncOnorOff.titleLabel.text isEqualToString:@"Sync off"]) {
        [syncOnorOff setTitle:@"Sync on" forState:UIControlStateNormal];
    }
    else {
        [syncOnorOff setTitle:@"Sync off" forState:UIControlStateNormal];
    }
}
</code>```

Due to the above code, when I click the button the title alternates.

How can I save the state of the button with different titles using NSUserDefaults. If anybody knows this please help me....

答:
```<code>UIButton *button;

// get nsuserdefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// save selected state
[defaults setBool:button.selected forKey:@"myButtonState"];
</code>```

Then later, after the app launches again...

```<code>// restore the selected state
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
button.selected = [defaults boolForKey:@"myButtonState"];
</code>```

Body:
I am new to iphone.I have small doubt that is I have a button with name Sync off when we click that button the below action executes :

- (IBAction)syncOffClickedInRegisterUserScreen:(id)sender {
    if ([syncOnorOff.titleLabel.text isEqualToString:@"Sync off"]) {
        [syncOnorOff setTitle:@"Sync on" forState:UIControlStateNormal];
    }
    else {
        [syncOnorOff setTitle:@"Sync off" forState:UIControlStateNormal];
    }
}

Due to the above code, when I click the button the title alternates.

How can I save the state of the button with different titles using NSUserDefaults. If anybody knows this please help me....

Body:
UIButton *button;

// get nsuserdefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// save selected state
[defaults setBool:button.selected forKey:@"myButtonState"];

Then later, after the app launches again...

// restore the selected state
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
button.selected = [defaults boolForKey:@"myButtonState"];


问:
Better algorithm to calculate this formula
Given an array of positive integers A, I want to find the following sum S:

S = 2^1 * (S_1) + 2^2 * (S_2) + 2^3 * (S_3) + ... + 2^n * (S_N)

where S_i is sum of product of consecutive i integers in A, for eg:

S_3 = (A[0]*A[1]*A[2]) + (A[1]*A[2]*A[3]) + .... + (A[n-3]*A[n-2]*A[n-1])

For calculating any of the S_i, I am using method similar to rolling hash, which achieve O(N):

```<code>Let tmp = A[0]*A[1]*A[2], S_3 = tmp;
For(i = 3 to n)
    (tmp *= A[i]) /= A[i-3]
    S_3 += tmp
</code>```

And for all two's power I can precompute  beforehand. So now my algorithm to calculate S is O(N^2)

My question is, is it possible to calculate S with a better complexity?

答:
There is a recurrence pattern you could use for calculating a solution with a linear time complexity.

Consider an example input:

      A = [2, 5, 3, 2, 1, 8]

Now look at the partial array with only the first element:

      A0 = [2]

Call the outcome for this partial array R0. It is clear that:

      R0 = 2⋅A[0] = 2⋅2 = 4

Then consider the array with one more value from the original array:

      A1 = [2, 5]

Call the outcome for this partial array R1. We calculate that:

      R1 = 2⋅(A[0]+A[1]) + 4⋅(A[0]⋅A[1]) = 54

We can try to write this in terms of R0, hoping we can thus limit the number of calculations to make:

      R1 = 2⋅(2⋅A[0] + 1)⋅A[1] + R0

Extending again with a third element, we get:

      R2 = 2⋅(A[0]+A[1]+A[2]) + 4⋅(A[0]⋅A[1] + A[1]⋅A[2]) + 8⋅(A[0]⋅A[1]⋅A[2]) = 360

Let's try to write this in terms of R1:

      R2 = 2⋅(2⋅(2⋅A[0] + 1)⋅A[1] + 1)⋅A[2] + R1

There is a pattern emerging, where the first term looks much like the first term in the previous R. It is something like 2⋅(X + 1)⋅A[2], where X is the first term of the previous R. We can generally say:

      Rn = 2⋅(Rn-1 − Rn-2 + 1)⋅A[n] + Rn-1

...where Rn is 0 when n < 0.

Now that is something that can be calculated in linear time. Here is an implementation in JavaScript, which also includes a second function that does the calculation in the naive, non-optimised way, so that the result can be compared:

function fastCalcS(a) {
    let r0, r1, r2;
    r1 = r2 = 0;
    for (let i = 0; i < a.length; i++) {
        r0 = r1;
        r1 = r2;
        r2 = 2*(r1 - r0 + 1)*a[i] + r1;
    }
    return r2;
}

// This function does it the slow way, and executes
// the literal definition of S without optimisation:
function slowCalcS(a) {
    let coeff = 2;
    let s = 0
    for (let i = 0; i < a.length; i++) {
        let s_i = 0;
        for (let j = 0; j < a.length-i; j++) {
            let prod = 1;
            for (let k = 0; k <= i; k++) {
                prod *= a[j+k];
            }
            s_i += prod;
        }
        s += coeff * s_i;
        coeff *= 2;
    }
    return s;
}

var a = [2, 5, 3, 2, 1, 8];
console.log('slow way:', slowCalcS(a));
console.log('fast way:', fastCalcS(a));```
</div>
</div>
</p>

<p>In languages that provide a <code>reduce</code> array method (as JavaScript does), the function can look like this (ES6 syntax):</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>function fastCalcS(a) {
    return a.reduce( ([r1, r2], v) => [r2, 2*(r2 - r1 + 1)*v + r2], [0, 0] )[1];
}

var a = [2, 5, 3, 2, 1, 8];
console.log(fastCalcS(a));</code>```

Body:
Given an array of positive integers A, I want to find the following sum S:

S = 2^1 * (S_1) + 2^2 * (S_2) + 2^3 * (S_3) + ... + 2^n * (S_N)

where S_i is sum of product of consecutive i integers in A, for eg:

S_3 = (A[0]*A[1]*A[2]) + (A[1]*A[2]*A[3]) + .... + (A[n-3]*A[n-2]*A[n-1])

For calculating any of the S_i, I am using method similar to rolling hash, which achieve O(N):

Let tmp = A[0]*A[1]*A[2], S_3 = tmp;
For(i = 3 to n)
    (tmp *= A[i]) /= A[i-3]
    S_3 += tmp

And for all two's power I can precompute  beforehand. So now my algorithm to calculate S is O(N^2)

My question is, is it possible to calculate S with a better complexity?

Body:
There is a recurrence pattern you could use for calculating a solution with a linear time complexity.

Consider an example input:

      A = [2, 5, 3, 2, 1, 8]

Now look at the partial array with only the first element:

      A0 = [2]

Call the outcome for this partial array R0. It is clear that:

      R0 = 2⋅A[0] = 2⋅2 = 4

Then consider the array with one more value from the original array:

      A1 = [2, 5]

Call the outcome for this partial array R1. We calculate that:

      R1 = 2⋅(A[0]+A[1]) + 4⋅(A[0]⋅A[1]) = 54

We can try to write this in terms of R0, hoping we can thus limit the number of calculations to make:

      R1 = 2⋅(2⋅A[0] + 1)⋅A[1] + R0

Extending again with a third element, we get:

      R2 = 2⋅(A[0]+A[1]+A[2]) + 4⋅(A[0]⋅A[1] + A[1]⋅A[2]) + 8⋅(A[0]⋅A[1]⋅A[2]) = 360

Let's try to write this in terms of R1:

      R2 = 2⋅(2⋅(2⋅A[0] + 1)⋅A[1] + 1)⋅A[2] + R1

There is a pattern emerging, where the first term looks much like the first term in the previous R. It is something like 2⋅(X + 1)⋅A[2], where X is the first term of the previous R. We can generally say:

      Rn = 2⋅(Rn-1 − Rn-2 + 1)⋅A[n] + Rn-1

...where Rn is 0 when n < 0.

Now that is something that can be calculated in linear time. Here is an implementation in JavaScript, which also includes a second function that does the calculation in the naive, non-optimised way, so that the result can be compared:

function fastCalcS(a) {
    let r0, r1, r2;
    r1 = r2 = 0;
    for (let i = 0; i < a.length; i++) {
        r0 = r1;
        r1 = r2;
        r2 = 2*(r1 - r0 + 1)*a[i] + r1;
    }
    return r2;
}

// This function does it the slow way, and executes
// the literal definition of S without optimisation:
function slowCalcS(a) {
    let coeff = 2;
    let s = 0
    for (let i = 0; i < a.length; i++) {
        let s_i = 0;
        for (let j = 0; j < a.length-i; j++) {
            let prod = 1;
            for (let k = 0; k <= i; k++) {
                prod *= a[j+k];
            }
            s_i += prod;
        }
        s += coeff * s_i;
        coeff *= 2;
    }
    return s;
}

var a = [2, 5, 3, 2, 1, 8];
console.log('slow way:', slowCalcS(a));
console.log('fast way:', fastCalcS(a));

In languages that provide a reduce array method (as JavaScript does), the function can look like this (ES6 syntax):

function fastCalcS(a) {
    return a.reduce( ([r1, r2], v) => [r2, 2*(r2 - r1 + 1)*v + r2], [0, 0] )[1];
}

var a = [2, 5, 3, 2, 1, 8];
console.log(fastCalcS(a));


问:
Set Minimum date to UIDatePicker
I have a date in UILabel(like 'Dec 14, 2010). This date i want to set as minimum date of my UIDatepicker. How can i do this please reply?

Thanks
Nishant

答:
You can use NSDateFormatter and use setDateFormat method for setting Date format.

```<code>[formatter setDateFormat:@"MMM dd,yyyy"];

NSDate *date = [formatter dateFromString:lblDate.text];

datePicker.minimumDate=date;
</code>```

Title: Set Minimum date to UIDatePicker

Body:
You can use NSDateFormatter and use setDateFormat method for setting Date format.

[formatter setDateFormat:@"MMM dd,yyyy"];

NSDate *date = [formatter dateFromString:lblDate.text];

datePicker.minimumDate=date;


问:
Detach and move element after completing animation
I have a list of items with a close button associated with each item. When clicked, animation plays, list slides up and the item is removed successfully .

```<code>$(document).on("click", ".close-button", function(e) { //removes with animation
    $(this).parent().animate({
        opacity: 0
    }, 250, function() {
        $(this).animate({
                marginBottom: 0
            }, 250)
            .children()
            .animate({
                padding: 0
            }, 250)
            .wrapInner("<div />")
            .children()
            .slideUp(250, function() {
                $(this).closest(".element").remove();
            });
    });
});
</code>```

I attempted to modify the above piece of code so that instead of removing the item, I detach the item and move it to another view. I attempted this  using the below code, to no avail.
$(this).closest('.element').detach().prependTo('#diff-view').hide().slideDown(250)

Getting rid of the animations moves the element to a different view successfully.

```<code>$(document).on("click", ".close-button" ,function(e) { //detaches w/o animation
  $(this).closest('.element').detach().prependTo('#diff-view').hide().slideDown(250)
});
</code>```

I want to keep the animations of course, but I just can't figure out how to detach instead of remove while keeping them in place. Any help would be greatly appreciated.

答:
As you are animating parent this refers to the animated element. As result reference to close button is lost.

Store the reference of element of current element and the use later to target.

```<code>$(document).on("click", ".close-button", function (e) {
    //Store the reference
    var $this= $(this);
    $(this).parent().animate({
        opacity: 0
    }, 250, function () {
        $(this).animate({
            marginBottom: 0
        }, 250)
        .children()
        .animate({
            padding: 0
        }, 250)
        .wrapInner("<div />")
        .children()
        .slideUp(250, function () {
            $this.closest('.element').prependTo('#diff-view').hide().slideDown(250)
        });
    });
});
</code>```

Body:
I have a list of items with a close button associated with each item. When clicked, animation plays, list slides up and the item is removed successfully .

$(document).on("click", ".close-button", function(e) { //removes with animation
    $(this).parent().animate({
        opacity: 0
    }, 250, function() {
        $(this).animate({
                marginBottom: 0
            }, 250)
            .children()
            .animate({
                padding: 0
            }, 250)
            .wrapInner("
")
            .children()
            .slideUp(250, function() {
                $(this).closest(".element").remove();
            });
    });
});

I attempted to modify the above piece of code so that instead of removing the item, I detach the item and move it to another view. I attempted this  using the below code, to no avail.
$(this).closest('.element').detach().prependTo('#diff-view').hide().slideDown(250)

Getting rid of the animations moves the element to a different view successfully.

$(document).on("click", ".close-button" ,function(e) { //detaches w/o animation
  $(this).closest('.element').detach().prependTo('#diff-view').hide().slideDown(250)
});

I want to keep the animations of course, but I just can't figure out how to detach instead of remove while keeping them in place. Any help would be greatly appreciated.

Body:
As you are animating parent this refers to the animated element. As result reference to close button is lost.

Store the reference of element of current element and the use later to target.

$(document).on("click", ".close-button", function (e) {
    //Store the reference
    var $this= $(this);
    $(this).parent().animate({
        opacity: 0
    }, 250, function () {
        $(this).animate({
            marginBottom: 0
        }, 250)
        .children()
        .animate({
            padding: 0
        }, 250)
        .wrapInner("<div />")
        .children()
        .slideUp(250, function () {
            $this.closest('.element').prependTo('#diff-view').hide().slideDown(250)
        });
    });
});


问:
Change filter intensity like brightness from 0 to 100 via slider control in gpuimage2 swift
I followed the example of changing filter intensity on video camera from GPUImage2 examples, I am trying to change the filter intensity on a static image with iOS slider control, but it's not changing the intensity.

```<code>    @IBOutlet weak var renderView: RenderView!
     var filterContrast:ContrastAdjustment!
    @IBOutlet weak var sliderContrast: UISlider!
    let inputImage = UIImage(named:"WID-small.jpg")!
     var picture:PictureInput!

     // setting dynamic observable property.
     dynamic var filterValue = 3.0 {

     didSet {
        filterContrast.contrast = GLfloat(filterValue)
        picture.processImage()
     }
}
</code>```

on viewDidLayoutSubviews

```<code>    picture = PictureInput(image: inputImage)
    filterContrast = ContrastAdjustment();

    picture --> filterContrast --> renderView
    filterValue  = 3; // will call did set property and call processimage from it
</code>```

on Slider Update

```<code>        filterValue = Double(nm);
</code>```

is there any thing wrong, with this approach?

Thanks

答:
Every time your slider value changes, you're creating a new ContrastAdjustment filter instance and attaching it to the picture. Your old filter instance is still there, and the RenderView will ignore any inputs beyond the first one that goes into it. In fact, you should have been seeing warnings on the console telling you about that fact that you're adding too many inputs to the RenderView.

Instead of creating a whole new ContrastAdjustment filter each time, simply save your contrast filter as an instance variable and adjust its contrast property when the slider changes.

Body:
I followed the example of changing filter intensity on video camera from GPUImage2 examples, I am trying to change the filter intensity on a static image with iOS slider control, but it's not changing the intensity.

    @IBOutlet weak var renderView: RenderView!
     var filterContrast:ContrastAdjustment!
    @IBOutlet weak var sliderContrast: UISlider!
    let inputImage = UIImage(named:"WID-small.jpg")!
     var picture:PictureInput!

     // setting dynamic observable property.
     dynamic var filterValue = 3.0 {

     didSet {
        filterContrast.contrast = GLfloat(filterValue)
        picture.processImage()
     }
}

on viewDidLayoutSubviews

    picture = PictureInput(image: inputImage)
    filterContrast = ContrastAdjustment();

    picture --> filterContrast --> renderView
    filterValue  = 3; // will call did set property and call processimage from it

on Slider Update

        filterValue = Double(nm);

is there any thing wrong, with this approach?

Thanks


问:
How to close download banner with Chrome Webdriver?
In my tests I download a file, which works fine, but later when I am trying to click on an element I cannot scroll into view, the chrome download dialog box on the bottom of the page is in the way.  There is no way to move the button I need to click into view, so is there a way to close that download box with chrome webdriver?</p>

答:
Sending the control keys did not work for me, but I developed a workaround. I do any download test in a new window, then close the download window, the original window does not have the download bar. It must be a new window, if you do a new tab it will transfer over, to get this I use JavaScript. Switch to the new window, run download test and then switch to the original window when done.</p>

```<code>string javascript = $"$(window.open('', '_blank', 'location=yes'))";

((IJavaScriptExecutor)Driver).ExecuteScript(javascript); //create new window

Driver.SwitchTo().Window(Driver.WindowHandles.Last())); //switch to new window

//do download test here

Driver.Close(); //close created window

Driver.SwitchTo().Window(Driver.WindowHandles.First()); //back to original window with no download bar
</code>```

Body:
Sending the control keys did not work for me, but I developed a workaround. I do any download test in a new window, then close the download window, the original window does not have the download bar. It must be a new window, if you do a new tab it will transfer over, to get this I use JavaScript. Switch to the new window, run download test and then switch to the original window when done.

string javascript = $"$(window.open('', '_blank', 'location=yes'))";

((IJavaScriptExecutor)Driver).ExecuteScript(javascript); //create new window

Driver.SwitchTo().Window(Driver.WindowHandles.Last())); //switch to new window

//do download test here

Driver.Close(); //close created window

Driver.SwitchTo().Window(Driver.WindowHandles.First()); //back to original window with no download bar


问:
.renderTitle(false) is not working on linechart DC.js
I have some DC.js charts, I added a tooltip with d3-tip, so I needed to disable .title, use .renderTitle (false) and works well with bar charts and a GeoJson map, but when I use it in Linechart does not work. Is it a DC.js or d3-tip bug?</p>

答:
It works, but you have to call it before the chart is rendered, because it will not affect an existing chart. (And redraw won't remove any existing titles.)

Here is a fiddle demo, based on the Line Chart Example. The important part is calling

```<code>chart.renderTitle(false);
</code>```

before

```<code>chart.render();
</code>```

http://jsfiddle.net/1rafgm40/2/

Body:
It works, but you have to call it before the chart is rendered, because it will not affect an existing chart. (And redraw won't remove any existing titles.)

Here is a fiddle demo, based on the Line Chart Example. The important part is calling

chart.renderTitle(false);

before

chart.render();

http://jsfiddle.net/1rafgm40/2/


问:
How to merge 2 strings alternately in rails?
I have 2 strings:

```<code>a = "qwer"

b = "asd"

Result = "qawsedr"
</code>```

Same is the length of b is greater than a. show alternate the characters.

What is the best way to do this? Should I use loop?

答:
You can get the chars from your a and b string to work with them as arrays and then "merge" them using zip, then join them.

In the case of strings with different length, the array values must be reversed, so:

```<code>def merge_alternately(a, b)
  a = a.chars
  b = b.chars
  if a.length >= b.length
    a.zip(b)
  else
    array = b.zip(a)
    array.map{|e| e != array[-1] ? e.reverse  : e}
  end
end

p merge_alternately('abc', 'def').join
# => "adbecf"
p merge_alternately('ab', 'zsd').join
# => "azbsd"
p merge_alternately('qwer', 'asd').join
# => "qawsedr"
</code>```

Body:
I have 2 strings:

a = "qwer"

b = "asd"

Result = "qawsedr"

Same is the length of b is greater than a. show alternate the characters.

What is the best way to do this? Should I use loop?

Body:
You can get the chars from your a and b string to work with them as arrays and then "merge" them using zip, then join them.

In the case of strings with different length, the array values must be reversed, so:

def merge_alternately(a, b)
  a = a.chars
  b = b.chars
  if a.length >= b.length
    a.zip(b)
  else
    array = b.zip(a)
    array.map{|e| e != array[-1] ? e.reverse  : e}
  end
end

p merge_alternately('abc', 'def').join
# => "adbecf"
p merge_alternately('ab', 'zsd').join
# => "azbsd"
p merge_alternately('qwer', 'asd').join
# => "qawsedr"