问:
Cannot return array and use in another method
I am trying to call my array in my printmessage method. I am getting an error as if I cannot access it outside my method getSum(). Any help? Thanks</p>

```<code>    public int getSum(int input) {
        int empty[] = new int[input] ;

        for (int i =0;i < input;i++) {
            int num = scan.nextInt();
            empty[i] = num;
            sum = num +sum;
        }
        return sum && empty[];
    }

    public void Printmessage(){
        for(int j = 0; j< empty.length; j++) {
            System.out.print(empty[j]+ " ");
        }
    }
}
</code>```

答:
In your Printmessage method, you just reference the array empty.  empty is a method variable, so it is only accessible within the getSum method.  In order to get the return value, you need to actually call the method.

You also return from your getSum method with the following line:

```<code>return sum && empty[];
</code>```

I believe you are trying to return both an int and an int array here.  You can only return one object from a method.  Since sum appears to be an instance variable (you don't declare it in your method), I believe you want to just return the array.

To eliminate both of the above problems, try the following code:

```<code>public int[] getSum(int input) { //declare the return type as int[] rather than int, since we are now returning an array
    int[] empty = new int[input] ; //move the square brackets over to be after int, not after empty

    for (int i =0;i < input;i++) {
        int num = scan.nextInt();
        empty[i] = num;
        sum = num +sum;

    }
    return empty; //only return one object

}
public void Printmessage(){
    //call the getSum method:
    int[] empty = getSum(5); //here 5 is just an arbitrary value

    for(int j = 0; j< empty.length; j++) {
        System.out.print(empty[j]+ " ");
    }
}
</code>```

Body:
I am trying to call my array in my printmessage method. I am getting an error as if I cannot access it outside my method getSum(). Any help? Thanks

    public int getSum(int input) {
        int empty[] = new int[input] ;

        for (int i =0;i < input;i++) {
            int num = scan.nextInt();
            empty[i] = num;
            sum = num +sum;
        }
        return sum && empty[];
    }

    public void Printmessage(){
        for(int j = 0; j< empty.length; j++) {
            System.out.print(empty[j]+ " ");
        }
    }
}

Body:
In your Printmessage method, you just reference the array empty.  empty is a method variable, so it is only accessible within the getSum method.  In order to get the return value, you need to actually call the method.

You also return from your getSum method with the following line:

return sum && empty[];

I believe you are trying to return both an int and an int array here.  You can only return one object from a method.  Since sum appears to be an instance variable (you don't declare it in your method), I believe you want to just return the array.

To eliminate both of the above problems, try the following code:

public int[] getSum(int input) { //declare the return type as int[] rather than int, since we are now returning an array
    int[] empty = new int[input] ; //move the square brackets over to be after int, not after empty

    for (int i =0;i < input;i++) {
        int num = scan.nextInt();
        empty[i] = num;
        sum = num +sum;

    }
    return empty; //only return one object

}
public void Printmessage(){
    //call the getSum method:
    int[] empty = getSum(5); //here 5 is just an arbitrary value

    for(int j = 0; j< empty.length; j++) {
        System.out.print(empty[j]+ " ");
    }
}


来源: stackexchange

问:
excel vba - how to increment a cell address?
the find function returns a range with address like $A$1

how do I increment it and use it to print the value of cell B1?

答:
Use .Offset(x, y) to return the cell which is x units down and y units to the right.

For example

```<code>Range("A1").Offset(0, 1)   => Range("B1")
</code>```

Also note there is .Resize(x, y) to take a single cell and make it table with x rows and y columns

```<code>Range("A1").Resize(10,3)   => Range("A1:C10")
</code>```

Finally, use .Cells(x, y) to treat the cell as a table. So to read 10 rows starting from A1 you do the following

```<code>For i = 1 to 10
    x = Range("A1").Cells(i,1).Value
    Debug.Print x
Next i
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Use .Offset(x, y) to return the cell which is x units down and y units to the right.

For example

Range("A1").Offset(0, 1)   => Range("B1")

Also note there is .Resize(x, y) to take a single cell and make it table with x rows and y columns

Range("A1").Resize(10,3)   => Range("A1:C10")

Finally, use .Cells(x, y) to treat the cell as a table. So to read 10 rows starting from A1 you do the following

For i = 1 to 10
    x = Range("A1").Cells(i,1).Value
    Debug.Print x
Next i


问:
How do I use an if statement in a Vue.js function?
What I am trying to do is have the result function offer two different equations:

return this.number1*(this.number2/100) if the {{ basketballbet.odds }} value is positive

return this.number1*(100/this.number2) if the {{ basketballbet.odds }} value is negative.

Does anyone know if this is possible?

code:

```<code><div id="odds_calculator">
<p>Placing <input type="number" name="number1" v-on:input= "update_number1"> on this bet would win you $XXXX if you were to win the bet.</p>

  <p>Bet Amount: [[ number1  ]] </p>
  <p>Odds: {{ basketballbet.odds }}</p>

  <hr>
  <p>Result: [[ result() ]]</p>
</div>
<script>
new Vue({
  delimiters: ['[[',']]'],
  el: '#odds_calculator',
  data: {
    number1: 0,
    number2: {{ basketballbet.odds }},
  },
  methods: {
    update_number1: function (event) {
      this.number1 = event.target.value;
    },
    result: function () {

      return this.number1*(this.number2/100);
    },

  },
});
</script>
</code>```

答:
```<code>result: function() {
  if (this.number1 > 0) {
    return this.number1 * (this.number2 / 100);
  } else if (this.number1 < 0) {
    return this.number1 * (100 / this.number2);
  }
},
</code>```

Body:
What I am trying to do is have the result function offer two different equations:

return this.number1*(this.number2/100) if the {{ basketballbet.odds }} value is positive

return this.number1*(100/this.number2) if the {{ basketballbet.odds }} value is negative.

Does anyone know if this is possible?

code:

Placing <input type="number" name="number1" v-on:input= "update_number1"> on this bet would win you $XXXX if you were to win the bet.

Bet Amount: [[ number1  ]]

Odds: {{ basketballbet.odds }}

Result: [[ result() ]]


问:
R Indicate If Group Has Value
```<code>data=data.frame(GROUP=c(1,1,1,2,2,2,3,3,3,4,4,4),
VAR=c('A','B','C','A','B','C','A','B','C','A','B','C'),
SCORE=c(3,6,NA,NA,NA,NA,1,NA,5,5,2,NA),
NEWVAR=c(1,1,1,NA,NA,NA,2,2,2,1,1,1))

score1 = c(2,3,7)
score2 = c(0,5,6)
</code>```

I have 'data' with all columns but 'NEWVAR' and I wish to create it like this:

If score1 %in% SCORE for a particular 'GROUP' then a value '1' is given to 'NEWVAR'

If score2 %in% SCORE & score1 is not in SCORE for a particular 'GROUP' then a value '2' is given to 'NEWVAR'

答:
```<code>scores = list(score1, score2)
ave(data$SCORE, data$GROUP, FUN = function(x){
    chk = sapply(scores, function(y) any(y %in% x))
    seq_along(scores)[chk][1]
})
# [1]  1  1  1 NA NA NA  2  2  2  1  1  1
</code>```

Title: R Indicate If Group Has Value

Body:
data=data.frame(GROUP=c(1,1,1,2,2,2,3,3,3,4,4,4),
VAR=c('A','B','C','A','B','C','A','B','C','A','B','C'),
SCORE=c(3,6,NA,NA,NA,NA,1,NA,5,5,2,NA),
NEWVAR=c(1,1,1,NA,NA,NA,2,2,2,1,1,1))

score1 = c(2,3,7)
score2 = c(0,5,6)

I have 'data' with all columns but 'NEWVAR' and I wish to create it like this:

If score1 %in% SCORE for a particular 'GROUP' then a value '1' is given to 'NEWVAR'

If score2 %in% SCORE & score1 is not in SCORE for a particular 'GROUP' then a value '2' is given to 'NEWVAR'


问:
Seperate CA for etcd in Kubernetes?
I was going through Control Plane Security in Google cloud(GKE) course and referring to 'certificate authority and cluster trust' in the link below and have these questions. Can someone clarify these ?.

https://cloud.google.com/kubernetes-engine/docs/concepts/control-plane-security

Learnt that every cluster has its on CA that would issue certificates, this part is fine.. there is also a mention on etcd having seperate CA...  does it mean a cluster has two CAs, one for rest of the components and one for etcd Or is it just one CA for whole control plane ?

It also says, each cluster has its own 'root' CA..I know what CA is, what does root Certificate Authority mean ?

Thanks in advance...

答:
1.- That's correct. There is one certificate for masters and nodes components, and another one for etcd. This article explains is better. Note that it's a GKE approach, not Kubernetes.

2.- The article I passed also explains this second points. Indeed there are two CAs. I quote  "In GKE, the master API certificate is signed by the cluster root CA. Each cluster runs its own CA, so that if one cluster's CA were to be compromised, no other cluster CA would be affected".

Title: Seperate CA for etcd in Kubernetes?


答:
Yes, it is. If it is simply about a positive or negative value then you can use Math.sign(). Check here for more info.

For example:

```<code>if (Math.sign(this.number2) == 1) {
  //positive
}else if (Math.sign(this.number2) == -1) {
  //negative
}else {
  //zero
}
</code>```

Good luck!

Title: How do I use an if statement in a Vue.js function?

Body:
Yes, it is. If it is simply about a positive or negative value then you can use Math.sign(). Check here for more info.

For example:

if (Math.sign(this.number2) == 1) {
  //positive
}else if (Math.sign(this.number2) == -1) {
  //negative
}else {
  //zero
}

Good luck!


问:
CSS not displaying properly after transferred to IIS 7 in IE 9
When running on dev server through VS 2010 all CSS displays properly.  I publish to win server 2008 r2 with IIS 7, and when I open in IE 9 the inline-block doesnt work, the gradients dont work, and the box-shadow doesnt work.  It strips out most of the CSS formatting, I load the same page in firefox and it looks the same as it does in IE 9 under the dev server.  Code below:
CSS file:

```<code>body {
}
#opsChartContainer
{
    background: #FFFFFF;
margin: auto;
width: 600px;
padding-top: 15px;
font-family: helvetica, arial, sans-serif;
display: inline-table;
}
#oldestActiveCon
{
    background: #FFFFFF;
    margin: auto;
    width: 300px;
    padding-top: 15px;
    font-family: helvetica, arial, sans-serif;
    display: inline-table;
}
#incVolumeCon
{
    background: #FFFFFF;
    margin: auto;
    width: 700px;
    padding-top: 15px;
    font-family: helvetica, arial, sans-serif;
    display: inline-table;
}
#reqSLACon
{
    background: #FFFFFF;
    margin: auto;
    width: 400px;
    padding-top: 15px;
    font-family: helvetica, arial, sans-serif;
    display: inline-table;
}

h1
{
    background: #e3e3e3;
    background: -moz-linear-gradient(top, #fcfdfe, #8bb7e3);
    background: -webkit-gradient(linear, left top, left bottom, from(#fcfdfe), to(#8bb7e3));
    padding: 10px 20px;
    margin-left: -20px;
    margin-top: 0;
    position: relative;
    width: 70%;
    -moz-box-shadow: 1px 1px 3px #292929;
    -webkit-box-shadow: 1px 1px 3px #292929;
    box-shadow: 3px 3px 3px #292929;
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#fcfdfe,     endColorstr=#8bb7e3)";
    color: #454545;
    text-shadow: 0 1px 0 white;
    font-size: small;
    font-weight: bold;
}
h2
{
    background: #dde3d5;
    padding: 10px 20px;
    margin-left: 5px;
    margin-top: 10px;
    position: relative;
    -moz-box-shadow: 1px 1px 3px #292929;
    -webkit-box-shadow: 1px 1px 3px #292929;
    box-shadow: 3px 3px 3px #b5baae;
    color: #454545;
    text-shadow: 0 1px 0 white;
    font-size: small;
    font-style: normal;
}
.mGrid {
    width: 100%;
    margin: 5px 0 10px 0;
    border: solid 1px #525252;
    border-collapse:collapse;
}
.mGrid td {
    padding: 2px;

}
.header
{
    padding: 4px 2px;
    color: #ffffff;
    background: #4289c6 url('../grd_head.png') repeat-x top;
}
.alt
{
    background: #FFFFFF url('../grd_alt.png') repeat-x top;
    font-size: smaller;
    font-family: Arial;
    font-style: normal;
}
.rst
{
    background: #FFFFFF url('../grd_firstt.png') repeat-x top;
    font-size: smaller;
    font-family: Arial;
    font-style: normal;
}

ul#testy li
{
    list-style-type: none;
    display: inline-block;
    vertical-align: top;
    padding-left: 50px;
}
</code>```

ASPX front end:

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true"     CodeBehind="test.aspx.cs" Inherits="test.test" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div id="opsChartContainer"><h1>TEXT</h1><h2>FLASHFILE</h2></div>
<div id="oldestActiveCon"><h1>TEXT</h1>
<h2>
    <asp:GridView ID="GridView1" runat="server" CellPadding="4"
        ForeColor="#333333"
        GridLines="None" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" Width="200px">
        <AlternatingRowStyle CssClass="alt" />
        <Columns>
            <asp:BoundField DataField="Status" HeaderText="Status"
                SortExpression="Status" />
            <asp:BoundField DataField="Team" HeaderText="Team" SortExpression="Team" />
            <asp:BoundField DataField="Time" HeaderText="Time" ReadOnly="True"
                SortExpression="Time" />
            <asp:TemplateField HeaderText="Request ID">
                <ItemTemplate>
                    <asp:HyperLink ID="HyperLink1" runat="server" Target="_blank"     NavigateUrl='<%    # "link"+ Eval("Request") + "&"%>'><%#Eval("Request")%></asp:HyperLink>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>

        <HeaderStyle CssClass="header" />

<RowStyle CssClass="rst"></RowStyle>

    </asp:GridView>
</h2>
</div>

<div id="incVolumeCon">
    <h1>text</h1>
    <h2>
        flashfile
    </h2>
</div>
<div id="reqSLACon">
    <h1> text</h1>
        <h2>
        <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
        DataSourceID="blahblah" CellPadding="4" ForeColor="#333333"
        GridLines="None" CssClass="mGrid" AlternatingRowStyle-CssClass="alt" RowStyle-CssClass="rst" Width = "400">
        <Columns>
            <asp:BoundField DataField="text" HeaderText="text" ReadOnly="True"
                SortExpression="text" />
            <asp:BoundField DataField="Dueby Time" HeaderText="text" ReadOnly="True"
                SortExpression="text" />
            <asp:BoundField DataField="text" HeaderText="text"
                ReadOnly="True" SortExpression="text" />
            <asp:BoundField DataField="text" HeaderText="text"
                ReadOnly="True" SortExpression="text" />
            <asp:BoundField DataField="Expr1" HeaderText="text" ReadOnly="True"
                SortExpression="Expr1" />
            <asp:TemplateField HeaderText="Request ID" >
            <ItemTemplate>
                    <asp:HyperLink ID="HyperLink1" runat="server" Target="_blank" NavigateUrl='<%# "link"+ Eval("Request ID") + "&"%>'><%#Eval("Request ID")%></asp:HyperLink>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>

</asp:GridView>

test
    </h2>
</div>
</code>```

ANY ideas?  What is causing the disparity between when I view it in IE 9 through dev server from vs 2010 and when I view it in IE 9 on production server?

答:
I had this same problem on a couple of websites. It rendered correctly in all browsers (That I tested) except IE9. I solved it by inserting <meta content="IE=8" http-equiv="X-UA-Compatible" /> in the HEADER.

But with me situation it did not work anywhere locally or remotely, so if your rendering locally it could be something else but it's worth a try.

Hope that helps....

ContentLicense: CC BY-SA 3.0

Body:
When running on dev server through VS 2010 all CSS displays properly.  I publish to win server 2008 r2 with IIS 7, and when I open in IE 9 the inline-block doesnt work, the gradients dont work, and the box-shadow doesnt work.  It strips out most of the CSS formatting, I load the same page in firefox and it looks the same as it does in IE 9 under the dev server.  Code below:
CSS file:

body {
}
#opsChartContainer
{
    background: #FFFFFF;
margin: auto;
width: 600px;
padding-top: 15px;
font-family: helvetica, arial, sans-serif;
display: inline-table;
}
#oldestActiveCon
{
    background: #FFFFFF;
    margin: auto;
    width: 300px;
    padding-top: 15px;
    font-family: helvetica, arial, sans-serif;
    display: inline-table;
}
#incVolumeCon
{
    background: #FFFFFF;
    margin: auto;
    width: 700px;
    padding-top: 15px;
    font-family: helvetica, arial, sans-serif;
    display: inline-table;
}
#reqSLACon
{
    background: #FFFFFF;
    margin: auto;
    width: 400px;
    padding-top: 15px;
    font-family: helvetica, arial, sans-serif;
    display: inline-table;
}

h1
{
    background: #e3e3e3;
    background: -moz-linear-gradient(top, #fcfdfe, #8bb7e3);
    background: -webkit-gradient(linear, left top, left bottom, from(#fcfdfe), to(#8bb7e3));
    padding: 10px 20px;
    margin-left: -20px;
    margin-top: 0;
    position: relative;
    width: 70%;
    -moz-box-shadow: 1px 1px 3px #292929;
    -webkit-box-shadow: 1px 1px 3px #292929;
    box-shadow: 3px 3px 3px #292929;
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#fcfdfe,     endColorstr=#8bb7e3)";
    color: #454545;
    text-shadow: 0 1px 0 white;
    font-size: small;
    font-weight: bold;
}
h2
{
    background: #dde3d5;
    padding: 10px 20px;
    margin-left: 5px;
    margin-top: 10px;
    position: relative;
    -moz-box-shadow: 1px 1px 3px #292929;
    -webkit-box-shadow: 1px 1px 3px #292929;
    box-shadow: 3px 3px 3px #b5baae;
    color: #454545;
    text-shadow: 0 1px 0 white;
    font-size: small;
    font-style: normal;
}
.mGrid {
    width: 100%;
    margin: 5px 0 10px 0;
    border: solid 1px #525252;
    border-collapse:collapse;
}
.mGrid td {
    padding: 2px;

}
.header
{
    padding: 4px 2px;
    color: #ffffff;
    background: #4289c6 url('../grd_head.png') repeat-x top;
}
.alt
{
    background: #FFFFFF url('../grd_alt.png') repeat-x top;
    font-size: smaller;
    font-family: Arial;
    font-style: normal;
}
.rst
{
    background: #FFFFFF url('../grd_firstt.png') repeat-x top;
    font-size: smaller;
    font-family: Arial;
    font-style: normal;
}

ul#testy li
{
    list-style-type: none;
    display: inline-block;
    vertical-align: top;
    padding-left: 50px;
}

ASPX front end:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true"     CodeBehind="test.aspx.cs" Inherits="test.test" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

TEXT

FLASHFILE

TEXT

    <asp:GridView ID="GridView1" runat="server" CellPadding="4"
        ForeColor="#333333"
        GridLines="None" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" Width="200px">
        <AlternatingRowStyle CssClass="alt" />
        <Columns>
            <asp:BoundField DataField="Status" HeaderText="Status"
                SortExpression="Status" />
            <asp:BoundField DataField="Team" HeaderText="Team" SortExpression="Team" />
            <asp:BoundField DataField="Time" HeaderText="Time" ReadOnly="True"
                SortExpression="Time" />
            <asp:TemplateField HeaderText="Request ID">
                <ItemTemplate>
                    <asp:HyperLink ID="HyperLink1" runat="server" Target="_blank"     NavigateUrl='<%    # "link"+ Eval("Request") + "&"%>'><%#Eval("Request")%></asp:HyperLink>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>

        <HeaderStyle CssClass="header" />

<RowStyle CssClass="rst"></RowStyle>

    </asp:GridView>

text

        flashfile

 text

        <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
        DataSourceID="blahblah" CellPadding="4" ForeColor="#333333"
        GridLines="None" CssClass="mGrid" AlternatingRowStyle-CssClass="alt" RowStyle-CssClass="rst" Width = "400">
        <Columns>
            <asp:BoundField DataField="text" HeaderText="text" ReadOnly="True"
                SortExpression="text" />
            <asp:BoundField DataField="Dueby Time" HeaderText="text" ReadOnly="True"
                SortExpression="text" />
            <asp:BoundField DataField="text" HeaderText="text"
                ReadOnly="True" SortExpression="text" />
            <asp:BoundField DataField="text" HeaderText="text"
                ReadOnly="True" SortExpression="text" />
            <asp:BoundField DataField="Expr1" HeaderText="text" ReadOnly="True"
                SortExpression="Expr1" />
            <asp:TemplateField HeaderText="Request ID" >
            <ItemTemplate>
                    <asp:HyperLink ID="HyperLink1" runat="server" Target="_blank" NavigateUrl='<%# "link"+ Eval("Request ID") + "&"%>'><%#Eval("Request ID")%></asp:HyperLink>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>

</asp:GridView>

test

ANY ideas?  What is causing the disparity between when I view it in IE 9 through dev server from vs 2010 and when I view it in IE 9 on production server?


问:
Using the lag function with two different columns R
I have data such as this.

```<code>data.input <-read_table2("user.id   problem.id  first.correct   cwa_prob    prob.seq
540995  PRABNBZQ    0   1   problem.id.problem.1
540995  PRABNBZ2    1   0   problem.id.problem.2
540995  PRABNBZK    0   1   problem.id.problem.3
540995  PRABNB2B    0   1   problem.id.problem.4
540995  PRABNBWE    0   1   problem.id.problem.5
565662  PRABNB2B    1   0   problem.id.problem.1
565662  PRABNBZQ    1   1   problem.id.problem.2
565662  PRABNBZ9    1   0   problem.id.problem.3
565662  PRABNBZV    1   0   problem.id.problem.4
565662  PRABNBWG    1   0   problem.id.problem.5
")
</code>```

I am trying to use the lag function to compare the occurrence of a flag in two separate columns. I want to see how a person fairs sequentially from one problem to the next. Specifically, if cwa_prob is 1 for problem.id.problem.1 (user 540995), is it the case that first.correct==1 in problem.id.problem.2 (user 540995).

I tried something like this, but it throws me an error.

```<code>input.data %>%
  group_by(user.id) %>%
  mutate(post.cwa.correct=ifelse(cwa_prob==1 & lag(first.correct==1),1,0))
</code>```

I would like my output to look something like this:

```<code>data.output <-read_table2("user.id  problem.id  first.correct   cwa_prob    prob.seq    post.cwa.correct
540995  PRABNBZQ    0   1   problem.id.problem.1    NA
540995  PRABNBZ2    1   0   problem.id.problem.2    1
540995  PRABNBZK    0   1   problem.id.problem.3    NA
540995  PRABNB2B    0   1   problem.id.problem.4    0
540995  PRABNBWE    0   1   problem.id.problem.5    0
565662  PRABNB2B    1   0   problem.id.problem.1    1
565662  PRABNBZQ    1   1   problem.id.problem.2    NA
565662  PRABNBZ9    1   0   problem.id.problem.3    1
565662  PRABNBZV    1   0   problem.id.problem.4    NA
565662  PRABNBWG    1   0   problem.id.problem.5    NA
")
</code>```

Maybe the lag function isn't the best function for this? Any help is appreciated!

答:
I ran everything, and it worked fine. However the output you list as wanted doesn't actually meet your criteria...you'd want

```<code>data.input %>%
  group_by(user.id) %>%
  mutate(post.cwa.correct=ifelse(cwa_prob==0, NA, ifelse(
    cwa_prob==1 & lead(first.correct==1),1,0)
  ))
</code>```

However, you list the dataset as "data.input," but then the dataset you use is listed as "input.data."

Body:
I have data such as this.

data.input <-read_table2("user.id   problem.id  first.correct   cwa_prob    prob.seq
540995  PRABNBZQ    0   1   problem.id.problem.1
540995  PRABNBZ2    1   0   problem.id.problem.2
540995  PRABNBZK    0   1   problem.id.problem.3
540995  PRABNB2B    0   1   problem.id.problem.4
540995  PRABNBWE    0   1   problem.id.problem.5
565662  PRABNB2B    1   0   problem.id.problem.1
565662  PRABNBZQ    1   1   problem.id.problem.2
565662  PRABNBZ9    1   0   problem.id.problem.3
565662  PRABNBZV    1   0   problem.id.problem.4
565662  PRABNBWG    1   0   problem.id.problem.5
")

I am trying to use the lag function to compare the occurrence of a flag in two separate columns. I want to see how a person fairs sequentially from one problem to the next. Specifically, if cwa_prob is 1 for problem.id.problem.1 (user 540995), is it the case that first.correct==1 in problem.id.problem.2 (user 540995).

I tried something like this, but it throws me an error.

input.data %>%
  group_by(user.id) %>%
  mutate(post.cwa.correct=ifelse(cwa_prob==1 & lag(first.correct==1),1,0))

I would like my output to look something like this:

data.output <-read_table2("user.id  problem.id  first.correct   cwa_prob    prob.seq    post.cwa.correct
540995  PRABNBZQ    0   1   problem.id.problem.1    NA
540995  PRABNBZ2    1   0   problem.id.problem.2    1
540995  PRABNBZK    0   1   problem.id.problem.3    NA
540995  PRABNB2B    0   1   problem.id.problem.4    0
540995  PRABNBWE    0   1   problem.id.problem.5    0
565662  PRABNB2B    1   0   problem.id.problem.1    1
565662  PRABNBZQ    1   1   problem.id.problem.2    NA
565662  PRABNBZ9    1   0   problem.id.problem.3    1
565662  PRABNBZV    1   0   problem.id.problem.4    NA
565662  PRABNBWG    1   0   problem.id.problem.5    NA
")

Maybe the lag function isn't the best function for this? Any help is appreciated!

Body:
I ran everything, and it worked fine. However the output you list as wanted doesn't actually meet your criteria...you'd want

data.input %>%
  group_by(user.id) %>%
  mutate(post.cwa.correct=ifelse(cwa_prob==0, NA, ifelse(
    cwa_prob==1 & lead(first.correct==1),1,0)
  ))

However, you list the dataset as "data.input," but then the dataset you use is listed as "input.data."


问:
VBA equality mistmatch?
I have this VBA code:

```<code>For q = 1 To pf.PivotItems.Count
        For i = LBound(myArray) To UBound(myArray)
                If pf.PivotItems(q).Name = myArray(i) Then same = True
        Next i
        pf.PivotItems(q).Visible = False
        If same = True Then pf.PivotItems(q).Visible = True
        same = False

Next q
</code>```

This line gives me an equality mismatch error: If pf.PivotItems(q).Name = myArray(i)

Why? How do I fix this?

答:
Try this, I've tweaked the code for efficiency. As mentioned in the comments, the main question is what is in myArray? it needs to output a single value, not an array or object, so you might need to further qualify myArray(i)</p>

```<code>Dim pvtItm As PivotItem    'put this with other dim statements

For Each pvtItm In pf.PivotItems
    pvtItm.Visible = True
    For i = LBound(myArray) To UBound(myArray)
        If pvtItm.Name = myArray(i) Then
            pvtItm.Visible = False
            Exit For
        End If
    Next
Next
</code>```

Title: VBA equality mistmatch?

Body:
I have this VBA code:

For q = 1 To pf.PivotItems.Count
        For i = LBound(myArray) To UBound(myArray)
                If pf.PivotItems(q).Name = myArray(i) Then same = True
        Next i
        pf.PivotItems(q).Visible = False
        If same = True Then pf.PivotItems(q).Visible = True
        same = False

Next q

This line gives me an equality mismatch error: If pf.PivotItems(q).Name = myArray(i)

Why? How do I fix this?

Body:
Try this, I've tweaked the code for efficiency. As mentioned in the comments, the main question is what is in myArray? it needs to output a single value, not an array or object, so you might need to further qualify myArray(i)

Dim pvtItm As PivotItem    'put this with other dim statements

For Each pvtItm In pf.PivotItems
    pvtItm.Visible = True
    For i = LBound(myArray) To UBound(myArray)
        If pvtItm.Name = myArray(i) Then
            pvtItm.Visible = False
            Exit For
        End If
    Next
Next


问:
send mail to non-registered user (email list) in a queue
I am trying to program a Laravel mailing list with a queue Try to send emails to Non-users, I did a good job with registered users and this is my code:

```<code>        foreach ($emails as  $i=>$item){
            $user = User::where('email',$item)->first();
            if ($i % $mailsCount == 0)$count++;
            if ($user){
                $thisBody = ElzahabyDynamicLaravelString($user,$body,$this->sign);
                $thisSubject = ElzahabyDynamicLaravelString($user,$subject,$this->sign);
                $when = Carbon::now()->addMinutes($every*$count);
                Mail::to($user)
                    ->later($when,new EmailForQueuing($user,$thisBody,$thisSubject,$request->emailTemplate));
            }
        }
</code>```

You can notice later() method, which is responsible for the queue.  but this only works with Mail::to method which only works for registered users.

So, any idea how to send a mailing list with a queue to non-registered emails.

Thanks in advance.

Edit 1

EmailForQueuing() method is a simple Mailable class

答:
You may use fill method to create an instance of User without saving into the database it such as;

```<code>$mailUser = (new User())->fill(['email' => 'something@foo.bar']);
</code>```

You may pass also other fields such as ['name' => 'some name', 'age' => 23]

Another option without using the fill would be

```<code>$mailUser = (new User(['email' => 'something@foo.bar']))
</code>```

Your code will be something like this;

```<code>$mails = ['email1@com', 'email2@com', 'email3@com', 'etc.com'];
$users = [];

foreach ($mails as $mail) {
    $users[] = (new User(['email' => $mail]));
}

return $users;
</code>```

Body:
I am trying to program a Laravel mailing list with a queue Try to send emails to Non-users, I did a good job with registered users and this is my code:

        foreach ($emails as  $i=>$item){
            $user = User::where('email',$item)->first();
            if ($i % $mailsCount == 0)$count++;
            if ($user){
                $thisBody = ElzahabyDynamicLaravelString($user,$body,$this->sign);
                $thisSubject = ElzahabyDynamicLaravelString($user,$subject,$this->sign);
                $when = Carbon::now()->addMinutes($every*$count);
                Mail::to($user)
                    ->later($when,new EmailForQueuing($user,$thisBody,$thisSubject,$request->emailTemplate));
            }
        }

You can notice later() method, which is responsible for the queue.  but this only works with Mail::to method which only works for registered users.

So, any idea how to send a mailing list with a queue to non-registered emails.

Thanks in advance.

Edit 1

EmailForQueuing() method is a simple Mailable class

Body:
You may use fill method to create an instance of User without saving into the database it such as;

$mailUser = (new User())->fill(['email' => 'something@foo.bar']);

You may pass also other fields such as ['name' => 'some name', 'age' => 23]

Another option without using the fill would be

$mailUser = (new User(['email' => 'something@foo.bar']))

Your code will be something like this;

$mails = ['email1@com', 'email2@com', 'email3@com', 'etc.com'];
$users = [];

foreach ($mails as $mail) {
    $users[] = (new User(['email' => $mail]));
}

return $users;


问:
Utilisation of 'this' in React Js
i have a classic functionnal component returning what will be rendered in JSX

```<code>function Search(){

    const loadFilms = function (){
         console.log(this)); // logs undefined
    };

    return(

            <View style= {styleAreas.view}>
                <TextInput style= {styleAreas.textinput} placeholder='Type your movie ' />
                <Button title='Search' onPress= {()=> { console.log(this);loadFilms();} } />  // logs undefined
                <FlatList
                data={films}
                keyExtractor = {item => item.id.toString()}
                renderItem={({item}) => <FilmItem filmDesc = {item} />}
                />
            </View>

        )
}
</code>```

so i'm learning JS / React, and what i don't understand why this is undefined but when we run it since Class Search extends React.Component {}. it returns the  right instance.
 especially that i tought that in JS ( i'm maybe over simplifying)  a class is  a function with pre-configured prototypes etc...

thank you for your explanations :)

答:
The reason for that is that loadFilms is a function different from your 'Class'. Therefore, it has a different this context. Since you seem to use strict mode, it's undefined. You could pass it explicitly by using the call method.

```<code>function Search(){

    const loadFilms = function (){
         console.log(this)); // logs undefined
    };

    return(

            <View style= {styleAreas.view}>
                <TextInput style= {styleAreas.textinput} placeholder='Type your movie ' />
                <Button title='Search' onPress= {()=> { console.log(this); loadFilms.call(this);} } />  // logs undefined
                <FlatList
                data={films}
                keyExtractor = {item => item.id.toString()}
                renderItem={({item}) => <FilmItem filmDesc = {item} />}
                />
            </View>

        )
}
</code>```

Title: Utilisation of 'this' in React Js

Body:
i have a classic functionnal component returning what will be rendered in JSX

function Search(){

    const loadFilms = function (){
         console.log(this)); // logs undefined
    };

    return(

            <View style= {styleAreas.view}>
                <TextInput style= {styleAreas.textinput} placeholder='Type your movie ' />
                <Button title='Search' onPress= {()=> { console.log(this);loadFilms();} } />  // logs undefined
                <FlatList
                data={films}
                keyExtractor = {item => item.id.toString()}
                renderItem={({item}) => <FilmItem filmDesc = {item} />}
                />
            </View>

        )
}

so i'm learning JS / React, and what i don't understand why this is undefined but when we run it since Class Search extends React.Component {}. it returns the  right instance.
 especially that i tought that in JS ( i'm maybe over simplifying)  a class is  a function with pre-configured prototypes etc...

thank you for your explanations :)

Body:
The reason for that is that loadFilms is a function different from your 'Class'. Therefore, it has a different this context. Since you seem to use strict mode, it's undefined. You could pass it explicitly by using the call method.

function Search(){

    const loadFilms = function (){
         console.log(this)); // logs undefined
    };

    return(

            <View style= {styleAreas.view}>
                <TextInput style= {styleAreas.textinput} placeholder='Type your movie ' />
                <Button title='Search' onPress= {()=> { console.log(this); loadFilms.call(this);} } />  // logs undefined
                <FlatList
                data={films}
                keyExtractor = {item => item.id.toString()}
                renderItem={({item}) => <FilmItem filmDesc = {item} />}
                />
            </View>

        )
}


问:
Importing Virtual Images into AWS
We have an older application that is running on Windows server 2008 (the application is being refactored as we speak). Until that is done, I need to get a copy of Windows Server 2008 in AWS but it is not available through their one-click-through process. Therefore, I need to import an image or add an ISO and do an install that way (if that's even possible). I've gone though the AWS documentation on importing via the aws cli and to be frank, I don't get it and wasn't able to do the import. Other than AWS Command Line tools, is there another way to get a VM into AWS? I've considered loading an Ubuntu 18.04 and then installing VMPlayer (a VM within a VM) but even then, I'm not sure if the sub-vm would be accessible to the outside world (via security groups).

I've only been working with AWS for about a month so use small aws words. :)

答:
If you have the ISO file create either a VMware or VirtualBox image. From there, you may convert this image into an EC2 AMI image and go from there.

Follow the steps to import Virtualbox instance https://aws.amazon.com/ec2/vm-import/

Also first check if you can get a normal windows server instance from amazon and customize.

Keep in mind to use the same architecture 32 or 64 bit all across.

Title: Importing Virtual Images into AWS


问:
ServicePointManager.SecurityProtocol is not SecurityProtocolType.SystemDefault
I am on Windows 10 1903, and my IE and Chrome can access Tls 1.2 website without any special settings. But when I try to use my .net 4.7.2 application to access a web API which only allows Tls 1.2 connect, my connection got terminated by the server.

I have to add ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; in my code to allow my application to connect to that endpoint correctly.

But after doing some research, I found from this document that for .Net 4.7 and above the default value for ServicePointManager.SecurityProtocol should be SecurityProtocolType.SystemDefault and according to this document the Tls 1.2 protocal is enable by default.

So I traced my code and found that the default value for ServicePointManager.SecurityProtocol on my system is System.Net.SecurityProtocolType.Ssl3 | System.Net.SecurityProtocolType.Tls. What's more crazy, when I set the protocol to SecurityProtocolType.SystemDefault, I got this error:

```<code>System.Net.Http.HttpRequestException : An error occurred while sending the request.
---- System.Net.WebException : The underlying connection was closed: An unexpected error occurred on a receive.
-------- System.ArgumentException : The specified value is not valid in the 'SslProtocolType' enumeration.
Parameter name: sslProtocolType
</code>```

I checked my system registry and IE settings, and nothing overrides or disables Tls 1.2.

So I am very confused and wonder if is there something wrong with my system or with my code.

答:
You will get this error if the app you're running targets a .NET framework earlier than 4.6 (even if you are actually running it on a newer .NET FX). You can check this by examining the value of AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName.

Specifically, this will get thrown in such a case where the SystemDefaultTlsVersions registry value is not set to 1:
https://referencesource.microsoft.com/#System/net/System/Net/SecureProtocols/_SslState.cs,164

AppContext switches won't help you either, as they only take effect for framework versions starting from 4.6. Assuming you can't change the targeted .NET version (example) and you don't want to force your users to change their registry settings, I recommend code like this:

```<code>if (ServicePointManager.SecurityProtocol != SecurityProtocolType.SystemDefault)
{
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}
</code>```

For more information:
https://learn.microsoft.com/en-us/dotnet/framework/network-programming/tls

Body:
I am on Windows 10 1903, and my IE and Chrome can access Tls 1.2 website without any special settings. But when I try to use my .net 4.7.2 application to access a web API which only allows Tls 1.2 connect, my connection got terminated by the server.

I have to add ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; in my code to allow my application to connect to that endpoint correctly.

But after doing some research, I found from this document that for .Net 4.7 and above the default value for ServicePointManager.SecurityProtocol should be SecurityProtocolType.SystemDefault and according to this document the Tls 1.2 protocal is enable by default.

So I traced my code and found that the default value for ServicePointManager.SecurityProtocol on my system is System.Net.SecurityProtocolType.Ssl3 | System.Net.SecurityProtocolType.Tls. What's more crazy, when I set the protocol to SecurityProtocolType.SystemDefault, I got this error:

System.Net.Http.HttpRequestException : An error occurred while sending the request.
---- System.Net.WebException : The underlying connection was closed: An unexpected error occurred on a receive.
-------- System.ArgumentException : The specified value is not valid in the 'SslProtocolType' enumeration.
Parameter name: sslProtocolType

I checked my system registry and IE settings, and nothing overrides or disables Tls 1.2.

So I am very confused and wonder if is there something wrong with my system or with my code.

Body:
You will get this error if the app you're running targets a .NET framework earlier than 4.6 (even if you are actually running it on a newer .NET FX). You can check this by examining the value of AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName.

Specifically, this will get thrown in such a case where the SystemDefaultTlsVersions registry value is not set to 1:
https://referencesource.microsoft.com/#System/net/System/Net/SecureProtocols/_SslState.cs,164

AppContext switches won't help you either, as they only take effect for framework versions starting from 4.6. Assuming you can't change the targeted .NET version (example) and you don't want to force your users to change their registry settings, I recommend code like this:

if (ServicePointManager.SecurityProtocol != SecurityProtocolType.SystemDefault)
{
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}

For more information:
https://learn.microsoft.com/en-us/dotnet/framework/network-programming/tls


问:
Docker Error bind: address already in use
When I run docker-compose up in my Docker project it fails with the following message:

Error starting userland proxy: listen tcp 0.0.0.0:3000: bind: address already in use

```<code>netstat -pna | grep 3000
</code>```

shows this:

```<code>tcp        0      0 0.0.0.0:3000            0.0.0.0:*               LISTEN      -
</code>```

I've already tried docker-compose down, but it doesn't help.

答:
The one that was using the port 8888 was Jupiter and I had to change the configuration file of Jupiter notebook to run on another port.

to list who is using that specific port.
sudo lsof -i -P -n | grep 9

You can specify the port you want Jupyter to run uncommenting/editing the following line in ~/.jupyter/jupyter_notebook_config.py:

c.NotebookApp.port = 9999

In case you don't have a jupyter_notebook_config.py try running jupyter notebook --generate-config. See this for further details on Jupyter configuration.

Body:
When I run docker-compose up in my Docker project it fails with the following message:

Error starting userland proxy: listen tcp 0.0.0.0:3000: bind: address already in use

netstat -pna | grep 3000

shows this:

tcp        0      0 0.0.0.0:3000            0.0.0.0:*               LISTEN      -

I've already tried docker-compose down, but it doesn't help.


问:
Intellij Maven Test Failed
I"m running selenium automation code on intellij but it shows test failed but my code is empty test only. The test result shows passed but this warning bothering me

Error log:
Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:3.0.0-M3:test (default-test) on project dsf-automation: There are test failures.

```<code>Please refer to C:\Users\peter.wong\IdeaProjects\dsf-automation\target\surefire-reports for the individual test results.
Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
There was an error in the forked process
null
org.apache.maven.surefire.booter.SurefireBooterForkException: There was an error in the forked process
null
    at org.apache.maven.plugin.surefire.booterclient.ForkStarter.fork(ForkStarter.java:657)
    at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:283)
    at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:246)
    at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeProvider(AbstractSurefireMojo.java:1161)
    at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeAfterPreconditionsChecked(AbstractSurefireMojo.java:1002)
    at org.apache.maven.plugin.surefire.AbstractSurefireMojo.execute(AbstractSurefireMojo.java:848)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:957)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:289)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:193)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:347)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:47)
</code>```

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>dsf-automation</groupId>
    <artifactId>dsf-automation</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                    <!--  <configuration>
                          <release>12</release>
                          <compilerArgs>enable-preview</compilerArgs>
                    </configuration>-->
                    <configuration>
                        <source>1.9</source>
                        <target>1.9</target>
                    </configuration>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>3.0.0-M3</version>
                    <configuration>
                        <includes>
                            <include>RestWebServiceTestManager.java</include>
                            <include>FirefoxTestManager.java</include>
                        </includes>
                    </configuration>
                </plugin>

            </plugins>
        </pluginManagement>
    </build>

    <dependencies>

        <!--=========================== Selenium ========================== -->
        <dependency>
            <groupId>io.appium</groupId>
            <artifactId>java-client</artifactId>
            <version>6.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.14.0</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-api</artifactId>
            <version>3.14.0</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-support</artifactId>
            <version>3.14.0</version>
        </dependency>

        <!--=============================Spring Framework ===================== -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>5.1.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-crypto</artifactId>
            <version>5.1.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-ws-test</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <!--============================Rest Assured========================== -->
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>com.github.scribejava</groupId>
            <artifactId>scribejava-apis</artifactId>
            <version>2.5.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.10.3</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.3</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.14.3</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>

        <!--=========================== Java Mail ==============================-->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>javax.mail-api</artifactId>
            <version>1.6.2</version>
        </dependency>

        <dependency>
            <groupId>com.github.bbottema</groupId>
            <artifactId>emailaddress-rfc2822</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-email</artifactId>
            <version>1.5</version>
        </dependency>

        <dependency>
            <groupId>io.codearte.jfairy</groupId>
            <artifactId>jfairy</artifactId>
            <version>0.5.9</version>
        </dependency>

        <dependency>
            <groupId>com.github.javafaker</groupId>
            <artifactId>javafaker</artifactId>
            <version>0.16</version>
        </dependency>

        <!-- ========================= Extent Report =======================-->
        <dependency>
            <groupId>com.aventstack</groupId>
            <artifactId>extentreports</artifactId>
            <version>3.1.5</version>
        </dependency>

        <!-- ======================= Log4j 2 =========================================== -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.11.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.11.1</version>
        </dependency>

        <!--============================ MySQL Driver ====================-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>
        <!--============================= Mongo DB Driver ====================-->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.12.2</version>
        </dependency>
        <!--============================= POI ============================-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180813</version>
        </dependency>

        <dependency>
            <groupId>com.deque</groupId>
            <artifactId>axe-selenium</artifactId>
            <version>2.1</version>
        </dependency>

    </dependencies>

</project>
</code>```

Please help me. Thanks.

答:
If your "test code" is really empty have you considered using Maven flag to skip the test step?

```<code>maven <step> -DskipTests
maven <step> -DskipITs
</code>```

Anyways, from your log I could not infer much but sounds like you are facing an issue related to the one helped with this answer: https://stackoverflow.com/a/49367127/8266490

Hope it helped a bit on finding a way for your investigation :)

Title: Intellij Maven Test Failed

Body:
I"m running selenium automation code on intellij but it shows test failed but my code is empty test only. The test result shows passed but this warning bothering me

Error log:
Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:3.0.0-M3:test (default-test) on project dsf-automation: There are test failures.

Please refer to C:\Users\peter.wong\IdeaProjects\dsf-automation\target\surefire-reports for the individual test results.
Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
There was an error in the forked process
null
org.apache.maven.surefire.booter.SurefireBooterForkException: There was an error in the forked process
null
    at org.apache.maven.plugin.surefire.booterclient.ForkStarter.fork(ForkStarter.java:657)
    at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:283)
    at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:246)
    at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeProvider(AbstractSurefireMojo.java:1161)
    at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeAfterPreconditionsChecked(AbstractSurefireMojo.java:1002)
    at org.apache.maven.plugin.surefire.AbstractSurefireMojo.execute(AbstractSurefireMojo.java:848)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:210)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:156)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:148)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:957)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:289)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:193)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:347)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:47)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>dsf-automation</groupId>
    <artifactId>dsf-automation</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>

                    <configuration>
                        <source>1.9</source>
                        <target>1.9</target>
                    </configuration>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>3.0.0-M3</version>
                    <configuration>
                        <includes>
                            <include>RestWebServiceTestManager.java</include>
                            <include>FirefoxTestManager.java</include>
                        </includes>
                    </configuration>
                </plugin>

            </plugins>
        </pluginManagement>
    </build>

    <dependencies>

        <dependency>
            <groupId>io.appium</groupId>
            <artifactId>java-client</artifactId>
            <version>6.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.14.0</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-api</artifactId>
            <version>3.14.0</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-support</artifactId>
            <version>3.14.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>5.1.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-crypto</artifactId>
            <version>5.1.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-ws-test</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>com.github.scribejava</groupId>
            <artifactId>scribejava-apis</artifactId>
            <version>2.5.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.10.3</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.3</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.14.3</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>javax.mail-api</artifactId>
            <version>1.6.2</version>
        </dependency>

        <dependency>
            <groupId>com.github.bbottema</groupId>
            <artifactId>emailaddress-rfc2822</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-email</artifactId>
            <version>1.5</version>
        </dependency>

        <dependency>
            <groupId>io.codearte.jfairy</groupId>
            <artifactId>jfairy</artifactId>
            <version>0.5.9</version>
        </dependency>

        <dependency>
            <groupId>com.github.javafaker</groupId>
            <artifactId>javafaker</artifactId>
            <version>0.16</version>
        </dependency>

        <dependency>
            <groupId>com.aventstack</groupId>
            <artifactId>extentreports</artifactId>
            <version>3.1.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.11.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.11.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.12.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20180813</version>
        </dependency>

        <dependency>
            <groupId>com.deque</groupId>
            <artifactId>axe-selenium</artifactId>
            <version>2.1</version>
        </dependency>

    </dependencies>

</project>

Please help me. Thanks.

Body:
If your "test code" is really empty have you considered using Maven flag to skip the test step?

maven <step> -DskipTests
maven <step> -DskipITs

Anyways, from your log I could not infer much but sounds like you are facing an issue related to the one helped with this answer: https://stackoverflow.com/a/49367127/8266490

Hope it helped a bit on finding a way for your investigation :)


问:
Render VAAPI surface with using OpenGL?
My project is to use the VAAPI hardware acceleration linked with FFmpeg.

I managed to decode with VAAPI however I would like to be able to display the video coming out of VAAPI using OpenGL.

Are there functions that allow this?

I know that for that you have to play with VAAPI's surface VASurfaceID but I do not see how...

答: You can use functions vaCreateSurfaceGLX(), vaCopySurfaceGLX() and vaCopySurfaceGLX() for that purpose. There is other alternatives using DRM and EGL, but in my opinion are much more difficult to achieve. You can find an example using EGL in mpv source code.

Title: Render VAAPI surface with using OpenGL?


问:
How does stringstream work when converting a double value into a char variable
I saw a post on here asking how to convert a double variable value into a char array. Someone said to just use stringstream but didn't explain why it works. I tried googling but couldn't find any documentation on specifically how it converts it. I was wondering if someone could explain to me how it works. Here is the code I wrote that converts a double variable value into a char array.</p>

```<code>#include <iostream>
#include <sstream>
using namespace std;

int main()
{
   double a = 12.99;
   char b[100];
   stringstream ss;

   ss << a;
   ss >> b;
   cout << b; // it outputs 12.99

   return 0;
}
</code>```

答:
When you do ss << a; you are inserting the double in the stringstream (let's suppose it holds the value in a string) and so when you run ss >> b; it just copies the string in the char[] char by char.

Now the only point is to convert double to string, thing that can be achieved with a simple algorithm:

```<code>std::string converter(double value){
    char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    bool is_negative = value < 0;
    std::string integer_to_string;
    value =  is_negative ? value * -1 : value; // make the number positive
    double fract = value - static_cast<unsigned int>(value); // fractionary part of the number
    unsigned int integer = static_cast<int>(value); // integer part of the number
    do{
        unsigned int current = integer % 10; // current digit
        integer_to_string = std::string(1, digits[current]) + integer_to_string; // append the current digit at the beginning
        integer = integer / 10; // delete the current digit
    } while(integer > 0); // do over and over again until there are digits
    integer_to_string = (is_negative ? "-" : "") + integer_to_string; // put the - in case of negative
    std::string fract_to_string;
    if(fract > 0) {
        fract_to_string = ".";
        do {
            unsigned int current = static_cast<int>(fract * 10); // current digit
            fract_to_string = fract_to_string + std::string(1, digits[current]); // append the current digit at the beginning
            fract = (fract * 10) - current; // delete the current digit
        } while (fract > 0);
    }
    return integer_to_string + fract_to_string;
}
</code>```

Keep in mind that this is a very basic conversion and will have a lot of errors due to the instability of the operator- in floating point operation, and so it's a lot unstable, but it's just an example

NOTE: this absolutely to avoid to use in legacy (and actually not only legacy) code, it's just been done as an example, instead you should use std::to_string() with will perform it faster and without any type of error (check this)

Body:
I saw a post on here asking how to convert a double variable value into a char array. Someone said to just use stringstream but didn't explain why it works. I tried googling but couldn't find any documentation on specifically how it converts it. I was wondering if someone could explain to me how it works. Here is the code I wrote that converts a double variable value into a char array.

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
   double a = 12.99;
   char b[100];
   stringstream ss;

   ss <> b;
   cout << b; // it outputs 12.99

   return 0;
}

Body:
When you do ss << a; you are inserting the double in the stringstream (let's suppose it holds the value in a string) and so when you run ss >> b; it just copies the string in the char[] char by char.

Now the only point is to convert double to string, thing that can be achieved with a simple algorithm:

std::string converter(double value){
    char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    bool is_negative = value < 0;
    std::string integer_to_string;
    value =  is_negative ? value * -1 : value; // make the number positive
    double fract = value - static_cast<unsigned int>(value); // fractionary part of the number
    unsigned int integer = static_cast<int>(value); // integer part of the number
    do{
        unsigned int current = integer % 10; // current digit
        integer_to_string = std::string(1, digits[current]) + integer_to_string; // append the current digit at the beginning
        integer = integer / 10; // delete the current digit
    } while(integer > 0); // do over and over again until there are digits
    integer_to_string = (is_negative ? "-" : "") + integer_to_string; // put the - in case of negative
    std::string fract_to_string;
    if(fract > 0) {
        fract_to_string = ".";
        do {
            unsigned int current = static_cast<int>(fract * 10); // current digit
            fract_to_string = fract_to_string + std::string(1, digits[current]); // append the current digit at the beginning
            fract = (fract * 10) - current; // delete the current digit
        } while (fract > 0);
    }
    return integer_to_string + fract_to_string;
}

Keep in mind that this is a very basic conversion and will have a lot of errors due to the instability of the operator- in floating point operation, and so it's a lot unstable, but it's just an example

NOTE: this absolutely to avoid to use in legacy (and actually not only legacy) code, it's just been done as an example, instead you should use std::to_string() with will perform it faster and without any type of error (check this)


问:
SFML "failed to create the font face" issue
I'm using SFML in Visual Studio 2015 to make a game that requires me to print text. I try to load fonts and keep getting an error that says "failed to create the font face". I've tried loading several different fonts and none of them work, and they are in the correct directory, which is the folder where my project is located.

This is literally all it is, and it doesn't work:

```<code> sf::Font font;
    if (!font.loadFromFile("arial.ttf"))
        return EXIT_FAILURE;
</code>```

The ttf file for arial is in the same folder as the project itself, which is what seems to solve the problem for everyone else I find online who has the same issue. Any idea why the font still won't load?

答: To add to this, I was experiencing this same error when I thought I'd had everything typed properly. What ultimately ended up being the issue was that I had written .tff for the font file rather than .ttf, which, once corrected, fixed the problem.</p>

Body:
I'm using SFML in Visual Studio 2015 to make a game that requires me to print text. I try to load fonts and keep getting an error that says "failed to create the font face". I've tried loading several different fonts and none of them work, and they are in the correct directory, which is the folder where my project is located.

This is literally all it is, and it doesn't work:

 sf::Font font;
    if (!font.loadFromFile("arial.ttf"))
        return EXIT_FAILURE;

The ttf file for arial is in the same folder as the project itself, which is what seems to solve the problem for everyone else I find online who has the same issue. Any idea why the font still won't load?


问:
How can I batch convert timezone of DATETIME entries?
For the past year and a half or so, our database server has been using Eastern Time, and the DATETIME type is used almost exclusively so datetimes in our databases have been timezone independent, since just the timestamp is stored. I've added some code in the application to be able to convert times to the local time zone in anticipation of changing this.

I know the best practice is to always use UTC, and I'd like to "cutover" to that now. I'm wondering what an easy way is of changing all the DATETIMEs in all the databases from Eastern time to UTC. By this, I mean literally modifying any DATETIME attributes for every single record, since changing the time zone on the server won't adjust those. Is there a command to easily do this?

I've been looking through some examples using CONVERT but these seem to just do that on the fly - not actually modify the data in the database. I'm sort of looking for something like:

UPDATE [all tables] SET [all DATETIME attributes] = [current server/DB time (Eastern Time) -> UTC]

(And then, hopefully, I could change the server time to UTC and nobody would notice anything had happened.)

But, to make matters worse, Daylight Savings has elapsed a few times in the past year and a half, so the simple approach of adding 5 hours to every datetime won't work, either. Is there an easy way out of this mess? Would CONVERT_TZ be sufficient or could that still muck things up?

答:
OK, so the process isn't necessarily complicated but it's not as obvious as one might hope, so I'm posting an answer. This is what worked for me:

Check if SELECT CONVERT_TZ(now(),'US/Eastern','US/Central'); does anything

First, make sure the above command doesn't return NULL when you execute it. If it does return NULL, as it did for me, complete steps 1 through 4 below:

cd to /usr/bin

./mysql_tzinfo_to_sql /usr/share/zoneinfo | ./mysql -u root -p --database=mysql

Enter password

Run service mariadb restart (or appropriate command) to restart the DB service.

Run SELECT CONVERT_TZ(now(),'US/Eastern','US/Central'); - now it should now work! (not return NULL)

Run sudo timedatectl set-timezone Etc/UTC

Now run SET GLOBAL time_zone = 'Etc/UTC';

Now, the server time and the DB time are UTC.

Now, we must manually update all the appropriate columns to the UTC in the database.

For every applicable table and column combo, run something like this:

```<code> UPDATE table SET `datetime` = CONVERT_TZ(`datetime`, 'America/New_York','Etc/UTC');
</code>```

Now, the database time has been updated and all records are also updated to UTC.

Only caveat is you might want to watch for records that get added while you're updating the tables. Ideally, you'd prepare all this as a batch SQL statement, and execute it immediately after changing the server time so nothing slips by.

At the end, finally, run service apache2 restart to restart the web server. The DB in this case sits on the web server, and for some reason the times did not adjust properly until Apache was restarted.

Body:
OK, so the process isn't necessarily complicated but it's not as obvious as one might hope, so I'm posting an answer. This is what worked for me:

Check if SELECT CONVERT_TZ(now(),'US/Eastern','US/Central'); does anything

First, make sure the above command doesn't return NULL when you execute it. If it does return NULL, as it did for me, complete steps 1 through 4 below:

cd to /usr/bin

./mysql_tzinfo_to_sql /usr/share/zoneinfo | ./mysql -u root -p --database=mysql

Enter password

Run service mariadb restart (or appropriate command) to restart the DB service.

Run SELECT CONVERT_TZ(now(),'US/Eastern','US/Central'); - now it should now work! (not return NULL)

Run sudo timedatectl set-timezone Etc/UTC

Now run SET GLOBAL time_zone = 'Etc/UTC';

Now, the server time and the DB time are UTC.

Now, we must manually update all the appropriate columns to the UTC in the database.

For every applicable table and column combo, run something like this:

 UPDATE table SET `datetime` = CONVERT_TZ(`datetime`, 'America/New_York','Etc/UTC');

Now, the database time has been updated and all records are also updated to UTC.

Only caveat is you might want to watch for records that get added while you're updating the tables. Ideally, you'd prepare all this as a batch SQL statement, and execute it immediately after changing the server time so nothing slips by.

At the end, finally, run service apache2 restart to restart the web server. The DB in this case sits on the web server, and for some reason the times did not adjust properly until Apache was restarted.


问:
Docker mount a volume and populate it from container
I'd like to mount a volume from a windows host to a linux container and have the content of the target folder in the linux container populate the folder in the windows host.

Example:
- host folder: c:\Users\abc\myfolder
- container folder: /data/mydata
The container is built from an image that creates data inside /data/mydata

If I do docker run -v c:\Users\abc\myfolder:/data/mydata image, then c:\Users\abc\myfolder content will override whatever was on /data/mydata inside the container. I would like to achieve the opposite (put the content of /data/mydata from the container in c:\Users\abc\myfolder)

Creating a shared folder and then logging inside the container and copying the content of /data/mydata to the shared folder would expose the content of /data/mydata to the windows host, but it involves a manual copy and is not very efficient.

Thank you.

答:
There is a feature to control read and write permissions

You can specify that a volume should be read-only by appending :ro to the -v switch:

```<code>docker run -v /path/in/host:/path/in/container:ro my_image_name
</code>```

But just works in container folder and by default (with any chance to modify) is read-write on the host

Sync

Maybe you could:

create a folder called /folders/left (c:\Users\abc\myfolder in your case)

create a folder called /folders/right

create a container to populate the /folders/right

```<code>docker run -v /folders/right:/path/in/container my_image_name
</code>```

ensure /folders/right is empty before container startup in order to not override the internal container folder

with this you will have /folders/left (host folder) and /folders/right (changes made by container)

finally try to sync left to right or another configurations with some tool

linux https://unix.stackexchange.com/a/203854/188975

Body:
There is a feature to control read and write permissions

You can specify that a volume should be read-only by appending :ro to the -v switch:

docker run -v /path/in/host:/path/in/container:ro my_image_name

But just works in container folder and by default (with any chance to modify) is read-write on the host

Sync

Maybe you could:

create a folder called /folders/left (c:\Users\abc\myfolder in your case)

create a folder called /folders/right

create a container to populate the /folders/right

docker run -v /folders/right:/path/in/container my_image_name

ensure /folders/right is empty before container startup in order to not override the internal container folder

with this you will have /folders/left (host folder) and /folders/right (changes made by container)

finally try to sync left to right or another configurations with some tool

linux https://unix.stackexchange.com/a/203854/188975


问:
Weekly Time schedule range between days
I have a weekly schedule set from Friday evening 2011-05-27 18:00 to Monday morning
2011-05-30 06:00. This schedule executed on every week starts from 2011-05-27. How we can identify an event time (2011-06-06 19:00) falls between this weekly schedule ?

UPDATE

```<code>ID    StartTime         EndTime            Recurrence  TimeDifferenceInSeconds
1     2011-05-27 18:00  2011-05-30 06:00   1           216000
</code>```

Here recurrence is every one week.

Regards,

Greepty

答:
A possible approach to this problem:

Get the number of whole weeks between the given date/time and StartTime.

Add the number of weeks to StartTime to obtain the latest start time.

Calculate the difference between the latest start time and the given date/time.

Check if that difference is less than TimeDifferenceInSeconds.

And this is how it could be implemented:

```<code>SELECT *
FROM Schedules
WHERE StartTime < @Date AND TimeDifferenceInSeconds >
  DATEDIFF(ss, DATEADD(week, DATEDIFF(day, StartTime, @Date) / 7, StartTime), @Date)
</code>```

This returns all the schedules that @Date falls on.

A more reader-friendly version:

```<code>WITH NewSchedules AS (
  SELECT
    *,
    NewStartTime = DATEADD(week, DATEDIFF(day, StartTime, @Date) / 7, StartTime)
  FROM Schedule
  WHERE StartTime < @Date
)
SELECT *
FROM NewSchedules
WHERE TimeDifferenceInSeconds > DATEDIFF(ss, NewStartTime , @Date)
</code>```

Title: Weekly Time schedule range between days

Body:
I have a weekly schedule set from Friday evening 2011-05-27 18:00 to Monday morning
2011-05-30 06:00. This schedule executed on every week starts from 2011-05-27. How we can identify an event time (2011-06-06 19:00) falls between this weekly schedule ?

UPDATE

ID    StartTime         EndTime            Recurrence  TimeDifferenceInSeconds
1     2011-05-27 18:00  2011-05-30 06:00   1           216000

Here recurrence is every one week.

Regards,

Greepty

Body:
A possible approach to this problem:

Get the number of whole weeks between the given date/time and StartTime.

Add the number of weeks to StartTime to obtain the latest start time.

Calculate the difference between the latest start time and the given date/time.

Check if that difference is less than TimeDifferenceInSeconds.

And this is how it could be implemented:

SELECT *
FROM Schedules
WHERE StartTime < @Date AND TimeDifferenceInSeconds >
  DATEDIFF(ss, DATEADD(week, DATEDIFF(day, StartTime, @Date) / 7, StartTime), @Date)

This returns all the schedules that @Date falls on.

A more reader-friendly version:

WITH NewSchedules AS (
  SELECT
    *,
    NewStartTime = DATEADD(week, DATEDIFF(day, StartTime, @Date) / 7, StartTime)
  FROM Schedule
  WHERE StartTime < @Date
)
SELECT *
FROM NewSchedules
WHERE TimeDifferenceInSeconds > DATEDIFF(ss, NewStartTime , @Date)


问:
omnet++ 5.4.1 shows xml parser error in inet examples
i try to run Inet framework examples in omnet++ but i get this error and dont know how to solve it

 Error: Cannot evaluate parameter 'config': Cannot parse XML
  string: XML input is not supported: this copy of OMNeT++ was compiled
  without an XML parser (libXML or Expat) -- in module
  (inet::Ipv4NetworkConfigurator) Net80211.configurator (id=3), during
  network setup

答: I too got the same error but I found a solution which might be useful. OMNeT++ IDE is not running on the same environment. Just choose the project file and right click "Run As > OMNeT++ simulation", it should run without an error.</p>


问:
Override CopyToQuote in PMQuoteMaint
I am trying to override the CopyToQuote method in PMQuoteMaint, but when I load the screen, I am getting an error saying the method with that signature is not found. I verified the method was public in PMQuoteMaint and my method signature matches. I feel like I am missing something obvious, but I am at a loss for what is not working. Here is my code:

```<code>    public delegate void CopyToQuoteDelegate(PMQuote currentquote, PMQuoteMaint.CopyQuoteFilter param);
    [PXOverride]
    public void CopyToQuote(PMQuote currentquote, PMQuoteMaint.CopyQuoteFilter param, CopyToQuoteDelegate baseMethod)
    {
        //My Code here
        baseMethod(currentquote, param);
    }
</code>```

Thanks in advance for your help!

答:
In the Project Quote screen (PM304500), you can extend/override the Action "Copy Quote".
The action returns an enumerator, and accepts PXAdapter as input parameter.
In your case, "CopyToQuote" method in the base graph PMQuoteMaint, is not marked as virtual, so you cannot override it.  If you want to change the base behavior, I recommend to override the Action, and add your custom logic

```<code>    public delegate IEnumerable CopyQuoteDelegate(PXAdapter adapter);
    [PXOverride]
    public IEnumerable CopyQuote(PXAdapter adapter, CopyQuoteDelegate baseMethod)
    {
        // add your custom logic here
        // to override the base logic

        return adapter.Get();  //just returns the enumerator
    }
</code>```

Title: Override CopyToQuote in PMQuoteMaint

Body:
I am trying to override the CopyToQuote method in PMQuoteMaint, but when I load the screen, I am getting an error saying the method with that signature is not found. I verified the method was public in PMQuoteMaint and my method signature matches. I feel like I am missing something obvious, but I am at a loss for what is not working. Here is my code:

    public delegate void CopyToQuoteDelegate(PMQuote currentquote, PMQuoteMaint.CopyQuoteFilter param);
    [PXOverride]
    public void CopyToQuote(PMQuote currentquote, PMQuoteMaint.CopyQuoteFilter param, CopyToQuoteDelegate baseMethod)
    {
        //My Code here
        baseMethod(currentquote, param);
    }

Thanks in advance for your help!

Body:
In the Project Quote screen (PM304500), you can extend/override the Action "Copy Quote".
The action returns an enumerator, and accepts PXAdapter as input parameter.
In your case, "CopyToQuote" method in the base graph PMQuoteMaint, is not marked as virtual, so you cannot override it.  If you want to change the base behavior, I recommend to override the Action, and add your custom logic

    public delegate IEnumerable CopyQuoteDelegate(PXAdapter adapter);
    [PXOverride]
    public IEnumerable CopyQuote(PXAdapter adapter, CopyQuoteDelegate baseMethod)
    {
        // add your custom logic here
        // to override the base logic

        return adapter.Get();  //just returns the enumerator
    }


问:
Java for( x : y) execution
I have the following for loop:

```<code>for(String s : someString.split("\\s+")){
   //do something
}
</code>```

Does java execute the split() method each time the loop iterates, or does it do it only once and keep a temp array to iterate on?

答: It stores the array in a temporary variable before using it.</p>

Title: Java for( x : y) execution

Body:
I have the following for loop:

for(String s : someString.split("\\s+")){
   //do something
}

Does java execute the split() method each time the loop iterates, or does it do it only once and keep a temp array to iterate on?


问:
Django and post request to an external API in different views
So i want to create a Django App where my users can post data through a form and make a post request to an external API, but getting the response in the same page/view

For example, i have my view

```<code>class Home(TemplateView):
    template_name: 'home/index.html'
</code>```

And i have my index.html:

```<code><form id="formdata" >
    <select id="options">
        <option id="sku">Option 1</option>
        <option id="sku2">Option 2</option>
    </select>

    <input name="number" type="text"  id="number">

    <select id="price">
        <option id="price1">$5</option>
        <option id="price2">%10</option>
    </select>

    <button type="button" data-loading-text="enviando..." onclick="submitInfo()">Send</button>
</form>
</code>```

Let's ignore the fact HTML may be wrong, it is a basic structure of a form with selects and input field, but note that i need to pass "product", "number" and "price" as parameters in the post request.

The thing is that when the user clics on the submit button, they make a post request to an external api, i know i can do int with JavaScript using fetch, but the thing is that i need to pass my personal Token Key in the body params, also i'd like to hide the real api url hiding it with an url of my website, for example: www.myurl.com/my-api-call

So i'm thinking about creating a "external_api_view" with post request, something like this:

```<code>import requests
import time
from rest_framework import status
from rest_framework.response import Response

def external_api_view(request):
    if request.method == "POST":
        attempt_num = 0  # keep track of how many times we've retried
        while attempt_num < MAX_RETRIES:
            url = 'www.apiexternal.com/endpoint'
            payload = {'Token':'My_Secret_Token','product':'product_select_in_form','price':'price_selected_in_form'}
            response = requests.post(url, data = payload)
            if r.status_code == 200:
                data = r.json()
                return Response(data, status=status.HTTP_200_OK)
            else:
                attempt_num += 1
                # You can probably use a logger to log the error here
                time.sleep(5)  # Wait for 5 seconds before re-trying
        return Response({"error": "Request failed"}, status=r.status_code)
    else:
        return Response({"error": "Method not allowed"}, status=status.HTTP_400_BAD_REQUEST)
</code>```

But not i have the problem that i don't know how to pass inputs of the form into that view, so i can make the post request and get the response through javascript on my index.html file (adding obviously the javascript needed)

I don't even know if this is possible, i was thinking in doing something like so with rest framework, but also i have no idea how to

Any help would be really appreciated :)

答:
First add an action attribute and method attribute to your form. Then add a csrf token for security.  Also add name attributes to the select elements.

```<code><form method="post" action="/external" id="formdata" >
  {% csrf_token %}
<select name="options" id="options">
    <option id="sku">Option 1</option>
    <option id="sku2">Option 2</option>
</select>

<input name="number" type="text"  id="number">

<select name="price" id="price">
    <option id="price1">$5</option>
    <option id="price2">%10</option>
</select>

<button type="button" data-loading-text="enviando..." onclick="submitInfo()">Send</button>
</code>```

Next add the url path for the action you added.
urls.py:

```<code>from django.urls import path
from . import views

app_name = "main"

urlpatterns = [
    ...
    path("external", views.external_api_view, name="home")

]
</code>```

Then get the input values in views.py

```<code>import requests
import time
from rest_framework import status
from rest_framework.response import Response

def external_api_view(request):
    if request.method == "POST":
        attempt_num = 0  # keep track of how many times we've retried
        while attempt_num < MAX_RETRIES:
            url = 'www.apiexternal.com/endpoint'
            payload = {'Token':'My_Secret_Token','product':request.POST.get("options"),'price':request.POST.get("price")}
            r = requests.post(url, data = payload)
            if r.status_code == 200:
                data = r.json()
                return Response(data, status=status.HTTP_200_OK)
            else:
                attempt_num += 1
                # You can probably use a logger to log the error here
                time.sleep(5)  # Wait for 5 seconds before re-trying
        return Response({"error": "Request failed"}, status=r.status_code)
    else:
        return Response({"error": "Method not allowed"}, status=status.HTTP_400_BAD_REQUEST)

</code>```

Body:
So i want to create a Django App where my users can post data through a form and make a post request to an external API, but getting the response in the same page/view

For example, i have my view

class Home(TemplateView):
    template_name: 'home/index.html'

And i have my index.html:

<form id="formdata" >
    <select id="options">
        <option id="sku">Option 1</option>
        <option id="sku2">Option 2</option>
    </select>

    <input name="number" type="text"  id="number">

    <select id="price">
        <option id="price1">$5</option>
        <option id="price2">%10</option>
    </select>

    <button type="button" data-loading-text="enviando..." onclick="submitInfo()">Send</button>
</form>

Let's ignore the fact HTML may be wrong, it is a basic structure of a form with selects and input field, but note that i need to pass "product", "number" and "price" as parameters in the post request.

The thing is that when the user clics on the submit button, they make a post request to an external api, i know i can do int with JavaScript using fetch, but the thing is that i need to pass my personal Token Key in the body params, also i'd like to hide the real api url hiding it with an url of my website, for example: www.myurl.com/my-api-call

So i'm thinking about creating a "external_api_view" with post request, something like this:

import requests
import time
from rest_framework import status
from rest_framework.response import Response

def external_api_view(request):
    if request.method == "POST":
        attempt_num = 0  # keep track of how many times we've retried
        while attempt_num < MAX_RETRIES:
            url = 'www.apiexternal.com/endpoint'
            payload = {'Token':'My_Secret_Token','product':'product_select_in_form','price':'price_selected_in_form'}
            response = requests.post(url, data = payload)
            if r.status_code == 200:
                data = r.json()
                return Response(data, status=status.HTTP_200_OK)
            else:
                attempt_num += 1
                # You can probably use a logger to log the error here
                time.sleep(5)  # Wait for 5 seconds before re-trying
        return Response({"error": "Request failed"}, status=r.status_code)
    else:
        return Response({"error": "Method not allowed"}, status=status.HTTP_400_BAD_REQUEST)

But not i have the problem that i don't know how to pass inputs of the form into that view, so i can make the post request and get the response through javascript on my index.html file (adding obviously the javascript needed)

I don't even know if this is possible, i was thinking in doing something like so with rest framework, but also i have no idea how to

Any help would be really appreciated :)

Body:
First add an action attribute and method attribute to your form. Then add a csrf token for security.  Also add name attributes to the select elements.

<form method="post" action="/external" id="formdata" >
  {% csrf_token %}
<select name="options" id="options">
    <option id="sku">Option 1</option>
    <option id="sku2">Option 2</option>
</select>

<input name="number" type="text"  id="number">

<select name="price" id="price">
    <option id="price1">$5</option>
    <option id="price2">%10</option>
</select>

<button type="button" data-loading-text="enviando..." onclick="submitInfo()">Send</button>

Next add the url path for the action you added.
urls.py:

from django.urls import path
from . import views

app_name = "main"

urlpatterns = [
    ...
    path("external", views.external_api_view, name="home")

]

Then get the input values in views.py

import requests
import time
from rest_framework import status
from rest_framework.response import Response

def external_api_view(request):
    if request.method == "POST":
        attempt_num = 0  # keep track of how many times we've retried
        while attempt_num < MAX_RETRIES:
            url = 'www.apiexternal.com/endpoint'
            payload = {'Token':'My_Secret_Token','product':request.POST.get("options"),'price':request.POST.get("price")}
            r = requests.post(url, data = payload)
            if r.status_code == 200:
                data = r.json()
                return Response(data, status=status.HTTP_200_OK)
            else:
                attempt_num += 1
                # You can probably use a logger to log the error here
                time.sleep(5)  # Wait for 5 seconds before re-trying
        return Response({"error": "Request failed"}, status=r.status_code)
    else:
        return Response({"error": "Method not allowed"}, status=status.HTTP_400_BAD_REQUEST)