问:
Generate Json Schema from POJO with a twist
What I have:

I'm generating a JSON schema from a pojo.  My code to generate the schema looks like so:

```<code>ObjectMapper mapper = new ObjectMapper();
TitleSchemaFactoryWrapper visitor = new TitleSchemaFactoryWrapper();
mapper.acceptJsonFormatVisitor(clazz, visitor);
JsonSchema schema = visitor.finalSchema();
schemas.put(clazz, mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema));
</code>```

I'm generating several schemas via the above code.  One of the pojos has an internal embedded enum to limit the possible values, like so:

```<code>public class MyClass {

    @JsonProperty("name")
    private String name;
    @JsonProperty("startDayOfWeek")
    private MyClass.StartDayOfWeek startDayOfWeek;
    /**
     * The ID of a timezone returned by the timezones route.
     *
     */
    @JsonProperty("timezone")
    private String timezone;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    /**
     *
     * @return
     *     The startDayOfWeek
     */
    @JsonProperty("startDayOfWeek")
    public MyClass.StartDayOfWeek getStartDayOfWeek() {
        return startDayOfWeek;
    }

    /**
     *
     * @param startDayOfWeek
     *     The startDayOfWeek
     */
    @JsonProperty("startDayOfWeek")
    public void setStartDayOfWeek(MyClass.StartDayOfWeek startDayOfWeek) {
        this.startDayOfWeek = startDayOfWeek;
    }

    public static enum StartDayOfWeek {

        MONDAY("Monday"),
        TUESDAY("Tuesday"),
        WEDNESDAY("Wednesday"),
        THURSDAY("Thursday"),
        FRIDAY("Friday"),
        SATURDAY("Saturday"),
        SUNDAY("Sunday");
        private final String value;
        private static Map<String, MyClass.StartDayOfWeek> constants = new HashMap<String, MyClass.StartDayOfWeek>();

        static {
            for (MyClass.StartDayOfWeek c: values()) {
                constants.put(c.value, c);
            }
        }

        private StartDayOfWeek(String value) {
            this.value = value;
        }

        @JsonValue
        @Override
        public String toString() {
            return this.value;
        }

        @JsonCreator
        public static MyClass.StartDayOfWeek fromValue(String value) {
            MyClass.StartDayOfWeek constant = constants.get(value);
            if (constant == null) {
                throw new IllegalArgumentException(value);
            } else {
                return constant;
            }
        }

    }

}
</code>```

The above code should limit the possible String values in the JSON data that's passed around to "Monday", "Tuesday", "Wednesday", etc.

When I run the schema generator on the code in question, I expect to get something like the following schema:

```<code>{
  "type" : "object",
  "javaType" : "my.package.MyClass",
  "properties": {
    "startDayOfWeek" : {
      "type" : "string",
      "enum" : [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ]
    }
  }
}
</code>```

but instead I'm getting this:

```<code>{
  "type" : "object",
  "id" : "urn:jsonschema:my:package:MyClass",
  "title" : "Lmy/package/MyClass;",
  "properties" : {
    "startDayOfWeek" : {
      "type" : "string"
    }
  }
}
</code>```

I've done some digging in the Jackson Schema Module source code and figured out that what's happening is Jackson's using ".toString()" as the default serialization method for enum types, but what I need it to do instead is create the line that looks like this based on StartDayOfWeek.values():

```<code>"enum" : [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ]
</code>```

Does anyone know how to do that?

答:
If someone comes here and wants to support the newest draft version in his code.

Look here for your preferred language:
https://json-schema.org/implementations.html

Body:
What I have:

I'm generating a JSON schema from a pojo.  My code to generate the schema looks like so:

ObjectMapper mapper = new ObjectMapper();
TitleSchemaFactoryWrapper visitor = new TitleSchemaFactoryWrapper();
mapper.acceptJsonFormatVisitor(clazz, visitor);
JsonSchema schema = visitor.finalSchema();
schemas.put(clazz, mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema));

I'm generating several schemas via the above code.  One of the pojos has an internal embedded enum to limit the possible values, like so:

public class MyClass {

    @JsonProperty("name")
    private String name;
    @JsonProperty("startDayOfWeek")
    private MyClass.StartDayOfWeek startDayOfWeek;
    /**
     * The ID of a timezone returned by the timezones route.
     *
     */
    @JsonProperty("timezone")
    private String timezone;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    /**
     *
     * @return
     *     The startDayOfWeek
     */
    @JsonProperty("startDayOfWeek")
    public MyClass.StartDayOfWeek getStartDayOfWeek() {
        return startDayOfWeek;
    }

    /**
     *
     * @param startDayOfWeek
     *     The startDayOfWeek
     */
    @JsonProperty("startDayOfWeek")
    public void setStartDayOfWeek(MyClass.StartDayOfWeek startDayOfWeek) {
        this.startDayOfWeek = startDayOfWeek;
    }

    public static enum StartDayOfWeek {

        MONDAY("Monday"),
        TUESDAY("Tuesday"),
        WEDNESDAY("Wednesday"),
        THURSDAY("Thursday"),
        FRIDAY("Friday"),
        SATURDAY("Saturday"),
        SUNDAY("Sunday");
        private final String value;
        private static Map<String, MyClass.StartDayOfWeek> constants = new HashMap<String, MyClass.StartDayOfWeek>();

        static {
            for (MyClass.StartDayOfWeek c: values()) {
                constants.put(c.value, c);
            }
        }

        private StartDayOfWeek(String value) {
            this.value = value;
        }

        @JsonValue
        @Override
        public String toString() {
            return this.value;
        }

        @JsonCreator
        public static MyClass.StartDayOfWeek fromValue(String value) {
            MyClass.StartDayOfWeek constant = constants.get(value);
            if (constant == null) {
                throw new IllegalArgumentException(value);
            } else {
                return constant;
            }
        }

    }

}

The above code should limit the possible String values in the JSON data that's passed around to "Monday", "Tuesday", "Wednesday", etc.

When I run the schema generator on the code in question, I expect to get something like the following schema:

{
  "type" : "object",
  "javaType" : "my.package.MyClass",
  "properties": {
    "startDayOfWeek" : {
      "type" : "string",
      "enum" : [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ]
    }
  }
}

but instead I'm getting this:

{
  "type" : "object",
  "id" : "urn:jsonschema:my:package:MyClass",
  "title" : "Lmy/package/MyClass;",
  "properties" : {
    "startDayOfWeek" : {
      "type" : "string"
    }
  }
}

I've done some digging in the Jackson Schema Module source code and figured out that what's happening is Jackson's using ".toString()" as the default serialization method for enum types, but what I need it to do instead is create the line that looks like this based on StartDayOfWeek.values():

"enum" : [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ]

Does anyone know how to do that?


来源: stackexchange

问:
Converting from alpha to numeric with decimals fails
I have to convert a alphanumeric value  to a numeric value with decimal places:

Input: '6000'

Output. 60.00

So I tried the %dec() BIF which takes the input as alpha, the precision and the decimal places. But when trying this:

```<code>dcl-s alphanumeric char(13);
dcl-s numeric packed(13:2);

alphanumeric = '6000';
numeric = %dec(alphanumeric:13:2);

*inlr = *on;
</code>```

the conversion produces NUMERIC = 00000006000.00 and not NUMERIC = 000000060.00. So what am I doing wrong?

Even when using zoned(13:2) instead of packed(13:2) the value doesn't have decimal places other than '00'

答:
Alpha 6000 become 6000.00 in Numeric, it's correct.

If you want to interpret the last 2 digits like decimal, you must but a . into your string.

```<code>str = %subst(alphanumeric: 1: %len(alphanumeric)-3) + '.' + %subst(alphanumeric: %len(alphanumeric)-2: 2)
</code>```

And then convert the new string into a number.

You can also use EMBEDDED SQL:

```<code>EXEC SQL
SET :NEW_STRING = (
                    SELECT
                        DECIMAL( substr(:alphanumeric,   1,   LENGTH(:alphanumeric)-3)
                        CONCAT '.'
                        CONCAT substr(:alphanumeric, LENGTH(:alphanumeric)-2,  2),
                        13, 2)
                    FROM
                        sysibm.sysdummy1
                  )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have to convert a alphanumeric value  to a numeric value with decimal places:

Input: '6000'

Output. 60.00

So I tried the %dec() BIF which takes the input as alpha, the precision and the decimal places. But when trying this:

dcl-s alphanumeric char(13);
dcl-s numeric packed(13:2);

alphanumeric = '6000';
numeric = %dec(alphanumeric:13:2);

*inlr = *on;

the conversion produces NUMERIC = 00000006000.00 and not NUMERIC = 000000060.00. So what am I doing wrong?

Even when using zoned(13:2) instead of packed(13:2) the value doesn't have decimal places other than '00'

Body:
Alpha 6000 become 6000.00 in Numeric, it's correct.

If you want to interpret the last 2 digits like decimal, you must but a . into your string.

str = %subst(alphanumeric: 1: %len(alphanumeric)-3) + '.' + %subst(alphanumeric: %len(alphanumeric)-2: 2)

And then convert the new string into a number.

You can also use EMBEDDED SQL:

EXEC SQL
SET :NEW_STRING = (
                    SELECT
                        DECIMAL( substr(:alphanumeric,   1,   LENGTH(:alphanumeric)-3)
                        CONCAT '.'
                        CONCAT substr(:alphanumeric, LENGTH(:alphanumeric)-2,  2),
                        13, 2)
                    FROM
                        sysibm.sysdummy1
                  )


问:
Multiline text to fit parent container in React JS
I am using a flexbox layout and am trying to get the text in a specific div to be resized to fit that div.

So for example, if I have code as follows:

```<code><div style={{display: "flex"}}>
   <div style={{flex: 1}}>
      A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.
   </div>
   <div style={{flex: 1}}>
      Some other text
   </div>
</div>
</code>```

In reality, the text will be pulled from a database, so will be dynamic in length.

How can I get the text in the first div to automatically adjust to fit the entire div?

Clarification: the div should stay a fixed size and only the text should be downsized to fit the div rather than overflowing the div.

Update

I have also posted a more specific question about a specific module called react-textfit not working the way I would expect it to work.

答:
You could simply hard code the size to 50 %

```<code><div style="display:flex">
  <div style="width:50%;background:lightgrey;">
    A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.
  </div>
  <div style="width:50%;background:lightblue;">
    Some other text
  </div>
</div>
</code>```

Body:
I am using a flexbox layout and am trying to get the text in a specific div to be resized to fit that div.

So for example, if I have code as follows:

      A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.

      Some other text

In reality, the text will be pulled from a database, so will be dynamic in length.

How can I get the text in the first div to automatically adjust to fit the entire div?

Clarification: the div should stay a fixed size and only the text should be downsized to fit the div rather than overflowing the div.

Update

I have also posted a more specific question about a specific module called react-textfit not working the way I would expect it to work.

Body:
You could simply hard code the size to 50 %

<div style="display:flex">
  <div style="width:50%;background:lightgrey;">
    A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.
  </div>
  <div style="width:50%;background:lightblue;">
    Some other text
  </div>
</div>


问:
Returning a stream from a generic handler in ASP.NET
So, what I want to do is add a link to a web-page which, when clicked, will call a generic handler that will create the required data in memory and serve it back to the user as a stream of some sort, who is then prompted to Save it as a file.

SO, we might have:
Clickety

and the JavaSctipt makeme() function is just

```<code> function makeme() {
    $.ajax({
        url: 'makefile.ashx',
        cache: false
    }).done(function (response) {
       //alert(repsonse)
    });
 }
</code>```

In the handler, I've tried:

```<code>  Dim rtn As String = "1,2,3,4,5"
  Dim bArray As Byte() = System.Text.Encoding.Default.GetBytes(rtn.ToCharArray())
  ' or Dim mstream As New MemoryStream(bArray)   ‘ alt (see below)
  ' either of the next two lines
  context.Response.ContentType = "application/octet-stream"
  context.Response.ContentType = "application/force-download"
  context.Response.AddHeader("Content-Length", bArray.Length.ToString())
  context.Response.AddHeader("Content-Disposition", "filename.csv")
  context.Response.BinaryWrite(bArray)
  ' or context.Response.Write(mstream)           ‘ if alt used above
</code>```

Nothing appears to happen though....

even simpler, this:

```<code>  Dim rtn As String = "1,2,3,4,5"
  context.Response.Clear()
  context.Response.ContentType = "text/csv"
  context.Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv")
  context.Response.Write(rtn)
</code>```

also though, nothing happens on clicking the link - I mean, the handler is called, but that's it.

答:
The problem is that jQuery's $.ajax method was never intended to trigger the download of a file. It's meant to download data to later be handled in JavaScript.

You should point the anchor's href attribute directly to the handler. Then the browser will notice the response's content-disposition and handle the file download.

```<code><a href="makefile.ashx">Clickety</a>
</code>```

Body:
So, what I want to do is add a link to a web-page which, when clicked, will call a generic handler that will create the required data in memory and serve it back to the user as a stream of some sort, who is then prompted to Save it as a file.

SO, we might have:
Clickety

and the JavaSctipt makeme() function is just

 function makeme() {
    $.ajax({
        url: 'makefile.ashx',
        cache: false
    }).done(function (response) {
       //alert(repsonse)
    });
 }

In the handler, I've tried:

  Dim rtn As String = "1,2,3,4,5"
  Dim bArray As Byte() = System.Text.Encoding.Default.GetBytes(rtn.ToCharArray())
  ' or Dim mstream As New MemoryStream(bArray)   ‘ alt (see below)
  ' either of the next two lines
  context.Response.ContentType = "application/octet-stream"
  context.Response.ContentType = "application/force-download"
  context.Response.AddHeader("Content-Length", bArray.Length.ToString())
  context.Response.AddHeader("Content-Disposition", "filename.csv")
  context.Response.BinaryWrite(bArray)
  ' or context.Response.Write(mstream)           ‘ if alt used above

Nothing appears to happen though....

even simpler, this:

  Dim rtn As String = "1,2,3,4,5"
  context.Response.Clear()
  context.Response.ContentType = "text/csv"
  context.Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv")
  context.Response.Write(rtn)

also though, nothing happens on clicking the link - I mean, the handler is called, but that's it.

Body:
The problem is that jQuery's $.ajax method was never intended to trigger the download of a file. It's meant to download data to later be handled in JavaScript.

You should point the anchor's href attribute directly to the handler. Then the browser will notice the response's content-disposition and handle the file download.

<a href="makefile.ashx">Clickety</a>


问:
Convert an exponential matrix into number matrix
I have a matrix, say:

corr_a1=[6 2.150000e+003   0   1.175000e+003   3.250000e+000   4.500000e+001]

I want to convert the said values into decimal format, i.e.

a=[6.00 2150.00 1175.00 3.25 45.00]

How do I do this?

答: Check format.</p>

ContentLicense: CC BY-SA 3.0

Body: Check format.


问:
Bash - making decisions based upon output?
I am scripting a lot of processes in BASH. I want to not build certain items if they are already up to date in Git.

if a git pull is issued and the results are something like:

```<code>Already on 'master'
Your branch is up-to-date with 'origin/master'.
From https://github.com/xxx/yyyy
 * branch            master     -> FETCH_HEAD
Already up-to-date.
</code>```

How can I base decisions on the output of git pull?

Attempts:

```<code>upstream ⚡ master) 17≡ $ git status
On branch master
nothing to commit, working tree clean

(upstream ⚡ master) 17≡ $ git pull origin master
From github.com:xxx/yyy  m
 * branch            master     -> FETCH_HEAD
Already up to date.

(upstream ⚡ master) 17≡ $ git pull origin master 2>/dev/null |grep -q "Already up-to-date"

(upstream ⚡ master) 17≡ $
</code>```

Attempt 2:

```<code>$ git pull origin master 2>/dev/null | grep -q "Already up-to-date"; echo $?
1
$
</code>```

Attempt 3:

```<code>$ git pull origin master 2>/dev/null |grep -q "Already up-to-date"; echo $?
1

$ git pull origin master
From github.com:cocos2d/cocos2d-x-docs
 * branch            master     -> FETCH_HEAD
Already up to date.

$ git status
On branch master
nothing to commit, working tree clean

$ git pull origin master 2>/dev/null |grep -q "Already up-to-date"; echo $?
1
</code>```

Attempt 4:

```<code>$ git pull origin master 2>/dev/null |cat
Already up to date.

$ git pull origin master 2>/dev/null | grep -q "Already up-to-date"; echo $?
1

</code>```

答:
This will return true (0) if the output of git pull contains Already up-to-date:

```<code>git pull | grep -q "Already up-to-date"
</code>```

Then you can put it into an if-statement to take action conditionally. For example:

```<code>if git pull | grep -q "Already up-to-date"; then
    echo "Building stuff"
else
    echo "Not building stuff"
fi
</code>```

Your attempts are failing because git is printing up to date without the dashes, but the grep command is searching for up-to-date with the dashes, which is what your example output says. (BTW I'm using git 2.7.4 which prints up-to-date.) This sort of output might change between versions of git, so there is a more stable way of checking this sort of output, but I'm not sure what it is :/

Body:
I am scripting a lot of processes in BASH. I want to not build certain items if they are already up to date in Git.

if a git pull is issued and the results are something like:

Already on 'master'
Your branch is up-to-date with 'origin/master'.
From https://github.com/xxx/yyyy
 * branch            master     -> FETCH_HEAD
Already up-to-date.

How can I base decisions on the output of git pull?

Attempts:

upstream ⚡ master) 17≡ $ git status
On branch master
nothing to commit, working tree clean

(upstream ⚡ master) 17≡ $ git pull origin master
From github.com:xxx/yyy  m
 * branch            master     -> FETCH_HEAD
Already up to date.

(upstream ⚡ master) 17≡ $ git pull origin master 2>/dev/null |grep -q "Already up-to-date"

(upstream ⚡ master) 17≡ $

Attempt 2:

$ git pull origin master 2>/dev/null | grep -q "Already up-to-date"; echo $?
1
$

Attempt 3:

$ git pull origin master 2>/dev/null |grep -q "Already up-to-date"; echo $?
1

$ git pull origin master
From github.com:cocos2d/cocos2d-x-docs
 * branch            master     -> FETCH_HEAD
Already up to date.

$ git status
On branch master
nothing to commit, working tree clean

$ git pull origin master 2>/dev/null |grep -q "Already up-to-date"; echo $?
1

Attempt 4:

$ git pull origin master 2>/dev/null |cat
Already up to date.

$ git pull origin master 2>/dev/null | grep -q "Already up-to-date"; echo $?
1

Body:
This will return true (0) if the output of git pull contains Already up-to-date:

git pull | grep -q "Already up-to-date"

Then you can put it into an if-statement to take action conditionally. For example:

if git pull | grep -q "Already up-to-date"; then
    echo "Building stuff"
else
    echo "Not building stuff"
fi

Your attempts are failing because git is printing up to date without the dashes, but the grep command is searching for up-to-date with the dashes, which is what your example output says. (BTW I'm using git 2.7.4 which prints up-to-date.) This sort of output might change between versions of git, so there is a more stable way of checking this sort of output, but I'm not sure what it is :/


问:
didnot write in excel sheet
i want to write my data in excel.but it didnot write in formatted way</p>

```<code>driver.get("https://careernavigator.naukri.com/sales-executive-retail-careers-in-mahindra-and-mahindra-financial-services-15731");
List<WebElement> row = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='rect' and @height='40']"));
        List<WebElement> column = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text']//*[name()='tspan' and (@dy=4 or @dy='3.5')]"));
         for (int i=0;i<column.size();i++) {
            System.out.println(column.get(i).getText());
            XSSFRow row1 = sheet.createRow(i);
            for(int j=0;j<4;j++)
            {
                Cell cell1 = row1.createCell(j);
                cell1.setCellValue(column.get(j).getText());
</code>```

答:
The issue appears to be with your for loop structure. A couple of notes, first, on some observations.
You need a high implicit wait here because the site is slow to load the findings.
Your rows xpath finds nothing, but your column xpath works, even though it did not when I ported to Protactor.
I am sketching an alternative using locator by id "f1" and splitting the resulting text, but it turns out that is equivalent to what your xpath "column" finds.
The key here is to know when a new row begins and when the items are no longer really data you want. Rows start when the index is a multiple of 3, since each row has 3 fields (a name and 2 numbers). Stuff about which we do not care begins with the number 1. I did not write code to put the data in Excel, but I indicated where you would.
Here is my code (yours will vary slightly because of where your chrome driver or whichever is located, as well as because you have the Excel sheet pieces):

```<code>import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class ShonaDriver {

public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver", "bin/chromedriver");
    WebDriver driver = new ChromeDriver();
    driver.manage().timeouts().implicitlyWait(90, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    driver.get(
            "https://careernavigator.naukri.com/sales-executive-retail-careers-in-mahindra-and-mahindra-financial-services-15731");
    /// the row xpath that ws once here found nothing
    List<WebElement> column = driver.findElements(
            By.xpath("(//*[name()='svg'])[2]//*[name()='text']//*[name()='tspan' and (@dy=4 or @dy='3.5')]"));
    int spreadSheetRowNum = 0;
    int spreadSheetColumnNum = 0;
    WebElement f1 = driver.findElement(By.id("f1"));
    for (int i = 0; i < column.size(); i++) {
        if (column.get(i).getText().equalsIgnoreCase("1")) {
            // reached end of meaningful fields
            break;
        }
        if (i % 3 == 0) {// start of new row
            spreadSheetRowNum++;
            System.out.println("here create row: " + spreadSheetRowNum);
            spreadSheetColumnNum = 1;// assuming excel column A is column 1
        } else {
            spreadSheetColumnNum++;
        }

        System.out.println("for column list " + i + " text is:");
        System.out.println(column.get(i).getText());
        System.out.println("write it to row " + spreadSheetRowNum + " column " + spreadSheetColumnNum);
    }

    String[] f1Arr = f1.getText().split("\n");
    System.out.println("if you prefer to use the f1 array, its contents are:");
    for (int i = 0; i < f1Arr.length; i++) {
        System.out.println("f1[" + i + "] = " + f1Arr[i]);
    }
    driver.close();
}
}
</code>```

and here is the output I get indicating what is there and what you need to do at the various steps:

```<code>here create row: 1
for column list 0 text is:
Mahindra and Mahindra Financia..
write it to row 1 column 1
for column list 1 text is:
4.8
write it to row 1 column 2
for column list 2 text is:
2.4
write it to row 1 column 3
here create row: 2
for column list 3 text is:
Tata Motors
write it to row 2 column 1
for column list 4 text is:
5.0
write it to row 2 column 2
for column list 5 text is:
2.6
write it to row 2 column 3
here create row: 3
for column list 6 text is:
Mahindra and Mahindra
write it to row 3 column 1
for column list 7 text is:
4.6
write it to row 3 column 2
for column list 8 text is:
2.9
write it to row 3 column 3
if you prefer to use the f1 array, its contents are:
f1[0] = Mahindra and Mahindra Financia..
f1[1] = 4.8
f1[2] = 2.4
f1[3] = Tata Motors
f1[4] = 5.0
f1[5] = 2.6
f1[6] = Mahindra and Mahindra
f1[7] = 4.6
f1[8] = 2.9
f1[9] = 1
f1[10] = 1
f1[11] = 2
f1[12] = 2
f1[13] = 3
f1[14] = 3
f1[15] = 4
f1[16] = 4
f1[17] = 5
f1[18] = 5
f1[19] = 6
f1[20] = 6
f1[21] = 7
f1[22] = 7
f1[23] = 8
f1[24] = 8
f1[25] = Avg.Exp
f1[26] = Avg.Sal
f1[27] = In lacs
f1[28] = Avg.Exp
f1[29] = Avg.Sal
f1[30] = In lacs
f1[31] = Top Companies
f1[32] = Top Companies
f1[33] = Top Companies
f1[34] = Top Companies
f1[35] = 1.6
f1[36] = 4.9
f1[37] = 2.4
f1[38] = 1.6
f1[39] = 7.0
f1[40] = 2.6
f1[41] = 1.3
f1[42] = 7.2
f1[43] = 2.9
f1[44] = View 22 more Companies.
</code>```

Title: didnot write in excel sheet

Body:
i want to write my data in excel.but it didnot write in formatted way

driver.get("https://careernavigator.naukri.com/sales-executive-retail-careers-in-mahindra-and-mahindra-financial-services-15731");
List<WebElement> row = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='rect' and @height='40']"));
        List<WebElement> column = driver.findElements(By.xpath("(//*[name()='svg'])[2]//*[name()='text']//*[name()='tspan' and (@dy=4 or @dy='3.5')]"));
         for (int i=0;i<column.size();i++) {
            System.out.println(column.get(i).getText());
            XSSFRow row1 = sheet.createRow(i);
            for(int j=0;j<4;j++)
            {
                Cell cell1 = row1.createCell(j);
                cell1.setCellValue(column.get(j).getText());

Body:
The issue appears to be with your for loop structure. A couple of notes, first, on some observations.
You need a high implicit wait here because the site is slow to load the findings.
Your rows xpath finds nothing, but your column xpath works, even though it did not when I ported to Protactor.
I am sketching an alternative using locator by id "f1" and splitting the resulting text, but it turns out that is equivalent to what your xpath "column" finds.
The key here is to know when a new row begins and when the items are no longer really data you want. Rows start when the index is a multiple of 3, since each row has 3 fields (a name and 2 numbers). Stuff about which we do not care begins with the number 1. I did not write code to put the data in Excel, but I indicated where you would.
Here is my code (yours will vary slightly because of where your chrome driver or whichever is located, as well as because you have the Excel sheet pieces):

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class ShonaDriver {

public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver", "bin/chromedriver");
    WebDriver driver = new ChromeDriver();
    driver.manage().timeouts().implicitlyWait(90, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    driver.get(
            "https://careernavigator.naukri.com/sales-executive-retail-careers-in-mahindra-and-mahindra-financial-services-15731");
    /// the row xpath that ws once here found nothing
    List<WebElement> column = driver.findElements(
            By.xpath("(//*[name()='svg'])[2]//*[name()='text']//*[name()='tspan' and (@dy=4 or @dy='3.5')]"));
    int spreadSheetRowNum = 0;
    int spreadSheetColumnNum = 0;
    WebElement f1 = driver.findElement(By.id("f1"));
    for (int i = 0; i < column.size(); i++) {
        if (column.get(i).getText().equalsIgnoreCase("1")) {
            // reached end of meaningful fields
            break;
        }
        if (i % 3 == 0) {// start of new row
            spreadSheetRowNum++;
            System.out.println("here create row: " + spreadSheetRowNum);
            spreadSheetColumnNum = 1;// assuming excel column A is column 1
        } else {
            spreadSheetColumnNum++;
        }

        System.out.println("for column list " + i + " text is:");
        System.out.println(column.get(i).getText());
        System.out.println("write it to row " + spreadSheetRowNum + " column " + spreadSheetColumnNum);
    }

    String[] f1Arr = f1.getText().split("\n");
    System.out.println("if you prefer to use the f1 array, its contents are:");
    for (int i = 0; i < f1Arr.length; i++) {
        System.out.println("f1[" + i + "] = " + f1Arr[i]);
    }
    driver.close();
}
}

and here is the output I get indicating what is there and what you need to do at the various steps:

here create row: 1
for column list 0 text is:
Mahindra and Mahindra Financia..
write it to row 1 column 1
for column list 1 text is:
4.8
write it to row 1 column 2
for column list 2 text is:
2.4
write it to row 1 column 3
here create row: 2
for column list 3 text is:
Tata Motors
write it to row 2 column 1
for column list 4 text is:
5.0
write it to row 2 column 2
for column list 5 text is:
2.6
write it to row 2 column 3
here create row: 3
for column list 6 text is:
Mahindra and Mahindra
write it to row 3 column 1
for column list 7 text is:
4.6
write it to row 3 column 2
for column list 8 text is:
2.9
write it to row 3 column 3
if you prefer to use the f1 array, its contents are:
f1[0] = Mahindra and Mahindra Financia..
f1[1] = 4.8
f1[2] = 2.4
f1[3] = Tata Motors
f1[4] = 5.0
f1[5] = 2.6
f1[6] = Mahindra and Mahindra
f1[7] = 4.6
f1[8] = 2.9
f1[9] = 1
f1[10] = 1
f1[11] = 2
f1[12] = 2
f1[13] = 3
f1[14] = 3
f1[15] = 4
f1[16] = 4
f1[17] = 5
f1[18] = 5
f1[19] = 6
f1[20] = 6
f1[21] = 7
f1[22] = 7
f1[23] = 8
f1[24] = 8
f1[25] = Avg.Exp
f1[26] = Avg.Sal
f1[27] = In lacs
f1[28] = Avg.Exp
f1[29] = Avg.Sal
f1[30] = In lacs
f1[31] = Top Companies
f1[32] = Top Companies
f1[33] = Top Companies
f1[34] = Top Companies
f1[35] = 1.6
f1[36] = 4.9
f1[37] = 2.4
f1[38] = 1.6
f1[39] = 7.0
f1[40] = 2.6
f1[41] = 1.3
f1[42] = 7.2
f1[43] = 2.9
f1[44] = View 22 more Companies.


问:
probability of a categorical column in pandas dataframe
I have a pandas dataframe like this

```<code>0 Age color country
1  23  red    Us
2  25  black  UK
3  19  blue   UK
4  10  red    India
5  15  red    UK
</code>```

What I want to do is to find the probability of each category in 'color' column and have something like this:

```<code>0 Age color country  color_pro
1  23  red    Us       0.6
2  25  black  UK       0.2
3  19  blue   UK       0.2
4  10  red    India    0.6
5  15  red    UK       0.6
</code>```

What should I do for finding probability in a tuple?
like this:

```<code>0 color color_pro
1 red    0.6
2 black  0.2
3 blue   0.2
4 red    0.6
5 red    0.6
</code>```

I want to have the probability in another tuple:

```<code>0 color_pro
1  0.6
2  0.2
3  0.2
4  0.6
5  0.6
</code>```

答:
Use groupby and count to get the values, then calculate proportion.

```<code>df['color_pro'] = df.groupby('color')['color'].transform('count')
df['color_pro'] = df['color_pro'].map(lambda x : x/len(df))
</code>```

OR, clubbing both lines together, we can do this as well.

```<code>df['color_pro'] = df.groupby('color')['color'].transform(lambda x : x.count()/len(df))
</code>```

Body:
I have a pandas dataframe like this

0 Age color country
1  23  red    Us
2  25  black  UK
3  19  blue   UK
4  10  red    India
5  15  red    UK

What I want to do is to find the probability of each category in 'color' column and have something like this:

0 Age color country  color_pro
1  23  red    Us       0.6
2  25  black  UK       0.2
3  19  blue   UK       0.2
4  10  red    India    0.6
5  15  red    UK       0.6

What should I do for finding probability in a tuple?
like this:

0 color color_pro
1 red    0.6
2 black  0.2
3 blue   0.2
4 red    0.6
5 red    0.6

I want to have the probability in another tuple:

0 color_pro
1  0.6
2  0.2
3  0.2
4  0.6
5  0.6

Body:
Use groupby and count to get the values, then calculate proportion.

df['color_pro'] = df.groupby('color')['color'].transform('count')
df['color_pro'] = df['color_pro'].map(lambda x : x/len(df))

OR, clubbing both lines together, we can do this as well.

df['color_pro'] = df.groupby('color')['color'].transform(lambda x : x.count()/len(df))


问:
How to use mat-calendar with reactive forms?
I want to use a calendar component without an input in a reactive form.

I found the component mat-calendar and tried this:

<mat-calendar formControlName="appointment"></mat-calendar>
```

<p>The corresponding TypeScript file has this:</p>

<pre class="lang-js prettyprint-override"><code>this.form = this.formBuilder.group({ appointment: [''] });
</code>```

But an error was shown:

```<code>ERROR Error: No value accessor for form control with name: 'appointment'
</code>```

答:
@prettyfly's answer is spot-on. I just wanted to add that the reason it's not working is that mat-calendar as a component doesn't implement the ControlValueAccessor, which is the interface necessary for FormControls to work.

If you wanted to encapsulate things better, you could take @prettyfly's solution and wrap it in a custom component and implement ControlValueAccessor on it. Only then could you use it the way you described.

Body:
I want to use a calendar component without an input in a reactive form.

I found the component mat-calendar and tried this:

<mat-calendar formControlName="appointment"></mat-calendar>

The corresponding TypeScript file has this:

this.form = this.formBuilder.group({ appointment: [''] });

But an error was shown:

ERROR Error: No value accessor for form control with name: 'appointment'


问:
Possible to get the size of an Elasticsearch index through Java API?
I have been trying to get the size of my Elasticsearch index through the Java API, and I have not been able to find the right call to accomplish this.  I found some suggestions like this one (https://groups.google.com/forum/#!topic/elasticsearch/jNCjCqAS1us), but it is from 2012 and seems to no longer be relevant.

I have been able to get an IndicesStatsResponse the following way:

```<code>IndicesStatsResponse response = client.admin().indices()
        .prepareStats(makeIndexName(tenant.getId()))
        .clear()
        .setStore(true)
        .execute()
        .actionGet();
</code>```

but from this point I cannot find the information that I need.  Is this possible?

答:
With RestHighLevelClient, tested with es 7.1.0:

```<code>RestHighLevelClient client = ...;

var resp = client.getLowLevelClient().performRequest(new Request("GET", "INDEX_NAME/_stats"));
var body =  new ObjectMapper().readTree(resp.getEntity().getContent());
var size = body.get("indices").get("INDEX_NAME").get("primaries").get("store").get("size_in_bytes");
</code>```

I use Jackson to parse json.

Body:
I have been trying to get the size of my Elasticsearch index through the Java API, and I have not been able to find the right call to accomplish this.  I found some suggestions like this one (https://groups.google.com/forum/#!topic/elasticsearch/jNCjCqAS1us), but it is from 2012 and seems to no longer be relevant.

I have been able to get an IndicesStatsResponse the following way:

IndicesStatsResponse response = client.admin().indices()
        .prepareStats(makeIndexName(tenant.getId()))
        .clear()
        .setStore(true)
        .execute()
        .actionGet();

but from this point I cannot find the information that I need.  Is this possible?

Body:
With RestHighLevelClient, tested with es 7.1.0:

RestHighLevelClient client = ...;

var resp = client.getLowLevelClient().performRequest(new Request("GET", "INDEX_NAME/_stats"));
var body =  new ObjectMapper().readTree(resp.getEntity().getContent());
var size = body.get("indices").get("INDEX_NAME").get("primaries").get("store").get("size_in_bytes");

I use Jackson to parse json.


问:
Zeppelin Docker Interpreter Configuration
I have created a Zeppelin docker image in my local system and configured the Spark Interpreter through maven repositories and runned the Zeppelin It worked. But when I stop the Docker and runned again the Interpreter binding was gone. How to solve this Issue ? I want that Interpreter binding one-time so that when ever I stop the docker and run again It has to store those interpreter Binding as it is.</p>

答:
You need 3 volumes for persisting configurations, notebooks and logs.

Note: If you added custom interpreters, you need an additional volume for your interpreter binaries.

```<code>docker volume create zeppelin-conf
docker volume create zeppelin-notebook
docker volume create zeppelin-logs
docker volume create zeppelin-interpreter
</code>```

Run the container with above volumes mounted.

```<code>docker run -d --restart always -p 8080:8080 -v zeppelin-conf:/zeppelin/conf -v zeppelin-notebook:/zeppelin/notebook -v zeppelin-logs:/zeppelin/logs -v zeppelin-interpreter:/zeppelin/interpreter apache/zeppelin:0.8.1
</code>```

If you just want to persist configurations you can use following lines:

```<code>docker volume create zeppelin-conf
docker run -d --restart always -p 8080:8080 -v zeppelin-conf:/zeppelin/conf apache/zeppelin:0.8.1
</code>```

Configurations:/zeppelin/conf

Notebooks: /zeppelin/notebook

Logs: /zeppelin/logs

Interpreters: /zeppelin/interpreter

Edit: The /zeppelin directory is the default home directory for docker images. See Dockerfile. Therefore, you don't need to specify ZEPPELIN_NOTEBOOK_DIR, ZEPPELIN_LOG_DIR or ZEPPELIN_INTERPRETER_DIR environment variables.

Body:
You need 3 volumes for persisting configurations, notebooks and logs.

Note: If you added custom interpreters, you need an additional volume for your interpreter binaries.

docker volume create zeppelin-conf
docker volume create zeppelin-notebook
docker volume create zeppelin-logs
docker volume create zeppelin-interpreter

Run the container with above volumes mounted.

docker run -d --restart always -p 8080:8080 -v zeppelin-conf:/zeppelin/conf -v zeppelin-notebook:/zeppelin/notebook -v zeppelin-logs:/zeppelin/logs -v zeppelin-interpreter:/zeppelin/interpreter apache/zeppelin:0.8.1

If you just want to persist configurations you can use following lines:

docker volume create zeppelin-conf
docker run -d --restart always -p 8080:8080 -v zeppelin-conf:/zeppelin/conf apache/zeppelin:0.8.1

Configurations:/zeppelin/conf

Notebooks: /zeppelin/notebook

Logs: /zeppelin/logs

Interpreters: /zeppelin/interpreter

Edit: The /zeppelin directory is the default home directory for docker images. See Dockerfile. Therefore, you don't need to specify ZEPPELIN_NOTEBOOK_DIR, ZEPPELIN_LOG_DIR or ZEPPELIN_INTERPRETER_DIR environment variables.


问:
%MessageID% different from BTS.MessageID
I am trying to identify the messages I am saving in a folder using MessageID property. However the MessageID values are different from the values I get when I use BTS.MessageID. Why?

In my orchestration I receive a message "myMsg" from a receive port (with receive pipeline: XML Receive). After that I check myMsg(BTS.MessageID) value with

```<code>System.Diagnostics.EventLog.WriteEntry("MessageID", System.String.Format("The Value = {0}", myMsg(BTS.MessageID)));
</code>```

and I get for example this value: c9953bec-72a8-4274-9ea3-d7770c52d4ab

Then I send my message through a send port (with send pipeline: PassThruTransmit)

When the message is saved, the name is: {EE2AB9A1-FA3C-4737-BB02-6AC0C0EA5EBC}.xml

Why are they different? I thought they would be the same.

答:
What you are seeing is the expected behavior.

A Message is a single publication to the MessageBox so the Message published by the Receive Port is different from the Message published by the Orchestration, hence different MessageID values.

While you might 'know' it's the same message, to BizTalk, they're not.

Body:
I am trying to identify the messages I am saving in a folder using MessageID property. However the MessageID values are different from the values I get when I use BTS.MessageID. Why?

In my orchestration I receive a message "myMsg" from a receive port (with receive pipeline: XML Receive). After that I check myMsg(BTS.MessageID) value with

System.Diagnostics.EventLog.WriteEntry("MessageID", System.String.Format("The Value = {0}", myMsg(BTS.MessageID)));

and I get for example this value: c9953bec-72a8-4274-9ea3-d7770c52d4ab

Then I send my message through a send port (with send pipeline: PassThruTransmit)

When the message is saved, the name is: {EE2AB9A1-FA3C-4737-BB02-6AC0C0EA5EBC}.xml

Why are they different? I thought they would be the same.


问:
Repositories / Lazy Loading / Persistance
I have some trouble with the repository pattern. Or maybe just some unclear points. For sake of these questions I have a simple example domain with two entity aggregates.

```<code>public class Category
{
  string Name {get;set;}
  Category Parent {get;set;}
  IList<Category> Children {get;set;}
}

public class Transaction
{
  Category Owner {get;set;}
  string Name
  ... bla bla
}
</code>```

In this particular Domain model these two do not form a single aggregate. As such, I have two standard IRepository implementations for each of the two entities.

Question One: When dealing with validation, such as deletion of a category, a repository needs to do relational checks. Is it a common practise that repositories talk (and as such are injected with references) to other repositories and generate errors, thus keeping it neatly disconnected from the other layers or do they delegate this to the database layer?

Question Two: Similarly, when updating an entity (aggregate) often save/change/delete validation needs to be done on various components. Presumably this is only reasonably doable when you have a unit of work that buffers changes and only commits when all validation succeed?

Question Three: Loading a single category results in an entire object tree to be loaded when not using lazy loading. To limit this the only real option is to implement lazy loading and/or change tracking in your entities?

答:
For all your three questions I would recomend you to implement UnitOfWork pattern. I ususaly implement IUnitOfWork that is a part of my repositories. When I want to work with more then one of my repositories I inject (the same) UnitOfWork into all I want to work with (That is just one of the ways that I prefer). Then when all work is done I call Commit() on my UnitOfWork which does savechanges on entity frameworks context. UnitOfWork is wrapper around entity frameworks context.

Question one: Relational checks are done by database. If something fails entity framework will throw exception and you should handle it in you higher app layer, lets call it service layer where you work with your UnitOfWork.

Question two: Use UnitOfWork pattern.

Question three: You should use lazy loading if you dont want to load the whole object tree.

Repository:

```<code>    public interface IRepository<T>
{
    IUnitOfWork UnitOfWork { get; set; }
    IQueryable<T> All();
    void Delete(T item);
    void Save(T item);
    void Update(T item);
    IQueryable<T> Find(Func<T, bool> expression);
    void Attach(T item);
}
</code>```

UnitOfWork:

```<code>    public interface IUnitOfWork : IDisposable
{
    ObjectContext Context { get; set; }
    void Commit();
    bool LazyLoadingEnabled { get; set; }
    bool ProxyCreationEnabled { get; set; }
    string ConnectionString { get; set; }
}
</code>```

OR here is very simle implementation of UnitOfWork pattern to get you started(Its a bit different from what i described UnitOfWork contains Repositories mine is the other way around...).

Body:
I have some trouble with the repository pattern. Or maybe just some unclear points. For sake of these questions I have a simple example domain with two entity aggregates.

public class Category
{
  string Name {get;set;}
  Category Parent {get;set;}
  IList<Category> Children {get;set;}
}

public class Transaction
{
  Category Owner {get;set;}
  string Name
  ... bla bla
}

In this particular Domain model these two do not form a single aggregate. As such, I have two standard IRepository implementations for each of the two entities.

Question One: When dealing with validation, such as deletion of a category, a repository needs to do relational checks. Is it a common practise that repositories talk (and as such are injected with references) to other repositories and generate errors, thus keeping it neatly disconnected from the other layers or do they delegate this to the database layer?

Question Two: Similarly, when updating an entity (aggregate) often save/change/delete validation needs to be done on various components. Presumably this is only reasonably doable when you have a unit of work that buffers changes and only commits when all validation succeed?

Question Three: Loading a single category results in an entire object tree to be loaded when not using lazy loading. To limit this the only real option is to implement lazy loading and/or change tracking in your entities?

Body:
For all your three questions I would recomend you to implement UnitOfWork pattern. I ususaly implement IUnitOfWork that is a part of my repositories. When I want to work with more then one of my repositories I inject (the same) UnitOfWork into all I want to work with (That is just one of the ways that I prefer). Then when all work is done I call Commit() on my UnitOfWork which does savechanges on entity frameworks context. UnitOfWork is wrapper around entity frameworks context.

Question one: Relational checks are done by database. If something fails entity framework will throw exception and you should handle it in you higher app layer, lets call it service layer where you work with your UnitOfWork.

Question two: Use UnitOfWork pattern.

Question three: You should use lazy loading if you dont want to load the whole object tree.

Repository:

    public interface IRepository<T>
{
    IUnitOfWork UnitOfWork { get; set; }
    IQueryable<T> All();
    void Delete(T item);
    void Save(T item);
    void Update(T item);
    IQueryable<T> Find(Func<T, bool> expression);
    void Attach(T item);
}

UnitOfWork:

    public interface IUnitOfWork : IDisposable
{
    ObjectContext Context { get; set; }
    void Commit();
    bool LazyLoadingEnabled { get; set; }
    bool ProxyCreationEnabled { get; set; }
    string ConnectionString { get; set; }
}

OR here is very simle implementation of UnitOfWork pattern to get you started(Its a bit different from what i described UnitOfWork contains Repositories mine is the other way around...).


问:
How to apply a method to a Pandas Dataframe
I have this dataframe

```<code>   Col1              Col2

0  A (1000 EUR)  C ( 3000 USD)

1  B (2000 CHF)  D ( 4000 GBP)
</code>```

I would like to convert it to

```<code>   Col1  Col2

0  1000  3000

1  2000  4000
</code>```

I know how to create a dataframe (with indexes) for 1 column, but not for multiple columns

This code produces this result

```<code>   Col1

0  1000

1  2000

a = z['Col1'].str.split('(').str[-1].str.split().str[0].apply(pd.to_numeric,errors='coerce')
</code>```

how can I amend the code above to also add col2 (ideally using vectorisation rather than iteration) (so ideally I wouln't want to have to enter the same code for every column)

答:
I would use df.applymap. The difference from df.apply is that df.apply takes a whole series (row or column) as an argument and applies a function where df.applymap takes every element of the DataFrame and applies a function. Try this:

```<code>df = df.applymap(lambda x: pd.to_numeric(str(x).split('(')[1].split()[0], errors='coerce'))
</code>```

print(df)

```<code>   Col1  Col2
0  1000  3000
1  2000  4000
</code>```

df.info()

```<code><class 'pandas.core.frame.DataFrame'>
Int64Index: 2 entries, 0 to 1
Data columns (total 2 columns):
Col1    2 non-null int64
Col2    2 non-null int64
dtypes: int64(2)
memory usage: 48.0 bytes
None
</code>```

Body:
I have this dataframe

   Col1              Col2

0  A (1000 EUR)  C ( 3000 USD)

1  B (2000 CHF)  D ( 4000 GBP)

I would like to convert it to

   Col1  Col2

0  1000  3000

1  2000  4000

I know how to create a dataframe (with indexes) for 1 column, but not for multiple columns

This code produces this result

   Col1

0  1000

1  2000

a = z['Col1'].str.split('(').str[-1].str.split().str[0].apply(pd.to_numeric,errors='coerce')

how can I amend the code above to also add col2 (ideally using vectorisation rather than iteration) (so ideally I wouln't want to have to enter the same code for every column)

Body:
I would use df.applymap. The difference from df.apply is that df.apply takes a whole series (row or column) as an argument and applies a function where df.applymap takes every element of the DataFrame and applies a function. Try this:

df = df.applymap(lambda x: pd.to_numeric(str(x).split('(')[1].split()[0], errors='coerce'))

print(df)

   Col1  Col2
0  1000  3000
1  2000  4000

df.info()

<class 'pandas.core.frame.DataFrame'>
Int64Index: 2 entries, 0 to 1
Data columns (total 2 columns):
Col1    2 non-null int64
Col2    2 non-null int64
dtypes: int64(2)
memory usage: 48.0 bytes
None


问:
MySQL to MongoDB convert integer IDs to ObjectIDs and rebuild references
I am building a new NodeJS application on an existing database. I have converted the existing database from MySQL to MongoDB. I used MySQL Workbench to export the sql data in JSON and then used mongorestore to restore the data to MongoDB. This works.

The existing MySQL database used the autoIncrement property to generate an integer ID number for the primary key.

For example, the "people" table has a primary key "PeopleID", an integer starting from 0 up to about three digits, such as 1, 12, or 123.

Many other tables use this same technique. The "Location" table has a "LocationID" in the same format auto incremented.

In related tables, the primary key is stored as a foreign key, just as a standard relational database.

Here is the newly imported document in MongoDB. Mongo generated an _id for each document.

```<code>{
    "_id": "5ce89632c15df953bbe163e1", // newly created MongoDB ObjectID
    "PersonID": 1, // old primary key
    "LocationID": 12, // old foreign key
    "FirstName": "John",
    "MiddleName": "",
    "LastName": "Smith"
}
</code>```

I want to rebuild all of the references using ObjectIDs instead of the auto incremented integers. So ideally the new document would look like this, with the "foreign key" as an ObjectID reference.

```<code>{
    "_id": "5ce89632c15df953bbe163e1", // Use this as the reference instead of the old "PersonID"
    "PersonID": 1, // old primary key
    "LocationID": "5ce8358ec15df953bab163ea", // example ObjectID as a reference
    "FirstName": "John",
    "MiddleName": "",
    "LastName": "Smith"
}
</code>```

Would it be possible to programmatically rebuild the relationships using references with ObjectIDs instead of the old integer values?

答:
I was able to build the references based on the integer foreign keys by writing a set of queries in Mongoose. The first step is to build an array of dictionaries to map each legacy foreign key to its ObjectID. The next step is to iterate over each document in the target collection, for each item, lookup the ObjectID in the idmap created previously. The last step is to update the target document with the new ObjectID.

In this case, I created a map of the LocationIDs to ObjectIDs and updated the People collection with the new Location_id. I set it up to work as a GET request in a router. This is a quick solution and only works on one mapping at a time. When I have a chance I can make it more scalable and parameterized and possibly even wrap it into a module. Let me know if anyone thinks this is a useful start. I will continue to use it as necessary for this MySQL to MongoDB migration.

```<code>const express = require('express');
const router = express.Router();

/**
 * *** INSTRUCTIONS ***
 *
 * Convert a MySQL relationship to a NoSQL reference
 *
 * People table is the target table that contains the relational primary key PersonID
 * LocationID is a relational foreign key stored as an integer
 * Iterate all documents in People collection
 * Match LocationID integer in the Locations collection to get its unique ObjectID
 * Store the retrieved ObjectID as Location_id in People collection

    MySQL Relationship to convert

    PersonID: {
      type: DataTypes.INTEGER(10).UNSIGNED,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
      unique: true
    },
    LocationID: {
      type: DataTypes.INTEGER(10).UNSIGNED,
      allowNull: true,
      references: {
        model: 'locations',
        key: 'LocationID'
      }

    MongoDB Reference to create

    // Relational primary key autoIncrement ID
    PersonID: {
      type: Number,
      index: true,
      unique: true
    },
    // Relational foreign key autoIncrement ID
    LocationID: {
      type: Number
    },
    // ObjectID reference
    Location_id: {
      type: Schema.Types.ObjectId,
      ref: 'Locations'
    }

 * People
 * Primary Key table = people
 * Foreign Key table = locations
 * Foreign Key field to convert = LocationID
 * New Foreign Key field  = Location_id
 *
 */

// Perform update if true if false read records and log only
const pktable = require('../../models/people');
const fktable = require('../../models/locations');
const prvfkfield = 'LocationID';
const newfkfield = 'Location_id';

router.get('/_id', (req, res, next) => {
  const origin = 'routes/migrate_id.js GET /';

  // Build a dictionary to map old Foreign Key integer to its ObjectID
  async function migrate() {

    // Initialize array to store map of Foreign Keys to ObjectIDs
    let idmap = [];
    // Initialize integer to store number of targets
    let targetcount = 0;
    // Initialize integer to store number of successful results
    let successcount = 0;
    // Initialize integer to store number of skipped results
    let skippedcount = 0;

    // Create a cursor on Foreign Key table
    const fkcursor = fktable.find({}, {[prvfkfield]: 1}).cursor();

    // Build a map of Foreign Keys to ObjectIDs
    await fkcursor.eachAsync(async function (id) {
      idmap.push(id.toObject());
    });

    // Create a cursor on Primary Key table
    const pkcursor = pktable.find().cursor();

    // Iterate each item in cursor and return target record to update
    await pkcursor.eachAsync(async function (target) {

      // Get Previous Foreign Key
      const prvfk = target[prvfkfield];

      targetcount = targetcount + 1;

      // Get ObjectID mapped to the Previous Foriegn Key field
      let objectid = idmap.find(item => item[prvfkfield] === prvfk);

      if (objectid) {
        // Set ObjectID on target document
        target[newfkfield] = objectid;

        try {
          await target.save();
          successcount = successcount + 1;
        } catch (saveerror) {
          console.error(`ERROR: ${JSON.stringify(saveerror)}`);
        }

      } else {
        skippedcount = skippedcount + 1;
      }

    });

    const result = {
      'idmapcount': idmap.length,
      'targetcount': targetcount,
      'successcount': successcount,
      'skippedcount': skippedcount
    };

    return result;

  }

  migrate().then((result) => {
    res.status(200).send(result);
  }).catch((error) => {
    console.error(`migrate failed ${error}`);
    res.status(500).send(`migrate failed ${error}`);
  });

});

module.exports = router;
</code>```

Body:
I am building a new NodeJS application on an existing database. I have converted the existing database from MySQL to MongoDB. I used MySQL Workbench to export the sql data in JSON and then used mongorestore to restore the data to MongoDB. This works.

The existing MySQL database used the autoIncrement property to generate an integer ID number for the primary key.

For example, the "people" table has a primary key "PeopleID", an integer starting from 0 up to about three digits, such as 1, 12, or 123.

Many other tables use this same technique. The "Location" table has a "LocationID" in the same format auto incremented.

In related tables, the primary key is stored as a foreign key, just as a standard relational database.

Here is the newly imported document in MongoDB. Mongo generated an _id for each document.

{
    "_id": "5ce89632c15df953bbe163e1", // newly created MongoDB ObjectID
    "PersonID": 1, // old primary key
    "LocationID": 12, // old foreign key
    "FirstName": "John",
    "MiddleName": "",
    "LastName": "Smith"
}

I want to rebuild all of the references using ObjectIDs instead of the auto incremented integers. So ideally the new document would look like this, with the "foreign key" as an ObjectID reference.

{
    "_id": "5ce89632c15df953bbe163e1", // Use this as the reference instead of the old "PersonID"
    "PersonID": 1, // old primary key
    "LocationID": "5ce8358ec15df953bab163ea", // example ObjectID as a reference
    "FirstName": "John",
    "MiddleName": "",
    "LastName": "Smith"
}

Would it be possible to programmatically rebuild the relationships using references with ObjectIDs instead of the old integer values?

Body:
I was able to build the references based on the integer foreign keys by writing a set of queries in Mongoose. The first step is to build an array of dictionaries to map each legacy foreign key to its ObjectID. The next step is to iterate over each document in the target collection, for each item, lookup the ObjectID in the idmap created previously. The last step is to update the target document with the new ObjectID.

In this case, I created a map of the LocationIDs to ObjectIDs and updated the People collection with the new Location_id. I set it up to work as a GET request in a router. This is a quick solution and only works on one mapping at a time. When I have a chance I can make it more scalable and parameterized and possibly even wrap it into a module. Let me know if anyone thinks this is a useful start. I will continue to use it as necessary for this MySQL to MongoDB migration.

const express = require('express');
const router = express.Router();

/**
 * *** INSTRUCTIONS ***
 *
 * Convert a MySQL relationship to a NoSQL reference
 *
 * People table is the target table that contains the relational primary key PersonID
 * LocationID is a relational foreign key stored as an integer
 * Iterate all documents in People collection
 * Match LocationID integer in the Locations collection to get its unique ObjectID
 * Store the retrieved ObjectID as Location_id in People collection

    MySQL Relationship to convert

    PersonID: {
      type: DataTypes.INTEGER(10).UNSIGNED,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
      unique: true
    },
    LocationID: {
      type: DataTypes.INTEGER(10).UNSIGNED,
      allowNull: true,
      references: {
        model: 'locations',
        key: 'LocationID'
      }

    MongoDB Reference to create

    // Relational primary key autoIncrement ID
    PersonID: {
      type: Number,
      index: true,
      unique: true
    },
    // Relational foreign key autoIncrement ID
    LocationID: {
      type: Number
    },
    // ObjectID reference
    Location_id: {
      type: Schema.Types.ObjectId,
      ref: 'Locations'
    }

 * People
 * Primary Key table = people
 * Foreign Key table = locations
 * Foreign Key field to convert = LocationID
 * New Foreign Key field  = Location_id
 *
 */

// Perform update if true if false read records and log only
const pktable = require('../../models/people');
const fktable = require('../../models/locations');
const prvfkfield = 'LocationID';
const newfkfield = 'Location_id';

router.get('/_id', (req, res, next) => {
  const origin = 'routes/migrate_id.js GET /';

  // Build a dictionary to map old Foreign Key integer to its ObjectID
  async function migrate() {

    // Initialize array to store map of Foreign Keys to ObjectIDs
    let idmap = [];
    // Initialize integer to store number of targets
    let targetcount = 0;
    // Initialize integer to store number of successful results
    let successcount = 0;
    // Initialize integer to store number of skipped results
    let skippedcount = 0;

    // Create a cursor on Foreign Key table
    const fkcursor = fktable.find({}, {[prvfkfield]: 1}).cursor();

    // Build a map of Foreign Keys to ObjectIDs
    await fkcursor.eachAsync(async function (id) {
      idmap.push(id.toObject());
    });

    // Create a cursor on Primary Key table
    const pkcursor = pktable.find().cursor();

    // Iterate each item in cursor and return target record to update
    await pkcursor.eachAsync(async function (target) {

      // Get Previous Foreign Key
      const prvfk = target[prvfkfield];

      targetcount = targetcount + 1;

      // Get ObjectID mapped to the Previous Foriegn Key field
      let objectid = idmap.find(item => item[prvfkfield] === prvfk);

      if (objectid) {
        // Set ObjectID on target document
        target[newfkfield] = objectid;

        try {
          await target.save();
          successcount = successcount + 1;
        } catch (saveerror) {
          console.error(`ERROR: ${JSON.stringify(saveerror)}`);
        }

      } else {
        skippedcount = skippedcount + 1;
      }

    });

    const result = {
      'idmapcount': idmap.length,
      'targetcount': targetcount,
      'successcount': successcount,
      'skippedcount': skippedcount
    };

    return result;

  }

  migrate().then((result) => {
    res.status(200).send(result);
  }).catch((error) => {
    console.error(`migrate failed ${error}`);
    res.status(500).send(`migrate failed ${error}`);
  });

});

module.exports = router;


问:
Kotlin extension function with generic types dependant on the receiver type parameter (without specifying it explicitly)
Sometimes I want to have an extension function on a generic type, whose parameter or return value is a subtype of the given type parameter, but without having to specify that actual type parameter. (maybe, if it isn't clear, the code will clarify it better?)

Using the signature of this answer:

```<code>inline fun <reified U : T, T> Iterable<T>.partitionByType(): Pair<List<U>, List<T>>
</code>```

It forces me to use it as follows:

```<code>val list : List<SomeType>
list.partitionByType<InterestedType, SomeType>()
</code>```

However, what I rather want to write is the following:

```<code>list.partitionByType<InterestedType>()
</code>```

Where InterestedType is a subtype of the type parameter of the list, i.e. SomeType. Both solutions above should then give me Pair<List<InterestedType>, List<SomeType>> as a return value.

This however isn't really possible. The best that comes to my mind is a signature similar as to follows:

```<code> inline fun <reified U : Any> Iterable<Any>.partitionByType(): Pair<List<U>, List<Any>>
</code>```

But then we lose the actual type T/SomeType which was known otherwise. An unchecked cast is still possible on the caller side, but that's not what I am after.

So my question is: is this somehow possible? Having something like U : T in place, without specifying the T? Or is there anything planned in this regard (KEEP or Kotlin issue available)?

For me it sounds like a reasonable feature, at least as long as it is applied on an extension function only. If it's not, what would be the problems of this that I am probably just overlooking/ignoring at the moment?
What I am not really looking for is a workaround (like having an intermediate type), but it may be worth it to have it as answer as well.

The more I think of it. Wouldn't it be more correct, if extension functions on generic types would be declared as follows?

```<code>fun SomeType<T>.extended()
</code>```

instead of

```<code>fun <T> SomeType<T>.extended()
</code>```

Because: if I were under control of SomeType<T> and would add that function there, I wouldn't need any generic type information to declare it, e.g. the following would suffice then:

```<code>fun extended()
</code>```

Same regarding functions with own generic types, e.g.:

```<code>fun <U : T> extended2()
</code>```

Adding that as extension function now forces one to add that T-generic type, although the type on which we would like to apply it, is clearly SomeType<T>:

```<code>fun <T, U: T> SomeType<T>.extended2()
</code>```

答:
Attention: this is a self-answer only for the "intermediate type"-solution-part. I am still looking for an answer if it can be solved without such a workaround or if there are plans to support it.

Example of an intermediate type to solve that issue could look as follows:

```<code>class PartitionType<T>

inline fun <reified T> type() = PartitionType<T>()
inline fun <reified U : T, T> Iterable<T>.partitionBy(type: PartitionType<U> = type()): Pair<List<U>, List<T>> {
    val first = ArrayList<U>()
    val second = ArrayList<T>()
    for (element in this) {
        if (element is U) first.add(element)
        else second.add(element)
    }
    return Pair(first, second)
}
</code>```

This way one can write:

```<code>list.partitionBy(type<InterestedType>())
</code>```

which will result in the Pair<List<InterestedType>, List<SomeType>>-return value, but requires to add that type that will not be used anyhow (except indirectly; an inline class may make sense here, but ... what should the parameter be then?).

The key here is to just pass the interested type(s) as parameter instead of specifying it as a requested generic type (partitionBy<InterestedType, SomeType>() would still work (or more correctly: would still be needed)).

Maybe I used the wrong words and that's why I couldn't find anything suitable yet. Or maybe it's just something I want to have and no one else? At least for me it sounds as if it could/should work.

Another variant is to explicitly specify all the extension functions on types that are known already, but then we need to be aware of platform clashes, e.g.:

```<code>@JvmName("partitionSomeTypeByType") // only needed if we require more partitionByType-functions with differing generic type parameters
inline fun <reified U : SomeType> Iterable<SomeType>.partitionByType() = partitionBy<U, SomeType>()
</code>```

But again only a workaround.

Body:
Sometimes I want to have an extension function on a generic type, whose parameter or return value is a subtype of the given type parameter, but without having to specify that actual type parameter. (maybe, if it isn't clear, the code will clarify it better?)

Using the signature of this answer:

inline fun <reified U : T, T> Iterable<T>.partitionByType(): Pair<List, List<T>>

It forces me to use it as follows:

val list : List<SomeType>
list.partitionByType<InterestedType, SomeType>()

However, what I rather want to write is the following:

list.partitionByType<InterestedType>()

Where InterestedType is a subtype of the type parameter of the list, i.e. SomeType. Both solutions above should then give me Pair<List<InterestedType>, List<SomeType>> as a return value.

This however isn't really possible. The best that comes to my mind is a signature similar as to follows:

 inline fun <reified U : Any> Iterable<Any>.partitionByType(): Pair<List, List<Any>>

But then we lose the actual type T/SomeType which was known otherwise. An unchecked cast is still possible on the caller side, but that's not what I am after.

So my question is: is this somehow possible? Having something like U : T in place, without specifying the T? Or is there anything planned in this regard (KEEP or Kotlin issue available)?

For me it sounds like a reasonable feature, at least as long as it is applied on an extension function only. If it's not, what would be the problems of this that I am probably just overlooking/ignoring at the moment?
What I am not really looking for is a workaround (like having an intermediate type), but it may be worth it to have it as answer as well.

The more I think of it. Wouldn't it be more correct, if extension functions on generic types would be declared as follows?

fun SomeType<T>.extended()

instead of

fun <T> SomeType<T>.extended()

Because: if I were under control of SomeType<T> and would add that function there, I wouldn't need any generic type information to declare it, e.g. the following would suffice then:

fun extended()

Same regarding functions with own generic types, e.g.:

fun  extended2()

Adding that as extension function now forces one to add that T-generic type, although the type on which we would like to apply it, is clearly SomeType<T>:

fun <T, U: T> SomeType<T>.extended2()

Body:
Attention: this is a self-answer only for the "intermediate type"-solution-part. I am still looking for an answer if it can be solved without such a workaround or if there are plans to support it.

Example of an intermediate type to solve that issue could look as follows:

class PartitionType<T>

inline fun <reified T> type() = PartitionType<T>()
inline fun <reified U : T, T> Iterable<T>.partitionBy(type: PartitionType<U> = type()): Pair<List<U>, List<T>> {
    val first = ArrayList<U>()
    val second = ArrayList<T>()
    for (element in this) {
        if (element is U) first.add(element)
        else second.add(element)
    }
    return Pair(first, second)
}

This way one can write:

list.partitionBy(type<InterestedType>())

which will result in the Pair<List<InterestedType>, List<SomeType>>-return value, but requires to add that type that will not be used anyhow (except indirectly; an inline class may make sense here, but ... what should the parameter be then?).

The key here is to just pass the interested type(s) as parameter instead of specifying it as a requested generic type (partitionBy<InterestedType, SomeType>() would still work (or more correctly: would still be needed)).

Maybe I used the wrong words and that's why I couldn't find anything suitable yet. Or maybe it's just something I want to have and no one else? At least for me it sounds as if it could/should work.

Another variant is to explicitly specify all the extension functions on types that are known already, but then we need to be aware of platform clashes, e.g.:

@JvmName("partitionSomeTypeByType") // only needed if we require more partitionByType-functions with differing generic type parameters
inline fun <reified U : SomeType> Iterable<SomeType>.partitionByType() = partitionBy<U, SomeType>()

But again only a workaround.


问:
How can I print the next line to the current line provided they start with certain words?
I want to print the next line on the current line provided the current line starts with "This" and the next line starts with "That" of a file and write it back to the same file. How can I achieve this?

Note: I have some other lines in my file that I want to maintain as they are.

```<code>prev = ''
with open("myfile.txt", 'r') as f:
    for line in f:
        if line.startswith('This') and prev.startswith('That'):
        # Attach 'That' line with 'This' line
        prev = line
#Once done, write back to myfile.txt
</code>```

INPUT:

```<code>Foo
This is my current line
That is my next line
Bar
</code>```

OUTPUT:

```<code>Foo
This is my current line That is my next line
Bar
</code>```

答:
Here

```<code>with open('myfile.txt', 'r') as f:
    new_lines = []
    lines = [l.strip() for l in f.readlines()]
    for idx, line in enumerate(lines):
        if idx > 0:
            if line.startswith('This') and lines[idx - 1].startswith('That'):
                new_lines.pop()
                new_lines.append('{} {}'.format(line, lines[idx - 1]))
            else:
                new_lines.append(line)
        else:
            new_lines.append(line)

with open('myfile.txt', 'w') as f:
    for line in new_lines:
        f.write(line + '\n')
</code>```

myfile.txt (before)

```<code>afdfsdfdf dfsdfsdfs
That is my next line
This is my current line
sadgsdfg sadfgsgdfg
dfgdfgdfgdfgd
dfgdfgdfgdfgdf
That is my next line
sdftgertgertge
This is my current line
srgegergegyb  dfgtyrtyrty
That is my next line
This is my current line
eferer erwer
</code>```

myfile.txt (after)

```<code>afdfsdfdf dfsdfsdfs
This is my current line That is my next line
sadgsdfg sadfgsgdfg
dfgdfgdfgdfgd
dfgdfgdfgdfgdf
That is my next line
sdftgertgertge
This is my current line
srgegergegyb  dfgtyrtyrty
This is my current line That is my next line
eferer erwer
</code>```

Body:
I want to print the next line on the current line provided the current line starts with "This" and the next line starts with "That" of a file and write it back to the same file. How can I achieve this?

Note: I have some other lines in my file that I want to maintain as they are.

prev = ''
with open("myfile.txt", 'r') as f:
    for line in f:
        if line.startswith('This') and prev.startswith('That'):
        # Attach 'That' line with 'This' line
        prev = line
#Once done, write back to myfile.txt

INPUT:

Foo
This is my current line
That is my next line
Bar

OUTPUT:

Foo
This is my current line That is my next line
Bar

Body:
Here

with open('myfile.txt', 'r') as f:
    new_lines = []
    lines = [l.strip() for l in f.readlines()]
    for idx, line in enumerate(lines):
        if idx > 0:
            if line.startswith('This') and lines[idx - 1].startswith('That'):
                new_lines.pop()
                new_lines.append('{} {}'.format(line, lines[idx - 1]))
            else:
                new_lines.append(line)
        else:
            new_lines.append(line)

with open('myfile.txt', 'w') as f:
    for line in new_lines:
        f.write(line + '\n')

myfile.txt (before)

afdfsdfdf dfsdfsdfs
That is my next line
This is my current line
sadgsdfg sadfgsgdfg
dfgdfgdfgdfgd
dfgdfgdfgdfgdf
That is my next line
sdftgertgertge
This is my current line
srgegergegyb  dfgtyrtyrty
That is my next line
This is my current line
eferer erwer

myfile.txt (after)

afdfsdfdf dfsdfsdfs
This is my current line That is my next line
sadgsdfg sadfgsgdfg
dfgdfgdfgdfgd
dfgdfgdfgdfgdf
That is my next line
sdftgertgertge
This is my current line
srgegergegyb  dfgtyrtyrty
This is my current line That is my next line
eferer erwer


答:
You can use the applymap method of a pandas dataframe. It would look something like:

```<code>import re

function_to_apply = lambda x: re.search("[0-9]+", x).group()
your_dataframe.applymap(function_to_apply)
</code>```

Possible something like that would work in your case, and would certainly be a bit simpler!

Title: How to apply a method to a Pandas Dataframe

Body:
You can use the applymap method of a pandas dataframe. It would look something like:

import re

function_to_apply = lambda x: re.search("[0-9]+", x).group()
your_dataframe.applymap(function_to_apply)

Possible something like that would work in your case, and would certainly be a bit simpler!


问:
How to call a variable from a matrix... from a list?
Basically, it's in the title.
With more details though, I have four parameters set that need to be organised in matrices, that I organised in a list (Alphaset), each having 4 variables. But I need to call in specific variables into a loop where it will go through an equation and should give me a plot.

Me and my poor knowledge of R tried different combination that resulted in being inefficient, such as "Alphaset[2,1,1]" or "Alphaset[2(1,1)]"
(this is an exemple where I want to display the variable that's first row first column of the second matrix).

```<code>#Parameters set on types (lambda 1, lambda 2, alphas)

Lambda1set<-c(5,5,3,3.2)
Lambda2set<-c(4,4,5,3)
Alphaset<-list(matrix(c(0.01, 0.007, 0.0045, 0.01),ncol = 2, byrow = TRUE),
            matrix(c(0.01, 0.003, 0.007, 0.01),ncol = 2, byrow = TRUE),
            matrix(c(0.01, 0.0055, 0.003, 0.01),ncol = 2, byrow = TRUE),
            matrix(c(0.005, 0.005, 0.0045, 0.004),ncol = 2, byrow = TRUE))

#Creating vectors
TimeVec<-seq(0,years,1)
N1<-matrix(0,4,years+1)
N2<-matrix(0,4,years+1)

#INITIALIZATION
N0 <- 40
N1[1] <-N0
N2[1] <-N0

for (t in 1:years){
  for(i in 1:4){
  N1[i,t+1]<-(Lambda1set[i]*N1[i,t])/(1+alphs[1,1]*N1[i,t]+alphs[1,2]*N2[i,t])
  N2[i,t+1]<-(lambda2set[i]*N2[i,t])/(1+alphs[2,1]*N1[i,t]+alphs[2,2]*N2[i,t])
  }
}

plot(TimeVec,N1,type="l",xlab='Time (years)',ylab='Population Density',col='blue',
     lwd = 2,ylim = c(0,400))
</code>```

Here you can see in the equations the "alphs[..,..]" are supposed to represent which variable from each i matrices I want to use.

But how do I call them in regard to my list of matrices ?

答:
Just define the alphs variable as follow:

```<code>alphs <- Alphaset[[i]]
</code>```

just after the line 21: for(i in 1:4){

Body:
Basically, it's in the title.
With more details though, I have four parameters set that need to be organised in matrices, that I organised in a list (Alphaset), each having 4 variables. But I need to call in specific variables into a loop where it will go through an equation and should give me a plot.

Me and my poor knowledge of R tried different combination that resulted in being inefficient, such as "Alphaset[2,1,1]" or "Alphaset[2(1,1)]"
(this is an exemple where I want to display the variable that's first row first column of the second matrix).

#Parameters set on types (lambda 1, lambda 2, alphas)

Lambda1set<-c(5,5,3,3.2)
Lambda2set<-c(4,4,5,3)
Alphaset<-list(matrix(c(0.01, 0.007, 0.0045, 0.01),ncol = 2, byrow = TRUE),
            matrix(c(0.01, 0.003, 0.007, 0.01),ncol = 2, byrow = TRUE),
            matrix(c(0.01, 0.0055, 0.003, 0.01),ncol = 2, byrow = TRUE),
            matrix(c(0.005, 0.005, 0.0045, 0.004),ncol = 2, byrow = TRUE))

#Creating vectors
TimeVec<-seq(0,years,1)
N1<-matrix(0,4,years+1)
N2<-matrix(0,4,years+1)

#INITIALIZATION
N0 <- 40
N1[1] <-N0
N2[1] <-N0

for (t in 1:years){
  for(i in 1:4){
  N1[i,t+1]<-(Lambda1set[i]*N1[i,t])/(1+alphs[1,1]*N1[i,t]+alphs[1,2]*N2[i,t])
  N2[i,t+1]<-(lambda2set[i]*N2[i,t])/(1+alphs[2,1]*N1[i,t]+alphs[2,2]*N2[i,t])
  }
}

plot(TimeVec,N1,type="l",xlab='Time (years)',ylab='Population Density',col='blue',
     lwd = 2,ylim = c(0,400))

Here you can see in the equations the "alphs[..,..]" are supposed to represent which variable from each i matrices I want to use.

But how do I call them in regard to my list of matrices ?

Body:
Just define the alphs variable as follow:

alphs <- Alphaset[[i]]

just after the line 21: for(i in 1:4){


问:
Addtional parameter with @ngrx/entity
I want to keep employee array and page loading status in store state. So my initial state will look like this

```<code>const initialState = {
  isLoading: false,
  employees: []
  };
</code>```

Now i want to use @ngrx/entity for employee instead of array. The documentation only show the demo for using entity with entire state.

How can i use entity for only one property rather than entire state?

If it's not possible what is the alternative for above scenario?

答:
See the docs for an example:</p>

```<code>import { EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity';

export interface User {
  id: string;
  name: string;
}

export interface State extends EntityState<User> {
  // additional entities state properties
  selectedUserId: number;
}

export const adapter: EntityAdapter<User> = createEntityAdapter<User>();
</code>```

Title: Addtional parameter with @ngrx/entity

Body:
I want to keep employee array and page loading status in store state. So my initial state will look like this

const initialState = {
  isLoading: false,
  employees: []
  };

Now i want to use @ngrx/entity for employee instead of array. The documentation only show the demo for using entity with entire state.

How can i use entity for only one property rather than entire state?

If it's not possible what is the alternative for above scenario?

Body:
See the docs for an example:

import { EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity';

export interface User {
  id: string;
  name: string;
}

export interface State extends EntityState<User> {
  // additional entities state properties
  selectedUserId: number;
}

export const adapter: EntityAdapter<User> = createEntityAdapter<User>();


问:
Reading MDSYS.SDO_GEOMETRY column value into JAVA entity fails to wrong column type
I am using hibernate 4.1.12 and trying to have MDSYS.SDO_GEOMETRY column from Oracle db in my JAVA entity.

In pom.xml, I have:

```<code><dependency>
    <groupId>oracle</groupId>
    <artifactId>sdoapi</artifactId>
    <version>11.2.0</version>
</dependency>
</code>```

In entity, I have:

```<code>@Column(name = "GEOMETRY", nullable = false)
private JGeometry geometry;
</code>```

When starting the application, I get following in validation process:

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [META-INF/spring/jpa-em-config.xml]:

Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: mapperPU] Unable to build EntityManagerFactory

Caused by: org.hibernate.HibernateException: Wrong column type in DB_USER1.WORK_AREA for column GEOMETRY.
Found: sdo_geometry, expected: raw(255)
</code>```

Maybe this is not the correct way to do MDSYS.SDO_GEOMETRY column reading to JAVA entity? How should this be done?

答:
With Oracle10gDialect and following definitions it worked in my case.

import com.vividsolutions.jts.geom.Geometry;

```<code>@Type(type = "org.hibernate.spatial.GeometryType")
@Column(name = "GEOMETRY", columnDefinition = "MDSYS.SDO_GEOMETRY")
public Geometry getGeometry() {
    return this.geometry;
}
</code>```

Body:
I am using hibernate 4.1.12 and trying to have MDSYS.SDO_GEOMETRY column from Oracle db in my JAVA entity.

In pom.xml, I have:

<dependency>
    <groupId>oracle</groupId>
    <artifactId>sdoapi</artifactId>
    <version>11.2.0</version>
</dependency>

In entity, I have:

@Column(name = "GEOMETRY", nullable = false)
private JGeometry geometry;

When starting the application, I get following in validation process:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [META-INF/spring/jpa-em-config.xml]:

Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: mapperPU] Unable to build EntityManagerFactory

Caused by: org.hibernate.HibernateException: Wrong column type in DB_USER1.WORK_AREA for column GEOMETRY.
Found: sdo_geometry, expected: raw(255)

Maybe this is not the correct way to do MDSYS.SDO_GEOMETRY column reading to JAVA entity? How should this be done?

Body:
With Oracle10gDialect and following definitions it worked in my case.

import com.vividsolutions.jts.geom.Geometry;

@Type(type = "org.hibernate.spatial.GeometryType")
@Column(name = "GEOMETRY", columnDefinition = "MDSYS.SDO_GEOMETRY")
public Geometry getGeometry() {
    return this.geometry;
}


问:
Identify Locale Date string correctly
I have a date string that is formatted depending on the language/locale of the browser. For example, "03/05/2019" in en-US is March 5, 2019 (mm/dd/yyyy) but in en-NZ, it's May 3, 2019 (dd/mm/yyyy).

I need to know how to convert the string to date using JavaScript with the corresponding locale. I cannot hardcode the format because the locale really depends on the browser. I tried using Moment.js but I cannot seem to make it work. It returns invalid date for dates like "16/05/2019". It looks like it's not following the locale which I set to en-NZ.

Here is the momentjs code that I have tried:

```<code>moment().locale('en-NZ').format('L')
</code>```

This will return the en-NZ format of the current date which is 27/05/2019 but when I try to include a date string:

```<code>moment('16/05/2019').locale('en-NZ').format('L')
</code>```

This returns 'Invalid Date'. Any suggestions on how to do it or even a different plugin that I can use? Thanks.

答:
Thank you for your suggestions but I think I found a solution and answered my own question. I was using momentjs incorrectly. The date, long date format, and locale are all parameters of the moment function. Therefore, it identified the date correctly and now, I can format it to any format I want. (assuming you have a code to get the browser locale like what @Dean Meehan suggested)

```<code>new Date(moment('16/05/2019','L','en-nz').format('MM/DD/YYYY'))
</code>```

So 16/05/2019 on en-NZ is read as May 16, 2019.

Title: Identify Locale Date string correctly

Body:
I have a date string that is formatted depending on the language/locale of the browser. For example, "03/05/2019" in en-US is March 5, 2019 (mm/dd/yyyy) but in en-NZ, it's May 3, 2019 (dd/mm/yyyy).

I need to know how to convert the string to date using JavaScript with the corresponding locale. I cannot hardcode the format because the locale really depends on the browser. I tried using Moment.js but I cannot seem to make it work. It returns invalid date for dates like "16/05/2019". It looks like it's not following the locale which I set to en-NZ.

Here is the momentjs code that I have tried:

moment().locale('en-NZ').format('L')

This will return the en-NZ format of the current date which is 27/05/2019 but when I try to include a date string:

moment('16/05/2019').locale('en-NZ').format('L')

This returns 'Invalid Date'. Any suggestions on how to do it or even a different plugin that I can use? Thanks.

Body:
Thank you for your suggestions but I think I found a solution and answered my own question. I was using momentjs incorrectly. The date, long date format, and locale are all parameters of the moment function. Therefore, it identified the date correctly and now, I can format it to any format I want. (assuming you have a code to get the browser locale like what @Dean Meehan suggested)

new Date(moment('16/05/2019','L','en-nz').format('MM/DD/YYYY'))

So 16/05/2019 on en-NZ is read as May 16, 2019.


问:
how to display the contents of a tab in the workspace of Jtabbedpane?
i'v put a jpanel on the tab of Jtabbedpane which is at the left side ,nw when the tab is clicked i want to display labels and textfields in the workspace of the tabbedpane,plz hlp. </p>

答:
When you say 'workspace of the tabbedpane' I think you are referring to your JPanel?

You must attach the JLabels and JTextfields to the JPanel using JPanel.add() before you add the JPanel to the JTabbedPane.


问:
How can I save an Excel sheet from R without blank lines?
I'm working with a large matrix which has some lines with blank IDs. And I want to save only the non.blank lines in a Excel sheet.

Assuming that the IDs are the first column, this is what I am currently doing:

```<code>k <- which(is.na(MyData[,1]))
if (length(k) > 0) MyData <- MyData[-k,]
library(XLConnect)
wb <- loadWorkbook("MyFolder\\MyFile.xls")
writeWorksheet(wb,data=MyData,sheet=1,header=TRUE)
saveWorkbook(wb)
</code>```

I don't know why, but the resulting Excel file has the full content of MyData, plus a sequence of blank lines in the same numbers of the blank ID ones.

For example, if MyData has 1000 rows and 5 blank IDs, I get an final MyData with 995 rows. But the final Excel file has those 995 rows plus 5 blank rows in the end!

Since I need to submit a xls (not xlsx) file with no blank rows, how can I solve it?

Many thanks in advance.

答:
I'm not familiar with the package, but this should work:

```<code>library(XLConnect)
wb <- loadWorkbook("MyFolder\\MyFile.xls")
writeWorksheet(wb,data=MyData[!is.na(MyData$ID), ],sheet=1,header=TRUE)
saveWorkbook(wb)
</code>```

Your code should have worked as both this and your Q should successfully filter the NAs. You may want to see if they are just blank strings instead of NAs. In that case, you'd do:

```<code>writeWorksheet(wb,data=MyData[MyData$ID != "", ],sheet=1,header=TRUE)
</code>```

Body:
I'm working with a large matrix which has some lines with blank IDs. And I want to save only the non.blank lines in a Excel sheet.

Assuming that the IDs are the first column, this is what I am currently doing:

k <- which(is.na(MyData[,1]))
if (length(k) > 0) MyData <- MyData[-k,]
library(XLConnect)
wb <- loadWorkbook("MyFolder\\MyFile.xls")
writeWorksheet(wb,data=MyData,sheet=1,header=TRUE)
saveWorkbook(wb)

I don't know why, but the resulting Excel file has the full content of MyData, plus a sequence of blank lines in the same numbers of the blank ID ones.

For example, if MyData has 1000 rows and 5 blank IDs, I get an final MyData with 995 rows. But the final Excel file has those 995 rows plus 5 blank rows in the end!

Since I need to submit a xls (not xlsx) file with no blank rows, how can I solve it?

Many thanks in advance.

Body:
I'm not familiar with the package, but this should work:

library(XLConnect)
wb <- loadWorkbook("MyFolder\\MyFile.xls")
writeWorksheet(wb,data=MyData[!is.na(MyData$ID), ],sheet=1,header=TRUE)
saveWorkbook(wb)

Your code should have worked as both this and your Q should successfully filter the NAs. You may want to see if they are just blank strings instead of NAs. In that case, you'd do:

writeWorksheet(wb,data=MyData[MyData$ID != "", ],sheet=1,header=TRUE)


问:
Laravel pass subdomain as a value to another route
now I have this code

```<code>    Route::group(['domain' => '{subdomain}.'.env('DOMAIN')], function()
{
    Route::any('/', function($subdomain)
    {
        Route::get('{/subdomain}/{identifier}/{reCreate?}','AController@index');
    });
});
</code>```

I want to pass {subdomain} to  Route::get('{/subdomain}/{identifier}/{reCreate?}','AController@index'); for when call subdomain.localhost/identifier I call AController@index I should pass the value of subdomain to AController@index

答:
I think by using Route::input('subdomain'); you can access the subdomain parameter.

Inside AController:

```<code>public function index() {
   dd(Route::input('subdomain'));
}
</code>```

Body:
now I have this code

    Route::group(['domain' => '{subdomain}.'.env('DOMAIN')], function()
{
    Route::any('/', function($subdomain)
    {
        Route::get('{/subdomain}/{identifier}/{reCreate?}','AController@index');
    });
});

I want to pass {subdomain} to  Route::get('{/subdomain}/{identifier}/{reCreate?}','AController@index'); for when call subdomain.localhost/identifier I call AController@index I should pass the value of subdomain to AController@index

Body:
I think by using Route::input('subdomain'); you can access the subdomain parameter.

Inside AController:

public function index() {
   dd(Route::input('subdomain'));
}


问:
Update Multiple rows with all diffrent values
I have a spread sheet with all the User ID's and their updated address's, I have over 10K user accounts that I need to update with their new addresses, I cant write a script for all the 10K Users, how would I go about this?

If I were to use Update Users Set Address=('','') where UserId In ()
This gives me Error's. With no info just saying syntax Error new address.

I have few UserID's and Values I could showcase, for example:
I have UserID's (1,2,3) and the Address is (1 Street,2 Street, 3 Street)

How can I run one script to update all 3 Records at once?
I expect the output updating all 3 files with the updated address.
Thanks for all your Help in Advance!

答:
Load the data into a table into the database and then use update with a join:

```<code>update o
    set address = n.address
    from originaltable o join
         newaddresses n
         on o.userid = n.userid;
</code>```

Body:
Load the data into a table into the database and then use update with a join:

update o
    set address = n.address
    from originaltable o join
         newaddresses n
         on o.userid = n.userid;


问:
Hyperledger Fabric- HistoryQueryIterator using nodejs
I am trying to create hyperledger chaincode using nodejs and fabric-shim is new to me.
I am trying to fetch history of an asset using getHistoryForKey().

I tried iterating through HistoryQueryIterator using while but i was not successful.

```<code>@Transaction()
public async getAllHistory(ctx:Context,key:string):Promise<void>{
    const history = await ctx.stub.getHistoryForKey(key);
     while(history.next()){
         history.next().then(value =>{
            console.info("================>",value.toString());
         })
         .catch(err =>{
            console.info("ERROR",err);
         })
     }

}
</code>```

The above code gives [object Object].

If someone could point me in the right direction it would be helpful.

答:
You can find an example about how to use getHistoryForKey in the official Hyperledger Fabric samples ( chaincodes/marbles02).

https://github.com/hyperledger/fabric-samples/blob/release-1.4/chaincode/marbles02/node/marbles_chaincode.js

Body:
I am trying to create hyperledger chaincode using nodejs and fabric-shim is new to me.
I am trying to fetch history of an asset using getHistoryForKey().

I tried iterating through HistoryQueryIterator using while but i was not successful.

@Transaction()
public async getAllHistory(ctx:Context,key:string):Promise<void>{
    const history = await ctx.stub.getHistoryForKey(key);
     while(history.next()){
         history.next().then(value =>{
            console.info("================>",value.toString());
         })
         .catch(err =>{
            console.info("ERROR",err);
         })
     }

}

The above code gives [object Object].

If someone could point me in the right direction it would be helpful.