问:
How to get AvPlayer Duration - Swift
How can I get AvPlayer to work like AvAudioPlayer. What I mean is, I cannot seem to get duration to work at all. Here is what I need to convert to AvPlayer:

```<code>import UIKit
import AVKit
import AVFoundation

class ModalViewController: UIViewController {

    var audioPlayer = AVAudioPlayer()
    let varSend = VarSend.sharedInstance
    var timer:NSTimer!
    var toggleState = 2

    @IBOutlet weak var slider: UISlider!
    @IBOutlet weak var sermonImage: UIImageView!
    @IBOutlet weak var sermont: UILabel!
    @IBOutlet weak var sermond: UILabel!
    @IBOutlet weak var sermonE: UILabel!
    @IBOutlet weak var sermonL: UILabel!
    @IBOutlet weak var play: UIButton!
    @IBOutlet var layer: UIView!

    override func viewDidLoad() {

        super.viewDidLoad()
        let url = varSend.url
        print("Setting up.")

        do {
           let data1 =  NSData(contentsOfURL: NSURL(string:url)!)
            audioPlayer = try AVAudioPlayer(data: data1!)
            audioPlayer.prepareToPlay()
            audioPlayer.volume = 1.0
            audioPlayer.play()
        } catch {
            print("Error getting the audio file")
        }

        slider.maximumValue = Float(audioPlayer.duration)
        timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("updateSlider"), userInfo: nil, repeats: true)
        slider.setThumbImage(UIImage(named: "circle"), forState: .Normal)
        slider.setThumbImage(UIImage(named: "circle"), forState: .Highlighted)

        let title = varSend.sermonName
        self.sermont.text = title

        let date = varSend.sermonDate
        self.sermond.text = date

        let image = varSend.sermonPic

        ImageLoader.sharedLoader.imageForUrl(image, completionHandler:{(image: UIImage?, url: String) in
            self.sermonImage.image = image!
        })
    }

    @IBAction func ChangeAudioTime(sender: AnyObject) {
        audioPlayer.stop()
        audioPlayer.currentTime = NSTimeInterval(slider.value)
        audioPlayer.prepareToPlay()
        audioPlayer.volume = 1.0
        audioPlayer.play()

    }

    func updateSlider() {
        slider.value = Float(audioPlayer.currentTime)
        let currentTime = Int(audioPlayer.currentTime)
        let minutes = currentTime / 60
        let seconds = currentTime - minutes * 60
        let con = Int(audioPlayer.duration)
        let currentItem = con - currentTime
        let minutesU = Int(currentItem / 60)
        let secondsU = Int(currentItem % 60)
        sermonE.text = NSString(format: "%02d:%02d", minutes,seconds) as String
        let timeLeft = NSString(format: "%02d:%02d", minutesU,secondsU) as String
        sermonL.text = "-\(timeLeft)"

        if currentItem == 1 {
            //audioPlayer.pause()
            toggleState = 1
            print(toggleState)
            play.setImage(UIImage(named:"play.png"),forState:UIControlState.Normal)
        }
    }

    @IBAction func playPauseButton(sender: AnyObject) {
        let playBtn = sender as! UIButton
        if toggleState == 1 {
            audioPlayer.play()
            toggleState = 2
            playBtn.setImage(UIImage(named:"pause.png"),forState:UIControlState.Normal)

        } else {
            audioPlayer.pause()
            toggleState = 1
            playBtn.setImage(UIImage(named:"play.png"),forState:UIControlState.Normal)
        }
    }

    @IBAction func play(sender: AnyObject) {
        audioPlayer.play()
    }

    @IBAction func pause(sender: AnyObject) {
        audioPlayer.pause()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func close(sender: AnyObject) {
       self.dismissViewControllerAnimated(true, completion: nil)
        audioPlayer.stop()
    }

}

</code>```

And here is what I have tried already:

```<code>import UIKit
import Alamofire
import SwiftyJSON
import AVKit
import AVFoundation
import CoreMedia

class test: UIViewController {
    var audioPlayer:AVPlayer!
    var playerItem:AVPlayerItem!

   var timer:NSTimer!

    @IBOutlet weak var sermonE: UILabel!
    @IBOutlet weak var sermonL: UILabel!
    @IBOutlet weak var slider: UISlider!

    override func viewDidLoad() {
        super.viewDidLoad()

        //let playerItem:AVPlayerItem!;
        let playerURL = "example.com"
        let steamingURL:NSURL = NSURL(string:playerURL)!
        audioPlayer = AVPlayer(URL: steamingURL)

         timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("updateSlider"), userInfo: nil, repeats: true)

    }

     func updateSlider() {
        let item = audioPlayer?.currentItem

            let durationInSeconds = CMTimeGetSeconds(item!.duration)
        print(durationInSeconds)

    }

    @IBAction func ChangeAudioTime(sender: AnyObject) {

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func Play(sender: AnyObject) {
        audioPlayer.play()
    }

}
</code>```

I have been searching for days and Apple's docs are very hard to make out.
I even tried

self.player.currentItem.asset.duration

from: How to get Duration from AVPlayer (Not AVAudioPlayer)?

Any help would be much appreciated.

答:
Swift 2.0

loadedTimeRanges  The array contains NSValue objects containing a CMTimeRange  value
  indicating the times ranges for which the player item has media data
  readily available. The time ranges returned may be discontinuous.

So I call myplayer.getCurrentTrackDuration every 1 second and noticed that when I'm streaming I got the correct final duration after 3-4 second.

```<code>extension AVPlayer {
 //run this every 1 second of streaming (or use KVO)
 //In Http stream the duration it going to increase and probably finallize near to 7% of the total duration of the song
 func getCurrentTrackDuration () -> Float64 {
    guard let currentItem = self.currentItem else { return 0.0 }
    guard currentItem.loadedTimeRanges.count > 0 else { return 0.0 }

    let timeInSecond = CMTimeGetSeconds((currentItem.loadedTimeRanges[0].CMTimeRangeValue).duration);

    return timeInSecond >= 0.0 ? timeInSecond : 0.0
 }
}
</code>```

Title: How to get AvPlayer Duration - Swift

Body:
How can I get AvPlayer to work like AvAudioPlayer. What I mean is, I cannot seem to get duration to work at all. Here is what I need to convert to AvPlayer:

import UIKit
import AVKit
import AVFoundation

class ModalViewController: UIViewController {

    var audioPlayer = AVAudioPlayer()
    let varSend = VarSend.sharedInstance
    var timer:NSTimer!
    var toggleState = 2

    @IBOutlet weak var slider: UISlider!
    @IBOutlet weak var sermonImage: UIImageView!
    @IBOutlet weak var sermont: UILabel!
    @IBOutlet weak var sermond: UILabel!
    @IBOutlet weak var sermonE: UILabel!
    @IBOutlet weak var sermonL: UILabel!
    @IBOutlet weak var play: UIButton!
    @IBOutlet var layer: UIView!

    override func viewDidLoad() {

        super.viewDidLoad()
        let url = varSend.url
        print("Setting up.")

        do {
           let data1 =  NSData(contentsOfURL: NSURL(string:url)!)
            audioPlayer = try AVAudioPlayer(data: data1!)
            audioPlayer.prepareToPlay()
            audioPlayer.volume = 1.0
            audioPlayer.play()
        } catch {
            print("Error getting the audio file")
        }

        slider.maximumValue = Float(audioPlayer.duration)
        timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("updateSlider"), userInfo: nil, repeats: true)
        slider.setThumbImage(UIImage(named: "circle"), forState: .Normal)
        slider.setThumbImage(UIImage(named: "circle"), forState: .Highlighted)

        let title = varSend.sermonName
        self.sermont.text = title

        let date = varSend.sermonDate
        self.sermond.text = date

        let image = varSend.sermonPic

        ImageLoader.sharedLoader.imageForUrl(image, completionHandler:{(image: UIImage?, url: String) in
            self.sermonImage.image = image!
        })
    }

    @IBAction func ChangeAudioTime(sender: AnyObject) {
        audioPlayer.stop()
        audioPlayer.currentTime = NSTimeInterval(slider.value)
        audioPlayer.prepareToPlay()
        audioPlayer.volume = 1.0
        audioPlayer.play()

    }

    func updateSlider() {
        slider.value = Float(audioPlayer.currentTime)
        let currentTime = Int(audioPlayer.currentTime)
        let minutes = currentTime / 60
        let seconds = currentTime - minutes * 60
        let con = Int(audioPlayer.duration)
        let currentItem = con - currentTime
        let minutesU = Int(currentItem / 60)
        let secondsU = Int(currentItem % 60)
        sermonE.text = NSString(format: "%02d:%02d", minutes,seconds) as String
        let timeLeft = NSString(format: "%02d:%02d", minutesU,secondsU) as String
        sermonL.text = "-\(timeLeft)"

        if currentItem == 1 {
            //audioPlayer.pause()
            toggleState = 1
            print(toggleState)
            play.setImage(UIImage(named:"play.png"),forState:UIControlState.Normal)
        }
    }

    @IBAction func playPauseButton(sender: AnyObject) {
        let playBtn = sender as! UIButton
        if toggleState == 1 {
            audioPlayer.play()
            toggleState = 2
            playBtn.setImage(UIImage(named:"pause.png"),forState:UIControlState.Normal)

        } else {
            audioPlayer.pause()
            toggleState = 1
            playBtn.setImage(UIImage(named:"play.png"),forState:UIControlState.Normal)
        }
    }

    @IBAction func play(sender: AnyObject) {
        audioPlayer.play()
    }

    @IBAction func pause(sender: AnyObject) {
        audioPlayer.pause()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func close(sender: AnyObject) {
       self.dismissViewControllerAnimated(true, completion: nil)
        audioPlayer.stop()
    }

}

And here is what I have tried already:

import UIKit
import Alamofire
import SwiftyJSON
import AVKit
import AVFoundation
import CoreMedia

class test: UIViewController {
    var audioPlayer:AVPlayer!
    var playerItem:AVPlayerItem!

   var timer:NSTimer!

    @IBOutlet weak var sermonE: UILabel!
    @IBOutlet weak var sermonL: UILabel!
    @IBOutlet weak var slider: UISlider!

    override func viewDidLoad() {
        super.viewDidLoad()

        //let playerItem:AVPlayerItem!;
        let playerURL = "example.com"
        let steamingURL:NSURL = NSURL(string:playerURL)!
        audioPlayer = AVPlayer(URL: steamingURL)

         timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("updateSlider"), userInfo: nil, repeats: true)

    }

     func updateSlider() {
        let item = audioPlayer?.currentItem

            let durationInSeconds = CMTimeGetSeconds(item!.duration)
        print(durationInSeconds)

    }

    @IBAction func ChangeAudioTime(sender: AnyObject) {

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func Play(sender: AnyObject) {
        audioPlayer.play()
    }

}

I have been searching for days and Apple's docs are very hard to make out.
I even tried

self.player.currentItem.asset.duration

from: How to get Duration from AVPlayer (Not AVAudioPlayer)?

Any help would be much appreciated.

Body:
Swift 2.0

loadedTimeRanges  The array contains NSValue objects containing a CMTimeRange  value
  indicating the times ranges for which the player item has media data
  readily available. The time ranges returned may be discontinuous.

So I call myplayer.getCurrentTrackDuration every 1 second and noticed that when I'm streaming I got the correct final duration after 3-4 second.

extension AVPlayer {
 //run this every 1 second of streaming (or use KVO)
 //In Http stream the duration it going to increase and probably finallize near to 7% of the total duration of the song
 func getCurrentTrackDuration () -> Float64 {
    guard let currentItem = self.currentItem else { return 0.0 }
    guard currentItem.loadedTimeRanges.count > 0 else { return 0.0 }

    let timeInSecond = CMTimeGetSeconds((currentItem.loadedTimeRanges[0].CMTimeRangeValue).duration);

    return timeInSecond >= 0.0 ? timeInSecond : 0.0
 }
}


来源: stackexchange

问:
Win32 dispatch program and redirect stdout to file buffer problem?
On Wi32
I am trying to start a executable who redirects to a filename (current date) e.g. the same as:

Someexecutable.exe > 20101220000000.txt

When I do this from windows cmd.exe everything works fine. However when doing this from my program as shown below the system seems ot either drop the redirect even if it creates the file and/or it seems to buffer a large amount of data before flushing to disk.
I can't change the executable that is being run.
The program beeing executed now only writes to stdout, but remember I can't change this at all. (the simplest way woud be to just do stdout = filehandle; but I that is sadly impossible for me right now!)

(Not required: Also the program waits as system() this is not required but what is the simplest way of detaching the program being run via system() )

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

int main(int argc, char *argv[])
{
  char   execstr[512];
  char   s[30];
  size_t i;
  struct tm tim;
  time_t now;

  now = time(NULL);
  tim = *(localtime(&now));
  i   = strftime(s,30,"%Y%m%d%H%M",&tim);

  sprintf(execstr,"someexecutable.exe > %s.txt",s);
  printf("Executing: \"%s\"\n",execstr);

  system(execstr);
  exit(0);
  return 0;
}
</code>```

答:
Your program works fine for me (testing in VS 2010).  Some problems you might run into if you're running your tests in the IDE are:

the current directory for the program might not be what you expect it to be (so you might be looking for the output file in the wrong place). By default, the current directory for the program when run in the IDE will be the directory that has the project file (whatever.vcproj or whatever,.vcxproj) - not the directory that has the executable.  This can be changed in the project settings.

the IDE's path might not be the same as what you get at a standard command line, so you program might not be finding someexecutable.exe

If you change you program so that the line with the sprintf() call looks like:

```<code>sprintf(execstr,"someexecutable.exe",s);
</code>```

Do you see the output of someexecutable.exe in the console window?

ContentLicense: CC BY-SA 2.5

Body:
On Wi32
I am trying to start a executable who redirects to a filename (current date) e.g. the same as:

Someexecutable.exe > 20101220000000.txt

When I do this from windows cmd.exe everything works fine. However when doing this from my program as shown below the system seems ot either drop the redirect even if it creates the file and/or it seems to buffer a large amount of data before flushing to disk.
I can't change the executable that is being run.
The program beeing executed now only writes to stdout, but remember I can't change this at all. (the simplest way woud be to just do stdout = filehandle; but I that is sadly impossible for me right now!)

(Not required: Also the program waits as system() this is not required but what is the simplest way of detaching the program being run via system() )

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

int main(int argc, char *argv[])
{
  char   execstr[512];
  char   s[30];
  size_t i;
  struct tm tim;
  time_t now;

  now = time(NULL);
  tim = *(localtime(&now));
  i   = strftime(s,30,"%Y%m%d%H%M",&tim);

  sprintf(execstr,"someexecutable.exe > %s.txt",s);
  printf("Executing: \"%s\"\n",execstr);

  system(execstr);
  exit(0);
  return 0;
}

Body:
Your program works fine for me (testing in VS 2010).  Some problems you might run into if you're running your tests in the IDE are:

the current directory for the program might not be what you expect it to be (so you might be looking for the output file in the wrong place). By default, the current directory for the program when run in the IDE will be the directory that has the project file (whatever.vcproj or whatever,.vcxproj) - not the directory that has the executable.  This can be changed in the project settings.

the IDE's path might not be the same as what you get at a standard command line, so you program might not be finding someexecutable.exe

If you change you program so that the line with the sprintf() call looks like:

sprintf(execstr,"someexecutable.exe",s);

Do you see the output of someexecutable.exe in the console window?


问:
Django model "doesn't declare an explicit app_label"
I'm at wit's end. After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got:

```<code>Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label
</code>```

There is SO LITTLE info on this on the web, and no solution out there has resolved my issue. Any advice would be tremendously appreciated.

I'm using Python 3.4 and Django 1.10.

From my settings.py:

```<code>INSTALLED_APPS = [
    'DeleteNote.apps.DeletenoteConfig',
    'LibrarySync.apps.LibrarysyncConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
</code>```

And my apps.py files look like this:

```<code>from django.apps import AppConfig

class DeletenoteConfig(AppConfig):
    name = 'DeleteNote'
</code>```

and

```<code>from django.apps import AppConfig

class LibrarysyncConfig(AppConfig):
    name = 'LibrarySync'
</code>```

答:
as a noob using Python3 ,I find it might be an import error instead of a Django error

wrong:

```<code>from someModule import someClass
</code>```

right:

```<code>from .someModule import someClass
</code>```

this happens a few days ago but I really can't reproduce it...I think only people new to Django may encounter this.here's what I remember:

try to register a model in admin.py:

```<code>from django.contrib import admin
from user import User
admin.site.register(User)
</code>```

try to run server, error looks like this

```<code>some lines...
File "/path/to/admin.py" ,line 6
tell you there is an import error
some lines...
Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label
</code>```

change user to .user ,problem solved

ContentLicense: CC BY-SA 3.0

Body:
I'm at wit's end. After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got:

Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label

There is SO LITTLE info on this on the web, and no solution out there has resolved my issue. Any advice would be tremendously appreciated.

I'm using Python 3.4 and Django 1.10.

From my settings.py:

INSTALLED_APPS = [
    'DeleteNote.apps.DeletenoteConfig',
    'LibrarySync.apps.LibrarysyncConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

And my apps.py files look like this:

from django.apps import AppConfig

class DeletenoteConfig(AppConfig):
    name = 'DeleteNote'

and

from django.apps import AppConfig

class LibrarysyncConfig(AppConfig):
    name = 'LibrarySync'

Body:
as a noob using Python3 ,I find it might be an import error instead of a Django error

wrong:

from someModule import someClass

right:

from .someModule import someClass

this happens a few days ago but I really can't reproduce it...I think only people new to Django may encounter this.here's what I remember:

try to register a model in admin.py:

from django.contrib import admin
from user import User
admin.site.register(User)

try to run server, error looks like this

some lines...
File "/path/to/admin.py" ,line 6
tell you there is an import error
some lines...
Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label

change user to .user ,problem solved


问:
Place API - getting place photo as marker icon
I follow this guide
https://developers.google.com/maps/documentation/javascript/places#places_photos
to create place photo as marker icon. This is my map initialization code:

```<code>var map;

function initMap() {
    // Create a map centered in Pyrmont, Sydney (Australia).
      map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -6.920812, lng: 107.604116},
        zoom: 13
      });

      var request = {
        location: map.getCenter(),
        radius: '5000',
        type: ['shopping_mall']
      };

      var service = new google.maps.places.PlacesService(map);
      service.textSearch(request, callback);
}

// Checks that the PlacesServiceStatus is OK, and adds a marker
// using the place ID and location from the PlacesService.
function callback(results, status) {
  console.log(results);
  if (status == google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        var place = results[i];
        createPhotoMarker(place);
      }
  }
}

google.maps.event.addDomListener(window, 'load', initMap);
</code>```

this is the createPhotoMarker function

```<code>function createPhotoMarker(place) {
      var photos = place.photos;
      if (!photos) {
        var marker = new google.maps.Marker({
            map: map,
            position: place.geometry.location,
            title: place.name
          });
          return;
      }

      var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location,
        title: place.name,
        icon: photos[0].getUrl({'maxWidth': 35, 'maxHeight': 35})
      });
}
</code>```

the function will create regular marker if place photo is not available. But for the place with photo available, I get this error :

Failed to load resource: the server responded with a status of 404 () lh3.googleusercontent.com/w35-h35-p/AF1QipOIL6GVVmtqp_cw_hBEQxdILZSa8poMO0HAqFHd=k

And the map only shows regular marker.
What did I do wrong?

This is the fiddle http://jsfiddle.net/v90fmrhp/

==========Update 2017-07-07============

Thanks for the answers and fixes

It seems the issue solved. My fiddle is working now
https://issuetracker.google.com/issues/63298126

Marked as Fixed

  Good news! We have fixed this issue. Thanks for your patience.

Happy Mapping!

答:
Had the same issue and Sulyman suggested a workaround that is working but I don't know for how long when google fixes this.

Google Places Photos .GetUrl is adding width and height to url

Here is what we did.

```<code>if(place.photos != null){
          for(var i = 0; i < place.photos.length; i++){
            //Do a string replace to get the w-h-p out of there.
            var str = place.photos[i].getUrl({"maxWidth": 100, "maxHeight": 100});
            var res = str.replace("w100-h100-p", "p");
            self.pacPhotos.push({
              id : res

            });

          }
        }else {
          console.log("no photo");
        }
      }
</code>```

Body:
I follow this guide
https://developers.google.com/maps/documentation/javascript/places#places_photos
to create place photo as marker icon. This is my map initialization code:

var map;

function initMap() {
    // Create a map centered in Pyrmont, Sydney (Australia).
      map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -6.920812, lng: 107.604116},
        zoom: 13
      });

      var request = {
        location: map.getCenter(),
        radius: '5000',
        type: ['shopping_mall']
      };

      var service = new google.maps.places.PlacesService(map);
      service.textSearch(request, callback);
}

// Checks that the PlacesServiceStatus is OK, and adds a marker
// using the place ID and location from the PlacesService.
function callback(results, status) {
  console.log(results);
  if (status == google.maps.places.PlacesServiceStatus.OK) {
      for (var i = 0; i < results.length; i++) {
        var place = results[i];
        createPhotoMarker(place);
      }
  }
}

google.maps.event.addDomListener(window, 'load', initMap);

this is the createPhotoMarker function

function createPhotoMarker(place) {
      var photos = place.photos;
      if (!photos) {
        var marker = new google.maps.Marker({
            map: map,
            position: place.geometry.location,
            title: place.name
          });
          return;
      }

      var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location,
        title: place.name,
        icon: photos[0].getUrl({'maxWidth': 35, 'maxHeight': 35})
      });
}

the function will create regular marker if place photo is not available. But for the place with photo available, I get this error :

Failed to load resource: the server responded with a status of 404 () lh3.googleusercontent.com/w35-h35-p/AF1QipOIL6GVVmtqp_cw_hBEQxdILZSa8poMO0HAqFHd=k

And the map only shows regular marker.
What did I do wrong?

This is the fiddle http://jsfiddle.net/v90fmrhp/

==========Update 2017-07-07============

Thanks for the answers and fixes

It seems the issue solved. My fiddle is working now
https://issuetracker.google.com/issues/63298126

Marked as Fixed

  Good news! We have fixed this issue. Thanks for your patience.

Happy Mapping!

Body:
Had the same issue and Sulyman suggested a workaround that is working but I don't know for how long when google fixes this.

Google Places Photos .GetUrl is adding width and height to url

Here is what we did.

if(place.photos != null){
          for(var i = 0; i < place.photos.length; i++){
            //Do a string replace to get the w-h-p out of there.
            var str = place.photos[i].getUrl({"maxWidth": 100, "maxHeight": 100});
            var res = str.replace("w100-h100-p", "p");
            self.pacPhotos.push({
              id : res

            });

          }
        }else {
          console.log("no photo");
        }
      }


问:
Custom FireMonkey component does not get drawn
Working in C++Builder 10.2 Tokyo, I am trying to add a custom component to a FireMonkey TForm programmatically at runtime.

The custom component is not installed as a package and registered in the IDE (as that ended up complicating the project too much), rather it is simply a subclass of TPanel.

However, The component, and its children, do not get drawn when I run the application. I have tested this on Windows and Android, and tried multiple modifications, like setting the Width and Height explicitly.

How can I fix this?

Below is the relevant bit of my code:

```<code>__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm3D(Owner)
{
    mkView = new MKView(this);
    mkView->Align = TAlignLayout::Client;
    mkView->Enabled = true;
    mkView->Visible = true;
    mkView->Parent = this;
}

__fastcall MKView::MKView(TComponent *Owner)
    : TPanel(Owner)
{
    this->OnMouseDown = MKView_OnMouseDown;

    TLabel1 = new TLabel(this);
    TLabel1->Text = "Here I am!";
    TLabel1->Enabled = true;
    TLabel1->Visible = true;
    TLabel1->Parent = this;
    TLabel1->OnMouseDown = MKView_OnMouseDown;
}
</code>```

答: It looks like TForm3D doesn't work well with standard FireMonkey components, as it is designed for rendering FireMonkey 3D components and uses OnRender() instead of OnPaint(). I was using TForm3D for its OpenGL context, but having switched to a standard TForm the components are now being drawn.</p>

Body:
Working in C++Builder 10.2 Tokyo, I am trying to add a custom component to a FireMonkey TForm programmatically at runtime.

The custom component is not installed as a package and registered in the IDE (as that ended up complicating the project too much), rather it is simply a subclass of TPanel.

However, The component, and its children, do not get drawn when I run the application. I have tested this on Windows and Android, and tried multiple modifications, like setting the Width and Height explicitly.

How can I fix this?

Below is the relevant bit of my code:

__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm3D(Owner)
{
    mkView = new MKView(this);
    mkView->Align = TAlignLayout::Client;
    mkView->Enabled = true;
    mkView->Visible = true;
    mkView->Parent = this;
}

__fastcall MKView::MKView(TComponent *Owner)
    : TPanel(Owner)
{
    this->OnMouseDown = MKView_OnMouseDown;

    TLabel1 = new TLabel(this);
    TLabel1->Text = "Here I am!";
    TLabel1->Enabled = true;
    TLabel1->Visible = true;
    TLabel1->Parent = this;
    TLabel1->OnMouseDown = MKView_OnMouseDown;
}


问:
How can I read data from an array if the array size is too large.....!
How can I read only that cells those are containing data values from this following array.
sample array </p>

<p>Here is my code as an example which is displaying the values but its reading all the cells for retrieve only 4 values. How can I avoid this zero containing locations?.There might be data in random locations and rest of the locations will be zero.So is there any way to read only the data value containing cells. </p>

```<code>#include<stdio.h>
void main()
{
    int i,data[500000]={25,0,0,0,0,98,0,0,13,0,857};
    for(i=0;i<500000;i++)
    {
        if(data[i]==0)
            continue;
        printf("%d\t",data[i]);
    }
}
</code>```

答:
Ah, I think I understand the question now. I think you want to know how you could stop reading after data[10] because although you've allocated half a million entries, right now nowhere near all those elements are populated.

Note that we're assuming our own meaning of "populated". C has no concept of an empty array element.

In C it's quite common to keep a size variable alongside oversized arrays. So you could do something similar to:

```<code>int data[500000]={25,0,0,0,0,98,0,0,13,0,857};
int size = 11;
for(int i=0;i<size;i++) {
    if(data[i]==0) {
        continue;
    }
    printf("%d\t",data[i]);
}
</code>```

(I've added braces to your if block - don't get in the habit of omitting them)

You seem to want to skip zeros, I've left that in.

When you add an element, you'll need to increment size.

```<code>data[size] = newValue;
size++;
</code>```

... or in terser idiomatic C ...

```<code>data[size++] = newValue;
</code>```

... and you'll need to make sure that whatever works with your array, also sees the length. For example, you can't have a function findHighest(int data[]) --
 it'll have to be findHighest(int data[], int size. As you progress in your C studies, you'll find how a struct helps you achieve this more neatly.

An example of this in action is the read system call:

```<code>int length = read(file, buf, count);
</code>```

buf is a char[] of a length <= count. read() will read some number of bytes up to count, and return length. buf[0] through to buf[length-1] contain the bytes you want to work with. buf[length] onward is junk.

An alternative is to ensure that the first irrelevant value in the array contains a sentinel value indicating "no more to see". For example you could use -1, if you're sure that will never be a valid value. A very simple approach is to fill the array with -1s at initialisation time (use memset()). Alternatively make sure you write a sentinel value at data[index_of_last_value + 1] whenever you extend the length.

The standard C string handling functions are examples of code that uses a sentinel. NULL (zero, '\0') indicates the end of a string, which is very often stored in a longer buffer.

Body:
How can I read only that cells those are containing data values from this following array.
sample array

Here is my code as an example which is displaying the values but its reading all the cells for retrieve only 4 values. How can I avoid this zero containing locations?.There might be data in random locations and rest of the locations will be zero.So is there any way to read only the data value containing cells.

#include<stdio.h>
void main()
{
    int i,data[500000]={25,0,0,0,0,98,0,0,13,0,857};
    for(i=0;i<500000;i++)
    {
        if(data[i]==0)
            continue;
        printf("%d\t",data[i]);
    }
}

Body:
Ah, I think I understand the question now. I think you want to know how you could stop reading after data[10] because although you've allocated half a million entries, right now nowhere near all those elements are populated.

Note that we're assuming our own meaning of "populated". C has no concept of an empty array element.

In C it's quite common to keep a size variable alongside oversized arrays. So you could do something similar to:

int data[500000]={25,0,0,0,0,98,0,0,13,0,857};
int size = 11;
for(int i=0;i<size;i++) {
    if(data[i]==0) {
        continue;
    }
    printf("%d\t",data[i]);
}

(I've added braces to your if block - don't get in the habit of omitting them)

You seem to want to skip zeros, I've left that in.

When you add an element, you'll need to increment size.

data[size] = newValue;
size++;

... or in terser idiomatic C ...

data[size++] = newValue;

... and you'll need to make sure that whatever works with your array, also sees the length. For example, you can't have a function findHighest(int data[]) --
 it'll have to be findHighest(int data[], int size. As you progress in your C studies, you'll find how a struct helps you achieve this more neatly.

An example of this in action is the read system call:

int length = read(file, buf, count);

buf is a char[] of a length <= count. read() will read some number of bytes up to count, and return length. buf[0] through to buf[length-1] contain the bytes you want to work with. buf[length] onward is junk.

An alternative is to ensure that the first irrelevant value in the array contains a sentinel value indicating "no more to see". For example you could use -1, if you're sure that will never be a valid value. A very simple approach is to fill the array with -1s at initialisation time (use memset()). Alternatively make sure you write a sentinel value at data[index_of_last_value + 1] whenever you extend the length.

The standard C string handling functions are examples of code that uses a sentinel. NULL (zero, '\0') indicates the end of a string, which is very often stored in a longer buffer.


问:
Jenkins Multibranch Pipeline: clean workspace / delete directory when build ends
we are using Jenkins multibranch (scripted) pipeline to run multiple builds, in parallel. Each one will create a new, uniquely named directory to checkout the code and run the test. Directories are uniquely named because they contain the branch name but also a random part like "JAA2A5HUZB7TRE4OTVXU7S...".

This means that after each build X directories (X = number of parallel jobs * number of branches) stay on the Jenkins node, filling disk space.

I wonder how I could automatically delete these directories.

A simplified version of my initial pipeline looks like this

// Initialize the matrix
def matrix = [
  'foo',
  'bar',
]

// Initialize empty tasks map
def tasks = [:]

// Job status
successful = true

// Fill our tasks map from the Matrix data
for (x in matrix) {

  def job_name = x

  tasks[job_name] = {
    node('libvirt') {
        // Checkout repository first
        stage("$job_name - Checkout") {
          checkout scm
        }

        // Then build the machine
        gitlabCommitStatus('build') {
            stage("$job_name - Build") {
                  sh "./bin/build.sh ${job_name}"
            }
        }
      }
    }
  }
}

//// Pipeline ////

notifyBuild('STARTED')

// Run tasks in parallel
try {
  parallel tasks
} catch(e) {
  throw e
} finally {
  if (successful) {
    notifyBuild('SUCCESS')
  } else {
    notifyBuild('FAILED')
  }
}

// Methods
def notifyBuild(String buildStatus = 'STARTED') {
   // used to send formatted e-mails
}
```

<p>I first added <code>deleteDir()</code> like this</p>

<pre class="lang-groovy prettyprint-override"><code>} finally {
  if (successful) {
    notifyBuild('SUCCESS')
  } else {
    notifyBuild('FAILED')
  }
  node('libvirt') {
    deleteDir()
  }
}
</code>```

it raises an error and makes the build fail.

I then added a cleanWs() like this

} finally {
  if (successful) {
    notifyBuild('SUCCESS')
  } else {
    notifyBuild('FAILED')
  }
  node('libvirt') {
    cleanWs()
  }
}
```

<p>The output is</p>

```Running on node in /srv/jenkins/workspace/pipeline-deletedir-DRD7EKBEMMWJQZW6KKMQVVBTJTPTKLRAE2ITDK7V7IB5PTFXZUZA
[Pipeline] {
[Pipeline] step
[WS-CLEANUP] Deleting project workspace...[WS-CLEANUP] done
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
```

but the directory /srv/jenkins/workspace/pipeline-deletedir-DRD7EKBEMMWJQZW6KKMQVVBTJTPTKLRAE2ITDK7V7IB5PTFXZUZA still exists.

I'm looking for any solution to adapt this scripted pipeline (and for declarative pipeline if you know how) to be able to delete all directories created by the build.

答:
First of all, you can not delete the directory in which the build is still running. The deleteDir() step just deletes the content of your workspace.

You could trigger a job that runs after your build is finished which deletes those directories. For this, you could use a pattern like pipeline-deletedir-*.

ContentLicense: CC BY-SA 4.0

Body:
we are using Jenkins multibranch (scripted) pipeline to run multiple builds, in parallel. Each one will create a new, uniquely named directory to checkout the code and run the test. Directories are uniquely named because they contain the branch name but also a random part like "JAA2A5HUZB7TRE4OTVXU7S...".

This means that after each build X directories (X = number of parallel jobs * number of branches) stay on the Jenkins node, filling disk space.

I wonder how I could automatically delete these directories.

A simplified version of my initial pipeline looks like this

// Initialize the matrix
def matrix = [
  'foo',
  'bar',
]

// Initialize empty tasks map
def tasks = [:]

// Job status
successful = true

// Fill our tasks map from the Matrix data
for (x in matrix) {

  def job_name = x

  tasks[job_name] = {
    node('libvirt') {
        // Checkout repository first
        stage("$job_name - Checkout") {
          checkout scm
        }

        // Then build the machine
        gitlabCommitStatus('build') {
            stage("$job_name - Build") {
                  sh "./bin/build.sh ${job_name}"
            }
        }
      }
    }
  }
}

//// Pipeline ////

notifyBuild('STARTED')

// Run tasks in parallel
try {
  parallel tasks
} catch(e) {
  throw e
} finally {
  if (successful) {
    notifyBuild('SUCCESS')
  } else {
    notifyBuild('FAILED')
  }
}

// Methods
def notifyBuild(String buildStatus = 'STARTED') {
   // used to send formatted e-mails
}

I first added deleteDir() like this

} finally {
  if (successful) {
    notifyBuild('SUCCESS')
  } else {
    notifyBuild('FAILED')
  }
  node('libvirt') {
    deleteDir()
  }
}

it raises an error and makes the build fail.

I then added a cleanWs() like this

} finally {
  if (successful) {
    notifyBuild('SUCCESS')
  } else {
    notifyBuild('FAILED')
  }
  node('libvirt') {
    cleanWs()
  }
}

The output is

Running on node in /srv/jenkins/workspace/pipeline-deletedir-DRD7EKBEMMWJQZW6KKMQVVBTJTPTKLRAE2ITDK7V7IB5PTFXZUZA
[Pipeline] {
[Pipeline] step
[WS-CLEANUP] Deleting project workspace...[WS-CLEANUP] done
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

but the directory /srv/jenkins/workspace/pipeline-deletedir-DRD7EKBEMMWJQZW6KKMQVVBTJTPTKLRAE2ITDK7V7IB5PTFXZUZA still exists.

I'm looking for any solution to adapt this scripted pipeline (and for declarative pipeline if you know how) to be able to delete all directories created by the build.


问:
'npm install --only=dev' deletes existing packages
While working on a node project, I am having trouble separating installation of application and test dependencies using npm. I am using node version 8.1.2 and npm version 5.0.3.

To elaborate, I am using docker to create production and test images for my node application with the idea that the production image will have only the application dependencies installed (e.g. aws-sdk, xml-builder). I am doing this by running npm install -q --only=prod in the production docker image.

The test image extends the production image and installs the test dependencies (e.g. chai, mocha) on top of it. This is achieved by running npm install -q --only=dev command in the test docker image. The purpose of this exercise is to create a clean production image that doesn't have unnecessary packages.

But when I execute the latter npm command (npm install -q --only=dev) it removes the packages installed by the first install. I'm doing the same thing in another project that uses an older version of npm and node and it works fine.

Did something change in the latest version of npm? If so is there another prescribed way of achieving the same effect?

答:
It's not because of the new version of Node.js, but because of the new version of npm that is bundled together (version 5).

In your case you could do one of these:

Execute first npm install --only=prod in your production image, and then just npm install in your test image.

Deleting package-lock.json after the first npm install.

Using the option --no-package-lock in each npm install.

The new npm version uses a new file called package-lock.js, the one producing this behaviour, more info here.

EDIT:

I just found out this is an issue with npm, it seems it will be fixed in the next release. At the moment the workarounds I wrote above should work.


问:
Get substing of a column in Oracle 11g
I have a column with a long text, and i need to find an specific string inside of it.

for example:
the column contains this: "Hello mi number is C.C. 2313"

and i need to extract "C.C. 2313"

Im using an Oracle 11g Database.

答:
I put answer in case that length of column is variable (it's easier if it is fixed):

```<code>create table t10(
test varchar2 (30));

insert into t10 (test) values ('Hello mi number is C.C. 2313');

select  substr(test,instr(test, 'C.C.'),length(test))  from t10 ar;
</code>```

You can also divide for all variation of C.C. cc C.c. c.c. with case when

Title: Get substing of a column in Oracle 11g

Body:
I put answer in case that length of column is variable (it's easier if it is fixed):

create table t10(
test varchar2 (30));

insert into t10 (test) values ('Hello mi number is C.C. 2313');

select  substr(test,instr(test, 'C.C.'),length(test))  from t10 ar;

You can also divide for all variation of C.C. cc C.c. c.c. with case when


问:
How to iterate through variables?
I was using the following in my current script

```<code>for x in {07..10}
</code>```

Trying to pass the start,end variables to the script using

```<code>for x in $(seq $1 $2)
</code>```

Since the sequence starts from 07, and 07 is a file name that I want to read, I cant change the variable to 7, as it happens when using the sequence. Can you please point me in the right direction as I don't have much experience with bash.

答:
Use printf to get the number format you want:

```<code>for (( x=7; x<=10; x++ )); do
   str=$( printf "%02d" "$x" )
   echo filename${str}.txt
done
</code>```

Results look like this:

```<code>$ for (( x=7; x<=10; x++ )); do str=$( printf "%02d" "$x" ); echo filename${str}.txt; done
filename07.txt
filename08.txt
filename09.txt
filename10.txt
</code>```

Works with variables, too:

```<code>$ start="07"
$ end="10"
$ for (( x=$start; x<=$end; x++ )); do str=$( printf "%02d" "$x" ); echo filename${str}.txt; done
filename07.txt
filename08.txt
filename09.txt
filename10.txt
</code>```

Title: How to iterate through variables?

Body:
I was using the following in my current script

for x in {07..10}

Trying to pass the start,end variables to the script using

for x in $(seq $1 $2)

Since the sequence starts from 07, and 07 is a file name that I want to read, I cant change the variable to 7, as it happens when using the sequence. Can you please point me in the right direction as I don't have much experience with bash.

Body:
Use printf to get the number format you want:

for (( x=7; x<=10; x++ )); do
   str=$( printf "%02d" "$x" )
   echo filename${str}.txt
done

Results look like this:

$ for (( x=7; x<=10; x++ )); do str=$( printf "%02d" "$x" ); echo filename${str}.txt; done
filename07.txt
filename08.txt
filename09.txt
filename10.txt

Works with variables, too:

$ start="07"
$ end="10"
$ for (( x=$start; x<=$end; x++ )); do str=$( printf "%02d" "$x" ); echo filename${str}.txt; done
filename07.txt
filename08.txt
filename09.txt
filename10.txt


问:
JsInterop - Get Value in Array
I created my own custom array in JsInterop:

```<code>@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Array")
public interface Array<T>
{
    public void push(T value);

    @JsProperty(name = "length")
    public int getLength();

    @JsProperty(name = "length")
    void setLength(int newLength);

    @JsOverlay
    default T get(int index) {
        return JsArrayHelper.getArrayValue(this, index);
    }
}
</code>```

And here is the JsArrayHelper class scaled down:

```<code>public class JsArrayHelper
{
    //TODO: Eliminate JSNI. Better way to do this?
    public static native <T> T getArrayValue(Array<T> a, int i) /*-{
        return a[i];
    }-*/;
}
</code>```

Is there a better way to get the value of the array instead of using JSNI?

答:
Use com.google.jsinterop:base lib, this lib should include utilities for anything that cannot be done with JsInterop, and the lib will maintain compatibility with GWT and j2cl. The lib is pretty small (only 10 classes, 2 of them internal), so just add it to your project and explore all its utilities.

So instead of your custom Array<T>.get(int) and JsArrayHelper classes use jsinterop.base.JsArrayLike<T>.getAt(int).

Title: JsInterop - Get Value in Array

Body:
I created my own custom array in JsInterop:

@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Array")
public interface Array<T>
{
    public void push(T value);

    @JsProperty(name = "length")
    public int getLength();

    @JsProperty(name = "length")
    void setLength(int newLength);

    @JsOverlay
    default T get(int index) {
        return JsArrayHelper.getArrayValue(this, index);
    }
}

And here is the JsArrayHelper class scaled down:

public class JsArrayHelper
{
    //TODO: Eliminate JSNI. Better way to do this?
    public static native <T> T getArrayValue(Array<T> a, int i) /*-{
        return a[i];
    }-*/;
}

Is there a better way to get the value of the array instead of using JSNI?


问:
How to declare array value in Kotlin annotations?
I have some problem with creating my own annotations in Kotlin. I have to create some annotations and in some of them i need to declare values with array type.
In java we can do this:

```<code>public @interface JoinTable {
...
    JoinColumn[] inverseJoinColumns() default {};
...
}
</code>```

Where JoinColumn is also an annotation type.

I want to do something like that in Kotlin:

```<code>annotation class JoinTable(
    val name: String,
    val joinColumns: Array<JoinColumn>
)
</code>```

I also tried to do this:

```<code>annotation class JoinTable(
    val name: String,
    val joinColumns: List<JoinColumn>
)
</code>```

But my IDe says:

Invalid type of annotation member

What should i do?

Thank you!

答:
So, it was my big fault. I didn't notice that JoinColumn in my realization isn't an annotation.

```<code>class JoinColumn()
</code>```

Well, it fixed ^_^:

```<code>annotation class JoinColumn()
</code>```

Body:
I have some problem with creating my own annotations in Kotlin. I have to create some annotations and in some of them i need to declare values with array type.
In java we can do this:

public @interface JoinTable {
...
    JoinColumn[] inverseJoinColumns() default {};
...
}

Where JoinColumn is also an annotation type.

I want to do something like that in Kotlin:

annotation class JoinTable(
    val name: String,
    val joinColumns: Array<JoinColumn>
)

I also tried to do this:

annotation class JoinTable(
    val name: String,
    val joinColumns: List<JoinColumn>
)

But my IDe says:

Invalid type of annotation member

What should i do?

Thank you!

Body:
So, it was my big fault. I didn't notice that JoinColumn in my realization isn't an annotation.

class JoinColumn()

Well, it fixed ^_^:

annotation class JoinColumn()


问:
Is there a tool,, code or setting in Android Studio where you can resize all your images to support multiple screens?
For example, the following application resource directories provide different layout designs for different screen sizes and different drawable's. Use the mipmap/ folders for launcher icons.</p>

```<code>res/layout/my_layout.xml              // layout for normal screen size ("default")
res/layout-large/my_layout.xml        // layout for large screen size
res/layout-xlarge/my_layout.xml       // layout for extra-large screen size
res/layout-xlarge-land/my_layout.xml  // layout for extra-large in landscape orientation

res/drawable-mdpi/graphic.png         // bitmap for medium-density
res/drawable-hdpi/graphic.png         // bitmap for high-density
res/drawable-xhdpi/graphic.png        // bitmap for extra-high-density
res/drawable-xxhdpi/graphic.png       // bitmap for extra-extra-high-density

res/mipmap-mdpi/my_icon.png         // launcher icon for medium-density
res/mipmap-hdpi/my_icon.png         // launcher icon for high-density
res/mipmap-xhdpi/my_icon.png        // launcher icon for extra-high-density
res/mipmap-xxhdpi/my_icon.png       // launcher icon for extra-extra-high-density
res/mipmap-xxxhdpi/my_icon.png      // launcher icon for extra-extra-extra-high-density
</code>```

答: You can use Material design icon plugin which will help you work with any icons provided by Google : Google material-design-icons and with every resolution.</p>

Body:
For example, the following application resource directories provide different layout designs for different screen sizes and different drawable's. Use the mipmap/ folders for launcher icons.

res/layout/my_layout.xml              // layout for normal screen size ("default")
res/layout-large/my_layout.xml        // layout for large screen size
res/layout-xlarge/my_layout.xml       // layout for extra-large screen size
res/layout-xlarge-land/my_layout.xml  // layout for extra-large in landscape orientation

res/drawable-mdpi/graphic.png         // bitmap for medium-density
res/drawable-hdpi/graphic.png         // bitmap for high-density
res/drawable-xhdpi/graphic.png        // bitmap for extra-high-density
res/drawable-xxhdpi/graphic.png       // bitmap for extra-extra-high-density

res/mipmap-mdpi/my_icon.png         // launcher icon for medium-density
res/mipmap-hdpi/my_icon.png         // launcher icon for high-density
res/mipmap-xhdpi/my_icon.png        // launcher icon for extra-high-density
res/mipmap-xxhdpi/my_icon.png       // launcher icon for extra-extra-high-density
res/mipmap-xxxhdpi/my_icon.png      // launcher icon for extra-extra-extra-high-density


问:
Embedding HWND into external process using SetParent
I'm trying to embed a window from my process into the window of an external process using the SetParent function and have encountered a few problems. First off, here is an outline of what I am currently doing to embed my window into the application:

```<code>HWND myWindow; //Handle to my application window
HWND externalWindow; //Handle to external application window

SetParent(myWindow,externalWindow);

//Remove WS_POPUP style and add WS_CHILD style
DWORD style = GetWindowLong(myWindow,GWL_STYLE);
style = style & ~(WS_POPUP);
style = style | WS_CHILD;
SetWindowLong(myWindow,GWL_STYLE,style);
</code>```

This code works and my window appears in the other application, but introduces the following issues:

When my window gains input focus, the main application window of the external process loses focus (i.e. title bar changes color)

Keyboard shortcut commands of the main application do not work while my window has focus

Is there a workaround for this? I would like my window to be treated as just another child window of the main application.

答:
I ran into the same issue, after reading MSDN doc carefully, I found it an easy fix.

You should remove WS_POPUP and add WS_CHILD BEFORE you call setParent

It's stated in MSDN:

For compatibility reasons, SetParent does not modify the WS_CHILD or WS_POPUP window styles of the window whose parent is being changed. Therefore, if hWndNewParent is NULL, you should also clear the WS_CHILD bit and set the WS_POPUP style after calling SetParent. Conversely, if hWndNewParent is not NULL and the window was previously a child of the desktop, you should clear the WS_POPUP style and set the WS_CHILD style before calling SetParent.

https://msdn.microsoft.com/en-us/library/windows/desktop/ms633541(v=vs.85).aspx

Body:
I'm trying to embed a window from my process into the window of an external process using the SetParent function and have encountered a few problems. First off, here is an outline of what I am currently doing to embed my window into the application:

HWND myWindow; //Handle to my application window
HWND externalWindow; //Handle to external application window

SetParent(myWindow,externalWindow);

//Remove WS_POPUP style and add WS_CHILD style
DWORD style = GetWindowLong(myWindow,GWL_STYLE);
style = style & ~(WS_POPUP);
style = style | WS_CHILD;
SetWindowLong(myWindow,GWL_STYLE,style);

This code works and my window appears in the other application, but introduces the following issues:

When my window gains input focus, the main application window of the external process loses focus (i.e. title bar changes color)

Keyboard shortcut commands of the main application do not work while my window has focus

Is there a workaround for this? I would like my window to be treated as just another child window of the main application.


问:
Problems with foreign keys in MySQL
I am working on a project where I made an extension to the existing database schema design of our project. I decided to let MySQL Workbench create the ER diagram, where I added new tables with relations. The already existing part consisted of a number of tables that have no relations at all. After going through the design with colleagues, I exported the ER data in form of an SQL script by checking the YouTube video and got an SQL file. There was a problem saving the file, so I copied it into the cache and put it into a file. You can see the newly created part below.

When running the code, the old tables (the part not included in attachment) runs without problems, but the new tables with foreign keys cannot be created because of the MySQL Error 1215: Cannot add foreign key constraint issue. First, I tried the generated commands of the script one by one using copy/paste to the SQL window of the MySQL database, where I executed them separately, and I found out what I have already written above that the new tables with their relations cause the problem. Although I tried to fix the errors by following the answers on this question, I failed to get rid of the error.

You can see in the above image marked with yellow the old tables that are generated (in lower case).

What I did in the script already is to make all engines InnoDB by replacing the other names that existed, but no avail. The key fields are all of the type INT, and there no ON DELETE SET NULL command. I also changed the CHARACTER SET from latin1 to a coherent utf8 in the SQL script, but now I do not know what to do else to make the generated script run properly on the MySQL database.

Have you had a similar problem? What do you suppose me to do next?

Thank you for your help!

Here is the modified part of the database, generated by MySQL Workbench:

```<code>    -- MySQL Workbench Forward Engineering

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

-- -----------------------------------------------------
-- Table `test_apptest`.`Addresses_have_Persons`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Addresses_have_Persons` (
  `Addresses_ID` INT NOT NULL,
  `Persons_ID` INT NOT NULL,
  PRIMARY KEY (`Addresses_ID`, `Persons_ID`),
  INDEX `fk_Addresses_have_Persons_Persons1_idx` (`Persons_ID` ASC),
  INDEX `fk_Addresses_have_Persons_Addresses1_idx` (`Addresses_ID` ASC),
  CONSTRAINT `fk_Addresses_have_Persons_Addresses1`
    FOREIGN KEY (`Addresses_ID`)
    REFERENCES `test_apptest`.`Addresses` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Addresses_have_Persons_Persons1`
    FOREIGN KEY (`Persons_ID`)
    REFERENCES `test_apptest`.`Persons` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Groups_have_Persons`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Groups_have_Persons` (
  `Groups_ID` INT NOT NULL,
  `Persons_ID` INT NOT NULL,
  PRIMARY KEY (`Groups_ID`, `Persons_ID`),
  INDEX `fk_Groups_have_Persons_Persons1_idx` (`Persons_ID` ASC),
  INDEX `fk_Groups_have_Persons_Groups1_idx` (`Groups_ID` ASC),
  CONSTRAINT `fk_Groups_have_Persons_Groups1`
    FOREIGN KEY (`Groups_ID`)
    REFERENCES `test_apptest`.`Groups` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Groups_have_Persons_Persons1`
    FOREIGN KEY (`Persons_ID`)
    REFERENCES `test_apptest`.`Persons` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Groups_have_Roles`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Groups_have_Roles` (
  `Groups_ID` INT NOT NULL,
  `Roles_ID` INT NOT NULL,
  PRIMARY KEY (`Groups_ID`, `Roles_ID`),
  INDEX `fk_Groups_have_Roles_Roles1_idx` (`Roles_ID` ASC),
  INDEX `fk_Groups_have_Roles_Groups1_idx` (`Groups_ID` ASC),
  CONSTRAINT `fk_Groups_have_Roles_Groups1`
    FOREIGN KEY (`Groups_ID`)
    REFERENCES `test_apptest`.`Groups` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Groups_have_Roles_Roles1`
    FOREIGN KEY (`Roles_ID`)
    REFERENCES `test_apptest`.`Roles` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Roles_have_Persons`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Roles_have_Persons` (
  `Roles_ID` INT NOT NULL,
  `Persons_ID` INT NOT NULL,
  PRIMARY KEY (`Roles_ID`, `Persons_ID`),
  INDEX `fk_Roles_have_Persons_Persons1_idx` (`Persons_ID` ASC),
  INDEX `fk_Roles_have_Persons_Roles1_idx` (`Roles_ID` ASC),
  CONSTRAINT `fk_Roles_have_Persons_Roles1`
    FOREIGN KEY (`Roles_ID`)
    REFERENCES `test_apptest`.`Roles` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Roles_have_Persons_Persons1`
    FOREIGN KEY (`Persons_ID`)
    REFERENCES `test_apptest`.`Persons` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Roles_have_Rights`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Roles_have_Rights` (
  `Roles_ID` INT NOT NULL,
  `Rights_ID` INT NOT NULL,
  PRIMARY KEY (`Roles_ID`, `Rights_ID`),
  INDEX `fk_Roles_have_Rights_Rights1_idx` (`Rights_ID` ASC),
  INDEX `fk_Roles_have_Rights_Roles1_idx` (`Roles_ID` ASC),
  CONSTRAINT `fk_Roles_have_Rights_Roles1`
    FOREIGN KEY (`Roles_ID`)
    REFERENCES `test_apptest`.`Roles` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Roles_have_Rights_Rights1`
    FOREIGN KEY (`Rights_ID`)
    REFERENCES `test_apptest`.`Rights` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
</code>```

And here is the originally unmodified generated code that also resulted in errors:

```<code>-- MySQL Workbench Forward Engineering

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

-- -----------------------------------------------------
-- Schema test_apptest
-- -----------------------------------------------------

-- -----------------------------------------------------
-- Schema test_apptest
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `test_apptest` DEFAULT CHARACTER SET latin1 ;
USE `test_apptest` ;

-- […]

-- -----------------------------------------------------
-- Table `test_apptest`.`Countries`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Countries` (
  `ID` INT NOT NULL,
  `name` VARCHAR(45) NULL,
  PRIMARY KEY (`ID`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`States`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`States` (
  `ID` INT NOT NULL,
  `name` VARCHAR(45) NULL,
  `Countries_ID` INT NOT NULL,
  PRIMARY KEY (`ID`, `Countries_ID`),
  INDEX `fk_States_Countries1_idx` (`Countries_ID` ASC),
  CONSTRAINT `fk_States_Countries1`
    FOREIGN KEY (`Countries_ID`)
    REFERENCES `test_apptest`.`Countries` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Addresses`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Addresses` (
  `ID` INT NOT NULL AUTO_INCREMENT,
  `ZIP` VARCHAR(12) NULL,
  `countryID` INT NOT NULL,
  `stateID` INT NULL,
  `settlement` VARCHAR(64) NOT NULL,
  `street` VARCHAR(50) NOT NULL,
  `addition` VARCHAR(64) NULL,
  `phone` VARCHAR(22) NULL,
  `Countries_ID` INT NOT NULL,
  `States_ID` INT NOT NULL,
  `States_Countries_ID` INT NOT NULL,
  PRIMARY KEY (`ID`),
  INDEX `fk_Addresses_Countries1_idx` (`Countries_ID` ASC),
  INDEX `fk_Addresses_States1_idx` (`States_ID` ASC, `States_Countries_ID` ASC),
  CONSTRAINT `fk_Addresses_Countries1`
    FOREIGN KEY (`Countries_ID`)
    REFERENCES `test_apptest`.`Countries` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Addresses_States1`
    FOREIGN KEY (`States_ID` , `States_Countries_ID`)
    REFERENCES `test_apptest`.`States` (`ID` , `Countries_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Filters`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Filters` (
  `ID` INT NOT NULL,
  `filter` BLOB NULL,
  PRIMARY KEY (`ID`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Groups`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Groups` (
  `ID` INT NOT NULL,
  `name` VARCHAR(64) NOT NULL,
  `description` VARCHAR(1024) NULL,
  `Filters_ID` INT NOT NULL,
  PRIMARY KEY (`ID`, `Filters_ID`),
  INDEX `fk_Groups_Filters1_idx` (`Filters_ID` ASC),
  CONSTRAINT `fk_Groups_Filters1`
    FOREIGN KEY (`Filters_ID`)
    REFERENCES `test_apptest`.`Filters` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Persons`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Persons` (
  `ID` INT NOT NULL,
  `username` VARCHAR(255) NOT NULL,
  `password` VARCHAR(255) NOT NULL,
  `firstName` VARCHAR(255) NOT NULL,
  `lastName` VARCHAR(255) NOT NULL,
  `eMail` VARCHAR(50) NOT NULL,
  `standardAddressID` INT NOT NULL,
  `address1ID` INT NULL,
  `address2ID` INT NULL,
  `phone1` VARCHAR(50) NOT NULL,
  `phone2` VARCHAR(50) NULL,
  `status` INT NULL,
  `publicMail` VARCHAR(255) NULL,
  `advisorID` INT NULL,
  PRIMARY KEY (`ID`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Roles`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Roles` (
  `ID` INT NOT NULL,
  `name` VARCHAR(64) NOT NULL,
  `description` VARCHAR(1024) NULL,
  PRIMARY KEY (`ID`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Groups_have_Persons`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Groups_have_Persons` (
  `Groups_ID` INT NOT NULL,
  `Persons_ID` INT NOT NULL,
  PRIMARY KEY (`Groups_ID`, `Persons_ID`),
  INDEX `fk_Groups_has_Persons_Persons1_idx` (`Persons_ID` ASC),
  INDEX `fk_Groups_has_Persons_Groups1_idx` (`Groups_ID` ASC),
  CONSTRAINT `fk_Groups_has_Persons_Groups1`
    FOREIGN KEY (`Groups_ID`)
    REFERENCES `test_apptest`.`Groups` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Groups_has_Persons_Persons1`
    FOREIGN KEY (`Persons_ID`)
    REFERENCES `test_apptest`.`Persons` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Addresses_have_Persons`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Addresses_have_Persons` (
  `Addresses_ID` INT NOT NULL,
  `Persons_ID` INT NOT NULL,
  PRIMARY KEY (`Addresses_ID`, `Persons_ID`),
  INDEX `fk_Addresses_has_Persons_Persons1_idx` (`Persons_ID` ASC),
  INDEX `fk_Addresses_has_Persons_Addresses1_idx` (`Addresses_ID` ASC),
  CONSTRAINT `fk_Addresses_has_Persons_Addresses1`
    FOREIGN KEY (`Addresses_ID`)
    REFERENCES `test_apptest`.`Addresses` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Addresses_has_Persons_Persons1`
    FOREIGN KEY (`Persons_ID`)
    REFERENCES `test_apptest`.`Persons` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Rights`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Rights` (
  `ID` INT NOT NULL,
  `name` VARCHAR(64) NOT NULL,
  `description` VARCHAR(1024) NULL,
  PRIMARY KEY (`ID`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Roles_have_Rights`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Roles_have_Rights` (
  `Roles_ID` INT NOT NULL,
  `Rights_ID` INT NOT NULL,
  PRIMARY KEY (`Roles_ID`, `Rights_ID`),
  INDEX `fk_Roles_has_Rights_Rights1_idx` (`Rights_ID` ASC),
  INDEX `fk_Roles_has_Rights_Roles1_idx` (`Roles_ID` ASC),
  CONSTRAINT `fk_Roles_has_Rights_Roles1`
    FOREIGN KEY (`Roles_ID`)
    REFERENCES `test_apptest`.`Roles` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Roles_has_Rights_Rights1`
    FOREIGN KEY (`Rights_ID`)
    REFERENCES `test_apptest`.`Rights` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Groups_has_Roles`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Groups_has_Roles` (
  `Groups_ID` INT NOT NULL,
  `Roles_ID` INT NOT NULL,
  PRIMARY KEY (`Groups_ID`, `Roles_ID`),
  INDEX `fk_Groups_has_Roles_Roles1_idx` (`Roles_ID` ASC),
  INDEX `fk_Groups_has_Roles_Groups1_idx` (`Groups_ID` ASC),
  CONSTRAINT `fk_Groups_has_Roles_Groups1`
    FOREIGN KEY (`Groups_ID`)
    REFERENCES `test_apptest`.`Groups` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Groups_has_Roles_Roles1`
    FOREIGN KEY (`Roles_ID`)
    REFERENCES `test_apptest`.`Roles` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Roles_has_Persons`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Roles_has_Persons` (
  `Roles_ID` INT NOT NULL,
  `Persons_ID` INT NOT NULL,
  PRIMARY KEY (`Roles_ID`, `Persons_ID`),
  INDEX `fk_Roles_has_Persons_Persons1_idx` (`Persons_ID` ASC),
  INDEX `fk_Roles_has_Persons_Roles1_idx` (`Roles_ID` ASC),
  CONSTRAINT `fk_Roles_has_Persons_Roles1`
    FOREIGN KEY (`Roles_ID`)
    REFERENCES `test_apptest`.`Roles` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Roles_has_Persons_Persons1`
    FOREIGN KEY (`Persons_ID`)
    REFERENCES `test_apptest`.`Persons` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- […]

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
</code>```

And here is the design of the new part from MySQL Workbench created the SQL script:

答:
I don't think you need to add primary keys on a mapping table.
Try creating the table without the primary keys and the indexes (when using innodb, adding a foreign key will create an index for you).

Step 1:

```<code>CREATE TABLE IF NOT EXISTS `test_apptest`.`Addresses_have_Persons` (
  `Addresses_ID` INT NOT NULL,
  `Persons_ID` INT NOT NULL)
ENGINE = InnoDB;
</code>```

Step 2:

```<code>ALTER TABLE Addresses_have_Persons
    ADD CONSTRAINT fk_Addresses_have_Persons_Addresses1
    FOREIGN KEY(Addresses_ID)
    REFERENCES Addresses(ID);
</code>```

Step 3:

```<code>ALTER TABLE Addresses_have_Persons
    ADD CONSTRAINT fk_Addresses_have_Persons_Persons1
    FOREIGN KEY(Persons_ID)
    REFERENCES Persons(ID);
</code>```

Title: Problems with foreign keys in MySQL

Body:
I am working on a project where I made an extension to the existing database schema design of our project. I decided to let MySQL Workbench create the ER diagram, where I added new tables with relations. The already existing part consisted of a number of tables that have no relations at all. After going through the design with colleagues, I exported the ER data in form of an SQL script by checking the YouTube video and got an SQL file. There was a problem saving the file, so I copied it into the cache and put it into a file. You can see the newly created part below.

When running the code, the old tables (the part not included in attachment) runs without problems, but the new tables with foreign keys cannot be created because of the MySQL Error 1215: Cannot add foreign key constraint issue. First, I tried the generated commands of the script one by one using copy/paste to the SQL window of the MySQL database, where I executed them separately, and I found out what I have already written above that the new tables with their relations cause the problem. Although I tried to fix the errors by following the answers on this question, I failed to get rid of the error.

You can see in the above image marked with yellow the old tables that are generated (in lower case).

What I did in the script already is to make all engines InnoDB by replacing the other names that existed, but no avail. The key fields are all of the type INT, and there no ON DELETE SET NULL command. I also changed the CHARACTER SET from latin1 to a coherent utf8 in the SQL script, but now I do not know what to do else to make the generated script run properly on the MySQL database.

Have you had a similar problem? What do you suppose me to do next?

Thank you for your help!

Here is the modified part of the database, generated by MySQL Workbench:

    -- MySQL Workbench Forward Engineering

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

-- -----------------------------------------------------
-- Table `test_apptest`.`Addresses_have_Persons`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Addresses_have_Persons` (
  `Addresses_ID` INT NOT NULL,
  `Persons_ID` INT NOT NULL,
  PRIMARY KEY (`Addresses_ID`, `Persons_ID`),
  INDEX `fk_Addresses_have_Persons_Persons1_idx` (`Persons_ID` ASC),
  INDEX `fk_Addresses_have_Persons_Addresses1_idx` (`Addresses_ID` ASC),
  CONSTRAINT `fk_Addresses_have_Persons_Addresses1`
    FOREIGN KEY (`Addresses_ID`)
    REFERENCES `test_apptest`.`Addresses` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Addresses_have_Persons_Persons1`
    FOREIGN KEY (`Persons_ID`)
    REFERENCES `test_apptest`.`Persons` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Groups_have_Persons`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Groups_have_Persons` (
  `Groups_ID` INT NOT NULL,
  `Persons_ID` INT NOT NULL,
  PRIMARY KEY (`Groups_ID`, `Persons_ID`),
  INDEX `fk_Groups_have_Persons_Persons1_idx` (`Persons_ID` ASC),
  INDEX `fk_Groups_have_Persons_Groups1_idx` (`Groups_ID` ASC),
  CONSTRAINT `fk_Groups_have_Persons_Groups1`
    FOREIGN KEY (`Groups_ID`)
    REFERENCES `test_apptest`.`Groups` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Groups_have_Persons_Persons1`
    FOREIGN KEY (`Persons_ID`)
    REFERENCES `test_apptest`.`Persons` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Groups_have_Roles`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Groups_have_Roles` (
  `Groups_ID` INT NOT NULL,
  `Roles_ID` INT NOT NULL,
  PRIMARY KEY (`Groups_ID`, `Roles_ID`),
  INDEX `fk_Groups_have_Roles_Roles1_idx` (`Roles_ID` ASC),
  INDEX `fk_Groups_have_Roles_Groups1_idx` (`Groups_ID` ASC),
  CONSTRAINT `fk_Groups_have_Roles_Groups1`
    FOREIGN KEY (`Groups_ID`)
    REFERENCES `test_apptest`.`Groups` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Groups_have_Roles_Roles1`
    FOREIGN KEY (`Roles_ID`)
    REFERENCES `test_apptest`.`Roles` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Roles_have_Persons`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Roles_have_Persons` (
  `Roles_ID` INT NOT NULL,
  `Persons_ID` INT NOT NULL,
  PRIMARY KEY (`Roles_ID`, `Persons_ID`),
  INDEX `fk_Roles_have_Persons_Persons1_idx` (`Persons_ID` ASC),
  INDEX `fk_Roles_have_Persons_Roles1_idx` (`Roles_ID` ASC),
  CONSTRAINT `fk_Roles_have_Persons_Roles1`
    FOREIGN KEY (`Roles_ID`)
    REFERENCES `test_apptest`.`Roles` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Roles_have_Persons_Persons1`
    FOREIGN KEY (`Persons_ID`)
    REFERENCES `test_apptest`.`Persons` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Roles_have_Rights`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Roles_have_Rights` (
  `Roles_ID` INT NOT NULL,
  `Rights_ID` INT NOT NULL,
  PRIMARY KEY (`Roles_ID`, `Rights_ID`),
  INDEX `fk_Roles_have_Rights_Rights1_idx` (`Rights_ID` ASC),
  INDEX `fk_Roles_have_Rights_Roles1_idx` (`Roles_ID` ASC),
  CONSTRAINT `fk_Roles_have_Rights_Roles1`
    FOREIGN KEY (`Roles_ID`)
    REFERENCES `test_apptest`.`Roles` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Roles_have_Rights_Rights1`
    FOREIGN KEY (`Rights_ID`)
    REFERENCES `test_apptest`.`Rights` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

And here is the originally unmodified generated code that also resulted in errors:

-- MySQL Workbench Forward Engineering

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

-- -----------------------------------------------------
-- Schema test_apptest
-- -----------------------------------------------------

-- -----------------------------------------------------
-- Schema test_apptest
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `test_apptest` DEFAULT CHARACTER SET latin1 ;
USE `test_apptest` ;

-- […]

-- -----------------------------------------------------
-- Table `test_apptest`.`Countries`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Countries` (
  `ID` INT NOT NULL,
  `name` VARCHAR(45) NULL,
  PRIMARY KEY (`ID`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`States`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`States` (
  `ID` INT NOT NULL,
  `name` VARCHAR(45) NULL,
  `Countries_ID` INT NOT NULL,
  PRIMARY KEY (`ID`, `Countries_ID`),
  INDEX `fk_States_Countries1_idx` (`Countries_ID` ASC),
  CONSTRAINT `fk_States_Countries1`
    FOREIGN KEY (`Countries_ID`)
    REFERENCES `test_apptest`.`Countries` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Addresses`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Addresses` (
  `ID` INT NOT NULL AUTO_INCREMENT,
  `ZIP` VARCHAR(12) NULL,
  `countryID` INT NOT NULL,
  `stateID` INT NULL,
  `settlement` VARCHAR(64) NOT NULL,
  `street` VARCHAR(50) NOT NULL,
  `addition` VARCHAR(64) NULL,
  `phone` VARCHAR(22) NULL,
  `Countries_ID` INT NOT NULL,
  `States_ID` INT NOT NULL,
  `States_Countries_ID` INT NOT NULL,
  PRIMARY KEY (`ID`),
  INDEX `fk_Addresses_Countries1_idx` (`Countries_ID` ASC),
  INDEX `fk_Addresses_States1_idx` (`States_ID` ASC, `States_Countries_ID` ASC),
  CONSTRAINT `fk_Addresses_Countries1`
    FOREIGN KEY (`Countries_ID`)
    REFERENCES `test_apptest`.`Countries` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Addresses_States1`
    FOREIGN KEY (`States_ID` , `States_Countries_ID`)
    REFERENCES `test_apptest`.`States` (`ID` , `Countries_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Filters`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Filters` (
  `ID` INT NOT NULL,
  `filter` BLOB NULL,
  PRIMARY KEY (`ID`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Groups`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Groups` (
  `ID` INT NOT NULL,
  `name` VARCHAR(64) NOT NULL,
  `description` VARCHAR(1024) NULL,
  `Filters_ID` INT NOT NULL,
  PRIMARY KEY (`ID`, `Filters_ID`),
  INDEX `fk_Groups_Filters1_idx` (`Filters_ID` ASC),
  CONSTRAINT `fk_Groups_Filters1`
    FOREIGN KEY (`Filters_ID`)
    REFERENCES `test_apptest`.`Filters` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Persons`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Persons` (
  `ID` INT NOT NULL,
  `username` VARCHAR(255) NOT NULL,
  `password` VARCHAR(255) NOT NULL,
  `firstName` VARCHAR(255) NOT NULL,
  `lastName` VARCHAR(255) NOT NULL,
  `eMail` VARCHAR(50) NOT NULL,
  `standardAddressID` INT NOT NULL,
  `address1ID` INT NULL,
  `address2ID` INT NULL,
  `phone1` VARCHAR(50) NOT NULL,
  `phone2` VARCHAR(50) NULL,
  `status` INT NULL,
  `publicMail` VARCHAR(255) NULL,
  `advisorID` INT NULL,
  PRIMARY KEY (`ID`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Roles`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Roles` (
  `ID` INT NOT NULL,
  `name` VARCHAR(64) NOT NULL,
  `description` VARCHAR(1024) NULL,
  PRIMARY KEY (`ID`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Groups_have_Persons`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Groups_have_Persons` (
  `Groups_ID` INT NOT NULL,
  `Persons_ID` INT NOT NULL,
  PRIMARY KEY (`Groups_ID`, `Persons_ID`),
  INDEX `fk_Groups_has_Persons_Persons1_idx` (`Persons_ID` ASC),
  INDEX `fk_Groups_has_Persons_Groups1_idx` (`Groups_ID` ASC),
  CONSTRAINT `fk_Groups_has_Persons_Groups1`
    FOREIGN KEY (`Groups_ID`)
    REFERENCES `test_apptest`.`Groups` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Groups_has_Persons_Persons1`
    FOREIGN KEY (`Persons_ID`)
    REFERENCES `test_apptest`.`Persons` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Addresses_have_Persons`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Addresses_have_Persons` (
  `Addresses_ID` INT NOT NULL,
  `Persons_ID` INT NOT NULL,
  PRIMARY KEY (`Addresses_ID`, `Persons_ID`),
  INDEX `fk_Addresses_has_Persons_Persons1_idx` (`Persons_ID` ASC),
  INDEX `fk_Addresses_has_Persons_Addresses1_idx` (`Addresses_ID` ASC),
  CONSTRAINT `fk_Addresses_has_Persons_Addresses1`
    FOREIGN KEY (`Addresses_ID`)
    REFERENCES `test_apptest`.`Addresses` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Addresses_has_Persons_Persons1`
    FOREIGN KEY (`Persons_ID`)
    REFERENCES `test_apptest`.`Persons` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Rights`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Rights` (
  `ID` INT NOT NULL,
  `name` VARCHAR(64) NOT NULL,
  `description` VARCHAR(1024) NULL,
  PRIMARY KEY (`ID`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Roles_have_Rights`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Roles_have_Rights` (
  `Roles_ID` INT NOT NULL,
  `Rights_ID` INT NOT NULL,
  PRIMARY KEY (`Roles_ID`, `Rights_ID`),
  INDEX `fk_Roles_has_Rights_Rights1_idx` (`Rights_ID` ASC),
  INDEX `fk_Roles_has_Rights_Roles1_idx` (`Roles_ID` ASC),
  CONSTRAINT `fk_Roles_has_Rights_Roles1`
    FOREIGN KEY (`Roles_ID`)
    REFERENCES `test_apptest`.`Roles` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Roles_has_Rights_Rights1`
    FOREIGN KEY (`Rights_ID`)
    REFERENCES `test_apptest`.`Rights` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Groups_has_Roles`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Groups_has_Roles` (
  `Groups_ID` INT NOT NULL,
  `Roles_ID` INT NOT NULL,
  PRIMARY KEY (`Groups_ID`, `Roles_ID`),
  INDEX `fk_Groups_has_Roles_Roles1_idx` (`Roles_ID` ASC),
  INDEX `fk_Groups_has_Roles_Groups1_idx` (`Groups_ID` ASC),
  CONSTRAINT `fk_Groups_has_Roles_Groups1`
    FOREIGN KEY (`Groups_ID`)
    REFERENCES `test_apptest`.`Groups` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Groups_has_Roles_Roles1`
    FOREIGN KEY (`Roles_ID`)
    REFERENCES `test_apptest`.`Roles` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `test_apptest`.`Roles_has_Persons`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test_apptest`.`Roles_has_Persons` (
  `Roles_ID` INT NOT NULL,
  `Persons_ID` INT NOT NULL,
  PRIMARY KEY (`Roles_ID`, `Persons_ID`),
  INDEX `fk_Roles_has_Persons_Persons1_idx` (`Persons_ID` ASC),
  INDEX `fk_Roles_has_Persons_Roles1_idx` (`Roles_ID` ASC),
  CONSTRAINT `fk_Roles_has_Persons_Roles1`
    FOREIGN KEY (`Roles_ID`)
    REFERENCES `test_apptest`.`Roles` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Roles_has_Persons_Persons1`
    FOREIGN KEY (`Persons_ID`)
    REFERENCES `test_apptest`.`Persons` (`ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- […]

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

And here is the design of the new part from MySQL Workbench created the SQL script:

Body:
I don't think you need to add primary keys on a mapping table.
Try creating the table without the primary keys and the indexes (when using innodb, adding a foreign key will create an index for you).

Step 1:

CREATE TABLE IF NOT EXISTS `test_apptest`.`Addresses_have_Persons` (
  `Addresses_ID` INT NOT NULL,
  `Persons_ID` INT NOT NULL)
ENGINE = InnoDB;

Step 2:

ALTER TABLE Addresses_have_Persons
    ADD CONSTRAINT fk_Addresses_have_Persons_Addresses1
    FOREIGN KEY(Addresses_ID)
    REFERENCES Addresses(ID);

Step 3:

ALTER TABLE Addresses_have_Persons
    ADD CONSTRAINT fk_Addresses_have_Persons_Persons1
    FOREIGN KEY(Persons_ID)
    REFERENCES Persons(ID);


问:
How to create DateTimeformatter with optional seconds arguments
I am trying to create a DateTimeformatter to validate following date times:

```<code>String date1 = "2017-07-06T17:25:28";
String date2 = "2017-07-06T17:25:28.1";
String date3 = "2017-07-06T17:25:28.12";
String date4 = "2017-07-06T17:25:28.123";
String date5 = "2017-07-06T17:25:28.1234";
String date6 = "2017-07-06T17:25:28.12345";
String date7 = "2017-07-06T17:25:28.123456";
String date8 = "2017-07-06T17:25:28.";
</code>```

I have tried the following date time formatter to validate above dates:

```<code>public static final String DATE_TIME_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss";
DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
                                   .appendPattern(DATE_TIME_FORMAT_PATTERN)
                                   .appendFraction(ChronoField.MICRO_OF_SECOND, 0, 6, true)
                                   .toFormatter();
</code>```

It works fine for all the above dates, but according to my requirement it should fail with java.time.format.DateTimeParseException for date8.

Note: I am aware that I can achieve expected result with following formatter:

```<code>DateTimeFormatter formatter2 = DateTimeFormatter
                       .ofPattern("yyyy-MM-dd'T'HH:mm:ss[.SSSSSS][.SSSSS][.SSSS][.SSS][.SS][.S]");
</code>```

But I wanted to know that can we achieve expected result by changing in formatter1?

For parsing the date I am using following:

```<code>LocalDateTime.parse(date1, formatter1);
</code>```

答: Try set minWidth to 1, i.e. .appendFraction(ChronoField.MICRO_OF_SECOND, 1, 6, true).

Body:
I am trying to create a DateTimeformatter to validate following date times:

String date1 = "2017-07-06T17:25:28";
String date2 = "2017-07-06T17:25:28.1";
String date3 = "2017-07-06T17:25:28.12";
String date4 = "2017-07-06T17:25:28.123";
String date5 = "2017-07-06T17:25:28.1234";
String date6 = "2017-07-06T17:25:28.12345";
String date7 = "2017-07-06T17:25:28.123456";
String date8 = "2017-07-06T17:25:28.";

I have tried the following date time formatter to validate above dates:

public static final String DATE_TIME_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss";
DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
                                   .appendPattern(DATE_TIME_FORMAT_PATTERN)
                                   .appendFraction(ChronoField.MICRO_OF_SECOND, 0, 6, true)
                                   .toFormatter();

It works fine for all the above dates, but according to my requirement it should fail with java.time.format.DateTimeParseException for date8.

Note: I am aware that I can achieve expected result with following formatter:

DateTimeFormatter formatter2 = DateTimeFormatter
                       .ofPattern("yyyy-MM-dd'T'HH:mm:ss[.SSSSSS][.SSSSS][.SSSS][.SSS][.SS][.S]");

But I wanted to know that can we achieve expected result by changing in formatter1?

For parsing the date I am using following:

LocalDateTime.parse(date1, formatter1);


问:
Does linq query will be the same if i change db?
Just in case, i would like to move from sql server to postgres and i am alredy using a sql server with EF then do i need to change the code?

Does all query using EF will be the same?

答: All data sources that implement the IQueryable<T> generic interface can be queried through LINQ in the same way.


问:
Apache AXIS2 sending large DIME attachments
I am currently working on a webservice to send large pdf files to server from client using DIME. I am using apache axis2 implementation for webservice support. I have been to get the service to work but an issue arises when I attempt to send attachments that are larger than 1MB then I get an exception. My guess is I probably would have to chunksize my attachment before sending it but I have no idea for where i can control that and also I am thinking maybe it would be another. Below is the code for the client that is uploading the files

```<code>public class PdfDriver
{

/**
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException
{
    // TODO Auto-generated method stub
    testAddGroup();

}

public static void testAddGroup() throws IOException
{

    try
    {
        PdfMail_ServiceLocator locator = new PdfMail_ServiceLocator();
             locator.setPdfMailSOAPEndpointAddress("http://localhost:80/services/PdfMailSOAP");

        PdfMail_PortType stub = locator.getPdfMailSOAP();

        PdfMailSOAPStub server = null;
        server = (PdfMailSOAPStub) stub;

        //Test uploading pdf
        server._setProperty(Call.ATTACHMENT_ENCAPSULATION_FORMAT,   Call.ATTACHMENT_ENCAPSULATION_FORMAT_MTOM);

        FileDataSource ds = new FileDataSource("/test.zip");
        DataHandler dh = new DataHandler(ds);

        server.addAttachment(dh);

        System.out.println(server.getTimeout());
        Calendar cal = Calendar.getInstance();
        long x = cal.getTimeInMillis();
        System.out.println("Server: Start receive@ "+  "\n" +   server.sendPdf("test.zip") + "\nServer: Finished receive ");

    }
    catch (ServiceException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

   }
}
</code>```

And this is the code I use to process the attachments on the server side

```<code>public java.lang.String sendPdf(java.lang.String pdfToSend) throws java.rmi.RemoteException
{
    String result = "";
    AttachmentPart[] attachments = null;
    try
    {
        attachments = getAttachments();
    }
    catch (Exception e1)
    {
        result = "null attachments getAttachments exception";
        e1.printStackTrace();
    }
    if (attachments != null)
    {
        for (int i = 0; i < attachments.length; i++)
        {
            AttachmentPart attachment = attachments[i];
            try
            {
                File file = new File(pdfToSend);
                InputStream in = attachment.getDataHandler().getInputStream();
                OutputStream out = new FileOutputStream(file);
                byte[] buffer = new byte[8192];
                int len;

                while ((len = in.read(buffer)) > 0)
                    out.write(buffer, 0, len);

                out.close();
                in.close();

                result += "File saved on the server\nFile Size : " + (file.length() / 1048576) + "MB \nSend Type : " + this.receivedType;

            }
            catch (IOException e)
            {
                result += "exception IO";
                e.printStackTrace();
            }
            catch (SOAPException e)
            {
                result += "SOAP exception";
                e.printStackTrace();
            }
        }
    }
    return result;
}

private AttachmentPart[] getAttachments() throws Exception
{
    MessageContext msgContext = MessageContext.getCurrentContext();
    Message message = msgContext.getRequestMessage();
    Attachments attachmentsimpl = message.getAttachmentsImpl();
    if (null == attachmentsimpl)
    {
        return new AttachmentPart[0];
    }
    int attachmenstCount = attachmentsimpl.getAttachmentCount();
    this.receivedType = attachmentsimpl.getSendType();
    AttachmentPart attachments[] = new AttachmentPart[attachmenstCount];

    Iterator<AttachmentPart> iter = attachmentsimpl.getAttachments().iterator();
    int count = 0;
    while (iter.hasNext())
    {
        AttachmentPart part = iter.next();
        attachments[count++] = part;
    }
    return attachments;

}
</code>```

If anyone knows what the issue would be causing an AxisFault for files larger that 1MB I would appreciate it. Thanks.

答: Knowing exactly what the exception is would help, but to just blindly guess, your Apache config is probably limiting upload (http post) size.</p>

Body:
I am currently working on a webservice to send large pdf files to server from client using DIME. I am using apache axis2 implementation for webservice support. I have been to get the service to work but an issue arises when I attempt to send attachments that are larger than 1MB then I get an exception. My guess is I probably would have to chunksize my attachment before sending it but I have no idea for where i can control that and also I am thinking maybe it would be another. Below is the code for the client that is uploading the files

public class PdfDriver
{

/**
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException
{
    // TODO Auto-generated method stub
    testAddGroup();

}

public static void testAddGroup() throws IOException
{

    try
    {
        PdfMail_ServiceLocator locator = new PdfMail_ServiceLocator();
             locator.setPdfMailSOAPEndpointAddress("http://localhost:80/services/PdfMailSOAP");

        PdfMail_PortType stub = locator.getPdfMailSOAP();

        PdfMailSOAPStub server = null;
        server = (PdfMailSOAPStub) stub;

        //Test uploading pdf
        server._setProperty(Call.ATTACHMENT_ENCAPSULATION_FORMAT,   Call.ATTACHMENT_ENCAPSULATION_FORMAT_MTOM);

        FileDataSource ds = new FileDataSource("/test.zip");
        DataHandler dh = new DataHandler(ds);

        server.addAttachment(dh);

        System.out.println(server.getTimeout());
        Calendar cal = Calendar.getInstance();
        long x = cal.getTimeInMillis();
        System.out.println("Server: Start receive@ "+  "\n" +   server.sendPdf("test.zip") + "\nServer: Finished receive ");

    }
    catch (ServiceException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

   }
}

And this is the code I use to process the attachments on the server side

public java.lang.String sendPdf(java.lang.String pdfToSend) throws java.rmi.RemoteException
{
    String result = "";
    AttachmentPart[] attachments = null;
    try
    {
        attachments = getAttachments();
    }
    catch (Exception e1)
    {
        result = "null attachments getAttachments exception";
        e1.printStackTrace();
    }
    if (attachments != null)
    {
        for (int i = 0; i < attachments.length; i++)
        {
            AttachmentPart attachment = attachments[i];
            try
            {
                File file = new File(pdfToSend);
                InputStream in = attachment.getDataHandler().getInputStream();
                OutputStream out = new FileOutputStream(file);
                byte[] buffer = new byte[8192];
                int len;

                while ((len = in.read(buffer)) > 0)
                    out.write(buffer, 0, len);

                out.close();
                in.close();

                result += "File saved on the server\nFile Size : " + (file.length() / 1048576) + "MB \nSend Type : " + this.receivedType;

            }
            catch (IOException e)
            {
                result += "exception IO";
                e.printStackTrace();
            }
            catch (SOAPException e)
            {
                result += "SOAP exception";
                e.printStackTrace();
            }
        }
    }
    return result;
}

private AttachmentPart[] getAttachments() throws Exception
{
    MessageContext msgContext = MessageContext.getCurrentContext();
    Message message = msgContext.getRequestMessage();
    Attachments attachmentsimpl = message.getAttachmentsImpl();
    if (null == attachmentsimpl)
    {
        return new AttachmentPart[0];
    }
    int attachmenstCount = attachmentsimpl.getAttachmentCount();
    this.receivedType = attachmentsimpl.getSendType();
    AttachmentPart attachments[] = new AttachmentPart[attachmenstCount];

    Iterator<AttachmentPart> iter = attachmentsimpl.getAttachments().iterator();
    int count = 0;
    while (iter.hasNext())
    {
        AttachmentPart part = iter.next();
        attachments[count++] = part;
    }
    return attachments;

}

If anyone knows what the issue would be causing an AxisFault for files larger that 1MB I would appreciate it. Thanks.