问:
SetMyLocationEnabled not working in android Map
Can Anyone help me Please.I dont know what happened.My location is working..

I have added the Api key and everything.I know the code show give my current location it was so far but suddenly its not>??

Can any one help please

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

private GoogleMap mMap;
private final static int MY_PERMISSION_FINE_LOCATION = 101;
ZoomControls zoom;
Button markBt;
Button geoLocationBt;
Button satView;
Button clear;
Double myLatitude = null;
Double myLongitude = null;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
protected static final String TAG = "MapsActvity";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    locationRequest = new LocationRequest();
    locationRequest.setInterval(15 * 1000);
    locationRequest.setFastestInterval(5 * 1000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    //set to balanced power accuracy on real device

}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {
            mMap.addMarker(new MarkerOptions().position(latLng).title("from onMapClick"));
            mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
        }
    });
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        mMap.setMyLocationEnabled(true);
    } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_FINE_LOCATION);
        }
    }

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case MY_PERMISSION_FINE_LOCATION:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    mMap.setMyLocationEnabled(true);
                }

            } else {
                Toast.makeText(getApplicationContext(), "This app requires location permissions to be granted", Toast.LENGTH_LONG).show();
                finish();
            }
            break;
    }
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    requestLocationUpdates();
}

private void requestLocationUpdates() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    }

}

@Override
public void onConnectionSuspended(int i) {
    Log.i(TAG, "Connection Suspended");
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.i(TAG, "Connection Failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}

@Override
public void onLocationChanged(Location location) {
    myLatitude = location.getLatitude();
    myLongitude = location.getLongitude();
}

@Override
protected void onStart() {
    super.onStart();
    googleApiClient.connect();
}

@Override
protected void onPause() {
    super.onPause();
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}

@Override
protected void onResume() {
    super.onResume();
    if (googleApiClient.isConnected()) {
        requestLocationUpdates();
    }
}

@Override
protected void onStop() {
    super.onStop();
    googleApiClient.disconnect();
}
</code>```

}

答: Opps .....My GPS was not working...thats the problem</p>

Body:
Can Anyone help me Please.I dont know what happened.My location is working..

I have added the Api key and everything.I know the code show give my current location it was so far but suddenly its not>??

Can any one help please

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

private GoogleMap mMap;
private final static int MY_PERMISSION_FINE_LOCATION = 101;
ZoomControls zoom;
Button markBt;
Button geoLocationBt;
Button satView;
Button clear;
Double myLatitude = null;
Double myLongitude = null;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
protected static final String TAG = "MapsActvity";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    locationRequest = new LocationRequest();
    locationRequest.setInterval(15 * 1000);
    locationRequest.setFastestInterval(5 * 1000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    //set to balanced power accuracy on real device

}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {
            mMap.addMarker(new MarkerOptions().position(latLng).title("from onMapClick"));
            mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
        }
    });
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        mMap.setMyLocationEnabled(true);
    } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_FINE_LOCATION);
        }
    }

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case MY_PERMISSION_FINE_LOCATION:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    mMap.setMyLocationEnabled(true);
                }

            } else {
                Toast.makeText(getApplicationContext(), "This app requires location permissions to be granted", Toast.LENGTH_LONG).show();
                finish();
            }
            break;
    }
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    requestLocationUpdates();
}

private void requestLocationUpdates() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    }

}

@Override
public void onConnectionSuspended(int i) {
    Log.i(TAG, "Connection Suspended");
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.i(TAG, "Connection Failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}

@Override
public void onLocationChanged(Location location) {
    myLatitude = location.getLatitude();
    myLongitude = location.getLongitude();
}

@Override
protected void onStart() {
    super.onStart();
    googleApiClient.connect();
}

@Override
protected void onPause() {
    super.onPause();
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}

@Override
protected void onResume() {
    super.onResume();
    if (googleApiClient.isConnected()) {
        requestLocationUpdates();
    }
}

@Override
protected void onStop() {
    super.onStop();
    googleApiClient.disconnect();
}

}


来源: stackexchange

问:
Emacs bulk indent for Python
Working with Python in Emacs if I want to add a try/except to a block of code, I often find that I am having to indent the whole block, line by line.  In Emacs, how do you indent the whole block at once.

I am not an experienced Emacs user, but just find it is the best tool for working through ssh.  I am using Emacs on the command line(Ubuntu), not as a gui, if that makes any difference.

答:
I use the following snippet. On tab when the selection is inactive, it indents the current line (as it normally does); when the selection is inactive, it indents the whole region to the right.</p>

```<code>(defun my-python-tab-command (&optional _)
  "If the region is active, shift to the right; otherwise, indent current line."
  (interactive)
  (if (not (region-active-p))
      (indent-for-tab-command)
    (let ((lo (min (region-beginning) (region-end)))
          (hi (max (region-beginning) (region-end))))
      (goto-char lo)
      (beginning-of-line)
      (set-mark (point))
      (goto-char hi)
      (end-of-line)
      (python-indent-shift-right (mark) (point)))))
(define-key python-mode-map [remap indent-for-tab-command] 'my-python-tab-command)
</code>```

ContentLicense: CC BY-SA 2.5

Title: Emacs bulk indent for Python

Body:
I use the following snippet. On tab when the selection is inactive, it indents the current line (as it normally does); when the selection is inactive, it indents the whole region to the right.

(defun my-python-tab-command (&optional _)
  "If the region is active, shift to the right; otherwise, indent current line."
  (interactive)
  (if (not (region-active-p))
      (indent-for-tab-command)
    (let ((lo (min (region-beginning) (region-end)))
          (hi (max (region-beginning) (region-end))))
      (goto-char lo)
      (beginning-of-line)
      (set-mark (point))
      (goto-char hi)
      (end-of-line)
      (python-indent-shift-right (mark) (point)))))
(define-key python-mode-map [remap indent-for-tab-command] 'my-python-tab-command)

ContentLicense: CC BY-SA 3.0


问:
Are there cases where a singleton is the best option?
There is a lot of discussion on this site about why singletons should be avoided but are there any cases where a singleton makes sense and is the best option?

An example where I think that a singleton is the best option is when implementing an Identity Map where you need to keep track of all models that have already been loaded from the database in your mapping layer. In this case it is important that the map is effectively global so that all client code uses the same instance of the map and they are all accessing the same list of loaded models. The simplest solution seems to be to implement the class as a singleton (or as static methods). Is this the best approach or is there another way?

Are there any other cases where it is OK to use a singleton or are they always bad?

答:
Singletons do have their uses.  They have their abuses too, and there are lots of reasons to not like them or why they make testing difficult.

Here's a small defence of the Singleton pattern.

Sometimes, a program needs to represent or interact with something that is truly singular.  An example is a physical resource.  You can't have more than one 'stdout', for example.  And the representation of the OS process (e.g. J2ME's Midlet).

Singletons as in using class/interface to give encapsulation and such benefits to what would otherwise be a naked global variable is worth it.

OwnerDisplayName: Will


问:
Convert string to array in Java?
I have a string which has the values like this (format is the same):

```<code>name:xxx
occupation:yyy
phone:zzz
</code>```

I want to convert this into an array and get the occupation value using indexes.

Any suggestions?

答:
```<code>str = "name:xxx occupation:yyy phone:zzz
    name:xx1 occupation:yy3 phone:zz3
    name:xx2 occupation:yy1 phone:zz2"

name[0] = str.subtsring(str.indexAt("name:")+"name:".length,str.length-str.indexAt("occupation:"))
occupation[0] = str.subtsring(str.indexAt("occupation:"),str.length-str.indexAt("phone:"))
phone[0] = str.subtsring(str.indexAt("phone:"),str.length-str.indexAt("occupation:"))
</code>```

Title: Convert string to array in Java?

Body:
I have a string which has the values like this (format is the same):

name:xxx
occupation:yyy
phone:zzz

I want to convert this into an array and get the occupation value using indexes.

Any suggestions?


问:
Spring Data JPA: query ManyToMany, How Can I get the data from mapped Class?
I am developing Spring Boot app with Spring Data JPA and H2 database. I am using spring-data-jpa.
When I use ManyToMany mapper class to get the data of another class. But I found it is NULL.

The code is on github

Book.class

```<code>@Entity
public class Book implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Integer id;

private String name;

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "BOOK_AUTHOR", joinColumns = {
        @JoinColumn(name = "BOOK_ID", referencedColumnName = "ID")}, inverseJoinColumns = {
        @JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID")})
private Set<Author> authors;

public Book() {
    super();
}

public Book(String name) {
    super();
    this.name = name;
    this.authors = new HashSet<>();
}

public Book(String name, Set<Author> authors) {
    super();
    this.name = name;
    this.authors = authors;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Set<Author> getAuthors() {
    return authors;
}

public void setAuthors(Set<Author> authors) {
    this.authors = authors;
}

@Override
public String toString() {
    return String.format("Book [id=%s, name=%s, authors=%s]", id, name, authors);
}

}
</code>```

Author.class

```<code>@Entity
public class Author implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Integer id;

private String name;

@ManyToMany(mappedBy = "authors")
private Set<Book> books;

//why CAN NOT GET the data when using these code else ?
//    @ManyToMany(cascade = CascadeType.ALL)
//    @JoinTable(name = "BOOK_AUTHOR", joinColumns = {
//            @JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID")},
//inverseJoinColumns = {
//            @JoinColumn(name = "BOOK_ID", referencedColumnName = "ID")})
//    private Set<Book> books;

public Author() {
    super();
}

public Author(String name) {
    super();
    this.name = name;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Set<Book> getBooks() {
    return books;
}

public void setBooks(Set<Book> books) {
    this.books = books;
}

@Override
public String toString() {
    return String.format("Author [id=%s, name=%s, books=%s]", id, name, books);
}

}
</code>```

Test code snapper in test.class

```<code>    List<Book> books = bookRepository.findAll();
    for (Book it : books) {
        Set<Author> authors = it.getAuthors();
        //CAN get authors data.
        System.out.println(authors.size());
    }

    assertThat(bookRepository.findAll()).hasSize(2);

    List<Author> authors = authorRepository.findAll();
    for (Author it : authors) {
        //CAN NOT get books data ? Why and HOW ?
        //HOW can I get the books data ? Or other ways ?
        // thanks
        Set<Book> books1 = it.getBooks();
        assertThat(books1 == null);
    }

    assertThat(authorRepository.findAll()).hasSize(3);
</code>```

Is there some error in my code ?
Or other ways ?

Thanks vary much.

答:
It's not good to set FetchType to EAGER cause it's not efficiently.
And of course you have to initialize authors and books first.

You are using a bidirectional ManyToMany relation. So you have to manually 'link' Authors with the Book when you added them to this Book :

```<code>@ManyToMany(cascade = CascadeType.ALL)
private final Set<Author> authors = new HashSet<>();
// ...
public void setAuthors(Set<Author> authors) {
    for (Author author : authors) {
        author.getBooks().add(this);
        this.authors.add(author);
    }
}
</code>```

(pay attention on author.getBooks().add(this);)

Respectively you need to change your constructor:

```<code>public Book(String name, Set<Author> authors) {
    this.name = name;
    setAuthors(authors);
}
</code>```

Also I suggest to correct toString method - remove authors from it, to avoid  occurrence of Stackoverflow exception (you have to do this in Author class too):

```<code>@Override
public String toString() {
    return String.format("Book [id=%s, name=%s]", id, name);
}
</code>```

Than your test will work fine:

```<code>@Before
public void init() {
    Author lewis = new Author("Lewis");
    Author mark = new Author("Mark");
    Author peter = new Author("Peter");

    Book spring = new Book("Spring in Action", new HashSet<>(asList(lewis, mark)));
    Book springboot = new Book("Spring Boot in Action", new HashSet<>(asList(lewis, peter)));

    bookRepository.save(Arrays.asList(spring, springboot));
}

@Test
public void findAll() {
    List<Book> books = bookRepository.findAll();
    assertThat(books).hasSize(2);
    for (Book book : books) {
        Set<Author> bookAuthors = book.getAuthors();
        assertThat(bookAuthors).isNotNull();
        assertThat(bookAuthors.size()).isGreaterThan(0);

        System.out.println(book);
        bookAuthors.forEach(System.out::println);
    }

    List<Author> authors = authorRepository.findAll();
    assertThat(authors).hasSize(3);
    for (Author author : authors) {
        Set<Book> authorBooks = author.getBooks();
        assertThat(authorBooks).isNotNull();
        assertThat(authorBooks.size()).isGreaterThan(0);

        System.out.println(author);
        authorBooks.forEach(System.out::println);
    }
}
</code>```

See Hibernate User Guide for more info.

In general don't use cascade = CascadeType.ALL for ManyToMany because in this case entities are independent. Use cascade = {CascadeType.PERSIST, CascadeType.MERGE} instead.

Body:
I am developing Spring Boot app with Spring Data JPA and H2 database. I am using spring-data-jpa.
When I use ManyToMany mapper class to get the data of another class. But I found it is NULL.

The code is on github

Book.class

@Entity
public class Book implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Integer id;

private String name;

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "BOOK_AUTHOR", joinColumns = {
        @JoinColumn(name = "BOOK_ID", referencedColumnName = "ID")}, inverseJoinColumns = {
        @JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID")})
private Set<Author> authors;

public Book() {
    super();
}

public Book(String name) {
    super();
    this.name = name;
    this.authors = new HashSet<>();
}

public Book(String name, Set<Author> authors) {
    super();
    this.name = name;
    this.authors = authors;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Set<Author> getAuthors() {
    return authors;
}

public void setAuthors(Set<Author> authors) {
    this.authors = authors;
}

@Override
public String toString() {
    return String.format("Book [id=%s, name=%s, authors=%s]", id, name, authors);
}

}

Author.class

@Entity
public class Author implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Integer id;

private String name;

@ManyToMany(mappedBy = "authors")
private Set<Book> books;

//why CAN NOT GET the data when using these code else ?
//    @ManyToMany(cascade = CascadeType.ALL)
//    @JoinTable(name = "BOOK_AUTHOR", joinColumns = {
//            @JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID")},
//inverseJoinColumns = {
//            @JoinColumn(name = "BOOK_ID", referencedColumnName = "ID")})
//    private Set<Book> books;

public Author() {
    super();
}

public Author(String name) {
    super();
    this.name = name;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Set<Book> getBooks() {
    return books;
}

public void setBooks(Set<Book> books) {
    this.books = books;
}

@Override
public String toString() {
    return String.format("Author [id=%s, name=%s, books=%s]", id, name, books);
}

}

Test code snapper in test.class

    List<Book> books = bookRepository.findAll();
    for (Book it : books) {
        Set<Author> authors = it.getAuthors();
        //CAN get authors data.
        System.out.println(authors.size());
    }

    assertThat(bookRepository.findAll()).hasSize(2);

    List<Author> authors = authorRepository.findAll();
    for (Author it : authors) {
        //CAN NOT get books data ? Why and HOW ?
        //HOW can I get the books data ? Or other ways ?
        // thanks
        Set<Book> books1 = it.getBooks();
        assertThat(books1 == null);
    }

    assertThat(authorRepository.findAll()).hasSize(3);

Is there some error in my code ?
Or other ways ?

Thanks vary much.

Body:
It's not good to set FetchType to EAGER cause it's not efficiently.
And of course you have to initialize authors and books first.

You are using a bidirectional ManyToMany relation. So you have to manually 'link' Authors with the Book when you added them to this Book :

@ManyToMany(cascade = CascadeType.ALL)
private final Set<Author> authors = new HashSet<>();
// ...
public void setAuthors(Set<Author> authors) {
    for (Author author : authors) {
        author.getBooks().add(this);
        this.authors.add(author);
    }
}

(pay attention on author.getBooks().add(this);)

Respectively you need to change your constructor:

public Book(String name, Set<Author> authors) {
    this.name = name;
    setAuthors(authors);
}

Also I suggest to correct toString method - remove authors from it, to avoid  occurrence of Stackoverflow exception (you have to do this in Author class too):

@Override
public String toString() {
    return String.format("Book [id=%s, name=%s]", id, name);
}

Than your test will work fine:

@Before
public void init() {
    Author lewis = new Author("Lewis");
    Author mark = new Author("Mark");
    Author peter = new Author("Peter");

    Book spring = new Book("Spring in Action", new HashSet<>(asList(lewis, mark)));
    Book springboot = new Book("Spring Boot in Action", new HashSet<>(asList(lewis, peter)));

    bookRepository.save(Arrays.asList(spring, springboot));
}

@Test
public void findAll() {
    List<Book> books = bookRepository.findAll();
    assertThat(books).hasSize(2);
    for (Book book : books) {
        Set<Author> bookAuthors = book.getAuthors();
        assertThat(bookAuthors).isNotNull();
        assertThat(bookAuthors.size()).isGreaterThan(0);

        System.out.println(book);
        bookAuthors.forEach(System.out::println);
    }

    List<Author> authors = authorRepository.findAll();
    assertThat(authors).hasSize(3);
    for (Author author : authors) {
        Set<Book> authorBooks = author.getBooks();
        assertThat(authorBooks).isNotNull();
        assertThat(authorBooks.size()).isGreaterThan(0);

        System.out.println(author);
        authorBooks.forEach(System.out::println);
    }
}

See Hibernate User Guide for more info.

In general don't use cascade = CascadeType.ALL for ManyToMany because in this case entities are independent. Use cascade = {CascadeType.PERSIST, CascadeType.MERGE} instead.


问:
Opencv and python - Shading area between two lines
I've got some working code, but performance is awful and it can be done better, so lets see how it can be optimized.

I have an image with two semi-vertical lines drawn and would like to shade the area between those two lines.  My current code iterates pixel by pixel, which is painfully slow in python.

```<code>#Get starting images
shade_image = np.zeros_like(image)
line_image = plot_lines(shade_image, left_line, right_line)
#Choose color
shade_color = [0, 255, 0]
#Iterate through and fill blank image
left_switch = False
right_switch = False
for i in range(0, image.shape[0]):
    left_switch = False
    right_switch = False
    for j in range(0, image.shape[1]):
        if left_switch & right_switch: shade_image[i][j] = shade_color
        #Find left edge of left line
        if (not left_switch) & (not right_switch) & np.any(line_image[i][j] != 0):
            left_switch = True
        #Find right edge of left line
        elif left_switch & (not right_switch) & np.all(line_image[i][j] == 0):
            right_switch = True
        #Find left edge of left line
        elif left_switch & right_switch & np.any(line_image[i][j] != 0):
            break
        #In case of a single line, no shading
        elif left_switch & right_switch & (j == (image.shape[1] - 1)):
             shade_image[i].fill(0)
#Shade lane area
output_image = cv2.addWeighted(image, 1.0, shade_image, 1.0, gamma=0.0)
</code>```

Not pretty.  I'm thinking somehow this can be done by using all the nonzeros in the line_image and creating a mask, but I don't know how to fill between the left and right points.  I tried using fillPolygon but I don't really know how to convert all the nonzero's into vertices.

If it helps, the shading can also incorporate the lines, this isn't exact.

@Alxeander - Very helpful!  I'm almost there, except now there is the issue of filling outside of a convex line due to the bounding box, like so:

Alternatively, I ditched the cv2.convexHull and used the concatenated points directly as vertices of a polygon and got this result:

Which follows the curvature, convex or concave, however because of the order of the points it flips when it goes left to right.  I've tried using np.flips(points2, 0) but no change.  I'll play with it some more, almost there.

Made a mistake with the np.flip(points2, 0), that worked!:

Thanks for the help!

答:
Since your lines are defined by a polynomial, that means you can easily get the point set from them. You have your domain values x and your polynomial values y. If you put these into a point array

```<code>points = np.array([[[x1, y1]], ..., [[xn, yn]]])
</code>```

then you can pass these points into the OpenCV function cv2.fillPoly() or cv2.drawContours() to fill in the region.

Note that polynomials can easily define lines way outside your image bounds. In order to plot a contour or polygon you should use closed shapes, and it will be easier to cut those excess points out of your domain.

Here's a full example defining a region based on two polynomials and filling the region:

```<code>import numpy as np
import cv2

img = cv2.imread('img1.png')
h, w = img.shape[:2]

x = np.arange(w)
polynomial1 = lambda x: x**2/800
polynomial2 = lambda x: x+200
y1 = polynomial1(x)
y2 = polynomial2(x)

points1 = np.array([[[xi, yi]] for xi, yi in zip(x, y1) if (0<=xi<w and 0<=yi<h)]).astype(np.int32)
points2 = np.array([[[xi, yi]] for xi, yi in zip(x, y2) if (0<=xi<w and 0<=yi<h)]).astype(np.int32)
points2 = np.flipud(points2)
points = np.concatenate((points1, points2))

polynomialgon = img.copy()
cv2.fillPoly(polynomialgon, [points], color=[255,255,255])
cv2.imshow('Polygon defined by two polynomials', polynomialgon)
cv2.waitKey(0)
</code>```

Resulting in:

Note that the flipud is to keep the points going in a clockwise fashion from the endpoints of the lines; otherwise where polynomial1 ends, the line then goes up to where polynomial2 begins, so we're backtracking and crossing over the region. It doesn't matter what the line does so long as the endpoints of the line are tracked clockwise or anti-clockwise.

Body:
I've got some working code, but performance is awful and it can be done better, so lets see how it can be optimized.

I have an image with two semi-vertical lines drawn and would like to shade the area between those two lines.  My current code iterates pixel by pixel, which is painfully slow in python.

#Get starting images
shade_image = np.zeros_like(image)
line_image = plot_lines(shade_image, left_line, right_line)
#Choose color
shade_color = [0, 255, 0]
#Iterate through and fill blank image
left_switch = False
right_switch = False
for i in range(0, image.shape[0]):
    left_switch = False
    right_switch = False
    for j in range(0, image.shape[1]):
        if left_switch & right_switch: shade_image[i][j] = shade_color
        #Find left edge of left line
        if (not left_switch) & (not right_switch) & np.any(line_image[i][j] != 0):
            left_switch = True
        #Find right edge of left line
        elif left_switch & (not right_switch) & np.all(line_image[i][j] == 0):
            right_switch = True
        #Find left edge of left line
        elif left_switch & right_switch & np.any(line_image[i][j] != 0):
            break
        #In case of a single line, no shading
        elif left_switch & right_switch & (j == (image.shape[1] - 1)):
             shade_image[i].fill(0)
#Shade lane area
output_image = cv2.addWeighted(image, 1.0, shade_image, 1.0, gamma=0.0)

Not pretty.  I'm thinking somehow this can be done by using all the nonzeros in the line_image and creating a mask, but I don't know how to fill between the left and right points.  I tried using fillPolygon but I don't really know how to convert all the nonzero's into vertices.

If it helps, the shading can also incorporate the lines, this isn't exact.

@Alxeander - Very helpful!  I'm almost there, except now there is the issue of filling outside of a convex line due to the bounding box, like so:

Alternatively, I ditched the cv2.convexHull and used the concatenated points directly as vertices of a polygon and got this result:

Which follows the curvature, convex or concave, however because of the order of the points it flips when it goes left to right.  I've tried using np.flips(points2, 0) but no change.  I'll play with it some more, almost there.

Made a mistake with the np.flip(points2, 0), that worked!:

Thanks for the help!

Body:
Since your lines are defined by a polynomial, that means you can easily get the point set from them. You have your domain values x and your polynomial values y. If you put these into a point array

points = np.array([[[x1, y1]], ..., [[xn, yn]]])

then you can pass these points into the OpenCV function cv2.fillPoly() or cv2.drawContours() to fill in the region.

Note that polynomials can easily define lines way outside your image bounds. In order to plot a contour or polygon you should use closed shapes, and it will be easier to cut those excess points out of your domain.

Here's a full example defining a region based on two polynomials and filling the region:

import numpy as np
import cv2

img = cv2.imread('img1.png')
h, w = img.shape[:2]

x = np.arange(w)
polynomial1 = lambda x: x**2/800
polynomial2 = lambda x: x+200
y1 = polynomial1(x)
y2 = polynomial2(x)

points1 = np.array([[[xi, yi]] for xi, yi in zip(x, y1) if (0<=xi<w and 0<=yi<h)]).astype(np.int32)
points2 = np.array([[[xi, yi]] for xi, yi in zip(x, y2) if (0<=xi<w and 0<=yi<h)]).astype(np.int32)
points2 = np.flipud(points2)
points = np.concatenate((points1, points2))

polynomialgon = img.copy()
cv2.fillPoly(polynomialgon, [points], color=[255,255,255])
cv2.imshow('Polygon defined by two polynomials', polynomialgon)
cv2.waitKey(0)

Resulting in:

Note that the flipud is to keep the points going in a clockwise fashion from the endpoints of the lines; otherwise where polynomial1 ends, the line then goes up to where polynomial2 begins, so we're backtracking and crossing over the region. It doesn't matter what the line does so long as the endpoints of the line are tracked clockwise or anti-clockwise.


问:
Script to delete all non-system objects in SQL Server 2008
Does anyone have a script that will delete all non-system tables/procs/views from a database?

I created some views, procs and tables which I need to clean up and doing them individually is too cumbersome.

答:
You could always query your system catalog views and have it generate the necessary DROP statements:

```<code>SELECT 'DROP PROCEDURE [' + SCHEMA_NAME(schema_id) + '].[' + pr.NAME +']'
FROM sys.procedures pr
WHERE pr.is_ms_shipped = 0

UNION

SELECT 'DROP VIEW [' + SCHEMA_NAME(schema_id) + '].[' + v.NAME + ']'
FROM sys.views v
WHERE v.is_ms_shipped = 0

UNION

SELECT 'ALTER TABLE [' + SCHEMA_NAME(schema_id) + '].[' + OBJECT_NAME(fk.parent_object_ID) + '] DROP CONSTRAINT ' + fk.name
FROM sys.foreign_keys fk
WHERE is_ms_shipped = 0

UNION

SELECT 'DROP TABLE [' + SCHEMA_NAME(schema_id) + '].[' + t.NAME + ']'
FROM sys.tables t
WHERE t.is_ms_shipped = 0
</code>```

This will generate a long list of DROP ..... statements, just copy & paste those into a new SSMS window and execute them.

Body:
You could always query your system catalog views and have it generate the necessary DROP statements:

SELECT 'DROP PROCEDURE [' + SCHEMA_NAME(schema_id) + '].[' + pr.NAME +']'
FROM sys.procedures pr
WHERE pr.is_ms_shipped = 0

UNION

SELECT 'DROP VIEW [' + SCHEMA_NAME(schema_id) + '].[' + v.NAME + ']'
FROM sys.views v
WHERE v.is_ms_shipped = 0

UNION

SELECT 'ALTER TABLE [' + SCHEMA_NAME(schema_id) + '].[' + OBJECT_NAME(fk.parent_object_ID) + '] DROP CONSTRAINT ' + fk.name
FROM sys.foreign_keys fk
WHERE is_ms_shipped = 0

UNION

SELECT 'DROP TABLE [' + SCHEMA_NAME(schema_id) + '].[' + t.NAME + ']'
FROM sys.tables t
WHERE t.is_ms_shipped = 0

This will generate a long list of DROP ..... statements, just copy & paste those into a new SSMS window and execute them.


问:
Display / Hide Advert Based on Role
I created a Web Control which is basically a div for holding a mobile banner but I wish to hide it if the user is an Admin

I have tried:

```<code><mob:MobileBanner runat="server" ID="MobileBanner" Visible='<%# Not HttpContext.Current.User.IsInRole("Admin") %>' />
</code>```

but it doesn't seem to work.

I was also thinking of surrounding the html but cannot seem to get that working so it checks if you're an admin and if not it writes the advert code to the client, which includes the css link.

There is a similar question (how to enable and disable button based on user role?) but that is an ASP.NET Server Side button not a basic Web Control which just holds html.

Those of you who want code, add a new Web Control to the project then paste in this code.

```<code><link href = "my_css_file_here.css" rel="stylesheet" type="text/css" />

<div Class="my_banner_container">
    <!--My banner code goes here -->
</div>
</code>```

I know I could create a container in the master document with runat="server" then use:

```<code>my_container.Visible = Not HttpContext.Current.User.IsInRole("Admin")
</code>```

but I also need to change the padding-top: 130px; to padding-top: 50px; and swap back if the admin logs out or the user is not an admin.

I know if could have a link like this for non Admins:

```<code><link href = "my_css_file_130_here.css" rel="stylesheet" type="text/css" runat="server" />
</code>```

which would then become for Admins:

```<code><link href = "my_css_file_50_here.css" rel="stylesheet" type="text/css" runat="server" />
</code>```

then from code behind have 2 different css for the padding-top and change the href based on if the user is an admin or not

```<code>body {
     padding-top: 130px;
}
</code>```

or

```<code>body {
     padding-top: 50px;
}
</code>```

Any ideas on how to achieve this or a better way than my complicated idea?

答:
Do not render it if you do not want it. Below will only render it if user is not in Admin role.

```<code><%If Not HttpContext.Current.User.IsInRole("Admin")
Then
    <mob:MobileBanner runat="server" ID="MobileBanner" />
End If %>
</code>```

Title: Display / Hide Advert Based on Role

Body:
I created a Web Control which is basically a div for holding a mobile banner but I wish to hide it if the user is an Admin

I have tried:

<mob:MobileBanner runat="server" ID="MobileBanner" Visible='<%# Not HttpContext.Current.User.IsInRole("Admin") %>' />

but it doesn't seem to work.

I was also thinking of surrounding the html but cannot seem to get that working so it checks if you're an admin and if not it writes the advert code to the client, which includes the css link.

There is a similar question (how to enable and disable button based on user role?) but that is an ASP.NET Server Side button not a basic Web Control which just holds html.

Those of you who want code, add a new Web Control to the project then paste in this code.

<link href = "my_css_file_here.css" rel="stylesheet" type="text/css" />

I know I could create a container in the master document with runat="server" then use:

my_container.Visible = Not HttpContext.Current.User.IsInRole("Admin")

but I also need to change the padding-top: 130px; to padding-top: 50px; and swap back if the admin logs out or the user is not an admin.

I know if could have a link like this for non Admins:

<link href = "my_css_file_130_here.css" rel="stylesheet" type="text/css" runat="server" />

which would then become for Admins:

<link href = "my_css_file_50_here.css" rel="stylesheet" type="text/css" runat="server" />

then from code behind have 2 different css for the padding-top and change the href based on if the user is an admin or not

body {
     padding-top: 130px;
}

or

body {
     padding-top: 50px;
}

Any ideas on how to achieve this or a better way than my complicated idea?

Body:
Do not render it if you do not want it. Below will only render it if user is not in Admin role.

<%If Not HttpContext.Current.User.IsInRole("Admin")
Then
    <mob:MobileBanner runat="server" ID="MobileBanner" />
End If %>


问:
Ionic 3 - Use jsencrypt
I'm trying to hash my passwords for login on my Ionic 3 app. I found some tutorial about jsencrypt but it doesn't work and i don't really understand how it work...

Here what i did :

npm install --save jsencrypt

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { ApiDatabaseService } from '../../providers/api-database-service';
import Encrypt from 'jsencrypt';
import { Injectable } from '@angular/core';

@Component({
  selector: 'page-Login',
  templateUrl: 'Login.html'
})

@Injectable()

export class LoginPage {

  private prem: string = `my_key`;
  Users:any = []; // Here there is all my users

  constructor(public navCtrl: NavController, public serviceOne: ApiDatabaseService) {
    this.serviceOne.getDataUser().subscribe( // I'm calling my api to acces to my database
            data => this.Users = data
        );
  }

  public create(name: string): string { // Here the password should be encrypt
        let encrypt = new Encrypt.JSEncrypt();
        encrypt.setPublicKey(this.pem);
        return encrypt.encrypt(name);
    };
}
</code>```

And i have this error :

Typescript Error
Property 'pem' does not exist on type 'LoginPage'.

Also, for Ionic 2 there is many documentation like this : https://docs.ionic.io/services/auth/. But nothing for Ionic 3, why ?

答:
When using the Ionic service your app sends your plain password to the Ionic with service when creating and logging into your account. The auth service will handling all the encryption.

Also, there are no separate docs for Ionic 3 as it is essential the same as Ionic 2 except for some new features and big fixes. There are a few breaking changes but not many. It's not a full rewrite like there was going from Ionic 1 -> Ionic 2 and they are now using semantic versioning so major releases will be more regular similar to Angular.

Title: Ionic 3 - Use jsencrypt

Body:
I'm trying to hash my passwords for login on my Ionic 3 app. I found some tutorial about jsencrypt but it doesn't work and i don't really understand how it work...

Here what i did :

npm install --save jsencrypt

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { ApiDatabaseService } from '../../providers/api-database-service';
import Encrypt from 'jsencrypt';
import { Injectable } from '@angular/core';

@Component({
  selector: 'page-Login',
  templateUrl: 'Login.html'
})

@Injectable()

export class LoginPage {

  private prem: string = `my_key`;
  Users:any = []; // Here there is all my users

  constructor(public navCtrl: NavController, public serviceOne: ApiDatabaseService) {
    this.serviceOne.getDataUser().subscribe( // I'm calling my api to acces to my database
            data => this.Users = data
        );
  }

  public create(name: string): string { // Here the password should be encrypt
        let encrypt = new Encrypt.JSEncrypt();
        encrypt.setPublicKey(this.pem);
        return encrypt.encrypt(name);
    };
}

And i have this error :

Typescript Error
Property 'pem' does not exist on type 'LoginPage'.

Also, for Ionic 2 there is many documentation like this : https://docs.ionic.io/services/auth/. But nothing for Ionic 3, why ?


问:
Passing messages in message Queue
How can I, in my application, sent a message as input to my application using message queue?
It is showing as number of messages in message queue is zero. </p>

答: Providing that you use Linux and C language, a simple example how POSIX message queue can be used to pass data between separate threads or processes can be found here.

Title: Passing messages in message Queue


问:
How do I create a nested dictionary under a key that is yet to exist?
I have an empty array.

I want to assign a value like this: array[key][subkey] = 'value'

This produces a KeyError as array[key] does not exist yet.

What do I do? I tried the following...

```<code>array['key'] = None
array['key']['subkey'] = 'value'
</code>```

TypeError: 'NoneType' object does not support item assignment

I tried:

```<code>array['key'] = []
array['key']['subkey'] = 'value'
</code>```

TypeError: list indices must be integers, not str

I tried:

```<code>array['key'] = ['subkey']
array['key']['subkey'] = 'value'
</code>```

TypeError: list indices must be integers, not str

So what do I do?

答:
You could use collections.defaultdict, passing the default factory as dict:

```<code>>>> from collections import defaultdict
>>> d = defaultdict(dict)
>>> d['key']['subkey'] = 'value'
>>> d
defaultdict(<type 'dict'>, {'key': {'subkey': 'value'}})
</code>```

To apply further levels of nesting, you can create a defaultdict that returns defaultdicts to a n-th depth of nesting, using a function, preferably anonymous, to return the nested default dict(s):

```<code>>>> d = defaultdict(lambda: defaultdict(dict))
>>> d['key']['subkey']['subsubkey'] = 'value'
>>> d
defaultdict(<function <lambda> at 0x104082398>, {'key': defaultdict(<type 'dict'>, {'subkey': {'subsubkey': 'value'}})})
</code>```

Example shows nesting up to depth n=1

Body:
I have an empty array.

I want to assign a value like this: array[key][subkey] = 'value'

This produces a KeyError as array[key] does not exist yet.

What do I do? I tried the following...

array['key'] = None
array['key']['subkey'] = 'value'

TypeError: 'NoneType' object does not support item assignment

I tried:

array['key'] = []
array['key']['subkey'] = 'value'

TypeError: list indices must be integers, not str

I tried:

array['key'] = ['subkey']
array['key']['subkey'] = 'value'

TypeError: list indices must be integers, not str

So what do I do?

Body:
You could use collections.defaultdict, passing the default factory as dict:

>>> from collections import defaultdict
>>> d = defaultdict(dict)
>>> d['key']['subkey'] = 'value'
>>> d
defaultdict(<type 'dict'>, {'key': {'subkey': 'value'}})

To apply further levels of nesting, you can create a defaultdict that returns defaultdicts to a n-th depth of nesting, using a function, preferably anonymous, to return the nested default dict(s):

>>> d = defaultdict(lambda: defaultdict(dict))
>>> d['key']['subkey']['subsubkey'] = 'value'
>>> d
defaultdict(<function <lambda> at 0x104082398>, {'key': defaultdict(<type 'dict'>, {'subkey': {'subsubkey': 'value'}})})

Example shows nesting up to depth n=1


问:
Custom shape Recycler View with button Onclick

]3

I want to view a a stagged recycler View  in start shape with profile pic ...When the user clicks on the pic..the image should change to the next image ..and when the red colr..it should open redActivity...Yellow means YellowActivity....etc

How to achieve this...Please don't block r tell me to add some code..As I'm a totally new to android...

答: Create an image with any custom shape library;..with relative layout as root....then place the texts inside the layouts as needed and hide and unhide those with in the recycler adapter using an onclick listener</p>


问:
MySQL custom storage path
I'm working on a server with almost no free space on it, so I attached a NFS volume to it. Now I would like MySQL to be storing tables or, even better, entire databases on the shared volume. Is there a way to do this?

Thanks a lot!

答:
I don't think that is a good idea. You will have performance and consistency issues if storage is on NFS. Consider adding a secondary local disk, mounting it, and hosting your database files in it.

Having said that, you could change database location in MySQL. It's pretty simple. Have a look at this web entry. MySQL is pretty flexible with this kind of things.

Title: MySQL custom storage path


问:
List files not in database
I have a database files for holding details about files in different folders and the field flink holds the path of the file.Now i want to run a search both in the folder and database and find the files that are not listed in the database.Is this possible using PHP MYSQL.I have written a sample code but it doesnt seem to work.Please note that files folder contains number of subdirectories as well.

```<code><?php

include("dbfiles.php");
$directory='files/';
// Query database
$query = 'SELECT `flink` FROM `files`';
$result = mysqli_query($fmysqli, $query);
$db = []; // create empty array
while ($row = mysqli_fetch_row($result))
    array_push($db, $row[0]);
// Check files
$files1 = scandir($directory);
if ( $files1 !== false ) {
    foreach ($files1 as $i => $value) {
        if (in_array($value, $db)) {
            // File exists in both
            echo '   Exists   '.$value;
        } else {
            // File doesn't exist in database
            echo '  Not Exists  '.$value;
        }
    }
} else {
    echo 0;
}
?>
</code>```

The result is something unexpected there is a file inside BT363 Folder the path is as follows files/BT363/BT363-Metabolic Engineering and Synthetic Biology-Class Slide--Module 4-admin-admin.pptx

But i am getting the output as

Not Exists . Not Exists .. Not Exists BT363

答:
You can list all the files in a directory by doing this:

```<code>$files = scandir($path);
</code>```

Then query your database for the file information you want and then loop through it and compare the current iteration and find that value in $files.

Title: List files not in database

Body:
I have a database files for holding details about files in different folders and the field flink holds the path of the file.Now i want to run a search both in the folder and database and find the files that are not listed in the database.Is this possible using PHP MYSQL.I have written a sample code but it doesnt seem to work.Please note that files folder contains number of subdirectories as well.

<?php

include("dbfiles.php");
$directory='files/';
// Query database
$query = 'SELECT `flink` FROM `files`';
$result = mysqli_query($fmysqli, $query);
$db = []; // create empty array
while ($row = mysqli_fetch_row($result))
    array_push($db, $row[0]);
// Check files
$files1 = scandir($directory);
if ( $files1 !== false ) {
    foreach ($files1 as $i => $value) {
        if (in_array($value, $db)) {
            // File exists in both
            echo '   Exists   '.$value;
        } else {
            // File doesn't exist in database
            echo '  Not Exists  '.$value;
        }
    }
} else {
    echo 0;
}
?>

The result is something unexpected there is a file inside BT363 Folder the path is as follows files/BT363/BT363-Metabolic Engineering and Synthetic Biology-Class Slide--Module 4-admin-admin.pptx

But i am getting the output as

Not Exists . Not Exists .. Not Exists BT363

Body:
You can list all the files in a directory by doing this:

$files = scandir($path);

Then query your database for the file information you want and then loop through it and compare the current iteration and find that value in $files.


问:
Unable to update composer, getting Deprecation Notice
Recently I wanted to add a new package (laravel-dompdf) in Laravel using composer. But it is throwing some Deprecated Notice. Initially I used composer for YII2 and was perfectly working.

Here is the screen short:

答:
Just delete folder 'vendor' and file 'composer.lock'.
Then 'composer global update'

IT WORKS.


问:
Full width video background
I'm attempting my first web video project and am getting nowhere and need a little help with using a full width video header or background.

I found an example that does what I am trying to do using the below videos and it works just fine - no buffering, acceptable quality, etc.

The .mp4 file uses a 640x360 format @ 23 fps (613kbps) and this works fine on any display I view it - the whole frame is visible top to bottom, side to side.

The research I've done indicates the best video format to use is 720 x 24fps, which I have tried (actual dimension is 1280x720) but found it only works well on less than maximized browser resolutions, in which case, it looks great, otherwise, a small portion of the bottom, maybe the bottom 18% of the frame, is not visible until you scroll down, which is unacceptable.  I need the video to work as well as the 640x360 with the whole image visible. In addition, buffering occurs with the 720 format, whereas there is no buffering with the 640x360.

I am using Sony Vegas for the video editing and there is no option for a 640x360 format.  The closest is 640x480 but that produces the same result - to tall and the bottom is not visible.

There is a site that uses the 1280x720 format successfully (http://mazwai.com/#/) but I have no idea how.

Can someone point me in the right direction?

Thank You.

This is  the current code:

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Video test</title>

<script>
$(document).ready(function () {
$(".player").mb_YTPlayer();
});
</script>

<style>
body{ margin:0px; background:#000; max-width:1000; }
#bg_container{ height:800px; overflow:auto; }
#bg{ width:100%; }
</style>

</head>

<body>

<div id="bg_container">
  <video id="bg" src="www.parishpc.com/images/720.mp4" autoplay loop muted">    </video>
</div>

</body>
</html>
</code>```

This code worked a little bit better - only the bottom 5% was not visible:

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Video test</title>

<style>

body, html { margin: auto;
background:#fff;
height: 100%;
}

header {
height:100%;
width:100%;
overflow:hidden;
position:relative;
}

.video {
    position:fixed;
    top: 50%; left: 50%;
    z-index:1;
    min-width: 100%;
    min-height: 100%;
    width:auto;
    height:auto;
    transform: translate(-50%,-50%);
}
</style>

</head>

<body>
    <header>
        <video autoplay loop class="video">
            <source src="www.parishpc.com/images/720.mp4" type="video/mp4">
        </video>
    </header>
</body>
</html>
</code>```

答:
Try

```<code>body {
   margin: 0;
   padding:0;
}
</code>```

and remove transform: translate(-50%,-50%); from video class

This should work

Let me know if you require any further help

Title: Full width video background

Body:
I'm attempting my first web video project and am getting nowhere and need a little help with using a full width video header or background.

I found an example that does what I am trying to do using the below videos and it works just fine - no buffering, acceptable quality, etc.

The .mp4 file uses a 640x360 format @ 23 fps (613kbps) and this works fine on any display I view it - the whole frame is visible top to bottom, side to side.

The research I've done indicates the best video format to use is 720 x 24fps, which I have tried (actual dimension is 1280x720) but found it only works well on less than maximized browser resolutions, in which case, it looks great, otherwise, a small portion of the bottom, maybe the bottom 18% of the frame, is not visible until you scroll down, which is unacceptable.  I need the video to work as well as the 640x360 with the whole image visible. In addition, buffering occurs with the 720 format, whereas there is no buffering with the 640x360.

I am using Sony Vegas for the video editing and there is no option for a 640x360 format.  The closest is 640x480 but that produces the same result - to tall and the bottom is not visible.

There is a site that uses the 1280x720 format successfully (http://mazwai.com/#/) but I have no idea how.

Can someone point me in the right direction?

Thank You.

This is  the current code:

<!DOCTYPE html>

<meta charset="UTF-8">
<title>Video test</title>

  <video id="bg" src="www.parishpc.com/images/720.mp4" autoplay loop muted">    </video>

This code worked a little bit better - only the bottom 5% was not visible:

<!DOCTYPE html>

<meta charset="UTF-8">
<title>Video test</title>

        <video autoplay loop class="video">
            <source src="www.parishpc.com/images/720.mp4" type="video/mp4">
        </video>

Body:
Try

body {
   margin: 0;
   padding:0;
}

and remove transform: translate(-50%,-50%); from video class

This should work

Let me know if you require any further help


问:
Copy asset from bundle to file system
I'm trying to copy an sqlite database from the root bundle onto the file system in order to use it.

I've tried many different ways but it always ended up writing incorrect amounts of data to disk. The code I'm using looks like this:

```<code>Directory appDocDir = await getExternalStorageDirectory();
String path = join(appDocDir.path, "data.db");
bool exists = await new File(path).exists();
if (!exists) {
  var out = new File(path).openWrite();

  var data = await rootBundle.load("assets/data.sqlite");
  var list = data.buffer.asUint8List();
  out.write(list);
  out.close();
}
</code>```

答:
You can't write the contents of a Uint8List to a File using IOSink.write (which is designed to operate on String arguments). You'll end up writing the UTF-8 encoded representation of the String obtained by calling toString() on your Uint8List, which is probably much larger than the actual contents of the list.

Instead, you can write a Uint8List to the file using IOSink.add.

In the example you've provided, you could also write the entire file at once using new File(path).writeAsBytes(list).

Title: Copy asset from bundle to file system

Body:
I'm trying to copy an sqlite database from the root bundle onto the file system in order to use it.

I've tried many different ways but it always ended up writing incorrect amounts of data to disk. The code I'm using looks like this:

Directory appDocDir = await getExternalStorageDirectory();
String path = join(appDocDir.path, "data.db");
bool exists = await new File(path).exists();
if (!exists) {
  var out = new File(path).openWrite();

  var data = await rootBundle.load("assets/data.sqlite");
  var list = data.buffer.asUint8List();
  out.write(list);
  out.close();
}


问:
Do same animation on header secton than cell

I followed the tutorial of Brian Advent https://www.youtube.com/watch?v=FpTY04efWC0 to animate my TableView but his animation works only on cell, how can i do the same animation on 3 sections headers ?

This is the animation on cell

```<code>func Animation(){
    TableViewContent.reloadData()
    let cells = TableViewContent.visibleCells

    let TableViewHeight = TableViewContent.bounds.size.height

    for cell in cells{
        cell.transform = CGAffineTransform(translationX: 0, y:TableViewHeight )
    }

    var delayCounter = 0.0
    for cell in cells{
        UIView.animate(withDuration: 1.75, delay: delayCounter * 0.05, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
        cell.transform = CGAffineTransform.identity}, completion: nil)
        delayCounter += 1
    }
}
</code>```

答:
Well this is possible but it's tricky and needs extra operations.

The way your animation works is that it gets all visible cell on the current window, loop through each of them and then apply animation for each of them. Your header is nothing special, it's like a normal cell, they are all just views. So all you need to do here is to add the header to correct position in your cells array and then simply loop through them and do the animation.

After getting all the cells, loop through them and check which section are they in. Say you find out that they are from section 0, 1 and 2. Then you need to get cells for these three section by calling this

```<code>let header = tableView.headerViewForSection(section: index) as! HeaderView
</code>```

Then you need to add these sections to the corresponding place in your cell array. So your cell array will finally look like

```<code>header0 - cell0 - cell1 - cell2 - header1 - cell0 - cell1 - header2 - cell0
</code>```

Finally, run the rest of your code to loop through them and apply animation one by one.

Body:
I followed the tutorial of Brian Advent https://www.youtube.com/watch?v=FpTY04efWC0 to animate my TableView but his animation works only on cell, how can i do the same animation on 3 sections headers ?

This is the animation on cell

func Animation(){
    TableViewContent.reloadData()
    let cells = TableViewContent.visibleCells

    let TableViewHeight = TableViewContent.bounds.size.height

    for cell in cells{
        cell.transform = CGAffineTransform(translationX: 0, y:TableViewHeight )
    }

    var delayCounter = 0.0
    for cell in cells{
        UIView.animate(withDuration: 1.75, delay: delayCounter * 0.05, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
        cell.transform = CGAffineTransform.identity}, completion: nil)
        delayCounter += 1
    }
}

Body:
Well this is possible but it's tricky and needs extra operations.

The way your animation works is that it gets all visible cell on the current window, loop through each of them and then apply animation for each of them. Your header is nothing special, it's like a normal cell, they are all just views. So all you need to do here is to add the header to correct position in your cells array and then simply loop through them and do the animation.

After getting all the cells, loop through them and check which section are they in. Say you find out that they are from section 0, 1 and 2. Then you need to get cells for these three section by calling this

let header = tableView.headerViewForSection(section: index) as! HeaderView

Then you need to add these sections to the corresponding place in your cell array. So your cell array will finally look like

header0 - cell0 - cell1 - cell2 - header1 - cell0 - cell1 - header2 - cell0

Finally, run the rest of your code to loop through them and apply animation one by one.


问:
Iterating through database results with php iterator interface
I've been studying this book on php and there's this example on the iterator pattern which uses the iterator interface. I can use the iterator interface to loop through simple arrays but I don't quite understand the example illustrated in the book. I'll post snippets of the code. It says instead of doing something like this.

```<code><?php
$posts = getAllPosts(); //example function return all post ids of this author
for($i = 0; $i<count($posts); $i++)
{
$title = getPostTitle($post[$i]);
echo $title;
$author = getPostAuthor($post[$i]);
$content = parseBBCode(getPostContent($post[$i]));
echo "Content";
$comments = getAllComments($post[$i]);
for ($j=0; $j<count($comments); $j++)
{
$commentAuthor = getCommentAuthor($comments[$j]);
echo $commentAuthor;
$comment = getCommentContent($comments[$j]);
echo $comment;
}
}
?>
</code>```

We can implement the iterator interface to provide something more effective

```<code><?php
class Posts implements Iterator
{
private $posts = array();
public function __construct($posts)
{
if (is_array($posts)) {
$this->posts = $posts;
}
}
public function rewind() {
reset($this->posts);
}
public function current() {
return current($this->posts);
}
public function key() {
return key($this->var);
}
public function next() {
return next($this->var);
}
public function valid() {
return ($this->current() !== false);
}
}
?>
</code>```

"Now let's use the Iterator we just created."

```<code><?
$blogposts = getAllPosts();
$posts = new Posts($posts);
foreach ($posts as $post)
{
echo $post->getTitle();
echo $post->getAuthor();
echo $post->getDate();
echo $post->getContent();
$comments = new Comments($post->getComments());
//another Iterator for comments, code is same as Posts
foreach ($comments as $comment)
{
echo $comment->getAuthor();
echo $comment->getContent();
}
}
?>
</code>```

Now I dont understand why the $blogposts was never used, why it isn't part of the methods of any class and what kind of data it will return, an array or an object.

I also dont understand how the $post->getTitle() is acheived. I'd understand $post['title'] or $posts->getTitle() since we can add a getTitle() method to the Posts class.

I'd really love to replicate something like this on something I'm working on

doing

```<code>foreach($key as $value) {
    $value->getTitle();
}
</code>```

instead of

```<code>foreach($key as $value) {
    $value['title'];
    //or
    $key->getTitle()
}
</code>```

答:
It seems a typo I think it shoud be

```<code>$blogposts = getAllPosts();
$posts = new Posts($blogposts);
</code>```

Regarding to the accesd to getTitle method I need more code to answer the question properly... But I it will work if the function "getAllPosts" returns an array of Post object which implement the method "getTitle()"

Hope it helps!

Body:
I've been studying this book on php and there's this example on the iterator pattern which uses the iterator interface. I can use the iterator interface to loop through simple arrays but I don't quite understand the example illustrated in the book. I'll post snippets of the code. It says instead of doing something like this.

<?php
$posts = getAllPosts(); //example function return all post ids of this author
for($i = 0; $i<count($posts); $i++)
{
$title = getPostTitle($post[$i]);
echo $title;
$author = getPostAuthor($post[$i]);
$content = parseBBCode(getPostContent($post[$i]));
echo "Content";
$comments = getAllComments($post[$i]);
for ($j=0; $j<count($comments); $j++)
{
$commentAuthor = getCommentAuthor($comments[$j]);
echo $commentAuthor;
$comment = getCommentContent($comments[$j]);
echo $comment;
}
}
?>

We can implement the iterator interface to provide something more effective

<?php
class Posts implements Iterator
{
private $posts = array();
public function __construct($posts)
{
if (is_array($posts)) {
$this->posts = $posts;
}
}
public function rewind() {
reset($this->posts);
}
public function current() {
return current($this->posts);
}
public function key() {
return key($this->var);
}
public function next() {
return next($this->var);
}
public function valid() {
return ($this->current() !== false);
}
}
?>

"Now let's use the Iterator we just created."

<?
$blogposts = getAllPosts();
$posts = new Posts($posts);
foreach ($posts as $post)
{
echo $post->getTitle();
echo $post->getAuthor();
echo $post->getDate();
echo $post->getContent();
$comments = new Comments($post->getComments());
//another Iterator for comments, code is same as Posts
foreach ($comments as $comment)
{
echo $comment->getAuthor();
echo $comment->getContent();
}
}
?>

Now I dont understand why the $blogposts was never used, why it isn't part of the methods of any class and what kind of data it will return, an array or an object.

I also dont understand how the $post->getTitle() is acheived. I'd understand $post['title'] or $posts->getTitle() since we can add a getTitle() method to the Posts class.

I'd really love to replicate something like this on something I'm working on

doing

foreach($key as $value) {
    $value->getTitle();
}

instead of

foreach($key as $value) {
    $value['title'];
    //or
    $key->getTitle()
}

Body:
It seems a typo I think it shoud be

$blogposts = getAllPosts();
$posts = new Posts($blogposts);

Regarding to the accesd to getTitle method I need more code to answer the question properly... But I it will work if the function "getAllPosts" returns an array of Post object which implement the method "getTitle()"

Hope it helps!


答:
Yes, it is possible.

Due to the extreme lack of specific detail in your question, my response is going to be equally non-specific.

You'll want to compile a list of files from your folder using glob, scandir or similar. Likewise you will want to compile a list of files in the database.

Compare the two to identify those in the folder, but not in the database.

Edit

The output you're getting . and .. are because filesystems have links to the current (.) and parent (..) directory. Typically you write code to skip these values.

For example, taking your code:

```<code>$files1 = scandir($directory)

if ($files1) {
    foreach ($files1 as $value) {
        if (in_array($value, ['.', '..'])) continue;

        // Your other code...
    }
}
</code>```

Title: List files not in database

Body:
Yes, it is possible.

Due to the extreme lack of specific detail in your question, my response is going to be equally non-specific.

You'll want to compile a list of files from your folder using glob, scandir or similar. Likewise you will want to compile a list of files in the database.

Compare the two to identify those in the folder, but not in the database.

Edit

The output you're getting . and .. are because filesystems have links to the current (.) and parent (..) directory. Typically you write code to skip these values.

For example, taking your code:

$files1 = scandir($directory)

if ($files1) {
    foreach ($files1 as $value) {
        if (in_array($value, ['.', '..'])) continue;

        // Your other code...
    }
}


问:
Java Swing - How to sound beep before any JOptionPane?
Whenever i show a JOptionPane in my Swing application i fire a beep before it like this :

```<code>Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog( myFrame, "Message", "Title", JOptionPane.INFORMATION_MESSAGE );
</code>```

Is there a way to apply the first line automatically to any JOptionPane in case i forgot to write it in code ?

答:
I agree with org.life.java and atamanroman.
Additionally I can suggest you the following.  Create AWTListener and register it using

```<code>Toolkit.getDefaultToolkit().addAWTEventListener(listener, eventMask)
</code>```

I think that this listener will be called in many cases including dialog opening. So you just have to recognize the case and call beep(). I did not try this but I believe it will work.

Body:
Whenever i show a JOptionPane in my Swing application i fire a beep before it like this :

Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog( myFrame, "Message", "Title", JOptionPane.INFORMATION_MESSAGE );

Is there a way to apply the first line automatically to any JOptionPane in case i forgot to write it in code ?

Body:
I agree with org.life.java and atamanroman.
Additionally I can suggest you the following.  Create AWTListener and register it using

Toolkit.getDefaultToolkit().addAWTEventListener(listener, eventMask)

I think that this listener will be called in many cases including dialog opening. So you just have to recognize the case and call beep(). I did not try this but I believe it will work.


答:
I have used this alternative way before (edit: although I preferred Moses Koledoye answer):</p>

```<code>array = {}

try:
    array[key][subkey] = 'value'
except KeyError:
    array[key] = {}
    array[key][subkey] = 'value'
</code>```

Title: How do I create a nested dictionary under a key that is yet to exist?

Body:
I have used this alternative way before (edit: although I preferred Moses Koledoye answer):

array = {}

try:
    array[key][subkey] = 'value'
except KeyError:
    array[key] = {}
    array[key][subkey] = 'value'


问:
pandas get mapping of categories to integer value
I can transform categorical columns to their categorical code but how do i get an accurate picture of their mapping?  Example:

```<code>df_labels = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':list('abcab')})
df_labels['col2'] = df_labels['col2'].astype('category')
</code>```

df_labels looks like this:

```<code>   col1 col2
0     1    a
1     2    b
2     3    c
3     4    a
4     5    b
</code>```

How do i get an accurate mapping of the cat codes to cat categories?
The stackoverflow response below says to enumerate the categories. However, I'm not sure if enumerating was the way cat.codes generated the integer values. Is there a more accurate way?

Get mapping of categorical variables in pandas

```<code>>>> dict( enumerate(df.five.cat.categories) )

{0: 'bad', 1: 'good'}
</code>```

What is a good way to get the mapping in the above format but accurate?

答:
I use:  </p>

```<code>dict([(category, code) for code, category in enumerate(df_labels.col2.cat.categories)])

# {'a': 0, 'b': 1, 'c': 2}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I can transform categorical columns to their categorical code but how do i get an accurate picture of their mapping?  Example:

df_labels = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':list('abcab')})
df_labels['col2'] = df_labels['col2'].astype('category')

df_labels looks like this:

   col1 col2
0     1    a
1     2    b
2     3    c
3     4    a
4     5    b

How do i get an accurate mapping of the cat codes to cat categories?
The stackoverflow response below says to enumerate the categories. However, I'm not sure if enumerating was the way cat.codes generated the integer values. Is there a more accurate way?

Get mapping of categorical variables in pandas

>>> dict( enumerate(df.five.cat.categories) )

{0: 'bad', 1: 'good'}

What is a good way to get the mapping in the above format but accurate?

Body:
I use:

dict([(category, code) for code, category in enumerate(df_labels.col2.cat.categories)])

# {'a': 0, 'b': 1, 'c': 2}


问:
How to send verification email with Firebase?
I am signing up my users using Firebase's email and password method. like this:

```<code>mAuth.createUserWithEmailAndPassword(email, password)

.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {

    if (task.isSuccessful()) {

        FirebaseUser signed = task.getResult().getUser();

        writeNewUser(signed.getUid());

        new android.os.Handler().postDelayed(

                new Runnable() {
                    public void run() {

                        updateUser(b);

                    }
                }, 3000);

    } else {

        new android.os.Handler().postDelayed(

                new Runnable() {
                    public void run() {

                        onSignupFailed();

                    }
                }, 3000);

    }

    }
});
</code>```

After the user's email has been successfully registered, I would like Firebase to send a verification email. I know this is possible using Firebase's sendEmailVerification. In addition to sending this email, I want the user's account to be disabled until they verify the email. This would also require using Firebase's isEmailVerified feature. However, I have been unsuccessful in getting Firebase to send the verification email, I have not been able to figure out to get it to disable and enable the account sending the verification email and after it has been verified.

答:
send verification to user's Email

```<code>FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.sendEmailVerification();
</code>```

check if user is verified

```<code>FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
boolean emailVerified = user.isEmailVerified();
</code>```

Body:
I am signing up my users using Firebase's email and password method. like this:

mAuth.createUserWithEmailAndPassword(email, password)

.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {

    if (task.isSuccessful()) {

        FirebaseUser signed = task.getResult().getUser();

        writeNewUser(signed.getUid());

        new android.os.Handler().postDelayed(

                new Runnable() {
                    public void run() {

                        updateUser(b);

                    }
                }, 3000);

    } else {

        new android.os.Handler().postDelayed(

                new Runnable() {
                    public void run() {

                        onSignupFailed();

                    }
                }, 3000);

    }

    }
});

After the user's email has been successfully registered, I would like Firebase to send a verification email. I know this is possible using Firebase's sendEmailVerification. In addition to sending this email, I want the user's account to be disabled until they verify the email. This would also require using Firebase's isEmailVerified feature. However, I have been unsuccessful in getting Firebase to send the verification email, I have not been able to figure out to get it to disable and enable the account sending the verification email and after it has been verified.

Body:
send verification to user's Email

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.sendEmailVerification();

check if user is verified

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
boolean emailVerified = user.isEmailVerified();


问:
When should I run `react-native start`?
Just getting started with React-Native (for the non-CRNA/Expo case) and it's not clear to me after reading the react-native docs or Understanding the CLI when it's appropriate to run react-native start

react-native start --help simply says starts the webserver.  Running react-native run-ios also starts the same server except it also actually runs it in the simulator.

Question: When is it appropriate to run react-native start vs. just running the simulators directly (i.e. react-native run-ios)?

答:
react-native start is same as npm start and like you said it's to start the react packager/server.

I have found myself in situations where I had to stop and start the server explicitly using npm start.

To start up a project, you use the react-native run-ios and it starts up both the simulator and the server but in cases where the app has been installed and you want to restart the server, you can stop it explicitly in the terminal and use react-native start or npm start to start it up again.

Title: When should I run `react-native start`?


问:
get an array of "val" attributes values from the rows of a table
```<code><table id ='t1'>
<tr val='1'></tr>
<tr val='2'></tr>
<tr val='3'></tr>
<tr val='4'></tr>
<table>
</code>```

how to get from this an array = 1,2,3,4

答:
You can use .map(), like this:

```<code>var arr = $("#t1 tr").map(function() { return $(this).attr("val"); }).get();
</code>```

You can test it out here.

Body: how to get from this an array = 1,2,3,4

Body:
You can use .map(), like this:

var arr = $("#t1 tr").map(function() { return $(this).attr("val"); }).get();

You can test it out here.


问:
AWS Lambda and API Gateway plus SOAP Client
I'm new to the AWS Lambda world, and I'm trying to figure out if what I'm trying to do is achievable using AWS web services.

The situation that I have is that a SaaS site will be sending JSON data whenever an event happens on their end, so I what I need to do is have a Restful API (using AWS API Gateway I'm assuming) that can handle CRUD events (e.g. a new employee is added / updated / deleted in the SaaS site, then AWS API gateway will route the event in AWS as such: example.com/employee/create or example.com/employee/update). I'm assuming AWS API Gateway routes the event to its corresponding Lambda function? Does this mean that there must be multiple lambda functions for each CRUD event? Or is this the standard?

If my assumption is correct and the event is sent to its corresponding lambda function, then the next thing that needs to happen is for the Lambda function to basically transform the data, or prepare the data, and talk to another final Site (site B) via a SOAP Client. So in retrospect, in this step the lambda function will eventually send the transformed data via SOAP client.

Functional summary: SaaS ---> [AWS-API-Gateway ---> AWS Lambda ---> Soap Client] --> Site B

Is this entire scenario even possible? In addition to this, there will be occasions when the site with the SOAP API will also need to send information back to the SaaS site.

My language of choice is Java using the Eclipse AWS toolkit. Can I also use any Java SOAP client when developing my lambda functions? Are there any examples out there I could reference?

答:
SaaS ---> [AWS-API-Gateway ---> AWS Lambda ---> Soap Client] --> Site B

This architecture should work. You'll have to figure out a way to authenticate the SaaS site to api gateway (Using api keys/custom authorizer).

You can use a single lambda function to push the event to site b using the client and return a response. Any public java soap client will work. You need to compile the entire program into a jar and upload it as a lambda function.

One thing you might want to look at is using just API Gateway to talk to Site B since API Gateway can transform request/response - http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html.