问:
How to use multiple connections one by module in Laravel
I'm creating an application in Laravel where each one will have its database, is it possible for each module to receive its connection file instead of leaving everything inside the config/database?</p>

答:
When you say module what do you mean by that?

Laravel supports multiple db connections, and in each Eloquent model you can add property $connection to specify which database connection to use for a specific model.

```<code>class MyClass extends Eloquent {

    protected $connection = 'myConnectionName';
    ...
}
</code>```

make sure that all models that are in relations are within the same database though.
Add defintion of myConnectionName in config/database.php

Body:
When you say module what do you mean by that?

Laravel supports multiple db connections, and in each Eloquent model you can add property $connection to specify which database connection to use for a specific model.

class MyClass extends Eloquent {

    protected $connection = 'myConnectionName';
    ...
}

make sure that all models that are in relations are within the same database though.
Add defintion of myConnectionName in config/database.php


来源: stackexchange

问:
Limit number of results in object.map
I'm importing the spaces object. I only want to render 3 of the Card components which requires attributes from spaces. Imagine a 'featured' section on a website displaying only a few items from a larger list.

With the below code I'm currently rendering all of the results instead of 3, am I using the correct methods? And if so, is the order wrong?

```<code><div className="row">

          {spaces.map(item => {

            for (var i = 0; i < 2; i++) {

              return (

                <div className="col-sm-12 col-md-6 col-lg-4" key={item.id}>

                  <Card
                    town={item.town}
                    name={item.name}
                    net={item.net}
                    day={item.day}
                    night={item.night}
                    dog={item.dog}
                    parking={item.parking}
                    image={item.image}
                  />

                </div>
              )
            }

          })}

</div>
</code>```

答:
You can do like below

          {spaces.map((item,index) => {

              if(index < 3){
              return (

                  <Card
                    town={item.town}
                    name={item.name}
                    net={item.net}
                    day={item.day}
                    night={item.night}
                    dog={item.dog}
                    parking={item.parking}
                    image={item.image}
                  />

              )
            }

          })}

```

ContentLicense: CC BY-SA 4.0

Title: Limit number of results in object.map

Body:
I'm importing the spaces object. I only want to render 3 of the Card components which requires attributes from spaces. Imagine a 'featured' section on a website displaying only a few items from a larger list.

With the below code I'm currently rendering all of the results instead of 3, am I using the correct methods? And if so, is the order wrong?

          {spaces.map(item => {

            for (var i = 0; i < 2; i++) {

              return (

                  <Card
                    town={item.town}
                    name={item.name}
                    net={item.net}
                    day={item.day}
                    night={item.night}
                    dog={item.dog}
                    parking={item.parking}
                    image={item.image}
                  />

              )
            }

          })}

Body:
You can do like below

<div className="row">

          {spaces.map((item,index) => {

              if(index < 3){
              return (

                <div className="col-sm-12 col-md-6 col-lg-4" key={item.id}>

                  <Card
                    town={item.town}
                    name={item.name}
                    net={item.net}
                    day={item.day}
                    night={item.night}
                    dog={item.dog}
                    parking={item.parking}
                    image={item.image}
                  />

                </div>
              )
            }

          })}

</div>


问:
Make a get request to download a pdf from url-to-pdf-api
Hi Guys I need your help.

I need to save a screenshot or a pdf from a website

I am relatively new on this, I don't know if I can use this url-to-pdf-api to make a get request to download or save the file on a DataBase, I am using Javascript/Vue and Python and I don't know how to do it

I'm trying to do this

```<code>this.$http.get('https://url-to-pdf-api.herokuapp.com/api/render?url=http://google.com').then(function(response) {
        console.log(response)
    }, function(response) {
        alert("error")
    });
</code>```

But after that, I don't know what to do

Thanks!

答:
You can use the following code to store the text in a file like so:

```<code>f = open("yourFileName.txt", "a")
f.write("Insert text here")
f.close()
</code>```

And i recommend you to use fpdf to save and edit pdf files

Body:
Hi Guys I need your help.

I need to save a screenshot or a pdf from a website

I am relatively new on this, I don't know if I can use this url-to-pdf-api to make a get request to download or save the file on a DataBase, I am using Javascript/Vue and Python and I don't know how to do it

I'm trying to do this

this.$http.get('https://url-to-pdf-api.herokuapp.com/api/render?url=http://google.com').then(function(response) {
        console.log(response)
    }, function(response) {
        alert("error")
    });

But after that, I don't know what to do

Thanks!

Body:
You can use the following code to store the text in a file like so:

f = open("yourFileName.txt", "a")
f.write("Insert text here")
f.close()

And i recommend you to use fpdf to save and edit pdf files


问:
compareTo() function in Java
I have written the code below

```<code>import java.util.*;
class compare{
    public static void main(String []args){
        String s1="java";
        String s2="javaProgramming";
        System.out.println(s1.compareTo(s2));
    }
}
</code>```

The output for this code is -11. Since there is no character for termination of string in java, which character in "java" is being compared with 'P' in "javaProgramming"?

答: As can be seen in the source code, the comparison stops when the minimum of the lengths of each string is reached. If all characters are equal through that point, then the difference in lengths is returned. </p>

Title: compareTo() function in Java

Body:
I have written the code below

import java.util.*;
class compare{
    public static void main(String []args){
        String s1="java";
        String s2="javaProgramming";
        System.out.println(s1.compareTo(s2));
    }
}

The output for this code is -11. Since there is no character for termination of string in java, which character in "java" is being compared with 'P' in "javaProgramming"?


问:
where did the 5th element of the array go after adding the 'a' and 'y' characters, and why isn't the character assigned instead of the nul terminator?
After adding characters, the array must contain 6 characters "roaday" but the for loop is executed 7 times and when if (p [i] == '\ 0') {p [i] = 'b';} the character b will not be assigned instead of the nul terminator .

how can I assign a character instead of a nul terminator  and why instead of 6 characters there are 7 characters???

```<code>#include <iostream>

using namespace std;

void main()
{
    char x[100];

    cin >>x; // cin >> "road"

    char* p;
    p = x;

    for (int i = 0; i < 100; i++)
    {
        if (p[i] == '\0')
        {
/*
no character is assigned to nul terminator
*/
 /* this line */    p[i] = p[0];
          p[i++] = 'a';
          p[i++] = 'y';
          p[i++] = '\0';

          cout << endl << p << endl;
          break;
        }
    }

    cout << p;
  }
</code>```

答:
when if (p [i] == '\ 0') {p [i] = 'b';} the character b will not be assigned instead of the nul terminator

This alone would work but in your code you are overwriting this assignment with the next line because you are probably misunderstanding the function of i++

You are entering the if-statement when i==4 which leads to:

```<code>p[4] = p[0] // overwrite '\0' with 'r'
p[4] = 'a'; // i is increased afterwards so you overwrite 'r' again
p[5] = 'y';
p[6] = '\0';
// i equals 7 now
</code>```

So for overwriting the '\0' with the first character and then append 'a' and 'y' you could just change p[i] = p[0] to p[i++] = p[0] to not replace this position twice.

Body:
After adding characters, the array must contain 6 characters "roaday" but the for loop is executed 7 times and when if (p [i] == '\ 0') {p [i] = 'b';} the character b will not be assigned instead of the nul terminator .

how can I assign a character instead of a nul terminator  and why instead of 6 characters there are 7 characters???

#include <iostream>

using namespace std;

void main()
{
    char x[100];

    cin >>x; // cin >> "road"

    char* p;
    p = x;

    for (int i = 0; i < 100; i++)
    {
        if (p[i] == '\0')
        {
/*
no character is assigned to nul terminator
*/
 /* this line */    p[i] = p[0];
          p[i++] = 'a';
          p[i++] = 'y';
          p[i++] = '\0';

          cout << endl << p << endl;
          break;
        }
    }

    cout << p;
  }

Body:
when if (p [i] == '\ 0') {p [i] = 'b';} the character b will not be assigned instead of the nul terminator

This alone would work but in your code you are overwriting this assignment with the next line because you are probably misunderstanding the function of i++

You are entering the if-statement when i==4 which leads to:

p[4] = p[0] // overwrite '\0' with 'r'
p[4] = 'a'; // i is increased afterwards so you overwrite 'r' again
p[5] = 'y';
p[6] = '\0';
// i equals 7 now

So for overwriting the '\0' with the first character and then append 'a' and 'y' you could just change p[i] = p[0] to p[i++] = p[0] to not replace this position twice.


问:
vert.x testing with TestNg
i am new to vert.x , i am trying to make unit testing by calling my webservices .
i need an example of testing webservices with testng.

when i did it with junit5 it works fine with the below code

```<code>@BeforeMethod
private static void deploy_verticle(Vertx vertx , VertxTestContext testContext) {
    vertx.deployVerticle(new MainVerticle(), testContext.completing());
}

@Test
public void getTestFalse(Vertx vertx , VertxTestContext testContext) throws InterruptedException {
    Assert.assertTrue("3".contains("tesdfsdf"));

    req = new HttpRequestEntityTest();
    req.setHost("localhost");
    req.setPort(8089);
    req.setUri("/api/data");
    utilTest = new RestUtilTest();
    response = new HttpResponseEntityTest();
    utilTest.getTestUtil(req, testContext.succeeding(response -> {
        testContext.verify(() -> {
            Assert.assertTrue(response.getBodyStr().contains("tesdfsdf"));

        });
        testContext.completeNow();

    }));
}

@AfterMethod
public void finish(Vertx vertx , VertxTestContext testContext) {

context.getVertx().close(context.getTestContext().succeeding(response -> {
    context.getTestContext().completeNow();
}));
}
</code>```

but when i try to work with TestNg like this :

```<code>@SuppressWarnings("deprecation")
    @Test
    public void getTestIqvia() throws InterruptedException {
        Future<HttpResponseEntityTest> future = Future.future();
        response = new HttpResponseEntityTest();
        req = new HttpRequestEntityTest();
        req.setHost("localhost");
        req.setPort(8089);
        req.setUri("/api/data");
        utilTest = new RestUtilTest();

        utilTest.getTestUtil(req, response -> {
            System.out.println(response.result().getBodyStr());

            System.out.println(response.result().getBodyStr().contains("dsds"));
            Assert.assertTrue(response.result().getBodyStr().contains("fdsfds"));

        });
</code>```

GetTestUtil Function :

```<code>public Future<HttpResponseEntityTest> getTestUtil(HttpRequestEntityTest req,
        Handler<AsyncResult<HttpResponseEntityTest>> resultHandler) {
    future = Future.future();

    WebClient client = WebClient.create(vertx);
    response = new HttpResponseEntityTest();
    client.get(req.getPort(), req.getHost(), req.getUri()).send(ar -> {
        if (ar.succeeded()) {

            response.setStatusCode(ar.result().statusCode());
            response.setBodyStr(ar.result().bodyAsString());
            future.complete(response);
            System.out.println("Received response with status code get" + response.getStatusCode());
            resultHandler.handle(Future.succeededFuture(response));

        } else {
            response.setErrorMsg(ar.cause().getMessage());
            System.out.println("Something went wrong " + ar.cause().getMessage());
            future.complete(response);

        }

    });

    return future;

}
</code>```

always sending to web client not entered in the arrow function ar and always test success because it doesn't go to Assert function . except fewtimes in debugging mode only

can any one has ana example in testNG with Vert.x?? or what's wrong in my code?

答:
This happens because the getTestIqvia completes before the WebClient callback is invoked.

With jUnit5, the corresponding Vert.x test extension makes sure the test is not marked as passed until all the asynchronous assertions pass.

With TestNG you need to do this manually. In practice, you need to make the test wait until the future returned by getTestUtil is completed.

Title: vert.x testing with TestNg

Body:
i am new to vert.x , i am trying to make unit testing by calling my webservices .
i need an example of testing webservices with testng.

when i did it with junit5 it works fine with the below code

@BeforeMethod
private static void deploy_verticle(Vertx vertx , VertxTestContext testContext) {
    vertx.deployVerticle(new MainVerticle(), testContext.completing());
}

@Test
public void getTestFalse(Vertx vertx , VertxTestContext testContext) throws InterruptedException {
    Assert.assertTrue("3".contains("tesdfsdf"));

    req = new HttpRequestEntityTest();
    req.setHost("localhost");
    req.setPort(8089);
    req.setUri("/api/data");
    utilTest = new RestUtilTest();
    response = new HttpResponseEntityTest();
    utilTest.getTestUtil(req, testContext.succeeding(response -> {
        testContext.verify(() -> {
            Assert.assertTrue(response.getBodyStr().contains("tesdfsdf"));

        });
        testContext.completeNow();

    }));
}

@AfterMethod
public void finish(Vertx vertx , VertxTestContext testContext) {

context.getVertx().close(context.getTestContext().succeeding(response -> {
    context.getTestContext().completeNow();
}));
}

but when i try to work with TestNg like this :

@SuppressWarnings("deprecation")
    @Test
    public void getTestIqvia() throws InterruptedException {
        Future<HttpResponseEntityTest> future = Future.future();
        response = new HttpResponseEntityTest();
        req = new HttpRequestEntityTest();
        req.setHost("localhost");
        req.setPort(8089);
        req.setUri("/api/data");
        utilTest = new RestUtilTest();

        utilTest.getTestUtil(req, response -> {
            System.out.println(response.result().getBodyStr());

            System.out.println(response.result().getBodyStr().contains("dsds"));
            Assert.assertTrue(response.result().getBodyStr().contains("fdsfds"));

        });

GetTestUtil Function :

public Future<HttpResponseEntityTest> getTestUtil(HttpRequestEntityTest req,
        Handler<AsyncResult<HttpResponseEntityTest>> resultHandler) {
    future = Future.future();

    WebClient client = WebClient.create(vertx);
    response = new HttpResponseEntityTest();
    client.get(req.getPort(), req.getHost(), req.getUri()).send(ar -> {
        if (ar.succeeded()) {

            response.setStatusCode(ar.result().statusCode());
            response.setBodyStr(ar.result().bodyAsString());
            future.complete(response);
            System.out.println("Received response with status code get" + response.getStatusCode());
            resultHandler.handle(Future.succeededFuture(response));

        } else {
            response.setErrorMsg(ar.cause().getMessage());
            System.out.println("Something went wrong " + ar.cause().getMessage());
            future.complete(response);

        }

    });

    return future;

}

always sending to web client not entered in the arrow function ar and always test success because it doesn't go to Assert function . except fewtimes in debugging mode only

can any one has ana example in testNG with Vert.x?? or what's wrong in my code?


问:
R round() rules for .5
Does rounding rules for .5 applies also for .05, .005 etc? I couldn't figure out why rounding for 45.445 and 73.445 differ.</p>

```<code>> round(45.445,2)
[1] 45.45
> round(73.445,2)
[1] 73.44
</code>```

Title: R round() rules for .5

Body:
Does rounding rules for .5 applies also for .05, .005 etc? I couldn't figure out why rounding for 45.445 and 73.445 differ.

> round(45.445,2)
[1] 45.45
> round(73.445,2)
[1] 73.44

Body:
The double numbers are not represented exactly and round uses the represented number.

sprintf("%.20f", 45.445)
#[1] "45.44500000000000028422"
sprintf("%.20f", 73.445)
#[1] "73.44499999999999317879"


问:
Prevent enter key on html input field react.js
I have a input field where when the user types in something, a list of options shows up underneath and the user will click on one of the options. The user can also press the Enter key as well. However, if the user were to enter something that is not in the dropdown that pops up and presses enter, my app crashes. I'm wondering if there is a way where I can disable the enter key on the input field so that when someone tries to press it, it just won't do anything.

Note that is in React as well!

Any help would be appreciated!

Thanks!

答:
You can use onKeyDown event of the input field. You can call some method like below,

```<code>const onKeyDown = (event) => {
    if (event.keyCode === 13) { //13 is the key code for Enter
      event.preventDefault()
      //Here you can even write the logic to select the value from the drop down or something.
    }
</code>```

Body:
You can use onKeyDown event of the input field. You can call some method like below,

const onKeyDown = (event) => {
    if (event.keyCode === 13) { //13 is the key code for Enter
      event.preventDefault()
      //Here you can even write the logic to select the value from the drop down or something.
    }


问:
Search multiple Elements with XPATH having unknown namespace prefix EXCEL VBA
I am loading different XML files that contain different xmlns namespaces having specific prefixes e.g. x,i,s,dt,xx etc. that change with different XML files. I am searching for multiple Element nodes e.g., AttributeType that may be prefixed with the namespace prefix.

My question is, how do i select the multiple nodes using VBA without knowing the xmlns Namespace prefix (e.g. whether it will be s or xx) that may be prefixed to the node?

Example:

```<code><xml
xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
xmlns:rs="urn:schemas-microsoft-com:rowset"
xmlns:z="#RowsetSchema">
    <s:Schema id="RowsetSchema">
        <s:ElementType name="row" content="eltOnly" rs:updatable="true">
            <s:AttributeType name="F1" rs:number="1" rs:nullable="true" rs:maydefer="true" rs:writeunknown="true" rs:basetable="abc$" rs:basecolumn="F1">
                <s:datatype dt:type="string" dt:maxLength="255"/>
            </s:AttributeType>
            <s:AttributeType name="F2" rs:number="1" rs:nullable="true" rs:maydefer="true" rs:writeunknown="true" rs:basetable="abc$" rs:basecolumn="F2">
                <s:datatype dt:type="string" dt:maxLength="255"/>
            </s:AttributeType>
....
        </s:AttributeType>
        <s:extends type="rs:rowbase"/>
    </s:ElementType>
</s:Schema>
<rs:data>
    <z:row F2="F2" F4="F4" F5="F5"/>
    <z:row F1="1.3" F2="2.3" F5="1.1"/>
    <z:row F1="3.4" F3="2.8" F4="5.3"/>
....
</xml>
</code>```

Another example:

```<code><xml
xmlns:xx="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
xmlns:rs="urn:schemas-microsoft-com:rowset"
xmlns:z="#RowsetSchema">
    <xx:Schema id="RowsetSchema">
        <xx:ElementType name="row" content="eltOnly" rs:updatable="true">
            <xx:AttributeType name="F1" rs:number="1" rs:nullable="true" rs:maydefer="true" rs:writeunknown="true" rs:basetable="abc$" rs:basecolumn="F1">
                <xx:datatype dt:type="string" dt:maxLength="255"/>
            </xx:AttributeType>
            <xx:AttributeType name="F2" rs:number="1" rs:nullable="true" rs:maydefer="true" rs:writeunknown="true" rs:basetable="abc$" rs:basecolumn="F2">
                <xx:datatype dt:type="string" dt:maxLength="255"/>
            </xx:AttributeType>
....
        </s:AttributeType>
        <s:extends type="rs:rowbase"/>
    </s:ElementType>
</s:Schema>
<rs:data>
    <z:row F2="F2" F4="F4" F5="F5"/>
    <z:row F1="1.3" F2="2.3" F5="1.1"/>
    <z:row F1="3.4" F3="2.8" F4="5.3"/>
....
</xml>
</code>```

Here is a sample VBA code:

```<code>Sub TestMe()

Dim XML As Object
Dim sFilePath As String, sXML As String, K As Variant, FirstDataRow As Object
Dim oRS As Object, Attr_XPath As String, FirstDataRow_XPath As String
Dim Attrs As Object, Attr As Object, I As Long, J As Long

sFilePath = "C:\Test_ADO.xml"
Set XML = CreateObject("Microsoft.XMLDOM")
XML.Load (sFilePath)

Attr_XPath = "//@*[name()='AttributeType']"
FirstDataRow_XPath = "//@*[name()='row']"

Set Attrs = XML.SelectNodes(Attr_XPath)
Set FirstDataRow = XML.SelectSingleNode(FirstDataRow_XPath)

Stop
For Each K In FirstDataRow.Attributes
    For Each Attr In Attrs
   '....
    Next Attr
Next K

....
End Sub
</code>```

答:
The namespace agnostic way to build XPath expression is simple but makes expressions much longer. For each element you supply following subexpression:

```<code>/*[local-name()='AttributeType']
</code>```

name() function returns prefix and local name of the element, e.g. "s:AttributeType" and local-name() returns only the local part of it.

Body:
I am loading different XML files that contain different xmlns namespaces having specific prefixes e.g. x,i,s,dt,xx etc. that change with different XML files. I am searching for multiple Element nodes e.g., AttributeType that may be prefixed with the namespace prefix.

My question is, how do i select the multiple nodes using VBA without knowing the xmlns Namespace prefix (e.g. whether it will be s or xx) that may be prefixed to the node?

Example:

<xml
xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
xmlns:rs="urn:schemas-microsoft-com:rowset"
xmlns:z="#RowsetSchema">
    <s:Schema id="RowsetSchema">
        <s:ElementType name="row" content="eltOnly" rs:updatable="true">
            <s:AttributeType name="F1" rs:number="1" rs:nullable="true" rs:maydefer="true" rs:writeunknown="true" rs:basetable="abc$" rs:basecolumn="F1">
                <s:datatype dt:type="string" dt:maxLength="255"/>
            </s:AttributeType>
            <s:AttributeType name="F2" rs:number="1" rs:nullable="true" rs:maydefer="true" rs:writeunknown="true" rs:basetable="abc$" rs:basecolumn="F2">
                <s:datatype dt:type="string" dt:maxLength="255"/>
            </s:AttributeType>
....
        </s:AttributeType>
        <s:extends type="rs:rowbase"/>
    </s:ElementType>
</s:Schema>
<rs:data>
    <z:row F2="F2" F4="F4" F5="F5"/>
    <z:row F1="1.3" F2="2.3" F5="1.1"/>
    <z:row F1="3.4" F3="2.8" F4="5.3"/>
....
</xml>

Another example:

<xml
xmlns:xx="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
xmlns:rs="urn:schemas-microsoft-com:rowset"
xmlns:z="#RowsetSchema">
    <xx:Schema id="RowsetSchema">
        <xx:ElementType name="row" content="eltOnly" rs:updatable="true">
            <xx:AttributeType name="F1" rs:number="1" rs:nullable="true" rs:maydefer="true" rs:writeunknown="true" rs:basetable="abc$" rs:basecolumn="F1">
                <xx:datatype dt:type="string" dt:maxLength="255"/>
            </xx:AttributeType>
            <xx:AttributeType name="F2" rs:number="1" rs:nullable="true" rs:maydefer="true" rs:writeunknown="true" rs:basetable="abc$" rs:basecolumn="F2">
                <xx:datatype dt:type="string" dt:maxLength="255"/>
            </xx:AttributeType>
....
        </s:AttributeType>
        <s:extends type="rs:rowbase"/>
    </s:ElementType>
</s:Schema>
<rs:data>
    <z:row F2="F2" F4="F4" F5="F5"/>
    <z:row F1="1.3" F2="2.3" F5="1.1"/>
    <z:row F1="3.4" F3="2.8" F4="5.3"/>
....
</xml>

Here is a sample VBA code:

Sub TestMe()

Dim XML As Object
Dim sFilePath As String, sXML As String, K As Variant, FirstDataRow As Object
Dim oRS As Object, Attr_XPath As String, FirstDataRow_XPath As String
Dim Attrs As Object, Attr As Object, I As Long, J As Long

sFilePath = "C:\Test_ADO.xml"
Set XML = CreateObject("Microsoft.XMLDOM")
XML.Load (sFilePath)

Attr_XPath = "//@*[name()='AttributeType']"
FirstDataRow_XPath = "//@*[name()='row']"

Set Attrs = XML.SelectNodes(Attr_XPath)
Set FirstDataRow = XML.SelectSingleNode(FirstDataRow_XPath)

Stop
For Each K In FirstDataRow.Attributes
    For Each Attr In Attrs
   '....
    Next Attr
Next K

....
End Sub

Body:
The namespace agnostic way to build XPath expression is simple but makes expressions much longer. For each element you supply following subexpression:

/*[local-name()='AttributeType']

name() function returns prefix and local name of the element, e.g. "s:AttributeType" and local-name() returns only the local part of it.


问:
Set x XML node to value in Powershell
I have this PowerShell script in which values for an XML-file will be set by the script. This works perfectly fine when all child nodes are uniquely named. However, I'm adapting the XML-file to one where some nodes are repeated. Now I get an error in Powershell.

My question is, how to set the X'th node in XML to a certain value via PowerShell?

In short, my script works like the following:

```<code>cls

[xml] $xml1 = '<Lvl1>
                    <Lvl2>""</Lvl2>
                    <Lvl2>""</Lvl2>
                </Lvl1>'

$xml1.Lvl1.Lvl2='./'

$xml1.Save("text.xml")
</code>```

There is two times the same node (Lvl2), that's why I get the following error in PowerShell: "Cannot set "Lvl2" because only strings can be used as values to set XmlNode properties."

When I remove one (Lvl2) node, the script works like a charm.

Please advice.

答:
You can get the child nodes of Lvl1 as aray and then use the index to adjust the wanted node:

```<code>[xml] $xml1 = '<Lvl1>
                    <Lvl2>""</Lvl2>
                    <Lvl2>""</Lvl2>
                </Lvl1>'

$lvl2Nodes = @($xml1.Lvl1.ChildNodes)

$lvl2Nodes[1].'#text' = "blah"  # updating the second childnode only

$xml1.Save("D:\text.xml")
</code>```

Result:

```<code><Lvl1>
  <Lvl2>""</Lvl2>
  <Lvl2>blah</Lvl2>
</Lvl1>
</code>```

Title: Set x XML node to value in Powershell

Body:
I have this PowerShell script in which values for an XML-file will be set by the script. This works perfectly fine when all child nodes are uniquely named. However, I'm adapting the XML-file to one where some nodes are repeated. Now I get an error in Powershell.

My question is, how to set the X'th node in XML to a certain value via PowerShell?

In short, my script works like the following:

cls

[xml] $xml1 = '<Lvl1>
                    <Lvl2>""</Lvl2>
                    <Lvl2>""</Lvl2>
                </Lvl1>'

$xml1.Lvl1.Lvl2='./'

$xml1.Save("text.xml")

There is two times the same node (Lvl2), that's why I get the following error in PowerShell: "Cannot set "Lvl2" because only strings can be used as values to set XmlNode properties."

When I remove one (Lvl2) node, the script works like a charm.

Please advice.

Body:
You can get the child nodes of Lvl1 as aray and then use the index to adjust the wanted node:

[xml] $xml1 = '<Lvl1>
                    <Lvl2>""</Lvl2>
                    <Lvl2>""</Lvl2>
                </Lvl1>'

$lvl2Nodes = @($xml1.Lvl1.ChildNodes)

$lvl2Nodes[1].'#text' = "blah"  # updating the second childnode only

$xml1.Save("D:\text.xml")

Result:

<Lvl1>
  <Lvl2>""</Lvl2>
  <Lvl2>blah</Lvl2>
</Lvl1>


问:
Is it possible to get synchronous spark request-reply response?
This might be a old question.But I could not find any solutions.I am able to get request-reply response from synchronous kafka.But I need to get the same response from spark application where I calculate aggregations.How to achieve this?</p>

答:
There is a Apache incubator project called Livy exactly for this purpose.
Their documentation is not bad and pretty simple and straight forward.</p>


问:
how to resolve the zone already loaded error in angular4?
Im trying to load my angular build from a typescript package using (dist/index.html). Its loading fine, but when im going back and again trying to load the same, its showing the below errors.

VM5485:1 Uncaught Error: Zone already loaded.
    at new d (:1:211206)

VM5457:1 Uncaught Error: Zone.js has detected that ZoneAwarePromise (window|global).Promise has been overwritten.

I tried:
removing the zone.js from polyfills.ts and adding "angularfire2": "5.0.0-rc.4".

But no luck. Can someone please help

答: Adding zone.js: 0.9.0 in the package.json and run npm install. The issue will get resolved.</p>


答:
```<code>PS D:\TEMP> type lvl.xml
<Lvl1>
                    <Lvl2>"test1"</Lvl2>
                    <Lvl2>"test2"</Lvl2>
                </Lvl1>
PS D:\TEMP> $xml = New-Object XML
PS D:\TEMP> $xml.Load("lvl.xml")
PS D:\TEMP> $element =  $xml.SelectSingleNode("/Lvl1/Lvl2[2]")
PS D:\TEMP> $element.InnerText ="bla"
PS D:\TEMP> $xml.Save("lvl2.xml")
PS D:\TEMP> type lvl2.xml
<Lvl1>
  <Lvl2>"test1"</Lvl2>
  <Lvl2>bla</Lvl2>
</Lvl1>
PS D:\TEMP>
</code>```

In the XmlPath (i.e. '/Lvl1/Lvl2[2]') the '[2]' refers to the second time this thing exists.

Title: Set x XML node to value in Powershell

Body:
PS D:\TEMP> type lvl.xml
<Lvl1>
                    <Lvl2>"test1"</Lvl2>
                    <Lvl2>"test2"</Lvl2>
                </Lvl1>
PS D:\TEMP> $xml = New-Object XML
PS D:\TEMP> $xml.Load("lvl.xml")
PS D:\TEMP> $element =  $xml.SelectSingleNode("/Lvl1/Lvl2[2]")
PS D:\TEMP> $element.InnerText ="bla"
PS D:\TEMP> $xml.Save("lvl2.xml")
PS D:\TEMP> type lvl2.xml
<Lvl1>
  <Lvl2>"test1"</Lvl2>
  <Lvl2>bla</Lvl2>
</Lvl1>
PS D:\TEMP>

In the XmlPath (i.e. '/Lvl1/Lvl2[2]') the '[2]' refers to the second time this thing exists.


答:
Let see what javadocs say about it

Compares two strings lexicographically. The comparison is based on the
  Unicode value of each character in the strings. The character sequence
  represented by this String object is compared lexicographically to the
  character sequence represented by the argument string. The result is a
  negative integer if this String object lexicographically precedes the
  argument string. The result is a positive integer if this String
  object lexicographically follows the argument string. The result is
  zero if the strings are equal; compareTo returns 0 exactly when the
  equals(Object) method would return true.

This is the definition of lexicographic ordering. If two strings are
  different, then either they have different characters at some index
  that is a valid index for both strings, or their lengths are
  different, or both. If they have different characters at one or more
  index positions, let k be the smallest such index; then the string
  whose character at position k has the smaller value, as determined by
  using the < operator, lexicographically precedes the other string. In
  this case, compareTo returns the difference of the two character
  values at position k in the two string -- that is, the value:

```<code> this.charAt(k)-anotherString.charAt(k)
</code>```

If there is no index position at which they differ, then the shorter
  string lexicographically precedes the longer string. In this case,
  compareTo returns the difference of the lengths of the strings -- that
  is, the value:

```<code> this.length()-anotherString.length()
</code>```

Title: compareTo() function in Java

Body:
Let see what javadocs say about it

Compares two strings lexicographically. The comparison is based on the
  Unicode value of each character in the strings. The character sequence
  represented by this String object is compared lexicographically to the
  character sequence represented by the argument string. The result is a
  negative integer if this String object lexicographically precedes the
  argument string. The result is a positive integer if this String
  object lexicographically follows the argument string. The result is
  zero if the strings are equal; compareTo returns 0 exactly when the
  equals(Object) method would return true.

This is the definition of lexicographic ordering. If two strings are
  different, then either they have different characters at some index
  that is a valid index for both strings, or their lengths are
  different, or both. If they have different characters at one or more
  index positions, let k be the smallest such index; then the string
  whose character at position k has the smaller value, as determined by
  using the < operator, lexicographically precedes the other string. In
  this case, compareTo returns the difference of the two character
  values at position k in the two string -- that is, the value:

 this.charAt(k)-anotherString.charAt(k)

If there is no index position at which they differ, then the shorter
  string lexicographically precedes the longer string. In this case,
  compareTo returns the difference of the lengths of the strings -- that
  is, the value:

 this.length()-anotherString.length()


问:
typescript array of required items
Is there a way to force all elements in array?

Only requirement is "type connection" to main Book type.

I hope there is some way to make tuple type ['id', 'title'] from Book type generically, as suggested in comments. Or at least array length check...

Sandbox.

```<code>type Book = {
  id: string
  title: string
  visible: boolean
  author: string
}

type BookFields = keyof Book

type BookFieldsExtract<ExtractedFields extends BookFields> = Extract<BookFields, ExtractedFields>

const arr: BookFieldsExtract<'id' | 'title'>[] = ['id'] // how to force error if title not inclided in array?
</code>```

Use case:

```<code>type SelectedBookFields = BookFieldsExtract<'id' | 'title'>
type ApiRes = ApiResBook<SelectedBookFields> // {book: {id: string, title: string}}

 const bookFields: SelectedBookFields[] = ['id', 'title'] // i just don't want to forget some fields when making request

  const response = await fetchAPI<ApiReqBookBody, ApiRes>(
    'book',
    { fields: { book: bookFields } }
  ) // response type is {error: true} | {book: {id: string, title: string}}
</code>```

答:
I dont know if it will work for you, but I would create some value constructor for this tuple with some overloads in order to guide the dev. Consider:

```<code>function makeArrFromKeys<T, A extends keyof T>(obj: T, key1: A): [A]
function makeArrFromKeys<T, A extends keyof T, B extends keyof Omit<T, A>>(obj: T, key1: A, key2: B): [A, B]
function makeArrFromKeys<T, A extends keyof T, B extends keyof Omit<T, A>, C extends keyof Omit<T, A | B>>(obj: T, key1: A, key2: B, key3: C): [A,B,C]
function makeArrFromKeys<T, K extends keyof T>(obj: T, ...keys: K[]): K[] {
    return keys;
}

const book: Book = {
    id: 'i',
    title: 't',
    visible: true,
    author: 'a'
}
const arr = makeArrFromKeys(book, 'id', 'author', 'title')
// arr has type ['id', 'author', 'title']
</code>```

Our function is extends to three keys, but if you will follow overloads you can go further. Function will make the tuple exactly how you wanted - keys are unique and if you provide you need 'id', 'title' you will get ['id', 'title'].

I would name it compromise between a crazy type which probably we can do, and just maintainable and safety code.

Title: typescript array of required items

Body:
Is there a way to force all elements in array?

Only requirement is "type connection" to main Book type.

I hope there is some way to make tuple type ['id', 'title'] from Book type generically, as suggested in comments. Or at least array length check...

Sandbox.

type Book = {
  id: string
  title: string
  visible: boolean
  author: string
}

type BookFields = keyof Book

type BookFieldsExtract<ExtractedFields extends BookFields> = Extract<BookFields, ExtractedFields>

const arr: BookFieldsExtract<'id' | 'title'>[] = ['id'] // how to force error if title not inclided in array?

Use case:

type SelectedBookFields = BookFieldsExtract<'id' | 'title'>
type ApiRes = ApiResBook<SelectedBookFields> // {book: {id: string, title: string}}

 const bookFields: SelectedBookFields[] = ['id', 'title'] // i just don't want to forget some fields when making request

  const response = await fetchAPI<ApiReqBookBody, ApiRes>(
    'book',
    { fields: { book: bookFields } }
  ) // response type is {error: true} | {book: {id: string, title: string}}

Body:
I dont know if it will work for you, but I would create some value constructor for this tuple with some overloads in order to guide the dev. Consider:

function makeArrFromKeys<T, A extends keyof T>(obj: T, key1: A): [A]
function makeArrFromKeys<T, A extends keyof T, B extends keyof Omit<T, A>>(obj: T, key1: A, key2: B): [A, B]
function makeArrFromKeys<T, A extends keyof T, B extends keyof Omit<T, A>, C extends keyof Omit<T, A | B>>(obj: T, key1: A, key2: B, key3: C): [A,B,C]
function makeArrFromKeys<T, K extends keyof T>(obj: T, ...keys: K[]): K[] {
    return keys;
}

const book: Book = {
    id: 'i',
    title: 't',
    visible: true,
    author: 'a'
}
const arr = makeArrFromKeys(book, 'id', 'author', 'title')
// arr has type ['id', 'author', 'title']

Our function is extends to three keys, but if you will follow overloads you can go further. Function will make the tuple exactly how you wanted - keys are unique and if you provide you need 'id', 'title' you will get ['id', 'title'].

I would name it compromise between a crazy type which probably we can do, and just maintainable and safety code.


问:
How to delete duplicates from one table, but keeping only one record?
Hello SQL query experts!
I have one table called 'mytable' which has 2 columns such as id and title .
I tried to remove duplicates except only one record(row) comparing title.
Below was my choice:

```<code>DELETE FROM `myTable` AS `m1`
WHERE `m1`.`id`
NOT IN (SELECT MIN(`b`.`id`) as `recordid` FROM `myTable` AS `b` GROUP BY `b`.`title`)
</code>```

error : Error in query (1064): Syntax error near '* FROM `myTable` AS `m1` WHERE `m1`.`id` NOT IN (SELECT MIN(`b`.`id`) as `reco' at line 1
but I faced a trouble and tried to resolve this problem more than 2 hours.
It seems like very simple problem.
But I can't figure it out. So I am asking to stackoverflow!

And mainly, I see something strange.
I tried like this but it has no any error.

```<code>SELECT * FROM `myTable` AS `m1`
WHERE `m1`.`id`
NOT IN (SELECT MIN(`b`.`id`) as `recordid` FROM `myTable` AS `b` GROUP BY `b`.`title`)
</code>```

When I run this query, I can obtain the list of records(rows) I want to delete from 'myTable' table.

Why do I face a deletion problem although I can obtain the list to delete?

I need your help really.
Thanks everyone!

答:
You can phrase this as:

```<code>delete m
    from mytable m left join
         (select m2.title, min(m2.id) as min_id
          from mytable m2
          group by m2.title
         ) m2
         on m.title = m2.title and m.id > m.min_id;
</code>```

For performance, you want in index on (title, id).

Body:
Hello SQL query experts!
I have one table called 'mytable' which has 2 columns such as id and title .
I tried to remove duplicates except only one record(row) comparing title.
Below was my choice:

DELETE FROM `myTable` AS `m1`
WHERE `m1`.`id`
NOT IN (SELECT MIN(`b`.`id`) as `recordid` FROM `myTable` AS `b` GROUP BY `b`.`title`)

error : Error in query (1064): Syntax error near '* FROM `myTable` AS `m1` WHERE `m1`.`id` NOT IN (SELECT MIN(`b`.`id`) as `reco' at line 1
but I faced a trouble and tried to resolve this problem more than 2 hours.
It seems like very simple problem.
But I can't figure it out. So I am asking to stackoverflow!

And mainly, I see something strange.
I tried like this but it has no any error.

SELECT * FROM `myTable` AS `m1`
WHERE `m1`.`id`
NOT IN (SELECT MIN(`b`.`id`) as `recordid` FROM `myTable` AS `b` GROUP BY `b`.`title`)

When I run this query, I can obtain the list of records(rows) I want to delete from 'myTable' table.

Why do I face a deletion problem although I can obtain the list to delete?

I need your help really.
Thanks everyone!

Body:
You can phrase this as:

delete m
    from mytable m left join
         (select m2.title, min(m2.id) as min_id
          from mytable m2
          group by m2.title
         ) m2
         on m.title = m2.title and m.id > m.min_id;

For performance, you want in index on (title, id).


问:
Populate with new value(s) to a fixed-shape numpy array filled with zeros
Given that a numpy array is stored contiguously, if we try to append or extend to it then this happens not in-place but, instead, a new copy of the array is created with adequate 'room' for the append or extend to occur contiguously (see https://stackoverflow.com/a/13215559/3286832).

To avoid that, and assuming we are lucky enough to know the specific number of elements we expect the array to have, we can create a numpy array with a fixed size filled with zeros:

```<code>import numpy as np

a = np.zeros(shape=(100,))  # [0. 0. 0. ... 0. 0. 0.]
</code>```

Say that we want to populate this array each element with a new value each time (e.g. provided by the user) by editing this array in-place:

```<code>pos = 0
a[pos] = 0.002              # [0.002 0. 0. ... 0. 0. 0.]

pos = pos + 1
a[pos] = 0.101              # [0.002 0.101 0. ... 0. 0. 0.]

# etc.

pos = -1
a[pos] = 42.00              # [0.002 0.101 ... ... ... 42.]
</code>```

Question:

Is there a way to keep track of the next available position pos (i.e. last position not previously populated with a new input value) instead of manually incrementing pos each time?

Is there a way in efficiently achieving this in numpy, preferably? Or is there a way of achieving this in another Python library (e.g. scipy or Pandas)?

(edited the question according the comments and initial answers which stated how not clear my initial question was phrased - hope this now is clearer)

答:
If I understand you correctly, you need some kind of circular buffer. Python has collections.deque for this purpose.

Here is my custom implementation of circular buffer using h5py, but you can change it to numpy.

Update: As it was already mentioned in comments it is impossible to track changes of an np.array out of the box. Instead, you can implement your own class and track all the necessary changes there (see my implementation as an example, i.e. concatenate arrays to extend its size). I'd suggest you to use python list if you need appending or deque if you need fixed size. The both arrays can be then converted to np.array

Body:
Given that a numpy array is stored contiguously, if we try to append or extend to it then this happens not in-place but, instead, a new copy of the array is created with adequate 'room' for the append or extend to occur contiguously (see https://stackoverflow.com/a/13215559/3286832).

To avoid that, and assuming we are lucky enough to know the specific number of elements we expect the array to have, we can create a numpy array with a fixed size filled with zeros:

import numpy as np

a = np.zeros(shape=(100,))  # [0. 0. 0. ... 0. 0. 0.]

Say that we want to populate this array each element with a new value each time (e.g. provided by the user) by editing this array in-place:

pos = 0
a[pos] = 0.002              # [0.002 0. 0. ... 0. 0. 0.]

pos = pos + 1
a[pos] = 0.101              # [0.002 0.101 0. ... 0. 0. 0.]

# etc.

pos = -1
a[pos] = 42.00              # [0.002 0.101 ... ... ... 42.]

Question:

Is there a way to keep track of the next available position pos (i.e. last position not previously populated with a new input value) instead of manually incrementing pos each time?

Is there a way in efficiently achieving this in numpy, preferably? Or is there a way of achieving this in another Python library (e.g. scipy or Pandas)?

(edited the question according the comments and initial answers which stated how not clear my initial question was phrased - hope this now is clearer)


问:
How to convert a JSONObject to a Java Bean with string variables?
How can I convert a JSONObject to a PersonBean as below?  I have an intermediary Person with a name field and a List<String for other attributes.  The List is of indeterminate size, but less than ten items.

My thinking is to create PersonBean with additional String fields and then manually copy values from the List into bean setters.

But, of course I'm getting out of bound errors when creating a PersonBean because the List might be empty:

```<code>package groupBaseX.io;

import java.util.logging.Logger;

public class PersonBeanBuilder {

    private static final Logger log = Logger.getLogger(PersonBeanBuilder.class.getName());
    private Person person = null;
    private PersonBean personBean = new PersonBean();

    private PersonBeanBuilder() {
    }

    public PersonBeanBuilder(Person person) {
        this.person = person;
        log.fine(person.toString());
        log.fine(person.getName());
        personBean.setName(person.getName());

        String a = person.getAttributes().get(0);
        String b = person.getAttributes().get(1);
        String c = person.getAttributes().get(2);
        String d = person.getAttributes().get(3);
        String e = person.getAttributes().get(4);

        personBean.setA(a);
        personBean.setB(b);
        personBean.setC(c);
        personBean.setD(d);
        personBean.setE(e);

    }

    public PersonBean getPersonBean() {
        return personBean;
    }

}
</code>```

Certainly, I can just use try/catch but is there not a more elegant solution?  The above code is very much a kludge.

because the underlying JSON, in a JSONArray, is of indeterminate size.  For practical purposes, I'm only interested in the name and the first few attributes for each object below:

```<code>[
  {
    "0":"z10",
    "1":"y9",
    "2":"x7",
    "3":"atrib6",
    "name":"alice"
  },
  {
    "0":"home5",
    "1":"cell4",
    "name":"sue"
  },
  {
    "0":"phone3",
    "1":"phone2",
    "2":"phone1",
    "name":"joe"
  },
  {
    "name":"people"
  }
]
</code>```

Some JSONObject will of course have zero attributes, but certainly less than ten.  Just looking to create a Java Bean from the above JSON, which is from BaseX.

答:
This is the somewhat reasonable approach I settled on:

```<code>package groupBaseX.io;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

public class PersonBeanBuilder {

    private static final Logger log = Logger.getLogger(PersonBeanBuilder.class.getName());
    private Person person = null;
    private PersonBean personBean = new PersonBean();

    private PersonBeanBuilder() {
    }

    public PersonBeanBuilder(Person person) {
        this.person = person;

    }

    public PersonBean getPersonBean() {
        personBean.setName(person.getName());

        Map<String, AF> map = new HashMap<>();

        AF attributeField = AF.GARBAGE;
        person.getAttributes().forEach((s) -> {
            map.put(s, attributeField.getType(s));
        });

        for (String key : map.keySet()) {
            switch (map.get(key)) {
                case HOME_PHONE:
                    log.fine(AF.HOME_PHONE.toString());
                    personBean.setHomePhone1(key);
                    break;
                default:
                    log.fine(AF.HOME_PHONE.toString());
                    break;
            }
        }
        return personBean;
    }

}
</code>```

enum:

```<code>package groupBaseX.io;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

public class AttributeParser {

    private static final Logger log = Logger.getLogger(AttributeParser.class.getName());
    private List<String> attributes = new ArrayList<>();

    private AttributeParser() {
    }

    public AttributeParser(List<String> attributes) {
        this.attributes = attributes;
    }

    // ^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$  phone
    // ^\d{5}(?:[-\s]\d{4})?$     zip
    public void foo() {

        boolean isPhone = false;
        boolean isZip = false;
        for (String s : attributes) {
            int x = 3;
            isPhone = false;
            isZip = false;

        }
    }

}
</code>```

But, still quite awkward.  The starting point is JSON so I'm sure this has been figured by smarter monkeys than me already.

Body:
How can I convert a JSONObject to a PersonBean as below?  I have an intermediary Person with a name field and a List<String for other attributes.  The List is of indeterminate size, but less than ten items.

My thinking is to create PersonBean with additional String fields and then manually copy values from the List into bean setters.

But, of course I'm getting out of bound errors when creating a PersonBean because the List might be empty:

package groupBaseX.io;

import java.util.logging.Logger;

public class PersonBeanBuilder {

    private static final Logger log = Logger.getLogger(PersonBeanBuilder.class.getName());
    private Person person = null;
    private PersonBean personBean = new PersonBean();

    private PersonBeanBuilder() {
    }

    public PersonBeanBuilder(Person person) {
        this.person = person;
        log.fine(person.toString());
        log.fine(person.getName());
        personBean.setName(person.getName());

        String a = person.getAttributes().get(0);
        String b = person.getAttributes().get(1);
        String c = person.getAttributes().get(2);
        String d = person.getAttributes().get(3);
        String e = person.getAttributes().get(4);

        personBean.setA(a);
        personBean.setB(b);
        personBean.setC(c);
        personBean.setD(d);
        personBean.setE(e);

    }

    public PersonBean getPersonBean() {
        return personBean;
    }

}

Certainly, I can just use try/catch but is there not a more elegant solution?  The above code is very much a kludge.

because the underlying JSON, in a JSONArray, is of indeterminate size.  For practical purposes, I'm only interested in the name and the first few attributes for each object below:

[
  {
    "0":"z10",
    "1":"y9",
    "2":"x7",
    "3":"atrib6",
    "name":"alice"
  },
  {
    "0":"home5",
    "1":"cell4",
    "name":"sue"
  },
  {
    "0":"phone3",
    "1":"phone2",
    "2":"phone1",
    "name":"joe"
  },
  {
    "name":"people"
  }
]

Some JSONObject will of course have zero attributes, but certainly less than ten.  Just looking to create a Java Bean from the above JSON, which is from BaseX.

Body:
This is the somewhat reasonable approach I settled on:

package groupBaseX.io;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

public class PersonBeanBuilder {

    private static final Logger log = Logger.getLogger(PersonBeanBuilder.class.getName());
    private Person person = null;
    private PersonBean personBean = new PersonBean();

    private PersonBeanBuilder() {
    }

    public PersonBeanBuilder(Person person) {
        this.person = person;

    }

    public PersonBean getPersonBean() {
        personBean.setName(person.getName());

        Map<String, AF> map = new HashMap<>();

        AF attributeField = AF.GARBAGE;
        person.getAttributes().forEach((s) -> {
            map.put(s, attributeField.getType(s));
        });

        for (String key : map.keySet()) {
            switch (map.get(key)) {
                case HOME_PHONE:
                    log.fine(AF.HOME_PHONE.toString());
                    personBean.setHomePhone1(key);
                    break;
                default:
                    log.fine(AF.HOME_PHONE.toString());
                    break;
            }
        }
        return personBean;
    }

}

enum:

package groupBaseX.io;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

public class AttributeParser {

    private static final Logger log = Logger.getLogger(AttributeParser.class.getName());
    private List<String> attributes = new ArrayList<>();

    private AttributeParser() {
    }

    public AttributeParser(List<String> attributes) {
        this.attributes = attributes;
    }

    // ^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$  phone
    // ^\d{5}(?:[-\s]\d{4})?$     zip
    public void foo() {

        boolean isPhone = false;
        boolean isZip = false;
        for (String s : attributes) {
            int x = 3;
            isPhone = false;
            isZip = false;

        }
    }

}

But, still quite awkward.  The starting point is JSON so I'm sure this has been figured by smarter monkeys than me already.


答:
The error is straight forward. The model is expecting an input of shape [b, 1024] (b for the batch size). You are passing as argument to the model an image of shape [1, 224, 224, 3]. Needless to say that it won't work.

To make the prediction work, the input of the model should match with the predicted tensor shape. Either the input model changes or the image is reshaped in a way that is fitting to the model.

Title: TensofrlowJS input mismatch from model expected input

Body:
I converted a Keras model to tfjs and when running it in browser I get the following warning:

topology.ts:1114 The shape of the input tensor ([null,1024]) does not match the expectation of layer dense: [null,[224,224,3]]

The model summary looks like this:

_________________________________________________________________
 Layer (type)                 Output shape              Param #
=================================================================
 mobilenet_1.00_224 (Model)   [null,1024]               3228864
_________________________________________________________________
 dense (Dense)                [null,256]                262400
_________________________________________________________________
 dropout (Dropout)            [null,256]                0
_________________________________________________________________
 dense_1 (Dense)              [null,512]                131584
_________________________________________________________________
 dropout_1 (Dropout)          [null,512]                0
_________________________________________________________________
 dense_2 (Dense)              [null,7]                  3591
=================================================================
Total params: 3626439
Trainable params: 397575
Non-trainable params: 3228864

For the prediction I implemented the following method:

async function classifyImage() {

    const cam = await tf.data.webcam(video); //video is a webcam element with 224x224 pixels
    const img = await cam.capture();
    console.log(img.shape);
    let new_frame = img.reshape([1, 224, 224, 3]);

    predictions = await model.predict(new_frame).print();

  }

How can I solve the warning message?


问:
What is causing these errors in my Heroku app?
I am getting the following errors when a Heroku worker runs a delayed_job and cannot work out why. The first error seems related to the Evernote gem, even though I don't actually have any code at all which uses it yet in the entire project. All I have is

```<code>gem 'evernote', "~> 0.9.0"
</code>```

in the gemfile.

The second one seems related to the Newrelic Heroku addon, which is an application monitoring service. But it does monitor the application so I have no idea what could be causing the error.

What is causing these errors?

1st

```<code>2011-05-11T03:31:22+00:00 heroku[worker.3]: Stopping process with SIGTERM
2011-05-11T03:31:22+00:00 app[worker.3]: rake aborted!
2011-05-11T03:31:22+00:00 app[worker.3]: SIGTERM
2011-05-11T03:31:22+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.0.1/lib/active_support/dependencies.rb:239:in `require'
2011-05-11T03:31:22+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.0.1/lib/active_support/dependencies.rb:239:in `block in require'
2011-05-11T03:31:22+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.0.1/lib/active_support/dependencies.rb:225:in `block in load_dependency'
2011-05-11T03:31:22+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.0.1/lib/active_support/dependencies.rb:591:in `new_constants_in'
2011-05-11T03:31:22+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.0.1/lib/active_support/dependencies.rb:225:in `load_dependency'
2011-05-11T03:31:22+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.0.1/lib/active_support/dependencies.rb:239:in `require'
2011-05-11T03:31:22+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/evernote-0.9.0/vendor/gen-rb/evernote.rb:5:in `<top (required)>'
2011-05-11T03:31:22+00:00 heroku[worker.3]: Process exited
2011-05-10T20:31:23-07:00 heroku[worker.2]: State changed from up to stopping
</code>```

2nd

```<code>2011-05-11T03:31:25+00:00 heroku[worker.2]: Stopping process with SIGTERM
2011-05-11T03:31:25+00:00 app[worker.2]: rake aborted!
2011-05-11T03:31:25+00:00 app[worker.2]: SIGTERM
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/caching/pages.rb:38:in `extend'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/caching/pages.rb:38:in `<module:Pages>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/caching/pages.rb:37:in `<module:Caching>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/caching/pages.rb:6:in `<module:ActionController>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/caching/pages.rb:5:in `<top (required)>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/caching.rb:60:in `<module:Caching>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/caching.rb:31:in `<module:ActionController>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/caching.rb:5:in `<top (required)>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/base.rb:192:in `<class:Base>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/base.rb:167:in `<module:ActionController>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/base.rb:3:in `<top (required)>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/vendor/plugins/rpm/lib/new_relic/control/frameworks/rails.rb:127:in `install_shim'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/vendor/plugins/rpm/lib/new_relic/control.rb:137:in `init_plugin'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/vendor/plugins/rpm/init.rb:26:in `block in <class:Plugin>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/railties-3.0.1/lib/rails/plugin.rb:81:in `eval'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/railties-3.0.1/lib/rails/plugin.rb:81:in `block in <class:Plugin>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/railties-3.0.1/lib/rails/initializable.rb:25:in `instance_exec'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/railties-3.0.1/lib/rails/initializable.rb:25:in `run'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/railties-3.0.1/lib/rails/initializable.rb:50:in `block in run_initializers'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/railties-3.0.1/lib/rails/initializable.rb:49:in `each'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/railties-3.0.1/lib/rails/initializable.rb:49:in `run_initializers'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/railties-3.0.1/lib/rails/application.rb:134:in `initialize!'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/config/environment.rb:5:in `<top (required)>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.0.1/lib/active_support/dependencies.rb:225:in `block in load_dependency'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.0.1/lib/active_support/dependencies.rb:239:in `require'
2011-05-11T03:31:25+00:00 app[worker.2]: /usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:588:in `invoke_with_call_chain'
2011-05-11T03:31:25+00:00 app[worker.2]: /usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2041:in `invoke_task'
2011-05-11T03:31:25+00:00 heroku[worker.2]: Process exited
</code>```

EDIT:

Here is the stack info:

```<code>Stack: bamboo-mri-1.9.2
</code>```

EDIT 2:

Here is another one:

```<code>2011-05-19T02:07:07+00:00 app[worker.1]: "success - end"
2011-05-19T02:07:07+00:00 app[worker.1]: [Worker(host:9c66d1f3-82a1-4489-b20b-b8460a467223 pid:1)] Mixpanel completed after 1.7464
2011-05-19T02:07:07+00:00 app[worker.1]: [Worker(host:9c66d1f3-82a1-4489-b20b-b8460a467223 pid:1)] 2 jobs processed at 0.1720 j/s, 0 failed ...
2011-05-19T02:07:07+00:00 app[worker.3]: rake aborted!
2011-05-19T02:07:07+00:00 app[worker.3]: SIGTERM
2011-05-19T02:07:07+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/builder-2.1.2/lib/blankslate.rb:107:in `append_features'
2011-05-19T02:07:07+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/devise-1.1.5/lib/devise/orm/active_record.rb:35:in `include'
2011-05-19T02:07:07+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/railties-3.0.1/lib/rails/engine.rb:200:in `block in <class:Engine>'
2011-05-19T02:07:07+00:00 heroku[worker.3]: Process exited
2011-05-18T19:07:08-07:00 heroku[worker.2]: State changed from created to starting
2011-05-19T02:07:08+00:00 app[worker.2]: [Worker(host:df710df0-7b32-42b7-b477-b810485b5dc7 pid:1)] RPM Monitoring DJ worker host:df710df0-7b32-42b7-b477-b810485b5dc7 pid:1
2011-05-19T02:07:08+00:00 app[worker.2]: Starting the New Relic Agent.
2011-05-19T02:07:08+00:00 app[worker.2]: [Worker(host:df710df0-7b32-42b7-b477-b810485b5dc7 pid:1)] Starting job worker
2011-05-19T02:07:09+00:00 heroku[worker.2]: Stopping process with SIGTERM
2011-05-19T02:07:09+00:00 app[worker.2]: [Worker(host:df710df0-7b32-42b7-b477-b810485b5dc7 pid:1)] Exiting...
2011-05-19T02:07:11+00:00 heroku[worker.2]: Starting process with command: `rake jobs:work`
2011-05-19T02:07:14+00:00 heroku[worker.2]: Process exited
2011-05-19T02:07:20+00:00 app[worker.2]: [Worker(host:5d665233-0dc4-4151-aab2-a64b7656df07 pid:1)] RPM Monitoring DJ worker host:5d665233-0dc4-4151-aab2-a64b7656df07 pid:1
2011-05-19T02:07:20+00:00 app[worker.2]: Starting the New Relic Agent.
2011-05-19T02:07:20+00:00 app[worker.2]: [Worker(host:5d665233-0dc4-4151-aab2-a64b7656df07 pid:1)] Starting job worker
</code>```

答:
The only time I've ever got the message "Stopping process with SIGTERM" has been when I have terminated the process manually - eg when I was running script/server and then hit CTRL-C

This is an operating system message saying that the process was terminated by somebody on purpose. It is not an internal failure.

I suggest you have a chat with the heroku people about whether your process was doing something silly and they terminated it.

ContentLicense: CC BY-SA 3.0

Body:
I am getting the following errors when a Heroku worker runs a delayed_job and cannot work out why. The first error seems related to the Evernote gem, even though I don't actually have any code at all which uses it yet in the entire project. All I have is

gem 'evernote', "~> 0.9.0"

in the gemfile.

The second one seems related to the Newrelic Heroku addon, which is an application monitoring service. But it does monitor the application so I have no idea what could be causing the error.

What is causing these errors?

1st

2011-05-11T03:31:22+00:00 heroku[worker.3]: Stopping process with SIGTERM
2011-05-11T03:31:22+00:00 app[worker.3]: rake aborted!
2011-05-11T03:31:22+00:00 app[worker.3]: SIGTERM
2011-05-11T03:31:22+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.0.1/lib/active_support/dependencies.rb:239:in `require'
2011-05-11T03:31:22+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.0.1/lib/active_support/dependencies.rb:239:in `block in require'
2011-05-11T03:31:22+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.0.1/lib/active_support/dependencies.rb:225:in `block in load_dependency'
2011-05-11T03:31:22+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.0.1/lib/active_support/dependencies.rb:591:in `new_constants_in'
2011-05-11T03:31:22+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.0.1/lib/active_support/dependencies.rb:225:in `load_dependency'
2011-05-11T03:31:22+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.0.1/lib/active_support/dependencies.rb:239:in `require'
2011-05-11T03:31:22+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/evernote-0.9.0/vendor/gen-rb/evernote.rb:5:in `<top (required)>'
2011-05-11T03:31:22+00:00 heroku[worker.3]: Process exited
2011-05-10T20:31:23-07:00 heroku[worker.2]: State changed from up to stopping

2nd

2011-05-11T03:31:25+00:00 heroku[worker.2]: Stopping process with SIGTERM
2011-05-11T03:31:25+00:00 app[worker.2]: rake aborted!
2011-05-11T03:31:25+00:00 app[worker.2]: SIGTERM
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/caching/pages.rb:38:in `extend'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/caching/pages.rb:38:in `<module:Pages>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/caching/pages.rb:37:in `<module:Caching>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/caching/pages.rb:6:in `<module:ActionController>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/caching/pages.rb:5:in `<top (required)>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/caching.rb:60:in `<module:Caching>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/caching.rb:31:in `<module:ActionController>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/caching.rb:5:in `<top (required)>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/base.rb:192:in `<class:Base>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/base.rb:167:in `<module:ActionController>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.1/lib/action_controller/base.rb:3:in `<top (required)>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/vendor/plugins/rpm/lib/new_relic/control/frameworks/rails.rb:127:in `install_shim'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/vendor/plugins/rpm/lib/new_relic/control.rb:137:in `init_plugin'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/vendor/plugins/rpm/init.rb:26:in `block in <class:Plugin>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/railties-3.0.1/lib/rails/plugin.rb:81:in `eval'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/railties-3.0.1/lib/rails/plugin.rb:81:in `block in <class:Plugin>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/railties-3.0.1/lib/rails/initializable.rb:25:in `instance_exec'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/railties-3.0.1/lib/rails/initializable.rb:25:in `run'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/railties-3.0.1/lib/rails/initializable.rb:50:in `block in run_initializers'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/railties-3.0.1/lib/rails/initializable.rb:49:in `each'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/railties-3.0.1/lib/rails/initializable.rb:49:in `run_initializers'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/railties-3.0.1/lib/rails/application.rb:134:in `initialize!'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/config/environment.rb:5:in `<top (required)>'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.0.1/lib/active_support/dependencies.rb:225:in `block in load_dependency'
2011-05-11T03:31:25+00:00 app[worker.2]: /app/.bundle/gems/ruby/1.9.1/gems/activesupport-3.0.1/lib/active_support/dependencies.rb:239:in `require'
2011-05-11T03:31:25+00:00 app[worker.2]: /usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:588:in `invoke_with_call_chain'
2011-05-11T03:31:25+00:00 app[worker.2]: /usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2041:in `invoke_task'
2011-05-11T03:31:25+00:00 heroku[worker.2]: Process exited

EDIT:

Here is the stack info:

Stack: bamboo-mri-1.9.2

EDIT 2:

Here is another one:

2011-05-19T02:07:07+00:00 app[worker.1]: "success - end"
2011-05-19T02:07:07+00:00 app[worker.1]: [Worker(host:9c66d1f3-82a1-4489-b20b-b8460a467223 pid:1)] Mixpanel completed after 1.7464
2011-05-19T02:07:07+00:00 app[worker.1]: [Worker(host:9c66d1f3-82a1-4489-b20b-b8460a467223 pid:1)] 2 jobs processed at 0.1720 j/s, 0 failed ...
2011-05-19T02:07:07+00:00 app[worker.3]: rake aborted!
2011-05-19T02:07:07+00:00 app[worker.3]: SIGTERM
2011-05-19T02:07:07+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/builder-2.1.2/lib/blankslate.rb:107:in `append_features'
2011-05-19T02:07:07+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/devise-1.1.5/lib/devise/orm/active_record.rb:35:in `include'
2011-05-19T02:07:07+00:00 app[worker.3]: /app/.bundle/gems/ruby/1.9.1/gems/railties-3.0.1/lib/rails/engine.rb:200:in `block in <class:Engine>'
2011-05-19T02:07:07+00:00 heroku[worker.3]: Process exited
2011-05-18T19:07:08-07:00 heroku[worker.2]: State changed from created to starting
2011-05-19T02:07:08+00:00 app[worker.2]: [Worker(host:df710df0-7b32-42b7-b477-b810485b5dc7 pid:1)] RPM Monitoring DJ worker host:df710df0-7b32-42b7-b477-b810485b5dc7 pid:1
2011-05-19T02:07:08+00:00 app[worker.2]: Starting the New Relic Agent.
2011-05-19T02:07:08+00:00 app[worker.2]: [Worker(host:df710df0-7b32-42b7-b477-b810485b5dc7 pid:1)] Starting job worker
2011-05-19T02:07:09+00:00 heroku[worker.2]: Stopping process with SIGTERM
2011-05-19T02:07:09+00:00 app[worker.2]: [Worker(host:df710df0-7b32-42b7-b477-b810485b5dc7 pid:1)] Exiting...
2011-05-19T02:07:11+00:00 heroku[worker.2]: Starting process with command: `rake jobs:work`
2011-05-19T02:07:14+00:00 heroku[worker.2]: Process exited
2011-05-19T02:07:20+00:00 app[worker.2]: [Worker(host:5d665233-0dc4-4151-aab2-a64b7656df07 pid:1)] RPM Monitoring DJ worker host:5d665233-0dc4-4151-aab2-a64b7656df07 pid:1
2011-05-19T02:07:20+00:00 app[worker.2]: Starting the New Relic Agent.
2011-05-19T02:07:20+00:00 app[worker.2]: [Worker(host:5d665233-0dc4-4151-aab2-a64b7656df07 pid:1)] Starting job worker


问:
How do you get the identity value after using MERGE when there is a match?
Say I have a table with an identity field. I want to insert a record in it if it doesn't already exist. In the below example, I check if the value stored in @Field1 already exists in the table. If not, I insert a new record:

Definition of the table:

```<code>MyTable (MyTableId int Identity not null, Field1 int not null, Field2 int not null)
</code>```

This is how I check if the value already exists and insert it if necessary

```<code>merge MyTable as t
using (@Field1, @Field2) as s (Field1,Field2)
on (t.Field1=s.Field1)
when not matched then
    insert (Field1,Field2) values (s.Field1,s.Field2);
</code>```

Getting the identity value when the record didn't already exist in the table can be done by adding:

```<code>output Inserted.MyTableId
</code>```

but what if the record was already in the table (ie if there was a match)?

The only way I found is to query the table after executing the Merge statement:

```<code>select MyTableId from MyTable where Field1=@Field1
</code>```

Is there a way to get the identity value directly from the Merge?

答:
Here other alternative:

```<code>DECLARE @FakeVar BIT

MERGE MyTable AS T
USING (VALUES(@Field1, @Field2)) AS S (Field1, Field2)
    ON (T.Field1 = S.Field1)
WHEN NOT MATCHED THEN
    INSERT (Field1, Field2)
    VALUES (S.Field1, T.Field2)
WHEN MATCHED THEN
    UPDATE SET @FakeVar = NULL -- do nothing, only force "an update" to ensure output on updates
OUTPUT INSERTED.MyTableId  ;
</code>```

If you check the OUPUT doc

INSERTED
Is a column prefix that specifies the value added by the insert or update operation.

you only need to do "something" on the update set clause

Body:
Say I have a table with an identity field. I want to insert a record in it if it doesn't already exist. In the below example, I check if the value stored in @Field1 already exists in the table. If not, I insert a new record:

Definition of the table:

MyTable (MyTableId int Identity not null, Field1 int not null, Field2 int not null)

This is how I check if the value already exists and insert it if necessary

merge MyTable as t
using (@Field1, @Field2) as s (Field1,Field2)
on (t.Field1=s.Field1)
when not matched then
    insert (Field1,Field2) values (s.Field1,s.Field2);

Getting the identity value when the record didn't already exist in the table can be done by adding:

output Inserted.MyTableId

but what if the record was already in the table (ie if there was a match)?

The only way I found is to query the table after executing the Merge statement:

select MyTableId from MyTable where Field1=@Field1

Is there a way to get the identity value directly from the Merge?

Body:
Here other alternative:

DECLARE @FakeVar BIT

MERGE MyTable AS T
USING (VALUES(@Field1, @Field2)) AS S (Field1, Field2)
    ON (T.Field1 = S.Field1)
WHEN NOT MATCHED THEN
    INSERT (Field1, Field2)
    VALUES (S.Field1, T.Field2)
WHEN MATCHED THEN
    UPDATE SET @FakeVar = NULL -- do nothing, only force "an update" to ensure output on updates
OUTPUT INSERTED.MyTableId  ;

If you check the OUPUT doc

INSERTED
Is a column prefix that specifies the value added by the insert or update operation.

you only need to do "something" on the update set clause