问:
XSLT transformation of comma seperated data returned from SQL
I return info from SQL using XSLT 1.0 like this:

```<code><xsl:if test="../Field[@Name='TheDBFieldName'][.!='']">
    <xsl:element namespace="http://BlahBlah" name="TheResult">
        <xsl:value-of select="../Field[@Name='TheDbFieldName']" />
    </xsl:element>
</xsl:if>
</code>```

My Current result looks like this:

1,2,3,6

I need to return it like this:

```<code><TheDBFieldName>
    <TheResult>
        <Result>1</Result>
    </TheResult>
    <TheResult>
        <Result>2</Result>
    </TheResult>
    <TheResult>
        <Result>3</Result>
    </TheResult>
    <TheResult>
        <Result>6</Result>
    </TheResult>
</TheDBFieldName>
</code>```

Unfortunately XSLT 2.0 is not an option for me

Any help on this including and example using my infowould be greatly appreciated!  I have been unable to apply current examples to mine example mainly because of my use of SQL data rather than absorbing an XML file

答:
You could use substring-before() and substring-after() in a recursive template call.

Example...

XML Input

```<code><Field Name="TheDBFieldName">1,2,3,6</Field>
</code>```

XSLT 1.0

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="Field">
    <xsl:element name="{@Name}">
      <xsl:call-template name="tokenize">
        <xsl:with-param name="input" select="."/>
      </xsl:call-template>
    </xsl:element>
  </xsl:template>

  <xsl:template name="tokenize">
    <xsl:param name="input"/>
    <xsl:variable name="remaining" select="substring-after($input,',')"/>
    <TheResult>
      <Result>
        <xsl:value-of select="normalize-space(substring-before(concat($input,','),','))"/>
      </Result>
    </TheResult>
    <xsl:if test="$remaining">
      <xsl:call-template name="tokenize">
        <xsl:with-param name="input" select="$remaining"/>
      </xsl:call-template>
    </xsl:if>
  </xsl:template>

</xsl:stylesheet>
</code>```

Output

```<code><TheDBFieldName>
   <TheResult>
      <Result>1</Result>
   </TheResult>
   <TheResult>
      <Result>2</Result>
   </TheResult>
   <TheResult>
      <Result>3</Result>
   </TheResult>
   <TheResult>
      <Result>6</Result>
   </TheResult>
</TheDBFieldName>
</code>```

To adapt to your stylesheet, add the tokenize template and change:

```<code><xsl:value-of select="../Field[@Name='TheDbFieldName']" />
</code>```

to:

```<code><xsl:call-template name="tokenize">
  <xsl:with-param name="input" select="../Field[@Name='TheDbFieldName']"/>
</xsl:call-template>
</code>```

Body:
I return info from SQL using XSLT 1.0 like this:

<xsl:if test="../Field[@Name='TheDBFieldName'][.!='']">
    <xsl:element namespace="http://BlahBlah" name="TheResult">
        <xsl:value-of select="../Field[@Name='TheDbFieldName']" />
    </xsl:element>
</xsl:if>

My Current result looks like this:

1,2,3,6

I need to return it like this:

<TheDBFieldName>
    <TheResult>
        <Result>1</Result>
    </TheResult>
    <TheResult>
        <Result>2</Result>
    </TheResult>
    <TheResult>
        <Result>3</Result>
    </TheResult>
    <TheResult>
        <Result>6</Result>
    </TheResult>
</TheDBFieldName>

Unfortunately XSLT 2.0 is not an option for me

Any help on this including and example using my infowould be greatly appreciated!  I have been unable to apply current examples to mine example mainly because of my use of SQL data rather than absorbing an XML file

Body:
You could use substring-before() and substring-after() in a recursive template call.

Example...

XML Input

<Field Name="TheDBFieldName">1,2,3,6</Field>

XSLT 1.0

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="Field">
    <xsl:element name="{@Name}">
      <xsl:call-template name="tokenize">
        <xsl:with-param name="input" select="."/>
      </xsl:call-template>
    </xsl:element>
  </xsl:template>

  <xsl:template name="tokenize">
    <xsl:param name="input"/>
    <xsl:variable name="remaining" select="substring-after($input,',')"/>
    <TheResult>
      <Result>
        <xsl:value-of select="normalize-space(substring-before(concat($input,','),','))"/>
      </Result>
    </TheResult>
    <xsl:if test="$remaining">
      <xsl:call-template name="tokenize">
        <xsl:with-param name="input" select="$remaining"/>
      </xsl:call-template>
    </xsl:if>
  </xsl:template>

</xsl:stylesheet>

Output

<TheDBFieldName>
   <TheResult>
      <Result>1</Result>
   </TheResult>
   <TheResult>
      <Result>2</Result>
   </TheResult>
   <TheResult>
      <Result>3</Result>
   </TheResult>
   <TheResult>
      <Result>6</Result>
   </TheResult>
</TheDBFieldName>

To adapt to your stylesheet, add the tokenize template and change:

<xsl:value-of select="../Field[@Name='TheDbFieldName']" />

to:

<xsl:call-template name="tokenize">
  <xsl:with-param name="input" select="../Field[@Name='TheDbFieldName']"/>
</xsl:call-template>


来源: stackexchange

问:
error while making connection in mvc .net (system.data.common.dbconnection)
i am new to the mvc and trying to connect my mysql database to the application using mvc..

my connection string is as-

```<code><connectionString>
    <add name ="Controlsheetlogin" connectionString="Server=localhost; database=test;User Id=root;password=123"/>
</connectionString>
</code>```

this is my connection string

and am getting error in MySql.Data.MySqlClient.MySqlCommand
thanks in advance for any help.

and this is the error that i am getting

答:
Your connection string does not look right. To Connect EF to MySQL you need to specify the provider as such:

```<code>[...] name="ConnectionString" providerName="MySql.Data.MySqlClient" [...]
</code>```

Answers to this question may be helpful, as it details how to set up EF with MySQL.

ContentLicense: CC BY-SA 3.0

Body:
i am new to the mvc and trying to connect my mysql database to the application using mvc..

my connection string is as-

<connectionString>
    <add name ="Controlsheetlogin" connectionString="Server=localhost; database=test;User Id=root;password=123"/>
</connectionString>

this is my connection string

and am getting error in MySql.Data.MySqlClient.MySqlCommand
thanks in advance for any help.

and this is the error that i am getting

Body:
Your connection string does not look right. To Connect EF to MySQL you need to specify the provider as such:

[...] name="ConnectionString" providerName="MySql.Data.MySqlClient" [...]

Answers to this question may be helpful, as it details how to set up EF with MySQL.


问:
Subset dataframe based on duplicate values in multiple rows
How can I subset the dataframe below to show only the rows were columns AAA:CCC all have the same value and retain the IndID field?

```<code>Dat <- data.frame(IndID = LETTERS[seq(1,10)],
                  AAA = c(1,5,3,2,3,1,5,4,6,2),
                  BBB = c(1,8,5,2,5,4,8,4,4,5),
                  CCC = c(1,5,3,2,3,5,5,4,6,5))

> Dat
   IndID AAA BBB CCC
1      A   1   1   1
2      B   5   8   5
3      C   3   5   3
4      D   2   2   2
5      E   3   5   3
6      F   1   4   5
7      G   5   8   5
8      H   4   4   4
9      I   6   4   6
10     J   2   5   5
</code>```

I would like to return the following result.

```<code>Result <- data.frame(IndID = c("A", "D", "H"),
                  AAA = c(1,2,4),
                  BBB = c(1,2,4),
                  CCC = c(1,2,4))

> Result
  IndID AAA BBB CCC
1     A   1   1   1
2     D   2   2   2
3     H   4   4   4
</code>```

I have found a number of related posts including Find duplicated rows (based on 2 columns) in Data Frame in R and Find duplicated elements with dplyr, among others, but have not been able to reproduce the desired result with three columns. For example, while close the code below shows all distinct rows, but with the undesired result of including rows were only two of the values are equal.

```<code>Dat %>% distinct(AAA, BBB, CCC)
</code>```

I suspect the solution involves filter but an not sure how to obtain the desired result from the example mentioned above. A dplyr solution is preferred.

Addition
I also wonder if this could be applied to multiple factors. For example with the data below, which contains an IndID and three dates stored as factors, can a similar result be produced by either allowing factors or changing the factors to numeric values?

```<code>Dat <- structure(list(GenIndID = structure(c(1L, 2L, 6L, 7L, 3L, 4L,
8L, 5L), .Label = c("BHS_601", "BHS_603", "BHS_604", "BHS_605",
"BHS_631", "BHS_635", "BHS_636", "BHS_637"), class = "factor"),
    CptrDate = structure(c(1L, 2L, 3L, 3L, 2L, 2L, 3L, 4L), .Label = c("2016-02-01",
    "2016-02-02", "2016-02-04", "2016-12-11"), class = "factor"),
    DtLastAlive = structure(c(2L, 2L, 1L, 1L, 2L, 2L, 1L, 3L), .Label = c("2016-02-04",
    "2017-07-13", "2017-08-27"), class = "factor"), DtFnlFate = structure(c(2L,
    2L, 1L, 1L, 2L, 2L, 1L, 3L), .Label = c("2016-02-04", "2017-07-13",
    "2017-08-27"), class = "factor")), .Names = c("GenIndID",
"CptrDate", "DtLastAlive", "DtFnlFate"), row.names = c(82L, 83L,
224L, 225L, 84L, 85L, 226L, 360L), class = "data.frame")

> Dat
    GenIndID   CptrDate DtLastAlive  DtFnlFate
82   BHS_601 2016-02-01  2017-07-13 2017-07-13
83   BHS_603 2016-02-02  2017-07-13 2017-07-13
224  BHS_635 2016-02-04  2016-02-04 2016-02-04
225  BHS_636 2016-02-04  2016-02-04 2016-02-04
84   BHS_604 2016-02-02  2017-07-13 2017-07-13
85   BHS_605 2016-02-02  2017-07-13 2017-07-13
226  BHS_637 2016-02-04  2016-02-04 2016-02-04
360  BHS_631 2016-12-11  2017-08-27 2017-08-27
</code>```

with the desired result being

```<code>> Dat[c(3, 4, 7),]
    GenIndID   CptrDate DtLastAlive  DtFnlFate
224  BHS_635 2016-02-04  2016-02-04 2016-02-04
225  BHS_636 2016-02-04  2016-02-04 2016-02-04
226  BHS_637 2016-02-04  2016-02-04 2016-02-04
</code>```

答:
You could use a combination of range() and diff().

```<code>Dat[apply(Dat[ ,-1], 1, function(x) diff(range(x)))==0, ]
#   IndID AAA BBB CCC
# 1     A   1   1   1
# 4     D   2   2   2
# 8     H   4   4   4
</code>```

range() gives you the minimum and the maximum of a vector. diff() gives you the difference between values in a vector. If the difference between min-value and max-value is zero, you know all values are equal. If we apply this row-wise using apply, we get a TRUE/FALSE vector that we can use to index Dat.

Small examples to illustrate the logic:

```<code>test <- c(1, 5, 3)
minmax <- range(test)    # gives c(1,5)
diff(minmax)             # gives 4
diff(range(c(1, 1, 1)))  # gives 0
</code>```

If we check for every row, whether or not diff(range(your_row)) equals zero, we can use the output of that to index Dat, like we did above.

Body:
How can I subset the dataframe below to show only the rows were columns AAA:CCC all have the same value and retain the IndID field?

Dat <- data.frame(IndID = LETTERS[seq(1,10)],
                  AAA = c(1,5,3,2,3,1,5,4,6,2),
                  BBB = c(1,8,5,2,5,4,8,4,4,5),
                  CCC = c(1,5,3,2,3,5,5,4,6,5))

> Dat
   IndID AAA BBB CCC
1      A   1   1   1
2      B   5   8   5
3      C   3   5   3
4      D   2   2   2
5      E   3   5   3
6      F   1   4   5
7      G   5   8   5
8      H   4   4   4
9      I   6   4   6
10     J   2   5   5

I would like to return the following result.

Result <- data.frame(IndID = c("A", "D", "H"),
                  AAA = c(1,2,4),
                  BBB = c(1,2,4),
                  CCC = c(1,2,4))

> Result
  IndID AAA BBB CCC
1     A   1   1   1
2     D   2   2   2
3     H   4   4   4

I have found a number of related posts including Find duplicated rows (based on 2 columns) in Data Frame in R and Find duplicated elements with dplyr, among others, but have not been able to reproduce the desired result with three columns. For example, while close the code below shows all distinct rows, but with the undesired result of including rows were only two of the values are equal.

Dat %>% distinct(AAA, BBB, CCC)

I suspect the solution involves filter but an not sure how to obtain the desired result from the example mentioned above. A dplyr solution is preferred.

Addition
I also wonder if this could be applied to multiple factors. For example with the data below, which contains an IndID and three dates stored as factors, can a similar result be produced by either allowing factors or changing the factors to numeric values?

Dat <- structure(list(GenIndID = structure(c(1L, 2L, 6L, 7L, 3L, 4L,
8L, 5L), .Label = c("BHS_601", "BHS_603", "BHS_604", "BHS_605",
"BHS_631", "BHS_635", "BHS_636", "BHS_637"), class = "factor"),
    CptrDate = structure(c(1L, 2L, 3L, 3L, 2L, 2L, 3L, 4L), .Label = c("2016-02-01",
    "2016-02-02", "2016-02-04", "2016-12-11"), class = "factor"),
    DtLastAlive = structure(c(2L, 2L, 1L, 1L, 2L, 2L, 1L, 3L), .Label = c("2016-02-04",
    "2017-07-13", "2017-08-27"), class = "factor"), DtFnlFate = structure(c(2L,
    2L, 1L, 1L, 2L, 2L, 1L, 3L), .Label = c("2016-02-04", "2017-07-13",
    "2017-08-27"), class = "factor")), .Names = c("GenIndID",
"CptrDate", "DtLastAlive", "DtFnlFate"), row.names = c(82L, 83L,
224L, 225L, 84L, 85L, 226L, 360L), class = "data.frame")

> Dat
    GenIndID   CptrDate DtLastAlive  DtFnlFate
82   BHS_601 2016-02-01  2017-07-13 2017-07-13
83   BHS_603 2016-02-02  2017-07-13 2017-07-13
224  BHS_635 2016-02-04  2016-02-04 2016-02-04
225  BHS_636 2016-02-04  2016-02-04 2016-02-04
84   BHS_604 2016-02-02  2017-07-13 2017-07-13
85   BHS_605 2016-02-02  2017-07-13 2017-07-13
226  BHS_637 2016-02-04  2016-02-04 2016-02-04
360  BHS_631 2016-12-11  2017-08-27 2017-08-27

with the desired result being

> Dat[c(3, 4, 7),]
    GenIndID   CptrDate DtLastAlive  DtFnlFate
224  BHS_635 2016-02-04  2016-02-04 2016-02-04
225  BHS_636 2016-02-04  2016-02-04 2016-02-04
226  BHS_637 2016-02-04  2016-02-04 2016-02-04

Body:
You could use a combination of range() and diff().

Dat[apply(Dat[ ,-1], 1, function(x) diff(range(x)))==0, ]
#   IndID AAA BBB CCC
# 1     A   1   1   1
# 4     D   2   2   2
# 8     H   4   4   4

range() gives you the minimum and the maximum of a vector. diff() gives you the difference between values in a vector. If the difference between min-value and max-value is zero, you know all values are equal. If we apply this row-wise using apply, we get a TRUE/FALSE vector that we can use to index Dat.

Small examples to illustrate the logic:

test <- c(1, 5, 3)
minmax <- range(test)    # gives c(1,5)
diff(minmax)             # gives 4
diff(range(c(1, 1, 1)))  # gives 0

If we check for every row, whether or not diff(range(your_row)) equals zero, we can use the output of that to index Dat, like we did above.


问:
Match value and count corresponding value differences between two sheets
I have two Google sheets with different Fictional characters (column A) and their corresponding Type (column B).

Sheet1

```<code>| Fictional character | Type            |
|:--------------------|:---------------:|
| Spider Ham          | Pig             |
| Iron Man            | Human           |
| Captain America     | Human           |
| Thor                | God             |
| Hercules            | God             |
| Superman            | Alien           |
</code>```

Sheet2

```<code>| Fictional character | Type            |
|:--------------------|:---------------:|
| Spider Ham          | Human           |
| Iron Man            | Human           |
| Captain America     | Human           |
| Thor                | God             |
| Hercules            | Demi-God        |
| Doctor Octopus      | Human           |
</code>```

The differences between Sheet1 and Sheet2:

Sheet1 have the fictional character "Superman", which Sheet2 does not have

Sheet2 have the fictional character "Doctor Octopus", which Sheet1 does not have

The fictional character "Spider Ham" and "Hercules" have another type in both sheets

I want to compare how many of the fictional characters that have a different Type (excluding characters that does not exist in both sheets)

Sheet3 should look like this:

```<code>| Difference          | Sum             |
|:--------------------|----------------:|
| Same type           | 3               |
| Not the same type   | 2               |
</code>```

I have tried with the following, but it's not a valid formula - and I haven't figured out how to exclude if characters that does not exist in both sheets:

=COUNTIF(VLOOKUP(Sheet1!A:A;Sheet1!A:B;2;FALSE)=VLOOKUP(Sheet2!A:A;Sheet1!A:B;2;FALSE);"=TRUE")
=COUNTIF(VLOOKUP(Sheet1!A:A;Sheet1!A:B;2;FALSE)=VLOOKUP(Sheet2!A:A;Sheet1!A:B;2;FALSE);"=FALSE")

答:
Same Type:

```<code>=SUMPRODUCT(IFERROR(VLOOKUP(A2:A7,A11:B16,2,0)=B2:B7,0))
</code>```

Not the same type:

```<code>=SUMPRODUCT(IFERROR(VLOOKUP(A2:A7,A11:B16,2,0)<>B2:B7,0))
</code>```

Notes:

A2:B7=Sheet 1 data

A11:B16=Sheet 2 data

Change , to ;

Body:
I have two Google sheets with different Fictional characters (column A) and their corresponding Type (column B).

Sheet1

| Fictional character | Type            |
|:--------------------|:---------------:|
| Spider Ham          | Pig             |
| Iron Man            | Human           |
| Captain America     | Human           |
| Thor                | God             |
| Hercules            | God             |
| Superman            | Alien           |

Sheet2

| Fictional character | Type            |
|:--------------------|:---------------:|
| Spider Ham          | Human           |
| Iron Man            | Human           |
| Captain America     | Human           |
| Thor                | God             |
| Hercules            | Demi-God        |
| Doctor Octopus      | Human           |

The differences between Sheet1 and Sheet2:

Sheet1 have the fictional character "Superman", which Sheet2 does not have

Sheet2 have the fictional character "Doctor Octopus", which Sheet1 does not have

The fictional character "Spider Ham" and "Hercules" have another type in both sheets

I want to compare how many of the fictional characters that have a different Type (excluding characters that does not exist in both sheets)

Sheet3 should look like this:

| Difference          | Sum             |
|:--------------------|----------------:|
| Same type           | 3               |
| Not the same type   | 2               |

I have tried with the following, but it's not a valid formula - and I haven't figured out how to exclude if characters that does not exist in both sheets:

=COUNTIF(VLOOKUP(Sheet1!A:A;Sheet1!A:B;2;FALSE)=VLOOKUP(Sheet2!A:A;Sheet1!A:B;2;FALSE);"=TRUE")
=COUNTIF(VLOOKUP(Sheet1!A:A;Sheet1!A:B;2;FALSE)=VLOOKUP(Sheet2!A:A;Sheet1!A:B;2;FALSE);"=FALSE")

Body:
Same Type:

=SUMPRODUCT(IFERROR(VLOOKUP(A2:A7,A11:B16,2,0)=B2:B7,0))

Not the same type:

=SUMPRODUCT(IFERROR(VLOOKUP(A2:A7,A11:B16,2,0)<>B2:B7,0))

Notes:

A2:B7=Sheet 1 data

A11:B16=Sheet 2 data

Change , to ;


问:
LINQ to SQL: What gives pain?
I decided to use LINQ to SQL in my personal project after hearing lots of goods. Is there any thing I need to taken care before start using it (during initial design)?</p>

答:
If you're going to write data, you require primary keys (for tracking row identity across in-memory objects).  These primary keys should be preferably single column.

Watch out for decimal precision and string length.

Watch out for any varchar(1) columns. these get mapped to a .Net char, which can't hold the empty string.

OwnerDisplayName: Mahesh

ContentLicense: CC BY-SA 2.5

Title: LINQ to SQL: What gives pain?

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: David B


问:
Where does the ASP.NET development server keep its logs?
I am trying to sort out a problem where some relative urls are not resolving properly in an ASP.NET website. I want to see the HTTP logs to determine which URLs are being requested from the web server. I am using the ASP.NET Development Server, not IIS.

So are there logs produced by the ASP.NET Development Server where I can check which files are being requested?

Windows 7, 64bit

VS2008

ASP.NET 3.5 SP1

答: As far as I understand Cassini has no logging feature</p>


问:
AWS CLI not working in Cygwin
I am working on a Windows computer and have been using Git Bash up until now without a problem. However, Git Bash seems to be missing some commands that Cygwin can provide, so I switched to Cygwin.

I need to use AWS CLI with Cygwin but any time I input any aws command, I get the following error:

C:\users\myusername\appdata\local\programs\python\python36\python.exe:
  can't open file
  '/cygdrive/c/Users/myusername/AppData/Local/Programs/Python/Python36/Scripts/aws':
  [Errno 2] No such file or directory

I've seen other questions about getting Cygwin working with AWS, but they seem to talk about AWS CLI being incompatible with Windows' Anaconda version of Python (which mine doesn't seem to be). Any thoughts on how to fix this? Thanks.

答:
You are mixing cygwin posix path with with a not cygwin Python.

C:\users\myusername\appdata\local\programs\python\python36\python.exe

Is not the cygwin python so it can't open the file as

/cygdrive/c/Users/myusername/AppData/Local/Programs/Python/Python36/Scripts/aws is not a windows path that it can understand . Only Cygwin programs understand it.

Two possible solutions:

1 Use a windows path

2 Use a cygwin Python

Title: AWS CLI not working in Cygwin


问:
Start .exe file and automatically "press enter for "Save"" in SAS
I have a SAS program I would like to schedule, so we don't have to run it manually.

In the program we call an excecutable (reg.exe), like this:

```<code>X CALL "K:\reg.exe";
</code>```

The executable opens a standard windows save-dialog and all we need to do is press save, which will save an xml-file. The save-dialog already opens in the correct directory.

What I would like is to somehow pass the instruction on, using code, to "press save", so the program can move on and work with the saved xml-file.

Is this possible somehow?

Thanks for your help!

答:
Thomas:

There are numerous Windows utilities for scripted control of an interactive program. For example: AutoIt (my favorite), MouseRobot and AutoHotKey to name a few.

The statement

```<code>options xmin noxwait noxsync;
</code>```

will cause the external program to run, not wait for the command session to exit, and not wait for the command to complete.

If your SAS programs needs to wait for the side effects of the scripting use of reg.exe to occur before occurring, use:

```<code>options xmin noxwait xsync;
</code>```

These settings affect other operating system interfacing features, such as:

X command

CALL SYSTEM routine

%SYSEXEC statement

The use of your reg.exe might require your login to have admin rights.

The SYSTASK statement can also run external commands.

If you find that you are unable to run external commands, it is probably because the system setting NOXCMD is active.  This setting is on by default in SAS server environments.

Body:
I have a SAS program I would like to schedule, so we don't have to run it manually.

In the program we call an excecutable (reg.exe), like this:

X CALL "K:\reg.exe";

The executable opens a standard windows save-dialog and all we need to do is press save, which will save an xml-file. The save-dialog already opens in the correct directory.

What I would like is to somehow pass the instruction on, using code, to "press save", so the program can move on and work with the saved xml-file.

Is this possible somehow?

Thanks for your help!

Body:
Thomas:

There are numerous Windows utilities for scripted control of an interactive program. For example: AutoIt (my favorite), MouseRobot and AutoHotKey to name a few.

The statement

options xmin noxwait noxsync;

will cause the external program to run, not wait for the command session to exit, and not wait for the command to complete.

If your SAS programs needs to wait for the side effects of the scripting use of reg.exe to occur before occurring, use:

options xmin noxwait xsync;

These settings affect other operating system interfacing features, such as:

X command

CALL SYSTEM routine

%SYSEXEC statement

The use of your reg.exe might require your login to have admin rights.

The SYSTASK statement can also run external commands.

If you find that you are unable to run external commands, it is probably because the system setting NOXCMD is active.  This setting is on by default in SAS server environments.


问:
spring boot rest ResponseEntity responses
Fairly new to spring boot rest and have questions regarding the how and the best way to handle responses to the client using the service.  Currently, I have the following controller code for handling the case of a record not being found in a database query:

```<code>@PreAuthorize("hasAuthority('ROLE_USER')")
@GetMapping("distance/{id}")
public ResponseEntity<?> getDistanceById(@PathVariable("id") Integer id) {
    log.info("getDistanceById");
    Distance distance = distanceService.getDistanceById(id);
    if (distance == null){
        return new ResponseEntity<CustomErrorMsg>(new CustomErrorMsg("Distance ID " + id + " Not Found"),HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<Distance>(distance, HttpStatus.OK);
}
</code>```

Where CustomErrorMsg is a simple class that sets a String in it's constructor.

Is this the best approach?  Would a ControllerAdvice based class be a better aproach?  Asking this question because the code above sends an expected 403 response when called by a cient without permission. Would like understand how that is occuring and if it can be used for a NOT FOUND condition.

答:
"Resource not found" is a well-known use case, for which you don't have to "bother" with ResponseEntity or ControllerAdvice. You can simply use ResourceNotFoundException.

```<code>@PreAuthorize("hasRole('USER')")
@GetMapping("distance/{id}")
public Distance getDistanceById(@PathVariable("id") Integer id) {
    log.info("getDistanceById");
    Distance distance = distanceService.getDistanceById(id);
    if (distance == null) {
        throw new ResourceNotFoundException("Distance ID " + id + " Not Found");
    }

    return distance;
}
</code>```

Declaring ResponseEntity<?> as return type is correct but doesn't convey much information, since you're putting actual data and an error message on the same level. If like me you prefer to use the ResponseEntity static builders, go for :

```<code>@PreAuthorize("hasRole('USER')")
@GetMapping("distance/{id}")
public ResponseEntity<Distance> getDistanceById(@PathVariable("id") Integer id) {
    log.info("getDistanceById");
    Distance distance = distanceService.getDistanceById(id);
    if (distance == null){
        throw new ResourceNotFoundException("Distance ID " + id + " Not Found");
    }

    return new ResponseEntity.ok(distance);
}
</code>```

Again, what you're interested in is a Distance (your code probably stands in a class called DistanceController), so let's not emphasize when it's not found.

Now, regarding the HTTP status.
If you request /distance/<id> with insufficient privileges, you'll get an access denial (403 Forbidden), which is not the same as an unknown resource (404 Not Found) - that is btw the status returned when ResourceNotFoundException is thrown.

Here, permissions to access the requested URL is checked first. If the user is authenticated with insufficient authorities, you get a 403 error. It not, you're free to go, and will get the requested resource (200), unless it doesn't exist (404).

Body:
Fairly new to spring boot rest and have questions regarding the how and the best way to handle responses to the client using the service.  Currently, I have the following controller code for handling the case of a record not being found in a database query:

@PreAuthorize("hasAuthority('ROLE_USER')")
@GetMapping("distance/{id}")
public ResponseEntity<?> getDistanceById(@PathVariable("id") Integer id) {
    log.info("getDistanceById");
    Distance distance = distanceService.getDistanceById(id);
    if (distance == null){
        return new ResponseEntity<CustomErrorMsg>(new CustomErrorMsg("Distance ID " + id + " Not Found"),HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<Distance>(distance, HttpStatus.OK);
}

Where CustomErrorMsg is a simple class that sets a String in it's constructor.

Is this the best approach?  Would a ControllerAdvice based class be a better aproach?  Asking this question because the code above sends an expected 403 response when called by a cient without permission. Would like understand how that is occuring and if it can be used for a NOT FOUND condition.

Body:
"Resource not found" is a well-known use case, for which you don't have to "bother" with ResponseEntity or ControllerAdvice. You can simply use ResourceNotFoundException.

@PreAuthorize("hasRole('USER')")
@GetMapping("distance/{id}")
public Distance getDistanceById(@PathVariable("id") Integer id) {
    log.info("getDistanceById");
    Distance distance = distanceService.getDistanceById(id);
    if (distance == null) {
        throw new ResourceNotFoundException("Distance ID " + id + " Not Found");
    }

    return distance;
}

Declaring ResponseEntity<?> as return type is correct but doesn't convey much information, since you're putting actual data and an error message on the same level. If like me you prefer to use the ResponseEntity static builders, go for :

@PreAuthorize("hasRole('USER')")
@GetMapping("distance/{id}")
public ResponseEntity<Distance> getDistanceById(@PathVariable("id") Integer id) {
    log.info("getDistanceById");
    Distance distance = distanceService.getDistanceById(id);
    if (distance == null){
        throw new ResourceNotFoundException("Distance ID " + id + " Not Found");
    }

    return new ResponseEntity.ok(distance);
}

Again, what you're interested in is a Distance (your code probably stands in a class called DistanceController), so let's not emphasize when it's not found.

Now, regarding the HTTP status.
If you request /distance/<id> with insufficient privileges, you'll get an access denial (403 Forbidden), which is not the same as an unknown resource (404 Not Found) - that is btw the status returned when ResourceNotFoundException is thrown.

Here, permissions to access the requested URL is checked first. If the user is authenticated with insufficient authorities, you get a 403 error. It not, you're free to go, and will get the requested resource (200), unless it doesn't exist (404).


问:
Laravel guzzle cURL error 6: Could not resolve host: http (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
On my development my code is working properly. When I push to my server it become error.

cURL error 6: Could not resolve host: http (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

Here is my code:

```<code>use GuzzleHttp\Client;

try {
    $client = new Client();
    $client->request('POST', env('API_DOMAIN') . '/v1/user/auth/verified_email',
        ['headers' => ['Authorization' => 'cm9vcGlhLnVzZXIud2ViOkY0RVN3VXJheS1qVVB1a18='],
         'query'   => ['token' => $key]]);

    return redirect('/')->with('status', 'Your email has been verified. Thanks!')->with('statusType', 'success');
} catch (ConnectException $e) {
    Log::error($e);
    return redirect('/');
}
</code>```

Any solution?

Thanks

答:
I spent a day to find that the best practice is to actually catch Exceptions in the following manner:

```<code>catch(\Exception $ex)
</code>```

That \ makes all the difference! so DO NOT use :

```<code>catch(Exception $ex)
</code>```

You can put this catch at the end where all other specific exceptions are caught.

Body:
On my development my code is working properly. When I push to my server it become error.

cURL error 6: Could not resolve host: http (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

Here is my code:

use GuzzleHttp\Client;

try {
    $client = new Client();
    $client->request('POST', env('API_DOMAIN') . '/v1/user/auth/verified_email',
        ['headers' => ['Authorization' => 'cm9vcGlhLnVzZXIud2ViOkY0RVN3VXJheS1qVVB1a18='],
         'query'   => ['token' => $key]]);

    return redirect('/')->with('status', 'Your email has been verified. Thanks!')->with('statusType', 'success');
} catch (ConnectException $e) {
    Log::error($e);
    return redirect('/');
}

Any solution?

Thanks

Body:
I spent a day to find that the best practice is to actually catch Exceptions in the following manner:

catch(\Exception $ex)

That \ makes all the difference! so DO NOT use :

catch(Exception $ex)

You can put this catch at the end where all other specific exceptions are caught.


问:
React-Redux container throws "mapStateToProps() in Connect(ModalRoot) must return a plain object. Instead received undefined."
I am building a Redux based Model/Dialog trigger based on Dan Abramov's solution to this question: Dan Abramov's solution

The error I am getting is "mapStateToProps() in Connect(ModalRoot) must return a plain object. Instead received undefined."

Here is the code for the modal container and the code that calls it:

```<code>// Code that calls the Modal Container

import React from 'react';
import { Provider } from 'react-redux';
import { Connector as HorizonConnector } from 'horizon-react';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

import routes from '../routes';
import store from '../store';
import horizon from '../db';
import ModalRoot from './Modal';

export default () => (
  <MuiThemeProvider muiTheme={getMuiTheme()}>
    <HorizonConnector horizon={horizon} store={store}>
      <div className="app">
        {routes}
        <ModalRoot />
      </div>
    </HorizonConnector>
  </MuiThemeProvider>
);
</code>```

```<code> // The Modal Container
 import LoginModal from '../components/Modals/LoginModal'
 import {connect} from 'react-redux'

const MODAL_COMPONENTS = {
  'LOGIN_MODAL': LoginModal
  /* other modals */
}

const ModalRoot = ({ modalType, modalProps }) => {
  if (!modalType) {
    return <span /> // after React v15 you can return null here
  }

  const SpecificModal = MODAL_COMPONENTS[modalType]
  return <SpecificModal {...modalProps} />
}

export default connect(
  state => state.modal
)(ModalRoot)
</code>```

Its probably something simple i'm forgetting but its driving me crazy, any comments or suggestions welcome.

答:
The root cause of the problem is that state.modal is undefined. You can get more info by adding a simple log statement like:

```<code>export default connect(state => { console.log('state', state); return state.modal })(ModalRoot)
</code>```

This may help you see what's in state and help in figuring out why state.modal is undefined.

To make this error go away, you can use either of these 2 solutions:

Ensuring the object is not undefined:

```<code>export default connect(state => state.modal || {})(ModalRoot)
</code>```

Using ES6 destructuring:

```<code>export default connect(({ modal }) => ({ modal }))(ModalRoot)
</code>```

If you use the ES6 destructuring (which is essentially same as @MichaelRasoahaingo's solution), your prop destructuring will also change to:

```<code>const ModalRoot = ({ modal: { modalType, modalProps } }) => {
</code>```

Or you can use this alternative syntax and keep your destructuring as is:

```<code>export default connect(({ modal }) => ({ ...modal }))(ModalRoot)
</code>```

Body:
I am building a Redux based Model/Dialog trigger based on Dan Abramov's solution to this question: Dan Abramov's solution

The error I am getting is "mapStateToProps() in Connect(ModalRoot) must return a plain object. Instead received undefined."

Here is the code for the modal container and the code that calls it:

// Code that calls the Modal Container

import React from 'react';
import { Provider } from 'react-redux';
import { Connector as HorizonConnector } from 'horizon-react';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

import routes from '../routes';
import store from '../store';
import horizon from '../db';
import ModalRoot from './Modal';

export default () => (
  <MuiThemeProvider muiTheme={getMuiTheme()}>
    <HorizonConnector horizon={horizon} store={store}>

        {routes}
        <ModalRoot />

    </HorizonConnector>
  </MuiThemeProvider>
);

 // The Modal Container
 import LoginModal from '../components/Modals/LoginModal'
 import {connect} from 'react-redux'

const MODAL_COMPONENTS = {
  'LOGIN_MODAL': LoginModal
  /* other modals */
}

const ModalRoot = ({ modalType, modalProps }) => {
  if (!modalType) {
    return  // after React v15 you can return null here
  }

  const SpecificModal = MODAL_COMPONENTS[modalType]
  return <SpecificModal {...modalProps} />
}

export default connect(
  state => state.modal
)(ModalRoot)

Its probably something simple i'm forgetting but its driving me crazy, any comments or suggestions welcome.

Body:
The root cause of the problem is that state.modal is undefined. You can get more info by adding a simple log statement like:

export default connect(state => { console.log('state', state); return state.modal })(ModalRoot)

This may help you see what's in state and help in figuring out why state.modal is undefined.

To make this error go away, you can use either of these 2 solutions:

Ensuring the object is not undefined:

export default connect(state => state.modal || {})(ModalRoot)

Using ES6 destructuring:

export default connect(({ modal }) => ({ modal }))(ModalRoot)

If you use the ES6 destructuring (which is essentially same as @MichaelRasoahaingo's solution), your prop destructuring will also change to:

const ModalRoot = ({ modal: { modalType, modalProps } }) => {

Or you can use this alternative syntax and keep your destructuring as is:

export default connect(({ modal }) => ({ ...modal }))(ModalRoot)


问:
changing maven cargo plugin deployment path
I want to have my integration test hit cargo's tomcat at http://localhost:8080/messaging but cargo (cargo-maven2-plugin:1.0.5) prefers to deploy my messaging project as /messaging-0.0.7-SNAPSHOT, as seen in the tomcat admin console and in the target\tomcat6x\webapps directory.

So I tried adding these lines to the cargo config, figuring that it will pick up the default artifact:

```<code> <deployer>
  <deployables>
   <deployable>
     <properties>
     <context>/messaging</context>
    </properties>
   </deployable>
  </deployables>
 </deployer>
</code>```

but it doesn't. It doesn't even attempt to since I don't see the messaging or messaging-0.0.7-SNAPSHOT in the target\tomcat6x\webapps directory.

The same thing happens when I set it up like so:

```<code><configuration>
  <type>standalone</type>
 <wait>false</wait>
 <properties>
  <cargo.servlet.port>8080</cargo.servlet.port>
  <cargo.logging>high</cargo.logging>
 </properties>
 <deployer>
  <deployables>
   <deployable>
     <groupId>com.company.platform</groupId>
     <artifactId>messaging</artifactId>
     <type>war</type>
     <properties>
     <context>/messaging</context>
    </properties>
   </deployable>
  </deployables>
 </deployer>
</configuration>
</code>```

Here's the full plugin config:

```<code>  <plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<executions>
 <execution>
  <id>start</id>
  <phase>pre-integration-test</phase>
  <goals>
   <goal>start</goal>
  </goals>
 </execution>
 <execution>
  <id>stop</id>
  <phase>post-integration-test</phase>
  <goals>
   <goal>stop</goal>
  </goals>
 </execution>
</executions>
<configuration>
  <type>standalone</type>
 <wait>false</wait>
 <properties>
  <cargo.servlet.port>8080</cargo.servlet.port>
  <cargo.logging>high</cargo.logging>
 </properties>
 <deployer>
  <deployables>
   <deployable>
     <properties>
     <context>/messaging</context>
    </properties>
   </deployable>
  </deployables>
 </deployer>
</configuration>
</code>```

My integration test looks like this:

```<code>import junit.framework.TestCase;

import java.io.InputStream;
import java.net.URL;
import java.net.HttpURLConnection;
import java.sql.Time;

public class WebappTest extends TestCase
{
    public void testCallIndexPage() throws Exception
    {
        URL url = new URL("http://localhost:8080/messaging/");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        assertEquals(200, connection.getResponseCode());
        InputStream is = connection.getInputStream();
        System.out.println(connection.getContent().getClass());

    }
}
</code>```

What's the best way to proceed? Knowing that it will successfully deploy as hxxp://localhost:8080/messaging-0.0.7-SNAPSHOT, I could alter the test, but what would be a quick way to pull the artifact version in?

Ideally, I'd like to have cargo deploy it correctly, but it is unclear how.

答:
From Cargo Plugin Reference,

```<code>About WAR contexts

    Many containers have their specific files for redefining context roots (Tomcat
has context.xml, JBoss has jboss-web.xml, etc.). If your WAR has such a file, the
server will most probably use the context root defined in that file instead of the
one you specify using the CARGO deployer.
</code>```

Could you be hitting this issue?

Also, I think context name should not have a leading /.

Body:
I want to have my integration test hit cargo's tomcat at http://localhost:8080/messaging but cargo (cargo-maven2-plugin:1.0.5) prefers to deploy my messaging project as /messaging-0.0.7-SNAPSHOT, as seen in the tomcat admin console and in the target\tomcat6x\webapps directory.

So I tried adding these lines to the cargo config, figuring that it will pick up the default artifact:

 <deployer>
  <deployables>
   <deployable>
     <properties>
     <context>/messaging</context>
    </properties>
   </deployable>
  </deployables>
 </deployer>

but it doesn't. It doesn't even attempt to since I don't see the messaging or messaging-0.0.7-SNAPSHOT in the target\tomcat6x\webapps directory.

The same thing happens when I set it up like so:

<configuration>
  <type>standalone</type>
 <wait>false</wait>
 <properties>
  <cargo.servlet.port>8080</cargo.servlet.port>
  <cargo.logging>high</cargo.logging>
 </properties>
 <deployer>
  <deployables>
   <deployable>
     <groupId>com.company.platform</groupId>
     <artifactId>messaging</artifactId>
     <type>war</type>
     <properties>
     <context>/messaging</context>
    </properties>
   </deployable>
  </deployables>
 </deployer>
</configuration>

Here's the full plugin config:

  <plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<executions>
 <execution>
  <id>start</id>
  <phase>pre-integration-test</phase>
  <goals>
   <goal>start</goal>
  </goals>
 </execution>
 <execution>
  <id>stop</id>
  <phase>post-integration-test</phase>
  <goals>
   <goal>stop</goal>
  </goals>
 </execution>
</executions>
<configuration>
  <type>standalone</type>
 <wait>false</wait>
 <properties>
  <cargo.servlet.port>8080</cargo.servlet.port>
  <cargo.logging>high</cargo.logging>
 </properties>
 <deployer>
  <deployables>
   <deployable>
     <properties>
     <context>/messaging</context>
    </properties>
   </deployable>
  </deployables>
 </deployer>
</configuration>

My integration test looks like this:

import junit.framework.TestCase;

import java.io.InputStream;
import java.net.URL;
import java.net.HttpURLConnection;
import java.sql.Time;

public class WebappTest extends TestCase
{
    public void testCallIndexPage() throws Exception
    {
        URL url = new URL("http://localhost:8080/messaging/");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        assertEquals(200, connection.getResponseCode());
        InputStream is = connection.getInputStream();
        System.out.println(connection.getContent().getClass());

    }
}

What's the best way to proceed? Knowing that it will successfully deploy as hxxp://localhost:8080/messaging-0.0.7-SNAPSHOT, I could alter the test, but what would be a quick way to pull the artifact version in?

Ideally, I'd like to have cargo deploy it correctly, but it is unclear how.

Body:
From Cargo Plugin Reference,

About WAR contexts

    Many containers have their specific files for redefining context roots (Tomcat
has context.xml, JBoss has jboss-web.xml, etc.). If your WAR has such a file, the
server will most probably use the context root defined in that file instead of the
one you specify using the CARGO deployer.

Could you be hitting this issue?

Also, I think context name should not have a leading /.


问:
mongoose nested arrays schema
I'm trying to create a schema for the following array:

```<code>const data = [ [ { name: 'AKA_A2',
      path: '/',
      expires: 1510762544.752427,
      size: 7 },
    { name: 'userInfo',
      path: '/',
      expires: 0,
      size: 82 },
    { name: 'userInfo',
      path: '/',
      expires: 0,
      size: 82 } ] ]
</code>```

This is the Schema that I've created:

```<code>import mongoose from 'mongoose';

const CookieSchema = mongoose.Schema(
  {
    name: String,
    path: String,
    expires: String,
    size: String
  }
)

const RunSchema = mongoose.Schema(
  {
    reports: {
      cookieSummary: [CookieSchema]
    }
  }
)

export default mongoose.model('Run', RunSchema);
</code>```

Then when I'm trying to update a document from this schema I get a null response and the document is not updated.

This is my code:

```<code>Run.findOneAndUpdate({_id: runId}, {$set: {'reports.cookieSummary': data}}, (err, doc) => {
  console.log(doc);
});
</code>```

My document looks like this:

```<code>{
    "_id": {
        "$oid": "5a0c5e86d4b737549e88d8cf"
    },
    "reports": {},
    "__v": 0
}
</code>```

答:
Try to Change your schema to</p>

```<code>const RunSchema = mongoose.Schema(
  {
     reports: {
        cookieSummary: [[CookieSchema]]
     }
  }
)
</code>```

Title: mongoose nested arrays schema

Body:
I'm trying to create a schema for the following array:

const data = [ [ { name: 'AKA_A2',
      path: '/',
      expires: 1510762544.752427,
      size: 7 },
    { name: 'userInfo',
      path: '/',
      expires: 0,
      size: 82 },
    { name: 'userInfo',
      path: '/',
      expires: 0,
      size: 82 } ] ]

This is the Schema that I've created:

import mongoose from 'mongoose';

const CookieSchema = mongoose.Schema(
  {
    name: String,
    path: String,
    expires: String,
    size: String
  }
)

const RunSchema = mongoose.Schema(
  {
    reports: {
      cookieSummary: [CookieSchema]
    }
  }
)

export default mongoose.model('Run', RunSchema);

Then when I'm trying to update a document from this schema I get a null response and the document is not updated.

This is my code:

Run.findOneAndUpdate({_id: runId}, {$set: {'reports.cookieSummary': data}}, (err, doc) => {
  console.log(doc);
});

My document looks like this:

{
    "_id": {
        "$oid": "5a0c5e86d4b737549e88d8cf"
    },
    "reports": {},
    "__v": 0
}

Body:
Try to Change your schema to

const RunSchema = mongoose.Schema(
  {
     reports: {
        cookieSummary: [[CookieSchema]]
     }
  }
)


问:
Insert elements in a BST
I get an error with this code, where i try insert elements of a list into a BST.

The error is tree-value: expects a tree, given 4 but i have no clue why this happens.

```<code>(define-struct tree (left right value))
(define example (make-tree
             (make-tree empty empty 3)
              (make-tree
               (make-tree 4 empty 7)
               (make-tree empty empty 10) 8)5))
(define app (list 1 2 3 4 6 11 12 13))

(define (insert tree val)
(cond [(empty? tree) (make-tree empty empty val)]
    [(= val (tree-value tree)) tree]
    [(< val (tree-value tree))
     (make-tree (insert (tree-left tree) val) (tree-right tree) (tree-value tree))]
    [(> val (tree-value tree))
     (make-tree  (tree-left tree) (insert (tree-right tree) val) (tree-value tree))]))

(define (insert-list tree lst)
(cond [(empty? lst) tree]
    [else (insert-list (insert tree (first lst)) (rest lst))]))

> (insert-list example app)
tree-value: expects a tree, given 4
>
</code>```

答: You can use DrRacket's stepper to help you understand this problem. Put the code above (along with the (insert-list example app) call) into the definitions window, make sure the language level is set to Beginner, and then click on the Step button. You can use the menu to jump to the last step of the failed evaluation, where you'll see a call to tree-value with 4. How did that happen? Use the step backward button to see the previous step, etc.

Title: Insert elements in a BST

Body:
I get an error with this code, where i try insert elements of a list into a BST.

The error is tree-value: expects a tree, given 4 but i have no clue why this happens.

(define-struct tree (left right value))
(define example (make-tree
             (make-tree empty empty 3)
              (make-tree
               (make-tree 4 empty 7)
               (make-tree empty empty 10) 8)5))
(define app (list 1 2 3 4 6 11 12 13))

(define (insert tree val)
(cond [(empty? tree) (make-tree empty empty val)]
    [(= val (tree-value tree)) tree]
    [(< val (tree-value tree))
     (make-tree (insert (tree-left tree) val) (tree-right tree) (tree-value tree))]
    [(> val (tree-value tree))
     (make-tree  (tree-left tree) (insert (tree-right tree) val) (tree-value tree))]))

(define (insert-list tree lst)
(cond [(empty? lst) tree]
    [else (insert-list (insert tree (first lst)) (rest lst))]))

> (insert-list example app)
tree-value: expects a tree, given 4
>


问:
Get Lat and Long from autocomplete address input and show the map below with google maps API
I have an input field for entering the location which supports location suggestion from google maps API. There are also two input fields for Latitude and Longitude. And the last there is a div for showing the map above input location. Whenever anyone start typing location and select a location from suggestion then automatically and map of the location will be shown in the below div. All should be real-time.

So far i have written the following-

```<code><input type="text" name="address1" id="address1" class="form-control" required="required" onkeyup="findAddress()" />
<input type="text" name="lattitude" id="cityLat" placeholder="Lattitude" class="form-control" required="required"/>
<input type="text" name="longitude" id="cityLng" placeholder="Longitude" class="form-control" required="required"/>

<div id="showMap"></div>
</code>```

And the javascript is

```<code>function findAddress() {

var input = document.getElementById('address1');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
            var place = autocomplete.getPlace();
            document.getElementById('cityLat').value = place.geometry.location.lat();
            document.getElementById('cityLng').value = place.geometry.location.lng();
}
</code>```

I have included the maps API

```<code><script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
</code>```

Searching suggestion is working but rest are not working.

答:
Find this piece of code in your script:

```<code>if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
}
</code>```

In this

"window.alert("Locaton: '" + place.geometry.location + "'");"

in  "if" condition add the following line it will alert/notify long and lat on option/address select:

Your code will look like this:

```<code>if (place.geometry.viewport) {
window.alert("Locaton: '" + place.geometry.location + "'"); //Add this line
map.fitBounds(place.geometry.viewport);
 }
</code>```

Body:
I have an input field for entering the location which supports location suggestion from google maps API. There are also two input fields for Latitude and Longitude. And the last there is a div for showing the map above input location. Whenever anyone start typing location and select a location from suggestion then automatically and map of the location will be shown in the below div. All should be real-time.

So far i have written the following-

<input type="text" name="address1" id="address1" class="form-control" required="required" onkeyup="findAddress()" />
<input type="text" name="lattitude" id="cityLat" placeholder="Lattitude" class="form-control" required="required"/>
<input type="text" name="longitude" id="cityLng" placeholder="Longitude" class="form-control" required="required"/>

And the javascript is

function findAddress() {

var input = document.getElementById('address1');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
            var place = autocomplete.getPlace();
            document.getElementById('cityLat').value = place.geometry.location.lat();
            document.getElementById('cityLng').value = place.geometry.location.lng();
}

I have included the maps API

Searching suggestion is working but rest are not working.

Body:
Find this piece of code in your script:

if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
}

In this

"window.alert("Locaton: '" + place.geometry.location + "'");"

in  "if" condition add the following line it will alert/notify long and lat on option/address select:

Your code will look like this:

if (place.geometry.viewport) {
window.alert("Locaton: '" + place.geometry.location + "'"); //Add this line
map.fitBounds(place.geometry.viewport);
 }


问:
"Session store not set on request." with Google 2fa
I used a tutorial for implementing Google's 2FA: https://www.sitepoint.com/2fa-in-laravel-with-google-authenticator-get-secure/

The ValidateSecretRequest class extends from App\Http\Requests; but I don't have this class in my "Requests"-folder. So I used use Illuminate\Http\Request;

But when I call this class in the Controller I get an error.

RuntimeException - Session store not set on request
…/vendor/laravel/framework/src/Illuminate/Http/Request.php 411

```<code>public function session()
    {
        if (! $this->hasSession()) {
            throw new RuntimeException('Session store not set on request.');
        }

        return $this->getSession();
    }
</code>```

Does anybody know how to handle?

答:
I had the same issue before but I fixed it by setting permissions of storage/* like:

```<code>chmown -R www-data storage/*
</code>```

If you're using files as session driver, it's probably because of these permissions issues.

Edit: It also works with database sessions

Body:
I used a tutorial for implementing Google's 2FA: https://www.sitepoint.com/2fa-in-laravel-with-google-authenticator-get-secure/

The ValidateSecretRequest class extends from App\Http\Requests; but I don't have this class in my "Requests"-folder. So I used use Illuminate\Http\Request;

But when I call this class in the Controller I get an error.

RuntimeException - Session store not set on request
…/vendor/laravel/framework/src/Illuminate/Http/Request.php 411

public function session()
    {
        if (! $this->hasSession()) {
            throw new RuntimeException('Session store not set on request.');
        }

        return $this->getSession();
    }

Does anybody know how to handle?

Body:
I had the same issue before but I fixed it by setting permissions of storage/* like:

chmown -R www-data storage/*

If you're using files as session driver, it's probably because of these permissions issues.

Edit: It also works with database sessions

ContentLicense: CC BY-SA 4.0


答:
I would suggest to use RestControllerAdvice annotated class (for example named GlobalExceptionHandler) for handling error case. You will need to change getDistanceById method to throw custom exception when distance is null. You will need to add a method to the GlobalExceptionHandler which will handle your custom exception. then you can change your code to the following:</p>

```<code>@PreAuthorize("hasAuthority('ROLE_USER')")
@GetMapping("distance/{id}")
public ResponseEntity<Distance> getDistanceById(@PathVariable("id") Integer id) {
    log.info("getDistanceById");
    return ResponseEntity.ok(distanceService.getDistanceById(id));
}
</code>```

Title: spring boot rest ResponseEntity responses

Body:
I would suggest to use RestControllerAdvice annotated class (for example named GlobalExceptionHandler) for handling error case. You will need to change getDistanceById method to throw custom exception when distance is null. You will need to add a method to the GlobalExceptionHandler which will handle your custom exception. then you can change your code to the following:

@PreAuthorize("hasAuthority('ROLE_USER')")
@GetMapping("distance/{id}")
public ResponseEntity<Distance> getDistanceById(@PathVariable("id") Integer id) {
    log.info("getDistanceById");
    return ResponseEntity.ok(distanceService.getDistanceById(id));
}


问:
Puppeteer Element Handle loses context when navigating
What I'm trying to do:

I'm trying to get a screenshot of every element example in my storybooks project. The way I'm trying to do this is by clicking on the element and then taking the screenshot, clicking on the next one, screenshot etc.

Here is the attached code:

```<code>test('no visual regression for button', async () => {
  const selector = 'a[href*="?selectedKind=Buttons&selectedStory="]';
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('http://localhost:8080');
  let examples = await page.$$(selector);
  await examples.map( async(example) => {
    await example.click();
    const screen = await page.screenshot();
    expect(screen).toMatchImageSnapshot();
  });
  await browser.close();
});
</code>```

But when I run this code I get the following error:

```<code>Protocol error (Runtime.callFunctionOn): Target closed.

  at Session._onClosed (../../node_modules/puppeteer/lib/Connection.js:209:23)
  at Connection._onClose (../../node_modules/puppeteer/lib/Connection.js:116:15)
  at Connection.dispose (../../node_modules/puppeteer/lib/Connection.js:121:10)
  at Browser.close (../../node_modules/puppeteer/lib/Browser.js:60:22)
  at Object.<anonymous>.test (__tests__/visual.spec.js:21:17)
      at <anonymous>
  at process._tickCallback (internal/process/next_tick.js:169:7)
</code>```

I believe it is because the element loses its context or something similar and I don't know what methods to use to get around this. Could you provide a deeper explanation or a possible solution? I don't find the API docs helpful at all.

答: ElementHandle.dispose() is called once page navigation occurs as garbage collection as stated here in the docs. So when you call element.click() it navigates and the rest of the elements no longer point to anything.

Body:
What I'm trying to do:

I'm trying to get a screenshot of every element example in my storybooks project. The way I'm trying to do this is by clicking on the element and then taking the screenshot, clicking on the next one, screenshot etc.

Here is the attached code:

test('no visual regression for button', async () => {
  const selector = 'a[href*="?selectedKind=Buttons&selectedStory="]';
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('http://localhost:8080');
  let examples = await page.$$(selector);
  await examples.map( async(example) => {
    await example.click();
    const screen = await page.screenshot();
    expect(screen).toMatchImageSnapshot();
  });
  await browser.close();
});

But when I run this code I get the following error:

Protocol error (Runtime.callFunctionOn): Target closed.

  at Session._onClosed (../../node_modules/puppeteer/lib/Connection.js:209:23)
  at Connection._onClose (../../node_modules/puppeteer/lib/Connection.js:116:15)
  at Connection.dispose (../../node_modules/puppeteer/lib/Connection.js:121:10)
  at Browser.close (../../node_modules/puppeteer/lib/Browser.js:60:22)
  at Object.<anonymous>.test (__tests__/visual.spec.js:21:17)
      at <anonymous>
  at process._tickCallback (internal/process/next_tick.js:169:7)

I believe it is because the element loses its context or something similar and I don't know what methods to use to get around this. Could you provide a deeper explanation or a possible solution? I don't find the API docs helpful at all.


问:
Eclipse: Errors occurred during the build. Errors running builder 'Java Builder'
I'm having an error while trying to make Eclipse Oxygen work in Kubuntu 16.04. Whenever I open a file, and sometimes on Eclipse startup too even if there's no open ones, I get many errors, in particular some I can't copy that occur when I try to use code completion, and most of all this one:

```<code>Errors occurred during the build.
Errors running builder 'Java Builder' on project 'MyFirstAfterReinstallAndPlugin'.
java.lang.NullPointerException
</code>```

I have to specify that this started to occur after I downloaded the extension for Java 9 support and created a new project with the Java_SE9 JRE: before that it would behave in another strange way. Code correction wouldn't find the "System" class and a lot of strange errors happened. I have installed openjdk9 and javac from command line works fine. Plus Eclipse said that I had to have Java 1.8 or superior, making the fact that it didn't work before strange as well.

I've tried everything I found online but still can't figure this out.

答:
I was also getting the following error.  To fix this I changed the Build class path order so that the JRE was listed last. (Project Properties>Java Build Path>Order and Export)

Errors running builder 'Java Builder'
java.lang.NullPointerException  on project X

Body:
I'm having an error while trying to make Eclipse Oxygen work in Kubuntu 16.04. Whenever I open a file, and sometimes on Eclipse startup too even if there's no open ones, I get many errors, in particular some I can't copy that occur when I try to use code completion, and most of all this one:

Errors occurred during the build.
Errors running builder 'Java Builder' on project 'MyFirstAfterReinstallAndPlugin'.
java.lang.NullPointerException

I have to specify that this started to occur after I downloaded the extension for Java 9 support and created a new project with the Java_SE9 JRE: before that it would behave in another strange way. Code correction wouldn't find the "System" class and a lot of strange errors happened. I have installed openjdk9 and javac from command line works fine. Plus Eclipse said that I had to have Java 1.8 or superior, making the fact that it didn't work before strange as well.

I've tried everything I found online but still can't figure this out.


问:
Angular 5 POST requests for my page
I'm receiving POST request to my Angular page, which might look like:

```<code>https://www.myangularsite.com/login
"POST /login HTTP/1.1
token: randomstring"
</code>```

My app module looks like

```<code>export const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: '', redirectTo: 'login', pathMatch: 'full' },
  { path: '**', redirectTo: 'login', pathMatch: 'full' }
];

@NgModule({
  declarations: [
    LoginComponent,
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    RouterModule.forRoot(routes, {errorHandler: errorLogger } )
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }
</code>```

My problem is that Angular application doesn't accept POST method requests, only GET.
Page displays

```<code>Cannot POST /login
</code>```

I'm running web server through ng serve. Is it possible to set it up to listen to POST requests? I can't change received request to GET.

Even though it is POST request, it is not a backend call. It is called after authorization (similar from oauth), therefore it should display page after login.

答:
```<code>You can use node.js Express as your CLI server. Please see the post at  http://tattoocoder.com/angular2-giving-your-cli-server/  on how to do that.
</code>```

Then in your express server.js, you can listen the post request for login:

```<code>var express        =         require("express");
var bodyParser     =         require("body-parser");
var app            =         express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/',function(req,res){
  res.sendfile("index.html");
});
app.post('/login',function(req,res){
  var user_name=req.body.user;
  var password=req.body.password;
  console.log("User name = "+user_name+", password is "+password);
  res.end("yes");
});
app.listen(3000,function(){
  console.log("Started on PORT 3000");
})
</code>```

Title: Angular 5 POST requests for my page

Body:
I'm receiving POST request to my Angular page, which might look like:

https://www.myangularsite.com/login
"POST /login HTTP/1.1
token: randomstring"

My app module looks like

export const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: '', redirectTo: 'login', pathMatch: 'full' },
  { path: '**', redirectTo: 'login', pathMatch: 'full' }
];

@NgModule({
  declarations: [
    LoginComponent,
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    RouterModule.forRoot(routes, {errorHandler: errorLogger } )
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

My problem is that Angular application doesn't accept POST method requests, only GET.
Page displays

Cannot POST /login

I'm running web server through ng serve. Is it possible to set it up to listen to POST requests? I can't change received request to GET.

Even though it is POST request, it is not a backend call. It is called after authorization (similar from oauth), therefore it should display page after login.

Body:
You can use node.js Express as your CLI server. Please see the post at  http://tattoocoder.com/angular2-giving-your-cli-server/  on how to do that.

Then in your express server.js, you can listen the post request for login:

var express        =         require("express");
var bodyParser     =         require("body-parser");
var app            =         express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/',function(req,res){
  res.sendfile("index.html");
});
app.post('/login',function(req,res){
  var user_name=req.body.user;
  var password=req.body.password;
  console.log("User name = "+user_name+", password is "+password);
  res.end("yes");
});
app.listen(3000,function(){
  console.log("Started on PORT 3000");
})


问:
Enabling query log in MySQL 5 on Windows 7
How do I do it? I want all queries logged, don't care about the performance hit. The docs say I need to start mysqld with -l but I can't change the parameters when editing this service.</p>

答: You can set the option in the my.cnf (possibly my.ini) file, wherever it happens to get installed on your machine. Command line arguments are more for a one-time override, while the my.cnf is for permanent settings.


问:
MySQL Error 1215: Cannot add foreign key constraint;
i have a task to creat a database about rail-way station.
got an error 1215. i have checked all similar parametres, they all match. however, the program doesn't work.
what is my mistake?
 please help.
this is my model part:

```<code>-- Table `mydb`.`WayOut`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`WayOut` (
  `WayOutNumberr` INT NOT NULL,
  UNIQUE INDEX `WayOutNumber_UNIQUE` (`WayOutNumberr` ASC),
  PRIMARY KEY (`WayOutNumberr`))
ENGINE = InnoDB;
</code>```

```<code>-- Table `mydb`.`TrainOut`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`TrainOut` (
  `NumberTrainOutRec` INT NOT NULL,
  `WayOutNumber` INT NOT NULL,
  `DateOut` VARCHAR(45) NOT NULL,
  `TrainNumber` INT NOT NULL,
  PRIMARY KEY (`NumberTrainOutRec`, `WayOutNumber`, `TrainNumber`),
  UNIQUE INDEX `WayOutNumber_UNIQUE` (`WayOutNumber` ASC),
  CONSTRAINT `WayOutNumber`
    FOREIGN KEY (`WayOutNumber`)
    REFERENCES `mydb`.`WayOut` (`WayOutNumberr`)
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB;
</code>```

here's a mistake code
what is a decision?(sorry for my english)

```<code>ERROR: Error 1215: Cannot add foreign key constraint
SQL Code:
        -- -----------------------------------------------------
        -- Table `mydb`.`TrainOut`
        -- -----------------------------------------------------
        CREATE TABLE IF NOT EXISTS `mydb`.`TrainOut` (
          `NumberTrainOutRec` INT NOT NULL,
          `WayOutNumber` INT NOT NULL,
          `DateOut` VARCHAR(45) NOT NULL,
          `TrainNumber` INT NOT NULL,
          PRIMARY KEY (`NumberTrainOutRec`, `WayOutNumber`, `TrainNumber`),
          UNIQUE INDEX `WayOutNumber_UNIQUE` (`WayOutNumber` ASC),
          CONSTRAINT `WayOutNumber`
            FOREIGN KEY (`WayOutNumber`)
            REFERENCES `mydb`.`WayOut` (`WayOutNumberr`)
            ON DELETE CASCADE
            ON UPDATE CASCADE)
        ENGINE = InnoDB

SQL script execution finished: statements: 9 succeeded, 1 failed

Fetching back view definitions in final form.
Nothing to fetch
</code>```

答:
Remove the database reference from CONSTRAINT. TrainOut is already created in mydb database.</p>

```<code>REFERENCES `WayOut` (`WayOutNumberr`)
</code>```

Body:
i have a task to creat a database about rail-way station.
got an error 1215. i have checked all similar parametres, they all match. however, the program doesn't work.
what is my mistake?
 please help.
this is my model part:

-- Table `mydb`.`WayOut`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`WayOut` (
  `WayOutNumberr` INT NOT NULL,
  UNIQUE INDEX `WayOutNumber_UNIQUE` (`WayOutNumberr` ASC),
  PRIMARY KEY (`WayOutNumberr`))
ENGINE = InnoDB;

-- Table `mydb`.`TrainOut`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`TrainOut` (
  `NumberTrainOutRec` INT NOT NULL,
  `WayOutNumber` INT NOT NULL,
  `DateOut` VARCHAR(45) NOT NULL,
  `TrainNumber` INT NOT NULL,
  PRIMARY KEY (`NumberTrainOutRec`, `WayOutNumber`, `TrainNumber`),
  UNIQUE INDEX `WayOutNumber_UNIQUE` (`WayOutNumber` ASC),
  CONSTRAINT `WayOutNumber`
    FOREIGN KEY (`WayOutNumber`)
    REFERENCES `mydb`.`WayOut` (`WayOutNumberr`)
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB;

here's a mistake code
what is a decision?(sorry for my english)

ERROR: Error 1215: Cannot add foreign key constraint
SQL Code:
        -- -----------------------------------------------------
        -- Table `mydb`.`TrainOut`
        -- -----------------------------------------------------
        CREATE TABLE IF NOT EXISTS `mydb`.`TrainOut` (
          `NumberTrainOutRec` INT NOT NULL,
          `WayOutNumber` INT NOT NULL,
          `DateOut` VARCHAR(45) NOT NULL,
          `TrainNumber` INT NOT NULL,
          PRIMARY KEY (`NumberTrainOutRec`, `WayOutNumber`, `TrainNumber`),
          UNIQUE INDEX `WayOutNumber_UNIQUE` (`WayOutNumber` ASC),
          CONSTRAINT `WayOutNumber`
            FOREIGN KEY (`WayOutNumber`)
            REFERENCES `mydb`.`WayOut` (`WayOutNumberr`)
            ON DELETE CASCADE
            ON UPDATE CASCADE)
        ENGINE = InnoDB

SQL script execution finished: statements: 9 succeeded, 1 failed

Fetching back view definitions in final form.
Nothing to fetch

Body:
Remove the database reference from CONSTRAINT. TrainOut is already created in mydb database.

REFERENCES `WayOut` (`WayOutNumberr`)


问:
Asp.net MVC Session timeout condition based handling
My MVC web application uses asp.net session management. Session has default timeout 20mins. On session timeout, user is redirected to the home page. My application uses SessionTimeout ActionFilterAttribute to handle session timeout.
SessionState is stored in server.

Problem:
Even if the session timout happens, when the user returns to a particular action method, I need to renew a session for that user and allow to continue instead of redirecting to home page.

I have tried to use the OnActionExecuting method in the SessionTimeout ActionFilterAttribute to identify the session timeout & if the action in the request is that particular action method, then allow the user to continue to that action.

But it seems to be not working. It just redirects the user to the Home page.
I am not sure how to proceed.

答:
Thanks for your responses.

"Session cannot be renewed" once it has expired.

Instead of renewing the session, create a new session in the ActionFilters Attribute (SessionTimeout).

The solution for my problem is to create a new session and re-link it with the domain object/user so that the user can continue his journey. I have done this in my SessionTimeout ActionFilterAttribute, to create new session for only a particular request which has the particular controller/action.


问:
Mocking Child Components - Angular 2
How do you mock a child component when testing? I have a parent component called product-selected whose template looks like this:

```<code><section id="selected-container" class="container-fluid">
    <hr/>
  <product-settings></product-settings>
  <product-editor></product-editor>
  <product-options></product-options>
</section>
</code>```

And the component declaration looks like this:

```<code>import { Component, Input }               from '@angular/core';

import { ProductSettingsComponent } from '../settings/product-settings.component';
import { ProductEditorComponent }   from '../editor/product-editor.component';
import { ProductOptionsComponent }  from '../options/product-options.component';

@Component({
    selector: 'product-selected',
    templateUrl: './product-selected.component.html',
    styleUrls: ['./product-selected.component.scss']
})
export class ProductSelectedComponent {}
</code>```

This component is really just a place for the other components to live in and probably won't contain any other functions.

But when I set up the testing I get the following template error, repeated for all three components:

```<code>Error: Template parse errors:
    'product-editor' is not a known element:
    1. If 'product-editor' is an Angular component, then verify that it is part of this module.
    2. If 'product-editor' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("
        <hr/>
      <product-settings></product-settings>
      [ERROR ->]<product-editor></product-editor>
</code>```

I've tried to load a mocked version of the child components but don't know how to do - the examples that I've seen just override the parent and don't even mention the child components. So how do I go about doing it?

答:
Found a nearly perfect solution, that will also correctly throw errors if someone refactors a component: https://www.npmjs.com/package/ng-mocks

npm install ng-mocks --save-dev
```
<p>Now in your .spec.ts you can do</p>
<pre class="lang-js prettyprint-override"><code>import { MockComponent } from 'ng-mocks';
import { ChildComponent } from './child.component.ts';
// ...
beforeEach(() => {
  TestBed.configureTestingModule({
    imports: [FormsModule, ReactiveFormsModule, RouterTestingModule],
    declarations: [
      ComponentUnderTest,
      MockComponent(ChildComponent), // <- here is the thing
      // ...
    ],
  });
});
</code>```

This creates a new anonymous Component that has the same selector,  @Input() and @Output() properties of the ChildComponent, but with no code attached.

Assume that your ChildComponent has a @Input() childValue: number, that is bound in your component under test, <app-child-component [childValue]="inputValue" />

Although it has been mocked, you can use By.directive(ChildComponent) in your tests, as well as By.css('app-child-component') like so

it('sets the right value on the child component', ()=> {
  component.inputValue=5;
  fixture.detectChanges();
  const element = fixture.debugElement.query(By.directive(ChildComponent));
  expect(element).toBeTruthy();

  const child: ChildComponent = element.componentInstance;
  expect(child.childValue).toBe(5);
});
```

Title: Mocking Child Components - Angular 2

Body:
How do you mock a child component when testing? I have a parent component called product-selected whose template looks like this:

  <product-settings></product-settings>
  <product-editor></product-editor>
  <product-options></product-options>

And the component declaration looks like this:

import { Component, Input }               from '@angular/core';

import { ProductSettingsComponent } from '../settings/product-settings.component';
import { ProductEditorComponent }   from '../editor/product-editor.component';
import { ProductOptionsComponent }  from '../options/product-options.component';

@Component({
    selector: 'product-selected',
    templateUrl: './product-selected.component.html',
    styleUrls: ['./product-selected.component.scss']
})
export class ProductSelectedComponent {}

This component is really just a place for the other components to live in and probably won't contain any other functions.

But when I set up the testing I get the following template error, repeated for all three components:

Error: Template parse errors:
    'product-editor' is not a known element:
    1. If 'product-editor' is an Angular component, then verify that it is part of this module.
    2. If 'product-editor' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("

      <product-settings></product-settings>
      [ERROR ->]<product-editor></product-editor>

I've tried to load a mocked version of the child components but don't know how to do - the examples that I've seen just override the parent and don't even mention the child components. So how do I go about doing it?

Body:
Found a nearly perfect solution, that will also correctly throw errors if someone refactors a component: https://www.npmjs.com/package/ng-mocks

npm install ng-mocks --save-dev

Now in your .spec.ts you can do

import { MockComponent } from 'ng-mocks';
import { ChildComponent } from './child.component.ts';
// ...
beforeEach(() => {
  TestBed.configureTestingModule({
    imports: [FormsModule, ReactiveFormsModule, RouterTestingModule],
    declarations: [
      ComponentUnderTest,
      MockComponent(ChildComponent), // <- here is the thing
      // ...
    ],
  });
});

This creates a new anonymous Component that has the same selector,  @Input() and @Output() properties of the ChildComponent, but with no code attached.

Assume that your ChildComponent has a @Input() childValue: number, that is bound in your component under test, <app-child-component [childValue]="inputValue" />

Although it has been mocked, you can use By.directive(ChildComponent) in your tests, as well as By.css('app-child-component') like so

it('sets the right value on the child component', ()=> {
  component.inputValue=5;
  fixture.detectChanges();
  const element = fixture.debugElement.query(By.directive(ChildComponent));
  expect(element).toBeTruthy();

  const child: ChildComponent = element.componentInstance;
  expect(child.childValue).toBe(5);
});


问:
How to debug an AlarmManager-activated service
I am implementing a widget that checks on-line train departure times between every minute and every hour, depending on the time of day.
Calling the service with

```<code> manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        SystemClock.elapsedRealtime() - 10000, 60000, pendingIntent)
</code>```

works fine, but for debugging I would like to reduce the interval to about 10 seconds which cannot be done because of the 1-minute limit in more recent versions of Android. Clearly, I don't care about battery life in the emulator.

As far as I understand, using an Hander/Timer is not an option, because it required the task to be in the foreground. Is a visible widget "in the forground"?
What is the recommended practice in this case?

答:
you actually have to tasks

configure the alarmmanager to add/remove trigger events via intents

interprete the events with intents in a service

If you seperate both you can easily create a very simple gui/activity that does the same as the alarmmanager would do when being triggerd and that you can debug:

```<code>* onSendButtonClick: create and send pendingIntent
</code>```

for the alarmmanager-handling i would implement logging into a text file each time alarmmanager is added/removed/triggered.

Be prepared that newer android versions may postpone alarmmanager events to save energy until the device is already active and that intervals less than 15 minutes may not work.

you may also need on_boot_complete to reconfigure alarmmanager after device-shutdown

Body:
I am implementing a widget that checks on-line train departure times between every minute and every hour, depending on the time of day.
Calling the service with

 manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        SystemClock.elapsedRealtime() - 10000, 60000, pendingIntent)

works fine, but for debugging I would like to reduce the interval to about 10 seconds which cannot be done because of the 1-minute limit in more recent versions of Android. Clearly, I don't care about battery life in the emulator.

As far as I understand, using an Hander/Timer is not an option, because it required the task to be in the foreground. Is a visible widget "in the forground"?
What is the recommended practice in this case?

Body:
you actually have to tasks

configure the alarmmanager to add/remove trigger events via intents

interprete the events with intents in a service

If you seperate both you can easily create a very simple gui/activity that does the same as the alarmmanager would do when being triggerd and that you can debug:

* onSendButtonClick: create and send pendingIntent

for the alarmmanager-handling i would implement logging into a text file each time alarmmanager is added/removed/triggered.

Be prepared that newer android versions may postpone alarmmanager events to save energy until the device is already active and that intervals less than 15 minutes may not work.

you may also need on_boot_complete to reconfigure alarmmanager after device-shutdown


问:
Application hangs on wait async method
I've got two combobox controls on my page, binded to a ObservableCollection<Vendor> and ObservableCollection<Driver>.

When the page is loaded the OnWindowLoaded() is executed.
When the setter of the property Vendor is triggered, OnVendorPropertyChanged is executed.
When OnWindowLoaded() finishes, Vendor and Driver is being set correctly.

However when I change the Vendor, the application waits on the line

```<code>LoadDriversAsync(Vendor.DCP).Wait();
</code>```

How can I fix this?

```<code>    private async void OnWindowLoaded()
    {
        Debug.WriteLine("Enter OnWindowLoaded");
        await LoadVendorsAsync();
        await System.Threading.Tasks.Task.Run(() => { Vendor = Vendors.FirstOrDefault(); });
        await System.Threading.Tasks.Task.Run(() => { Driver = Drivers.FirstOrDefault(); });
        Debug.WriteLine("Leave OnWindowLoaded");
    }

     private Vendor _vendor;
     public Vendor Vendor
    {
        get
        {
            return _vendor;
        }

        set
        {
            if (value != _vendor)
            {
                var oldVendor = new Vendor();
                oldVendor = _vendor;
                _vendor = value;
                RaisePropertyChanged(nameof(Vendor), oldVendor, Vendor, true);
            }
        }
    }

    /// <summary>
    /// Raised when Vendor property is changed
    /// </summary>
    /// <param name="vendor"></param>
    private void OnVendorPropertyChanged(PropertyChangedMessage<Vendor> vendor)
    {
         Debug.WriteLine("Enter OnVendorPropertyChanged");

            //application hangs when vendor is changed
            LoadDriversAsync(Vendor.DCP).Wait();
            Debug.WriteLine("Leave OnVendorPropertyChanged");
    }

    private async System.Threading.Tasks.Task LoadVendorsAsync()
    {
            Debug.WriteLine("Enter LoadVendorsAsync");
            //load the vendors, don't return data
            Debug.WriteLine("Leave LoadVendorsAsync");

    }

      private Vendor _vendor;
    public Vendor Vendor
    {
        get
        {
            return _vendor;
        }

        set
        {
            if (value != _vendor)
            {
                var oldVendor = new Vendor();
                oldVendor = _vendor;
                _vendor = value;
                RaisePropertyChanged(nameof(Vendor), oldVendor, Vendor, true);
            }
        }
    }

   ObservableCollection<Vendor> _vendors = new ObservableCollection<Vendor>();
    public ObservableCollection<Vendor> Vendors
    {
        get
        {
            return _vendors;
        }

        set
        {
            if (_vendors != value)
            {
                var oldVendors = _vendors;
                _vendors = value;
                RaisePropertyChanged(nameof(Vendors), oldVendors, Vendors, true);
            }

        }
    }

private async System.Threading.Tasks.Tas LoadDriversAsync(Objects.Vendor Vendor)
    {

            Debug.WriteLine("Enter LoadDriversAsync");
//load data, don't return

            Debug.WriteLine("Leave LoadDriversAsync");
            RaisePropertyChanged(nameof(Drivers), oldDrivers, Drivers, true);
        }

    }
</code>```

Output

```<code>Enter OnWindowLoaded
Enter LoadVendorsAsync
Leave LoadVendorsAsync
Enter OnVendorPropertyChanged
Enter LoadDriversAsync
Leave LoadDriversAsync
Leave OnVendorPropertyChanged
Leave OnWindowLoaded
</code>```

Edited

Following Boo advice did not help. Application still blocks when changing vendor.

Following @Frederik Gheysels advice did not help.

Output

```<code>Enter OnWindowLoaded
Enter LoadVendorsAsync
Enter OnVendorPropertyChanged
Enter LoadDriversAsync
Leave OnWindowLoaded
Leave LoadDriversAsync
Leave OnVendorPropertyChanged
</code>```

答:
You will almost never want to call wait when you have async methods.

Here is an example how deadlock can happen

async method called

async method enters wait and main thread runs something else

main thread executes a method calling wait()

wait is waiting for async to finish

async is waiting for main thread to become free

DEAD LOCK

so if it is possible, change the method where you are calling .wait() on to be async and call await on it

Title: Application hangs on wait async method

Body:
I've got two combobox controls on my page, binded to a ObservableCollection<Vendor> and ObservableCollection<Driver>.

When the page is loaded the OnWindowLoaded() is executed.
When the setter of the property Vendor is triggered, OnVendorPropertyChanged is executed.
When OnWindowLoaded() finishes, Vendor and Driver is being set correctly.

However when I change the Vendor, the application waits on the line

LoadDriversAsync(Vendor.DCP).Wait();

How can I fix this?

    private async void OnWindowLoaded()
    {
        Debug.WriteLine("Enter OnWindowLoaded");
        await LoadVendorsAsync();
        await System.Threading.Tasks.Task.Run(() => { Vendor = Vendors.FirstOrDefault(); });
        await System.Threading.Tasks.Task.Run(() => { Driver = Drivers.FirstOrDefault(); });
        Debug.WriteLine("Leave OnWindowLoaded");
    }

     private Vendor _vendor;
     public Vendor Vendor
    {
        get
        {
            return _vendor;
        }

        set
        {
            if (value != _vendor)
            {
                var oldVendor = new Vendor();
                oldVendor = _vendor;
                _vendor = value;
                RaisePropertyChanged(nameof(Vendor), oldVendor, Vendor, true);
            }
        }
    }

    ///
    /// Raised when Vendor property is changed
    ///
    /// <param name="vendor"></param>
    private void OnVendorPropertyChanged(PropertyChangedMessage<Vendor> vendor)
    {
         Debug.WriteLine("Enter OnVendorPropertyChanged");

            //application hangs when vendor is changed
            LoadDriversAsync(Vendor.DCP).Wait();
            Debug.WriteLine("Leave OnVendorPropertyChanged");
    }

    private async System.Threading.Tasks.Task LoadVendorsAsync()
    {
            Debug.WriteLine("Enter LoadVendorsAsync");
            //load the vendors, don't return data
            Debug.WriteLine("Leave LoadVendorsAsync");

    }

      private Vendor _vendor;
    public Vendor Vendor
    {
        get
        {
            return _vendor;
        }

        set
        {
            if (value != _vendor)
            {
                var oldVendor = new Vendor();
                oldVendor = _vendor;
                _vendor = value;
                RaisePropertyChanged(nameof(Vendor), oldVendor, Vendor, true);
            }
        }
    }

   ObservableCollection<Vendor> _vendors = new ObservableCollection<Vendor>();
    public ObservableCollection<Vendor> Vendors
    {
        get
        {
            return _vendors;
        }

        set
        {
            if (_vendors != value)
            {
                var oldVendors = _vendors;
                _vendors = value;
                RaisePropertyChanged(nameof(Vendors), oldVendors, Vendors, true);
            }

        }
    }

private async System.Threading.Tasks.Tas LoadDriversAsync(Objects.Vendor Vendor)
    {

            Debug.WriteLine("Enter LoadDriversAsync");
//load data, don't return

            Debug.WriteLine("Leave LoadDriversAsync");
            RaisePropertyChanged(nameof(Drivers), oldDrivers, Drivers, true);
        }

    }

Output

Enter OnWindowLoaded
Enter LoadVendorsAsync
Leave LoadVendorsAsync
Enter OnVendorPropertyChanged
Enter LoadDriversAsync
Leave LoadDriversAsync
Leave OnVendorPropertyChanged
Leave OnWindowLoaded

Edited

Following Boo advice did not help. Application still blocks when changing vendor.

Following @Frederik Gheysels advice did not help.

Output

Enter OnWindowLoaded
Enter LoadVendorsAsync
Enter OnVendorPropertyChanged
Enter LoadDriversAsync
Leave OnWindowLoaded
Leave LoadDriversAsync
Leave OnVendorPropertyChanged


问:
Cannot assign through subscript: 'dict' is a 'let' constant
I have a very simple problem with Swift.
I created this function:

```<code>var dictAges : [String: Int] = ["John":40, "Michael":20, "Bob": -16]

func correctAges(dict:[String:Int]) {
     for (name, age) in dict {
          guard age >= 0 else {
          dict[name] = 0
          continue
          }
     }
}
correctAges(dict:dictAges)
</code>```

But I don't understand the error:

"cannot assign through subscript: 'dict' is a 'let' constant, dict[name] = 0"

How can I solve it?

答:
In general, it's not good to mutate a sequence as you're looping through it, which is why you only get an immutable copy of the dictionary in your code.

Swift 4

I think a nicer approach could be to use map, and to take a more functional approach:

```<code>var dictAges : [String: Int] = ["John":40, "Michael":20, "Bob": -16]

func correctAges(dict:[String:Int]) -> [String:Int]
{
    let corrected = dict.map { (name, age) in age > 0 ? (name, age) : (name, 0) }
    return Dictionary(uniqueKeysWithValues: corrected)
}

dictAges = correctAges(dict: dictAges)
print(dictAges) // ["Michael": 20, "Bob": 0, "John": 40]
</code>```

This way you can reuse this method for any [String:Int] dictionary.

Body:
I have a very simple problem with Swift.
I created this function:

var dictAges : [String: Int] = ["John":40, "Michael":20, "Bob": -16]

func correctAges(dict:[String:Int]) {
     for (name, age) in dict {
          guard age >= 0 else {
          dict[name] = 0
          continue
          }
     }
}
correctAges(dict:dictAges)

But I don't understand the error:

"cannot assign through subscript: 'dict' is a 'let' constant, dict[name] = 0"

How can I solve it?

Body:
In general, it's not good to mutate a sequence as you're looping through it, which is why you only get an immutable copy of the dictionary in your code.

Swift 4

I think a nicer approach could be to use map, and to take a more functional approach:

var dictAges : [String: Int] = ["John":40, "Michael":20, "Bob": -16]

func correctAges(dict:[String:Int]) -> [String:Int]
{
    let corrected = dict.map { (name, age) in age > 0 ? (name, age) : (name, 0) }
    return Dictionary(uniqueKeysWithValues: corrected)
}

dictAges = correctAges(dict: dictAges)
print(dictAges) // ["Michael": 20, "Bob": 0, "John": 40]

This way you can reuse this method for any [String:Int] dictionary.