问:
Two divs with inline-block style not aligned
I have two div tags and only one has input tag; why output is in this way?

div.logo, div.form {
  display: inline-block;
  height: 200px;
  width: 200px;
  border: 1px dotted;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="logo">
  <input type="text">
</div>

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

Output:

Can anyone explain this? Here is the fiddle: https://jsfiddle.net/ag487L5m/

答:
That's because the vertical alignment of inline elements defaults to baseline. Change it to top:

```<code>div.logo, div.form {
  display: inline-block;
  height: 200px;
  width: 200px;
  border: 1px dotted;
  vertical-align:top;
}
</code>```

div.logo, div.form {
  display: inline-block;
  height: 200px;
  width: 200px;
  border: 1px dotted;
  vertical-align:top;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="logo">
  <input type="text">
</div>

<div class="form">

</div></code>```

Body:
I have two div tags and only one has input tag; why output is in this way?

div.logo, div.form {
  display: inline-block;
  height: 200px;
  width: 200px;
  border: 1px dotted;
}

  <input type="text">

Output:

Can anyone explain this? Here is the fiddle: https://jsfiddle.net/ag487L5m/

Body:
That's because the vertical alignment of inline elements defaults to baseline. Change it to top:

div.logo, div.form {
  display: inline-block;
  height: 200px;
  width: 200px;
  border: 1px dotted;
  vertical-align:top;
}

div.logo, div.form {
  display: inline-block;
  height: 200px;
  width: 200px;
  border: 1px dotted;
  vertical-align:top;
}

<div class="logo">
  <input type="text">
</div>

<div class="form">

</div>


来源: stackexchange

问:
save in for loop matlab
I am trying to save variables in a for loop. The following new variable can be created:

```<code>eval(['C' num2str(j) '=B']);
</code>```

But I get an error while using this to save the variable by the following command :

```<code>save([dataDir, files(j).name],eval(['C' num2str(j) '=B']),'-append')
</code>```

The error is : (Error: The expression to the left of the equals sign is not a valid target for an assignment.).

I wonder what is wrong with my approach and how can I save the changing variable name in changing file name in a for loop.

I will greatly appreciate your assistance.

答:
There is an equal sign in your eval statement.

Can't you just save B?
do not use eval in a function itself.

```<code>save([dataDir, files(j).name],B,'-append')
</code>```

Otherwise I would recommend storing the variable name itself

```<code>varname = sprintf('C%.0f',j)
eval([varname,'=B']);
save([dataDir, files(j).name],varname,'-append')
</code>```

ContentLicense: CC BY-SA 3.0

Title: save in for loop matlab

Body:
I am trying to save variables in a for loop. The following new variable can be created:

eval(['C' num2str(j) '=B']);

But I get an error while using this to save the variable by the following command :

save([dataDir, files(j).name],eval(['C' num2str(j) '=B']),'-append')

The error is : (Error: The expression to the left of the equals sign is not a valid target for an assignment.).

I wonder what is wrong with my approach and how can I save the changing variable name in changing file name in a for loop.

I will greatly appreciate your assistance.

Body:
There is an equal sign in your eval statement.

Can't you just save B?
do not use eval in a function itself.

save([dataDir, files(j).name],B,'-append')

Otherwise I would recommend storing the variable name itself

varname = sprintf('C%.0f',j)
eval([varname,'=B']);
save([dataDir, files(j).name],varname,'-append')


问:
"Types of property 'X' are incompatible" but it is not
I tried to create an object of an interface with properties initialized from another object like that:

```<code>id: data.reference.id
</code>```

The properties are compatible, but typescript compiler throws an error. I don't understand why and how to avoid this error.

(a link to test the code can be found after)

```<code>// INTERFACES AND TYPES
type CategoryOne = 1
type CategoryTwo = 2
type Category = CategoryOne | CategoryTwo

interface ReferenceOne {
    id: string,
    type: CategoryOne
}

interface ReferenceTwo {
    id: string,
    type: CategoryTwo
}

type Reference = ReferenceOne |  ReferenceTwo

// DIRECT INIT
let reference_OK: Reference = { // works here
    id: '1',
    type: 1
}

// INIT FROM DATA
interface Data {
    reference: {
        id: string,
        type: Category
    }
}

let data: Data = {
    reference: {
        id: '1',
        type: 1
    }
}

let reference_KO: Reference = { // <--- error here
    id: data.reference.id,      // but compatible property
    type: data.reference.type   // but compatible property
}

let param: Category = data.reference.type // == 1

let reference_KO2: Reference = { // <--- error here
    id: data.reference.id,       // but compatible property
    type: param                  // but compatible property
}

param = 1 // == data.reference.type, same variable

let reference_OK2: Reference = { // <--- no error here
    id: data.reference.id,
    type: param
}
</code>```

this code in Typescript playground

[update] I added the case when a new reference is created from a variable (reference_KO2 - variable initialized from a property of data - and reference_OK2 - same variable initialized with a constant)

two behaviors with the same variable of a compatible type !

答:
While the code appears to be semantically correct, the compiler will disagree because Data does not retain additional information about the category underneath: it only knows that the field type is a Category.

So, we know that reference_ok can be assigned either a ReferenceOne or a ReferenceTwo. ReferenceOne requires type to be a CategoryOne, whereas ReferenceTwo requires type to be a CategoryTwo. Neither of these work, since data.reference.type is a generalized Category. We could reproduce the same effect with less code, by "upcasting" the value on purpose:

```<code>let r: Reference = {
  id: '1',
  type: 1 as Category,
}
</code>```

There are at least two ways to avoid this situation. One of them is to redefine Reference as an interface, which basically tells the compiler that we don't need to know the category in compile time at this point.

```<code>interface Reference {
    id: string,
    type: Category,
}
</code>```

The most appealing solution, however, is with generics. We can augment Data to also contain the type of the category:

```<code>interface Data<C extends Category> {
    reference: {
        id: string,
        type: C
    }
}
</code>```

At this point, this code works:

```<code>let data: Data<CategoryOne> = {
    reference: {
        id: '1',
        type: 1
    }
}

let reference_KO: Reference = {
    id: data.reference.id,
    type: data.reference.type
}
</code>```

The same treatment can be applied to Reference, if so you wish.

Body:
I tried to create an object of an interface with properties initialized from another object like that:

id: data.reference.id

The properties are compatible, but typescript compiler throws an error. I don't understand why and how to avoid this error.

(a link to test the code can be found after)

// INTERFACES AND TYPES
type CategoryOne = 1
type CategoryTwo = 2
type Category = CategoryOne | CategoryTwo

interface ReferenceOne {
    id: string,
    type: CategoryOne
}

interface ReferenceTwo {
    id: string,
    type: CategoryTwo
}

type Reference = ReferenceOne |  ReferenceTwo

// DIRECT INIT
let reference_OK: Reference = { // works here
    id: '1',
    type: 1
}

// INIT FROM DATA
interface Data {
    reference: {
        id: string,
        type: Category
    }
}

let data: Data = {
    reference: {
        id: '1',
        type: 1
    }
}

let reference_KO: Reference = { // <--- error here
    id: data.reference.id,      // but compatible property
    type: data.reference.type   // but compatible property
}

let param: Category = data.reference.type // == 1

let reference_KO2: Reference = { // <--- error here
    id: data.reference.id,       // but compatible property
    type: param                  // but compatible property
}

param = 1 // == data.reference.type, same variable

let reference_OK2: Reference = { // <--- no error here
    id: data.reference.id,
    type: param
}

<a href="https://www.typescriptlang.org/play/index.html#src=%2F%2F%20INTERFACES%20AND%20TYPES%0D%0Atype%20CategoryOne%20%3D%201%0D%0Atype%20CategoryTwo%20%3D%202%0D%0Atype%20Category%20%3D%20CategoryOne%20%7C%20CategoryTwo%0D%0A%0D%0Ainterface%20ReferenceOne%20%7B%0D%0A%20%20%20%20id%3A%20string%2C%0D%0A%20%20%20%20type%3A%20CategoryOne%0D%0A%7D%0D%0A%0D%0Ainterface%20ReferenceTwo%20%7B%0D%0A%20%20%20%20id%3A%20string%2C%0D%0A%20%20%20%20type%3A%20CategoryTwo%0D%0A%7D%0D%0A%0D%0Atype%20Reference%20%3D%20ReferenceOne%20%7C%20%C2%A0ReferenceTwo%0D%0A%0D%0A%2F%2F%20DIRECT%20INIT%0D%0Alet%20reference_OK%3A%20Reference%20%3D%20%7B%20%2F%2F%20works%20here%0D%0A%20%20%20%20id%3A%20'1'%2C%0D%0A%20%20%20%20type%3A%201%0D%0A%7D%0D%0A%0D%0A%2F%2F%20INIT%20FROM%20DATA%0D%0Ainterface%20Data%20%7B%0D%0A%20%20%20%20reference%3A%20%7B%0D%0A%20%20%20%20%20%20%20%20id%3A%20string%2C%0D%0A%20%20%20%20%20%20%20%20type%3A%20Category%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Alet%20data%3A%20Data%20%3D%20%7B%0D%0A%20%20%20%20reference%3A%20%7B%0D%0A%20%20%20%20%20%20%20%20id%3A%20'1'%2C%0D%0A%20%20%20%20%20%20%20%20type%3A%201%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Alet%20reference_KO%3A%20Reference%20%3D%20%7B%20%2F%2F%20%3C---%20error%20here%0D%0A%20%20%20%20id%3A%20data.reference.id%2C%20%20%20%20%20%20%2F%2F%20but%20compatible%20property%0D%0A%20%20%20%20type%3A%20data.reference.type%20%20%20%2F%2F%20but%20compatible%20property%0D%0A%7D%0D%0A%0D%0Alet%20param%3A%20Category%20%3D%20data.reference.type%20%2F%2F%20%3D%3D%201%0D%0A%0D%0Alet%20reference_KO2%3A%20Reference%20%3D%20%7B%20%2F%2F%20%3C---%20error%20here%0D%0A%20%20%20%20id%3A%20data.reference.id%2C%20%20%20%20%20%20%20%2F%2F%20but%20compatible%20property%0D%0A%20%20%20%20type%3A%20param%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2F%2F%20but%20compatible%20property%0D%0A%7D%0D%0A%0D%0Aparam%20%3D%201%20%2F%2F%20%3D%3D%20data.reference.type%2C%20same%20variable%0D%0A%0D%0Alet%20reference_OK2%3A%20Reference%20%3D%20%7B%20%2F%2F%20%3C---%20no%20error%20here%0D%0A%20%20%20%20id%3A%20data.reference.id%2C%0D%0A%20%20%20%20type%3A%20param%0D%0A%7D" rel="noreferrer">this code in Typescript playground

[update] I added the case when a new reference is created from a variable (reference_KO2 - variable initialized from a property of data - and reference_OK2 - same variable initialized with a constant)

two behaviors with the same variable of a compatible type !

Body:
While the code appears to be semantically correct, the compiler will disagree because Data does not retain additional information about the category underneath: it only knows that the field type is a Category.

So, we know that reference_ok can be assigned either a ReferenceOne or a ReferenceTwo. ReferenceOne requires type to be a CategoryOne, whereas ReferenceTwo requires type to be a CategoryTwo. Neither of these work, since data.reference.type is a generalized Category. We could reproduce the same effect with less code, by "upcasting" the value on purpose:

let r: Reference = {
  id: '1',
  type: 1 as Category,
}

There are at least two ways to avoid this situation. One of them is to redefine Reference as an interface, which basically tells the compiler that we don't need to know the category in compile time at this point.

interface Reference {
    id: string,
    type: Category,
}

The most appealing solution, however, is with generics. We can augment Data to also contain the type of the category:

interface Data<C extends Category> {
    reference: {
        id: string,
        type: C
    }
}

At this point, this code works:

let data: Data<CategoryOne> = {
    reference: {
        id: '1',
        type: 1
    }
}

let reference_KO: Reference = {
    id: data.reference.id,
    type: data.reference.type
}

The same treatment can be applied to Reference, if so you wish.


问:
Use js variables in C# Webform(ASP.net)
I have created some variables in my JS file and linked it to my webform in Xhtml code, my js code is as follows:

```<code>var access_key = 'my key';
var email_address;
var valid_format,smtp_check,disposable,mxfound,Urole;
// verify email address via AJAX call
function verify()
{
$.ajax({
url: 'domain/api/check?access_key=' + access_key + '&email=' +
email_address,
dataType: 'jsonp',
success: function validate(json) {
valid_format = json.valid_format ;
smtp_check = json.smtp_check ;
disposable = json.disposable;
mxfound = json.mxfound ;
Urole = json.role ;
}
});
}
</code>```

I need to use variables (valid_format,smtp_check,disposable,mxfound,Urole) from the js part in the Signup.aspx.cp file.

Note: I have linked myJs.js to Signup.aspx file.(myJs is not original name just for example purposes)

答:
These easiest thing to do is probably add some HiddenField server controls and put your values in them clientside, then you can reference the HiddenField controls in your C# code upon the next postback.

For example to do the valid_format value:

```<code><asp:HiddenField runat="server" ID="hdnValidFormat" ClientIDMode="Static" />
</code>```

Then use jQuery to set the value in your success callback:

```<code>$('#hdnValidFormat').val(json.valid_format);
</code>```

Then you can just reference hdnValidFormat.Value in your C# code like normal.

Then just do the same for the other variables.

Notes:

Make sure you have ViewState enabled for the HiddenField controls or the values won't persist across postbacks.

If you can't/don't want to use ClientIDMode="Static" on your HiddenField controls, you can use the default dynamically generated ID, you'll just have to reference them using server code like:

$('#<%=hdnValidFormat.ClientID%>').val(...);

Be careful that you don't do this with values that could be manipulated and compromise the security of your app.  All someone would have to do is edit the markup and they could put whatever values they wanted in there.

Title: Use js variables in C# Webform(ASP.net)

Body:
I have created some variables in my JS file and linked it to my webform in Xhtml code, my js code is as follows:

var access_key = 'my key';
var email_address;
var valid_format,smtp_check,disposable,mxfound,Urole;
// verify email address via AJAX call
function verify()
{
$.ajax({
url: 'domain/api/check?access_key=' + access_key + '&email=' +
email_address,
dataType: 'jsonp',
success: function validate(json) {
valid_format = json.valid_format ;
smtp_check = json.smtp_check ;
disposable = json.disposable;
mxfound = json.mxfound ;
Urole = json.role ;
}
});
}

I need to use variables (valid_format,smtp_check,disposable,mxfound,Urole) from the js part in the Signup.aspx.cp file.

Note: I have linked myJs.js to Signup.aspx file.(myJs is not original name just for example purposes)

Body:
These easiest thing to do is probably add some HiddenField server controls and put your values in them clientside, then you can reference the HiddenField controls in your C# code upon the next postback.

For example to do the valid_format value:

<asp:HiddenField runat="server" ID="hdnValidFormat" ClientIDMode="Static" />

Then use jQuery to set the value in your success callback:

$('#hdnValidFormat').val(json.valid_format);

Then you can just reference hdnValidFormat.Value in your C# code like normal.

Then just do the same for the other variables.

Notes:

Make sure you have ViewState enabled for the HiddenField controls or the values won't persist across postbacks.

If you can't/don't want to use ClientIDMode="Static" on your HiddenField controls, you can use the default dynamically generated ID, you'll just have to reference them using server code like:

$('#<%=hdnValidFormat.ClientID%>').val(...);

Be careful that you don't do this with values that could be manipulated and compromise the security of your app.  All someone would have to do is edit the markup and they could put whatever values they wanted in there.


问:
migrate oracle to Postgresql UTL_FILE EXCEPTIONS
I have the same situation as described in this post: Porting Oracle procedure to PostgreSQL (exception codes from orafce for utl_file module)

I'm migrating from oracle to postgres with ora2pg and I`m trying to correct the syntax of the exception handling that I have for 'utl_file'. Someone commented a solution in the other post but I didn't understand how to properly apply it.

I have the next code :

```<code>   V_Step := 1;

    FOR Rec_Report IN C_Report LOOP

      V_Counter := V_Counter + 1;

      -- Header
      IF V_Counter = 1 THEN

         -- Open File
        V_File_Type := UTL_FILE.FOPEN(V_Dir_Name, V_File_Name,'w');

        V_Step := 2;

        bl_create_flat_file_pg.open_html(V_File_Type);
         .......
         .......
         .......

          V_Step :=10

EXCEPTION
when UTL_FILE.INVALID_PATH then
PERFORM control_reports_pg.send_error_mail('invalid_path
V_Step'||V_Step,C_Function_Name);
PERFORM UTL_FILE.FCLOSE(V_File_Type);

when UTL_FILE.INVALID_MODE then
PERFORM control_reports_pg.send_error_mail('INVALID_MODE
 V_Step'||V_Step,C_Function_Name);
     PERFORM  UTL_FILE.FCLOSE(V_File_Type);
</code>```

Therefore for every step I have a piece of code like this that handles the exception. I get a syntax error :
ERROR:  syntax error at or near "UTL_FILE".

Please help...

答:
I've been writing PL/SQL for quite some time and I've never come across the PERFORM imperative. If this code is to run on an Oracle instance, then I would simply the remove the two "PERFORM" strings.

If this is supposed to run on a POSTGRES instance, then I'd not expect UTL_FILE to exist. If it does exist, then maybe the user running the code has not been granted permissions to execute UTL_FILE.

Body:
I have the same situation as described in this post: Porting Oracle procedure to PostgreSQL (exception codes from orafce for utl_file module)

I'm migrating from oracle to postgres with ora2pg and I`m trying to correct the syntax of the exception handling that I have for 'utl_file'. Someone commented a solution in the other post but I didn't understand how to properly apply it.

I have the next code :

   V_Step := 1;

    FOR Rec_Report IN C_Report LOOP

      V_Counter := V_Counter + 1;

      -- Header
      IF V_Counter = 1 THEN

         -- Open File
        V_File_Type := UTL_FILE.FOPEN(V_Dir_Name, V_File_Name,'w');

        V_Step := 2;

        bl_create_flat_file_pg.open_html(V_File_Type);
         .......
         .......
         .......

          V_Step :=10

EXCEPTION
when UTL_FILE.INVALID_PATH then
PERFORM control_reports_pg.send_error_mail('invalid_path
V_Step'||V_Step,C_Function_Name);
PERFORM UTL_FILE.FCLOSE(V_File_Type);

when UTL_FILE.INVALID_MODE then
PERFORM control_reports_pg.send_error_mail('INVALID_MODE
 V_Step'||V_Step,C_Function_Name);
     PERFORM  UTL_FILE.FCLOSE(V_File_Type);

Therefore for every step I have a piece of code like this that handles the exception. I get a syntax error :
ERROR:  syntax error at or near "UTL_FILE".

Please help...


问:
mac terminal: Adding 127.0.0.1 calypso.localhost to localhost file
I am trying out wp-calypso which requires an addition to my localhost file. Via the terminal, I first typed

```<code>sudo vim /etc/localhost
</code>```

which took me here

```<code>...

~

~

~

~

~

"/etc/localhost" [New File]
</code>```

I seem to be presented with a different screen than what's presented in the guide via https://www.howtogeek.com/howto/27350/beginner-geek-how-to-edit-your-hosts-file/

I then in the first line tried typing..

```<code>172.0.0.1      calypso.localhost

~

~

~

~

~

-- INSERT --
</code>```

and realized I had no idea what to do next. Am I even in the right file? What would be my next steps?

答:
On a mac, the file you are looking for is /etc/hosts, not /etc/localhost.

Using nano:

```<code>$ sudo nano /etc/hosts
</code>```

Enter your sudo password, then navigate your cursor to the end of the file and add the line for calypso:

```<code>127.0.0.1    calypso.localhost
</code>```

Hit ctrl-x then y to save your hosts file.

Body:
I am trying out wp-calypso which requires an addition to my localhost file. Via the terminal, I first typed

sudo vim /etc/localhost

which took me here

...

~

~

~

~

~

"/etc/localhost" [New File]

I seem to be presented with a different screen than what's presented in the guide via https://www.howtogeek.com/howto/27350/beginner-geek-how-to-edit-your-hosts-file/

I then in the first line tried typing..

172.0.0.1      calypso.localhost

~

~

~

~

~

-- INSERT --

and realized I had no idea what to do next. Am I even in the right file? What would be my next steps?

Body:
On a mac, the file you are looking for is /etc/hosts, not /etc/localhost.

Using nano:

$ sudo nano /etc/hosts

Enter your sudo password, then navigate your cursor to the end of the file and add the line for calypso:

127.0.0.1    calypso.localhost

Hit ctrl-x then y to save your hosts file.


问:
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!

答:
Looks like the error you are seeing is caused by some issue on Google's side. It's affecting quite a few other users as well, have a look at their public issue tracker:

Thanks for reporting this issue. We verified it and we'll keep tracking it.
  https://issuetracker.google.com/issues/63298126

UPDATE (2017-07-06):

A fix for this is going into our release process now and it should be out soon - probably Monday at the latest.
  https://issuetracker.google.com/issues/63298126#comment13

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!


问:
Jenkins is going to shut down
A strange thing happen sometime, Jenkins start displaying " Jenkins is going to shut down" even when nobody turned this message on and restarting Jenkins.

Screenshot:

答: To get rid of the 'Shutdown' message one can also login to the actual Jenkins admin section, go to "Manage Jenkins" link on the left then click on ->"Cancel Shutdown"</p>

Title: Jenkins is going to shut down


问:
Getting failed to configure cluster endpoints error when using DAX with DynamoDB
I created a cluster according to AWS' tutorials and it supposed to be working just fine but when I try to connect to it, I get the following error

java.io.IOException: failed to configure cluster endpoints from hosts: [mydaxcluster.ximfba.clustercfg.dax.use1.cache.amazonaws.com:8111]
      at com.amazon.dax.client.cluster.Source$AutoconfSource.pull(Source.java:128) ~[DaxJavaClient-latest.jar:1.0.792.0]
      at com.amazon.dax.client.cluster.Source$AutoconfSource.update(Source.java:60) ~[DaxJavaClient-latest.jar:1.0.792.0]
      at com.amazon.dax.client.cluster.Source$AutoconfSource.refresh(Source.java:51) ~[DaxJavaClient-latest.jar:1.0.792.0]
      at com.amazon.dax.client.cluster.Cluster.refresh(Cluster.java:311) ~[DaxJavaClient-latest.jar:1.0.792.0]
      at com.amazon.dax.client.cluster.Cluster.refresh(Cluster.java:294) ~[DaxJavaClient-latest.jar:1.0.792.0]
      at com.amazon.dax.client.cluster.Cluster.startup(Cluster.java:191) ~[DaxJavaClient-latest.jar:1.0.792.0]
      at com.amazon.dax.client.cluster.Cluster.startup(Cluster.java:143) ~[DaxJavaClient-latest.jar:1.0.792.0]
      at com.amazon.dax.client.dynamodbv2.ClusterDaxClient.(ClusterDaxClient.java:159) [DaxJavaClient-latest.jar:1.0.792.0]
      at com.amazon.dax.client.dynamodbv2.ClusterDaxClient.(ClusterDaxClient.java:130) [DaxJavaClient-latest.jar:1.0.792.0]
      at com.poc.dynamo.controller.DataController.testDax(DataController.java:190) [classes/:na]
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
      at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
      at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.11.jar:8.5.11]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:108) [spring-boot-actuator-1.5.1.RELEASE.jar:1.5.1.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106) [spring-boot-actuator-1.5.1.RELEASE.jar:1.5.1.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.11.jar:8.5.11]
      at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]
  Caused by: java.net.ConnectException: timeout waiting for an available tube
      at com.amazon.dax.client.SocketTubePool.alloc(SocketTubePool.java:77) ~[DaxJavaClient-latest.jar:1.0.792.0]
      at com.amazon.dax.client.generated.DaxClientStubs.endpoints_455855874_1(DaxClientStubs.java:449) ~[DaxJavaClient-latest.jar:1.0.792.0]
      at com.amazon.dax.client.dynamodbv2.DaxClient.endpoints(DaxClient.java:1825) ~[DaxJavaClient-latest.jar:1.0.792.0]
      at com.amazon.dax.client.cluster.Source$AutoconfSource.pullFrom(Source.java:138) ~[DaxJavaClient-latest.jar:1.0.792.0]
      at com.amazon.dax.client.cluster.Source$AutoconfSource.pull(Source.java:106) ~[DaxJavaClient-latest.jar:1.0.792.0]
      ... 75 common frames omitted
      Suppressed: java.net.ConnectException: timeout waiting for an available tube
          ... 80 common frames omitted
      Suppressed: java.net.ConnectException: timeout waiting for an available tube
          ... 80 common frames omitted

Unable to read item
Unable to call cluster endpoint: No endpoints available

答:
We will need to know more info about how you setup your DAX cluster and client instances to be able to help. Some general ideas to try:

Are you able to connect to the DAX cluster from the EC2 client instance? Try running:
nc -z mydaxcluster.ximfba.clustercfg.dax.use1.cache.amazonaws.com 8111

Have you used the default security group for your VPC to create DAX cluster? You will need to authorize inbound traffic on TCP port 8111 to the security group used to create the DAX cluster from the security group of the client instance. Please follow the steps for configuring security group rules for your VPC


问:
Drawing atop a scrollable, zoomable image in Qt
I'm sorry if my question is somewhat vague. It's been a few years since I did anything with Qt, and back then I never did any fancy image stuff. What I'm asking for below is just some general suggestions on which classes to consider using. I'm trying to avoid barking up the wrong tree from the very start.

The situation: I'm writing a Qt-based program in which I need to display a somewhat large (let's say 5000x5000) raster image. The user should be able to zoom (quickly) in and out, and pan around the image in a way similar to for example Google maps. So far, this is not very different from the Qt ImageViewer example, except perhaps for the requirement that zooming happens quickly. However, I need to draw on the order of 50k simple geometric shapes (let's say circles) on top of the image, and be able to add and remove some of these in a simple way. The circles should have the same size no matter the zoom level, and should thus either be redrawn whenever the user zooms, or should be drawn with vector graphics. Think of the circles as map annotations. These should look the same at any zoom level, and also behave nicely with respect to panning.

I guess my question is twofold:

Can Qt draw vector graphics on top of a raster image?

In general, which classes should I consider for the above?

Thanks in advance. I don't like answering vague questions myself, but maybe someone with experience with Qt's graphics capabilities has an answer.

答:
I suggest you use QGraphicsView and friends for this. It helps handling all the view/world transformation and the vector items can be achieved with various QGraphicsItems.

You can change the sizes of the items whenever the zoom level changes to maintain constant apparent sizes.

ContentLicense: CC BY-SA 2.5


问:
How to set border to div element for text formatting?
I'm working a comment section page where it allows the user to leave a comment. I need assistance in my layout for displaying the comments into the repeater control. I used to put the comments inside the div element of the item and alternatingitem template of the repeater. And as a result, the comment would go straight along the line in the div element if the user is typing too many words or paragraph. What I want is to put a limit where the text will stop and proceed to the next line of the div element. How would I do that?What is the best way?Any suggestion? Here's my layout for the repeater control where I used to insert the comments.</p>

```<code><asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">

<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td >
<div style="background-color:#FFFF66" >
<%# Eval("Name") %> Says...
<%# Eval("Comments") %>
</div>
</td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr>
<td >
<div style="background-color:#CCFF33" >
<%# Eval("Name")%> Says...
<%# Eval("Comments")%>
</div>
</td>
</tr>
</AlternatingItemTemplate>
<SeparatorTemplate >
<br />
</SeparatorTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
</code>```

答:
Refer to Is there a way to word-wrap long words in a div?

I had the same problem with a repeater inside a div and I found the answer there.

/* Source: http://snipplr.com/view/10979/css-cross-browser-word-wrap */

```<code>.wordwrap {
   white-space: pre-wrap;      /* CSS3 */
   white-space: -moz-pre-wrap; /* Firefox */
   white-space: -pre-wrap;     /* Opera <7 */
   white-space: -o-pre-wrap;   /* Opera 7 */
   word-wrap: break-word;      /* IE */
}
</code>```

Body:
I'm working a comment section page where it allows the user to leave a comment. I need assistance in my layout for displaying the comments into the repeater control. I used to put the comments inside the div element of the item and alternatingitem template of the repeater. And as a result, the comment would go straight along the line in the div element if the user is typing too many words or paragraph. What I want is to put a limit where the text will stop and proceed to the next line of the div element. How would I do that?What is the best way?Any suggestion? Here's my layout for the repeater control where I used to insert the comments.

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">

<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>

<%# Eval("Name") %> Says...
<%# Eval("Comments") %>

</ItemTemplate>
<AlternatingItemTemplate>

<%# Eval("Name")%> Says...
<%# Eval("Comments")%>

</AlternatingItemTemplate>
<SeparatorTemplate >

</SeparatorTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>

Body:
Refer to Is there a way to word-wrap long words in a div?

I had the same problem with a repeater inside a div and I found the answer there.

/* Source: http://snipplr.com/view/10979/css-cross-browser-word-wrap */

.wordwrap {
   white-space: pre-wrap;      /* CSS3 */
   white-space: -moz-pre-wrap; /* Firefox */
   white-space: -pre-wrap;     /* Opera <7 */
   white-space: -o-pre-wrap;   /* Opera 7 */
   word-wrap: break-word;      /* IE */
}


问:
Performance issue in bulk importing data in Dynamics CRM
I am importing data to Dynamics CRM using C# console application. I am using following code:

```<code>    public static void Main(string[] args)
    {
            int totalRecords = dbcon.GetDataCount();
            int rowCount = totalRecords / 10;

            for (int i = 1, j = 1; i <= totalRecords; i = i + rowCount, j = j + 1)
            {
                Task myTask = new Task(() => TestMethod(i, (rowCount * j)));
                myTask.Start();
            }
          Task.WaitAll();
     }

public static void TestMethod(int startSeqNo, int endSeqNo)
{
   IOrganizationService service = getServiceProxcy();
    DBConnection dbcon = new DBConnection();
    DataTable dt = dbcon.GetData(startSeqNo, endSeqNo);
    // Insert Commented
    BulkCreate(service, dt);
 }

public static void BulkCreate(IOrganizationService service, DataTable dt)
{
  // Create an ExecuteMultipleRequest object.
  ExecuteMultipleRequest multipleRequest = new ExecuteMultipleRequest()
  {
    // Assign settings that define execution behavior: continue on error, return responses.
    Settings = new ExecuteMultipleSettings()
    {
        ContinueOnError = false,
        ReturnResponses = true
    },
    // Create an empty organization request collection.
    Requests = new OrganizationRequestCollection()
};

foreach (DataRow row in dt.Rows)
{
    Entity entity = new Entity("new_dataimporttest");
    entity["new_name"] = row["name"].ToString();
    entity["new_telephone"] = row["telephone1"].ToString();
    if (multipleRequest.Requests.Count == 1000)
    {
        // Execute all the requests in the request collection using a single web method call.
        ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
        multipleRequest.Requests.Clear();
    }
    CreateRequest createRequest = new CreateRequest { Target = entity };
    multipleRequest.Requests.Add(createRequest);
}

// Execute all the requests in the request collection using a single web method call.
if (multipleRequest.Requests.Count > 0)
{
    ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
}
}
</code>```

I am using Task Parallel Library. It works fine but issue is that when following line is executed it takes time.

```<code>// Execute all the requests in the request collection using a single web method call.
    //            ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
</code>```

I want to improve performance of code as I am importing large amount of data nearly 1 million records. Currently it takes 1h 50 mins. How do I improve code to reduce execution time.

答:
With the ExecuteMultipleRequest data throughput can only be enhanced in a limited way. This is because the Dynamics CRM server processes the requests in it in sequential order, not parallel. Therefore your main gain is less roundtrips to the server.

Throughput can really be boosted when working with multiple threads. Every thread communicating with CRM must get its own IOrganizationService instance. By default a CRM server accepts up to 10 simultaneous connections from a client. (This is the WCF default.)

In batch processes I tend to use a BlockingCollection<T> with a Producer Consumer pattern: one thread produces the requests to be sent to the CRM server and multiple threads consume the requests by taking them off the collection and sending them to CRM.

ContentLicense: CC BY-SA 4.0

Body:
I am importing data to Dynamics CRM using C# console application. I am using following code:

    public static void Main(string[] args)
    {
            int totalRecords = dbcon.GetDataCount();
            int rowCount = totalRecords / 10;

            for (int i = 1, j = 1; i <= totalRecords; i = i + rowCount, j = j + 1)
            {
                Task myTask = new Task(() => TestMethod(i, (rowCount * j)));
                myTask.Start();
            }
          Task.WaitAll();
     }

public static void TestMethod(int startSeqNo, int endSeqNo)
{
   IOrganizationService service = getServiceProxcy();
    DBConnection dbcon = new DBConnection();
    DataTable dt = dbcon.GetData(startSeqNo, endSeqNo);
    // Insert Commented
    BulkCreate(service, dt);
 }

public static void BulkCreate(IOrganizationService service, DataTable dt)
{
  // Create an ExecuteMultipleRequest object.
  ExecuteMultipleRequest multipleRequest = new ExecuteMultipleRequest()
  {
    // Assign settings that define execution behavior: continue on error, return responses.
    Settings = new ExecuteMultipleSettings()
    {
        ContinueOnError = false,
        ReturnResponses = true
    },
    // Create an empty organization request collection.
    Requests = new OrganizationRequestCollection()
};

foreach (DataRow row in dt.Rows)
{
    Entity entity = new Entity("new_dataimporttest");
    entity["new_name"] = row["name"].ToString();
    entity["new_telephone"] = row["telephone1"].ToString();
    if (multipleRequest.Requests.Count == 1000)
    {
        // Execute all the requests in the request collection using a single web method call.
        ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
        multipleRequest.Requests.Clear();
    }
    CreateRequest createRequest = new CreateRequest { Target = entity };
    multipleRequest.Requests.Add(createRequest);
}

// Execute all the requests in the request collection using a single web method call.
if (multipleRequest.Requests.Count > 0)
{
    ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
}
}

I am using Task Parallel Library. It works fine but issue is that when following line is executed it takes time.

// Execute all the requests in the request collection using a single web method call.
    //            ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);

I want to improve performance of code as I am importing large amount of data nearly 1 million records. Currently it takes 1h 50 mins. How do I improve code to reduce execution time.


问:
in typescript, how do I implement a interface with a callback?
I created an interface in typescript with callback, how do I implement it?</p>

```<code>interface LoginCallback{
    Error: boolean,
    UserInfo: {
        Id: string,
        OrganizationId: string
    }
}

interface IntegrationInterface {
    Init(): void;
    LogIn(UserName: string, Password: string, LoginCallback:LoginCallback): void;
}
</code>```

答:
The way you declared LoginCallback means it's just an object rather than a function. I assume this is what you wanted:

```<code>interface LoginCallback {
    (Error: boolean, UserInfo: { Id: string, OrganizationId: string }): void;
}

interface IntegrationInterface {
    Init(): void;
    LogIn(UserName: string, Password: string, LoginCallback: LoginCallback): void;
}
</code>```

Then to implement the interface you can do:

```<code>class IntegrationImpl implements IntegrationInterface {
    Init() {
       //...
    }
    LogIn(UserName: string, Password: string, LoginCallback: LoginCallback) {
     //...
    }

}
</code>```

Body:
I created an interface in typescript with callback, how do I implement it?

interface LoginCallback{
    Error: boolean,
    UserInfo: {
        Id: string,
        OrganizationId: string
    }
}

interface IntegrationInterface {
    Init(): void;
    LogIn(UserName: string, Password: string, LoginCallback:LoginCallback): void;
}

Body:
The way you declared LoginCallback means it's just an object rather than a function. I assume this is what you wanted:

interface LoginCallback {
    (Error: boolean, UserInfo: { Id: string, OrganizationId: string }): void;
}

interface IntegrationInterface {
    Init(): void;
    LogIn(UserName: string, Password: string, LoginCallback: LoginCallback): void;
}

Then to implement the interface you can do:

class IntegrationImpl implements IntegrationInterface {
    Init() {
       //...
    }
    LogIn(UserName: string, Password: string, LoginCallback: LoginCallback) {
     //...
    }

}


问:
How do you combine two arrays in such a way that the two are equally distributed?
It is way easier to give an example than to explain it with words.
Starting with 2 arrays:

{a,a,a,a,a,a,a} and {b,b,b}

I would like the output to be:

{a,a,b,a,a,b,a,a,b,a}

With a little help I found the following:

```<code>    let result = [];
    let ratio = array1.length / array2.length;
    let pushA = 0;
    while (array2.length >0) {
        pushA+= ratio;
        while (pushA >= 1){
            result.push(array1.pop());
            pushA--;
        }
        result.push(array2.pop());

    }

    return result;
</code>```

答:
Slightly non-traditional way:

Use simplest implementation of Bresenham algorithm for segment with coordinates (0,0) - (A.Length, B.Length)

When x is incremented - insert "a", when y - insert "b"  (in general case - use next index from corresponding array)

Body:
It is way easier to give an example than to explain it with words.
Starting with 2 arrays:

{a,a,a,a,a,a,a} and {b,b,b}

I would like the output to be:

{a,a,b,a,a,b,a,a,b,a}

With a little help I found the following:

    let result = [];
    let ratio = array1.length / array2.length;
    let pushA = 0;
    while (array2.length >0) {
        pushA+= ratio;
        while (pushA >= 1){
            result.push(array1.pop());
            pushA--;
        }
        result.push(array2.pop());

    }

    return result;


问:
Getting all open files for process results in errno 12 = Out of Memory
With the help of SO, I wrote an app that displays all open TCP/UDP connections in Swift.
In the next step, I would like to get the process that opened the connection (pretty much as lsof does).

Since lsof is open source, I could write the following code to get all the open files for a process:

Bridging-Header:

```<code>#include <mach/mach_types.h>
#include <mach/vm_param.h>
#include <mach/host_info.h>
#include <mach/task_info.h>
#include <mach/thread_info.h>
#include <mach/vm_region.h>
#include <libproc.h>

#include <sys/proc_info.h>
#include <sys/kdebug.h>
#include <sys/msgbuf.h>
</code>```

(I don't think every include is needed, but at least it compiles for now).

```<code>for app in NSWorkspace.shared().runningApplications
    {
        let pid = app.processIdentifier

        var tai = proc_taskallinfo()
        let size = MemoryLayout<proc_bsdinfo>.size
        var result = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &tai, Int32(size))
        let fileCount: Int32 = Int32(tai.pbsd.pbi_nfiles)

        if result <= 0
        {
            if errno == ENOMEM
            {
                Swift.print("Out of memory.")
            }
            Swift.print(errno)
            continue
        }

        var fid = proc_fdinfo()
        let fdInfoSize = MemoryLayout<proc_fdinfo>.size
        result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, &fid, Int32(fdInfoSize) * fileCount)

        if result <= 0
        {
            Swift.print("Error. No Files?")
        }
        else
        {
            Swift.print("Files found.")
        }
    }
</code>```

The code was ported from C to Swift 3. The original C code looks like this:

```<code>int nb;
struct proc_taskallinfo tai;
...
nb = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &tai, sizeof(tai));
</code>```

When I run my code, I get the errno 12 (Out of memory). Why?

P.S. I know that the second proc_pidinfo will also fail because a pointer to an array of proc_fdinfo is returned and not a pointer to a single struct, but one step at a time. It's all about the errno 12.

答:
There are two errors. First, it should be

```<code>let size = MemoryLayout<proc_taskallinfo>.size
</code>```

Second, the proc_pidinfo(pid, PROC_PIDLISTFDS, ...) expects a buffer
with room for fileCount structures of type proc_fdinfo, not just
a single one:

```<code>var fid = Array(repeating: proc_fdinfo(), count: Int(fileCount))
let fdInfoSize = MemoryLayout<proc_fdinfo>.stride
result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, &fid, Int32(fdInfoSize) * fileCount)
</code>```

Body:
With the help of SO, I wrote an app that displays all open TCP/UDP connections in Swift.
In the next step, I would like to get the process that opened the connection (pretty much as lsof does).

Since lsof is open source, I could write the following code to get all the open files for a process:

Bridging-Header:

#include <mach/mach_types.h>
#include <mach/vm_param.h>
#include <mach/host_info.h>
#include <mach/task_info.h>
#include <mach/thread_info.h>
#include <mach/vm_region.h>
#include <libproc.h>

#include <sys/proc_info.h>
#include <sys/kdebug.h>
#include <sys/msgbuf.h>

(I don't think every include is needed, but at least it compiles for now).

for app in NSWorkspace.shared().runningApplications
    {
        let pid = app.processIdentifier

        var tai = proc_taskallinfo()
        let size = MemoryLayout<proc_bsdinfo>.size
        var result = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &tai, Int32(size))
        let fileCount: Int32 = Int32(tai.pbsd.pbi_nfiles)

        if result <= 0
        {
            if errno == ENOMEM
            {
                Swift.print("Out of memory.")
            }
            Swift.print(errno)
            continue
        }

        var fid = proc_fdinfo()
        let fdInfoSize = MemoryLayout<proc_fdinfo>.size
        result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, &fid, Int32(fdInfoSize) * fileCount)

        if result <= 0
        {
            Swift.print("Error. No Files?")
        }
        else
        {
            Swift.print("Files found.")
        }
    }

The code was ported from C to Swift 3. The original C code looks like this:

int nb;
struct proc_taskallinfo tai;
...
nb = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &tai, sizeof(tai));

When I run my code, I get the errno 12 (Out of memory). Why?

P.S. I know that the second proc_pidinfo will also fail because a pointer to an array of proc_fdinfo is returned and not a pointer to a single struct, but one step at a time. It's all about the errno 12.

Body:
There are two errors. First, it should be

let size = MemoryLayout<proc_taskallinfo>.size

Second, the proc_pidinfo(pid, PROC_PIDLISTFDS, ...) expects a buffer
with room for fileCount structures of type proc_fdinfo, not just
a single one:

var fid = Array(repeating: proc_fdinfo(), count: Int(fileCount))
let fdInfoSize = MemoryLayout<proc_fdinfo>.stride
result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, &fid, Int32(fdInfoSize) * fileCount)


问:
How to intercept an outgoing Text Message on Android and notify user
Is it possible on Android to intercept an outgoing text message and show a "prompt" to the user before it goes out?

For example, can I look at a message, do a spell check, then prompt the user to change the spelling of something before the message is actually sent?

Or, for another example, if I were to create a game around text messaging, and the format of the text needed to be changed a little before going to the receiver (like adding a comma).

Is this even possible?  If so, where do I start to learn how to do this?

答:
Is it possible on Android to intercept an outgoing text message and show a "prompt" to the user before it goes out?

AFAIK, no. SmsManager -- what everything on the device uses to send SMS messages -- sends them directly. There are no broadcast Intents or plug-ins or anything to intercept these messages. In part, I imagine this is for privacy reasons.


问:
Add code into JS with button click
So I have these buttons that when pressed play a sound, and I wanted to make a button that when pressed would allow these sounds to loop. I dont know how to explain this correctly, so ill just show the code

```<code>function aud1play() {
  aud1.src = "aud1.mp3";
  aud1.play();
}
document.getElementById('aud1button').addEventListener('click', aud1play);

function aud2play() {
  aud2.src = "aud2.mp3";
  aud2.play();
}
document.getElementById('aud2button').addEventListener('click', aud2play);

function aud3play() {
  aud3.src = "aud3.mp3";
  aud3.play();
}
document.getElementById('aud3button').addEventListener('click', aud3play);
</code>```

is there a way to take the names (aud1, aud2, aud3) and put (name).loop; under each of the functions with a button press without having to actually write the (name).loop; for every one?

答:
Try this

JS:

```<code>function play(){
    var audio = document.getElementById("audio");
    audio.play();
}
</code>```

HTML5:

```<code><audio controls loop id="audio">
  <source src="horse.mp3" type="audio/mpeg">
</audio>
</code>```

Title: Add code into JS with button click

Body:
So I have these buttons that when pressed play a sound, and I wanted to make a button that when pressed would allow these sounds to loop. I dont know how to explain this correctly, so ill just show the code

function aud1play() {
  aud1.src = "aud1.mp3";
  aud1.play();
}
document.getElementById('aud1button').addEventListener('click', aud1play);

function aud2play() {
  aud2.src = "aud2.mp3";
  aud2.play();
}
document.getElementById('aud2button').addEventListener('click', aud2play);

function aud3play() {
  aud3.src = "aud3.mp3";
  aud3.play();
}
document.getElementById('aud3button').addEventListener('click', aud3play);

is there a way to take the names (aud1, aud2, aud3) and put (name).loop; under each of the functions with a button press without having to actually write the (name).loop; for every one?

Body:
Try this

JS:

function play(){
    var audio = document.getElementById("audio");
    audio.play();
}

HTML5:

<audio controls loop id="audio">
  <source src="horse.mp3" type="audio/mpeg">
</audio>


问:
Programmatically Scroll an SWT Table horizontally
Similar question, but not exactly the same.

table.showColumn() is helpful, but the scrolling only has the granularity of the column width. But I want a more precise control of the scroll location.

Consider the following use case. I have two tables that I know are of the same width and have the same column widths. And I want to implement some kind of a scroll synchronizer so that when the user scrolls one table (horizontally), the other table scrolls to the same location.

EDIT:

On the Eclipse forum there seems to be the same question and some working ideas, but no resolution.

EDIT:
I discovered this behavior on Windows

答:
Having poked around in the ScrollBar source a bit, it looks like there are numerous (windows) bugs that have been overcome at one point or another.  This may be another, though you didn't mention your OS, nor did Paul, so it's hard to tell.

All the "change the scroll bar position" functions end up calling SetScrollInfo which is package private.  I suspect that the intention is for this to actually update things the way you want.

None of that solves your problem.  Thankfully the same source also hints at a solution:

Slider.

You'd have to reimplement all the scrollbar behavior within slider, but once done, that should give you the control (har) you want.  Hopefully.  OTOH, you may run into exactly the same OS bug (if bug it be), and be back at square one.

At THAT point, you definitely register it as an Eclipse UI bug.

PS: Have you searched the Eclipse Bugzilla for anything similar?  Poking around a bit turned up this bug related to the scroll bar being out of sync with a tree view in the Navigator (on PC Linux-Motif, but working fine in Windows).  I suspect you'll find similar issues if you dig a bit more.


问:
Trouble connecting to PostgreSQL in python with psycopg2
I am having problems connecting to my database through postgreSQL3 version 9.5. However, after running the code below:

```<code>import psycopg2 as p

con = p.connect("dbname ='dvdrental' user = 'myusername' host ='localhost' password ='somepassword'")
cur = con.cursor()
cur.execute("select * from title")
rows = cur.fetchall()
</code>```

I get this error message:

```<code>psycopg2.OperationalError: could not connect to server: Connection refused
(0x0000274D/10061)
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused (0x0000274D/10061)
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
</code>```

For background information, I accidentally downloaded the newest version of PostgreSQL, and it connected to the part 5432. I need it to connect to PostgreSQL port 5433. I do not know how to do that. How can I solve this DB problem? Is this a PostgreSQL problem or a python problem?

答:
what if you add port = '5433' to your p.connect line?

```<code>import psycopg2 as p

con = p.connect("dbname ='dvdrental' user = 'myusername' host ='localhost' password ='somepassword' port='5433'")
cur = con.cursor()
cur.execute("select * from title")
rows = cur.fetchall()
</code>```

Body:
I am having problems connecting to my database through postgreSQL3 version 9.5. However, after running the code below:

import psycopg2 as p

con = p.connect("dbname ='dvdrental' user = 'myusername' host ='localhost' password ='somepassword'")
cur = con.cursor()
cur.execute("select * from title")
rows = cur.fetchall()

I get this error message:

psycopg2.OperationalError: could not connect to server: Connection refused
(0x0000274D/10061)
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused (0x0000274D/10061)
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?

For background information, I accidentally downloaded the newest version of PostgreSQL, and it connected to the part 5432. I need it to connect to PostgreSQL port 5433. I do not know how to do that. How can I solve this DB problem? Is this a PostgreSQL problem or a python problem?

Body:
what if you add port = '5433' to your p.connect line?

import psycopg2 as p

con = p.connect("dbname ='dvdrental' user = 'myusername' host ='localhost' password ='somepassword' port='5433'")
cur = con.cursor()
cur.execute("select * from title")
rows = cur.fetchall()


问:
Two divs with inline-block style not aligned
I have two div tags and only one has input tag; why output is in this way?

div.logo, div.form {
  display: inline-block;
  height: 200px;
  width: 200px;
  border: 1px dotted;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="logo">
  <input type="text">
</div>

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

Output:

Can anyone explain this? Here is the fiddle: https://jsfiddle.net/ag487L5m/

答:
By default, inline and inline-block elements are set to vertical-align: baseline.

Since your div.logo has a text input, div.form which is now an inline-block element, aligns itself on the baseline of the input.

Adding vertical-align: top to the CSS should fix it.  As in:

```<code>div.logo, div.form {
    display: inline-block;
    height: 200px;
    width: 200px;
    border: 1px dotted;
    vertical-align: top;
}
</code>```

div.logo, div.form {
    display: inline-block;
    height: 200px;
    width: 200px;
    border: 1px dotted;
    vertical-align:top;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="logo">
  <input type="text">
</div>

<div class="form">

</div></code>```

Body:
I have two div tags and only one has input tag; why output is in this way?

div.logo, div.form {
  display: inline-block;
  height: 200px;
  width: 200px;
  border: 1px dotted;
}

  <input type="text">

Output:

Can anyone explain this? Here is the fiddle: https://jsfiddle.net/ag487L5m/

Body:
By default, inline and inline-block elements are set to vertical-align: baseline.

Since your div.logo has a text input, div.form which is now an inline-block element, aligns itself on the baseline of the input.

Adding vertical-align: top to the CSS should fix it.  As in:

div.logo, div.form {
    display: inline-block;
    height: 200px;
    width: 200px;
    border: 1px dotted;
    vertical-align: top;
}

div.logo, div.form {
    display: inline-block;
    height: 200px;
    width: 200px;
    border: 1px dotted;
    vertical-align:top;
}

<div class="logo">
  <input type="text">
</div>

<div class="form">

</div>


问:
RecyclerView startSmoothScroll() incorrect scroll amount with AppBarLayout?
I'm having trouble implementing smooth scroll with a RecyclerView when it is paired with AppBarLayout. This is my layout:

```<code><CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="#ff0000"
            app:layout_scrollFlags="scroll|enterAlways|snap" />
    </AppBarLayout>

    <RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</CoordinatorLayout>
</code>```

I try to scroll to a position like so:

```<code>RecyclerView.SmoothScroller ss = new LinearSmoothScroller(getActivity()) {
        @Override protected int getVerticalSnapPreference() {
            return LinearSmoothScroller.SNAP_TO_END;
        }
    };
ss.setTargetPosition(position);
llm.startSmoothScroll(ss);
</code>```

There are two problems:

If the target position is off the bottom edge of the recycler view, the scroll amount is incorrect - it is offset by the height of the AppBarLayout. If I change to SNAP_TO_START, then it works fine. Or, if I remove the AppBarLayout, it works fine in all cases.

Attempting to scroll to the last element in the recycler view is broken in additional ways. The SNAP_TO_START flag usually works fine (see #1), but in this case the recycler view refuses to scroll it up completely.

So removing the AppBarLayout fixes everything, is there some additional setting needed when using this with AppBarLayout? I'm on the latest support library version.

Thanks

答:
Please use smoothScrollToPosition to fix your issue as below.

```<code>RecyclerView rv = (RecyclerView)findViewById(R.id.recyclerView);
rv.smoothScrollToPosition(mMessages.count-1);
</code>```

Body:
I'm having trouble implementing smooth scroll with a RecyclerView when it is paired with AppBarLayout. This is my layout:

<CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="#ff0000"
            app:layout_scrollFlags="scroll|enterAlways|snap" />
    </AppBarLayout>

    <RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</CoordinatorLayout>

I try to scroll to a position like so:

RecyclerView.SmoothScroller ss = new LinearSmoothScroller(getActivity()) {
        @Override protected int getVerticalSnapPreference() {
            return LinearSmoothScroller.SNAP_TO_END;
        }
    };
ss.setTargetPosition(position);
llm.startSmoothScroll(ss);

There are two problems:

If the target position is off the bottom edge of the recycler view, the scroll amount is incorrect - it is offset by the height of the AppBarLayout. If I change to SNAP_TO_START, then it works fine. Or, if I remove the AppBarLayout, it works fine in all cases.

Attempting to scroll to the last element in the recycler view is broken in additional ways. The SNAP_TO_START flag usually works fine (see #1), but in this case the recycler view refuses to scroll it up completely.

So removing the AppBarLayout fixes everything, is there some additional setting needed when using this with AppBarLayout? I'm on the latest support library version.

Thanks

Body:
Please use smoothScrollToPosition to fix your issue as below.

RecyclerView rv = (RecyclerView)findViewById(R.id.recyclerView);
rv.smoothScrollToPosition(mMessages.count-1);


问:
Always getting KeyError when trying to access the key in a dictionary
I'm writing a Python script using the Boto3 of AWS to manage the security groups. I created a dictionary to get the group ID and its properties only. I could access the properties of sg-aaaaaaaa but when I was trying to access the sg-bbbbbbbb, it always throws a KeyError.

How I Created the Dictionary

```<code>def get_rules(sg_ids, region):
    sg_rules = {}
    sg_rules['SecurityGroups'] = []
    ec2 = boto3.client('ec2', region_name=region)

    for sg_id in sg_ids:
        response = ec2.describe_security_groups(
            Filters=[
                {
                    'Name': 'group-id',
                    'Values': [
                        sg_id
                    ]
                }
            ]
        )
        data = response['SecurityGroups'][0]['IpPermissions']

        sg_rules['SecurityGroups'].append({sg_id: data})

    return sg_rules
</code>```

Dictionary

```<code>{'SecurityGroups': [{'sg-aaaaaaaa': [{'FromPort': 22, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': 'XX.XX.XX.XX/32'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'ToPort': 22, 'U
serIdGroupPairs': []}, {'FromPort': 6556, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': 'XX.XX.XX.XX/32'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'ToPort': 6556, 'UserIdGroup
Pairs': []}]}, {'sg-bbbbbbbb': [{'FromPort': 61137, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'ToPort': 61137, 'UserIdGro
upPairs': []}, {'FromPort': 3389, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': 'XX.XX.XX.XX/32'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'ToPort': 3389, 'UserIdGroupPairs':
[]}]}]}
</code>```

Test

```<code>sg_ids = get_sg(cidr, region)
sg_rules = get_rules(sg_ids, region)

print(sg_rules['SecurityGroups'][0]['sg-aaaaaaaa']) # OK
print(sg_rules['SecurityGroups'][0]['sg-bbbbbbbb']) # KeyError
</code>```

Error

```<code>Traceback (most recent call last):
File "aws_sg_test.py", line 135, in <module>
    main()
File "aws_sg_test.py", line 131, in main
    update(args.cidr, args.region)
File "aws_sg_test.py", line 105, in update
    print(sg_rules['SecurityGroups'][0]['sg-bbbbbbbb']) # KeyError
KeyError: 'sg-bbbbbbbb'
</code>```

答:
You are accessing the wrong index. This will fix it.</p>

```<code>print(sg_rules['SecurityGroups'][1]['sg-bbbbbbbb'])
</code>```

Body:
I'm writing a Python script using the Boto3 of AWS to manage the security groups. I created a dictionary to get the group ID and its properties only. I could access the properties of sg-aaaaaaaa but when I was trying to access the sg-bbbbbbbb, it always throws a KeyError.

How I Created the Dictionary

def get_rules(sg_ids, region):
    sg_rules = {}
    sg_rules['SecurityGroups'] = []
    ec2 = boto3.client('ec2', region_name=region)

    for sg_id in sg_ids:
        response = ec2.describe_security_groups(
            Filters=[
                {
                    'Name': 'group-id',
                    'Values': [
                        sg_id
                    ]
                }
            ]
        )
        data = response['SecurityGroups'][0]['IpPermissions']

        sg_rules['SecurityGroups'].append({sg_id: data})

    return sg_rules

Dictionary

{'SecurityGroups': [{'sg-aaaaaaaa': [{'FromPort': 22, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': 'XX.XX.XX.XX/32'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'ToPort': 22, 'U
serIdGroupPairs': []}, {'FromPort': 6556, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': 'XX.XX.XX.XX/32'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'ToPort': 6556, 'UserIdGroup
Pairs': []}]}, {'sg-bbbbbbbb': [{'FromPort': 61137, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'ToPort': 61137, 'UserIdGro
upPairs': []}, {'FromPort': 3389, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': 'XX.XX.XX.XX/32'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'ToPort': 3389, 'UserIdGroupPairs':
[]}]}]}

Test

sg_ids = get_sg(cidr, region)
sg_rules = get_rules(sg_ids, region)

print(sg_rules['SecurityGroups'][0]['sg-aaaaaaaa']) # OK
print(sg_rules['SecurityGroups'][0]['sg-bbbbbbbb']) # KeyError

Error

Traceback (most recent call last):
File "aws_sg_test.py", line 135, in <module>
    main()
File "aws_sg_test.py", line 131, in main
    update(args.cidr, args.region)
File "aws_sg_test.py", line 105, in update
    print(sg_rules['SecurityGroups'][0]['sg-bbbbbbbb']) # KeyError
KeyError: 'sg-bbbbbbbb'

Body:
You are accessing the wrong index. This will fix it.

print(sg_rules['SecurityGroups'][1]['sg-bbbbbbbb'])


问:
Unique Key Constraint
What's the best practice in handling data insertion/update on a table with unique key constraints at the application level? These are what I came up with:

1. Run a query on the table before inserting data to see if it will violate the constraint.

Pros

You have full control so you don't have to deal with any DBMS specific error messages.

Addtional layer of data integrity check

Cons

There might be a performance hit since there will be no constraint violation most of the time.

You will need to lock the table while you run the query for duplicate data.

2. Do nothing. Update the table and see what sticks.

Pros

Simple!

Faster overall since you don't have to run an additional query everytime you update a table.

Cons

Your validation routine depends on the database layer.

If the data doesn't stick, you have to wade through the stack trace to find the cause.

Which one is the more widely accepted solution? Are there alternatives to these?

I'm using Java, JPA, Hibernate, and Spring BTW. Any suggestions, even framework specific, are welcome!

Thanks!

答:
A third option is to use a MERGE operation (sometimes called UPSERT) if your DBMS supports it. There is usually a DBMS specific way of checking whether the row was inserted or not.

Avoid the tautology "unique" key. Keys ARE unique, so the word "key" is quite sufficient to say what you mean.

Title: Unique Key Constraint


答:
You should look at the bind method: https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/

```<code>function playAudio(type) {
   aud.src = (type === '1') ?
     "aud1.mp3" :
     (type === "2") ?
     "aud2.mp3" :
     "aud3.mp3";

   aud.play();
}

document.getElementById('aud1button').addEventListener('click', playAudio.bind("1"));
document.getElementById('aud2button').addEventListener('click', playAudio.bind("2"));
document.getElementById('aud3button').addEventListener('click', playAudio.bind("3"));
</code>```

Title: Add code into JS with button click

Body:
You should look at the bind method: https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/

function playAudio(type) {
   aud.src = (type === '1') ?
     "aud1.mp3" :
     (type === "2") ?
     "aud2.mp3" :
     "aud3.mp3";

   aud.play();
}

document.getElementById('aud1button').addEventListener('click', playAudio.bind("1"));
document.getElementById('aud2button').addEventListener('click', playAudio.bind("2"));
document.getElementById('aud3button').addEventListener('click', playAudio.bind("3"));


问:
Tuning Spring JMS for AWS SQS free tier
I'm using Spring JMS to communicate with Amazon SQS queues.  I set up a handful of queues and wired up the listeners, but the app isn't sending any messages through them currently. AWS allows 1 million requests per month for free, which I thought should be no problem, but after a month I got billed a small amount for going over that limit.

Is there a way to tune SQS or Spring JMS to keep the requests down?

I'm assuming a request is whenever my app polls the queue to check for new messages. Some queues don't need to be near realtime so I could definitely reduce those requests.  I'd appreciate any insights you can offer into how SQS and Spring JMS communicate.

答:
"Normal" JMS clients, when polled for messages, don't poll the server - the server pushes messages to the client and the poll is just done locally.

If the SQS client polls the server, that would be unusual, to say the least, but if it's using REST calls, I can see why it would happen.

Increasing the container's receiveTimeout (default 1 second) might help, but without knowing what the client is doing under the covers, it's hard to tell.

Title: Tuning Spring JMS for AWS SQS free tier


问:
Wamp Server not starting in Windows 10 64-bit
I was writing some PHP code for my web application recently. I was trying to test sending an e-mail from a contact form on a local server (by using a variety of methods, including SendMail). None of them worked (though it may be code-related but I don't know yet). I basically restarted Apache/MySQL several times throughout testing. At one point when I was changing the configurations for SendMail, I was unable to re-start Apache & MySQL after stopping them. The icon remained red. Every time I try to start Apache, nothing would happen and the icon still remains red. I tried doing it manually from Services but it's giving me an error. It has always worked in the past, so I am not sure what's happening now or whether or not changing some of the SMTP configurations on php.ini or sendmail.ini and installing these mail server tools messed something up?

Anyone have any suggestions on how to fix/troubleshoot this? I am pretty new to server-side development. I appreciate the help!

答:
I think the first place to go would be the WAMP logs. On Windows these can be found under the root_application_install_directory/logs. For example on my Windows 10 machine I can find them under C:\wamp64\logs.

You should find all logs from Apache, PHP etc. placed here. Having a look at those may help you get closer to the cause of your issue and why the server is not starting.


问:
How to check if a button has this image

I want to check if myButton has a named image.

I try this but it doesn't work

```<code>if (myButton.currentImage?.isEqual(UIImage(named: "ButtonAppuyer.png")) != nil){
        print("YES")
    } else {
        print("NO")
    }
</code>```

and this too doesn't work

```<code>if myButton.currentImage?.isEqual(UIImage(named: "ButtonAppuyer.png")){
        print("YES")
    } else {
        print("NO")
    }
</code>```

答:
There is no way to retrieve the image name from a UI element. You will need to store the value you want to retrieve in another location.

For instance, you could create a custom subclass of UIButton that contains an additional property to store the image name or other identifying data.

Title: How to check if a button has this image

Body:
I want to check if myButton has a named image.

I try this but it doesn't work

if (myButton.currentImage?.isEqual(UIImage(named: "ButtonAppuyer.png")) != nil){
        print("YES")
    } else {
        print("NO")
    }

and this too doesn't work

if myButton.currentImage?.isEqual(UIImage(named: "ButtonAppuyer.png")){
        print("YES")
    } else {
        print("NO")
    }


问:
Is it better to rotate an arrow-icon or to use separate icons for right and left arrow?
In Android, i have an Arrow-Right icon (SVG). I also need an Arrow-Left icon. Is it better to use Arrow-Right and rotate it by 180° or use a separate drawable?

I imagine that rotating one icon is more efficient than loading a second drawable, but what if i have to use the icon hundreds of times in my activity?

Also, what if i have to use a bigger image (a .png file > 1MB)?

答:
If you need icons for the menu or the action bar there is no place to rotate it, you just assign a drawable resource ID to the menu item.

The standard (correct) way is to generate PNG's for each screen density and in your case for each orientation.

http://iconhandbook.co.uk/reference/chart/android/


问:
Links being acted on -- style in CSS or using JavaScript?
Should you use a:hover, a:active, a:visited and a:link, or similar javascript things (tags??) instead?</p>

答:
Use CSS when you can (in your example, there is a simple way to do what you need in CSS so that makes it a good fit).

Otherwise, fall back to JavaScript.


问:
Inverted Collectors.toMap to add to an ArrayList
I would like to put the frequencies of the numbers in a TreeMap with the frequencies as the keys and the numbers that have that frequency in an ArrayList.

I have two problems:

1) I'm getting a "non-static methods cannot be referenced from a static context" error in the first parameter (AFAIK the stream references an object - what's going on?)

2) There are 4 parameters for Collectors.toMap() - it seems like parameter 4 requires initialization with a new TreeMap>, parameter 2 could be an ArrayList add() function and parameter 3 could be null (maybe). How is this done?

```<code>import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {

        List<Integer> array = Arrays.asList(1, 2, 4, 5, 6, 4, 8, 4, 2, 3);

        Map<Integer, Long> m = array.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(m);

        TreeMap<Long, List<Integer>> tm = m.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getValue, ...));
</code>```

At the moment I can't use see how to get from
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html to where I need to be.

答:
You are almost correct in your reasoning... Just that the 3-rd argument is where you merge your values for the same key - so you can't omit it.</p>

```<code> TreeMap<Long, List<Integer>> tm = m.entrySet().stream()
            .collect(Collectors.toMap(
                  Entry::getValue,
                  x -> {
                      List<Integer> list = new ArrayList<>();
                      list.add(x.getKey());
                      return list;
                  },
                  (left, right) -> {
                     left.addAll(right);
                     return left;
                  },
                  TreeMap::new));
</code>```

Body:
I would like to put the frequencies of the numbers in a TreeMap with the frequencies as the keys and the numbers that have that frequency in an ArrayList.

I have two problems:

1) I'm getting a "non-static methods cannot be referenced from a static context" error in the first parameter (AFAIK the stream references an object - what's going on?)

2) There are 4 parameters for Collectors.toMap() - it seems like parameter 4 requires initialization with a new TreeMap>, parameter 2 could be an ArrayList add() function and parameter 3 could be null (maybe). How is this done?

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {

        List<Integer> array = Arrays.asList(1, 2, 4, 5, 6, 4, 8, 4, 2, 3);

        Map<Integer, Long> m = array.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(m);

        TreeMap<Long, List<Integer>> tm = m.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getValue, ...));

At the moment I can't use see how to get from
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html to where I need to be.

Body:
You are almost correct in your reasoning... Just that the 3-rd argument is where you merge your values for the same key - so you can't omit it.

 TreeMap<Long, List<Integer>> tm = m.entrySet().stream()
            .collect(Collectors.toMap(
                  Entry::getValue,
                  x -> {
                      List<Integer> list = new ArrayList<>();
                      list.add(x.getKey());
                      return list;
                  },
                  (left, right) -> {
                     left.addAll(right);
                     return left;
                  },
                  TreeMap::new));


问:
In Drools, what does it mean to compare IDs
I understand the basics of writing drools rules now but i can't seem to understand in the examples that i've seen (optaplanner), there are comparisons of IDs. Is this necessary? Why is it there?

```<code>// RoomOccupancy: Two lectures in the same room at the same period.
// Any extra lecture in the same period and room counts as one more violation.
rule "roomOccupancy"
    when
        Lecture($leftId : id, period != null, $period : period, room != null, $room : room)
        // $leftLecture has lowest id of the period+room combo
        not Lecture(period == $period, room == $room, id < $leftId)
        // rightLecture has the same period
        Lecture(period == $period, room == $room, id > $leftId, $rightId : id)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -1);
end
</code>```

From my understanding deleting the line with not Lecture(.. and leaving Lecture(period == $period, room == $room) should do the trick. Is my understanding correct or am I missing some use cases here?

答:
Given 2 queens A and B, the id comparison in the "no 2 queens on the same horizontal row" constraint makes sure that we only match A-B and not B-A, A-A and B-B.

Same principle for lectures.

Body:
I understand the basics of writing drools rules now but i can't seem to understand in the examples that i've seen (optaplanner), there are comparisons of IDs. Is this necessary? Why is it there?

// RoomOccupancy: Two lectures in the same room at the same period.
// Any extra lecture in the same period and room counts as one more violation.
rule "roomOccupancy"
    when
        Lecture($leftId : id, period != null, $period : period, room != null, $room : room)
        // $leftLecture has lowest id of the period+room combo
        not Lecture(period == $period, room == $room, id < $leftId)
        // rightLecture has the same period
        Lecture(period == $period, room == $room, id > $leftId, $rightId : id)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -1);
end

From my understanding deleting the line with not Lecture(.. and leaving Lecture(period == $period, room == $room) should do the trick. Is my understanding correct or am I missing some use cases here?


答:
I think Collectors.groupingBy makes more sense than Collectors.toMap to achieve what you are looking for:

```<code>Map<Long, List<Integer>> tm =
    m.entrySet()
     .stream()
     .collect(Collectors.groupingBy(Map.Entry::getValue, // group the entries by the
                                                         // value (the frequency)
                                    TreeMap::new, // generate a TreeMap
                                    Collectors.mapping (Map.Entry::getKey,
                                                        Collectors.toList()))); // the
                                                         // value of the output TreeMap
                                                         // should be a List of the
                                                         // original keys
</code>```

You can replace Collectors.toList() with Collectors.toCollection(ArrayList::new) to make sure that the values of the output Map are ArrayLists (though the current implementation of toList() already results in java.util.ArrayList instances).

For your sample input, this produces the following TreeMap:

```<code>{1=[1, 3, 5, 6, 8], 2=[2], 3=[4]}
</code>```

Title: Inverted Collectors.toMap to add to an ArrayList

Body:
I think Collectors.groupingBy makes more sense than Collectors.toMap to achieve what you are looking for:

Map<Long, List<Integer>> tm =
    m.entrySet()
     .stream()
     .collect(Collectors.groupingBy(Map.Entry::getValue, // group the entries by the
                                                         // value (the frequency)
                                    TreeMap::new, // generate a TreeMap
                                    Collectors.mapping (Map.Entry::getKey,
                                                        Collectors.toList()))); // the
                                                         // value of the output TreeMap
                                                         // should be a List of the
                                                         // original keys

You can replace Collectors.toList() with Collectors.toCollection(ArrayList::new) to make sure that the values of the output Map are ArrayLists (though the current implementation of toList() already results in java.util.ArrayList instances).

For your sample input, this produces the following TreeMap:

{1=[1, 3, 5, 6, 8], 2=[2], 3=[4]}


问:
How can I find the percentage of times that a point in a 2D numpy array is greater than the corresponding point in a reference array, for all points?
Python newbie here. Given a list (mylist) of 2D numpy arrays, and a reference 2D numpy array (refarr), I'm looking for a way to create an array (percentage_array) in which each point (i,j) is the percentage of corresponding (i,j) points in the mylist arrays that are greater than [i,j] in refarr. I could do this by looping through all the points in the array and though the list, e.g.:

```<code>percentage_array = numpy.empty(arr.shape)
for i in range(arr.shape[0]):
    for j in range(arr.shape[1]):
        t = 0
        f = 0
        for arr in mylist:
            if arr[i,j] > refarr[i,j]:
                t += 1 # counting the number of arrays for which [i,j] is true
            elif arr[i,j] <= refarr[i,j]:
                f += 1 # counting the number of arrays for which [i,j] is false
        percentage_array[i,j] = t/(t+f) # fraction of arrays which have
                                        # arr[i,j] > refarr[i,j]
</code>```

...but this is neither quick nor elegant (I'm dealing with large amounts of data). Are there better ways to do this?

答:
You can create a 3d array with

```<code>a = np.array(myList)
</code>```

Then you can compare this array to your original one using broadcasting:

```<code>a < refarr # gives a 3D array of booleans because refarr is broadcasted to a 3D array
</code>```

and to count the percentage of values where the condition is met, you average on the first axis:

```<code>(a < refarr[None, :, :]).mean(axis = 0)
</code>```

The main drawback of this approach is that you have to create an array a which may be big. Otherwise I'd consider treating arrays one by one.

Body:
Python newbie here. Given a list (mylist) of 2D numpy arrays, and a reference 2D numpy array (refarr), I'm looking for a way to create an array (percentage_array) in which each point (i,j) is the percentage of corresponding (i,j) points in the mylist arrays that are greater than [i,j] in refarr. I could do this by looping through all the points in the array and though the list, e.g.:

percentage_array = numpy.empty(arr.shape)
for i in range(arr.shape[0]):
    for j in range(arr.shape[1]):
        t = 0
        f = 0
        for arr in mylist:
            if arr[i,j] > refarr[i,j]:
                t += 1 # counting the number of arrays for which [i,j] is true
            elif arr[i,j] <= refarr[i,j]:
                f += 1 # counting the number of arrays for which [i,j] is false
        percentage_array[i,j] = t/(t+f) # fraction of arrays which have
                                        # arr[i,j] > refarr[i,j]

...but this is neither quick nor elegant (I'm dealing with large amounts of data). Are there better ways to do this?

Body:
You can create a 3d array with

a = np.array(myList)

Then you can compare this array to your original one using broadcasting:

a < refarr # gives a 3D array of booleans because refarr is broadcasted to a 3D array

and to count the percentage of values where the condition is met, you average on the first axis:

(a < refarr[None, :, :]).mean(axis = 0)

The main drawback of this approach is that you have to create an array a which may be big. Otherwise I'd consider treating arrays one by one.