问:
Looping inside a string in JavaScript
How does a loop work in a string like this?</p>

```<code>var w = window.open('','','width=792,height=612');
$(w.document.body).html('<div>'+
    '<ul>' +
    for(var i=o; i<=10; i++){
        '<li>'+ i +'</li>'+
    }
    '</ul>'+
    '</div>');
</code>```

答:
I highly suggest you create your string before inserting it into your table.

$(document).ready(function(){
  var w = window.open('','','width=792,height=612');
  var myString = "";
   for(var i=0; i<=10; i++){
     myString += "
hello
";
  }
  $('body').html('
' + myString + '
');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>

</body></code>```

 I also corrected a lot of your code since there was a few error, ex: var i = o instead of i = 0.

Title: Looping inside a string in JavaScript

Body:
How does a loop work in a string like this?

var w = window.open('','','width=792,height=612');
$(w.document.body).html('
'+
    '
' +
    for(var i=o; i<=10; i++){
        '
'+ i +'
'+
    }
    '
'+
    '
');

Body:
I highly suggest you create your string before inserting it into your table.

$(document).ready(function(){
  var w = window.open('','','width=792,height=612');
  var myString = "";
   for(var i=0; i<=10; i++){
     myString += "<tr><td>hello</td></tr>";
  }
  $('body').html('<table>' + myString + '</table>');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>

</body>

 I also corrected a lot of your code since there was a few error, ex: var i = o instead of i = 0.


来源: stackexchange

问:
How to set ArrayList with isChecked in CheckBox android
How to set data with checkbox when user clicks submit? I want to get all data within isChecked()

And I try this code which doesn't work.

myadapter

```<code>viewHoder.cx_select_invite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            Log.d("ChatGroupInviteAdap", "onClick position: " + position);
            Log.d("ChatGroupInviteAdap", "onClick getFirstname: " + chatFriendsListModels.get(position).getFirstname());
            id = chatFriendsListModels.get(position).getId();
            ChatGroupInviteFragment.dataMember.add(id);
        }

        if (!isChecked) {
            id = chatFriendsListModels.get(position).getId();
            ChatGroupInviteFragment.dataMember.remove(id);
        }

    }
});
</code>```

myFragment

user clicks submit when user checks finish

```<code>tx_submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.d(TAG, "OnClick: " + ChatGroupInviteFragment.dataMember.size());

        for (int i=0;i<ChatGroupInviteFragment.dataMember.size();i++){
            Log.d(TAG, "OnClick2 : " + ChatGroupInviteFragment.dataMember.get(i));
        }
    }
});
</code>```

I get error when user unChecked

FATAL EXCEPTION: main
                                                                           Process: xxx.xx.x, PID: 20496
                                                                           java.lang.IndexOutOfBoundsException: Invalid index 36, size is 3

```<code>36 is id unChecked

and 3 = size isChecked
</code>```

How to set it?

答:
Add one boolean parameter isChecked to your model class
and then do like this

```<code>    viewHoder.cx_select_invite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                chatFriendsListModels.isChecked(isChecked);

            }
        });
</code>```

and then on your final submit button do like this

```<code>tx_submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        for (int i=0;i<chatFriendsListModels.size();i++){
            if(chatFriendsListModels.isChecked()==true)
           String id = chatFriendsListModels.get(i).getId();
            // you do what you want with id here
        }

    }
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How to set data with checkbox when user clicks submit? I want to get all data within isChecked()

And I try this code which doesn't work.

myadapter

viewHoder.cx_select_invite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            Log.d("ChatGroupInviteAdap", "onClick position: " + position);
            Log.d("ChatGroupInviteAdap", "onClick getFirstname: " + chatFriendsListModels.get(position).getFirstname());
            id = chatFriendsListModels.get(position).getId();
            ChatGroupInviteFragment.dataMember.add(id);
        }

        if (!isChecked) {
            id = chatFriendsListModels.get(position).getId();
            ChatGroupInviteFragment.dataMember.remove(id);
        }

    }
});

myFragment

user clicks submit when user checks finish

tx_submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.d(TAG, "OnClick: " + ChatGroupInviteFragment.dataMember.size());

        for (int i=0;i<ChatGroupInviteFragment.dataMember.size();i++){
            Log.d(TAG, "OnClick2 : " + ChatGroupInviteFragment.dataMember.get(i));
        }
    }
});

I get error when user unChecked

FATAL EXCEPTION: main
                                                                           Process: xxx.xx.x, PID: 20496
                                                                           java.lang.IndexOutOfBoundsException: Invalid index 36, size is 3

36 is id unChecked

and 3 = size isChecked

How to set it?

Body:
Add one boolean parameter isChecked to your model class
and then do like this

    viewHoder.cx_select_invite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                chatFriendsListModels.isChecked(isChecked);

            }
        });

and then on your final submit button do like this

tx_submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        for (int i=0;i<chatFriendsListModels.size();i++){
            if(chatFriendsListModels.isChecked()==true)
           String id = chatFriendsListModels.get(i).getId();
            // you do what you want with id here
        }

    }
});

ContentLicense: CC BY-SA 4.0


问:
Gini Index in R
I am trying to calculate the Gini index for each row of my database. Each row is a customer and each column is a monthly session. So what i need to do is to add a column with the Gini index by row, for each customer throughout the 12 months.
See example attached

I found some examples online and did this:

```<code>Gini_index <- apply(DT_file[,c('sessions_201607_pct','sessions_201608_pct', 'sessions_201609_pct','sessions_201610_pct','sessions_201611_pct','sessions_201612_pct','sessions_201701_pct','sessions_201702_pct','sessions_201703_pct','sessions_201704_pct','sessions_201705_pct','sessions_201706_pct')], 1, gini)
</code>```

However, I get the following error:

Error in match.fun(FUN) : object 'gini' not found

I have installed both Ineq and Reldist (and libraries) so I don't know why this isn't working.

答:
Try to do this to have your gini's coeff by column :

```<code>library(ineq)

coeff= NULL
for (i in colnames(your_data[,-1])){
  coeff= c(coeff,round(ineq(your_data[,i],type = 'Gini'),4))
}

data_coeff = data.frame(cbind(coeff,colnames(your_data[,-1])))
colnames(data_coeff) = c("Coeff","Colnames")
</code>```

If you want it by for each rows try this :

```<code>your_new_data = as.data.frame(t(your_data[,-1]), row.names =T)

colnames(your_new_data) = your_data[,1]

ind = NULL
for (i in colnames(your_new_data)){
  ind = c(ind,round(ineq(your_new_data[,i],type = 'Gini'),4))
}

data_coeff= data.frame(cbind(ind,colnames(your_new_data)))
colnames(data_coeff) = c("Coeff","customer")
</code>```

Finaly you add your coeffs at the end of your data_frame with a merge for instance :

```<code>your_data_final = merge(your_data,data_coeff, by = "customer" )
</code>```

Title: Gini Index in R

Body:
I am trying to calculate the Gini index for each row of my database. Each row is a customer and each column is a monthly session. So what i need to do is to add a column with the Gini index by row, for each customer throughout the 12 months.
See example attached

I found some examples online and did this:

Gini_index <- apply(DT_file[,c('sessions_201607_pct','sessions_201608_pct', 'sessions_201609_pct','sessions_201610_pct','sessions_201611_pct','sessions_201612_pct','sessions_201701_pct','sessions_201702_pct','sessions_201703_pct','sessions_201704_pct','sessions_201705_pct','sessions_201706_pct')], 1, gini)

However, I get the following error:

Error in match.fun(FUN) : object 'gini' not found

I have installed both Ineq and Reldist (and libraries) so I don't know why this isn't working.

Body:
Try to do this to have your gini's coeff by column :

library(ineq)

coeff= NULL
for (i in colnames(your_data[,-1])){
  coeff= c(coeff,round(ineq(your_data[,i],type = 'Gini'),4))
}

data_coeff = data.frame(cbind(coeff,colnames(your_data[,-1])))
colnames(data_coeff) = c("Coeff","Colnames")

If you want it by for each rows try this :

your_new_data = as.data.frame(t(your_data[,-1]), row.names =T)

colnames(your_new_data) = your_data[,1]

ind = NULL
for (i in colnames(your_new_data)){
  ind = c(ind,round(ineq(your_new_data[,i],type = 'Gini'),4))
}

data_coeff= data.frame(cbind(ind,colnames(your_new_data)))
colnames(data_coeff) = c("Coeff","customer")

Finaly you add your coeffs at the end of your data_frame with a merge for instance :

your_data_final = merge(your_data,data_coeff, by = "customer" )


问:
MYSQL Query - Some results don't return
I have a problem im my sql query:

```<code>SELECT table_2.id, SUM(table_2.time + table_4.time + table_6.time + table_8.time + table_10.time + table_12.time) AS total_time, SUM(table_2.connects + table_4.connects + table_6.connects + table_8.connects + table_10.connects + table_12.connects) AS total_connects FROM table_2
  INNER JOIN table_4 ON table_2.id = table_4.id
  INNER JOIN table_6 ON table_2.id = table_6.id
  INNER JOIN table_8 ON table_2.id = table_8.id
  INNER JOIN table_10 ON table_2.id = table_10.id
  INNER JOIN table_12 ON table_2.id = table_12.id
GROUP BY table_2.authid ORDER BY total_time DESC
</code>```

Ok, I have a script that grabs the user IDS and the time they spent and then puts it in mysql tables depending on which forum they have entered. The query above seems to be working fine but only for the users that have entered all forums, because the others that haven't entered in all forums don't return any result.

The ID is always the same, it is the users ID and connects is the number of times the user enters the specific forum.

If you understand my problem and know the answear please let me know, otherwise I'll try to explain better

Thanks

答: Replace the INNER JOIN by a LEFT OUTER JOIN this will get you results over all the tables. You might need to re-define the SUM probably you'll get NULL on users who haven't visited all forums...</p>

ContentLicense: CC BY-SA 2.5

Title: MYSQL Query - Some results don't return

Body:
I have a problem im my sql query:

SELECT table_2.id, SUM(table_2.time + table_4.time + table_6.time + table_8.time + table_10.time + table_12.time) AS total_time, SUM(table_2.connects + table_4.connects + table_6.connects + table_8.connects + table_10.connects + table_12.connects) AS total_connects FROM table_2
  INNER JOIN table_4 ON table_2.id = table_4.id
  INNER JOIN table_6 ON table_2.id = table_6.id
  INNER JOIN table_8 ON table_2.id = table_8.id
  INNER JOIN table_10 ON table_2.id = table_10.id
  INNER JOIN table_12 ON table_2.id = table_12.id
GROUP BY table_2.authid ORDER BY total_time DESC

Ok, I have a script that grabs the user IDS and the time they spent and then puts it in mysql tables depending on which forum they have entered. The query above seems to be working fine but only for the users that have entered all forums, because the others that haven't entered in all forums don't return any result.

The ID is always the same, it is the users ID and connects is the number of times the user enters the specific forum.

If you understand my problem and know the answear please let me know, otherwise I'll try to explain better

Thanks


问:
How to send a stacktrace to log4j?
Say you catch an exception and get the following on the standard output (like, say, the console) if you do a e.printStackTrace() :

```<code>java.io.FileNotFoundException: so.txt
        at java.io.FileInputStream.<init>(FileInputStream.java)
        at ExTest.readMyFile(ExTest.java:19)
        at ExTest.main(ExTest.java:7)
</code>```

Now I want to send this instead to a logger like, say, log4j to get the following:

```<code>31947 [AWT-EventQueue-0] ERROR Java.io.FileNotFoundException: so.txt
32204 [AWT-EventQueue-0] ERROR    at java.io.FileInputStream.<init>(FileInputStream.java)
32235 [AWT-EventQueue-0] ERROR    at ExTest.readMyFile(ExTest.java:19)
32370 [AWT-EventQueue-0] ERROR    at ExTest.main(ExTest.java:7)
</code>```

How can I do this?

```<code>try {
   ...
} catch (Exception e) {
    final String s;
    ...  // <-- What goes here?
    log.error( s );
}
</code>```

答:
The answer from skaffman is definitely the correct answer. All logger methods such as error(), warn(), info(), debug() take Throwable as a second parameter:

```<code>try {
...
 } catch (Exception e) {
logger.error("error: ", e);
}
</code>```

However, you can extract stacktrace as a String as well. Sometimes it could be useful if you wish to take advantage of formatting feature using "{}" placeholder - see method void info(String var1, Object... var2); In this case say you have a stacktrace as String, then you can actually do something like this:

```<code>try {
...
 } catch (Exception e) {
String stacktrace = TextUtils.getStacktrace(e);
logger.error("error occurred for usename {} and group {}, details: {}",username, group, stacktrace);
}
</code>```

This will print parametrized message and the stacktrace at the end the same way it does for method: logger.error("error: ", e);

I actually wrote an open source library that has a Utility for extraction of a stacktrace as a String with an option to smartly filter out some noise out of stacktrace. I.e. if you specify the package prefix that you are interested in your extracted stacktrace would be filtered out of some irrelevant parts and leave you with very consized info. Here is the link to the article that explains what utilities the library has and where to get it (both as maven artifacts and git sources) and how to use it as well. Open Source Java library with stack trace filtering, Silent String parsing Unicode converter and Version comparison  See the paragraph "Stacktrace noise filter"

Title: How to send a stacktrace to log4j?

Body:
Say you catch an exception and get the following on the standard output (like, say, the console) if you do a e.printStackTrace() :

java.io.FileNotFoundException: so.txt
        at java.io.FileInputStream.<init>(FileInputStream.java)
        at ExTest.readMyFile(ExTest.java:19)
        at ExTest.main(ExTest.java:7)

Now I want to send this instead to a logger like, say, log4j to get the following:

31947 [AWT-EventQueue-0] ERROR Java.io.FileNotFoundException: so.txt
32204 [AWT-EventQueue-0] ERROR    at java.io.FileInputStream.<init>(FileInputStream.java)
32235 [AWT-EventQueue-0] ERROR    at ExTest.readMyFile(ExTest.java:19)
32370 [AWT-EventQueue-0] ERROR    at ExTest.main(ExTest.java:7)

How can I do this?

try {
   ...
} catch (Exception e) {
    final String s;
    ...  // <-- What goes here?
    log.error( s );
}

Body:
The answer from skaffman is definitely the correct answer. All logger methods such as error(), warn(), info(), debug() take Throwable as a second parameter:

try {
...
 } catch (Exception e) {
logger.error("error: ", e);
}

However, you can extract stacktrace as a String as well. Sometimes it could be useful if you wish to take advantage of formatting feature using "{}" placeholder - see method void info(String var1, Object... var2); In this case say you have a stacktrace as String, then you can actually do something like this:

try {
...
 } catch (Exception e) {
String stacktrace = TextUtils.getStacktrace(e);
logger.error("error occurred for usename {} and group {}, details: {}",username, group, stacktrace);
}

This will print parametrized message and the stacktrace at the end the same way it does for method: logger.error("error: ", e);

I actually wrote an open source library that has a Utility for extraction of a stacktrace as a String with an option to smartly filter out some noise out of stacktrace. I.e. if you specify the package prefix that you are interested in your extracted stacktrace would be filtered out of some irrelevant parts and leave you with very consized info. Here is the link to the article that explains what utilities the library has and where to get it (both as maven artifacts and git sources) and how to use it as well. Open Source Java library with stack trace filtering, Silent String parsing Unicode converter and Version comparison  See the paragraph "Stacktrace noise filter"


问:
SQLite3::SQLException: near "&": syntax error: SELECT "pages".* FROM "pages" WHERE (menu_display=true && is_published=true)
How to get rid of this exception?!

答:
Use the power of Rails and use </p>

```<code>Page.where(:menu_display => true, :is_published => true)...
</code>```

Body: How to get rid of this exception?!

Body:
Use the power of Rails and use

Page.where(:menu_display => true, :is_published => true)...


问:
R - Calculate difference (similarity measure) between similar datasets
I have seen many questions that touch on this topic but haven't yet found an answer. If I have missed a question that does answer this question, please do mark this and point us to the question.

Scenario: We have a benchmark dataset, we have imputation methods, we systematically delete values from the benchmark and use two different imputation methods. Thus we have a benchmark, imputedData1 and imputedData2.

Question: Is there a function that can produce a number that represents the difference between the benchmark and imputedData1 or/and the difference between the benchmark and imputedData2. Ie function(benchmark, imputedData1) = 3.3 and function(benchmark, imputedData2) = 2.8

Note: Datasets are numerical, datasets are the same size, method should work at the data level if possible (ie not creating a regression and comparing regressions - unless it can work with ANY numerical dataset).

Reproducible datasets, they have only been changed in the first row:

benchmark:

```<code>> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
</code>```

imputedData1:

```<code>> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         22.0   4 108.0 100 3.90 2.200 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
</code>```

imputedData2:

```<code>> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         18.0   6 112.0 105 3.90 2.620 16.46  0  0    3    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
</code>```

I have tried to use RMSE (root mean squared error) but it didn't work very well so I am trying to find other ways to tackle this problem.

答:
One possible way is to calculate a norm of their difference and prefer the imputation method that minimises this value.  There are different matrix norms for different purposes.  I'll point you to the wikipedia as a starting point - https://en.wikipedia.org/wiki/Matrix_norm.  </p>

<p>In the absence of any specifics about your data I can't really say which you should choose but one method could be to create your own index that averages across different matrix norms and select the imputation method that minimizes this average.  Or you could just eyeball them and with any luck one of the methods is a clear winner across most or all matrix norms.  </p>

Body:
I have seen many questions that touch on this topic but haven't yet found an answer. If I have missed a question that does answer this question, please do mark this and point us to the question.

Scenario: We have a benchmark dataset, we have imputation methods, we systematically delete values from the benchmark and use two different imputation methods. Thus we have a benchmark, imputedData1 and imputedData2.

Question: Is there a function that can produce a number that represents the difference between the benchmark and imputedData1 or/and the difference between the benchmark and imputedData2. Ie function(benchmark, imputedData1) = 3.3 and function(benchmark, imputedData2) = 2.8

Note: Datasets are numerical, datasets are the same size, method should work at the data level if possible (ie not creating a regression and comparing regressions - unless it can work with ANY numerical dataset).

Reproducible datasets, they have only been changed in the first row:

benchmark:

> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4

imputedData1:

> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         22.0   4 108.0 100 3.90 2.200 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4

imputedData2:

> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         18.0   6 112.0 105 3.90 2.620 16.46  0  0    3    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4

I have tried to use RMSE (root mean squared error) but it didn't work very well so I am trying to find other ways to tackle this problem.

Body:
One possible way is to calculate a norm of their difference and prefer the imputation method that minimises this value.  There are different matrix norms for different purposes.  I'll point you to the wikipedia as a starting point - https://en.wikipedia.org/wiki/Matrix_norm.

In the absence of any specifics about your data I can't really say which you should choose but one method could be to create your own index that averages across different matrix norms and select the imputation method that minimizes this average.  Or you could just eyeball them and with any luck one of the methods is a clear winner across most or all matrix norms.


问:
SQL Server Concatenate results on one line
I've been trying to do the following with STUFF but I'm missing something I think.

I have a query which returns results from joined tables in the form

```<code>DATE       | CLIENT_ID | ITEM_DESC
2017-02-01 | 12        | GLOVES
2017-02-01 | 12        | HAT
2017-02-01 | 12        | SHOES
2017-02-01 | 25        | GLOVES
</code>```

and I want to reduce this by combining the ITEM_DESC into one line:

```<code>DATE       | CLIENT_ID | ITEM_DESC
2017-02-01 | 12        | GLOVES, HAT, SHOES
2017-02-01 | 25        | GLOVES
</code>```

I'm trying to run a nested query on the returned results:

```<code> select [Date] as PurDate, [client_ID],
 AllDetails =
 STUFF (
  (select ', ' + Details  FOR XML PATH ('')), 1, 1, ''
 )
from (select...
</code>```

However it's just returning the exact same results. I need to group the first two columns and concatenate only what's common to that combination but that's where I'm stuck.

答:
you need to add group by at the end as below:

```<code>select [Date] as PurDate, [client_ID],
 AllDetails =
 STUFF (
  (select ', ' + Details  FOR XML PATH ('')), 1, 1, ''
 )
from (select...
) a
group by [Date], [Client_Id]
</code>```

Created with your sample data and you can query as below:

```<code>Select [Date], Client_id,
    Stuff((Select ','+Item_desc from #alldata where [Date] = a.[Date] and [Client_id] = a.Client_id for xml path('')), 1,1,'')
    from #alldata a
    group by [Date], Client_id
</code>```

Input table:

```<code>create table #alldata ([Date] date, Client_id int, Item_desc varchar(15))

insert into #alldata([date], Client_id, Item_desc) values
 ('2017-02-01', 12  ,'GLOVES')
,('2017-02-01', 12  ,'HAT')
,('2017-02-01', 12  ,'SHOES')
,('2017-02-01', 25  ,'GLOVES')
</code>```

Output as below:

```<code>+------------+-----------+---------------------+
|    Date    | Client_id |      Item_Desc      |
+------------+-----------+---------------------+
| 2017-02-01 |        12 |  GLOVES, HAT, SHOES |
| 2017-02-01 |        25 |  GLOVES             |
+------------+-----------+---------------------+
</code>```

Body:
I've been trying to do the following with STUFF but I'm missing something I think.

I have a query which returns results from joined tables in the form

DATE       | CLIENT_ID | ITEM_DESC
2017-02-01 | 12        | GLOVES
2017-02-01 | 12        | HAT
2017-02-01 | 12        | SHOES
2017-02-01 | 25        | GLOVES

and I want to reduce this by combining the ITEM_DESC into one line:

DATE       | CLIENT_ID | ITEM_DESC
2017-02-01 | 12        | GLOVES, HAT, SHOES
2017-02-01 | 25        | GLOVES

I'm trying to run a nested query on the returned results:

 select [Date] as PurDate, [client_ID],
 AllDetails =
 STUFF (
  (select ', ' + Details  FOR XML PATH ('')), 1, 1, ''
 )
from (select...

However it's just returning the exact same results. I need to group the first two columns and concatenate only what's common to that combination but that's where I'm stuck.

Body:
you need to add group by at the end as below:

select [Date] as PurDate, [client_ID],
 AllDetails =
 STUFF (
  (select ', ' + Details  FOR XML PATH ('')), 1, 1, ''
 )
from (select...
) a
group by [Date], [Client_Id]

Created with your sample data and you can query as below:

Select [Date], Client_id,
    Stuff((Select ','+Item_desc from #alldata where [Date] = a.[Date] and [Client_id] = a.Client_id for xml path('')), 1,1,'')
    from #alldata a
    group by [Date], Client_id

Input table:

create table #alldata ([Date] date, Client_id int, Item_desc varchar(15))

insert into #alldata([date], Client_id, Item_desc) values
 ('2017-02-01', 12  ,'GLOVES')
,('2017-02-01', 12  ,'HAT')
,('2017-02-01', 12  ,'SHOES')
,('2017-02-01', 25  ,'GLOVES')

Output as below:

+------------+-----------+---------------------+
|    Date    | Client_id |      Item_Desc      |
+------------+-----------+---------------------+
| 2017-02-01 |        12 |  GLOVES, HAT, SHOES |
| 2017-02-01 |        25 |  GLOVES             |
+------------+-----------+---------------------+


问:
Select a row based on two other columns R
I have a dataframe df

```<code>df = data.frame(L = rep(letters[1:6], each = 2),
                M = rep(letters[7:12]),
                freq = sample(c(5, 10), replace = FALSE))

   L M freq
1  a g    5
2  a h   10
3  b i    5
4  b j   10
5  c k    5
6  c l   10
7  d g    5
8  d h   10
9  e i    5
10 e j   10
11 f k    5
12 f l   10
</code>```

I want to select the most frequent M for each L.

In this example the output would show:

```<code>h, j, l, h, j, l
</code>```

Frequency is not necessarily every second value in the actual problem.

How can I do this easily?

I've tried a tapply approach, but get stuck here because this seems to only apply to variables and can't be used to subset a subset data frame. (This didn't result in anything close so I won't post the approach)

答:
We can do

```<code>library(data.table)
setDT(df)[, .(M = M[which.max(freq)]), L]
#   L M
#1: a h
#2: b j
#3: c l
#4: d h
#5: e j
#6: f l
</code>```

Or order the 'freq' and select the first 'M' for each 'L'

```<code>setDT(df)[order(-freq), .(M = M[1]) , L]
</code>```

Body:
I have a dataframe df

df = data.frame(L = rep(letters[1:6], each = 2),
                M = rep(letters[7:12]),
                freq = sample(c(5, 10), replace = FALSE))

   L M freq
1  a g    5
2  a h   10
3  b i    5
4  b j   10
5  c k    5
6  c l   10
7  d g    5
8  d h   10
9  e i    5
10 e j   10
11 f k    5
12 f l   10

I want to select the most frequent M for each L.

In this example the output would show:

h, j, l, h, j, l

Frequency is not necessarily every second value in the actual problem.

How can I do this easily?

I've tried a tapply approach, but get stuck here because this seems to only apply to variables and can't be used to subset a subset data frame. (This didn't result in anything close so I won't post the approach)

Body:
We can do

library(data.table)
setDT(df)[, .(M = M[which.max(freq)]), L]
#   L M
#1: a h
#2: b j
#3: c l
#4: d h
#5: e j
#6: f l

Or order the 'freq' and select the first 'M' for each 'L'

setDT(df)[order(-freq), .(M = M[1]) , L]


问:
Data Not displaying while passing from controller
In asp.net MVC getting the model value but while passing to view nothing displayed.

Controller

```<code>  public ActionResult Index(plan plan1)
        {
            var myCharge = new StripeChargeCreateOptions();

            string apiKey = "";
            var stripeClient = new StripeClient(apiKey);
            var planService = new StripePlanService(apiKey);
            StripePlan response = planService.Get("1234");
            plan1.Amount = (response.Amount).ToString();

            return View();
        }
</code>```

view

```<code><div>
    @Html.TextBoxFor(m => m.Amount)

</div>
</code>```

How to display the Amount value inside textbox

答:
The answer is already given. You should return the model bij calling

```<code>return View(plan1);
</code>```

It's better to return a ViewModel instead of your model to your view.

```<code>  public class PlanViewModel
  {
     public plan plan1 { get; set; }
  }

public ActionResult Index(plan plan1)
{
   var myCharge = new StripeChargeCreateOptions();

   string apiKey = "";
   var stripeClient = new StripeClient(apiKey);
   var planService = new StripePlanService(apiKey);
   StripePlan response = planService.Get("1234");
   plan1.Amount = (response.Amount).ToString();

   var viewModel = new PlanViewModel {
      plan1 = plan1
   };

   return View(viewModel);
}
</code>```

Body:
In asp.net MVC getting the model value but while passing to view nothing displayed.

Controller

  public ActionResult Index(plan plan1)
        {
            var myCharge = new StripeChargeCreateOptions();

            string apiKey = "";
            var stripeClient = new StripeClient(apiKey);
            var planService = new StripePlanService(apiKey);
            StripePlan response = planService.Get("1234");
            plan1.Amount = (response.Amount).ToString();

            return View();
        }

view

    @Html.TextBoxFor(m => m.Amount)

How to display the Amount value inside textbox

Body:
The answer is already given. You should return the model bij calling

return View(plan1);

It's better to return a ViewModel instead of your model to your view.

  public class PlanViewModel
  {
     public plan plan1 { get; set; }
  }

public ActionResult Index(plan plan1)
{
   var myCharge = new StripeChargeCreateOptions();

   string apiKey = "";
   var stripeClient = new StripeClient(apiKey);
   var planService = new StripePlanService(apiKey);
   StripePlan response = planService.Get("1234");
   plan1.Amount = (response.Amount).ToString();

   var viewModel = new PlanViewModel {
      plan1 = plan1
   };

   return View(viewModel);
}


问:
javascript frameworks prototype to jquery
I have found the following script which is apparently written using the javascript framework prototype.

```<code>Event.observe(window, 'load', function() {

    Event.observe( 'btnSubmit', 'click', purchaseCD);

    connectToServer();
});

function connectToServer()
{
    new Ajax.Updater(
        { success: 'CD Count', failure: 'errors' },
        'server_side.php',
        {
            method:     'get',
            onSuccess:  function(transport)
            {
                if (parseInt(transport.responseText)) connectToServer();
            }
    });
}

function purchaseCD()
{
    new Ajax.Updater(
        { success: 'CD Count', failure: 'errors' },
        'server_side.php',
        {
            method:     'get',
            parameters: { num: $('txtQty').getValue() }
    });
}
</code>```

Is anyone here able to convert this script to use jQuery instead of prototype?  I don't know prorotype at all so I don't understand it.

答:
Ajax.Updater takes, as parameter 1, two containers into which it will update the successful or failed response of a request to the URL given in parameter 2.

What this script does is that upon page load (I translated it below to DOMReady which is not exactly the same, but jQuery convention) an AJAX request is sent to server_side.php. If it gets a response that it understands, it immediately sends off another request, in order to keep the session alive.

This looks like a terrible design. If you're going to do something like that, you definitely want a timeout between the requests.

Another thing that's not very neat with this script is that every AJAX request is handled by the same page - server_side.php - relying on different parameters for instructions on what action to perform. It would appear cleaner to simply request different pages for different actions.

```<code>$(function() {
    $('#btnSubmit').click(purchaseCD);
    connectToServer();
});

function connectToServer() {
    $.ajax({
        url: "server_side.php",
        success: function(res) {
            $('#CD Count').html(res);
            if(parseInt(res))
                connectToServer();
        },
        error: function(xhr) {
            $('#errors').html(xhr.responseText);
        }
    });
}

function purchaseCD() {
    $.ajax({
        url: "server_side.php",
        success: function(res) {
            $('#CD Count').html(res);
        },
        data: { num: $('#txtQty').val() },
        error: function(xhr) {
            $('#errors').html(xhr.responseText);
        }
    });
}
</code>```

Body:
I have found the following script which is apparently written using the javascript framework prototype.

Event.observe(window, 'load', function() {

    Event.observe( 'btnSubmit', 'click', purchaseCD);

    connectToServer();
});

function connectToServer()
{
    new Ajax.Updater(
        { success: 'CD Count', failure: 'errors' },
        'server_side.php',
        {
            method:     'get',
            onSuccess:  function(transport)
            {
                if (parseInt(transport.responseText)) connectToServer();
            }
    });
}

function purchaseCD()
{
    new Ajax.Updater(
        { success: 'CD Count', failure: 'errors' },
        'server_side.php',
        {
            method:     'get',
            parameters: { num: $('txtQty').getValue() }
    });
}

Is anyone here able to convert this script to use jQuery instead of prototype?  I don't know prorotype at all so I don't understand it.

Body:
Ajax.Updater takes, as parameter 1, two containers into which it will update the successful or failed response of a request to the URL given in parameter 2.

What this script does is that upon page load (I translated it below to DOMReady which is not exactly the same, but jQuery convention) an AJAX request is sent to server_side.php. If it gets a response that it understands, it immediately sends off another request, in order to keep the session alive.

This looks like a terrible design. If you're going to do something like that, you definitely want a timeout between the requests.

Another thing that's not very neat with this script is that every AJAX request is handled by the same page - server_side.php - relying on different parameters for instructions on what action to perform. It would appear cleaner to simply request different pages for different actions.

$(function() {
    $('#btnSubmit').click(purchaseCD);
    connectToServer();
});

function connectToServer() {
    $.ajax({
        url: "server_side.php",
        success: function(res) {
            $('#CD Count').html(res);
            if(parseInt(res))
                connectToServer();
        },
        error: function(xhr) {
            $('#errors').html(xhr.responseText);
        }
    });
}

function purchaseCD() {
    $.ajax({
        url: "server_side.php",
        success: function(res) {
            $('#CD Count').html(res);
        },
        data: { num: $('#txtQty').val() },
        error: function(xhr) {
            $('#errors').html(xhr.responseText);
        }
    });
}


问:
Rename laravel collection "data" key
Is there way i can rename the data key in laravel collection results? At the moment this

```<code>DB::table('contracts AS C')->paginate(1)
</code>```

returns

  {
  "current_page": 1,
    "data": [
        {
            "id": 191,
            "buyer": "John",
            "provider": "Jane"
        }
    ],
    "from": 1,
    "last_page": 1,
    "next_page_url": "",
    "path": "",
    "per_page": 1,
    "prev_page_url": null,
    "to": 1,
    "total": 1
}```
</div>
</div>
</p>

<p>What i would like is this</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>  {
  "current_page": 1,
    "parties": [
        {
            "id": 191,
            "buyer": "John",
            "provider": "Jane"
        }
    ],
    "from": 1,
    "last_page": 1,
    "next_page_url": "",
    "path": "",
    "per_page": 1,
    "prev_page_url": null,
    "to": 1,
    "total": 1
}</code>```

The challenge here changing the data key to parties

答:
The data key is only set when the Paginator object toArray() is called. Before that it's a Collection with the key items.

Quick and dirty solution would be to call toArray() on the Paginator object and change the key name of the array before the json_encode().

Another solution would be to extend the Builder class, much like it's done here, overwrite the paginate() method and Paginator's toArray() method.

Title: Rename laravel collection "data" key

Body:
Is there way i can rename the data key in laravel collection results? At the moment this

DB::table('contracts AS C')->paginate(1)

returns

  {
  "current_page": 1,
    "data": [
        {
            "id": 191,
            "buyer": "John",
            "provider": "Jane"
        }
    ],
    "from": 1,
    "last_page": 1,
    "next_page_url": "",
    "path": "",
    "per_page": 1,
    "prev_page_url": null,
    "to": 1,
    "total": 1
}

What i would like is this

  {
  "current_page": 1,
    "parties": [
        {
            "id": 191,
            "buyer": "John",
            "provider": "Jane"
        }
    ],
    "from": 1,
    "last_page": 1,
    "next_page_url": "",
    "path": "",
    "per_page": 1,
    "prev_page_url": null,
    "to": 1,
    "total": 1
}

The challenge here changing the data key to parties


问:
context window of frames speech recognition
In many speech recognition paper, I see this term "context window of frame". I am not sure about that but it seem like u take a frame x from a utterance, and you concatenation this frame with 5 previous frames and 5 future frames. And the label for this context window is the center frame. Am I right?

Thank you

(Btw the number 5 is just an example)

答:
Yes, this term gained popularity starting from application of Deep Neural Networks (DNN) to Automatic Speech Recognition. For example, "11 frame acoustic context window" means you concatenate feature vectors of 5 previous and 5 future frames to current frame's vector. But the label is still center frame's label. Using context windows improved performance of DNN models, but not previously used HMMs (Hidden Markov Models).

Please refer to this article for more info.


问:
internship interview, best JSON structure
So i had this internship interview for a PHP and MySQL internship and after talking for a while they gave me some test questions to see if i got skills, dead line to answer is tonight.

I was able to solve most questions but there was three of them i couldn't figure out how to answer them, they are about JSON and API, so here they are :

Propose a JSON structure that sends informations upon login (email and password) to an API

Propose a JSON structure that returns a response to the previous call

Same question as question 2, knowing that you evolve with an API

I'm really lost, isn't the JSON structure relative to how the API is expecting to receive data ?

What is the best answer i can give to those three questions ?

答:
These questions are valid as they most probably want to know if you are capable of designing API's. API is the interface and JSON is the interface format. The questions are regarding the format, For example a very simple login api, could be that the client must send over the following as a post request.

```<code>{ "email" : "user@xyz.com", "password" : "password" }
</code>```

If the client sent a request which was not a post request, the response could be

```<code>{ "status" : "405", "msg" : "http method not allowed" }
</code>```

or if the authorizarion failed,

```<code>{ "status" : "401", "msg" : "unauthorized" }
</code>```

if successfull

```<code>{ "status" : "200", "token" : "some long crypto hash string" }
</code>```

The token can then be used in subsequent API calls to identify the user.

Body:
These questions are valid as they most probably want to know if you are capable of designing API's. API is the interface and JSON is the interface format. The questions are regarding the format, For example a very simple login api, could be that the client must send over the following as a post request.

{ "email" : "user@xyz.com", "password" : "password" }

If the client sent a request which was not a post request, the response could be

{ "status" : "405", "msg" : "http method not allowed" }

or if the authorizarion failed,

{ "status" : "401", "msg" : "unauthorized" }

if successfull

{ "status" : "200", "token" : "some long crypto hash string" }

The token can then be used in subsequent API calls to identify the user.


问:
Functor type variables for Flip data type
I have following type definition:

```<code>newtype Flip f a b =
  Flip (f b a) deriving (Eq, Show)
</code>```

Does the Flip data constructor has one or three arguments?

Consinder following implementation:

```<code>data K a b = K a

newtype Flip f a b =
  Flip (f b a) deriving (Eq, Show)

instance Functor (Flip K a) where
  fmap f (Flip (K b)) = Flip (K (f b))
</code>```

What is the type of (Flip K a)?

答:
The Flip data constructor has one argument. That argument has type f b a.

That thus means that f itself is a higher order type argument with type f :: * -> * -> *. A more rigorous newtype statement would be:

```<code>newtype Flip (f :: * -> * -> *) a b = Flip (f b a)
</code>```

You can thus for instance instantiate a Flip Either Int Bool, since Either is a type that requires two additional type parameters, and then construct a Flip (Right 1) :: Flip Either Int Bool.

What is the type of (Flip K a)?

Flip K a is not a fully applied type. In pseudo-code, it has type b -> Flip K a b. Once the b has been resolved (Functor works with higher order types), we know that the only argument of Flip will have a K b constructor. So for instance Flip (K 1) is a Flip K a Int type.

Body:
I have following type definition:

newtype Flip f a b =
  Flip (f b a) deriving (Eq, Show)

Does the Flip data constructor has one or three arguments?

Consinder following implementation:

data K a b = K a

newtype Flip f a b =
  Flip (f b a) deriving (Eq, Show)

instance Functor (Flip K a) where
  fmap f (Flip (K b)) = Flip (K (f b))

What is the type of (Flip K a)?

Body:
The Flip data constructor has one argument. That argument has type f b a.

That thus means that f itself is a higher order type argument with type f :: * -> * -> *. A more rigorous newtype statement would be:

newtype Flip (f :: * -> * -> *) a b = Flip (f b a)

You can thus for instance instantiate a Flip Either Int Bool, since Either is a type that requires two additional type parameters, and then construct a Flip (Right 1) :: Flip Either Int Bool.

What is the type of (Flip K a)?

Flip K a is not a fully applied type. In pseudo-code, it has type b -> Flip K a b. Once the b has been resolved (Functor works with higher order types), we know that the only argument of Flip will have a K b constructor. So for instance Flip (K 1) is a Flip K a Int type.


问:
Javascript XMLHttpRequest: Ignore invalid SSL Certificate
so I have been having trouble with grabbing information from a device that is interfaced with via https due to the fact that it has an invalid security certificate.  I know the device is to be trusted and I don't have access to the server-side so I can't change it.  I was wondering if there was any way to set up an XMLHttpRequest object in Javascript to just ignore an invalid SSL certificate and just grab the information anyway.  As it is now it seems to just reject the certificate and stop.  Thanks.</p>

答: No, there isn't.  XMLHTTPRequest doesn't allow you to override that.  Being able to override SSL security might make sense in your case, but if you think about it, it would be a bad idea in general.  You'd never want to allow arbitrary javascript code on the internet to connect to a supposedly secure service that the js host (the browser) knows has a possible MITM issue.</p>


问:
Typescript type requiring any one attribute of an object to be defined: how?
I have the following TypeScript code:

```<code>interface qux {
    foo?: string;
    bar?: number | string;
}

function foobar(x: qux) { ...; something_frobz(x); ...; }
</code>```

Problem: I can call foobar("hello, world"), even though this causes something_frobz to misbehave. I would like to catch and reject calls to foobar with string argument at compile time, while altering the structure of qux as little as possible. What's the best way of going about this?

My own solution is to make one field required; that field has a sensible default value, and AFAIK string doesn't have any fields with the same name. That's a bit of a hack, but it works.

Another approach might be to have foobar take a union type of first-field-is-required | second-field-is-required | ... | hundredth-field-is-required, but then I have to maintain N almost-identical copies of qux (for N > 1) and that never goes well.

Is there anything better?

答:
Typescript version 2.2 - 2.3

To prevent passing "primitives" as a parameter, you can require it to be an object:

```<code>function foobar(x: qux & object) { }

foobar(''); //error
foobar(1); //error
foobar({a:1}); //error

foobar({foo:'bar'}); //ok
</code>```

Typescript version >= 2.4 object constraint is not required anymore. See @dbandstra's answer for more information.

Body:
I have the following TypeScript code:

interface qux {
    foo?: string;
    bar?: number | string;
}

function foobar(x: qux) { ...; something_frobz(x); ...; }

Problem: I can call foobar("hello, world"), even though this causes something_frobz to misbehave. I would like to catch and reject calls to foobar with string argument at compile time, while altering the structure of qux as little as possible. What's the best way of going about this?

My own solution is to make one field required; that field has a sensible default value, and AFAIK string doesn't have any fields with the same name. That's a bit of a hack, but it works.

Another approach might be to have foobar take a union type of first-field-is-required | second-field-is-required | ... | hundredth-field-is-required, but then I have to maintain N almost-identical copies of qux (for N > 1) and that never goes well.

Is there anything better?

Body:
Typescript version 2.2 - 2.3

To prevent passing "primitives" as a parameter, you can require it to be an object:

function foobar(x: qux & object) { }

foobar(''); //error
foobar(1); //error
foobar({a:1}); //error

foobar({foo:'bar'}); //ok

Typescript version >= 2.4 object constraint is not required anymore. See @dbandstra's answer for more information.


问:
Google BigQuery - Updating a nested repeated field
I am trying to update the hits.page.pagePath field in the Google Analytics export in BigQuery, however i'm unable to unnest the field using the method outlined in the documentation. In my case, the pagePath field is nested at two levels, "hits" and "page".

https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#update_repeated_records

The following code is incomplete, but I'm stuck with unnesting pagePath from the page RECORD.

```<code>UPDATE `project-name.datasetId.ga_sessions_yyyymmdd`

SET hits = ARRAY(
  SELECT page.pagePath FROM UNNEST(hits) as pagePath
  )

WHERE fullVisitorID like "%1%"
</code>```

Has anyone managed to use update this field or a similar one in the GA export?

Thanks.

答:
This should help get you started. You need to include everything else from hits in order to perform the update, including the nested page.

```<code>UPDATE `you_dataset.tablename`
SET hits = ARRAY(
  SELECT AS STRUCT * REPLACE (
    (SELECT AS STRUCT page.* REPLACE ('foo' AS pagePath)) AS page
  )
  FROM UNNEST(hits) as pagePath
)
WHERE fullVisitorID like "%1%"
</code>```

Body:
I am trying to update the hits.page.pagePath field in the Google Analytics export in BigQuery, however i'm unable to unnest the field using the method outlined in the documentation. In my case, the pagePath field is nested at two levels, "hits" and "page".

https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#update_repeated_records

The following code is incomplete, but I'm stuck with unnesting pagePath from the page RECORD.

UPDATE `project-name.datasetId.ga_sessions_yyyymmdd`

SET hits = ARRAY(
  SELECT page.pagePath FROM UNNEST(hits) as pagePath
  )

WHERE fullVisitorID like "%1%"

Has anyone managed to use update this field or a similar one in the GA export?

Thanks.

Body:
This should help get you started. You need to include everything else from hits in order to perform the update, including the nested page.

UPDATE `you_dataset.tablename`
SET hits = ARRAY(
  SELECT AS STRUCT * REPLACE (
    (SELECT AS STRUCT page.* REPLACE ('foo' AS pagePath)) AS page
  )
  FROM UNNEST(hits) as pagePath
)
WHERE fullVisitorID like "%1%"


问:
Forecasting of BEKK(1,1) model for 5 variables
I have estimated a BEKK(1,1) model and now I want to have forecast values of the model. Following are the R codes to estimate the BEKK(1,1) model.

```<code>> install.packages('MTS')
> install.packages('rmgarch')
> simulated <- simulateBEKK(2, 1000, c(1, 1))

##prepare the matrix:
> simulated <- do.call(cbind, simulated$eps)

##Estimate with default arguments:
> estimated <- BEKK(simulated)
> diagnoseBEKK(estimated)
</code>```

答:
Since your question (is it a question?) doesn't really make clear what you are trying to achieve (and mixes up packages / commands) I will answer to what I think you want to know.

First of all, the commands you describe come from the package mgarchBEKK, not MTS or rmgarch.

I will stick with your example, which has two series (not five, like implied by your title).

1. Model simulation and estimation

You run your code (example actually comes from the documentation, page 4:

```<code>install.packages('mgarchBEKK')
library('mgarchBEKK')
## Simulate series: (2 = number of series to be simulated,
##                   1000 = length of series to be simulated,
##                   c(1,1) = BEKK(p, q) order.
simulated = simulateBEKK(2, 1000, c(1,1))
## Prepare the matrix:
simulated = do.call(cbind, simulated$eps)
## Estimate with default arguments:
estimated = BEKK(simulated)
</code>```

Now you have all the information stored in estimated. Assuming your input variables would be e. g. daily return series from shares or indices the last value for H would be your forecast for the conditional variance of tomorrow and the last value for cor your forecast for the conditional correlation of tomorrow. So basically a 1-day-forecast.

2. Preparing the data

You could store the conditional standarddeviation and conditional correlation in a sepearte data frame for convienience. Like:

```<code>results = data.frame('bekk.csd.variable1' = estimated$sd[[1]],
                     'bekk.csd.variable2' = estimated$sd[[2]],
                     'bekk.ccor.var1_var2' = estimated$[[1]][[2]])
</code>```

3. Show the results

And then show your 1-day/period-forecast for the conditional volatility and conditional correlation:

```<code>tail(results, n = 1)
</code>```

Body:
I have estimated a BEKK(1,1) model and now I want to have forecast values of the model. Following are the R codes to estimate the BEKK(1,1) model.

> install.packages('MTS')
> install.packages('rmgarch')
> simulated <- simulateBEKK(2, 1000, c(1, 1))

##prepare the matrix:
> simulated <- do.call(cbind, simulated$eps)

##Estimate with default arguments:
> estimated <- BEKK(simulated)
> diagnoseBEKK(estimated)

Body:
Since your question (is it a question?) doesn't really make clear what you are trying to achieve (and mixes up packages / commands) I will answer to what I think you want to know.

First of all, the commands you describe come from the package mgarchBEKK, not MTS or rmgarch.

I will stick with your example, which has two series (not five, like implied by your title).

1. Model simulation and estimation

You run your code (example actually comes from the documentation, page 4:

install.packages('mgarchBEKK')
library('mgarchBEKK')
## Simulate series: (2 = number of series to be simulated,
##                   1000 = length of series to be simulated,
##                   c(1,1) = BEKK(p, q) order.
simulated = simulateBEKK(2, 1000, c(1,1))
## Prepare the matrix:
simulated = do.call(cbind, simulated$eps)
## Estimate with default arguments:
estimated = BEKK(simulated)

Now you have all the information stored in estimated. Assuming your input variables would be e. g. daily return series from shares or indices the last value for H would be your forecast for the conditional variance of tomorrow and the last value for cor your forecast for the conditional correlation of tomorrow. So basically a 1-day-forecast.

2. Preparing the data

You could store the conditional standarddeviation and conditional correlation in a sepearte data frame for convienience. Like:

results = data.frame('bekk.csd.variable1' = estimated$sd[[1]],
                     'bekk.csd.variable2' = estimated$sd[[2]],
                     'bekk.ccor.var1_var2' = estimated$[[1]][[2]])

3. Show the results

And then show your 1-day/period-forecast for the conditional volatility and conditional correlation:

tail(results, n = 1)


问:
.htaccess to redirect specific index file when particular url is visited
I have one website url http://t8.example.info/home.html
I want to redirect this url to http://t8.example.info/index.php?id=802 when i open it in mobile version.
I dont want to redirect when it is open in desktop version. It should be open as it is in desktop version.

need a quick help.
Thanks in advance

答:
at last i found one solution
i use below code in .htaccess file</p>

```<code>RewriteCond %{REQUEST_URI} /home.html$
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteRule ^/?(.*)$ http://t8.example.info/index.php?id=802 [L,R=302]
</code>```

Body:
at last i found one solution
i use below code in .htaccess file

RewriteCond %{REQUEST_URI} /home.html$
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteRule ^/?(.*)$ http://t8.example.info/index.php?id=802 [L,R=302]


问:
How to draw a shape of polygon dynamically on map in Angular
how to draw a shape of polygon dynamically(not predefined paths) and how to store lat long values of Polygon

I already refer AGMPolygon but it didn't solve my isuse

答:
Refer to this and try to implement using javascript.
The Code will be much simpler (i personally prefer this)
https://developers.google.com/maps/documentation/javascript/examples/drawing-tools</p>


问:
No property type found
I was working on a project but I got this no property type found error.
Please check my code and try to understand what the problem is.

```<code>package com.bisoft.staj.poi;

import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class PoiApplication implements CommandLineRunner {

    @Autowired
    MesafeRepository mesafeRepository;

    public static void main(String[] args) {
        SpringApplication.run(PoiApplication.class, args);
    }

    @Override
    public void run(String... strings) throws Exception {
        System.out.println("Debug");

        FileInputStream file = new FileInputStream(new File("C:/Users/MONSTER/Desktop/Hello.xlsx"));
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        XSSFSheet sheet = workbook.getSheetAt(0);
        Row row;
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            row = (Row) sheet.getRow(i);  //sheet number

            String kayitNo;
            if (row.getCell(0) == null) {
                kayitNo = "0";
            } else {
                kayitNo = row.getCell(0).toString();
            }

            int cihazNo = 0;
            if (row.getCell(1) != null) {
                cihazNo = (int) row.getCell(1).getNumericCellValue();
            }
            String plaka;
            if (row.getCell(2) == null) {
                plaka = "null";
            } else {
                plaka = row.getCell(2).toString();                           //exceldeki isimleri
            }
            String surucu;
            if (row.getCell(3) == null) {
                surucu = "null";
            } else {
                surucu = row.getCell(3).toString();
            }
            float ilkMesafeSayaci = 0;
            if (row.getCell(4) != null) {
                ilkMesafeSayaci = (float)row.getCell(4).getNumericCellValue();
            }
            String ilkMesafeTarih;
            if (row.getCell(5) == null) {
                ilkMesafeTarih = "null";
            } else {
                ilkMesafeTarih = row.getCell(5).toString();
            }
            float sonMesafeSayaci = 0;
            if (row.getCell(6) != null) {
                sonMesafeSayaci = (float)row.getCell(6).getNumericCellValue();
            }
            String sonMesafeTarih;
            if (row.getCell(7) == null) {
                sonMesafeTarih = "null";
            } else {
                sonMesafeTarih = row.getCell(7).toString();
            }
            float toplamMesafe = 0;
            if (row.getCell(8) != null) {
                toplamMesafe = (float)row.getCell(8).getNumericCellValue();
            }

            Mesafe c = new Mesafe();
            c.setCihazNo(cihazNo);
            c.setPlaka(plaka);
            c.setSurucu(surucu);
            c.setIlkMesafeSayaci(ilkMesafeSayaci);
            c.setIlkMesafeTarih(ilkMesafeTarih);
            c.setSonMesafeSayaci(sonMesafeSayaci);
            c.setSonMesafeTarih(sonMesafeTarih);
            c.setToplamMesafe(toplamMesafe);
            mesafeRepository.save(c);

            System.out.println(cihazNo + " " + plaka + " " + surucu);

        }

        mesafeRepository.findByName("Berkin").forEach(System.out::println);

        file.close();
        System.out.println("Completed!");
    }
}
</code>```

Repository

```<code>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bisoft.staj.poi;

import java.io.Serializable;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;

/**
 *
 * @author MONSTER
 */
public interface MesafeRepository extends JpaRepository<Mesafe, Long>{

    public List<Mesafe> findByName(String name);
}
</code>```

Class

```<code>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bisoft.staj.poi;

import javax.annotation.Generated;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;

/**
 *
 * @author MONSTER
 */
@Entity
public class Mesafe {

    @Id
    @SequenceGenerator(name = "customersequence", sequenceName = "customersequence", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "customersequence")
    private Long kayitNo;
    private int cihazNo;
    private String plaka;
    private String surucu;
    private float ilkMesafeSayaci;
    private String ilkMesafeTarih;
    private float sonMesafeSayaci;
    private String SonMesafeTarih;
    private float toplamMesafe;

    public Long getKayitNo() {
        return kayitNo;
    }

    public void setKayitNo(Long kayitNo) {
        this.kayitNo = kayitNo;
    }

    public int getCihazNo() {
        return cihazNo;
    }

    public void setCihazNo(int cihazNo) {
        this.cihazNo = cihazNo;
    }

    public String getPlaka() {
        return plaka;
    }

    public void setPlaka(String plaka) {
        this.plaka = plaka;
    }

    public String getSurucu() {
        return surucu;
    }

    public void setSurucu(String surucu) {
        this.surucu = surucu;
    }

    public float getIlkMesafeSayaci() {
        return ilkMesafeSayaci;
    }

    public void setIlkMesafeSayaci(float ilkMesafeSayaci) {
        this.ilkMesafeSayaci = ilkMesafeSayaci;
    }

    public String getIlkMesafeTarih() {
        return ilkMesafeTarih;
    }

    public void setIlkMesafeTarih(String ilkMesafeTarih) {
        this.ilkMesafeTarih = ilkMesafeTarih;
    }

    public float getSonMesafeSayaci() {
        return sonMesafeSayaci;
    }

    public void setSonMesafeSayaci(float sonMesafeSayaci) {
        this.sonMesafeSayaci = sonMesafeSayaci;
    }

    public String getSonMesafeTarih() {
        return SonMesafeTarih;
    }

    public void setSonMesafeTarih(String SonMesafeTarih) {
        this.SonMesafeTarih = SonMesafeTarih;
    }

    public float getToplamMesafe() {
        return toplamMesafe;
    }

    public void setToplamMesafe(float toplamMesafe) {
        this.toplamMesafe = toplamMesafe;
    }

    @Override
    public String toString() {
        return "Mesafe{" + "kayitNo=" + kayitNo + ", cihazNo=" + cihazNo + ", plaka=" + plaka + ", surucu=" + surucu + ", ilkMesafeSayaci=" + ilkMesafeSayaci + ", ilkMesafeTarih=" + ilkMesafeTarih + ", sonMesafeSayaci=" + sonMesafeSayaci + ", SonMesafeTarih=" + SonMesafeTarih + ", toplamMesafe=" + toplamMesafe + '}';
    }
}
</code>```

Error

```<code>by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mesafeRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property name found for type Mesafe!
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    ... 18 common frames omitted
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property name found for type Mesafe!
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:329) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:309) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:272) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:243) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:247) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:398) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:378) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:89) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:64) ~[spring-data-jpa-1.11.4.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:103) ~[spring-data-jpa-1.11.4.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:214) ~[spring-data-jpa-1.11.4.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:77) ~[spring-data-jpa-1.11.4.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:436) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:221) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:101) ~[spring-data-jpa-1.11.4.RELEASE.jar:na]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    ... 28 common frames omitted
</code>```

my pom.xml and application.properties files are working OK so where can the problem be? Thanks...

答:
I think the problem is in your repo:

```<code>public interface MesafeRepository extends JpaRepository<Mesafe, Long>{

    public List<Mesafe> findByName(String name);
}
</code>```

According to method findByName, your entity should have a property name, but there is no such property in Mesafe entity

You can just remove this method from repo, or add corresponding property to the entity

Title: No property type found

Body:
I was working on a project but I got this no property type found error.
Please check my code and try to understand what the problem is.

package com.bisoft.staj.poi;

import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class PoiApplication implements CommandLineRunner {

    @Autowired
    MesafeRepository mesafeRepository;

    public static void main(String[] args) {
        SpringApplication.run(PoiApplication.class, args);
    }

    @Override
    public void run(String... strings) throws Exception {
        System.out.println("Debug");

        FileInputStream file = new FileInputStream(new File("C:/Users/MONSTER/Desktop/Hello.xlsx"));
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        XSSFSheet sheet = workbook.getSheetAt(0);
        Row row;
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            row = (Row) sheet.getRow(i);  //sheet number

            String kayitNo;
            if (row.getCell(0) == null) {
                kayitNo = "0";
            } else {
                kayitNo = row.getCell(0).toString();
            }

            int cihazNo = 0;
            if (row.getCell(1) != null) {
                cihazNo = (int) row.getCell(1).getNumericCellValue();
            }
            String plaka;
            if (row.getCell(2) == null) {
                plaka = "null";
            } else {
                plaka = row.getCell(2).toString();                           //exceldeki isimleri
            }
            String surucu;
            if (row.getCell(3) == null) {
                surucu = "null";
            } else {
                surucu = row.getCell(3).toString();
            }
            float ilkMesafeSayaci = 0;
            if (row.getCell(4) != null) {
                ilkMesafeSayaci = (float)row.getCell(4).getNumericCellValue();
            }
            String ilkMesafeTarih;
            if (row.getCell(5) == null) {
                ilkMesafeTarih = "null";
            } else {
                ilkMesafeTarih = row.getCell(5).toString();
            }
            float sonMesafeSayaci = 0;
            if (row.getCell(6) != null) {
                sonMesafeSayaci = (float)row.getCell(6).getNumericCellValue();
            }
            String sonMesafeTarih;
            if (row.getCell(7) == null) {
                sonMesafeTarih = "null";
            } else {
                sonMesafeTarih = row.getCell(7).toString();
            }
            float toplamMesafe = 0;
            if (row.getCell(8) != null) {
                toplamMesafe = (float)row.getCell(8).getNumericCellValue();
            }

            Mesafe c = new Mesafe();
            c.setCihazNo(cihazNo);
            c.setPlaka(plaka);
            c.setSurucu(surucu);
            c.setIlkMesafeSayaci(ilkMesafeSayaci);
            c.setIlkMesafeTarih(ilkMesafeTarih);
            c.setSonMesafeSayaci(sonMesafeSayaci);
            c.setSonMesafeTarih(sonMesafeTarih);
            c.setToplamMesafe(toplamMesafe);
            mesafeRepository.save(c);

            System.out.println(cihazNo + " " + plaka + " " + surucu);

        }

        mesafeRepository.findByName("Berkin").forEach(System.out::println);

        file.close();
        System.out.println("Completed!");
    }
}

Repository

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bisoft.staj.poi;

import java.io.Serializable;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;

/**
 *
 * @author MONSTER
 */
public interface MesafeRepository extends JpaRepository<Mesafe, Long>{

    public List<Mesafe> findByName(String name);
}

Class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bisoft.staj.poi;

import javax.annotation.Generated;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;

/**
 *
 * @author MONSTER
 */
@Entity
public class Mesafe {

    @Id
    @SequenceGenerator(name = "customersequence", sequenceName = "customersequence", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "customersequence")
    private Long kayitNo;
    private int cihazNo;
    private String plaka;
    private String surucu;
    private float ilkMesafeSayaci;
    private String ilkMesafeTarih;
    private float sonMesafeSayaci;
    private String SonMesafeTarih;
    private float toplamMesafe;

    public Long getKayitNo() {
        return kayitNo;
    }

    public void setKayitNo(Long kayitNo) {
        this.kayitNo = kayitNo;
    }

    public int getCihazNo() {
        return cihazNo;
    }

    public void setCihazNo(int cihazNo) {
        this.cihazNo = cihazNo;
    }

    public String getPlaka() {
        return plaka;
    }

    public void setPlaka(String plaka) {
        this.plaka = plaka;
    }

    public String getSurucu() {
        return surucu;
    }

    public void setSurucu(String surucu) {
        this.surucu = surucu;
    }

    public float getIlkMesafeSayaci() {
        return ilkMesafeSayaci;
    }

    public void setIlkMesafeSayaci(float ilkMesafeSayaci) {
        this.ilkMesafeSayaci = ilkMesafeSayaci;
    }

    public String getIlkMesafeTarih() {
        return ilkMesafeTarih;
    }

    public void setIlkMesafeTarih(String ilkMesafeTarih) {
        this.ilkMesafeTarih = ilkMesafeTarih;
    }

    public float getSonMesafeSayaci() {
        return sonMesafeSayaci;
    }

    public void setSonMesafeSayaci(float sonMesafeSayaci) {
        this.sonMesafeSayaci = sonMesafeSayaci;
    }

    public String getSonMesafeTarih() {
        return SonMesafeTarih;
    }

    public void setSonMesafeTarih(String SonMesafeTarih) {
        this.SonMesafeTarih = SonMesafeTarih;
    }

    public float getToplamMesafe() {
        return toplamMesafe;
    }

    public void setToplamMesafe(float toplamMesafe) {
        this.toplamMesafe = toplamMesafe;
    }

    @Override
    public String toString() {
        return "Mesafe{" + "kayitNo=" + kayitNo + ", cihazNo=" + cihazNo + ", plaka=" + plaka + ", surucu=" + surucu + ", ilkMesafeSayaci=" + ilkMesafeSayaci + ", ilkMesafeTarih=" + ilkMesafeTarih + ", sonMesafeSayaci=" + sonMesafeSayaci + ", SonMesafeTarih=" + SonMesafeTarih + ", toplamMesafe=" + toplamMesafe + '}';
    }
}

Error

by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mesafeRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property name found for type Mesafe!
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    ... 18 common frames omitted
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property name found for type Mesafe!
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:329) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:309) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:272) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:243) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:247) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:398) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:378) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:89) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:64) ~[spring-data-jpa-1.11.4.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:103) ~[spring-data-jpa-1.11.4.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:214) ~[spring-data-jpa-1.11.4.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:77) ~[spring-data-jpa-1.11.4.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:436) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:221) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:101) ~[spring-data-jpa-1.11.4.RELEASE.jar:na]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    ... 28 common frames omitted

my pom.xml and application.properties files are working OK so where can the problem be? Thanks...

Body:
I think the problem is in your repo:

public interface MesafeRepository extends JpaRepository<Mesafe, Long>{

    public List<Mesafe> findByName(String name);
}

According to method findByName, your entity should have a property name, but there is no such property in Mesafe entity

You can just remove this method from repo, or add corresponding property to the entity


问:
Paypal : Angular Js paypal button is not redirecting to the payment page
I am trying to test my paypal integration with using sandbox account credentials

this is my button code

```<code>    <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="3M2C8VGPZSHSW">
<input type="image" src="https://www.sandbox.paypal.com/en_GB/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.sandbox.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</code>```

the button is not redirecting anywhere?

答:
I got my answer from this , it contains many example and helpful code
https://developer.paypal.com/demo/checkout/#/pattern/validation</p>

Body:
I am trying to test my paypal integration with using sandbox account credentials

this is my button code

    <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="3M2C8VGPZSHSW">
<input type="image" src="https://www.sandbox.paypal.com/en_GB/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online!">

</form>

the button is not redirecting anywhere?


问:
Convert UTC time to system time getting null
```<code> NSString *strUTCTime=@"2017-07-06T10:00:00";

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 dateFormatter.dateFormat = @"yyyy-MM-ddTHH:mm:ss";

 NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
 [dateFormatter setTimeZone:destinationTimeZone];

 NSDate *oldTime = [dateFormatter dateFromString:strUTCTime];

 NSString *estDateString = [dateFormatter stringFromDate:oldTime];
 NSLog(@"Local time is ===> %@",estDateString);
</code>```

答:
Here are the following working and tested code.

```<code>NSString *strUTCTime=@"2017-07-06T10:00:00";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss";
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en-US"]];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

NSDate *oldTime = [dateFormatter dateFromString:strUTCTime];

NSLog(@"UTC time is ===> %@",oldTime);

NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
[dateFormatter setTimeZone:destinationTimeZone];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";

NSString *estDateString = [dateFormatter stringFromDate:oldTime];
NSLog(@"Local time is ===> %@",estDateString);
</code>```

Please let me know if it works.

Body:
Here are the following working and tested code.

NSString *strUTCTime=@"2017-07-06T10:00:00";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss";
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en-US"]];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

NSDate *oldTime = [dateFormatter dateFromString:strUTCTime];

NSLog(@"UTC time is ===> %@",oldTime);

NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
[dateFormatter setTimeZone:destinationTimeZone];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";

NSString *estDateString = [dateFormatter stringFromDate:oldTime];
NSLog(@"Local time is ===> %@",estDateString);

Please let me know if it works.


问:
Class instances differ, which one to use?
I'm stuck with the following. In a program, I'm trying to communicate between different classes (View Controllers with NIB files attached in a TabBar application etc). I want to call a method 'OMFG' in a class called 'ProductViewDetailController'. This class is a UIViewController (SplitViewDelegate). It's loaded programmatically.

Anyways, I've been trying to get the right call to this controller, and I came up with 2 solutions. One is declaring the productviewdetailcontroller in the caller's .h file and .m file, making an IBOutlet, linking it in the Interface builder and calling it directly by the line

```<code>[productDetailController OMFG];
</code>```

When I call this method, it calls the right method in the ProductViewDetailController, but the instance of this viewcontroller differs from the one I programmatically can reach with this code:

```<code>for (UIViewController *controller in self.tabBarController.viewControllers) {
      NSLog(@"%@", [controller class]);
      if ([controller isKindOfClass:[UISplitViewController class]]) {
       UISplitViewController *cell = (UISplitViewController *)controller;
       for (UIViewController *controller2 in cell.viewControllers) {
        NSLog(@"%@", [controller2 class]);
        if ([controller2 isKindOfClass:[ProductViewDetailController class]]) {
         [controller2 OMFG];

        }
       }
      }
</code>```

Which one should I use, and why?

edit: When I try to add a SubView to both viewcontrollers, the one where the call is [controller2 OMFG]; actually shows the newly added view, where the [productDetailController OMFG]; doesn't show the newly added view... Why is that? Is there a shorter (and more chique) way to get access to the right ViewController?

答:
You should use a IBOutlet. This makes sure your app can still call the correct target if you later decide to change the hierarchy of view controllers, for example if creating an iPhone compatible setup without a UISplitViewController.

Calling isKindOfClass: in Objective-C is a sure sign that what you are doing is probably wrong. Firstly in Cocoa Touch what you do is always more important than who you are. Secondly what you try to do is probably peeking inside something that should be left private.

Body:
I'm stuck with the following. In a program, I'm trying to communicate between different classes (View Controllers with NIB files attached in a TabBar application etc). I want to call a method 'OMFG' in a class called 'ProductViewDetailController'. This class is a UIViewController (SplitViewDelegate). It's loaded programmatically.

Anyways, I've been trying to get the right call to this controller, and I came up with 2 solutions. One is declaring the productviewdetailcontroller in the caller's .h file and .m file, making an IBOutlet, linking it in the Interface builder and calling it directly by the line

[productDetailController OMFG];

When I call this method, it calls the right method in the ProductViewDetailController, but the instance of this viewcontroller differs from the one I programmatically can reach with this code:

for (UIViewController *controller in self.tabBarController.viewControllers) {
      NSLog(@"%@", [controller class]);
      if ([controller isKindOfClass:[UISplitViewController class]]) {
       UISplitViewController *cell = (UISplitViewController *)controller;
       for (UIViewController *controller2 in cell.viewControllers) {
        NSLog(@"%@", [controller2 class]);
        if ([controller2 isKindOfClass:[ProductViewDetailController class]]) {
         [controller2 OMFG];

        }
       }
      }

Which one should I use, and why?

edit: When I try to add a SubView to both viewcontrollers, the one where the call is [controller2 OMFG]; actually shows the newly added view, where the [productDetailController OMFG]; doesn't show the newly added view... Why is that? Is there a shorter (and more chique) way to get access to the right ViewController?


问:
Angular - Custom Input: reset touched state via form.reset() not working
i've got a question regarding resetting a Form with a Custom Input on it.

I bound my validation messages to the touched property of my inputs.
While on default Inputs the form.reset() also resets the touched state back to false, on custom inputs, its not forwarded.

I've added a plunkr https://plnkr.co/edit/ZyELDDFf3rxQRipHlWnb?p=preview to illustrate the problem: touch and leave both controls, both are touched: true, afterwards reset.
How can i forward this clearing reset event, which reverts the touched state back to false, to my Custom Input?

```<code>@Component({
selector: 'my-app',
template: `
    <p><span class="boldspan">Form data:</span>{{demoForm.value | json}}</p>
    <p><span class="boldspan">Model data:</span> {{dataModel}}</p>
    <form #demoForm="ngForm">
      <custom-input name="someValue" [(ngModel)]="dataModel">
        custom input
      </custom-input>
      <label>native input<br>
      <input type="text" [(ngModel)]="someOtherValue" name="someOtherValue"
      #sOV="ngModel"></label>
      <div>touched: {{sOV.touched}}</div>
    </form>
    <br>
    <button (click)="demoForm.reset()">Reset Form</button>`
})
export class App {
    dataModel: string = '';
}
</code>```

Thanks and best regards

答:
Use

```<code>demoForm.resetForm()
</code>```

rather than

```<code>demoForm.reset()
</code>```

Body:
i've got a question regarding resetting a Form with a Custom Input on it.

I bound my validation messages to the touched property of my inputs.
While on default Inputs the form.reset() also resets the touched state back to false, on custom inputs, its not forwarded.

I've added a plunkr https://plnkr.co/edit/ZyELDDFf3rxQRipHlWnb?p=preview to illustrate the problem: touch and leave both controls, both are touched: true, afterwards reset.
How can i forward this clearing reset event, which reverts the touched state back to false, to my Custom Input?

@Component({
selector: 'my-app',
template: `

Form data:{{demoForm.value | json}}

Model data: {{dataModel}}

    <form #demoForm="ngForm">
      <custom-input name="someValue" [(ngModel)]="dataModel">
        custom input
      </custom-input>
      native input

      <input type="text" [(ngModel)]="someOtherValue" name="someOtherValue"
      #sOV="ngModel">

touched: {{sOV.touched}}

    </form>

    <button (click)="demoForm.reset()">Reset Form</button>`
})
export class App {
    dataModel: string = '';
}

Thanks and best regards

Body:
Use

demoForm.resetForm()

rather than

demoForm.reset()


问:
How to do Angular 2 project with DevExtreme using Visual Studio 2017/2015
Can any one explain me how to do Angular 2 project with DevExtreme control using Visual Studio 2017/2015. I want to use the control shown here-https://js.devexpress.com/Demos/WidgetsGallery/Demo/Scheduler/Timelines/Angular/Light/..
Please help me out

答:
You should create a Visual studio solution, for example by following the tutorial here: http://blog.stevensanderson.com/2016/10/04/angular2-template-for-visual-studio/ .
use npm to install devextreme and you're ready to create the devextreme controls.</p>


问:
Service Fabric, which certificate do I use where?
I'm settings up a Service Fabric cluster in Azure and want to run a web API (using .NET Core) over https. I want to use my CA-signed wildcard (*.mydomain.com) certificate to access this API. But I'm a bit confused as to where I use it when I create the cluster, is it the cluster or client certificate? I'm thinking the client certificate, but the documentation states that this is for admin tools (i.e. the Explorer), so I'm unsure on how to proceed.

And yes I've read a ton of posts and resources, but I still find this confusing.

答:
The way we are using it is to have Application gateway configured in front of service fabric cluster, and web certificate is uploaded to Application Gateway (and dns is pointing to application gateway) In that scenario SSL is terminated at application gateway.

Another possibility is to terminate SSL at each node in service fabric cluster, in this scenario you would need to ensure that certificate gets deployed to each of the nodes.

As for cluster vs client certificate dilemma, I am also confused, but I think the answer is neither. Client certificate is not for sure since this certificate is used to identify you as admin when running service fabric admin ps scripts.

I do not think it is cluster certificate either, here is what MS docs say what it is used for:

Cluster and server certificate is required to secure a cluster and prevent unauthorized access to it. It provides cluster security in two ways:
Cluster authentication: Authenticates node-to-node communication for cluster federation. Only nodes that can prove their identity with this certificate can join the cluster.
Server authentication: Authenticates the cluster management endpoints to a management client, so that the management client knows it is talking to the real cluster. This certificate also provides an SSL for the HTTPS management API and for Service Fabric Explorer over HTTPS.

as far as I am reading into it, this certificate is used for internal cluster authentication, and it is also used so your management tools can be asured that they are working with right cluster.