问:
Rmysql query does not return the correct values?
I have a query in r, using rmysql package :

```<code>sql.query = paste0("SELECT * FROM performance_db.pcTab WHERE
                       fk_ID_calc = (SELECT ID_calc FROM performance_db.calculationTab WHERE
                       turbine_model = '",input$t1,"' AND
                       op_mode = '",input$t2,"' AND
                       date_entered ='",input$t3,"')
                       AND sensor = 'P_el'"
  )
    spc = fetch(dbSendQuery(conn, sql.query), n = -1)
</code>```

this return a table :

```<code>head(spc)
  ID_pc voltage_side sensor Air_density v2.5 v3  v4  v5  v6   v7   v8   v9  v10  v11  v12  v13  v14  v15  v16  v17  v18  v19
1     1            0   P_el       1.225    0 44 184 404 721 1165 1686 2107 2272 2300 2300 2300 2300 2300 2300 2300 2300 2300
2     2            0   P_el       1.000   NA 33 155 346 622 1010 1486 1967 2224 2286 2294 2300 2300 2300 2300 2300 2300 2300
3     3            0   P_el       1.030   NA 35 161 358 642 1041 1529 1999 2235 2291 2297 2300 2300 2300 2300 2300 2300 2300
4     4            0   P_el       1.060   NA 37 167 369 661 1072 1571 2036 2249 2295 2300 2300 2300 2300 2300 2300 2300 2300
5     5            0   P_el       1.090   NA 39 173 381 681 1103 1612 2060 2256 2300 2300 2300 2300 2300 2300 2300 2300 2300
6     6            0   P_el       1.120   NA 42 178 392 701 1134 1649 2080 2263 2300 2300 2300 2300 2300 2300 2300 2300 2300
</code>```

I would like to add additional filter on Air_density like :

```<code>sql.query = paste0("SELECT * FROM performance_db.pcTab WHERE
                       fk_ID_calc = (SELECT ID_calc FROM performance_db.calculationTab WHERE
                       turbine_model = '",input$t1,"' AND
                       op_mode = '",input$t2,"' AND
                       date_entered ='",input$t3,"')
                       AND sensor = 'P_el' AND Air_density = 1"
  )
</code>```

This is return just one row contain the information for Air_density = 1 :

```<code>ID_pc voltage_side sensor Air_density v2.5 v3  v4  v5  v6   v7   v8   v9  v10  v11  v12  v13  v14  v15  v16  v17  v18  v19
1     2            0   P_el           1   NA 33 155 346 622 1010 1486 1967 2224 2286 2294 2300 2300 2300 2300 2300 2300 2300
</code>```

But when I try to filter base on other Air_densities It does not return anything. Like if in above mentioned query I put AND Air_density = 1.225 :

```<code>head(spc)
 [1] ID_pc        voltage_side sensor       Air_density  v2.5         v3           v4           v5           v6
[10] v7           v8           v9           v10          v11          v12          v13          v14          v15
[19] v16          v17          v18          v19
</code>```

I have no idea why it is happening !!!

答:
FLOAT and DOUBLE data types are not precise.

If you save the value 1.225 it can be saved as 1.22500001.
And when you try to query all data with the value 1.225, it won't find it, because it is saved as 1.22500001.

You should better use datatypes DECIMAL or NUMERIC
or try to CAST the FLOAT values as DECIMAL like this:

```<code>CAST(Air_density as DECIMAL(10,3))
</code>```

This is from the docs of MySQL:

11.2.3 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE

The FLOAT and DOUBLE types represent approximate numeric data values.
  MySQL uses four bytes for single-precision values and eight bytes for
  double-precision values.

For FLOAT, the SQL standard permits an optional specification of the
  precision (but not the range of the exponent) in bits following the
  keyword FLOAT in parentheses. MySQL also supports this optional
  precision specification, but the precision value is used only to
  determine storage size. A precision from 0 to 23 results in a 4-byte
  single-precision FLOAT column. A precision from 24 to 53 results in an
  8-byte double-precision DOUBLE column.

MySQL permits a nonstandard syntax: FLOAT(M,D) or REAL(M,D) or DOUBLE
  PRECISION(M,D). Here, (M,D) means than values can be stored with up to
  M digits in total, of which D digits may be after the decimal point.
  For example, a column defined as FLOAT(7,4) will look like -999.9999
  when displayed. MySQL performs rounding when storing values, so if you
  insert 999.00009 into a FLOAT(7,4) column, the approximate result is
  999.0001.

Because floating-point values are approximate and not stored as exact
  values, attempts to treat them as exact in comparisons may lead to
  problems. They are also subject to platform or implementation
  dependencies. For more information, see Section B.5.4.8, “Problems
  with Floating-Point Values”

For maximum portability, code requiring storage of approximate numeric
  data values should use FLOAT or DOUBLE PRECISION with no specification
  of precision or number of digits.

https://dev.mysql.com/doc/refman/5.7/en/floating-point-types.html

This link should help you, too:

https://dev.mysql.com/doc/refman/5.7/en/problems-with-float.html

Body:
I have a query in r, using rmysql package :

sql.query = paste0("SELECT * FROM performance_db.pcTab WHERE
                       fk_ID_calc = (SELECT ID_calc FROM performance_db.calculationTab WHERE
                       turbine_model = '",input$t1,"' AND
                       op_mode = '",input$t2,"' AND
                       date_entered ='",input$t3,"')
                       AND sensor = 'P_el'"
  )
    spc = fetch(dbSendQuery(conn, sql.query), n = -1)

this return a table :

head(spc)
  ID_pc voltage_side sensor Air_density v2.5 v3  v4  v5  v6   v7   v8   v9  v10  v11  v12  v13  v14  v15  v16  v17  v18  v19
1     1            0   P_el       1.225    0 44 184 404 721 1165 1686 2107 2272 2300 2300 2300 2300 2300 2300 2300 2300 2300
2     2            0   P_el       1.000   NA 33 155 346 622 1010 1486 1967 2224 2286 2294 2300 2300 2300 2300 2300 2300 2300
3     3            0   P_el       1.030   NA 35 161 358 642 1041 1529 1999 2235 2291 2297 2300 2300 2300 2300 2300 2300 2300
4     4            0   P_el       1.060   NA 37 167 369 661 1072 1571 2036 2249 2295 2300 2300 2300 2300 2300 2300 2300 2300
5     5            0   P_el       1.090   NA 39 173 381 681 1103 1612 2060 2256 2300 2300 2300 2300 2300 2300 2300 2300 2300
6     6            0   P_el       1.120   NA 42 178 392 701 1134 1649 2080 2263 2300 2300 2300 2300 2300 2300 2300 2300 2300

I would like to add additional filter on Air_density like :

sql.query = paste0("SELECT * FROM performance_db.pcTab WHERE
                       fk_ID_calc = (SELECT ID_calc FROM performance_db.calculationTab WHERE
                       turbine_model = '",input$t1,"' AND
                       op_mode = '",input$t2,"' AND
                       date_entered ='",input$t3,"')
                       AND sensor = 'P_el' AND Air_density = 1"
  )

This is return just one row contain the information for Air_density = 1 :

ID_pc voltage_side sensor Air_density v2.5 v3  v4  v5  v6   v7   v8   v9  v10  v11  v12  v13  v14  v15  v16  v17  v18  v19
1     2            0   P_el           1   NA 33 155 346 622 1010 1486 1967 2224 2286 2294 2300 2300 2300 2300 2300 2300 2300

But when I try to filter base on other Air_densities It does not return anything. Like if in above mentioned query I put AND Air_density = 1.225 :

head(spc)
 [1] ID_pc        voltage_side sensor       Air_density  v2.5         v3           v4           v5           v6
[10] v7           v8           v9           v10          v11          v12          v13          v14          v15
[19] v16          v17          v18          v19

I have no idea why it is happening !!!

Body:
FLOAT and DOUBLE data types are not precise.

If you save the value 1.225 it can be saved as 1.22500001.
And when you try to query all data with the value 1.225, it won't find it, because it is saved as 1.22500001.

You should better use datatypes DECIMAL or NUMERIC
or try to CAST the FLOAT values as DECIMAL like this:

CAST(Air_density as DECIMAL(10,3))

This is from the docs of MySQL:

11.2.3 Floating-Point Types (Approximate Value) - FLOAT, DOUBLE

The FLOAT and DOUBLE types represent approximate numeric data values.
  MySQL uses four bytes for single-precision values and eight bytes for
  double-precision values.

For FLOAT, the SQL standard permits an optional specification of the
  precision (but not the range of the exponent) in bits following the
  keyword FLOAT in parentheses. MySQL also supports this optional
  precision specification, but the precision value is used only to
  determine storage size. A precision from 0 to 23 results in a 4-byte
  single-precision FLOAT column. A precision from 24 to 53 results in an
  8-byte double-precision DOUBLE column.

MySQL permits a nonstandard syntax: FLOAT(M,D) or REAL(M,D) or DOUBLE
  PRECISION(M,D). Here, (M,D) means than values can be stored with up to
  M digits in total, of which D digits may be after the decimal point.
  For example, a column defined as FLOAT(7,4) will look like -999.9999
  when displayed. MySQL performs rounding when storing values, so if you
  insert 999.00009 into a FLOAT(7,4) column, the approximate result is
  999.0001.

Because floating-point values are approximate and not stored as exact
  values, attempts to treat them as exact in comparisons may lead to
  problems. They are also subject to platform or implementation
  dependencies. For more information, see Section B.5.4.8, “Problems
  with Floating-Point Values”

For maximum portability, code requiring storage of approximate numeric
  data values should use FLOAT or DOUBLE PRECISION with no specification
  of precision or number of digits.

https://dev.mysql.com/doc/refman/5.7/en/floating-point-types.html

This link should help you, too:

https://dev.mysql.com/doc/refman/5.7/en/problems-with-float.html


来源: stackexchange

问:
Alternative to for and ifelse loops - determining whether elements lie within generated confidence intervals
I am trying to rewrite my code to not contain any for loops or ifelse loops. The purpose is to extract a matrix containing 0s and 1s depending on variable mu and variable cinterval - to generate a 1 if y0 falls within its 95th CI, and 0 y0 falls within its 95th CI, and likewise for y1. This would be repeated with both y0 and y1 for a number of modules.

mu contains values for y0 and y1; cinterval contains four rows:

lower 95th CI limit for y0

upper 95th CI limit for y0

lower 95th CI limit for y1

upper 95th CI limit for y1

cinterval can be programmed to have any number of modules:

```<code>cinterval.fn <- function(y0y1modules) {
  matrix(c(y0results, y1results) nrow=4, ncol=no.of.modules, byrow=T) #simplified from true code
  rownames(cinterval) <- c("y0 95LCI", "y0 95UCI", "y1 95LCI", "y1 95UCI")
  colnames(cinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
  return(cinterval)
}

> cinterval
         module.1 module.2  module.3
y0 95LCI 2.434602 1.784056  1.751713
y0 95UCI 5.988160 6.519465  6.833455
y1 95LCI 3.778811 2.681708  2.805293
y1 95UCI 9.228941 9.716476 10.258412
</code>```

mu looks like this:

```<code>mu <- c(4, 8)
mu
y0 y1
 4  8
</code>```

The code I have is:

```<code>incinterval.fn <- function(cov.xy, mu, n1, dr) {
  cinterval <- cintervaloutput.fn(cov.xy, mu, n1, dr) # Generates matrix with 95% CI values for y0 and y1 after modules
  y0 <- NULL   # Empty vector
  for (module.no in 1:ncol(cinterval)) {
    y0 <- cbind(y0, ifelse (cinterval[1, module.no] <= mu["y0"] || mu["y0"] <= cinterval[2, module.no], 1, 0))
  }            # If y0 inside CI, 1, else 0
  y1 <- NULL   # Empty vector
  for (module.no in 1:ncol(cinterval)) {
    y1 <- cbind(y1, ifelse (cinterval[3, module.no] <= mu["y1"] || mu["y1"] <= cinterval[4, module.no], 1, 0))
  }            # If y1 inside CI, 1, else 0
  incinterval <- rbind(y0, y1) # Combines vectors
  colnames(incinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
  return(incinterval)
}
</code>```

The result, incinterval, looks like this:

```<code>     module.1 module.2 module.3
[y0]        1        1        1
[y1]        1        1        1
</code>```

Any assistance with more efficient coding to replace for and ifelse would be greatly appreciated! I currently use 2 for and ifeelse loops.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to rewrite my code to not contain any for loops or ifelse loops. The purpose is to extract a matrix containing 0s and 1s depending on variable mu and variable cinterval - to generate a 1 if y0 falls within its 95th CI, and 0 y0 falls within its 95th CI, and likewise for y1. This would be repeated with both y0 and y1 for a number of modules.

mu contains values for y0 and y1; cinterval contains four rows:

lower 95th CI limit for y0

upper 95th CI limit for y0

lower 95th CI limit for y1

upper 95th CI limit for y1

cinterval can be programmed to have any number of modules:

cinterval.fn <- function(y0y1modules) {
  matrix(c(y0results, y1results) nrow=4, ncol=no.of.modules, byrow=T) #simplified from true code
  rownames(cinterval) <- c("y0 95LCI", "y0 95UCI", "y1 95LCI", "y1 95UCI")
  colnames(cinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
  return(cinterval)
}

> cinterval
         module.1 module.2  module.3
y0 95LCI 2.434602 1.784056  1.751713
y0 95UCI 5.988160 6.519465  6.833455
y1 95LCI 3.778811 2.681708  2.805293
y1 95UCI 9.228941 9.716476 10.258412

mu looks like this:

mu <- c(4, 8)
mu
y0 y1
 4  8

The code I have is:

incinterval.fn <- function(cov.xy, mu, n1, dr) {
  cinterval <- cintervaloutput.fn(cov.xy, mu, n1, dr) # Generates matrix with 95% CI values for y0 and y1 after modules
  y0 <- NULL   # Empty vector
  for (module.no in 1:ncol(cinterval)) {
    y0 <- cbind(y0, ifelse (cinterval[1, module.no] <= mu["y0"] || mu["y0"] <= cinterval[2, module.no], 1, 0))
  }            # If y0 inside CI, 1, else 0
  y1 <- NULL   # Empty vector
  for (module.no in 1:ncol(cinterval)) {
    y1 <- cbind(y1, ifelse (cinterval[3, module.no] <= mu["y1"] || mu["y1"] <= cinterval[4, module.no], 1, 0))
  }            # If y1 inside CI, 1, else 0
  incinterval <- rbind(y0, y1) # Combines vectors
  colnames(incinterval) <- paste('module', 1:length(cinterval[1,]), sep='.')
  return(incinterval)
}

The result, incinterval, looks like this:

     module.1 module.2 module.3
[y0]        1        1        1
[y1]        1        1        1

Any assistance with more efficient coding to replace for and ifelse would be greatly appreciated! I currently use 2 for and ifeelse loops.

Body:
Example data:

cinterval <- data.frame(rbind(c(2.434602,1.784056,1.751713),
                                 c(5.988160,6.519465,6.833455),
                                 c(3.778811,2.681708,2.805293),
                                 c(9.228941,9.716476,10.258412)),
                   row.names = c("y0 L","y0 U","y1 L","y1 U")
)
colnames(cinterval) <- paste0("module.",1:3)
mu <- c("y0" = 4, "y1" = 8)

You can take advantage of vectorization and compare single value with a vector

as.numeric(mu["y0"] >= cinterval[1,] & mu["y0"] <= cinterval[2,])

[1] 1 1 1

Works accordingly for "y1".


问:
Navigation with Waze and Google Maps using Intent.createChooser shows Waze icon twice
I'm creating this question after finding the answer, I was not sure about the etiquette, but it seems to be OK (plus, I see now there's a built-in option).

The problem was as described in the title, we created an intent chooser using code that resembles this:

```<code>String url = "waze://?ll=" + latitude + ", " + longitude + "&navigate=yes";
Intent intentWaze = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

String uriGoogle = "google.navigation:q=" + latitude + "," + longitude;
Intent intentGoogleNav = new Intent(Intent.ACTION_VIEW, Uri.parse(uriGoogle));

String title = context.getString(R.string.title);
Intent chooserIntent = Intent.createChooser(intentGoogleNav, title);
Intent[] arr = new Intent[1];
arr[0] = intentWaze;
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, arr);
context.startActivity(chooserIntent);
</code>```

And got two Waze icons and one Google Maps icon; and worse, one of the Waze icons did not start the navigation (only open the app).

We could not use the geo: intent because we need to control the intents shown (we don't want to show both intents at all times) and the navigation type in Google Maps (for example: &mode=w).

答:
After some time I used the solution found here, and there was only one icon that was working properly. As I wrote in the question, I could not use this solution because it lacks the flexibility I needed, so after looking at the code I saw that what was missing was this:

```<code>intentWaze.setPackage("com.waze");
// and more importantly, this:
intentGoogleNav.setPackage("com.google.android.apps.maps");
</code>```

It seems that Waze is listening to the Google Maps intent (and does not work well with it), and that's why there were two icons.

Body:
I'm creating this question after finding the answer, I was not sure about the etiquette, but it seems to be OK (plus, I see now there's a built-in option).

The problem was as described in the title, we created an intent chooser using code that resembles this:

String url = "waze://?ll=" + latitude + ", " + longitude + "&navigate=yes";
Intent intentWaze = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

String uriGoogle = "google.navigation:q=" + latitude + "," + longitude;
Intent intentGoogleNav = new Intent(Intent.ACTION_VIEW, Uri.parse(uriGoogle));

String title = context.getString(R.string.title);
Intent chooserIntent = Intent.createChooser(intentGoogleNav, title);
Intent[] arr = new Intent[1];
arr[0] = intentWaze;
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, arr);
context.startActivity(chooserIntent);

And got two Waze icons and one Google Maps icon; and worse, one of the Waze icons did not start the navigation (only open the app).

We could not use the geo: intent because we need to control the intents shown (we don't want to show both intents at all times) and the navigation type in Google Maps (for example: &mode=w).

Body:
After some time I used the solution found here, and there was only one icon that was working properly. As I wrote in the question, I could not use this solution because it lacks the flexibility I needed, so after looking at the code I saw that what was missing was this:

intentWaze.setPackage("com.waze");
// and more importantly, this:
intentGoogleNav.setPackage("com.google.android.apps.maps");

It seems that Waze is listening to the Google Maps intent (and does not work well with it), and that's why there were two icons.


问:
Jquery Droppable not working for file upload drag and drop, throws Error: Expected DOM element or View
I have been working on a https://github.com/wekan/ fork where I try to implement additional drag and drop functionality.
Out of the box wekan already came with labels/member drag and drop where the hover overlay is done via droppable hoverClass:

```<code>    const selector = $cards.find(itemsSelector);
    selector.droppable({
      hoverClass: 'draggable-hover-card',
      accept: '.js-member,.js-label',
      'drop'(evt, ui) {
        evt.preventDefault();
        evt.stopPropagation();
        const cardId = Blaze.getData(this)._id;
        const card = Cards.findOne(cardId); //get current card I am hovering
        //stuff
      },
    });
</code>```

I added attachment drag and drop functionality, which won't work exactly like above code and produces the problem that I cannot add the hoverClass cleanly.
When I implement it as shown below the logic of doing addClass is sound but I get an error:

```<code>Exception from Tracker afterFlush function:
debug.js:41 Error: Expected DOM element or View
at Object.Blaze.getData (view.js:757)
at list.js:116
at Object.Tracker._runFlush (tracker.js:511)
at onGlobalMessage (setimmediate.js:102)
</code>```

My code where I want to get an overlay/hover functionality for a single card that I hover over with a file:

```<code>    const cardId = Blaze.getData(this)._id;
    const card = Cards.findOne(cardId); //get current card I am hovering
    selector.on({'': (evt) => { //.droppable as above does not work
      evt.preventDefault(); //prevent default browser behavior
      evt.stopPropagation();
    },
    dragover(e) { // pulled out of selector.on() to add/removeClass
      e.preventDefault();
      e.stopPropagation();
      card.addClass('is-selected'); //add overlay on hover
    },
    dragenter(e) {
      e.preventDefault();
      e.stopPropagation();
    },
    dragleave(e) {
      e.preventDefault();
      e.stopPropagation();
      card.removeClass('is-selected');
    },
    drop(evt, ui) {
      card.removeClass('is-selected');
      if(!ui){ // prevent complications with other drop events
        evt.preventDefault();
        evt.stopImmediatePropagation(); // prevent x -times actions
        evt.target.files = evt.dataTransfer.files; // working file upload
        _.each(evt.dataTransfer.files, (f) => {
          const file = new FS.File(f);
          file.boardId = card.boardId;
          file.cardId = card._id;
          Attachments.insert(file);
        });}
    },
    });
</code>```

When I move

```<code>const cardId = Blaze.getData(this)._id;
const card = Cards.findOne(cardId);
</code>```

back into the drop event like in the first code block and try/test e.g. selector.addClass('') instead, the overlay works, but not correctly(selector basically returns the whole card list instead of a single card).
I am a novice currently in training and I just can't understand what error I am making.

Template.currentData() instead of Blaze.getData() does not work.
When I try selector.droppable() my dropped file isn't accepted and all the other events won't fire either.
After trying different varieties I am pretty sure that Blaze.getData() is the problem here. I don't know how to replace its function though.

答:
The problem was a syntax and logic error on my side. While I knew that this in Blaze.getData() would point to the div I wanted, this.addClass() would throw an error. So I thought I'd need the whole Blaze-Block which then lead to the problem above.

Right Syntax:

```<code>$(this).addClass('');
</code>```

Body:
I have been working on a https://github.com/wekan/ fork where I try to implement additional drag and drop functionality.
Out of the box wekan already came with labels/member drag and drop where the hover overlay is done via droppable hoverClass:

    const selector = $cards.find(itemsSelector);
    selector.droppable({
      hoverClass: 'draggable-hover-card',
      accept: '.js-member,.js-label',
      'drop'(evt, ui) {
        evt.preventDefault();
        evt.stopPropagation();
        const cardId = Blaze.getData(this)._id;
        const card = Cards.findOne(cardId); //get current card I am hovering
        //stuff
      },
    });

I added attachment drag and drop functionality, which won't work exactly like above code and produces the problem that I cannot add the hoverClass cleanly.
When I implement it as shown below the logic of doing addClass is sound but I get an error:

Exception from Tracker afterFlush function:
debug.js:41 Error: Expected DOM element or View
at Object.Blaze.getData (view.js:757)
at list.js:116
at Object.Tracker._runFlush (tracker.js:511)
at onGlobalMessage (setimmediate.js:102)

My code where I want to get an overlay/hover functionality for a single card that I hover over with a file:

    const cardId = Blaze.getData(this)._id;
    const card = Cards.findOne(cardId); //get current card I am hovering
    selector.on({'': (evt) => { //.droppable as above does not work
      evt.preventDefault(); //prevent default browser behavior
      evt.stopPropagation();
    },
    dragover(e) { // pulled out of selector.on() to add/removeClass
      e.preventDefault();
      e.stopPropagation();
      card.addClass('is-selected'); //add overlay on hover
    },
    dragenter(e) {
      e.preventDefault();
      e.stopPropagation();
    },
    dragleave(e) {
      e.preventDefault();
      e.stopPropagation();
      card.removeClass('is-selected');
    },
    drop(evt, ui) {
      card.removeClass('is-selected');
      if(!ui){ // prevent complications with other drop events
        evt.preventDefault();
        evt.stopImmediatePropagation(); // prevent x -times actions
        evt.target.files = evt.dataTransfer.files; // working file upload
        _.each(evt.dataTransfer.files, (f) => {
          const file = new FS.File(f);
          file.boardId = card.boardId;
          file.cardId = card._id;
          Attachments.insert(file);
        });}
    },
    });

When I move

const cardId = Blaze.getData(this)._id;
const card = Cards.findOne(cardId);

back into the drop event like in the first code block and try/test e.g. selector.addClass('') instead, the overlay works, but not correctly(selector basically returns the whole card list instead of a single card).
I am a novice currently in training and I just can't understand what error I am making.

Template.currentData() instead of Blaze.getData() does not work.
When I try selector.droppable() my dropped file isn't accepted and all the other events won't fire either.
After trying different varieties I am pretty sure that Blaze.getData() is the problem here. I don't know how to replace its function though.

Body:
The problem was a syntax and logic error on my side. While I knew that this in Blaze.getData() would point to the div I wanted, this.addClass() would throw an error. So I thought I'd need the whole Blaze-Block which then lead to the problem above.

Right Syntax:

$(this).addClass('');


问:
SearchView: Keyboard not show button Done
android 4.3.

here snippet:

```<code> <android.support.v7.widget.SearchView
        android:id="@+id/searchView"
        style="@style/Widget.AppCompat.SearchView.ActionBar"
        android:layout_width="0dp"
        android:layout_height="30dp"
        android:layout_marginEnd="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginStart="20dp"
        android:background="@drawable/search_view_bg"
        android:imeOptions="actionDone"
        android:maxLines="1"
        android:inputType="text"
        android:theme="@style/SearchViewTheme"
        app:defaultQueryHint="@null"
        app:layout_constraintLeft_toLeftOf="@+id/searchViewContainer"
        app:layout_constraintRight_toRightOf="@+id/searchViewContainer"
        app:layout_constraintTop_toTopOf="@+id/searchViewContainer"
        app:searchHintIcon="@null" />
</code>```

I want when click on SearchView to show keyboard with Done button. So I set android:imeOptions="actionDone". But it not help:

Here result:

答:
Try this</p>

```<code>searchview.setImeOptions(EditorInfo.IME_ACTION_DONE);
searchview.setSingleLine(true);
</code>```

Body:
android 4.3.

here snippet:

 <android.support.v7.widget.SearchView
        android:id="@+id/searchView"
        style="@style/Widget.AppCompat.SearchView.ActionBar"
        android:layout_width="0dp"
        android:layout_height="30dp"
        android:layout_marginEnd="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginStart="20dp"
        android:background="@drawable/search_view_bg"
        android:imeOptions="actionDone"
        android:maxLines="1"
        android:inputType="text"
        android:theme="@style/SearchViewTheme"
        app:defaultQueryHint="@null"
        app:layout_constraintLeft_toLeftOf="@+id/searchViewContainer"
        app:layout_constraintRight_toRightOf="@+id/searchViewContainer"
        app:layout_constraintTop_toTopOf="@+id/searchViewContainer"
        app:searchHintIcon="@null" />

I want when click on SearchView to show keyboard with Done button. So I set android:imeOptions="actionDone". But it not help:

Here result:

Body:
Try this

searchview.setImeOptions(EditorInfo.IME_ACTION_DONE);
searchview.setSingleLine(true);


问:
Calculation between two Frangments in an Activity
I want to calculate each item separately as well as together. Also want to print the Quantity. Now I'm only able to print Total Amount. But i have to insert value in each Item. If I leave 1 blank the app crashes.

Image 1 is the FrangmentActivity showing calculating Total Amount

Image 2 is crashing of the app when i leave 1 blank input and tried to calculate

TopSectionFragment

```<code>import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

public class TopSectionFragment extends Fragment {

private static EditText editText2, editText3, editText4;

TopSectionListener activityCommander;

public interface TopSectionListener {
    public void createQuantity(String result);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        activityCommander = (TopSectionListener) activity;
    }catch (ClassCastException e){
        throw new ClassCastException(activity.toString());
    }
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.top_section_fragment,
container, false);

    editText2 = (EditText) view.findViewById(R.id.etQSmall);
    editText3 = (EditText) view.findViewById(R.id.etQMedium);
    editText4 = (EditText) view.findViewById(R.id.etQLarge);
    final Button button = (Button) view.findViewById(R.id.btnCal);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            buttonClicked(v);
        }
    });

    return view;
}
public void buttonClicked(View view){

    int smallPizza = Integer.parseInt(editText2.getText().toString());
    int mediumPizza = Integer.parseInt(editText3.getText().toString());
    int largePizza = Integer.parseInt(editText4.getText().toString());

    //Do Calculation Small = 15, Medium = 20, Large = 25

    int total = (smallPizza * 15) + (mediumPizza * 20) + (largePizza *
    25);

    String result = "Total RM "+total;
    activityCommander.createQuantity(result);
   }
}
</code>```

BottomSectionFragment

```<code>import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class BottomSectionFragment extends Fragment{

private static TextView textAmount;
private static TextView textQuantity;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.bottom_section_fragment,
container, false);

    textAmount = (TextView) view.findViewById(R.id.tvAmount);
    textQuantity = (TextView) view.findViewById(R.id.tvQuantity);

    return view;
}
public void setText(String amount){
    textAmount.setText(amount);
 }
}
</code>```

FragmentActivity

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class FragmentActivity extends AppCompatActivity implements
TopSectionFragment.TopSectionListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fragment);
}

@Override
public void createQuantity(String amount) {
    BottomSectionFragment bottomFragment = (BottomSectionFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment2);
    bottomFragment.setText(amount);
  }
}
</code>```

答:
Check the textbox is empty or not before converting inside onClick()

```<code>int smallPizza, mediumPizza ,largePizza;
if(!editText1.getText().toString().trim().isEmpty()){
   smallPizza = Integer.parseInt(editText1.getText().toString());
}else{
   smallPizza = 0;
}
if(!editText2.getText().toString().trim().isEmpty()){
   mediumPizza = Integer.parseInt(editText2.getText().toString());
}else{
   mediumPizza = 0;
}
if(!editText3.getText().toString().trim().isEmpty()){
   largePizza = Integer.parseInt(editText3.getText().toString());
}else{
   largePizza = 0;
}

int total = (smallPizza * 15) + (mediumPizza * 20) + (largePizza * 25);
</code>```

Body:
I want to calculate each item separately as well as together. Also want to print the Quantity. Now I'm only able to print Total Amount. But i have to insert value in each Item. If I leave 1 blank the app crashes.

Image 1 is the FrangmentActivity showing calculating Total Amount

Image 2 is crashing of the app when i leave 1 blank input and tried to calculate

TopSectionFragment

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

public class TopSectionFragment extends Fragment {

private static EditText editText2, editText3, editText4;

TopSectionListener activityCommander;

public interface TopSectionListener {
    public void createQuantity(String result);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        activityCommander = (TopSectionListener) activity;
    }catch (ClassCastException e){
        throw new ClassCastException(activity.toString());
    }
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.top_section_fragment,
container, false);

    editText2 = (EditText) view.findViewById(R.id.etQSmall);
    editText3 = (EditText) view.findViewById(R.id.etQMedium);
    editText4 = (EditText) view.findViewById(R.id.etQLarge);
    final Button button = (Button) view.findViewById(R.id.btnCal);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            buttonClicked(v);
        }
    });

    return view;
}
public void buttonClicked(View view){

    int smallPizza = Integer.parseInt(editText2.getText().toString());
    int mediumPizza = Integer.parseInt(editText3.getText().toString());
    int largePizza = Integer.parseInt(editText4.getText().toString());

    //Do Calculation Small = 15, Medium = 20, Large = 25

    int total = (smallPizza * 15) + (mediumPizza * 20) + (largePizza *
    25);

    String result = "Total RM "+total;
    activityCommander.createQuantity(result);
   }
}

BottomSectionFragment

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class BottomSectionFragment extends Fragment{

private static TextView textAmount;
private static TextView textQuantity;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.bottom_section_fragment,
container, false);

    textAmount = (TextView) view.findViewById(R.id.tvAmount);
    textQuantity = (TextView) view.findViewById(R.id.tvQuantity);

    return view;
}
public void setText(String amount){
    textAmount.setText(amount);
 }
}

FragmentActivity

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class FragmentActivity extends AppCompatActivity implements
TopSectionFragment.TopSectionListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fragment);
}

@Override
public void createQuantity(String amount) {
    BottomSectionFragment bottomFragment = (BottomSectionFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment2);
    bottomFragment.setText(amount);
  }
}

Body:
Check the textbox is empty or not before converting inside onClick()

int smallPizza, mediumPizza ,largePizza;
if(!editText1.getText().toString().trim().isEmpty()){
   smallPizza = Integer.parseInt(editText1.getText().toString());
}else{
   smallPizza = 0;
}
if(!editText2.getText().toString().trim().isEmpty()){
   mediumPizza = Integer.parseInt(editText2.getText().toString());
}else{
   mediumPizza = 0;
}
if(!editText3.getText().toString().trim().isEmpty()){
   largePizza = Integer.parseInt(editText3.getText().toString());
}else{
   largePizza = 0;
}

int total = (smallPizza * 15) + (mediumPizza * 20) + (largePizza * 25);


问:
How and where to add angular material theme in Ionic 2?
How and where to add angular material theme?

//Import a pre-built theme

@import ‘~@angular/material/prebuilt-themes/deeppurple-amber.css’;

答:
add @import ‘~@angular/material/prebuilt-themes/deeppurple-amber.css’; in style.css under src folder

refer https://material.angular.io/guide/theming


问:
How do I sort a Laravel Collection by multiple properties with both asc and desc?
If I have an Illuminate\Support\Collection, how do I sort by multiple properties with both asc and desc?  (This is a simple hypothetical - not at all looking for tips on query building.)</p>

```<code>$collection = User::all(); // not looking for User::orderBy()->get() solutions.  Read the question.
$sorting_insructions = [
    ['column'=>'first_name', 'order'=>'asc'],
    ['column'=>'date_of_birth', 'order'=>'desc'],
];
$collection->sort(function($a,$b) use ($sorting_instructions){
    // something...
});
</code>```

答:
```<code>public static function multiPropertySort(
    Collection $collection,
    array $rules
)
{
    return $collection->sort(
        function ($a, $b) use ($rules) {
            foreach($rules as $rule){
                $sortColumn = array_get($rule, 'column');

                array_set(
                    $a,
                    $sortColumn,
                    array_get($a, $sortColumn, '')
                );

                array_set(
                    $b,
                    $sortColumn,
                    array_get($b, $sortColumn, '')
                );

                if ($sortOrder = array_get($rule, 'order', 'asc')) {
                    $x = (array_get($a, $sortColumn) <=> array_get($b, $sortColumn));
                } else {
                    $x = (array_get($b, $sortColumn) <=> array_get($a, $sortColumn));
                }

                if ($x != 0) {
                    return $x;
                }
            }

            return 0;
        }
    );
}
</code>```

Let's imagine something imperative...

Body:
If I have an Illuminate\Support\Collection, how do I sort by multiple properties with both asc and desc?  (This is a simple hypothetical - not at all looking for tips on query building.)

$collection = User::all(); // not looking for User::orderBy()->get() solutions.  Read the question.
$sorting_insructions = [
    ['column'=>'first_name', 'order'=>'asc'],
    ['column'=>'date_of_birth', 'order'=>'desc'],
];
$collection->sort(function($a,$b) use ($sorting_instructions){
    // something...
});

Body:
public static function multiPropertySort(
    Collection $collection,
    array $rules
)
{
    return $collection->sort(
        function ($a, $b) use ($rules) {
            foreach($rules as $rule){
                $sortColumn = array_get($rule, 'column');

                array_set(
                    $a,
                    $sortColumn,
                    array_get($a, $sortColumn, '')
                );

                array_set(
                    $b,
                    $sortColumn,
                    array_get($b, $sortColumn, '')
                );

                if ($sortOrder = array_get($rule, 'order', 'asc')) {
                    $x = (array_get($a, $sortColumn) <=> array_get($b, $sortColumn));
                } else {
                    $x = (array_get($b, $sortColumn) <=> array_get($a, $sortColumn));
                }

                if ($x != 0) {
                    return $x;
                }
            }

            return 0;
        }
    );
}

Let's imagine something imperative...


问:
Controller repeatedly calling itself in Spring-MVC
I was trying to just output my request with just a direct write to the response object. This works great with servlets but with Spring-MVC I ended up creating an infinite loop for some reason I don't understand. Basically the controller just gets called repeatedly. I don't even know how that is possible.

```<code>public ModelAndView handleRequest(
        HttpServletRequest request, HttpServletResponse response )
        throws ServletException, IOException
{
    System.out.println("I will get called infinitely");
    response.getWriter().print( "Hello World!");
    response.getWriter().close();
    return new ModelAndView();

}
</code>```

So the question is, does anyone know why it would cause an infinite amount of re-requests to this page? It seems to only occur when I am creating a ModelAndView() with nothing in it. But in this case I don't want anything in it, just a blank page. So secondly then is there a way to accomplish that?

答:
Try to return null, instead of ModelAndView, and call flush() instead of close(). Like this,

```<code>public ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response )
        throws ServletException, IOException {

    System.out.println("I will get called infinitely");
    response.getWriter().print( "Hello World!");
    response.getWriter().flush();
    return null;
}
</code>```

NOTE: I am not sure, whether close() will commit the response or not, but flush() will.

ContentLicense: CC BY-SA 2.5

Body:
I was trying to just output my request with just a direct write to the response object. This works great with servlets but with Spring-MVC I ended up creating an infinite loop for some reason I don't understand. Basically the controller just gets called repeatedly. I don't even know how that is possible.

public ModelAndView handleRequest(
        HttpServletRequest request, HttpServletResponse response )
        throws ServletException, IOException
{
    System.out.println("I will get called infinitely");
    response.getWriter().print( "Hello World!");
    response.getWriter().close();
    return new ModelAndView();

}

So the question is, does anyone know why it would cause an infinite amount of re-requests to this page? It seems to only occur when I am creating a ModelAndView() with nothing in it. But in this case I don't want anything in it, just a blank page. So secondly then is there a way to accomplish that?

Body:
Try to return null, instead of ModelAndView, and call flush() instead of close(). Like this,

public ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response )
        throws ServletException, IOException {

    System.out.println("I will get called infinitely");
    response.getWriter().print( "Hello World!");
    response.getWriter().flush();
    return null;
}

NOTE: I am not sure, whether close() will commit the response or not, but flush() will.


问:
Angular 4: (click) event on <option>-Tag not firing in IE11
In my application i'm using the angular (click)-Event on an option-tag. The event is fired correctly in Chrome and Firefox. Sadly it isn't fired in IE11.

My code looks like this:

```<code><select ...>
    <ng-template ngFor ...>
        <optgroup ...>
            <option ... (click)="fireEvent()">...</option>
        </optgroup>
    </ng-template>
</select>
</code>```

(The "..." are just abbreviations for some attributes that doesn't have any influence here.)

According to some other internet sources, my problem with the IE11 and the click Event in angular seems to be a known issue since....let's just say since a long time :D

There are some solutions for other HTML-Structures which doesn't work in this case.

Does anyone know some workaround for the IE11 ?

答:
I found a solution for this issue on my own. I didn't manage to get the click event running, so i tried to implement a workaround.
My workaround is using the (change) event on the  Tag. Everytime i click on another option the (change) event is emitted. The model for the currently selected  Item is still updated in my angular component, so everything seems fine.

```<code><select ... (change)="fireEvent()">
<ng-template ngFor ...>
    <optgroup ...>
        <option ... >...</option>
    </optgroup>
</ng-template>
</code>```

Body:
In my application i'm using the angular (click)-Event on an option-tag. The event is fired correctly in Chrome and Firefox. Sadly it isn't fired in IE11.

My code looks like this:

<select ...>
    <ng-template ngFor ...>
        <optgroup ...>
            <option ... (click)="fireEvent()">...</option>
        </optgroup>
    </ng-template>
</select>

(The "..." are just abbreviations for some attributes that doesn't have any influence here.)

According to some other internet sources, my problem with the IE11 and the click Event in angular seems to be a known issue since....let's just say since a long time :D

There are some solutions for other HTML-Structures which doesn't work in this case.

Does anyone know some workaround for the IE11 ?

Body:
I found a solution for this issue on my own. I didn't manage to get the click event running, so i tried to implement a workaround.
My workaround is using the (change) event on the  Tag. Everytime i click on another option the (change) event is emitted. The model for the currently selected  Item is still updated in my angular component, so everything seems fine.

<select ... (change)="fireEvent()">
<ng-template ngFor ...>
    <optgroup ...>
        <option ... >...</option>
    </optgroup>
</ng-template>


问:
PHP CSV from S3 as string - want to convert to array
I have some code which downloads a CSV file from an S3 bucket into a PHP variable.

I want to get this CSV content (a string) from this variable and convert it into an array.

I'm having some issues reading from my php://memory resource.

When I print the $csv_fread or $rows I see nothing.

Dumping the $csv_fstat shows the correct length of my file I uploaded and then downloaded and put into the $file_contents string and wrote to the $csv resource.

Any help appreciated.

```<code>  // use Aws\S3\S3Client;
  $result = $this->client->getObject([
    'Bucket' => $this->bucket,
    'Key'  => $id
  ]);

  $file_contents = $result['Body'];

  $csv = fopen('php://memory', 'r+');
  if ($csv === false) {
    throw new Exception('Could not create file wrapper');
  }
  if (fwrite($csv, $file_contents) === false) {
    throw new Exception('Could not write contents to file wrapper');
  }

  $csv_fstat = fstat($csv);
  $csv_fread = fread($csv, $csv_fstat['size']);

  if ($csv_fread === false) {
    throw new Exception('there was an error reading shit');
  }

  $header = null;
  $rows = [];
  while (($row = fgetcsv($csv, 0, ',')) !== false) {
    if (!$header) {
      $header = [];
      foreach ($row as $v) {
        $header_raw[] = $v;
        $hcounts = array_count_values($header_raw);
        $header[] = $hcounts[$v] > 1 ? $v . $hcounts[$v] : $v;
      }
    } else {
      foreach ($row as &$l) {
        $l = trim($l);
      }
      $rows[] = array_combine($header, $row);
    }
  }
  fclose($csv);
</code>```

答:
I figured out the issue. Needed to do:

```<code>rewind($csv);
</code>```

After fwrite

Body:
I have some code which downloads a CSV file from an S3 bucket into a PHP variable.

I want to get this CSV content (a string) from this variable and convert it into an array.

I'm having some issues reading from my php://memory resource.

When I print the $csv_fread or $rows I see nothing.

Dumping the $csv_fstat shows the correct length of my file I uploaded and then downloaded and put into the $file_contents string and wrote to the $csv resource.

Any help appreciated.

  // use Aws\S3\S3Client;
  $result = $this->client->getObject([
    'Bucket' => $this->bucket,
    'Key'  => $id
  ]);

  $file_contents = $result['Body'];

  $csv = fopen('php://memory', 'r+');
  if ($csv === false) {
    throw new Exception('Could not create file wrapper');
  }
  if (fwrite($csv, $file_contents) === false) {
    throw new Exception('Could not write contents to file wrapper');
  }

  $csv_fstat = fstat($csv);
  $csv_fread = fread($csv, $csv_fstat['size']);

  if ($csv_fread === false) {
    throw new Exception('there was an error reading shit');
  }

  $header = null;
  $rows = [];
  while (($row = fgetcsv($csv, 0, ',')) !== false) {
    if (!$header) {
      $header = [];
      foreach ($row as $v) {
        $header_raw[] = $v;
        $hcounts = array_count_values($header_raw);
        $header[] = $hcounts[$v] > 1 ? $v . $hcounts[$v] : $v;
      }
    } else {
      foreach ($row as &$l) {
        $l = trim($l);
      }
      $rows[] = array_combine($header, $row);
    }
  }
  fclose($csv);

Body:
I figured out the issue. Needed to do:

rewind($csv);

After fwrite


问:
Is it possible to access the different ports on a web server?
I created a game and I want to put it on online.  I want to buy a website (I'll probably use goddaddy to buy a domain name and use them as the web host) to use as the server to handle game play.  Because I would need a separate server for each game, I would need each game's server to exists on different ports.  So this leads to my question, is is possible to access these ports on my future web server? (I wrote the program in Java, so I would assume that I would access the ports from the server side by choosing a port for a ServerSocket, and from the client side by using the IP address from the website and the chosen port for a Socket)

(note: also, I am aware that it may be easier to simply use one port and run the servers on different threads instead, but I am just curious to have my question answered)

thanks a lot,
Ian

答: Your solution may work theoritically, and I like AlexR's solution. But providers like godaddy doesnt let you run a java server, on ANY port. You will need to find out somebody who does. What I found is the cost goes up from $5/mo to about $20/mo, but you get a much better (read faster) machine. Good wishes, - MS.</p>


问:
Import <template> Element From Another Website
tl;dr: Trying to get <template> element hosted somewhere else, how do?

I have an html page locally, which has the following template in the  (The point is that it's some stuff within a template tag):

```<code>  <template>
    <style>div{ background-color: red;}</style>
    <div id = "testTemplate">1</div>
  </template>
</code>```

As expected, this code doesn't template until I attach the template to some shadow-root, e.g.:

```<code><script>
  var template = document.querySelector('template');
  var containerHost = document.querySelector('.containerHost');
  var shadowRoot = containerHost.createShadowRoot();
  shadowRoot.appendChild(document.importNode(template.content, true));
</script>
</code>```

When I run the code above, my template displays. Great. Now I am trying to move my web component to a website hosted somewhere else. So I created a github page that I confirmed works: https://myusername.github.io/webcomponent/.

That is a complete html page, that has my template (same as above) in the head. I then try to pull in the html from the github page into my html using:

```<code>  <link rel="import" href="https://myusername.github.io/webcomponent/">
</code>```

This throws no errors, but the <template> is NOT visible to my page and I get the following error:

Uncaught TypeError: Cannot read property 'content' of null
      at web-component2.html:31

Because var template = document.querySelector('template'); returns null.

What gives? How do I get to my template?

P.S.
Using this page as a guide

Got the html import statement from here

Edit:

I see a request going out to my site and coming back with a 304, this is the response:

```<code><html>
<head>

  <template>
    <style>div{ background-color: red;}</style>
    <div id = "testTemplate">1</div>
  </template>

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

So the html I expect comes back fine (but is not accessible from my local page) - I am not sure if I need to isolate the <template> or am missing something equally simple.

答:
The template imported is not accessible from the document DOM. You'll need to get the current document on which the script is running and select the template from it. For example,

```<code>const currentDocument = document.currentScript.ownerDocument;
// Above is the document in which the script is executing.
// Template also resides in this document.
const template = currentDocument.querySelector('#my-template');
const instance = template.content.cloneNode(true);
shadowRoot.appendChild(instance);
</code>```

Also reconsider using HTML imports as they've been deprecated and are likely to be removed from the spec. Consider fetching HTML using AJAX requests. You can find an example here.

Body:
tl;dr: Trying to get <template> element hosted somewhere else, how do?

I have an html page locally, which has the following template in the  (The point is that it's some stuff within a template tag):

  <template>

1

  </template>

As expected, this code doesn't template until I attach the template to some shadow-root, e.g.:

When I run the code above, my template displays. Great. Now I am trying to move my web component to a website hosted somewhere else. So I created a github page that I confirmed works: https://myusername.github.io/webcomponent/.

That is a complete html page, that has my template (same as above) in the head. I then try to pull in the html from the github page into my html using:

  <link rel="import" href="https://myusername.github.io/webcomponent/">

This throws no errors, but the <template> is NOT visible to my page and I get the following error:

Uncaught TypeError: Cannot read property 'content' of null
      at web-component2.html:31

Because var template = document.querySelector('template'); returns null.

What gives? How do I get to my template?

P.S.
Using this page as a guide

Got the html import statement from here

Edit:

I see a request going out to my site and coming back with a 304, this is the response:

  <template>

1

  </template>

So the html I expect comes back fine (but is not accessible from my local page) - I am not sure if I need to isolate the <template> or am missing something equally simple.

Body:
The template imported is not accessible from the document DOM. You'll need to get the current document on which the script is running and select the template from it. For example,

const currentDocument = document.currentScript.ownerDocument;
// Above is the document in which the script is executing.
// Template also resides in this document.
const template = currentDocument.querySelector('#my-template');
const instance = template.content.cloneNode(true);
shadowRoot.appendChild(instance);

Also reconsider using HTML imports as they've been deprecated and are likely to be removed from the spec. Consider fetching HTML using AJAX requests. You can find an example here.


问:
Finding the idNumber element from this below HTML code
```<code><div id="rightContent" style="display: inline-block; width: 700px; vertical-align: top;">
                <div>
                    <h1><em class="SomethingHeading">Something</em></h1>
                </div>

<div class="content scaffold-list" role="main">
    <h1>Search</h1>

    <form action="/SomethingArchiveUI/search/search" method="post">
        <table>
            <tbody>
            <tr>
                <td>ID/Registration Number:</td>
                <td>
                    <**input type="text" name="idNumber" maxlength="20" value="" id="idNumber"**>
                </td>
            </tr>
            <tr>
                <td>Client Name:</td>
                <td>
                    <input type="text" name="clientName" maxlength="50" value="" id="clientName">
                </td>
            </tr>
            <tr>
                <td>Client Surname:</td>
                <td>
                    <input type="text" name="clientSurname" maxlength="50" value="" id="clientSurname">
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="hidden" name="_dateRange"><input type="checkbox" name="dateRange" value="true" id="dateRange"><label for="dateRange"> Use date range?</label>
                </td>
            </tr>
            <tr>
                <td colspan="2"><p>From: <input type="text" name="fromDate" value="" maxlength="10" id="fromDate" class="hasDatepicker"> To: <input type="text" name="toDate" value="" maxlength="10" id="toDate" class="hasDatepicker"></p></td>
            </tr>
            </tbody>
        </table>
        <div style="display: inline;">
            <div id="divSubmit">
                <input type="submit" name="cmdSearch" class="buttons" value="Search" id="cmdSearch">
            </div>
            <div id="divBusy" style="display: none;">
                Busy Searching...
            </div>
        </div>
    </form>

    <table id="customerIdentificationList" style="display: block;">

    </table>
    <div id="loadingMessage" style="display: none;">
        Loading. Please wait.
    </div>
</div>

            </div>
</code>```

I used this code below for logging into the Application, but similar code doesn't seem to work on this form above. I'm trying to find the 'idNumber' element:

```<code>driver.findElement(By.xpath("//*[@id='idnumber']")).sendKeys("Username");
driver.findElement(By.xpath("//*[@id=\'password\']")).sendKeys("Password");
driver.findElement(By.xpath("//*[@id=\'submit\']")).click();
</code>```

The error i get is: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":

Looking forward to your responses.

答:
I don't know the reason why you can't use By.id() or By.xpath in this case. But you can try to find the input using text in previous td. I hope next code will help:</p>

```<code>driver.findElement(By.xpath("//td[text()='ID/Registration Number:']/following-sibling::td/input")).sendKeys("Username");
</code>```

Body:
Something

Search

    <form action="/SomethingArchiveUI/search/search" method="post">

                ID/Registration Number:

                    <**input type="text" name="idNumber" maxlength="20" value="" id="idNumber"**>

                Client Name:

                    <input type="text" name="clientName" maxlength="50" value="" id="clientName">

                Client Surname:

                    <input type="text" name="clientSurname" maxlength="50" value="" id="clientSurname">

                    <input type="hidden" name="_dateRange"><input type="checkbox" name="dateRange" value="true" id="dateRange"> Use date range?

From: <input type="text" name="fromDate" value="" maxlength="10" id="fromDate" class="hasDatepicker"> To: <input type="text" name="toDate" value="" maxlength="10" id="toDate" class="hasDatepicker">

                <input type="submit" name="cmdSearch" class="buttons" value="Search" id="cmdSearch">

                Busy Searching...

    </form>

        Loading. Please wait.

I used this code below for logging into the Application, but similar code doesn't seem to work on this form above. I'm trying to find the 'idNumber' element:

driver.findElement(By.xpath("//*[@id='idnumber']")).sendKeys("Username");
driver.findElement(By.xpath("//*[@id=\'password\']")).sendKeys("Password");
driver.findElement(By.xpath("//*[@id=\'submit\']")).click();

The error i get is: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":

Looking forward to your responses.

Body:
I don't know the reason why you can't use By.id() or By.xpath in this case. But you can try to find the input using text in previous td. I hope next code will help:

driver.findElement(By.xpath("//td[text()='ID/Registration Number:']/following-sibling::td/input")).sendKeys("Username");


问:
JavaScript user input text to options value not sending to php
I want user to enter number of items from a few different textboxes in iframe and display them in parent.php as one combine options list where you can select each item and delete it if you what to. Then I want to send the final list of all options values to an email through php. I got everything working until assigning the options values to php variable. I keep getting nothing no list kin email. I'm not sure how to pass the options values to php.

This is what I got so far.

parent.php

```<code><?php

 $to = 'myemail@email.com';
 $subject = 'Available Item Lists';

 if(isset($_POST['submit'])){
      foreach ($_POST['qlist'] as $selectList)   {
           echo "You have the following :" .$selectList; // Display all
   selection values
      $body = $selectList;
      }

      $headers = '$email';
      $headers .=  'MIME-Version: 1.0' . "\r\n";
      $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

      mail ($to, $subject, $body, $headers);
  }
  ?>

    <form method="post" id="quote-form" name="quote-form" action="?">
        <label for="items">List of items</label><br />
        <div class="form-section">
            <select name="qlist[]" id="qlist" multiple="multiple"></select>
            <button id="deleteButton" onclick="deleteEntry(); return
false;">Delete</button>
       <input type="submit" value="Send" name="submit" id="submit">
    </div>

<script type="text/javascript">

       function displayQuantity(noOfitems, labelVal)  {
          var qq = noOfitems;
          var labelName = labelVal;
          var quoteQuantity = document.getElementById("qlist");
          var quantity = quoteQuantity.value;
          quantity += labelName + ": ";
          quantity += qq;
          quantity += " pcs\n";
          quoteQuantity.value = quantity;
          var option = document.createElement("option");
          option.text = quantity;
          quoteQuantity.add(option);

       }

       function deleteEntry() {
          var myList = document.getElementById('qlist');
          var i;
          for (i = myList.length - 1; i>=0; i--) {
              if (myList.options[i].selected) {
                  myList.remove(i);
              }
          }
       }
</script>
</code>```

iframe.php

```<code><div class="order-quantity">
   <form name="form">
        <label id="itemType">Heavy Duty Square Core Drilled</label>
        <input type="number" id="total-quantity" name="quantity" />
        <button type="button" id="addItem"
             onclick="parent.displayQuantity(this.form.quantity.value,
         getVal())">Add</button>
   </form>
</div>

    <script type="text/javascript">
    function getVal() {
       var labelVal = document.getElementById("itemType").textContent;
       return labelVal;
    }
    </script>
</code>```

答:
I got it!! I added this function to the submit button to select all options in a list :D</p>

```<code>   function selectAll()  {
       selectBox = document.getElementById("qlist");
       for (var i = 0; i < selectBox.options.length; i++) {
           selectBox.options[i].selected = true;
       }
   }
</code>```

Body:
I want user to enter number of items from a few different textboxes in iframe and display them in parent.php as one combine options list where you can select each item and delete it if you what to. Then I want to send the final list of all options values to an email through php. I got everything working until assigning the options values to php variable. I keep getting nothing no list kin email. I'm not sure how to pass the options values to php.

This is what I got so far.

parent.php

<?php

 $to = 'myemail@email.com';
 $subject = 'Available Item Lists';

 if(isset($_POST['submit'])){
      foreach ($_POST['qlist'] as $selectList)   {
           echo "You have the following :" .$selectList; // Display all
   selection values
      $body = $selectList;
      }

      $headers = '$email';
      $headers .=  'MIME-Version: 1.0' . "\r\n";
      $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

      mail ($to, $subject, $body, $headers);
  }
  ?>

    <form method="post" id="quote-form" name="quote-form" action="?">
        List of items

            <select name="qlist[]" id="qlist" multiple="multiple"></select>
            <button id="deleteButton" onclick="deleteEntry(); return
false;">Delete</button>
       <input type="submit" value="Send" name="submit" id="submit">

iframe.php

   <form name="form">
        Heavy Duty Square Core Drilled
        <input type="number" id="total-quantity" name="quantity" />
        <button type="button" id="addItem"
             onclick="parent.displayQuantity(this.form.quantity.value,
         getVal())">Add</button>
   </form>

Body:
I got it!! I added this function to the submit button to select all options in a list :D

   function selectAll()  {
       selectBox = document.getElementById("qlist");
       for (var i = 0; i < selectBox.options.length; i++) {
           selectBox.options[i].selected = true;
       }
   }


问:
Angular 5 plugin dependencies
If I use Angular plugins having own dependencies managed by Node and a package.json will the total list of dependencies the sum of it? Even if they have the same dependencies? So plugin 1 has 1000 dependencies and plugin 2 900 dependencies. 850 dependencies are the same. Will the total list of dependencies for the application 1900 or 200?

答:
No,

NPM knows how to deal with it. If one of your modules/dep have the same dep (version...etc), it will be downloaded once by npm and webpack should manage it too.

Title: Angular 5 plugin dependencies


问:
Plone: TinyMCE upload files
I'm trying to find a solution for files uploading directly with TinyMCE. Imagine creating a list of pdf files by uploading them using a custom button.

Is there something already done I can use? collective.clipboardupload seems to be a solution only for images.

答:
Try to use reponsive file manager :
http://www.responsivefilemanager.com/</p>

Title: Plone: TinyMCE upload files


问:
Java substring from right-hand direction, until a specific character
I want to select specific substring from the input string:

```<code>String i = "example/test/foo-foo";
</code>```

How to get only the substring foo-foo as a new string?

Expected output:

```<code>String newString = "foo-foo";
</code>```

答:
Best way to do this is through a utility class since we can reuse the code with this approach. Furthermore some corner cases can be handled to avoid runtime exceptions.

```<code>public class StringUtils {
    public static final String EMPTY = "";

    public static String substringAfterLast(String str, String separator) {
        if (isEmpty(str)) {
            return str;
        }
        if (isEmpty(separator)) {
            return EMPTY;
        }
        int pos = str.lastIndexOf(separator);
        if (pos == -1 || pos == (str.length() - separator.length())) {
            return EMPTY;
        }
        return str.substring(pos + separator.length());
    }

    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }
}
</code>```

Then create your newString using,

String newString = StringUtils.substringAfterLast(i, "/");

Body:
I want to select specific substring from the input string:

String i = "example/test/foo-foo";

How to get only the substring foo-foo as a new string?

Expected output:

String newString = "foo-foo";

Body:
Best way to do this is through a utility class since we can reuse the code with this approach. Furthermore some corner cases can be handled to avoid runtime exceptions.

public class StringUtils {
    public static final String EMPTY = "";

    public static String substringAfterLast(String str, String separator) {
        if (isEmpty(str)) {
            return str;
        }
        if (isEmpty(separator)) {
            return EMPTY;
        }
        int pos = str.lastIndexOf(separator);
        if (pos == -1 || pos == (str.length() - separator.length())) {
            return EMPTY;
        }
        return str.substring(pos + separator.length());
    }

    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }
}

Then create your newString using,

String newString = StringUtils.substringAfterLast(i, "/");


问:
tf.slice with one constant size component
Let image_shape and crop_shape be tensors of shape [None, None, None, 64]

I can do the following (propose that image_shape is greater than crop_shape)

```<code>image_shape = tf.shape(inputs)[1:-1]
crop_shape = tf.shape(shape_image)[1:-1]
n_channels = inputs.get_shape().as_list()[-1]
size = tf.concat([(-1,), image_size, (64,)], axis=0)
x = tf.slice(inputs, begin=begin, size=size)
</code>```

The resulting tensor x will be of shape [None, None, None, None] but I'd like to get  [None, None, None, 64]. Is it possible?

答: x.set_shape([None, None, None, 64]) solves my problem

Body:
Let image_shape and crop_shape be tensors of shape [None, None, None, 64]

I can do the following (propose that image_shape is greater than crop_shape)

image_shape = tf.shape(inputs)[1:-1]
crop_shape = tf.shape(shape_image)[1:-1]
n_channels = inputs.get_shape().as_list()[-1]
size = tf.concat([(-1,), image_size, (64,)], axis=0)
x = tf.slice(inputs, begin=begin, size=size)

The resulting tensor x will be of shape [None, None, None, None] but I'd like to get  [None, None, None, 64]. Is it possible?


问:
Changing the structure of an array
I have a function that looks something like this:

```<code>let result = [];
$(this).find('.js-readable').each(function(){
    if (this._value().length > 0){
        result.push({
            [this.mainId] : this._value()
        });
    };
});
return result
</code>```

As result I get an array that looks like this:

[{
  "dpr_name3": "3"
}, {
  "dpr_name1": "1"
}, {
  "dpr_name4": "5"
}, {
  "dpr_name2": "2"
}, {
  "dfnc_cur": "181"
}, {
  "doc_dt": "14.11.2017"
}]
```

<p>How can I change my function to get it like this: </p>

<pre class="lang-js prettyprint-override"><code>[{
  "dpr_name3": "3",
  "dpr_name1": "1",
  "dpr_name4": "5",
  "dpr_name2": "2",
  "dfnc_cur": "181",
  "doc_dt": "14.11.2017"
}]
</code>```

答:
You don't have to push into array. All you have to do is to initialize your array with an empty object as a first element then add key-value into it while looping:

let result = [{}];
$(this).find('.js-readable').each(function(){
    if (this._value().length > 0){
        result[0][this.mainId] = this._value;
    };
});
return result
```

Title: Changing the structure of an array

Body:
I have a function that looks something like this:

let result = [];
$(this).find('.js-readable').each(function(){
    if (this._value().length > 0){
        result.push({
            [this.mainId] : this._value()
        });
    };
});
return result

As result I get an array that looks like this:

[{
  "dpr_name3": "3"
}, {
  "dpr_name1": "1"
}, {
  "dpr_name4": "5"
}, {
  "dpr_name2": "2"
}, {
  "dfnc_cur": "181"
}, {
  "doc_dt": "14.11.2017"
}]

How can I change my function to get it like this:

[{
  "dpr_name3": "3",
  "dpr_name1": "1",
  "dpr_name4": "5",
  "dpr_name2": "2",
  "dfnc_cur": "181",
  "doc_dt": "14.11.2017"
}]


问:
Adding whitespace in a DAX expression for display in PBI Card
I'm using Power BI to create a report.I'm creating a card where I have to show product sales/target sales.
The following measure is being displayed on the card.

```<code>Measure 2 = ROUND(sum('Sales by Category'[ProductSales]),0) & "  /  " & Round(sum('Sales by Category'[TargetSales]),0)
</code>```

I need some gap at both sides of the slash i.e 25000   /   30000 .
But Even if I give multiple number of spaces before and after the / in the DAX expression,the resultant card looks like this.
 25000 / 30000

only one whitespace is being displayed on both sides of the /.
Is there any way to add a whitespace, like a '\t' or something?

答:
Interesting findings. I believe it's some built-in logic behind the visualizations which causes such inconsistent behavior.

It happens with Card and Multi-row card but not Table and Matrix:

With that said, to workaround with such behavior, you can use some other whitespace character, for example the whitespace in fullwidth form 　:

```<code>Measure = 123 & "　　　　　/         " & 456
</code>```

Results: (The left part is fullwidth whitespace)

ContentLicense: CC BY-SA 4.0

Body:
I'm using Power BI to create a report.I'm creating a card where I have to show product sales/target sales.
The following measure is being displayed on the card.

Measure 2 = ROUND(sum('Sales by Category'[ProductSales]),0) & "  /  " & Round(sum('Sales by Category'[TargetSales]),0)

I need some gap at both sides of the slash i.e 25000   /   30000 .
But Even if I give multiple number of spaces before and after the / in the DAX expression,the resultant card looks like this.
 25000 / 30000

only one whitespace is being displayed on both sides of the /.
Is there any way to add a whitespace, like a '\t' or something?

Body:
Interesting findings. I believe it's some built-in logic behind the visualizations which causes such inconsistent behavior.

It happens with Card and Multi-row card but not Table and Matrix:

With that said, to workaround with such behavior, you can use some other whitespace character, for example the whitespace in fullwidth form 　:

Measure = 123 & "　　　　　/         " & 456

Results: (The left part is fullwidth whitespace)


问:
SQL Server pagination of a result set
I have a very meaty stored procedure in a SQL Server 2000 DB which returns a single resultset. I don't want to (not allowed to) touch the original SP but would like add pagination to the returned records.

Is it possible to wrap this SP with another that takes the returned resultset and only gives me rows X to Y ?

答: Get the results from the SP and put them in a temporary table, then you can select X results from that table.</p>

Title: SQL Server pagination of a result set


问:
`applicationDidFinishLaunching` not called in iOS project
applicationDidFinishLaunching is never called in the running of my app(tested on real device and simulator) despite the fact that applicationDidBecomeActive is called. I can only find macOS solutions to this problem(here, here, and here)

In my info.plist file, I have Main storyboard file base name set correctly. I have a Storyboard entry point hooked up to my initial view controller. The app launches and I see everything I should, but applicationDidFinishLaunching is never called and I use that method to handle on-startup configuration and construction.

Based on the macOS posts, I tried dragging an object(yellow cube) into the IB hierarchy of the initial view controller, set its class as my app delegate class, and set it as the initial view controller's delegate. But applicationDidFinishLaunching is still never called.

The method signature is correct (I know this is a common issue for Swift projects)

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    return YES;
}

- (void)applicationDidFinishLaunching:(UIApplication *)application{
   //code
}
</code>```

答:
In the documentation for applicationDidFinishLaunching: it says:

Although not formally deprecated, do not use this method in your apps.
  Use the application:willFinishLaunchingWithOptions: and
  application:didFinishLaunchingWithOptions: methods instead.

If you use application:didFinishLaunchingWithOptions: then applicationDidFinishLaunching: will not be called.

Body:
applicationDidFinishLaunching is never called in the running of my app(tested on real device and simulator) despite the fact that applicationDidBecomeActive is called. I can only find macOS solutions to this problem(here, here, and here)

In my info.plist file, I have Main storyboard file base name set correctly. I have a Storyboard entry point hooked up to my initial view controller. The app launches and I see everything I should, but applicationDidFinishLaunching is never called and I use that method to handle on-startup configuration and construction.

Based on the macOS posts, I tried dragging an object(yellow cube) into the IB hierarchy of the initial view controller, set its class as my app delegate class, and set it as the initial view controller's delegate. But applicationDidFinishLaunching is still never called.

The method signature is correct (I know this is a common issue for Swift projects)

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    return YES;
}

- (void)applicationDidFinishLaunching:(UIApplication *)application{
   //code
}


问:
Selenium (Java) Get FULL text from shortened displayed on page
I want to get the FULL text of link, that is contained in a page element and retrieve is value possibly with .getText() parameter. Problem is, that on the page there is only part of it displayed followed by "...".

```<code>.getText returns = "http://www.example.com/es_es/spa..."
what I need to get ="http://www.example.com/es_es/spain/legal-notice.html"
</code>```

this is HTML

http://www.example.com/es_es/spa...```

I am able to locate the element, just not to retrieve its full text. I tried .getAttribute("href") but it returns "null".

Thank you!

答:
You wanted to use getText() method, but getText() will be helpfull while we want to retrieve the innerHTML only. But if we use getAttribute() method, we will be able to pull out any of the attributes of the WebElement.

Now, to retrieve the full text of href attribute you can use the following line of code :

```<code>System.out.println(driver.findElement(By.xpath("//a[contains(@href,'example.com/es_es/spain/legal-notice')]")).getAttribute("href"));
</code>```

Body:
I want to get the FULL text of link, that is contained in a page element and retrieve is value possibly with .getText() parameter. Problem is, that on the page there is only part of it displayed followed by "...".

.getText returns = "http://www.example.com/es_es/spa..."
what I need to get ="http://www.example.com/es_es/spain/legal-notice.html"

this is HTML

http://www.example.com/es_es/spa...

I am able to locate the element, just not to retrieve its full text. I tried .getAttribute("href") but it returns "null".

Thank you!

Body:
You wanted to use getText() method, but getText() will be helpfull while we want to retrieve the innerHTML only. But if we use getAttribute() method, we will be able to pull out any of the attributes of the WebElement.

Now, to retrieve the full text of href attribute you can use the following line of code :

System.out.println(driver.findElement(By.xpath("//a[contains(@href,'example.com/es_es/spain/legal-notice')]")).getAttribute("href"));


问:
Angular2 - Removing disabled attribute from element
I have a form that is using a directive called ng-select which enhances select inputs. In my setup, I allow a user to make some selections and then click on a "Filter" button.

Upon clicking this button, I disable the input.

HTML:

```<code><div class="form-group">
   <div class="input-group">
      <ng-select #cc formControlName="costCenter" (removed)="updateChoices(cc.active, 'costCenter')" [allowClear]="true" [multiple]="true"
      [items]="getCostCenters()" placeholder="Select one or more Cost Centers">
      </ng-select>
      <span class="input-group-btn">
      <button #b_cc class="btn btn-sm btn-default" type="button" title="Update Filter" (click)="updateChoices(cc.active, 'costCenter', cc, b_cc)"><i class="fa fa-filter"></i></button>
      </span>
   </div>
</div>
</code>```

Component Function:

```<code>    /**
     * Upon selecting a data point, reload available options
     * based on data selected.
     *
     * @param formValues
     * @param field
     */
    updateChoices(formValues, field, selectInput, button): void {

        // Show the loading indicator
        this.showLoader = true;

        // Set and fetch data
        this.selectedFields[field] = formValues;
        this.getFields(this.selectedFields, false);

        // Disable our search field and filter button
        button.disabled = true;
        selectInput.disabled = true;

    }
</code>```

You can see in the component that I am disabling both the field and the button that they clicked on.

I am now trying to implement a reset method where I can reset all of the fields back to empty, including toggling them to enabled.

I tried doing it through my reactive form by using this.importForm.controls['costCenter'].enable(); but that didn't do anything.

I inspected the form after reset and it gets set back to pristine and not touched, so I know my form reset is working, the re-enabling is not though.

I have also tried to do this in my form reset method as such:

```<code>this.importForm.reset({
  costCenter: {value:[], disabled:false},
});
</code>```

What am I missing here?

答:
Apparently solution to this is here.

This worked for me

```<code><input [attr.disabled]="IsTextBoxDisabled?'true':null">
</code>```

Body:
I have a form that is using a directive called ng-select which enhances select inputs. In my setup, I allow a user to make some selections and then click on a "Filter" button.

Upon clicking this button, I disable the input.

HTML:

      <ng-select #cc formControlName="costCenter" (removed)="updateChoices(cc.active, 'costCenter')" [allowClear]="true" [multiple]="true"
      [items]="getCostCenters()" placeholder="Select one or more Cost Centers">
      </ng-select>

      <button #b_cc class="btn btn-sm btn-default" type="button" title="Update Filter" (click)="updateChoices(cc.active, 'costCenter', cc, b_cc)"></button>

Component Function:

    /**
     * Upon selecting a data point, reload available options
     * based on data selected.
     *
     * @param formValues
     * @param field
     */
    updateChoices(formValues, field, selectInput, button): void {

        // Show the loading indicator
        this.showLoader = true;

        // Set and fetch data
        this.selectedFields[field] = formValues;
        this.getFields(this.selectedFields, false);

        // Disable our search field and filter button
        button.disabled = true;
        selectInput.disabled = true;

    }

You can see in the component that I am disabling both the field and the button that they clicked on.

I am now trying to implement a reset method where I can reset all of the fields back to empty, including toggling them to enabled.

I tried doing it through my reactive form by using this.importForm.controls['costCenter'].enable(); but that didn't do anything.

I inspected the form after reset and it gets set back to pristine and not touched, so I know my form reset is working, the re-enabling is not though.

I have also tried to do this in my form reset method as such:

this.importForm.reset({
  costCenter: {value:[], disabled:false},
});

What am I missing here?

Body:
Apparently solution to this is here.

This worked for me

<input [attr.disabled]="IsTextBoxDisabled?'true':null">


答:
You could change result to an object and assign the values to the given keys.

```<code>let result = {};
$(this).find('.js-readable').each(function(){
    if (this._value().length > 0){
        result[this.mainId] = this._value()
    };
});
</code>```

For later use, you could wrap the result in an array.

Title: Changing the structure of an array

Body:
You could change result to an object and assign the values to the given keys.

let result = {};
$(this).find('.js-readable').each(function(){
    if (this._value().length > 0){
        result[this.mainId] = this._value()
    };
});

For later use, you could wrap the result in an array.


问:
how can we use will_paginate in ruby on rails 3.0.3
is their will_paginate will support to ruby on rails 3.0.3?</p>

答: Yes, Its still in beta and we have used will paginate successfully in a production rails project.The bug that i have seen so far is the count of items at times is wrong. You can work around it by firing your own count query and populate it. </p>


问:
SQL table Convert date column to epoch
I have a table of events which includes a field called date in date format, so all entries are in the shape of YYYY-MM-DD.

Is there any simple solution to (batch) convert them all into epoch timestamp, even as a new field (date2 e.g.) as it has to be an int?

There are around 15000 entries inside this table, so I can't do it manually of course.

答:
The unix_timestamp function does just that:

```<code>ALTER TABLE mytable ADD COLUMN new_date NUMERIC;

UPDATE mytable SET new_date = UNIX_TIMESTAMP(date);
</code>```

Title: SQL table Convert date column to epoch

Body:
The unix_timestamp function does just that:

ALTER TABLE mytable ADD COLUMN new_date NUMERIC;

UPDATE mytable SET new_date = UNIX_TIMESTAMP(date);


问:
How can I save multiple value in v-model on vue.js 2?
My vue component like this :

```<code><template>
    <div class="panel panel-default">
        <a @click="deleteAll" href="javascript:" class="btn btn-danger pull-right">
            <span class="fa fa-trash"></span> Delete All
        </a>
        ...
            <tr v-for="item in list">
                <td>
                    <div class="checkbox">
                        <label>
                            <input type="checkbox" :value="item.id" v-model="checkedData">
                        </label>
                    </div>
                </td>
                ...
            </tr>
        ...
    </div>
</template>
<script>
    export default {
        data() {
            return {
                checkedData: []
            }
        },
        methods: {
            deleteAll() {
                this.$http.post(window.BaseUrl+'/message/deleteAll', {ids: this.checkedData})
            }
        }
    }
</script>
</code>```

If I check the some checkbox and click delete all button, it will send value item.id by ajax

I want to send another value too. I have value item.seller_id and item.buyer_id

I try like this :

```<code><input type="checkbox" :value="item._id+'#'+item.seller_id+'#'+item.buyer_id" v-model="checkedData">
</code>```

So I use separator # to separate the value. Seems it works

Whether it is the best solution? Or is there another better solution?

答:
Hi please look at this https://jsfiddle.net/p8zhrg6g/29/ .

```<code><div v-for="item in list">
    <input type="checkbox" :id="item.id" :value="item.value" v-model="checkedNames">
    <label :for="item.id">{{item.value}}</label>
</code>```

This is how I would have done it, hope this helps?

Body:
My vue component like this :

<template>

             Delete All

        ...

                            <input type="checkbox" :value="item.id" v-model="checkedData">

                ...

        ...

</template>

If I check the some checkbox and click delete all button, it will send value item.id by ajax

I want to send another value too. I have value item.seller_id and item.buyer_id

I try like this :

<input type="checkbox" :value="item._id+'#'+item.seller_id+'#'+item.buyer_id" v-model="checkedData">

So I use separator # to separate the value. Seems it works

Whether it is the best solution? Or is there another better solution?

Body:
Hi please look at this https://jsfiddle.net/p8zhrg6g/29/ .

<div v-for="item in list">
    <input type="checkbox" :id="item.id" :value="item.value" v-model="checkedNames">
    <label :for="item.id">{{item.value}}</label>

This is how I would have done it, hope this helps?


问:
dynamic hintText not displaying in ios in appcelerator app
Dynamically set hintText for textarea is not displaying in ios app created using appcelerator titanium.Please advise any alternative. However it works fine in android.</p>

```<code>    if (rowId == 1 ){
        $.remarktextarea.hintText = "Input Remarks";

    } else if (rowId == 2) {
        $.remarktextarea.hintText = "Add Annotation";

    }
</code>```

答:
The HintText property of a textarea is not supported on iOS, as you can see in the documentation

I'd recommend placing a label on top of the textarea with the styling you want your hinttext to have, and add touchEnabled: false to the property, so users can't click on it (but the click will go through to the textarea instead).

Then watch for changes on the textArea <TextArea id="remarktextarea" onChange="handleChange" /> and hide and show the hinttext based on length:

```<code>function handleChange(){
    $.hinttextlabel.visible = $.remarktextarea.value.length == 0
}
</code>```

Body:
Dynamically set hintText for textarea is not displaying in ios app created using appcelerator titanium.Please advise any alternative. However it works fine in android.

    if (rowId == 1 ){
        $.remarktextarea.hintText = "Input Remarks";

    } else if (rowId == 2) {
        $.remarktextarea.hintText = "Add Annotation";

    }

Body:
The HintText property of a textarea is not supported on iOS, as you can see in the documentation

I'd recommend placing a label on top of the textarea with the styling you want your hinttext to have, and add touchEnabled: false to the property, so users can't click on it (but the click will go through to the textarea instead).

Then watch for changes on the textArea <TextArea id="remarktextarea" onChange="handleChange" /> and hide and show the hinttext based on length:

function handleChange(){
    $.hinttextlabel.visible = $.remarktextarea.value.length == 0
}


问:
batch - append either date/time of creation or random to end of filename
Damsel in distress needing help with a batch-script.

I have a bunch of files that one system creates. Either in one of 2 directories, or in the directory above that.

The naming is apparently not very important, so It's a bit random.

2 questions for you batch-geniuses out there.

a) How can I append date/time of creation to the end of the filename with a batch-script?
b) How can I append a random filename (so I make the files unique) with a batch-script?

Thanks in advance, dudes and dudettes.

Yours sincerely, the Maclovin!

I have decided in my wisdom to not give a sh*t about the date of creation. I gather it follows the file anyway. What I want to do instead, is to append todays date/time to the file.

This is what I have:

```<code>SetLocal EnableDelayedExpansion
set kvitt1="c:\a"
set kvitt2="c:\b"
set tmpDir="c:\temp"
set LASTMOD=
set DATO=%DATE%
set KLOKKE=%TIME%
pause

REM lets go to this directory, and scan for files, and copy to the temp
pushd %kvitt1%

:ONE
for /f "tokens=*" %%a in ('dir /b /od 2^>NUL') do set lastmod=%%a
if "%lastmod%"=="" echo Could not locate files.&goto :TWO

COPY "%Lastmod%" %tmpDir%
pause

@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul

popd
@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul

REM Let's go to the next directory, and scan for files to copy to the temp
:TWO
REM Gå til ny nettverksstasjon
pushd %kvitt2%

for /f "tokens=*" %%a in ('dir /b /od 2^>NUL') do set lastmod=%%a
if "%lastmod%"=="" echo Could not locate files.&goto :EOF

COPY "%LASTMOD%" %tmpDir%
pause
@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul

popd

REM we have copied the files we need, lets skip to the temp directory for renaming and filenaming

pushd %tmpDir%
echo %tmpDir%
pause

REM this is clearly not doing much.
REM gåsetegn foran tmpDir fordi det kan finnes filer med mellomrom. dir/b lister opp filene i mappen, og lagrer det i  filelist.txt
dir /b "%tmpDir%" >>filelist.txt
pause
REM går igjennom alle linjene i fillist.txt. %%i inneholder filnavnet
pause
REM for /f %%i in (filelist.txt) do
REM (

REM This is clearly not working
for /F "tokens=2,3,4 delims=/ " %%a in ('date /t') do set filedate=%%a-%%b-%%c
ren %filedate%_"%%T" "%T"
REM ren "%%T" %!random%"%%~nT.kvi")

pause
</code>```

答:
you are better off using vbscript (or powershell if you have) , rather than batch. this is because date manipulation in batch is dependent on regional settings of your computer. You will have to use tricks like going into the registry and stuff as workaround.

Here's a vbscript you can adapt to your needs.

```<code>Set objFS = CreateObject( "Scripting.FileSystemObject" )
strFolder = WScript.Arguments(0)
Set objFolder = objFS.GetFolder(strFolder)
t = Now
strDate = Year(t) & Month(t) & Day(t) & Hour(t) & Minute(t) & Second(t)
' by random number
Randomize
upperbound = 99999
lowerbound = 55555

For Each strFile In objFolder.Files
    strExtension = objFS.GetExtensionName( strFile )
    strName = objFS.GetBaseName( strFile)
    rand = Int((upperbound - lowerbound + 1) * Rnd + lowerbound) 'gen random number
    ' uncomment to use date
    ' strFile.Name = strName & strDate & "." & strExtension

    ' uncomment to use random number of your choosing
    ' strFile.Name = strName & rand & "." & strExtension

Next
</code>```

Body:
Damsel in distress needing help with a batch-script.

I have a bunch of files that one system creates. Either in one of 2 directories, or in the directory above that.

The naming is apparently not very important, so It's a bit random.

2 questions for you batch-geniuses out there.

a) How can I append date/time of creation to the end of the filename with a batch-script?
b) How can I append a random filename (so I make the files unique) with a batch-script?

Thanks in advance, dudes and dudettes.

Yours sincerely, the Maclovin!

I have decided in my wisdom to not give a sh*t about the date of creation. I gather it follows the file anyway. What I want to do instead, is to append todays date/time to the file.

This is what I have:

SetLocal EnableDelayedExpansion
set kvitt1="c:\a"
set kvitt2="c:\b"
set tmpDir="c:\temp"
set LASTMOD=
set DATO=%DATE%
set KLOKKE=%TIME%
pause

REM lets go to this directory, and scan for files, and copy to the temp
pushd %kvitt1%

:ONE
for /f "tokens=*" %%a in ('dir /b /od 2^>NUL') do set lastmod=%%a
if "%lastmod%"=="" echo Could not locate files.&goto :TWO

COPY "%Lastmod%" %tmpDir%
pause

@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul

popd
@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul

REM Let's go to the next directory, and scan for files to copy to the temp
:TWO
REM Gå til ny nettverksstasjon
pushd %kvitt2%

for /f "tokens=*" %%a in ('dir /b /od 2^>NUL') do set lastmod=%%a
if "%lastmod%"=="" echo Could not locate files.&goto :EOF

COPY "%LASTMOD%" %tmpDir%
pause
@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul

popd

REM we have copied the files we need, lets skip to the temp directory for renaming and filenaming

pushd %tmpDir%
echo %tmpDir%
pause

REM this is clearly not doing much.
REM gåsetegn foran tmpDir fordi det kan finnes filer med mellomrom. dir/b lister opp filene i mappen, og lagrer det i  filelist.txt
dir /b "%tmpDir%" >>filelist.txt
pause
REM går igjennom alle linjene i fillist.txt. %%i inneholder filnavnet
pause
REM for /f %%i in (filelist.txt) do
REM (

REM This is clearly not working
for /F "tokens=2,3,4 delims=/ " %%a in ('date /t') do set filedate=%%a-%%b-%%c
ren %filedate%_"%%T" "%T"
REM ren "%%T" %!random%"%%~nT.kvi")

pause

Body:
you are better off using vbscript (or powershell if you have) , rather than batch. this is because date manipulation in batch is dependent on regional settings of your computer. You will have to use tricks like going into the registry and stuff as workaround.

Here's a vbscript you can adapt to your needs.

Set objFS = CreateObject( "Scripting.FileSystemObject" )
strFolder = WScript.Arguments(0)
Set objFolder = objFS.GetFolder(strFolder)
t = Now
strDate = Year(t) & Month(t) & Day(t) & Hour(t) & Minute(t) & Second(t)
' by random number
Randomize
upperbound = 99999
lowerbound = 55555

For Each strFile In objFolder.Files
    strExtension = objFS.GetExtensionName( strFile )
    strName = objFS.GetBaseName( strFile)
    rand = Int((upperbound - lowerbound + 1) * Rnd + lowerbound) 'gen random number
    ' uncomment to use date
    ' strFile.Name = strName & strDate & "." & strExtension

    ' uncomment to use random number of your choosing
    ' strFile.Name = strName & rand & "." & strExtension

Next