问:
View in XIB Not Resizing For Different Devices
In my app I subclass a UIView in order to capture video from the camera that is displayed in the View, along with an UIImage that is overlaid on it.  I have AutoLayout turned on, but the issue is that the View stays the same size of whatever I have listed in the XIB for Simulated Metrics Size.  If I leave simulated Metrics as Inferred or Freeform, it doesn't work on either of them, but if I put it on iPhone 4.7, you see a background behind it on the edges.  Here is the code for the ViewController where the AVCaptureSession happens:

```<code>-(void)viewWillAppear:(BOOL)animated {
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MMM d hh:mm:ss a"];
    // display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
    NSString *currentTime = [dateFormatter stringFromDate:today];
    NSError* error4 = nil;
    AVAudioSession* audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryAmbient error:&error4];
    OSStatus propertySetError = 0;
    UInt32 allowMixing = true;
    propertySetError |= AudioSessionSetProperty(kAudioSessionProperty_OtherMixableAudioShouldDuck, sizeof(allowMixing), &allowMixing);

    // Activate the audio session
    error4 = nil;
    if (![audioSession setActive:YES error:&error4]) {
        NSLog(@"AVAudioSession setActive:YES failed: %@", [error4 localizedDescription]);
    }
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [paths objectAtIndex:0];

    self.session = [[AVCaptureSession alloc] init];
    [self.session beginConfiguration];
    self.session.sessionPreset = AVCaptureSessionPreset1280x720;
    self.navigationController.navigationBarHidden = YES;

    NSError *error = nil;

    AVCaptureDevice *audioCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
    NSError *error2 = nil;
    AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioCaptureDevice error:&error2];

    AVCaptureDevice *device;
    AVCaptureDevicePosition desiredPosition = AVCaptureDevicePositionBack;
    // find the front facing camera

    device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    // get the input device
    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];

    AVCaptureMovieFileOutput *movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];

    NSString *archives = [documentsDirectoryPath stringByAppendingPathComponent:@"archives"];
    NSString *editedfilename = [[@"ComeOnDown" lastPathComponent] stringByDeletingPathExtension];
    NSString *datestring = [[editedfilename stringByAppendingString:@" "] stringByAppendingString:currentTime];
    NSLog(@"%@", datestring);
    NSString *outputpathofmovie = [[archives stringByAppendingPathComponent:datestring] stringByAppendingString:@".mp4"];
    NSURL *outputURL = [[NSURL alloc] initFileURLWithPath:outputpathofmovie];
    [self.session addInput:audioInput];
    [self.session addInput:deviceInput];
    [self.session addOutput:movieFileOutput];
    [self.session commitConfiguration];
    [self.session startRunning];

    AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    previewLayer.backgroundColor = [[UIColor blackColor] CGColor];
    previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    previewLayer.connection.videoOrientation = AVCaptureVideoOrientationLandscapeRight;

    CALayer *overlayLayer = [CALayer layer];
    CALayer *overlayLayer2 = [CALayer layer];

    UIImage *overlayImage = [UIImage imageNamed:@"LiveBorder.png"];

    [overlayLayer setContents:(id)[overlayImage CGImage]];
    overlayLayer.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
    [overlayLayer setMasksToBounds:YES];

       CALayer *rootLayer = [self.view layer];
    [rootLayer setMasksToBounds:YES];
    [previewLayer setFrame:[rootLayer bounds]];
    [rootLayer addSublayer:previewLayer];
    [rootLayer addSublayer:overlayLayer];
    [rootLayer addSublayer:label2.layer];
        movieFileOutput.movieFragmentInterval = kCMTimeInvalid;

    [movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self];

    //self.session = nil;
    if (error) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:
                                  [NSString stringWithFormat:@"Failed with error %d", (int)[error code]]
                                                            message:[error localizedDescription]
                                                           delegate:nil
                                                  cancelButtonTitle:@"Dismiss"
                                                  otherButtonTitles:nil];
        [alertView show];

    }
    [super viewWillAppear:YES];
}
-(void)viewWillDisappear:(BOOL)animated {
    self.navigationController.navigationBarHidden = NO;

}

-(void)captureOutput:(AVCaptureFileOutput *)captureOutput didStartRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray *)connections {

}
-(void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    NSLog(@"Finished with error: %@", error);
}
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error {
    //finished
    NSLog(@"Finished");
    NSString *proud = [[NSString alloc] initWithString:[outputFileURL path]];
    UISaveVideoAtPathToSavedPhotosAlbum(proud, self, @selector(video:didFinishSavingWithError: contextInfo:), (__bridge void *)(proud));
}

-(IBAction)goBackNow {
    [myAVPlayer stop];

    [self.session stopRunning];
    // [captureView performSelector:@selector(stopRecording) withObject:nil afterDelay:0.0];

    NSString *outputPath = [[NSString alloc] initWithFormat:@"%@/%@", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0], @"output.mp4"];
    UISaveVideoAtPathToSavedPhotosAlbum(outputPath, self, @selector(video:didFinishSavingWithError: contextInfo:), (__bridge void *)(outputPath));

    [self.navigationController popToRootViewControllerAnimated:YES];
    self.navigationController.navigationBarHidden = NO;

    //[self.navigationController popToRootViewControllerAnimated:YES];
}
-(void)allDone {

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
</code>```

And here is the code for the UIView subclass:

```<code>- (void) writeVideoFrameAtTime:(CMTime)time;
@end

@implementation ScreenCaptureView

@synthesize currentScreen, frameRate, delegate;

- (void) initialize {
    // Initialization code
    self.clearsContextBeforeDrawing = YES;
    self.currentScreen = nil;
    self.frameRate = 10.0f;     //10 frames per seconds
    _recording = false;
    videoWriter = nil;
    videoWriterInput = nil;
    avAdaptor = nil;
    startedAt = nil;
    bitmapData = NULL;
}

- (id) initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self initialize];
    }
    return self;
}

- (id) init {
    self = [super init];
    if (self) {
        [self initialize];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initialize];
    }
    return self;
}

- (CGContextRef) createBitmapContextOfSize:(CGSize) size {
    CGContextRef    context = NULL;
    CGColorSpaceRef colorSpace;
    int             bitmapByteCount;
    int             bitmapBytesPerRow;

    bitmapBytesPerRow   = (size.width * 4);
    bitmapByteCount     = (bitmapBytesPerRow * size.height);
    colorSpace = CGColorSpaceCreateDeviceRGB();
    if (bitmapData != NULL) {
        free(bitmapData);
    }
    bitmapData = malloc( bitmapByteCount );
    if (bitmapData == NULL) {
        fprintf (stderr, "Memory not allocated!");
        return NULL;
    }

    context = CGBitmapContextCreate (bitmapData,
                                     size.width,
                                     size.height,
                                     8,      // bits per component
                                     bitmapBytesPerRow,
                                     colorSpace,
                                     kCGImageAlphaNoneSkipFirst);

    CGContextSetAllowsAntialiasing(context,NO);
    if (context== NULL) {
        free (bitmapData);
        fprintf (stderr, "Context not created!");
        return NULL;
    }
    CGColorSpaceRelease( colorSpace );

    return context;
}

//static int frameCount = 0;            //debugging
- (void) drawRect:(CGRect)rect {
    NSDate* start = [NSDate date];
    CGContextRef context = [self createBitmapContextOfSize:self.frame.size];

    //not sure why this is necessary...image renders upside-down and mirrored
    CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, self.frame.size.height);
    CGContextConcatCTM(context, flipVertical);

    [self.layer renderInContext:context];

    CGImageRef cgImage = CGBitmapContextCreateImage(context);
    UIImage* background = [UIImage imageWithCGImage: cgImage];
    CGImageRelease(cgImage);

    self.currentScreen = background;

    //debugging
    //if (frameCount < 40) {
    //      NSString* filename = [NSString stringWithFormat:@"Documents/frame_%d.png", frameCount];
    //      NSString* pngPath = [NSHomeDirectory() stringByAppendingPathComponent:filename];
    //      [UIImagePNGRepresentation(self.currentScreen) writeToFile: pngPath atomically: YES];
    //      frameCount++;
    //}

    //NOTE:  to record a scrollview while it is scrolling you need to implement your UIScrollViewDelegate such that it calls
    //       'setNeedsDisplay' on the ScreenCaptureView.
    if (_recording) {
        float millisElapsed = [[NSDate date] timeIntervalSinceDate:startedAt] * 1000.0;
        [self writeVideoFrameAtTime:CMTimeMake((int)millisElapsed, 1000)];
    }

    float processingSeconds = [[NSDate date] timeIntervalSinceDate:start];
    float delayRemaining = (1.0 / self.frameRate) - processingSeconds;

    CGContextRelease(context);

    //redraw at the specified framerate
    [self performSelector:@selector(setNeedsDisplay) withObject:nil afterDelay:delayRemaining > 0.0 ? delayRemaining : 0.01];
}

- (void) cleanupWriter {
    [avAdaptor release];
    avAdaptor = nil;

    [videoWriterInput release];
    videoWriterInput = nil;

    [videoWriter release];
    videoWriter = nil;

    [startedAt release];
    startedAt = nil;

    if (bitmapData != NULL) {
        free(bitmapData);
        bitmapData = NULL;
    }
}

- (void)dealloc {
    [self cleanupWriter];
    [super dealloc];
}

- (NSURL*) tempFileURL {
    NSString* outputPath = [[NSString alloc] initWithFormat:@"%@/%@", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0], @"output.mp4"];
    NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:outputPath];
    NSFileManager* fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:outputPath]) {
        NSError* error;
        if ([fileManager removeItemAtPath:outputPath error:&error] == NO) {
            NSLog(@"Could not delete old recording file at path:  %@", outputPath);
        }
    }

    [outputPath release];
    return [outputURL autorelease];
}

-(BOOL) setUpWriter {
    NSError* error = nil;
    videoWriter = [[AVAssetWriter alloc] initWithURL:[self tempFileURL] fileType:AVFileTypeQuickTimeMovie error:&error];
    NSParameterAssert(videoWriter);

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

    NSDictionary* videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                   AVVideoCodecH264, AVVideoCodecKey,
                                   [NSNumber numberWithInt:self.frame.size.width], AVVideoWidthKey,
                                   [NSNumber numberWithInt:self.frame.size.height], AVVideoHeightKey,
                                   videoCompressionProps, AVVideoCompressionPropertiesKey,
                                   nil];

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

    NSParameterAssert(videoWriterInput);
    videoWriterInput.expectsMediaDataInRealTime = YES;
    NSDictionary* bufferAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                      [NSNumber numberWithInt:kCVPixelFormatType_32ARGB], kCVPixelBufferPixelFormatTypeKey, nil];

    avAdaptor = [[AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:videoWriterInput sourcePixelBufferAttributes:bufferAttributes] retain];

    //add input
    [videoWriter addInput:videoWriterInput];
    [videoWriter startWriting];
    [videoWriter startSessionAtSourceTime:CMTimeMake(0, 1000)];

    return YES;
}

- (void) completeRecordingSession {
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

    [videoWriterInput markAsFinished];

    // Wait for the video
    int status = videoWriter.status;
    while (status == AVAssetWriterStatusUnknown) {
        NSLog(@"Waiting...");
        [NSThread sleepForTimeInterval:0.5f];
        status = videoWriter.status;
    }

    @synchronized(self) {
        BOOL success = [videoWriter finishWriting];
        if (!success) {
            NSLog(@"finishWriting returned NO");
        }

        [self cleanupWriter];

        id delegateObj = self.delegate;
        NSString *outputPath = [[NSString alloc] initWithFormat:@"%@/%@", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0], @"output.mp4"];
        NSURL *outputURL = [[NSURL alloc] initFileURLWithPath:outputPath];

        NSLog(@"Completed recording, file is stored at:  %@", outputURL);
        if ([delegateObj respondsToSelector:@selector(recordingFinished:)]) {
            [delegateObj performSelectorOnMainThread:@selector(recordingFinished:) withObject:(success ? outputURL : nil) waitUntilDone:YES];
        }

        [outputPath release];
        [outputURL release];
    }

    [pool drain];
}

- (bool) startRecording {
    bool result = NO;
    @synchronized(self) {
        if (! _recording) {
            result = [self setUpWriter];
            startedAt = [[NSDate date] retain];
            _recording = true;
        }
    }

    return result;
}

- (void) stopRecording {
    @synchronized(self) {
        if (_recording) {
            _recording = false;
            [self completeRecordingSession];
        }
    }
}

-(void) writeVideoFrameAtTime:(CMTime)time {
    if (![videoWriterInput isReadyForMoreMediaData]) {
        NSLog(@"Not ready for video data");
    }
    else {
        @synchronized (self) {
            UIImage* newFrame = [self.currentScreen retain];
            CVPixelBufferRef pixelBuffer = NULL;
            CGImageRef cgImage = CGImageCreateCopy([newFrame CGImage]);
            CFDataRef image = CGDataProviderCopyData(CGImageGetDataProvider(cgImage));

            int status = CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, avAdaptor.pixelBufferPool, &pixelBuffer);
            if(status != 0){
                //could not get a buffer from the pool
                NSLog(@"Error creating pixel buffer:  status=%d", status);
            }
            // set image data into pixel buffer
            CVPixelBufferLockBaseAddress( pixelBuffer, 0 );
            uint8_t* destPixels = CVPixelBufferGetBaseAddress(pixelBuffer);
            CFDataGetBytes(image, CFRangeMake(0, CFDataGetLength(image)), destPixels);  //XXX:  will work if the pixel buffer is contiguous and has the same bytesPerRow as the input data

            if(status == 0){
                BOOL success = [avAdaptor appendPixelBuffer:pixelBuffer withPresentationTime:time];
                if (!success)
                    NSLog(@"Warning:  Unable to write buffer to video");
            }

            //clean up
            [newFrame release];
            CVPixelBufferUnlockBaseAddress( pixelBuffer, 0 );
            CVPixelBufferRelease( pixelBuffer );
            CFRelease(image);
            CGImageRelease(cgImage);
        }

    }

}

@end
</code>```

答:
From what I observed:  The size of self.view does not get resize until

-(void) viewDidAppear:(BOOL)animated

putting your code in ViewWillAppear does not help

You can also do this everytime the orientation changes .:

```<code>     self.view.frame = [[UIScreen mainScreen] bounds];
    _prevLayer.frame = [[UIScreen mainScreen] bounds];
    _prevLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [_prevLayer.connection setVideoOrientation:statusBarOrientation];
</code>```

Body:
In my app I subclass a UIView in order to capture video from the camera that is displayed in the View, along with an UIImage that is overlaid on it.  I have AutoLayout turned on, but the issue is that the View stays the same size of whatever I have listed in the XIB for Simulated Metrics Size.  If I leave simulated Metrics as Inferred or Freeform, it doesn't work on either of them, but if I put it on iPhone 4.7, you see a background behind it on the edges.  Here is the code for the ViewController where the AVCaptureSession happens:

-(void)viewWillAppear:(BOOL)animated {
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MMM d hh:mm:ss a"];
    // display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
    NSString *currentTime = [dateFormatter stringFromDate:today];
    NSError* error4 = nil;
    AVAudioSession* audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryAmbient error:&error4];
    OSStatus propertySetError = 0;
    UInt32 allowMixing = true;
    propertySetError |= AudioSessionSetProperty(kAudioSessionProperty_OtherMixableAudioShouldDuck, sizeof(allowMixing), &allowMixing);

    // Activate the audio session
    error4 = nil;
    if (![audioSession setActive:YES error:&error4]) {
        NSLog(@"AVAudioSession setActive:YES failed: %@", [error4 localizedDescription]);
    }
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [paths objectAtIndex:0];

    self.session = [[AVCaptureSession alloc] init];
    [self.session beginConfiguration];
    self.session.sessionPreset = AVCaptureSessionPreset1280x720;
    self.navigationController.navigationBarHidden = YES;

    NSError *error = nil;

    AVCaptureDevice *audioCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
    NSError *error2 = nil;
    AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioCaptureDevice error:&error2];

    AVCaptureDevice *device;
    AVCaptureDevicePosition desiredPosition = AVCaptureDevicePositionBack;
    // find the front facing camera

    device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    // get the input device
    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];

    AVCaptureMovieFileOutput *movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];

    NSString *archives = [documentsDirectoryPath stringByAppendingPathComponent:@"archives"];
    NSString *editedfilename = [[@"ComeOnDown" lastPathComponent] stringByDeletingPathExtension];
    NSString *datestring = [[editedfilename stringByAppendingString:@" "] stringByAppendingString:currentTime];
    NSLog(@"%@", datestring);
    NSString *outputpathofmovie = [[archives stringByAppendingPathComponent:datestring] stringByAppendingString:@".mp4"];
    NSURL *outputURL = [[NSURL alloc] initFileURLWithPath:outputpathofmovie];
    [self.session addInput:audioInput];
    [self.session addInput:deviceInput];
    [self.session addOutput:movieFileOutput];
    [self.session commitConfiguration];
    [self.session startRunning];

    AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    previewLayer.backgroundColor = [[UIColor blackColor] CGColor];
    previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    previewLayer.connection.videoOrientation = AVCaptureVideoOrientationLandscapeRight;

    CALayer *overlayLayer = [CALayer layer];
    CALayer *overlayLayer2 = [CALayer layer];

    UIImage *overlayImage = [UIImage imageNamed:@"LiveBorder.png"];

    [overlayLayer setContents:(id)[overlayImage CGImage]];
    overlayLayer.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
    [overlayLayer setMasksToBounds:YES];

       CALayer *rootLayer = [self.view layer];
    [rootLayer setMasksToBounds:YES];
    [previewLayer setFrame:[rootLayer bounds]];
    [rootLayer addSublayer:previewLayer];
    [rootLayer addSublayer:overlayLayer];
    [rootLayer addSublayer:label2.layer];
        movieFileOutput.movieFragmentInterval = kCMTimeInvalid;

    [movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self];

    //self.session = nil;
    if (error) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:
                                  [NSString stringWithFormat:@"Failed with error %d", (int)[error code]]
                                                            message:[error localizedDescription]
                                                           delegate:nil
                                                  cancelButtonTitle:@"Dismiss"
                                                  otherButtonTitles:nil];
        [alertView show];

    }
    [super viewWillAppear:YES];
}
-(void)viewWillDisappear:(BOOL)animated {
    self.navigationController.navigationBarHidden = NO;

}

-(void)captureOutput:(AVCaptureFileOutput *)captureOutput didStartRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray *)connections {

}
-(void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    NSLog(@"Finished with error: %@", error);
}
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error {
    //finished
    NSLog(@"Finished");
    NSString *proud = [[NSString alloc] initWithString:[outputFileURL path]];
    UISaveVideoAtPathToSavedPhotosAlbum(proud, self, @selector(video:didFinishSavingWithError: contextInfo:), (__bridge void *)(proud));
}

-(IBAction)goBackNow {
    [myAVPlayer stop];

    [self.session stopRunning];
    // [captureView performSelector:@selector(stopRecording) withObject:nil afterDelay:0.0];

    NSString *outputPath = [[NSString alloc] initWithFormat:@"%@/%@", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0], @"output.mp4"];
    UISaveVideoAtPathToSavedPhotosAlbum(outputPath, self, @selector(video:didFinishSavingWithError: contextInfo:), (__bridge void *)(outputPath));

    [self.navigationController popToRootViewControllerAnimated:YES];
    self.navigationController.navigationBarHidden = NO;

    //[self.navigationController popToRootViewControllerAnimated:YES];
}
-(void)allDone {

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

And here is the code for the UIView subclass:

- (void) writeVideoFrameAtTime:(CMTime)time;
@end

@implementation ScreenCaptureView

@synthesize currentScreen, frameRate, delegate;

- (void) initialize {
    // Initialization code
    self.clearsContextBeforeDrawing = YES;
    self.currentScreen = nil;
    self.frameRate = 10.0f;     //10 frames per seconds
    _recording = false;
    videoWriter = nil;
    videoWriterInput = nil;
    avAdaptor = nil;
    startedAt = nil;
    bitmapData = NULL;
}

- (id) initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self initialize];
    }
    return self;
}

- (id) init {
    self = [super init];
    if (self) {
        [self initialize];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initialize];
    }
    return self;
}

- (CGContextRef) createBitmapContextOfSize:(CGSize) size {
    CGContextRef    context = NULL;
    CGColorSpaceRef colorSpace;
    int             bitmapByteCount;
    int             bitmapBytesPerRow;

    bitmapBytesPerRow   = (size.width * 4);
    bitmapByteCount     = (bitmapBytesPerRow * size.height);
    colorSpace = CGColorSpaceCreateDeviceRGB();
    if (bitmapData != NULL) {
        free(bitmapData);
    }
    bitmapData = malloc( bitmapByteCount );
    if (bitmapData == NULL) {
        fprintf (stderr, "Memory not allocated!");
        return NULL;
    }

    context = CGBitmapContextCreate (bitmapData,
                                     size.width,
                                     size.height,
                                     8,      // bits per component
                                     bitmapBytesPerRow,
                                     colorSpace,
                                     kCGImageAlphaNoneSkipFirst);

    CGContextSetAllowsAntialiasing(context,NO);
    if (context== NULL) {
        free (bitmapData);
        fprintf (stderr, "Context not created!");
        return NULL;
    }
    CGColorSpaceRelease( colorSpace );

    return context;
}

//static int frameCount = 0;            //debugging
- (void) drawRect:(CGRect)rect {
    NSDate* start = [NSDate date];
    CGContextRef context = [self createBitmapContextOfSize:self.frame.size];

    //not sure why this is necessary...image renders upside-down and mirrored
    CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, self.frame.size.height);
    CGContextConcatCTM(context, flipVertical);

    [self.layer renderInContext:context];

    CGImageRef cgImage = CGBitmapContextCreateImage(context);
    UIImage* background = [UIImage imageWithCGImage: cgImage];
    CGImageRelease(cgImage);

    self.currentScreen = background;

    //debugging
    //if (frameCount < 40) {
    //      NSString* filename = [NSString stringWithFormat:@"Documents/frame_%d.png", frameCount];
    //      NSString* pngPath = [NSHomeDirectory() stringByAppendingPathComponent:filename];
    //      [UIImagePNGRepresentation(self.currentScreen) writeToFile: pngPath atomically: YES];
    //      frameCount++;
    //}

    //NOTE:  to record a scrollview while it is scrolling you need to implement your UIScrollViewDelegate such that it calls
    //       'setNeedsDisplay' on the ScreenCaptureView.
    if (_recording) {
        float millisElapsed = [[NSDate date] timeIntervalSinceDate:startedAt] * 1000.0;
        [self writeVideoFrameAtTime:CMTimeMake((int)millisElapsed, 1000)];
    }

    float processingSeconds = [[NSDate date] timeIntervalSinceDate:start];
    float delayRemaining = (1.0 / self.frameRate) - processingSeconds;

    CGContextRelease(context);

    //redraw at the specified framerate
    [self performSelector:@selector(setNeedsDisplay) withObject:nil afterDelay:delayRemaining > 0.0 ? delayRemaining : 0.01];
}

- (void) cleanupWriter {
    [avAdaptor release];
    avAdaptor = nil;

    [videoWriterInput release];
    videoWriterInput = nil;

    [videoWriter release];
    videoWriter = nil;

    [startedAt release];
    startedAt = nil;

    if (bitmapData != NULL) {
        free(bitmapData);
        bitmapData = NULL;
    }
}

- (void)dealloc {
    [self cleanupWriter];
    [super dealloc];
}

- (NSURL*) tempFileURL {
    NSString* outputPath = [[NSString alloc] initWithFormat:@"%@/%@", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0], @"output.mp4"];
    NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:outputPath];
    NSFileManager* fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:outputPath]) {
        NSError* error;
        if ([fileManager removeItemAtPath:outputPath error:&error] == NO) {
            NSLog(@"Could not delete old recording file at path:  %@", outputPath);
        }
    }

    [outputPath release];
    return [outputURL autorelease];
}

-(BOOL) setUpWriter {
    NSError* error = nil;
    videoWriter = [[AVAssetWriter alloc] initWithURL:[self tempFileURL] fileType:AVFileTypeQuickTimeMovie error:&error];
    NSParameterAssert(videoWriter);

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

    NSDictionary* videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                   AVVideoCodecH264, AVVideoCodecKey,
                                   [NSNumber numberWithInt:self.frame.size.width], AVVideoWidthKey,
                                   [NSNumber numberWithInt:self.frame.size.height], AVVideoHeightKey,
                                   videoCompressionProps, AVVideoCompressionPropertiesKey,
                                   nil];

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

    NSParameterAssert(videoWriterInput);
    videoWriterInput.expectsMediaDataInRealTime = YES;
    NSDictionary* bufferAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                      [NSNumber numberWithInt:kCVPixelFormatType_32ARGB], kCVPixelBufferPixelFormatTypeKey, nil];

    avAdaptor = [[AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:videoWriterInput sourcePixelBufferAttributes:bufferAttributes] retain];

    //add input
    [videoWriter addInput:videoWriterInput];
    [videoWriter startWriting];
    [videoWriter startSessionAtSourceTime:CMTimeMake(0, 1000)];

    return YES;
}

- (void) completeRecordingSession {
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

    [videoWriterInput markAsFinished];

    // Wait for the video
    int status = videoWriter.status;
    while (status == AVAssetWriterStatusUnknown) {
        NSLog(@"Waiting...");
        [NSThread sleepForTimeInterval:0.5f];
        status = videoWriter.status;
    }

    @synchronized(self) {
        BOOL success = [videoWriter finishWriting];
        if (!success) {
            NSLog(@"finishWriting returned NO");
        }

        [self cleanupWriter];

        id delegateObj = self.delegate;
        NSString *outputPath = [[NSString alloc] initWithFormat:@"%@/%@", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0], @"output.mp4"];
        NSURL *outputURL = [[NSURL alloc] initFileURLWithPath:outputPath];

        NSLog(@"Completed recording, file is stored at:  %@", outputURL);
        if ([delegateObj respondsToSelector:@selector(recordingFinished:)]) {
            [delegateObj performSelectorOnMainThread:@selector(recordingFinished:) withObject:(success ? outputURL : nil) waitUntilDone:YES];
        }

        [outputPath release];
        [outputURL release];
    }

    [pool drain];
}

- (bool) startRecording {
    bool result = NO;
    @synchronized(self) {
        if (! _recording) {
            result = [self setUpWriter];
            startedAt = [[NSDate date] retain];
            _recording = true;
        }
    }

    return result;
}

- (void) stopRecording {
    @synchronized(self) {
        if (_recording) {
            _recording = false;
            [self completeRecordingSession];
        }
    }
}

-(void) writeVideoFrameAtTime:(CMTime)time {
    if (![videoWriterInput isReadyForMoreMediaData]) {
        NSLog(@"Not ready for video data");
    }
    else {
        @synchronized (self) {
            UIImage* newFrame = [self.currentScreen retain];
            CVPixelBufferRef pixelBuffer = NULL;
            CGImageRef cgImage = CGImageCreateCopy([newFrame CGImage]);
            CFDataRef image = CGDataProviderCopyData(CGImageGetDataProvider(cgImage));

            int status = CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, avAdaptor.pixelBufferPool, &pixelBuffer);
            if(status != 0){
                //could not get a buffer from the pool
                NSLog(@"Error creating pixel buffer:  status=%d", status);
            }
            // set image data into pixel buffer
            CVPixelBufferLockBaseAddress( pixelBuffer, 0 );
            uint8_t* destPixels = CVPixelBufferGetBaseAddress(pixelBuffer);
            CFDataGetBytes(image, CFRangeMake(0, CFDataGetLength(image)), destPixels);  //XXX:  will work if the pixel buffer is contiguous and has the same bytesPerRow as the input data

            if(status == 0){
                BOOL success = [avAdaptor appendPixelBuffer:pixelBuffer withPresentationTime:time];
                if (!success)
                    NSLog(@"Warning:  Unable to write buffer to video");
            }

            //clean up
            [newFrame release];
            CVPixelBufferUnlockBaseAddress( pixelBuffer, 0 );
            CVPixelBufferRelease( pixelBuffer );
            CFRelease(image);
            CGImageRelease(cgImage);
        }

    }

}

@end

Body:
From what I observed:  The size of self.view does not get resize until

-(void) viewDidAppear:(BOOL)animated

putting your code in ViewWillAppear does not help

You can also do this everytime the orientation changes .:

     self.view.frame = [[UIScreen mainScreen] bounds];
    _prevLayer.frame = [[UIScreen mainScreen] bounds];
    _prevLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [_prevLayer.connection setVideoOrientation:statusBarOrientation];


来源: stackexchange

问:
Retrofit. java.net.ProtocolException: expected * bytes but received *
I'm trying to do a Multipart POST request through Retrofit2, where I upload to the API a custom file.

It randomly fails with this Exception:

```<code>W/System.err: java.net.ProtocolException: expected 154 bytes but received 634
</code>```

Does anyone could put some light on it?

This is my code in the interface:

```<code>@Multipart
@POST("recordings/{id}/{rec_id}/")
Call<ResponseBody> uploadRecording(@Path("id") String id, @Path("rec_id") String rec_id, @Part MultipartBody.Part bleFile);
</code>```

In the constructor:

```<code>public ApiConnectionManager(Context con){
    Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
            .create();

    OkHttpClient.Builder client = new OkHttpClient.Builder();
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    client.addInterceptor(loggingInterceptor);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(con.getResources().getString(R.string.api_url)) // API url is hidden
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(client.build())
            .build();

    this.companyAPI = retrofit.create(CompanyAPI.class);
}
</code>```

and in the upload method:

```<code>private void uploadFile(String id, final File bleFile) {
    MediaType MEDIA_TYPE = MediaType.parse("multipart/mixed");
    RequestBody requestBody = RequestBody.create(MEDIA_TYPE,bleFile);
    MultipartBody.Part partFile = MultipartBody.Part.createFormData("file", bleFile.getName(), requestBody);
    String recordingId = bleFile.getName().replace(".BLE","");
    Call<ResponseBody> call = companyAPI.uploadRecording(id, recordingId, partFile);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Log.d(TAG+"-Upload "+bleFile.getName(),response.message());
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.d(TAG,"FAILED");
            t.printStackTrace();
        }
    });
}
</code>```

答:
Here is what I use for all my requests and have no problems at all. Let me know if it does not work for you. I am assuming POST name for your file is "file".

In the protocol:

```<code>@Multipart
@POST
Call<ResponseBody> request(
        @Url String url, // Request URL
        @PartMap Map<String, String> vars, // POST Strings
        @PartMap Map<String, RequestBody> files // POST Files
);
</code>```

Construct a call:

```<code>Map<String, String> vars = new HashMap<>();
Map<String, RequestBody> files = new HashMap<>();

/** Put a string **/

vars.put("name", "value");

/** Put a file **/

String key = String.format(Locale.US, "file\"; filename=\"%s", file.getName());
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
files.put(key, requestBody);

/** Construct the call **/

Call<ResponseBody> call = mProtocol.request(url, vars, files);

call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Log.d("Debug", response.body().string());
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            if (call.isCanceled()) Log.d("Debug", "Call Canceled");
            else Log.d("Debug", "Call Failed: " + t.toString());
        }
});
</code>```

PS: You can use this piece of code to upload multiple files, since it accepts a map of files rather than a single file.

PS#2: Due to several problems I have had with this method, I had to add the below code to make sure it never sends null or empty map.

```<code>if (vars == null) {
    vars = new HashMap<>();
    vars.put("01110011", "01101101"); // put whatever you want
}
if (files == null) files = new HashMap<>();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to do a Multipart POST request through Retrofit2, where I upload to the API a custom file.

It randomly fails with this Exception:

W/System.err: java.net.ProtocolException: expected 154 bytes but received 634

Does anyone could put some light on it?

This is my code in the interface:

@Multipart
@POST("recordings/{id}/{rec_id}/")
Call<ResponseBody> uploadRecording(@Path("id") String id, @Path("rec_id") String rec_id, @Part MultipartBody.Part bleFile);

In the constructor:

public ApiConnectionManager(Context con){
    Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
            .create();

    OkHttpClient.Builder client = new OkHttpClient.Builder();
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    client.addInterceptor(loggingInterceptor);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(con.getResources().getString(R.string.api_url)) // API url is hidden
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(client.build())
            .build();

    this.companyAPI = retrofit.create(CompanyAPI.class);
}

and in the upload method:

private void uploadFile(String id, final File bleFile) {
    MediaType MEDIA_TYPE = MediaType.parse("multipart/mixed");
    RequestBody requestBody = RequestBody.create(MEDIA_TYPE,bleFile);
    MultipartBody.Part partFile = MultipartBody.Part.createFormData("file", bleFile.getName(), requestBody);
    String recordingId = bleFile.getName().replace(".BLE","");
    Call<ResponseBody> call = companyAPI.uploadRecording(id, recordingId, partFile);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Log.d(TAG+"-Upload "+bleFile.getName(),response.message());
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.d(TAG,"FAILED");
            t.printStackTrace();
        }
    });
}

Body:
Here is what I use for all my requests and have no problems at all. Let me know if it does not work for you. I am assuming POST name for your file is "file".

In the protocol:

@Multipart
@POST
Call<ResponseBody> request(
        @Url String url, // Request URL
        @PartMap Map<String, String> vars, // POST Strings
        @PartMap Map<String, RequestBody> files // POST Files
);

Construct a call:

Map<String, String> vars = new HashMap<>();
Map<String, RequestBody> files = new HashMap<>();

/** Put a string **/

vars.put("name", "value");

/** Put a file **/

String key = String.format(Locale.US, "file\"; filename=\"%s", file.getName());
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
files.put(key, requestBody);

/** Construct the call **/

Call<ResponseBody> call = mProtocol.request(url, vars, files);

call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Log.d("Debug", response.body().string());
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            if (call.isCanceled()) Log.d("Debug", "Call Canceled");
            else Log.d("Debug", "Call Failed: " + t.toString());
        }
});

PS: You can use this piece of code to upload multiple files, since it accepts a map of files rather than a single file.

PS#2: Due to several problems I have had with this method, I had to add the below code to make sure it never sends null or empty map.

if (vars == null) {
    vars = new HashMap<>();
    vars.put("01110011", "01101101"); // put whatever you want
}
if (files == null) files = new HashMap<>();


问:
How to display model name (basically LabelFor's inner text)?
I'd like to have the functionality of printing out a model's member name/display name. This is akin to using HtmlHelper<TModel>.LabelFor but having the text not wrapped in a label. Is there an extension method already built into MVC for this exact purpose? I couldn't find one so I looked at what LabelFor does with Reflector and made a LabelTextFor method:

```<code>public static string LabelTextFor<TModel, TValue>(this HtmlHelper<TModel> source, Expression<Func<TModel, TValue>> expression)
{
    var memberName = ExpressionHelper.GetExpressionText((LambdaExpression)expression);

    var metadata = ModelMetadata.FromLambdaExpression(expression, new ViewDataDictionary<TModel>());

    return metadata.DisplayName ?? metadata.PropertyName ?? memberName.Split('.').Last();
}
</code>```

I'm thinking I should maybe change the name as well of this method. Thoughts are appreciated.

答: I've decided to use the method that I've created.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'd like to have the functionality of printing out a model's member name/display name. This is akin to using HtmlHelper<TModel>.LabelFor but having the text not wrapped in a label. Is there an extension method already built into MVC for this exact purpose? I couldn't find one so I looked at what LabelFor does with Reflector and made a LabelTextFor method:

public static string LabelTextFor<TModel, TValue>(this HtmlHelper<TModel> source, Expression<Func<TModel, TValue>> expression)
{
    var memberName = ExpressionHelper.GetExpressionText((LambdaExpression)expression);

    var metadata = ModelMetadata.FromLambdaExpression(expression, new ViewDataDictionary<TModel>());

    return metadata.DisplayName ?? metadata.PropertyName ?? memberName.Split('.').Last();
}

I'm thinking I should maybe change the name as well of this method. Thoughts are appreciated.


问:
DataTables warning: table id=StudentTable - Requested unknown parameter '0' for row 0, column 0
I am getting JSON object successfully form the server. But when I use to show the data with jQuery DataTables, it shows this alert:

DataTables warning: table id=StudentTable - Requested unknown parameter '0' for row 0, column 0

When I click OK then it shows the rows without data. How can I resolve this issue?

Here is the code

@section scripts{

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <table id="StudentTable" class="table">
        <thead>
            <tr>
                <th>Student Name</th>
                <th>Reg No</th>
                <th>Department</th>
                <th>Email</th>
                <th>Date</th>
                <th>Seasson</th>
                <th>Address</th>
                <th>Contact No</th>
                <th></th>
            </tr>
        </thead>
        <tbody></tbody>
    </table></code>```

答:
The error means that DataTables is unable to obtain data for a cell.

You have misspelled option name, it should be columns, not column.

There are many other reasons for this error, possible solutions are explained in this technical note.

Body:
I am getting JSON object successfully form the server. But when I use to show the data with jQuery DataTables, it shows this alert:

DataTables warning: table id=StudentTable - Requested unknown parameter '0' for row 0, column 0

When I click OK then it shows the rows without data. How can I resolve this issue?

Here is the code

@section scripts{

}

                Student Name
                Reg No
                Department
                Email
                Date
                Seasson
                Address
                Contact No


问:
changing text in html with php without affecting html tags
i've edited a simple php function to convert the letters to the homograph with similar look.

my code :

```<code>function homographit($string){

$alphabet = array("A", "B", "C", "E", "H", "J", "K", "M", "N", "O", "P", "S", "T", "X", "Y",
"a", "b", "c", "e", "i", "j", "k", "o", "p", "r", "s", "v", "x", "y");
$Greec   = array("\u0391", "\u0392", "\u0421", "\u0395", "\u0397", "\u0408", "\u039A", "\u039C", "\u039D", "\u039F", "\u03A1", "\u0405",
"\u03A4", "\u03A7", "\u03A5", "\u0430", "\u042C", "\u0441", "\u0435", "\u0456", "\u0458", "\u03BA", "\u03BF", "\u03C1", "\u0433", "\u0455",
"\u03BD", "\u03C7", "\u0443");

$newstring = str_replace($alphabet, $Greec, $string);
return json_decode('"'.$newstring.'"', true);
}
</code>```

for a text string the function work as perfect.

My question:

How to apply this homgraphit() to all text in html string withouwt affecting html TAGS?
thx

答:
i've solved my probblem with the </p>

```<code>preg_replace_callback()
</code>```

Body:
i've edited a simple php function to convert the letters to the homograph with similar look.

my code :

function homographit($string){

$alphabet = array("A", "B", "C", "E", "H", "J", "K", "M", "N", "O", "P", "S", "T", "X", "Y",
"a", "b", "c", "e", "i", "j", "k", "o", "p", "r", "s", "v", "x", "y");
$Greec   = array("\u0391", "\u0392", "\u0421", "\u0395", "\u0397", "\u0408", "\u039A", "\u039C", "\u039D", "\u039F", "\u03A1", "\u0405",
"\u03A4", "\u03A7", "\u03A5", "\u0430", "\u042C", "\u0441", "\u0435", "\u0456", "\u0458", "\u03BA", "\u03BF", "\u03C1", "\u0433", "\u0455",
"\u03BD", "\u03C7", "\u0443");

$newstring = str_replace($alphabet, $Greec, $string);
return json_decode('"'.$newstring.'"', true);
}

for a text string the function work as perfect.

My question:

How to apply this homgraphit() to all text in html string withouwt affecting html TAGS?
thx

Body:
i've solved my probblem with the

preg_replace_callback()


问:
How to add already created .a file while creating .a file
can anyone tell how can I include already existing .a file while creating .a with this?

```<code>ar rcs libcrypt.a
</code>```

I need to add libssl.a and libcrypto.a files together into a libcrypt.a file. Can you help me to solve this?

答:
man ar tells you how to extract
all the members from an archive, and it tells you how to insert members
into an archive.

So extract all the members from libssl.a and libcrypto.a
and insert them all into libcrypt.a, taking care to do the extracting
in an empty directory.

```<code>$ mkdir scrap
$ cd scrap
$ ar -x ../libssl.a
$ ar -x ../libcrypto.a
$ ar rcs ../libcrypt.a *
$ cd ..
$ rm -r scrap/
</code>```

Body:
can anyone tell how can I include already existing .a file while creating .a with this?

ar rcs libcrypt.a

I need to add libssl.a and libcrypto.a files together into a libcrypt.a file. Can you help me to solve this?

Body:
man ar tells you how to extract
all the members from an archive, and it tells you how to insert members
into an archive.

So extract all the members from libssl.a and libcrypto.a
and insert them all into libcrypt.a, taking care to do the extracting
in an empty directory.

$ mkdir scrap
$ cd scrap
$ ar -x ../libssl.a
$ ar -x ../libcrypto.a
$ ar rcs ../libcrypt.a *
$ cd ..
$ rm -r scrap/


问:
django how to change account info using UserChangeForm
I'm making a website using django. I was learning 'How to Let superusers Change Account Info Using Forms' by youtube. But, I have a problem to go edit page.

member_management.html in management app

```<code>      {% for staff in staff_list %}
        <tr>
            <td><a href="{% url "management:edit_staff" staff.id %}">{{ staff }}</a></td>
            <td>{{ staff.birth }}</td>
            <td>{{ staff.groups.all.0 }}</td>
        </tr>
        {% endfor %}
</code>```

If I click the {{staff}}, the page url changes 'management/member_management' to 'management/member_management/edit_staff/1' ( 1 is the staff id ). But page doesn't go to edit_staff page, rather redirect memeber_management page(this page).

my urls.py in management app

```<code>  from django.conf.urls import url, include
  from management import views

   urlpatterns = [
url(r'^member_management/', views.member_management, name='member_management'),
url(r'^member_management/edit_staff/(?P<staff_id>\d+)', views.edit_staff, name="edit_staff"),
 ]
</code>```

my views.py in management app

```<code>from django.conf import settings
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserChangeForm
from authentication.models import User
from staff.models import Member

def member_management(request):
    staff_list = User.objects.all()
    member_list = Member.objects.all()
    context = {
        'staff_list':staff_list,
        'member_list' : member_list,
    }
    return render(request, 'management/member_management.html', context)

def edit_staff(request, staff_id):
    staff = User.objects.get(id=staff_id)
    print("sdf")

    if request.method == 'POST':
        form = UserChangeForm(request.POST, instance=staff)

        if form.is_valid():
            form.save()
            return redirect('member_management')
    else:
        staff = User.objects.get(id=staff_id)
        form = UserChangeForm(instance=staff)

    context = {
        'form' : form,
    }
    return render(request, 'management/edit_staff.html', context)
</code>```

What's the problem?? Any error doesn't come in my CMD, maybe some route I miss..
Any help will be very helpful to me, thanks!

答:
You can fix this, just put the $ (end-of-string match character) at the end of the first url.

```<code>urlpatterns = [
    url(r'^member_management/$', views.member_management,
      name='member_management'),
    url(r'^member_management/edit_staff/(?P<staff_id>\d+)',
      views.edit_staff, name="edit_staff"),
]
</code>```

Note that the regular expressions in this example don’t have a $
  (end-of-string match character) but do include a trailing slash.
  Whenever Django encounters include() (django.conf.urls.include()), it
  chops off whatever part of the URL matched up to that point and sends
  the remaining string to the included URLconf for further processing.

If you doens't put the $, you may experience unexpected results, something like:

management/member_management/edit_staff/1/foo/bar/baz will match, and will call views.edit_staff

To avoid this, you should include the $ on the edit_staff url too.

```<code>url(r'^member_management/edit_staff/(?P<staff_id>\d+)$',
      views.edit_staff, name="edit_staff"),
</code>```

Body:
I'm making a website using django. I was learning 'How to Let superusers Change Account Info Using Forms' by youtube. But, I have a problem to go edit page.

member_management.html in management app

      {% for staff in staff_list %}

            {{ staff }}
            {{ staff.birth }}
            {{ staff.groups.all.0 }}

        {% endfor %}

If I click the {{staff}}, the page url changes 'management/member_management' to 'management/member_management/edit_staff/1' ( 1 is the staff id ). But page doesn't go to edit_staff page, rather redirect memeber_management page(this page).

my urls.py in management app

  from django.conf.urls import url, include
  from management import views

   urlpatterns = [
url(r'^member_management/', views.member_management, name='member_management'),
url(r'^member_management/edit_staff/(?P<staff_id>\d+)', views.edit_staff, name="edit_staff"),
 ]

my views.py in management app

from django.conf import settings
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserChangeForm
from authentication.models import User
from staff.models import Member

def member_management(request):
    staff_list = User.objects.all()
    member_list = Member.objects.all()
    context = {
        'staff_list':staff_list,
        'member_list' : member_list,
    }
    return render(request, 'management/member_management.html', context)

def edit_staff(request, staff_id):
    staff = User.objects.get(id=staff_id)
    print("sdf")

    if request.method == 'POST':
        form = UserChangeForm(request.POST, instance=staff)

        if form.is_valid():
            form.save()
            return redirect('member_management')
    else:
        staff = User.objects.get(id=staff_id)
        form = UserChangeForm(instance=staff)

    context = {
        'form' : form,
    }
    return render(request, 'management/edit_staff.html', context)

What's the problem?? Any error doesn't come in my CMD, maybe some route I miss..
Any help will be very helpful to me, thanks!

Body:
You can fix this, just put the $ (end-of-string match character) at the end of the first url.

urlpatterns = [
    url(r'^member_management/$', views.member_management,
      name='member_management'),
    url(r'^member_management/edit_staff/(?P<staff_id>\d+)',
      views.edit_staff, name="edit_staff"),
]

Note that the regular expressions in this example don’t have a $
  (end-of-string match character) but do include a trailing slash.
  Whenever Django encounters include() (django.conf.urls.include()), it
  chops off whatever part of the URL matched up to that point and sends
  the remaining string to the included URLconf for further processing.

If you doens't put the $, you may experience unexpected results, something like:

management/member_management/edit_staff/1/foo/bar/baz will match, and will call views.edit_staff

To avoid this, you should include the $ on the edit_staff url too.

url(r'^member_management/edit_staff/(?P<staff_id>\d+)$',
      views.edit_staff, name="edit_staff"),


问:
How does React know the component is removed from the DOM?
Under Adding Lifecycle Methods to a Class in the official Facebook docs for React, it's mentioned:

5) If the Clock component is ever removed from the DOM, React calls the componentWillUnmount() lifecycle hook so the timer is stopped.

Just trying to understand how? I get that React knows when it's about to insert the component in the DOM, so it can callcomponentDidMount life cycle hook then.

But for componentWillUnmount it just says "ever removed from the DOM". Seems to suggest it's the real DOM not React DOM. One might as well remove the component with javaScript/jQuery and componentWillUnmount should fire.

How exactly does React know the component has been removed from the real DOM? Could there be a watcher?

Thanks

答:
There is no watcher on the actual DOM.
Everytime the render function of a component gets called, the Virtual DOM gets re-build. If a component is no longer necessary, it gets removed from the virtual DOM.

A diffing algorithm identifies those parts of the actual DOM that need to be changed for the actual DOM to be a reflection of the virtual DOM: some components will have to be added to the actual DOM (= called mounting), other components will have to be removed (= unmounting). This whole process is called reconciliation.

It is because of this reconciliation process, that React knows which components are to be removed from the actual DOM. Right before the component is removed, React calls the componentWillUnmount() lifecycle hook.

If another script (Javascript or jQuery) causes the removal of a certain component from the actual DOM, React will never notice it and therefore will not call the componentWillUnmount() lifecycle hook.


问:
is matlab's xmlread using too much memory?
I am running into a memory problem when trying to read in large (not huge!) xml files. Estimating Java memory usage is tricky, but it seems that

dom=xmlread('somefile.xml');

takes way more memory than it ought to. I know how to set the default available Java memory in the preferences, but I am already up to 512MB and not even my full "resolution" xmls yet. And memory usage definitely does not scale well with file size.

If it will help I could provide a link to a ~5MB xml file that takes ~60MB of Java memory with xmlread.

Any ideas? Thanks in advance,
-n

答:
You could try the XML IO Tools from the file exchange as an alternative way of reading your file.

Also take a look at the Mathworks doc on Resolving "out of memory" errors.


问:
Google realtime multiplayer automatch won't work for more then 1 opponent.
I ran into a strange problem. In my multiplayer game user decides how many opponents they want to play with(up to 3), and after they've decided I create an autoMatchCriteria like this-

```<code>Bundle am = RoomConfig.createAutoMatchCriteria(opponentCount, opponentCount, 0);
</code>```

And create a room-

```<code>// build the room config:
        RoomConfig.Builder roomConfigBuilder = makeBasicRoomConfigBuilder();
        roomConfigBuilder.setAutoMatchCriteria(am);
        RoomConfig roomConfig = roomConfigBuilder.build();

        // create room:
        Games.RealTimeMultiplayer.create(((MainActivity) getActivity()).getGoogleApiClient(), roomConfig);
</code>```

This triggers RoomUpdateListener's onJoinedRoom() or onRoomCreated() accordingly. And while the user waits in a waitingRoom they gets room status updates in RoomStatusUpdateListener's onPeersConnected() when a peer gets connected and after minimum required players are connected the game play can be started.

But when user selects more then one opponents, onPeersConnected() only gets called once if at all and the connected player keeps waiting indefinitely until they leave the room.

I tried it with google's waiting room ui and strange enough it worked with it for every opponent count.

So if anyone can point me to what am I doing wrong, would be a great help. Thank you.

答: Based from this thread, if you set min to 1 and max to 3, you might be getting a 2 player game. To have players up to 3, set MIN_OPPONENTS and MAX_OPPONENTS to 3, and handle the game start logic from your code. If the logic gets more complicated, it might make sense to elect a "server". You can do that, for example, by saying that the client with the lowest Participant ID (lexicographically) is the server. Saying "whoever created the game is the server" is no good, because when automatching, everyone thinks they created the game. Hope this helps!

Body:
I ran into a strange problem. In my multiplayer game user decides how many opponents they want to play with(up to 3), and after they've decided I create an autoMatchCriteria like this-

Bundle am = RoomConfig.createAutoMatchCriteria(opponentCount, opponentCount, 0);

And create a room-

// build the room config:
        RoomConfig.Builder roomConfigBuilder = makeBasicRoomConfigBuilder();
        roomConfigBuilder.setAutoMatchCriteria(am);
        RoomConfig roomConfig = roomConfigBuilder.build();

        // create room:
        Games.RealTimeMultiplayer.create(((MainActivity) getActivity()).getGoogleApiClient(), roomConfig);

This triggers RoomUpdateListener's onJoinedRoom() or onRoomCreated() accordingly. And while the user waits in a waitingRoom they gets room status updates in RoomStatusUpdateListener's onPeersConnected() when a peer gets connected and after minimum required players are connected the game play can be started.

But when user selects more then one opponents, onPeersConnected() only gets called once if at all and the connected player keeps waiting indefinitely until they leave the room.

I tried it with google's waiting room ui and strange enough it worked with it for every opponent count.

So if anyone can point me to what am I doing wrong, would be a great help. Thank you.


问:
CORS work correctly on sharing host but not in localhost
I try to build a simple api base app with Laravel (as backend) and angularjs (as frontend).
In the beginning, I faced this error:

XMLHttpRequest cannot load http://127.0.0.1:8000/api/myroute. Response
  to preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost' is therefore not allowed access.

http://127.0.0.1:8000/api/myroute is my route to get some data, defined in Laravel as POST route.

That's while I've added the CORS middleware on my routes (according this sample) in this way:
Cors Middleware:

```<code>public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'x-requested-with, Content-Type, origin, authorization, accept, client-security-token');
    }
</code>```

and the below code is my $http code that I send request in Angularjs:

```<code>$http({
    method: 'POST',
    url: 'http://127.0.0.1:8000/api/myroute',
    headers: {
        'Content-Type': 'application/json'
    }
}).then(function (response) {
    console.log(response);
}, function (reject) {
    console.log(reject);
});
</code>```

I should to add this point that when I upload my project on a host, this Cors works Ok!
My problem is just http://localhost.

I also tried this in Firefox but the result was same, just Firefox not shown the Cross Origin Error and it's the only difference.

In this time I could not develop my project on host and I need to work locally.
So I need help!

答:
Try to add below codes as header to your laravel's index.php file:

```<code>header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization');
</code>```

but be careful about cross origion!

Body:
I try to build a simple api base app with Laravel (as backend) and angularjs (as frontend).
In the beginning, I faced this error:

XMLHttpRequest cannot load http://127.0.0.1:8000/api/myroute. Response
  to preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost' is therefore not allowed access.

http://127.0.0.1:8000/api/myroute is my route to get some data, defined in Laravel as POST route.

That's while I've added the CORS middleware on my routes (according this sample) in this way:
Cors Middleware:

public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'x-requested-with, Content-Type, origin, authorization, accept, client-security-token');
    }

and the below code is my $http code that I send request in Angularjs:

$http({
    method: 'POST',
    url: 'http://127.0.0.1:8000/api/myroute',
    headers: {
        'Content-Type': 'application/json'
    }
}).then(function (response) {
    console.log(response);
}, function (reject) {
    console.log(reject);
});

I should to add this point that when I upload my project on a host, this Cors works Ok!
My problem is just http://localhost.

I also tried this in Firefox but the result was same, just Firefox not shown the Cross Origin Error and it's the only difference.

In this time I could not develop my project on host and I need to work locally.
So I need help!

Body:
Try to add below codes as header to your laravel's index.php file:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization');

but be careful about cross origion!


问:
MySQL/PHP - page number pagination Only show 10 pages at times
I am having difficulties with my MYSQL / PHP dashboard. - Currently i am having 50 pages, but currently they are all showing on the same page.

http://imgur.com/wDfTWUa - as you can see in the attached file. - I only want 10 pages to be shown, and be able to click through the rest of the pages without seeing 4 rows of pages.

Exsampel <- 2 3 4 5 6 7 8 9 10 ->  when you are on ?page=1, if you are on page ?page=10 <- 11 12 13 14 15 16 17 18 19->

Hope you can help me.

Code:

```<code><?php

include 'config.php';

$sidenr = $_GET['page'];

$sidenr2 = ($sidenr -1) * 10;

echo $sidenr2;
echo "<br><br>";

$query100 = mysqli_query($conn, "SELECT * FROM `test` LIMIT $sidenr2,10") or die(mysqli_error($conn));
while($row = mysqli_fetch_array($query100))
    {
        echo $row['id']."<br>";
    }

    $result = mysqli_query($conn, "SELECT * FROM test");
    $num_rows = mysqli_num_rows($result);

    $sideantal = $num_rows / 10;

    echo "Der skal være antal sider: ". $sideantal;

    echo "<br><br>antal rækker ". $num_rows . "<br><br>";

    ?>
    <br><br>
    <?php

    for ($number = 1; $number <= $sideantal; $number++) {
    echo "<li><a href=\"test.php?page=".$number."\" >". $number. "</a></li>";
    }
    ?>
</code>```

答:
try to change this:

```<code>for ($number = 1; $number <= $sideantal; $number++) {
    echo "<li><a href=\"test.php?page=".$number."\" >". $number. "</a>
    </li>";
}
</code>```

to this:

```<code>for ($number = 1; $number <= $sideantal; $number++) {
    if (($number > $_GET['page']) && ($number <= $_GET['page'] + 10)) {
        echo "<li><a href=\"test.php?page=".$number."\" >". $number. "</a>
        </li>";
    }
}
</code>```

Body:
I am having difficulties with my MYSQL / PHP dashboard. - Currently i am having 50 pages, but currently they are all showing on the same page.

http://imgur.com/wDfTWUa - as you can see in the attached file. - I only want 10 pages to be shown, and be able to click through the rest of the pages without seeing 4 rows of pages.

Exsampel <- 2 3 4 5 6 7 8 9 10 ->  when you are on ?page=1, if you are on page ?page=10 <- 11 12 13 14 15 16 17 18 19->

Hope you can help me.

Code:

<?php

include 'config.php';

$sidenr = $_GET['page'];

$sidenr2 = ($sidenr -1) * 10;

echo $sidenr2;
echo "

";

$query100 = mysqli_query($conn, "SELECT * FROM `test` LIMIT $sidenr2,10") or die(mysqli_error($conn));
while($row = mysqli_fetch_array($query100))
    {
        echo $row['id']."
";
    }

    $result = mysqli_query($conn, "SELECT * FROM test");
    $num_rows = mysqli_num_rows($result);

    $sideantal = $num_rows / 10;

    echo "Der skal være antal sider: ". $sideantal;

    echo "

antal rækker ". $num_rows . "

";

    ?>

    <?php

    for ($number = 1; $number <= $sideantal; $number++) {
    echo "
". $number. "
";
    }
    ?>

Body:
try to change this:

for ($number = 1; $number <= $sideantal; $number++) {
    echo "<li><a href=\"test.php?page=".$number."\" >". $number. "</a>
    </li>";
}

to this:

for ($number = 1; $number <= $sideantal; $number++) {
    if (($number > $_GET['page']) && ($number <= $_GET['page'] + 10)) {
        echo "<li><a href=\"test.php?page=".$number."\" >". $number. "</a>
        </li>";
    }
}


问:
Trouble understanding meaning of "driver" in nodejs

I am having trouble trying to understand what is meant by a MongoDB driver for nodejs. Is driver another way to say a module or a library?

答:
At the end of the day- yes.
The term comes from os drivers which allow the os to communicate with different hardware. </p>

<p>The mongo driver for node allows node to communicate with an external entity (mongo in this case) using js api inside the node application. </p>

Body:
At the end of the day- yes.
The term comes from os drivers which allow the os to communicate with different hardware.

The mongo driver for node allows node to communicate with an external entity (mongo in this case) using js api inside the node application.


问:
Should defined numbers be stored in a table within the database?
Imagine you have a table - lets contrive an example where this is Orders - which has a field named type, which may be only one of a few fixed values (lets say 0 or 1, for Quotation and Order).

Should all the possible values of type be represented by another table in the database (with just typeID and typeName columns?), and Orders made to reference the new table?

Or is it normal to leave these numbers as-is and have them documented outside the database?

If this is a "it depends" situation: What are the important implications of both options?

I have used the first option in a recent University assignement, but without really thinking about why - and looking back at the design now I'm wondering whether this is important.

I never once queried the reference table as part of my application - because I didn't "need" to - does this indicate the reference table is unneeded, or is this a flaw in my application because it should be checking the ref table (what for?)?

答: My five cents are for lookup tables, as (except for what others say) you can automatically generate enums over these tables in the code, thus keeping your front-end code in sync with database.</p>


问:
Android app is not running on android studio and going to force close
i am new at android app development. i made a simple app in which text changes whenever button is clicked but whenever i run it the app going to force close. kindly help .

Following is my XML

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.progneers.www.app.MainActivity">

<TextView
    android:text="@string/txtString"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="41dp"
    android:id="@+id/myTextView"
    android:textAppearance="@style/TextAppearance.AppCompat" />

<Button
    android:text="@string/click_me"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/myTextView"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="100dp"
    android:id="@+id/myButton" />
</RelativeLayout>
</code>```

Following is my Java Code

```<code>package com.progneers.www.app;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView myTextView = (TextView) findViewById(R.id.myTextView);
    private Button myButton = (Button) findViewById(R.id.myButton);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myButton.setOnClickListener(
                new Button.OnClickListener(){
                    public void onClick(View v){
                        myTextView.setText("Button Clicked! Thank You!");
                    }
                }
        );
    }
  }
</code>```

Error shows after app closed

答:
You have to assign the views in the onCreate, try this</p>

```<code>public class MainActivity extends AppCompatActivity {

private TextView myTextView;
private Button myButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myTextView = (TextView) findViewById(R.id.myTextView);
    myButton = (Button) findViewById(R.id.myButton);
    myButton.setOnClickListener(
            new Button.OnClickListener(){
                public void onClick(View v){
                    myTextView.setText("Button Clicked! Thank You!");
                }
            }
    );
}
}
</code>```

Body:
i am new at android app development. i made a simple app in which text changes whenever button is clicked but whenever i run it the app going to force close. kindly help .

Following is my XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.progneers.www.app.MainActivity">

<TextView
    android:text="@string/txtString"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="41dp"
    android:id="@+id/myTextView"
    android:textAppearance="@style/TextAppearance.AppCompat" />

<Button
    android:text="@string/click_me"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/myTextView"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="100dp"
    android:id="@+id/myButton" />
</RelativeLayout>

Following is my Java Code

package com.progneers.www.app;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView myTextView = (TextView) findViewById(R.id.myTextView);
    private Button myButton = (Button) findViewById(R.id.myButton);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myButton.setOnClickListener(
                new Button.OnClickListener(){
                    public void onClick(View v){
                        myTextView.setText("Button Clicked! Thank You!");
                    }
                }
        );
    }
  }

Error shows after app closed

Body:
You have to assign the views in the onCreate, try this

public class MainActivity extends AppCompatActivity {

private TextView myTextView;
private Button myButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myTextView = (TextView) findViewById(R.id.myTextView);
    myButton = (Button) findViewById(R.id.myButton);
    myButton.setOnClickListener(
            new Button.OnClickListener(){
                public void onClick(View v){
                    myTextView.setText("Button Clicked! Thank You!");
                }
            }
    );
}
}


问:
Why does dropwhile and takewhile skip the last a?
Why does dropwhile and takewhile skip the last a in the following exmaple?

```<code>>>> import itertools
>>> s = "Aardvark"
>>> def vowel(c):
...     return c.lower() in "aeiou"
...
>>> list(itertools.dropwhile(vowel, s))
['r', 'd', 'v', 'a', 'r', 'k']
>>> list(itertools.takewhile(vowel, s))
['A', 'a']
</code>```

Before test in console, I think the result should be ['r', 'd', 'v', 'r', 'k'] and ['A', 'a', 'a'].

The documentation said the roughly implementation of dropwhile and takewhile as follows:

```<code>def dropwhile(predicate, iterable):
# dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
iterable = iter(iterable)
for x in iterable:
    if not predicate(x):
        yield x
        break
for x in iterable:
    yield x

def takewhile(predicate, iterable):
    # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
    for x in iterable:
        if predicate(x):
            yield x
        else:
            break
</code>```

答:
You are not filtering the string, you are dropping or taking as a certain condition is maintained.

The drop-while would stop dropping when reaching "r" which is not a vowel, and take the rest, and the take-while would stop taking when reaching "r" which is not a vowel, and drop the rest.

The behavior you are describing as desired can be gained with filter:

```<code>>>> list(filter(lambda x: x.lower() in 'aeoui', "Aardvark"))
['A', 'a', 'a']
>>> list(filter(lambda x: x.lower() not in 'aeoui', "Aardvark"))
['r', 'd', 'v', 'r', 'k']
</code>```

Body:
Why does dropwhile and takewhile skip the last a in the following exmaple?

>>> import itertools
>>> s = "Aardvark"
>>> def vowel(c):
...     return c.lower() in "aeiou"
...
>>> list(itertools.dropwhile(vowel, s))
['r', 'd', 'v', 'a', 'r', 'k']
>>> list(itertools.takewhile(vowel, s))
['A', 'a']

Before test in console, I think the result should be ['r', 'd', 'v', 'r', 'k'] and ['A', 'a', 'a'].

The documentation said the roughly implementation of dropwhile and takewhile as follows:

def dropwhile(predicate, iterable):
# dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
iterable = iter(iterable)
for x in iterable:
    if not predicate(x):
        yield x
        break
for x in iterable:
    yield x

def takewhile(predicate, iterable):
    # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
    for x in iterable:
        if predicate(x):
            yield x
        else:
            break

Body:
You are not filtering the string, you are dropping or taking as a certain condition is maintained.

The drop-while would stop dropping when reaching "r" which is not a vowel, and take the rest, and the take-while would stop taking when reaching "r" which is not a vowel, and drop the rest.

The behavior you are describing as desired can be gained with filter:

>>> list(filter(lambda x: x.lower() in 'aeoui', "Aardvark"))
['A', 'a', 'a']
>>> list(filter(lambda x: x.lower() not in 'aeoui', "Aardvark"))
['r', 'd', 'v', 'r', 'k']


问:
Shouldn't NRVO guarantee the local named variable and the call-site variable to take the same address?
I think it should, because it's important for correctness. However, I'm surprised to see Clang's output. Consider the code below:

```<code>#include <iostream>

struct S
{
    int i;

    S(int i) : i(i) {}

    S(S&&)
    {
        std::cout << "S(S&&)\n";
    }

    S(S const&) = delete;
};

S f()
{
    S s{42};
    std::cout << &s << "\n";
    return s;
}

int main()
{
    S s{f()};
    std::cout << &s << "\n";
    std::cout << s.i << "\n";
}
</code>```

We defined a move ctor for S to check if S(S&&) is called, if not, NRVO is applied.

The result we see from GCC is:

```<code>0x7ffc3ed7b5ac
0x7ffc3ed7b5ac
42
</code>```

NRVO is applied and they take the same address, which is expected.

However, Clang's output:

```<code>0x7fff908bbcc8
0x7fff908bbcf8
42
</code>```

NRVO is applied but the addresses differ.

In case you wonder why having the same address is important - it's because some object may do some registration with its address at construction, and if the object is moved, it should be notified (e.g. via move-ctor).

Having NRVO applied but with different memory address thus makes it ill-formed.
It's a clear violation of the contract - no custom move/copy ctor is called, how could the compiler "copy" the data of S to a different place?

Is this a bug in Clang?

If we add a destructor to S, e.g.

```<code>~S() {}
</code>```

This time, Clang outputs the same address.

答:
Definitely seems to be a bug in clang, they should be the same, else things like the following will be erroneous

```<code>struct S
{
    int i;
    int* ptr;

    S(int i) : i(i) {
        this->ptr = &this->i;
    }

    S(S&& s)
    {
        this->i = s.i;
        this->ptr = &this->i;
        std::cout << "S(S&&)\n";
    }

    S(S const&) = delete;
};
</code>```

Where a move (or elision where addresses don't change) is required to ensure that the internal pointer points to the correct integer.  But because of elision that pointer points to memory that does not contain the member integer.

See output here https://wandbox.org/permlink/NgNR0mupCfnnmlhK

As pointed out by @T.C., this is actually a bug in the Itanium ABI spec that doesn't take move-ctor into account. Quoting from Clang's dev:

Clang's rule is the one in the ABI: a class is passed indirectly if it
  has a non-trivial destructor or a non-trivial copy constructor. This
  rule definitely needs some adjustment [...]

Indeed, if we define either a non-trivial dtor or copy-ctor for S in the original example, we get the expected result (i.e. same address).

Body:
I think it should, because it's important for correctness. However, I'm surprised to see Clang's output. Consider the code below:

#include <iostream>

struct S
{
    int i;

    S(int i) : i(i) {}

    S(S&&)
    {
        std::cout << "S(S&&)\n";
    }

    S(S const&) = delete;
};

S f()
{
    S s{42};
    std::cout << &s << "\n";
    return s;
}

int main()
{
    S s{f()};
    std::cout << &s << "\n";
    std::cout << s.i << "\n";
}

We defined a move ctor for S to check if S(S&&) is called, if not, NRVO is applied.

The result we see from GCC is:

0x7ffc3ed7b5ac
0x7ffc3ed7b5ac
42

NRVO is applied and they take the same address, which is expected.

However, Clang's output:

0x7fff908bbcc8
0x7fff908bbcf8
42

NRVO is applied but the addresses differ.

In case you wonder why having the same address is important - it's because some object may do some registration with its address at construction, and if the object is moved, it should be notified (e.g. via move-ctor).

Having NRVO applied but with different memory address thus makes it ill-formed.
It's a clear violation of the contract - no custom move/copy ctor is called, how could the compiler "copy" the data of S to a different place?

Is this a bug in Clang?

If we add a destructor to S, e.g.

~S() {}

This time, Clang outputs the same address.

Body:
Definitely seems to be a bug in clang, they should be the same, else things like the following will be erroneous

struct S
{
    int i;
    int* ptr;

    S(int i) : i(i) {
        this->ptr = &this->i;
    }

    S(S&& s)
    {
        this->i = s.i;
        this->ptr = &this->i;
        std::cout << "S(S&&)\n";
    }

    S(S const&) = delete;
};

Where a move (or elision where addresses don't change) is required to ensure that the internal pointer points to the correct integer.  But because of elision that pointer points to memory that does not contain the member integer.

See output here https://wandbox.org/permlink/NgNR0mupCfnnmlhK

As pointed out by @T.C., this is actually a bug in the Itanium ABI spec that doesn't take move-ctor into account. Quoting from Clang's dev:

Clang's rule is the one in the ABI: a class is passed indirectly if it
  has a non-trivial destructor or a non-trivial copy constructor. This
  rule definitely needs some adjustment [...]

Indeed, if we define either a non-trivial dtor or copy-ctor for S in the original example, we get the expected result (i.e. same address).


问:
Storing BST values into an array using index
I'm trying to create a function that uses a BST to store its values in an array. I have a global variable index = -1; dynamically created array with size of BST.

```<code>int index = -1;
struct treeNode{
    int value;
    treeNode *left;
    treeNode *right;
}

void treeTraversal(treeNode *node, int array[], int index){
    index++;
    if (node != nullptr){
        array[index] = node->value;
        treeTraversal(node->left, array, index);
        treeTraversal(node->right, array, index);
    }
}
</code>```

It works for some trees with structures like this

```<code>        6
    5
4
</code>```

But it's not working for a structure like this

```<code>    3
2       4
            5
</code>```

答:
The array assignment should be in the middle of tree traversal

```<code>int index = 0;
struct treeNode{
int value;
treeNode *left;
treeNode *right;
}

void treeTraversal(treeNode *node, int array[], int *index){
if (node != nullptr){

    treeTraversal(node->left, array, &index);
    array[index++] = node->value;
    treeTraversal(node->right, array, &index);
    }
}
</code>```

Tree Sort Tutorial

Body:
I'm trying to create a function that uses a BST to store its values in an array. I have a global variable index = -1; dynamically created array with size of BST.

int index = -1;
struct treeNode{
    int value;
    treeNode *left;
    treeNode *right;
}

void treeTraversal(treeNode *node, int array[], int index){
    index++;
    if (node != nullptr){
        array[index] = node->value;
        treeTraversal(node->left, array, index);
        treeTraversal(node->right, array, index);
    }
}

It works for some trees with structures like this

        6
    5
4

But it's not working for a structure like this

    3
2       4
            5

Body:
The array assignment should be in the middle of tree traversal

int index = 0;
struct treeNode{
int value;
treeNode *left;
treeNode *right;
}

void treeTraversal(treeNode *node, int array[], int *index){
if (node != nullptr){

    treeTraversal(node->left, array, &index);
    array[index++] = node->value;
    treeTraversal(node->right, array, &index);
    }
}

Tree Sort Tutorial


答:
Starting at the beginning, it takes items While they match a condition, and stops when they don’t. You’re looking for filter (and itertools.filterfalse):

```<code>list(filter(vowel, s))
</code>```

or a list comprehension:

```<code>[c for c in s if vowel(c)]
</code>```

Title: Why does dropwhile and takewhile skip the last a?

Body:
Starting at the beginning, it takes items While they match a condition, and stops when they don’t. You’re looking for filter (and itertools.filterfalse):

list(filter(vowel, s))

or a list comprehension:

[c for c in s if vowel(c)]


问:
Upgrading from MVC Preview 3 to Beta/RC
We have a web app that is using MVC Preview 3. I'm new to the project and relatively new to ASP.NET MVC itself - soon we will be looking to upgrade to either the Beta or RC version.

Are there any major difference between preview 3 and Beta version that would require extensive refactoring?

Any "gotchas"?

From my understanding the RC will be very close to the current Beta... does anyone have a view on this?

Any advice apprecited really.... thanks.

答: ASP NET MVC - Beta Release Notes has all the details regarding the changes. It is available at the mvc download page.</p>

Title: Upgrading from MVC Preview 3 to Beta/RC


问:
Returning DataTables in WCF/.NET
I have a WCF service from which I want to return a DataTable. I know that this is often a highly-debated topic, as far as whether or not returning DataTables is a good practice. Let's put that aside for a moment.

When I create a DataTable from scratch, as below, there are no problems whatsoever. The table is created, populated, and returned to the client, and all is well:

```<code>[DataContract]
public DataTable GetTbl()
{
    DataTable tbl = new DataTable("testTbl");
    for(int i=0;i<100;i++)
    {
        tbl.Columns.Add(i);
        tbl.Rows.Add(new string[]{"testValue"});
    }
    return tbl;
}
</code>```

However, as soon as I go out and hit the database to create the table, as below, I get a CommunicationException "The underlying connection was closed: The connection was closed unexpectedly."

```<code>[DataContract]
public DataTable GetTbl()
{
    DataTable tbl = new DataTable("testTbl");
    //Populate table with SQL query

    return tbl;
}
</code>```

The table is being populated correctly on the server side. It is significantly smaller than the test table that I looped through and returned, and the query is small and fast - there is no issue here with timeouts or large data transfer. The same exact functions and DataContracts/ServiceContracts/BehaviorContracts are being used.

Why would the way that the table is being populated have any bearing on the table returning successfully?

答:
Other than setting maximum values for all binding attributes.

Make sure each table you are passing/returning from webservice must have a table name, meaning the table.tablename property should not be blank.

OwnerDisplayName: theprise

Title: Returning DataTables in WCF/.NET

Body:
I have a WCF service from which I want to return a DataTable. I know that this is often a highly-debated topic, as far as whether or not returning DataTables is a good practice. Let's put that aside for a moment.

When I create a DataTable from scratch, as below, there are no problems whatsoever. The table is created, populated, and returned to the client, and all is well:

[DataContract]
public DataTable GetTbl()
{
    DataTable tbl = new DataTable("testTbl");
    for(int i=0;i<100;i++)
    {
        tbl.Columns.Add(i);
        tbl.Rows.Add(new string[]{"testValue"});
    }
    return tbl;
}

However, as soon as I go out and hit the database to create the table, as below, I get a CommunicationException "The underlying connection was closed: The connection was closed unexpectedly."

[DataContract]
public DataTable GetTbl()
{
    DataTable tbl = new DataTable("testTbl");
    //Populate table with SQL query

    return tbl;
}

The table is being populated correctly on the server side. It is significantly smaller than the test table that I looped through and returned, and the query is small and fast - there is no issue here with timeouts or large data transfer. The same exact functions and DataContracts/ServiceContracts/BehaviorContracts are being used.

Why would the way that the table is being populated have any bearing on the table returning successfully?

LastEditorDisplayName: Chris Fournier


问:
Convert windows R package to linux usage
I want to convert certain R packages (which have been installed under windows) for linux usage, then I can simply upload these R package to the linux server, and therefore it is not necessary to install these R packages again under linux environment.

I wonder that is it doable?

答:
Most likely not. Many are precompiled binaries for windows, but need to be compiled in linux. Especially those packages that contain compiled code (such as C or C++), these need to be compiled on the target platform so that they are linked to that platform's libraries. </p>

<p>If the issue is the time it takes to maintain a set of packages, one thing you can do is create your own utilities package, which imports all of the packages you would want. Then, if you install your utilities package, it will automatically install all of the others. </p>

Body:
Most likely not. Many are precompiled binaries for windows, but need to be compiled in linux. Especially those packages that contain compiled code (such as C or C++), these need to be compiled on the target platform so that they are linked to that platform's libraries.

If the issue is the time it takes to maintain a set of packages, one thing you can do is create your own utilities package, which imports all of the packages you would want. Then, if you install your utilities package, it will automatically install all of the others.


问:
How to remove straight lines from a Matlab image?
I have a matlab image from a matrix named Two_dim as shown in the figure below.

I would like to remove all 3 of the bottom straight horizontal lines from the image. I looked up on Stackoverflow to use regionprops to eliminate horizontal lines and obtained this code. But that doesn't seem to remove the lines.

```<code>rp = regionprops(Two_dim, 'PixelIdxList', 'Eccentricity', 'Orientation');
rp = rp([rp.Eccentricity]>0.95 & (abs([rp.Orientation])<2 | abs([rp.Orientation])>89));
Two_dim(vertcat(rp.PixelIdxList)) = false;
</code>```

答:
You could look at the row intensity sums. They will stand out as long as the lines stay horizontal.

```<code>grayI = rgb2gray(I);

rowSums = sum(grayI,2);

plot(rowSums);
</code>```

```<code>filterRows = rowSums > 1*10^5

I(filterRows,:,:) = 255;
</code>```

Body:
I have a matlab image from a matrix named Two_dim as shown in the figure below.

I would like to remove all 3 of the bottom straight horizontal lines from the image. I looked up on Stackoverflow to use regionprops to eliminate horizontal lines and obtained this code. But that doesn't seem to remove the lines.

rp = regionprops(Two_dim, 'PixelIdxList', 'Eccentricity', 'Orientation');
rp = rp([rp.Eccentricity]>0.95 & (abs([rp.Orientation])<2 | abs([rp.Orientation])>89));
Two_dim(vertcat(rp.PixelIdxList)) = false;

Body:
You could look at the row intensity sums. They will stand out as long as the lines stay horizontal.

grayI = rgb2gray(I);

rowSums = sum(grayI,2);

plot(rowSums);

filterRows = rowSums > 1*10^5

I(filterRows,:,:) = 255;


问:
PHP parsed error : unexpected '<<' (echo <<<_EOT)
I tried to use echo <<< syntax on my website, but it said parse error.

```<code><?php
echo <<<_EOT
<h1>Welcome to www.panthers.zone, TIS community.</h1>
<br><br> <h5>We are still building our website, Any interest about
<i>The Independent School</i> see:
</h5> <a href='www.theindependentschool.com'>
www.theindependentschool.com </a><br><br> Hope you have a good day! --- TIS Web Development club
_EOT;

?>
</code>```

I've tried many search the solution online but it doesn't appears to be the same problem.

Here is the error log:

2017/07/09 22:32:51 [error] 5439#0: *17 FastCGI sent in stderr: "PHP message: PHP Parse error:  syntax error, unexpected '<<' (T_SL) in /var/local/www/front/index.php on line 3" while reading response header from upstream, client: 13.59.195.100, server: panthers.zone, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/tmp/php-cgi.sock:", host: "panthers.zone"

答:
```<code><?php

echo <<<_EOT
<h1>Welcome to www.panthers.zone, TIS community.</h1>
<br/><br/>
<h5>We are still building our website, Any interest about
<i>The Independent School</i> see: </h5>
<a href='www.theindependentschool.com'> www.theindependentschool.com </a>
<br/><br/>
Hope you have a good day! --- TIS Web Development club
_EOT;

?>
</code>```

<p>dont give extra space after tag ,use this it should work properly, and why do you want to use it ,cant you use simple php tags  </p>

Body:
I tried to use echo <<< syntax on my website, but it said parse error.

<?php
echo <<<_EOT

Welcome to www.panthers.zone, TIS community.

We are still building our website, Any interest about
The Independent School see:

www.theindependentschool.com

 Hope you have a good day! --- TIS Web Development club
_EOT;

?>

I've tried many search the solution online but it doesn't appears to be the same problem.

Here is the error log:

2017/07/09 22:32:51 [error] 5439#0: *17 FastCGI sent in stderr: "PHP message: PHP Parse error:  syntax error, unexpected '<<' (T_SL) in /var/local/www/front/index.php on line 3" while reading response header from upstream, client: 13.59.195.100, server: panthers.zone, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/tmp/php-cgi.sock:", host: "panthers.zone"

Body:
<?php

echo <<<_EOT
<h1>Welcome to www.panthers.zone, TIS community.</h1>
<br/><br/>
<h5>We are still building our website, Any interest about
<i>The Independent School</i> see: </h5>
<a href='www.theindependentschool.com'> www.theindependentschool.com </a>
<br/><br/>
Hope you have a good day! --- TIS Web Development club
_EOT;

?>

dont give extra space after tag ,use this it should work properly, and why do you want to use it ,cant you use simple php tags


问:
Canvas height and width
When programming in HTML canvas, the js dimensions of the canvas don't always match the css dimensions.
Why is this happening and how can I fix this?</p>

答:
You can try to set the width and height of the canvas to be equal to the dimensions of the window object:

```<code>function createCanvas() {
    var ctx = //the canvas context;
    ctx.canvas.width  = window.innerWidth;
    ctx.canvas.height = window.innerHeight;
   //your code
}
</code>```

In addition, it is a good idea to set the body and html tags to the full width of the window:

```<code>body, html{
     height: 100%;
     width:  100%;
}
</code>```

Title: Canvas height and width

Body:
You can try to set the width and height of the canvas to be equal to the dimensions of the window object:

function createCanvas() {
    var ctx = //the canvas context;
    ctx.canvas.width  = window.innerWidth;
    ctx.canvas.height = window.innerHeight;
   //your code
}

In addition, it is a good idea to set the body and html tags to the full width of the window:

body, html{
     height: 100%;
     width:  100%;
}