问:
Using both respondWith and waitUntil in a fetch event
Is it ever necessary to use a waitUntil inside a respondWith (itself within a fetch event)?  Doesn't respondWith already waitUntil it receives a resolved promise?

Some discussion of this is here, in which the following simple example is given in which both are used:

```<code>addEventListener('fetch', event => {
  event.respondWith(
    fetch(whatever).then(response => {
      event.waitUntil(addThisToTheCache(response));
      return response;
    })
  );
});
</code>```

But couldn't this be written without a waitUntil?  As follows:

```<code>addEventListener('fetch', event => {
  event.respondWith(
    fetch(whatever).then(response => {
      return addThisToTheCache(response).then(() => {
        return response;
      });
    })
  );
});
</code>```

答:
This will delay the browser processing & displaying the response by two seconds:

```<code>addEventListener('fetch', event => {
  event.respondWith(async function() {
    const response = await fetch(event.request);
    await processResponseForTwoSeconds(response);
    return response;
  }());
});
</code>```

This won't:

```<code>addEventListener('fetch', event => {
  event.respondWith(async function () {
    const response = await fetch(event.request);
    event.waitUntil(processResponseForTwoSeconds(response));
    return response;
  }());
});
</code>```

waitUntil tells the service worker to stay alive for ongoing tasks, but does not delay the response.

Body:
Is it ever necessary to use a waitUntil inside a respondWith (itself within a fetch event)?  Doesn't respondWith already waitUntil it receives a resolved promise?

Some discussion of this is here, in which the following simple example is given in which both are used:

addEventListener('fetch', event => {
  event.respondWith(
    fetch(whatever).then(response => {
      event.waitUntil(addThisToTheCache(response));
      return response;
    })
  );
});

But couldn't this be written without a waitUntil?  As follows:

addEventListener('fetch', event => {
  event.respondWith(
    fetch(whatever).then(response => {
      return addThisToTheCache(response).then(() => {
        return response;
      });
    })
  );
});

Body:
This will delay the browser processing & displaying the response by two seconds:

addEventListener('fetch', event => {
  event.respondWith(async function() {
    const response = await fetch(event.request);
    await processResponseForTwoSeconds(response);
    return response;
  }());
});

This won't:

addEventListener('fetch', event => {
  event.respondWith(async function () {
    const response = await fetch(event.request);
    event.waitUntil(processResponseForTwoSeconds(response));
    return response;
  }());
});

waitUntil tells the service worker to stay alive for ongoing tasks, but does not delay the response.


来源: stackexchange

问:
MySQL select AND statement
I have a MySQL database like that:

```
Id | Name
1  | term1
1  | term2
1  | term3
2  | term4
2  | term5
2  | term6
```

I want to select ID that contains term1 AND term3.

Or, for example, term4 AND term5 AND term6.

How can I do that?
Any help would be greatly appreciated, thanks.

答:
To get Ids which must have the names provided as parameters you can use below query which meets the criteria using some aggregation

For term1 & term3

```<code>select Id
from demo
where Name in ('term1', 'term3')
group by Id
having count(*) = sum(Name in ('term1', 'term3'));
</code>```

For term4 & term5 & term6

```<code>select Id
from demo
where Name in ('term4', 'term5','term6')
group by Id
having count(*) = sum(Name in ('term4', 'term5','term6'));
</code>```

Demo

ContentLicense: CC BY-SA 3.0

Title: MySQL select AND statement

Body:
I have a MySQL database like that:

Id | Name
1  | term1
1  | term2
1  | term3
2  | term4
2  | term5
2  | term6

I want to select ID that contains term1 AND term3.

Or, for example, term4 AND term5 AND term6.

How can I do that?
Any help would be greatly appreciated, thanks.

Body:
To get Ids which must have the names provided as parameters you can use below query which meets the criteria using some aggregation

For term1 & term3

select Id
from demo
where Name in ('term1', 'term3')
group by Id
having count(*) = sum(Name in ('term1', 'term3'));

For term4 & term5 & term6

select Id
from demo
where Name in ('term4', 'term5','term6')
group by Id
having count(*) = sum(Name in ('term4', 'term5','term6'));

Demo


问:
how to modify json Object in javascript
I am trying to load sample csv files into project read the content and display according to the filed. I done uploading and file writing but could not optimize the json structure properly for future use case

Here is my sample code :

```<code>let csvToJson = require('convert-csv-to-json');
let json = csvToJson.getJsonFromCsv(filepath);
var lines = [];
for(let i=0; i<json.length;i++){
console.log(json[i]);
lines.push(json[i])
}
console.log(lines);
var result3=JSON.stringify(lines);
result3 = result3.replace(/\r?\n|\r/g, " ");
console.log(result3);
</code>```

My output:

console.log(json[i]) =

```<code>Object {name,age,address: "asd,20,"12/76, 11th cross"
"}
browser.js:5358 Object {name,age,address: "dff,30,"33, 11th cross"
"}
browser.js:5358 Object {name,age,address: "f,22,"7g/22, 12th cross"
"}
browser.js:5358 Object {name,age,address: "ghth,55,"4h, 13th cross"
"}
</code>```

console.log(lines) = [Object, Object, Object, Object, Object]

console.log(result3)

```<code>[{"name,age,address":"asd,20,\"12/76, 11th cross\"\r"},
{"name,age,address":"dff,30,\"33, 11th cross\"\r"},
{"name,age,address":"f,22,\"7g/22, 12th cross\"\r"},
{"name,age,address":"ghth,55,\"4h, 13th cross\"\r"},
{"name,age,address":"fhg,44,\"6t, 10th cross\"\r"}]
</code>```

My expected output:

```<code>{name:[],age:[],address:[]}
</code>```

i.e I want all "name" values should store in the  name key similar to "age" and "address". Can anybody help me how to do this?

答:
DEMO

var jsonObj = [{"name,age,address":"asd,20,\"12/76, 11th cross\"\r"},
{"name,age,address":"dff,30,\"33, 11th cross\"\r"},
{"name,age,address":"f,22,\"7g/22, 12th cross\"\r"},
{"name,age,address":"ghth,55,\"4h, 13th cross\"\r"},
{"name,age,address":"fhg,44,\"6t, 10th cross\"\r"}];

var newArray = {
            name:[],
            age:[],
            address:[]
          };

for (var i in jsonObj) {
  let [name, age, ...address] = jsonObj[i]["name,age,address"].split(',');
  newArray.name.push(name);
  newArray.age.push(age);
  newArray.address.push(address.join(''));
};

console.log(newArray);```

Title: how to modify json Object in javascript

Body:
I am trying to load sample csv files into project read the content and display according to the filed. I done uploading and file writing but could not optimize the json structure properly for future use case

Here is my sample code :

let csvToJson = require('convert-csv-to-json');
let json = csvToJson.getJsonFromCsv(filepath);
var lines = [];
for(let i=0; i<json.length;i++){
console.log(json[i]);
lines.push(json[i])
}
console.log(lines);
var result3=JSON.stringify(lines);
result3 = result3.replace(/\r?\n|\r/g, " ");
console.log(result3);

My output:

console.log(json[i]) =

Object {name,age,address: "asd,20,"12/76, 11th cross"
"}
browser.js:5358 Object {name,age,address: "dff,30,"33, 11th cross"
"}
browser.js:5358 Object {name,age,address: "f,22,"7g/22, 12th cross"
"}
browser.js:5358 Object {name,age,address: "ghth,55,"4h, 13th cross"
"}

console.log(lines) = [Object, Object, Object, Object, Object]

console.log(result3)

[{"name,age,address":"asd,20,\"12/76, 11th cross\"\r"},
{"name,age,address":"dff,30,\"33, 11th cross\"\r"},
{"name,age,address":"f,22,\"7g/22, 12th cross\"\r"},
{"name,age,address":"ghth,55,\"4h, 13th cross\"\r"},
{"name,age,address":"fhg,44,\"6t, 10th cross\"\r"}]

My expected output:

{name:[],age:[],address:[]}

i.e I want all "name" values should store in the  name key similar to "age" and "address". Can anybody help me how to do this?


问:
PHP undefined index database issues
I am having issues with displaying the database table. My database table (activities) have the following value, ID (Primary Key), type, title, description and picture. I am trying to retrieve and display title,description and picture in a table format but is facing an  error

"Notice: Undefined index: title, Notice: Undefined index: description
  and Notice: Undefined index: picture"

which I am unable to solve it.
Below are my php code:

```<code>      <div class="col-md-4 col-md-offset-1">
           <div id="content">
               <table><?php
                $servername = "localhost";
                $username = "root";
                $password = "";
                $dbname = "sentosa_resort";

                $conn = new mysqli($servername, $username, $password,
               $dbname);
               // Check connection
               if ($conn->connect_error) {
                   die("Connection failed: " . $conn->connect_error);
               }

                $query = "SELECT title,description,picture FROM activites";
                $result = $conn->query($sql);;

                 // start a table tag in the HTML

                while($row=mysqli_fetch_array($result)){
                    $title = $row['title'];
                    $description = $row['description'];
                   $picture = $row['picture'];
                    echo "<tr>";
                    echo "<td>" . $title . "</td>";
                    echo "<td>" . $description . "</td>";
                     echo "<td>" . $picture . "</td>";
                    echo "</tr>";
                }
                ?></table>
                </div>
          </div>
</code>```

答:
I have changed your code please check it</p>

```<code><div class="col-md-4 col-md-offset-1">
           <div id="content">
               <table><?php
                $servername = "localhost";
                $username = "root";
                $password = "";
                $dbname = "sentosa_resort";

                $conn = mysqli_connect($servername, $username, $password,
               $dbname);

                $query = "SELECT title,description,picture FROM activites";
                $result = mysqli_query($conn,$query);

                while($row=mysqli_fetch_assoc($result)){
                    $title = $row['title'];
                    $description = $row['description'];
                   $picture = $row['picture'];
                    echo "<tr>";
                    echo "<td>" . $title . "</td>";
                    echo "<td>" . $description . "</td>";
                     echo "<td>" . $picture . "</td>";
                    echo "</tr>";
                }
                ?></table>
                </div>
          </div>
</code>```

Title: PHP undefined index database issues

Body:
I am having issues with displaying the database table. My database table (activities) have the following value, ID (Primary Key), type, title, description and picture. I am trying to retrieve and display title,description and picture in a table format but is facing an  error

"Notice: Undefined index: title, Notice: Undefined index: description
  and Notice: Undefined index: picture"

which I am unable to solve it.
Below are my php code:

<?php
                $servername = "localhost";
                $username = "root";
                $password = "";
                $dbname = "sentosa_resort";

                $conn = new mysqli($servername, $username, $password,
               $dbname);
               // Check connection
               if ($conn->connect_error) {
                   die("Connection failed: " . $conn->connect_error);
               }

                $query = "SELECT title,description,picture FROM activites";
                $result = $conn->query($sql);;

                 // start a table tag in the HTML

                while($row=mysqli_fetch_array($result)){
                    $title = $row['title'];
                    $description = $row['description'];
                   $picture = $row['picture'];
                    echo "
";
                    echo "" . $title . "	";
                    echo "" . $description . "	";
                     echo "" . $picture . "	";
                    echo "
";
                }
                ?>

Body:
I have changed your code please check it

<div class="col-md-4 col-md-offset-1">
           <div id="content">
               <table><?php
                $servername = "localhost";
                $username = "root";
                $password = "";
                $dbname = "sentosa_resort";

                $conn = mysqli_connect($servername, $username, $password,
               $dbname);

                $query = "SELECT title,description,picture FROM activites";
                $result = mysqli_query($conn,$query);

                while($row=mysqli_fetch_assoc($result)){
                    $title = $row['title'];
                    $description = $row['description'];
                   $picture = $row['picture'];
                    echo "<tr>";
                    echo "<td>" . $title . "</td>";
                    echo "<td>" . $description . "</td>";
                     echo "<td>" . $picture . "</td>";
                    echo "</tr>";
                }
                ?></table>
                </div>
          </div>


问:
Synopsys VCS message severity change from warning to error
I want to change the severity of a VCS message from warning to error.

E.g.:

```<code>Warning-[TMR] Text macro redefined
</code>```

I want to change TMR to Error severity instead of warning.

Please suggest me a way of doing this. Where am I supposed to do this setting?

答:
You should add the next flag to your VCS command:
 -error="TMR"</p>

Body:
I want to change the severity of a VCS message from warning to error.

E.g.:

Warning-[TMR] Text macro redefined

I want to change TMR to Error severity instead of warning.

Please suggest me a way of doing this. Where am I supposed to do this setting?


问:
DataLabels formatter not working in Highcharts Sankey Diagram
Expected Behaviour:
Ability to format the dataLabel in the sankey diagram

Actual Behaviour:
dataLabel is not getting formatted.

```<code>dataLabels: {
    enabled: true,
    formatter: function(){
        return "Abc";
    }
  }
</code>```

Live demo with steps to reproduce the issue:

http://jsfiddle.net/jy0761aw/2/

Affected browser(s):
All browsers

答:
I was having the same issues. Sankey is really hard to implement I guess. Use nodeFormatter instead, formatter is just not working. Example below.</p>

```<code>nodeFormatter: function (arg) {
    if (!this.point.sum) {
        return null;
    } else {
        return this.key;
    }
}
</code>```

Body:
Expected Behaviour:
Ability to format the dataLabel in the sankey diagram

Actual Behaviour:
dataLabel is not getting formatted.

dataLabels: {
    enabled: true,
    formatter: function(){
        return "Abc";
    }
  }

Live demo with steps to reproduce the issue:

http://jsfiddle.net/jy0761aw/2/

Affected browser(s):
All browsers

Body:
I was having the same issues. Sankey is really hard to implement I guess. Use nodeFormatter instead, formatter is just not working. Example below.

nodeFormatter: function (arg) {
    if (!this.point.sum) {
        return null;
    } else {
        return this.key;
    }
}


问:
Failed to create JVM: error code -6, JVM Path: C:\<jre path>
If you alreadt have a 32-bit JDK installed, define a JAVA_HOME variable in

```<code>Computer>System Properties>System Setting>Enviorment VAriables.
</code>```

I have allready set the JAVA_HOME path in Enviorment setting.

Whenever, I want to open android studio, this problem will be occure.

I am using 32 bit windows 7 machine and 32 bit 1.8 java version in his machine.

答:
I compared studio.exe.vmoptions file with my previous version Android Studio installation. (C:\Users\xxxx\.AndroidStudio3.0\studio.exe.vmoptions)

I changed -Xmx4096m to -Xmx750m as was in previous version and this "error code -6" problem disappeared.

Body:
If you alreadt have a 32-bit JDK installed, define a JAVA_HOME variable in

Computer>System Properties>System Setting>Enviorment VAriables.

I have allready set the JAVA_HOME path in Enviorment setting.

Whenever, I want to open android studio, this problem will be occure.

I am using 32 bit windows 7 machine and 32 bit 1.8 java version in his machine.


问:
Remove a verb as a stopword
There are some words which are used sometimes as a verb and sometimes as other part of speech.

Example

A sentence with the meaning of the word as verb:

```<code>I blame myself for what happened
</code>```

And a sentence with the meaning of word as noun:

```<code>For what happened the blame is yours
</code>```

The word I want to detect is known to me, in the example above is "blame". I would like to detect and remove as stopwords only when it has meaning like a verb.

Is there any easy way to make it?

答:
You can install TreeTagger and then use the koRpus package in R to use TreeTagger from R. Install it in a location like e.g. C:\Treetagger.

I will first show how treetagger works so you understand what's going in the actual solution further down below in this answer:

Intro treetagger

```<code>library(koRpus)

your_sentences <- c("I blame myself for what happened",
                    "For what happened the blame is yours")

text.tagged <- treetag(file="I blame myself for what happened",
                  format="obj", treetagger="manual", lang="en",
                  TT.options = list(path="C:\\Treetagger", preset="en") )
text.tagged@TT.res[, 1:2]
#       token tag
#1         I  PP
#2     blame VVP
#3    myself  PP
#4       for  IN
#5      what  WP
#6  happened VVD
</code>```

The sentences have been analysed now and the "only thing left" is to remove those occurrences of "blame" that are a verb.

Solution

I'll do this sentence for sentence by creating a function that first tags the sentence, then checks for "bad words" like "blame" that are also a verb and finally removes them from the sentence:

```<code>remove_words <- function(sentence, badword="blame"){
  tagged.text <- treetag(file=sentence, format="obj", treetagger="manual", lang="en",
                         TT.options=list(path=":C\\Treetagger", preset="en"))
  # Check for bad words AND verb:
  cond1 <- (tagged.text@TT.res$token == badword)
  cond2 <- (substring(tagged.text@TT.res$tag, 0, 1) == "V")
  redflag <- which(cond1 & cond2)

  # If no such case, return sentence as is. If so, then remove that word:
  if(length(redflag) == 0) return(sentence)
  else{
    splitsent <- strsplit(sentence, " ")[[1]]
    splitsent <- splitsent[-redflag]
    return(paste0(splitsent, collapse=" "))
  }
}

lapply(your_sentences, remove_words)
# [[1]]
# [1] "I myself for what happened"
# [[2]]
# [1] "For what happened the blame is yours"
</code>```

Title: Remove a verb as a stopword

Body:
There are some words which are used sometimes as a verb and sometimes as other part of speech.

Example

A sentence with the meaning of the word as verb:

I blame myself for what happened

And a sentence with the meaning of word as noun:

For what happened the blame is yours

The word I want to detect is known to me, in the example above is "blame". I would like to detect and remove as stopwords only when it has meaning like a verb.

Is there any easy way to make it?

Body:
You can install TreeTagger and then use the koRpus package in R to use TreeTagger from R. Install it in a location like e.g. C:\Treetagger.

I will first show how treetagger works so you understand what's going in the actual solution further down below in this answer:

Intro treetagger

library(koRpus)

your_sentences <- c("I blame myself for what happened",
                    "For what happened the blame is yours")

text.tagged <- treetag(file="I blame myself for what happened",
                  format="obj", treetagger="manual", lang="en",
                  TT.options = list(path="C:\\Treetagger", preset="en") )
text.tagged@TT.res[, 1:2]
#       token tag
#1         I  PP
#2     blame VVP
#3    myself  PP
#4       for  IN
#5      what  WP
#6  happened VVD

The sentences have been analysed now and the "only thing left" is to remove those occurrences of "blame" that are a verb.

Solution

I'll do this sentence for sentence by creating a function that first tags the sentence, then checks for "bad words" like "blame" that are also a verb and finally removes them from the sentence:

remove_words <- function(sentence, badword="blame"){
  tagged.text <- treetag(file=sentence, format="obj", treetagger="manual", lang="en",
                         TT.options=list(path=":C\\Treetagger", preset="en"))
  # Check for bad words AND verb:
  cond1 <- (tagged.text@TT.res$token == badword)
  cond2 <- (substring(tagged.text@TT.res$tag, 0, 1) == "V")
  redflag <- which(cond1 & cond2)

  # If no such case, return sentence as is. If so, then remove that word:
  if(length(redflag) == 0) return(sentence)
  else{
    splitsent <- strsplit(sentence, " ")[[1]]
    splitsent <- splitsent[-redflag]
    return(paste0(splitsent, collapse=" "))
  }
}

lapply(your_sentences, remove_words)
# [[1]]
# [1] "I myself for what happened"
# [[2]]
# [1] "For what happened the blame is yours"


问:
Why enums require an explicit cast to int type?
There is no data loss by doing this, so what's the reason for having to explicitly cast enums to ints?

Would it not be more intuitive if it was implicit, say when you have a higher level method like:

```<code>PerformOperation ( OperationType.Silent type )
</code>```

where PerformOperation calls a wrapped C++ method that's exposed as such:

```<code>_unmanaged_perform_operation ( int operation_type )
</code>```

答:
Why do you say no data loss? Not all enums are ints, after all. They must be integer-typed, but that can mean byte, ulong, etc.

As a corner-case the literal 0 is implicit, but; what would be your use-case here?

It is pretty rare I need to do this - usually data import etc. An occasional no-op cast makes perfect sense to me, and avoids accidental mistakes.

ContentLicense: CC BY-SA 2.5

Body:
There is no data loss by doing this, so what's the reason for having to explicitly cast enums to ints?

Would it not be more intuitive if it was implicit, say when you have a higher level method like:

PerformOperation ( OperationType.Silent type )

where PerformOperation calls a wrapped C++ method that's exposed as such:

_unmanaged_perform_operation ( int operation_type )


问:
How to fill non column field of entity in room library
I have a class entity as below

```<code>@Entity
public class Task {
    private String name;
    private Integer ParentId;
    private Integer userId;
    @Ignore
    private int noOfSubTask;
}
</code>```

in DAO class there is a method getTaskList()

```<code>@Dao
public interface TaskDao extends Dao<Task> {

@Query("SELECT *,(SELECT count(*) FROM Task b  WHERE a._id = b.ParentId ) AS noOfSubTask FROM Task a ")
LiveData<List<Task>> getTaskList();
}
</code>```

I want to fill
noOfSubTask with the number given by (SELECT count(*) FROM Task b  WHERE a._id = b.ParentId ) portion of query,
but problem is it is not a column so room library does not map it getTaskList method in dao implementation (auto-generated) class.

Is there any way to fill non column field of entity (like noOfSubTask in my case) using any method of dao class of room library?

答:
Create a sub class of Task suppose

```<code>public class TaskDisplayModel extends Task{

@Ignore
private transient int noOfSubTask;

}
</code>```

Then your query will be

```<code>@Query("SELECT *,(SELECT count(*) FROM Task b  WHERE a._id = b.ParentId ) AS noOfSubTask FROM Task a ")
LiveData<List<TaskDisplayModel >> getTaskList();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a class entity as below

@Entity
public class Task {
    private String name;
    private Integer ParentId;
    private Integer userId;
    @Ignore
    private int noOfSubTask;
}

in DAO class there is a method getTaskList()

@Dao
public interface TaskDao extends Dao<Task> {

@Query("SELECT *,(SELECT count(*) FROM Task b  WHERE a._id = b.ParentId ) AS noOfSubTask FROM Task a ")
LiveData<List<Task>> getTaskList();
}

I want to fill
noOfSubTask with the number given by (SELECT count(*) FROM Task b  WHERE a._id = b.ParentId ) portion of query,
but problem is it is not a column so room library does not map it getTaskList method in dao implementation (auto-generated) class.

Is there any way to fill non column field of entity (like noOfSubTask in my case) using any method of dao class of room library?

Body:
Create a sub class of Task suppose

public class TaskDisplayModel extends Task{

@Ignore
private transient int noOfSubTask;

}

Then your query will be

@Query("SELECT *,(SELECT count(*) FROM Task b  WHERE a._id = b.ParentId ) AS noOfSubTask FROM Task a ")
LiveData<List<TaskDisplayModel >> getTaskList();


问:
Fastest Way To Query SQL with Loop
I have an issue to looping SQL Query using VBA, its take a long time to run.
Total looping is 115 times in 15 minutes. Is there any way reduce the query time?
Here's is my code :</p>

```<code>    Dim Conn As New ADODB.Connection
    Dim mrs As New ADODB.Recordset
    x = 1
    DBPath = ThisWorkbook.FullName
    sconnect = "Provider=SQLOLEDB;SERVER=DWSQL\BCAPP;Database=TEST;Uid=admin;Pwd=admin;"
    Conn.Open sconnect
    Do
        If Sheets("Foil (+)").Cells(12, 12) <> "" And Sheets("Data").Cells(x, 3).Value Like "E*" Then
            sSqlSting = "SELECT *FROM [TEST].[dbo].[process_details] where pos_no = '" & Sheets("Data").Cells(x, 3) & "' and scan_type = 'Anode Foil' and status = 'OK' and returned = 'N'"
        Else
            Sheets("Data").Cells(x, 3).Value = "E" & Sheets("Data").Cells(x, 3).Value
            sSqlSting = "SELECT *FROM [TEST].[dbo].[process_details] where pos_no = '" & Sheets("Data").Cells(x, 3) & "' and scan_type = 'Anode Foil' and status = 'OK' and returned = 'N'"
        End If

        mrs.Open sSqlSting, Conn, adOpenForwardOnly
        If Sheets("Data").Cells(1, 18) = "" Then
            Sheets("Data").Cells(1, 18).CopyFromRecordset mrs
        Else
            Sheets("Data").Cells(Rows.Count, 18).End(xlUp).Offset(1, 0).CopyFromRecordset mrs
        End If
        mrs.Close
        x = x + 1
    Loop Until Sheets("Data").Cells(x, 3) = ""
    Conn.Close
</code>```

答:
```<code>   sSqlSting = "SELECT *FROM [TEST].[dbo].[process_details] where scan_type = 'Anode Foil' and status = 'OK' and returned = 'N' and pos_no = in ('"
enter code here

 Do
    If Sheets("Foil (+)").Cells(12, 12) <> "" And Sheets("Data").Cells(x, 3).Value Like "E*" Then
        sSqlSting = sSqlString &  Sheets("Data").Cells(x, 3) & "','"
    Else
        Sheets("Data").Cells(x, 3).Value = "E" & Sheets("Data").Cells(x, 3).Value
        sSqlSting = sSqlString &  '" & Sheets("Data").Cells(x, 3) & "','"
    End If
     x = x + 1
Loop Until Sheets("Data").Cells(x, 3) = ""

 sSqlSting = left(sSqlSting,len(sSqlsting)-1) & ")"

    mrs.Open sSqlSting, Conn, adOpenForwardOnly
    If Sheets("Data").Cells(1, 18) = "" Then
        Sheets("Data").Cells(1, 18).CopyFromRecordset mrs
    Else
        Sheets("Data").Cells(Rows.Count, 18).End(xlUp).Offset(1, 0).CopyFromRecordset mrs
    End If
    mrs.Close
</code>```

Title: Fastest Way To Query SQL with Loop

Body:
I have an issue to looping SQL Query using VBA, its take a long time to run.
Total looping is 115 times in 15 minutes. Is there any way reduce the query time?
Here's is my code :

    Dim Conn As New ADODB.Connection
    Dim mrs As New ADODB.Recordset
    x = 1
    DBPath = ThisWorkbook.FullName
    sconnect = "Provider=SQLOLEDB;SERVER=DWSQL\BCAPP;Database=TEST;Uid=admin;Pwd=admin;"
    Conn.Open sconnect
    Do
        If Sheets("Foil (+)").Cells(12, 12) <> "" And Sheets("Data").Cells(x, 3).Value Like "E*" Then
            sSqlSting = "SELECT *FROM [TEST].[dbo].[process_details] where pos_no = '" & Sheets("Data").Cells(x, 3) & "' and scan_type = 'Anode Foil' and status = 'OK' and returned = 'N'"
        Else
            Sheets("Data").Cells(x, 3).Value = "E" & Sheets("Data").Cells(x, 3).Value
            sSqlSting = "SELECT *FROM [TEST].[dbo].[process_details] where pos_no = '" & Sheets("Data").Cells(x, 3) & "' and scan_type = 'Anode Foil' and status = 'OK' and returned = 'N'"
        End If

        mrs.Open sSqlSting, Conn, adOpenForwardOnly
        If Sheets("Data").Cells(1, 18) = "" Then
            Sheets("Data").Cells(1, 18).CopyFromRecordset mrs
        Else
            Sheets("Data").Cells(Rows.Count, 18).End(xlUp).Offset(1, 0).CopyFromRecordset mrs
        End If
        mrs.Close
        x = x + 1
    Loop Until Sheets("Data").Cells(x, 3) = ""
    Conn.Close


问:
Prestashop 1.6 CCC css new file in cache each time
I don't know how prestashop work. I'm a full stack developer and i need to resolve a problem in a prestashop project.

I use a theme "sns_kanta" modified by one other developper.

When i enable the css cache with the CCC options in dashboard, each time a user load a page, a compiled css file is created in cache folder in the theme. 1 page view = 1 new file.

Many time later... this give 28 GB useless data. Time passed to compile it is useless.

Anyone have an idea ?
A start point for see where is the problem ? To debug it.

i try to check the prestashop documentation and try to see why css it's compiled each time  ...

I know it's not easy without an access and all data, but if you have an idea, a file to check, ...

Thx a lot in advance

答:
You should have a look at displayHeader() method in classes/controller/FrontController.php. For each page, this method will check if CCC is activated and will accordingly assign one or multiple css files to the header of your page.

If CCC is activated, then the method cccCss() in classes/controller/Media.php is called. You can debug this method to find the file that have changed since last page load.


问:
Update observable from promise based on other observable
I have a service which returns filters from our backend. This service has a method getForPage which returns a promise, and a getForPage$ which returns an observable.

On the service there is also the method onEvent which is an observable which emits when there was a change on a filter.

Now I want that the getForPage$ observable is updated when the onEvent emits an event. Which is done with the following code.

```<code>getForPage(page: string): Promise<DashboardPageFilter[]> {
    return this.service.call(
        'dashboard.page.filter.getForPage',
        {page}
    );
}

getForPage$(page: string): Observable<DashboardPageFilter[]> {
    let subject = new Subject<DashboardPageFilter[]>();

    this.getForPage(page).then(
        response => subject.next(response),
        response => subject.error(response)
    );

    this.onEvent().subscribe(() => {
        console.log(page);
        this.getForPage(page).then(
            response => subject.next(response),
            response => subject.error(response)
        );
    });

    return subject.asObservable();
}
</code>```

However when I can the route the subscription on onEvent won't be closed. So the log will be called even when there is not an active subscription any more on the subject observable.

How do you make an observable from a promise which can be to be updated and is completed on route change?

答:
You can use a merge operator instead:

```<code>getForPage$(page: string): Observable<DashboardPageFilter[]> {

    const obsFromPromise = Observable.fromPromise(this.getForPage(page));

    const result = this.onEvent.switchMap(() => Observable.fromPromise(this.getForPage(page)));

    return Observable.merge(obsFromPromise, obsFromEvent)
}
</code>```

By doing this, your promise and your event are merged into one observable with no subscription.

More details about the merge operator are available on rxjs documentation website.

Body:
I have a service which returns filters from our backend. This service has a method getForPage which returns a promise, and a getForPage$ which returns an observable.

On the service there is also the method onEvent which is an observable which emits when there was a change on a filter.

Now I want that the getForPage$ observable is updated when the onEvent emits an event. Which is done with the following code.

getForPage(page: string): Promise<DashboardPageFilter[]> {
    return this.service.call(
        'dashboard.page.filter.getForPage',
        {page}
    );
}

getForPage$(page: string): Observable<DashboardPageFilter[]> {
    let subject = new Subject<DashboardPageFilter[]>();

    this.getForPage(page).then(
        response => subject.next(response),
        response => subject.error(response)
    );

    this.onEvent().subscribe(() => {
        console.log(page);
        this.getForPage(page).then(
            response => subject.next(response),
            response => subject.error(response)
        );
    });

    return subject.asObservable();
}

However when I can the route the subscription on onEvent won't be closed. So the log will be called even when there is not an active subscription any more on the subject observable.

How do you make an observable from a promise which can be to be updated and is completed on route change?

Body:
You can use a merge operator instead:

getForPage$(page: string): Observable<DashboardPageFilter[]> {

    const obsFromPromise = Observable.fromPromise(this.getForPage(page));

    const result = this.onEvent.switchMap(() => Observable.fromPromise(this.getForPage(page)));

    return Observable.merge(obsFromPromise, obsFromEvent)
}

By doing this, your promise and your event are merged into one observable with no subscription.

More details about the merge operator are available on rxjs documentation website.


问:
Does iostream includes functions of cstdio?
I use Dev C++ 5.11. TDM-GCC 4.8.1

And this code runs well.

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

int main()
{
printf("%d\n", 42);
cout << "good";
}
</code>```

But as far as I know, iostream does not include "printf".  (http://en.cppreference.com/w/cpp/header/iostream)

Why this code run? iostream acutally include printf? Is it a kind of standard?

答:
The list of header files included in a system/standard header file is library implementation dependent (that is usually associated with the compiler you're using), and (as far as I remember) the C++ standard does not prohibit one header file from automatically including another one

In your case <iostream> is probably also #including <stdio.h> (or <cstdio>).

Relying on a header file being included in another is non portable to different standard libraries, compilers and platforms, so it's better to make sure that you explicitly #include everything you need.

Body:
I use Dev C++ 5.11. TDM-GCC 4.8.1

And this code runs well.

#include<iostream>
using namespace std;

int main()
{
printf("%d\n", 42);
cout << "good";
}

But as far as I know, iostream does not include "printf".  (http://en.cppreference.com/w/cpp/header/iostream)

Why this code run? iostream acutally include printf? Is it a kind of standard?


问:
how to pass list when redirect to another controller in mvc?
This is my search action I get the output value with query and I want to pass this value to another action AddCurrency, but after redirect the value became null although it have value before redirect please help me what is the error here:

```<code>//the output after redirect became null
public ActionResult SearchCurrency(string Word)
{
    List<Currency> Output = (from Cur in db.Currencies.ToList()
                             where Word.All(s => Cur.currencyname.Contains(s))
                             select Cur).ToList();

    return RedirectToAction("AddCurrency",Output);
}

//  this is my AddCurrency Action
[HttpGet]
public ActionResult AddCurrency(List<Currency> Output =null)
{
    if (Output !=null)
    {
        ViewBag.L = from cur in Output where cur.CurrencyProperties == "L"  select cur;
        ViewBag.T = from cur in Output where cur.CurrencyProperties == "T" select cur;
        ViewBag.B = from cur in Output where cur.CurrencyProperties == "B" select cur;
        ViewBag.Count = Output.Count();

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

答: Save data in TempData and use it in the redirected action method.</p>

Body:
This is my search action I get the output value with query and I want to pass this value to another action AddCurrency, but after redirect the value became null although it have value before redirect please help me what is the error here:

//the output after redirect became null
public ActionResult SearchCurrency(string Word)
{
    List<Currency> Output = (from Cur in db.Currencies.ToList()
                             where Word.All(s => Cur.currencyname.Contains(s))
                             select Cur).ToList();

    return RedirectToAction("AddCurrency",Output);
}

//  this is my AddCurrency Action
[HttpGet]
public ActionResult AddCurrency(List<Currency> Output =null)
{
    if (Output !=null)
    {
        ViewBag.L = from cur in Output where cur.CurrencyProperties == "L"  select cur;
        ViewBag.T = from cur in Output where cur.CurrencyProperties == "T" select cur;
        ViewBag.B = from cur in Output where cur.CurrencyProperties == "B" select cur;
        ViewBag.Count = Output.Count();

        return View();
    }
}


问:
Beautiful Soup skip comment and script tags
I'm using Beautiful Soup for replacing text.

Here's an example my code:

```<code>for x in soup.find('body').find_all(string=True):
   fix_str = re.sub(...)
   x.replace_with(fix_str)
</code>```

How do I skip the script and comment (<--! -->) tags?

How can I determine which elements or tag are in x?

答:
If you take the parent item for each text item you get, you can then determine whether or not it comes from within a

Some text 1

Some text 2

<script>a script</script>
Some text 2

"""

soup = BeautifulSoup(html, "html.parser")

for text in soup.body.find_all(string=True):
    if text.parent.name != 'script' and not isinstance(text, Comment):
        text.replace_with('new text')   # add re.sub() logic here

print soup
```

<p>Giving you the following new HTML:</p>

```

<title>A title</title>
<script>a script</script>

new textnew textnew textnew text<script>a script</script>new text

```

Body:
I'm using Beautiful Soup for replacing text.

Here's an example my code:

for x in soup.find('body').find_all(string=True):
   fix_str = re.sub(...)
   x.replace_with(fix_str)

How do I skip the script and comment (<--! -->) tags?

How can I determine which elements or tag are in x?

Body:
If you take the parent item for each text item you get, you can then determine whether or not it comes from within a <script> tag or from an HTML comment. If not, the text can then be used to call replace_with() using your re.sub() function:

from bs4 import BeautifulSoup, Comment

html = """<html>
<head>
<!-- a comment -->
<title>A title</title>
<script>a script</script>
</head>

<body>
Some text 1
<!-- a comment -->
<!-- a comment -->
Some text 2
<!-- a comment -->
<script>a script</script>
Some text 2
</body>
</html>"""

soup = BeautifulSoup(html, "html.parser")

for text in soup.body.find_all(string=True):
    if text.parent.name != 'script' and not isinstance(text, Comment):
        text.replace_with('new text')   # add re.sub() logic here

print soup

Giving you the following new HTML:

<html>
<head>
<!-- a comment -->
<title>A title</title>
<script>a script</script>
</head>
<body>new text<!-- a comment -->new text<!-- a comment -->new text<!-- a comment -->new text<script>a script</script>new text</body>
</html>


问:
SQL get latest row in one to many relationship using where clause only
I have two tables in which (roll_no) is same in both tables.
I have a table (student) having columns name and roll_no. e.g

```<code>roll_no    name
----------------
123        John
</code>```

It has relation with another table (student_changed). Which has columns name, roll_no and LastEditTime. e.g.

```<code>roll_no    name     LastEditTime
--------------------------------------
123        Johny    2017-11-09 06:00:00
123        John     2017-11-08 07:00:00
</code>```

What I want to ask is, how can I get the join having the most recent LastEditTime.
There are many similar questions but my limitation is that I can only use/modify where clause.
e.g.
I cannot modify the select query as well.
Consider it like this

```<code>select * from student, student_changed <-- *this part cannot be changed*
where <-- This can be modified
</code>```

答:
Try this query:

```<code>select roll_no,name, max(LastEditTime)
from table2
group by
roll_no,name;
</code>```

Update 1:

```<code>select table1.roll_no,table1.name, max(table2.LastEditTime)
from table2 join table1 on table1.roll_no=table2.roll_no
group by
table1.roll_no,table1.name;
</code>```

One table is enough for your requirement.

Update 2:

```<code>select table1.roll_no,table1.name, max(table2.LastEditTime)
from table2 join table1
where table1.roll_no=table2.roll_no
group by table1.roll_no,table1.name;
</code>```

Update 3:

```<code>select table1.roll_no,table1.name,table2.LastEditTime
from table2 join table1
where
(table1.roll_no,table1.name,table2.lastEditTime) in (select table1.roll_no,table1.name, max(table2.LastEditTime) from table2 join table 1 on table1.roll_no=table2.roll_no
group by table1.roll_no,table1.name);
</code>```

Body:
I have two tables in which (roll_no) is same in both tables.
I have a table (student) having columns name and roll_no. e.g

roll_no    name
----------------
123        John

It has relation with another table (student_changed). Which has columns name, roll_no and LastEditTime. e.g.

roll_no    name     LastEditTime
--------------------------------------
123        Johny    2017-11-09 06:00:00
123        John     2017-11-08 07:00:00

What I want to ask is, how can I get the join having the most recent LastEditTime.
There are many similar questions but my limitation is that I can only use/modify where clause.
e.g.
I cannot modify the select query as well.
Consider it like this

select * from student, student_changed <-- *this part cannot be changed*
where <-- This can be modified

Body:
Try this query:

select roll_no,name, max(LastEditTime)
from table2
group by
roll_no,name;

Update 1:

select table1.roll_no,table1.name, max(table2.LastEditTime)
from table2 join table1 on table1.roll_no=table2.roll_no
group by
table1.roll_no,table1.name;

One table is enough for your requirement.

Update 2:

select table1.roll_no,table1.name, max(table2.LastEditTime)
from table2 join table1
where table1.roll_no=table2.roll_no
group by table1.roll_no,table1.name;

Update 3:

select table1.roll_no,table1.name,table2.LastEditTime
from table2 join table1
where
(table1.roll_no,table1.name,table2.lastEditTime) in (select table1.roll_no,table1.name, max(table2.LastEditTime) from table2 join table 1 on table1.roll_no=table2.roll_no
group by table1.roll_no,table1.name);


问:
phonegap cli 6.5 Skipping 'cordova-plugin-camera' for android
Phone Gap Build Getting failed.
On Build Log Getting following Error

Installing "cordova-plugin-camera" at "3.0.0" for android

Plugin doesn't support this project's cordova-android version.
  cordova-android: 6.1.2, failed version requirement: >=6.3.0

Skipping 'cordova-plugin-camera' for android

Getting same issue for cordova-plugin-file-transfer plugin also.

Here is my Config XML

```<code><?xml version="1.0" encoding="UTF-8"?>
<widget
xmlns="http://www.w3.org/ns/widgets"
xmlns:gap="http://phonegap.com/ns/1.0" id="com.myapp.Entry" version="2017.1" versionCode="197">
<name>My App</name>
<description>
    My App
</description>
<author email="sujoy.banerjee@synechron.com">
    Sujoy Banerjee
</author>
<!-- Multi-Platform -->
<preference name="phonegap-version" value="cli-6.5.0" />
<preference name="orientation" value="default" />
<preference name="fullscreen" value="false" />
<preference name="webviewbounce" value="false" />
<!-- iOS Only-->
<preference name="target-device" value="universal" />
<gap:config-file platform="ios" parent="CFBundleVersion">
    <string>2017.01.0</string>
</gap:config-file>
<gap:config-file parent="NSPhotoLibraryUsageDescription" platform="ios" target="*-Info.plist">
    <string>This app needs access to your Photo Library to include images of the incident</string>
</gap:config-file>
<gap:config-file parent="NSCameraUsageDescription" platform="ios" target="*-Info.plist">
    <string>This app needs to access the camera to include images of the incident</string>
</gap:config-file>
<!-- Android Only-->
<preference name="android-windowSoftInputMode" value="adjustResize" />
<preference name="android-minSdkVersion" value="11" />
<!-- Supproted Platforms -->
<gap:platform name="ios" />
<gap:platform name="android" />
<!-- Core plugins -->
<gap:plugin name="cordova-plugin-whitelist" source="npm" />
<gap:plugin name="cordova-plugin-camera" source="npm" />
<gap:plugin name="cordova-plugin-file-transfer" source="npm" />
<gap:plugin name="cordova-plugin-network-information" source="npm" />
<gap:plugin name="cordova-plugin-inappbrowser" source="npm" />
<!-- Icon are here.... -->
</code>```

答:
After lots of R&D finally i got the key solution.Use older version of cordova camera plugin.Current version is 3.0.0 use older version 2.4.1.</p>

```<code><plugin name="cordova-plugin-camera" spec="2.4.1" />
</code>```

Body:
Phone Gap Build Getting failed.
On Build Log Getting following Error

Installing "cordova-plugin-camera" at "3.0.0" for android

Plugin doesn't support this project's cordova-android version.
  cordova-android: 6.1.2, failed version requirement: >=6.3.0

Skipping 'cordova-plugin-camera' for android

Getting same issue for cordova-plugin-file-transfer plugin also.

Here is my Config XML

<?xml version="1.0" encoding="UTF-8"?>
<widget
xmlns="http://www.w3.org/ns/widgets"
xmlns:gap="http://phonegap.com/ns/1.0" id="com.myapp.Entry" version="2017.1" versionCode="197">
<name>My App</name>
<description>
    My App
</description>
<author email="sujoy.banerjee@synechron.com">
    Sujoy Banerjee
</author>

<preference name="phonegap-version" value="cli-6.5.0" />
<preference name="orientation" value="default" />
<preference name="fullscreen" value="false" />
<preference name="webviewbounce" value="false" />

<preference name="target-device" value="universal" />
<gap:config-file platform="ios" parent="CFBundleVersion">
    <string>2017.01.0</string>
</gap:config-file>
<gap:config-file parent="NSPhotoLibraryUsageDescription" platform="ios" target="*-Info.plist">
    <string>This app needs access to your Photo Library to include images of the incident</string>
</gap:config-file>
<gap:config-file parent="NSCameraUsageDescription" platform="ios" target="*-Info.plist">
    <string>This app needs to access the camera to include images of the incident</string>
</gap:config-file>

<preference name="android-windowSoftInputMode" value="adjustResize" />
<preference name="android-minSdkVersion" value="11" />

<gap:platform name="ios" />
<gap:platform name="android" />

<gap:plugin name="cordova-plugin-whitelist" source="npm" />
<gap:plugin name="cordova-plugin-camera" source="npm" />
<gap:plugin name="cordova-plugin-file-transfer" source="npm" />
<gap:plugin name="cordova-plugin-network-information" source="npm" />
<gap:plugin name="cordova-plugin-inappbrowser" source="npm" />

Body:
After lots of R&D finally i got the key solution.Use older version of cordova camera plugin.Current version is 3.0.0 use older version 2.4.1.

<plugin name="cordova-plugin-camera" spec="2.4.1" />


问:
How is possible to identify Tampering Data in Hidden Field in PHP?
Introduction

It is required to identify the changes made by someone in hidden field through tampering data application.

Snapshot

<img src="https://i.stack.imgur.com/XWcqF.jpg" alt="In the snapshot, hidden field tampering application is opened and all the fields are there including text fields as well as hidden fields. The price has been changed from 2999 to 29.">

Question

How to identify that the someone is changing the hidden field value our web page through this application? Is there any way to identify in JavaScript (through AJAX or JQuery code)? or is there any other way to identify?

答:
If your are loading the value into a hidden field, then I am assuming you know what the value is and should be.

Option One:
Store the value in a session before the hidden input gets displayed and then compare on form post.

```<code>session_start();
$_SESSION['hiddenValue'] = $someValue;

<form action="http://somedomain.com/endpoint" method="post">
   ...
   <input type="hidden" name="hidden" value="<?php echo $someValue;?>"/>
   <button type="submit">Submit</button>
</form>
</code>```

Then on POST:

```<code><?php
   if($_POST['hidden'] != $_SESSION['hiddenValue']) {
         // Hidden value has been changed.
   }
</code>```

Option Two:
Read the value back from database or other data source and compare with post.

```<code>$someValue = // Load value from your data source

<form action="http://somedomain.com/endpoint" method="post">
   ...
   <input type="hidden" name="hidden" value="<?php echo $someValue;?>"/>
   <button type="submit">Submit</button>
</form>
</code>```

Then on POST:

```<code><?php
   $someValue = // Load value from your data source

   if($_POST['hidden'] != $someValue) {
         // Hidden value has been changed.
   }
</code>```

Body:
If your are loading the value into a hidden field, then I am assuming you know what the value is and should be.

Option One:
Store the value in a session before the hidden input gets displayed and then compare on form post.

session_start();
$_SESSION['hiddenValue'] = $someValue;

<form action="http://somedomain.com/endpoint" method="post">
   ...
   <input type="hidden" name="hidden" value="<?php echo $someValue;?>"/>
   <button type="submit">Submit</button>
</form>

Then on POST:

<?php
   if($_POST['hidden'] != $_SESSION['hiddenValue']) {
         // Hidden value has been changed.
   }

Option Two:
Read the value back from database or other data source and compare with post.

$someValue = // Load value from your data source

<form action="http://somedomain.com/endpoint" method="post">
   ...
   <input type="hidden" name="hidden" value="<?php echo $someValue;?>"/>
   <button type="submit">Submit</button>
</form>

Then on POST:

<?php
   $someValue = // Load value from your data source

   if($_POST['hidden'] != $someValue) {
         // Hidden value has been changed.
   }


问:
Converting input range to array in function
I have been learning VBA and thought I was getting the hang of it, but for some reason this basic task is eluding me. I am trying to create a function where I select an input region of numbers (really only one row or column), and then output the summation of the numbers in a cell. Here is my code:

```<code>Function CashFlow(CashArray As Excel.Range)

Dim cashflows() As Variant
cashflows = CashArray.Value

amount = CashArray.Rows.Count

dim y()
redim y(amount)
Sum = 0

For i = 1 To amount
    y(i) = cashflows(i)
    Sum = Sum + y(i)
Next i

CashFlow = Sum

End Function
</code>```

Despite me knowing how to do essentially this in a subroutine, the fact that I'm getting my data from the function's input is throwing me off. How do I accomplish this task?

答:
Just to summarize the above comments, please give the following code a try:

```<code>Option Explicit

Function CashFlow(CashArray As Excel.Range)

Dim sum As Double
Dim x As Long, y As Long
Dim cashflows() As Variant

cashflows = CashArray.Value
sum = 0

For y = LBound(cashflows, 1) To UBound(cashflows, 1)
    For x = LBound(cashflows, 2) To UBound(cashflows, 2)
        sum = sum + cashflows(y, x)
    Next x
Next y

CashFlow = sum

End Function
</code>```

Note, that this code summarizes all cells in the given range (even if there are multiple rows and columns in that range). Basically, the range is stored in the array cashflows. As mentioned in the comments, this will yield a two-dimensional array. The function LBound(cashflows) will give you the Lower Boundary of that array.

By specifying LBound(cashflows, 1) I am specifically asking for the lower boundary of the first dimension (in this case the rows). UBound returns the Upper Boundary of that array for the specified dimension. Similarily UBound(cashflows, 2) returns the last column (second dimension) of the given array.

Remark: I am always using LBound() and UBound() in my code instead of starting with 0 or 1 to avoid coding errors. Some people prefer Option Base 0 and some prefer Option Base 1. While neither will have an impact on the above (as ranges always yield an array starting with 1) it is just good coding practice to prevent bugs in the future.

Body:
I have been learning VBA and thought I was getting the hang of it, but for some reason this basic task is eluding me. I am trying to create a function where I select an input region of numbers (really only one row or column), and then output the summation of the numbers in a cell. Here is my code:

Function CashFlow(CashArray As Excel.Range)

Dim cashflows() As Variant
cashflows = CashArray.Value

amount = CashArray.Rows.Count

dim y()
redim y(amount)
Sum = 0

For i = 1 To amount
    y(i) = cashflows(i)
    Sum = Sum + y(i)
Next i

CashFlow = Sum

End Function

Despite me knowing how to do essentially this in a subroutine, the fact that I'm getting my data from the function's input is throwing me off. How do I accomplish this task?

Body:
Just to summarize the above comments, please give the following code a try:

Option Explicit

Function CashFlow(CashArray As Excel.Range)

Dim sum As Double
Dim x As Long, y As Long
Dim cashflows() As Variant

cashflows = CashArray.Value
sum = 0

For y = LBound(cashflows, 1) To UBound(cashflows, 1)
    For x = LBound(cashflows, 2) To UBound(cashflows, 2)
        sum = sum + cashflows(y, x)
    Next x
Next y

CashFlow = sum

End Function

Note, that this code summarizes all cells in the given range (even if there are multiple rows and columns in that range). Basically, the range is stored in the array cashflows. As mentioned in the comments, this will yield a two-dimensional array. The function LBound(cashflows) will give you the Lower Boundary of that array.

By specifying LBound(cashflows, 1) I am specifically asking for the lower boundary of the first dimension (in this case the rows). UBound returns the Upper Boundary of that array for the specified dimension. Similarily UBound(cashflows, 2) returns the last column (second dimension) of the given array.

Remark: I am always using LBound() and UBound() in my code instead of starting with 0 or 1 to avoid coding errors. Some people prefer Option Base 0 and some prefer Option Base 1. While neither will have an impact on the above (as ranges always yield an array starting with 1) it is just good coding practice to prevent bugs in the future.


问:
React-Redux Store is not properly changed by reducer
I'm struggling to learn React-Redux. I'm making a simple application that fetch data from Teleport API and show the list according to the user's input.

My issue is that even though action is dispatched in container component, state is not changed and the result does not show up.

This is a screenshot of console after dispatching action twice.

I suppose that there is an issue to store data properly. I appreciate if you can help me.

Here is my code.

/container/search.js

```<code>class Search extends Component{
 constructor(props){
    super(props);
    this.state = {
      city : ""
    }
   this.handleSubmit = this.handleSubmit.bind(this);
   this.handleChange = this.handleChange.bind(this);
   }

handleChange(event) {
    console.log(event.target.value)
    this.setState({
        city: event.target.value
    });
}

handleSubmit(event){
    event.preventDefault();
    console.log(this.state.city)
    this.props.addData(this.state.city);
    this.setState({
        city: ""
    });
}
render(){
    return(
        <div>
        <form onSubmit={this.handleSubmit}>
        <input type="text"
               placeholder="add city name"
               onChange={this.handleChange}
               value={this.state.city} />
        <button>Submit</button>
        </form>
        </div>
        )
}
}

function mapDispatchToProps(dispatch) {
return bindActionCreators({ addData }, dispatch);
}

export default connect(null, mapDispatchToProps)(Search);
</code>```

/actions/index.js

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

const ROOT_URL = "https://api.teleport.org/api/cities/?search";

const ADD_DATA = 'ADD_DATA';

export function addData(city){
    const url = `${ROOT_URL}=${city}`;
    const request = axios.get(url);
    return {
        type: ADD_DATA,
        payload: request
    };
 }
</code>```

/reducers/reducer_data.js

```<code>import { ADD_DATA } from "../actions/index";

export default function( state=[], action) {
switch(action.type) {
    case ADD_DATA:
        return [action.payload.data, ...state];
}
return state;
}
</code>```

/reducers/index.js

```<code>import { ADD_DATA } from "../actions/index";

export default function( state=[], action) {
    switch(action.type) {
        case ADD_DATA:
            return [action.payload.data, ...state];
}
return state;
}
</code>```

//EDIT
// index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import promiseMiddleware from 'redux-promise';
import logger from 'redux-logger'

import reducers from './reducers';
import Search from './containers/search';

const createStoreWithMiddleware = applyMiddleware(promiseMiddleware, logger)(createStore);

ReactDOM.render(
    <Provider store={createStoreWithMiddleware(reducers)}>
    <Search />
    </Provider>
, document.querySelector('.container'));
</code>```

答:
You can use redux api middleware to do the api call.All you have to change is

actions/index.js

```<code>import {CALL_API} from 'redux-api-middleware';

export const addData=(city)=>({

    [CALL_API]:{

        endpoint:"https://api.teleport.org/api/cities",
        query:{
              "search":city
             }
        method:'GET',
        types:["ADD_DATA","ADD_DATA_SUCCESS","ADD_DATA_FAILURE"]
    }
    });
</code>```

/reducers/reducer_data.js

```<code>           import {combineReducers} from 'redux'
                const InitialData={
                    dataList:[],
                    error:null,
                    loading:false
                }
                export const dataList=(state=InitialData,action)=>{
                    switch(action.type){
                        case "ADD_DATA":
                            return Object.assign({},state,{
                                dataList:[],error:null,loading:true
                            })
                        case "ADD_DATA_SUCCESS":
                            return Object.assign({},state,{
                                dataList:action.payload,error:null,loading:false
                            })
                        case "ADD_DATA_FAILURE":
                           error = action.payload.data || { message: action.payload };
                            return Object.assign({},state,{
                                dataList:action.payload,error:error,loading:false
                            })
                        default:
                            return state;
                    }
                }

            //Its better to use combine reducer to combine all the reducers
            //you have in your app  as one as redux permits only one store per app

            export const reducers=combineReducers({
            DataList:dataList
            })

export default reducers
</code>```

store.js

```<code>import {
  applyMiddleware,
  createStore,compose
} from 'redux';

// import thunk from 'redux-thunk';
import { apiMiddleware } from 'redux-api-middleware';
import {CALL_API} from 'redux-api-middleware';
import promise from 'redux-promise';
import reducers from './reducer';
import { logger} from 'redux-logger';
import ReduxThunk from 'redux-thunk'

import qs from 'querystring'

 function queryMiddleware() {
  return next => action => {
    if (action.hasOwnProperty(CALL_API) && action[CALL_API].hasOwnProperty('query')) {
      const request = action[CALL_API];
      request.endpoint = [
        request.endpoint.replace(/\?*/, ''),
        qs.stringify(request.query),
      ].join('?');
      delete request.query;

      return next({ [CALL_API]: request });
    }

    return next(action);
  };
}
export function ConfigureStore(IntitialState={}){
    const stores=createStore(reducers,IntitialState,compose(
        applyMiddleware(queryMiddleware,ReduxThunk,apiMiddleware,promise),
         window.devToolsExtension ? window.devToolsExtension() : f => f
        ));

    return stores;
};
 export const  store=ConfigureStore()
</code>```

index.js

```<code>import React from 'react'
import  ReactDOM from 'react-dom'
import store from './store'
import Search from './Search'
ReactDOM.render((
     <Provider store={store}>
            <Search />
        </Provider>
    ),document.getElementById('main-container'))
</code>```

Note: you can install Redux devtools extension in chrome and u can check the redux store in your chrome developer tools.I think this will be easy to find out what happens in your redux store.

Body:
I'm struggling to learn React-Redux. I'm making a simple application that fetch data from Teleport API and show the list according to the user's input.

My issue is that even though action is dispatched in container component, state is not changed and the result does not show up.

This is a screenshot of console after dispatching action twice.

I suppose that there is an issue to store data properly. I appreciate if you can help me.

Here is my code.

/container/search.js

class Search extends Component{
 constructor(props){
    super(props);
    this.state = {
      city : ""
    }
   this.handleSubmit = this.handleSubmit.bind(this);
   this.handleChange = this.handleChange.bind(this);
   }

handleChange(event) {
    console.log(event.target.value)
    this.setState({
        city: event.target.value
    });
}

handleSubmit(event){
    event.preventDefault();
    console.log(this.state.city)
    this.props.addData(this.state.city);
    this.setState({
        city: ""
    });
}
render(){
    return(

        <form onSubmit={this.handleSubmit}>
        <input type="text"
               placeholder="add city name"
               onChange={this.handleChange}
               value={this.state.city} />
        <button>Submit</button>
        </form>

        )
}
}

function mapDispatchToProps(dispatch) {
return bindActionCreators({ addData }, dispatch);
}

export default connect(null, mapDispatchToProps)(Search);

/actions/index.js

import axios from 'axios';

const ROOT_URL = "https://api.teleport.org/api/cities/?search";

const ADD_DATA = 'ADD_DATA';

export function addData(city){
    const url = `${ROOT_URL}=${city}`;
    const request = axios.get(url);
    return {
        type: ADD_DATA,
        payload: request
    };
 }

/reducers/reducer_data.js

import { ADD_DATA } from "../actions/index";

export default function( state=[], action) {
switch(action.type) {
    case ADD_DATA:
        return [action.payload.data, ...state];
}
return state;
}

/reducers/index.js

import { ADD_DATA } from "../actions/index";

export default function( state=[], action) {
    switch(action.type) {
        case ADD_DATA:
            return [action.payload.data, ...state];
}
return state;
}

//EDIT
// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import promiseMiddleware from 'redux-promise';
import logger from 'redux-logger'

import reducers from './reducers';
import Search from './containers/search';

const createStoreWithMiddleware = applyMiddleware(promiseMiddleware, logger)(createStore);

ReactDOM.render(
    <Provider store={createStoreWithMiddleware(reducers)}>
    <Search />
    </Provider>
, document.querySelector('.container'));

Body:
You can use redux api middleware to do the api call.All you have to change is

actions/index.js

import {CALL_API} from 'redux-api-middleware';

export const addData=(city)=>({

    [CALL_API]:{

        endpoint:"https://api.teleport.org/api/cities",
        query:{
              "search":city
             }
        method:'GET',
        types:["ADD_DATA","ADD_DATA_SUCCESS","ADD_DATA_FAILURE"]
    }
    });

/reducers/reducer_data.js

           import {combineReducers} from 'redux'
                const InitialData={
                    dataList:[],
                    error:null,
                    loading:false
                }
                export const dataList=(state=InitialData,action)=>{
                    switch(action.type){
                        case "ADD_DATA":
                            return Object.assign({},state,{
                                dataList:[],error:null,loading:true
                            })
                        case "ADD_DATA_SUCCESS":
                            return Object.assign({},state,{
                                dataList:action.payload,error:null,loading:false
                            })
                        case "ADD_DATA_FAILURE":
                           error = action.payload.data || { message: action.payload };
                            return Object.assign({},state,{
                                dataList:action.payload,error:error,loading:false
                            })
                        default:
                            return state;
                    }
                }

            //Its better to use combine reducer to combine all the reducers
            //you have in your app  as one as redux permits only one store per app

            export const reducers=combineReducers({
            DataList:dataList
            })

export default reducers

store.js

import {
  applyMiddleware,
  createStore,compose
} from 'redux';

// import thunk from 'redux-thunk';
import { apiMiddleware } from 'redux-api-middleware';
import {CALL_API} from 'redux-api-middleware';
import promise from 'redux-promise';
import reducers from './reducer';
import { logger} from 'redux-logger';
import ReduxThunk from 'redux-thunk'

import qs from 'querystring'

 function queryMiddleware() {
  return next => action => {
    if (action.hasOwnProperty(CALL_API) && action[CALL_API].hasOwnProperty('query')) {
      const request = action[CALL_API];
      request.endpoint = [
        request.endpoint.replace(/\?*/, ''),
        qs.stringify(request.query),
      ].join('?');
      delete request.query;

      return next({ [CALL_API]: request });
    }

    return next(action);
  };
}
export function ConfigureStore(IntitialState={}){
    const stores=createStore(reducers,IntitialState,compose(
        applyMiddleware(queryMiddleware,ReduxThunk,apiMiddleware,promise),
         window.devToolsExtension ? window.devToolsExtension() : f => f
        ));

    return stores;
};
 export const  store=ConfigureStore()

index.js

import React from 'react'
import  ReactDOM from 'react-dom'
import store from './store'
import Search from './Search'
ReactDOM.render((
     <Provider store={store}>
            <Search />
        </Provider>
    ),document.getElementById('main-container'))

Note: you can install Redux devtools extension in chrome and u can check the redux store in your chrome developer tools.I think this will be easy to find out what happens in your redux store.


问:
getBoundingClientRect not working as expected on body after transform

$( document ).ready(function() {

    $('body').append('

');
    $('#tester2').css({
     position:'absolute',
      background:'blue',
      width: 10,
      height:10
    });
    setInterval(function(){
      var x = $('#tester')[0].getBoundingClientRect();
      $('#tester-pos').text('top: ' + x.top + ', left:' + x.left);
      $('#tester2').css({
       top:x.top,
       left:x.left
     });
    }, 1000);

    $('#jquery-version').text('jquery version: ' + $.fn.jquery);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#tester{
  position:absolute;
  top:50px;
  left:50px;
  width:10px;
  height:10px;
  background:red;
}

#page{
  min-height:200px;
}

body{
  border:2px solid green;
  transform: scale(1) translate(20px, 40px);
}</code>```

getBoundingClientRect on red tester returned:

```
</div>
</div>
</p>

<p>I need to place a <code>div</code> over an existing <code>div</code>. The existing <code>div</code> is contained inside the body of and HTML document that has the CSS transform property set. I need to place the new <code>div</code> after the document was rendered and transformed.</p>

<p>When I call <code>getBoundingClientRect()</code> on the <code>div</code> that I need to hide (red square in attached fiddle) I get the wrong top/left. I set the top/left of the blue square to the output of <code>getBoundingClientRect()</code> and they do not overlap.</p>

```setInterval(function(){
    var x = $('#tester')[0].getBoundingClientRect();
    $('#tester-pos').text('top: ' + x.top + ', left:' + x.left);
    $('#tester2').css({
        top:x.top,
        left:x.left
    });
}, 1000);
```

How can this be solved?

答:
I have an answer that works, it may not be the best answer yet, but it works 100% for me.

$( document ).ready(function() {

    $('body').append('

');
    $('#tester2').css({
     position:'absolute',
      background:'blue',
      width: 10,
      height:10,
    });

    setInterval(function(){
      var x = $('#tester')[0].getBoundingClientRect();
      $('#tester-pos').text('top: ' + x.top + ', left:' + x.left);
      $('#tester2').css({
       'top':x.top/2,
       'left':(x.left/2)+x.width
     });
    }, 1000);

    $('#jquery-version').text('jquery version: ' + $.fn.jquery);
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#tester{
  position:absolute;
  top:50px;
  left:50px;
  width:10px;
  height:10px;
  background:red;
}

#page{
  min-height:200px;
}

body{
  border:2px solid green;
  transform: scale(1) translate(20px, 40px);
}

#tester2{
  transform: scale(1) translate(0, 0);
}</code>```

getBoundingClientRect on red tester returned:

```

Edit

The only time that my potential solution gets a bit weird is when you have to scroll... So be warned there.

Body:
$( document ).ready(function() {

    $('body').append('

');
    $('#tester2').css({
     position:'absolute',
      background:'blue',
      width: 10,
      height:10
    });
    setInterval(function(){
      var x = $('#tester')[0].getBoundingClientRect();
      $('#tester-pos').text('top: ' + x.top + ', left:' + x.left);
      $('#tester2').css({
       top:x.top,
       left:x.left
     });
    }, 1000);

    $('#jquery-version').text('jquery version: ' + $.fn.jquery);
});

#tester{
  position:absolute;
  top:50px;
  left:50px;
  width:10px;
  height:10px;
  background:red;
}

#page{
  min-height:200px;
}

body{
  border:2px solid green;
  transform: scale(1) translate(20px, 40px);
}

getBoundingClientRect on red tester returned:

I need to place a div over an existing div. The existing div is contained inside the body of and HTML document that has the CSS transform property set. I need to place the new div after the document was rendered and transformed.

When I call getBoundingClientRect() on the div that I need to hide (red square in attached fiddle) I get the wrong top/left. I set the top/left of the blue square to the output of getBoundingClientRect() and they do not overlap.

setInterval(function(){
    var x = $('#tester')[0].getBoundingClientRect();
    $('#tester-pos').text('top: ' + x.top + ', left:' + x.left);
    $('#tester2').css({
        top:x.top,
        left:x.left
    });
}, 1000);

How can this be solved?

Body:
I have an answer that works, it may not be the best answer yet, but it works 100% for me.

$( document ).ready(function() {

    $('body').append('<div id="tester2"></div>');
    $('#tester2').css({
     position:'absolute',
      background:'blue',
      width: 10,
      height:10,
    });

    setInterval(function(){
      var x = $('#tester')[0].getBoundingClientRect();
      $('#tester-pos').text('top: ' + x.top + ', left:' + x.left);
      $('#tester2').css({
       'top':x.top/2,
       'left':(x.left/2)+x.width
     });
    }, 1000);

    $('#jquery-version').text('jquery version: ' + $.fn.jquery);
 });

#tester{
  position:absolute;
  top:50px;
  left:50px;
  width:10px;
  height:10px;
  background:red;
}

#page{
  min-height:200px;
}

body{
  border:2px solid green;
  transform: scale(1) translate(20px, 40px);
}

#tester2{
  transform: scale(1) translate(0, 0);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tester">
</div>
<div id="page">
getBoundingClientRect on red tester returned:
<span id="tester-pos"></span>
<div id="jquery-version"></div>
</div>

Edit

The only time that my potential solution gets a bit weird is when you have to scroll... So be warned there.


问:
Spring Boot Controller not mapping
I have used STS and now I am using IntelliJ Ultimate Edition but I am still getting the same output. My controller is not getting mapped thus showing 404 error. I am completely new to Spring Framework.

DemoApplication.java

```<code>package com.webservice.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
</code>```

HelloController.java

```<code>package com.webservice.demo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String sayHello(){
        return "Hey";
    }

}
</code>```

Console Output

```<code>com.webservice.demo.DemoApplication      : Starting DemoApplication on XFT000159365001 with PID 11708 (started by Mayank Khursija in C:\Users\Mayank Khursija\IdeaProjects\demo)
    2017-07-19 12:59:46.150  INFO 11708 --- [           main] com.webservice.demo.DemoApplication      : No active profile set, falling back to default profiles: default
    2017-07-19 12:59:46.218  INFO 11708 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@238e3f: startup date [Wed Jul 19 12:59:46 IST 2017]; root of context hierarchy
    2017-07-19 12:59:47.821  INFO 11708 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8211 (http)
    2017-07-19 12:59:47.832  INFO 11708 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
    2017-07-19 12:59:47.832  INFO 11708 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.15
    2017-07-19 12:59:47.944  INFO 11708 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2017-07-19 12:59:47.944  INFO 11708 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1728 ms
    2017-07-19 12:59:47.987  INFO 11708 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
    2017-07-19 12:59:48.510  INFO 11708 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
    2017-07-19 12:59:48.519  INFO 11708 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
    2017-07-19 12:59:48.634  INFO 11708 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8211 (http)
    2017-07-19 12:59:48.638  INFO 11708 --- [           main] com.webservice.demo.DemoApplication      : Started DemoApplication in 2.869 seconds (JVM running for 3.44)
</code>```

答:
I too had the similar issue and was able to finally resolve it by correcting the source package structure following this

Your Controller classes are not scanned by the Component scanning. Your Controller classes must be nested below in package hierarchy to the main SpringApplication class having the main() method, then only it will be scanned and you should also see the RequestMappings listed in the console output while Spring Boot is getting started.

Tested on Spring Boot 1.5.8.RELEASE

But in case you prefer to use your own packaging structure, you can always use the @ComponentScan annotation to define your basePackages to scan.

Title: Spring Boot Controller not mapping

Body:
I have used STS and now I am using IntelliJ Ultimate Edition but I am still getting the same output. My controller is not getting mapped thus showing 404 error. I am completely new to Spring Framework.

DemoApplication.java

package com.webservice.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
public class DemoApplication {

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

HelloController.java

package com.webservice.demo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String sayHello(){
        return "Hey";
    }

}

Console Output

com.webservice.demo.DemoApplication      : Starting DemoApplication on XFT000159365001 with PID 11708 (started by Mayank Khursija in C:\Users\Mayank Khursija\IdeaProjects\demo)
    2017-07-19 12:59:46.150  INFO 11708 --- [           main] com.webservice.demo.DemoApplication      : No active profile set, falling back to default profiles: default
    2017-07-19 12:59:46.218  INFO 11708 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@238e3f: startup date [Wed Jul 19 12:59:46 IST 2017]; root of context hierarchy
    2017-07-19 12:59:47.821  INFO 11708 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8211 (http)
    2017-07-19 12:59:47.832  INFO 11708 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
    2017-07-19 12:59:47.832  INFO 11708 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.15
    2017-07-19 12:59:47.944  INFO 11708 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2017-07-19 12:59:47.944  INFO 11708 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1728 ms
    2017-07-19 12:59:47.987  INFO 11708 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
    2017-07-19 12:59:48.510  INFO 11708 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
    2017-07-19 12:59:48.519  INFO 11708 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
    2017-07-19 12:59:48.634  INFO 11708 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8211 (http)
    2017-07-19 12:59:48.638  INFO 11708 --- [           main] com.webservice.demo.DemoApplication      : Started DemoApplication in 2.869 seconds (JVM running for 3.44)


问:
Validating C# base class constructor parameter
After running Code Analysis in VS2010 beta (FxCop for previous versions) I'm getting the following warning:

In externally visible method
  'Identity.Identity(WindowsIdentity)',
  validate parameter 'windowsIdentity'
  before using it.

The constructor is:

```<code>public Identity(WindowsIdentity windowsIdentity)
         : base(windowsIdentity.Token)
{
         init();
}
</code>```

for a class defined as:

```<code>public class Identity : WindowsIdentity
</code>```

My question is, how do I validate the windowsIdentity parameter?  Should I validate it in the constructor, and throw an exception, or is there a better way to call this?

答:
As of C# 6.0 you can use null-coalescing operator combined with the null-conditional operator like this:</p>

```<code>public Identity(WindowsIdentity winIdentity)
    : base(winIdentity?.Token ?? throw new ArgumentNullException(nameof(winIdentity)))
{
    init();
}
</code>```

Body:
After running Code Analysis in VS2010 beta (FxCop for previous versions) I'm getting the following warning:

In externally visible method
  'Identity.Identity(WindowsIdentity)',
  validate parameter 'windowsIdentity'
  before using it.

The constructor is:

public Identity(WindowsIdentity windowsIdentity)
         : base(windowsIdentity.Token)
{
         init();
}

for a class defined as:

public class Identity : WindowsIdentity

My question is, how do I validate the windowsIdentity parameter?  Should I validate it in the constructor, and throw an exception, or is there a better way to call this?

Body:
As of C# 6.0 you can use null-coalescing operator combined with the null-conditional operator like this:

public Identity(WindowsIdentity winIdentity)
    : base(winIdentity?.Token ?? throw new ArgumentNullException(nameof(winIdentity)))
{
    init();
}


问:
contextMenuStrip add Symbols in Margin C# Windows Form Application
I have contextMenuStrip with 6 menu items. In the Margin displayed by default on left, I want to add special characters or Symbols as ↓  on the Margin. </p>

<p>This is not image but special characters added by shortcut on keyboard. Please Help. </p>

答:
You can use the character map to select and copy the symbol you want and add it to the Text field of the contextmenu's toolstripmenuitem

If you want symbols in place of the image, you should get an image made for that symbol :)

Body:
I have contextMenuStrip with 6 menu items. In the Margin displayed by default on left, I want to add special characters or Symbols as ↓  on the Margin.

This is not image but special characters added by shortcut on keyboard. Please Help.


问:
Programmatically opening Kube CSS Framework Message Alert
How do I open a message alert from javascript?

I have my div defined below:

HTML

```<code><div class="message success" id="cart-message-success"><p>Added to cart</p></div>
</code>```

Javascript:

```<code> $('#cart-message-success').message('open');
</code>```

And when I try to open it through javascript as below, I get the error message as illustrated below:

Error: No such method "open" for message

How do I make the call correctly?

答:
HTML

```<code><div class="message success" id="cart-message-success" style="display: none;">Added to cart</div>
</code>```

Javascript

```<code>$('#cart-message-success').fadeIn(200);
</code>```

Body:
How do I open a message alert from javascript?

I have my div defined below:

HTML

Added to cart

Javascript:

 $('#cart-message-success').message('open');

And when I try to open it through javascript as below, I get the error message as illustrated below:

Error: No such method "open" for message

How do I make the call correctly?

Body:
HTML

<div class="message success" id="cart-message-success" style="display: none;">Added to cart</div>

Javascript

$('#cart-message-success').fadeIn(200);


问:
Unable to find control
I want to find and click a button using Autoit. I tried AutoIt Window Information Tool but the button is not recognized so ControlClick() fails.

The button is active on the current window but Send("Enter") does not work. Tried using MouseClick() but the window does not appear in the same place every time, and I tried this script:

```<code>$hWnd = WinWait("vcredist_x86")
WinWaitActive("vcredist_x86")
ControlClick($hWnd, "", "[CLASS FROM AUTOITINFO]", "Left", 1)
</code>```

but neither of them works. Is there any other way to identify and click the button?

答:
If both version of AutoItWindowInfo(32 and 64bit) don't "see" the control you need to automate, here is what you can do:

Method 1 - Sending keystrokes:

Activate the window with WindowActivate

Send a number of TABs until the control is focused(if its not initially)

Send ENTER or SPACE

Method 2 - MouseClick:

Activate the window

Get the coordinates of a control relative to the application window(position the window at 0,0. Open Autoit Window Info, click on Mouse tab and get the position of the button). That position is usually always the same

When your code is running it must get the window position with WinGetPos and then add control position you got in step 2. That's your clicking position.

Method 3 - PixelSearch(If the control has unique color):

Get the desired color with AutoIt Window Info(mouse tab)

Search it using PixelSearch

Click the coords you got

Method 4 - ImageSearch:

Get ImageSearch UDF and DLL

Make a picture of the button

Search and click it

NOTE: Sometimes you need to give your script Admin rights in order to automate certain windows.

Title: Unable to find control

Body:
I want to find and click a button using Autoit. I tried AutoIt Window Information Tool but the button is not recognized so ControlClick() fails.

The button is active on the current window but Send("Enter") does not work. Tried using MouseClick() but the window does not appear in the same place every time, and I tried this script:

$hWnd = WinWait("vcredist_x86")
WinWaitActive("vcredist_x86")
ControlClick($hWnd, "", "[CLASS FROM AUTOITINFO]", "Left", 1)

but neither of them works. Is there any other way to identify and click the button?


问:
assembly: continuing after call
I'm looking at the following code:

```<code>cmp edx edx
jle loc_40234
call some_func
add eax, eax
</code>```

What I'm trying to understand is how can I even reach the fourth line since it's not a loc (can't be jumped to) and it immediately follows a function call. I mean, the call acts like a jump right?

Edit: ok I understand the basic idea. I should have specified: this code is part of some_func (it's a loop I gather).

答:
cmp edx,edx will compare edx with itself, so it will always be "equal", and jle is always taken.

The call will be not reached from this code path (if it will ever execute, some other code would have to jump directly at the call instruction or at the jle instruction with flags already set to evaluate as "greater" condition).

The call is technically like jmp, with small additional twist. It will push to stack address of next instruction (add), so if the code at some_func will somehow use this address from stack to jump there (most commonly functions end with ret instruction, which does exactly that, pops top of stack value and jumps to it, which is the return address, if the stack content was not damaged and stack pointer is correct), the add will be reached.

Of course it's impossible to say without checking some_func code, if it will return to that add.

Title: assembly: continuing after call

Body:
I'm looking at the following code:

cmp edx edx
jle loc_40234
call some_func
add eax, eax

What I'm trying to understand is how can I even reach the fourth line since it's not a loc (can't be jumped to) and it immediately follows a function call. I mean, the call acts like a jump right?

Edit: ok I understand the basic idea. I should have specified: this code is part of some_func (it's a loop I gather).


问:
Why enums require an explicit cast to int type?
There is no data loss by doing this, so what's the reason for having to explicitly cast enums to ints?

Would it not be more intuitive if it was implicit, say when you have a higher level method like:

```<code>PerformOperation ( OperationType.Silent type )
</code>```

where PerformOperation calls a wrapped C++ method that's exposed as such:

```<code>_unmanaged_perform_operation ( int operation_type )
</code>```

答:
That is the way C# works...

If Enum had inherited from int, then this should be possible. Enum doesn't inherit from int, and therefore, a cast is required.

The only way to implicit cast classes, is if they inherit.

Body:
There is no data loss by doing this, so what's the reason for having to explicitly cast enums to ints?

Would it not be more intuitive if it was implicit, say when you have a higher level method like:

PerformOperation ( OperationType.Silent type )

where PerformOperation calls a wrapped C++ method that's exposed as such:

_unmanaged_perform_operation ( int operation_type )


问:
svn: how to ignore folder except two files
How to ignore all subfolders of submissions except one_file?

```<code>submissions/
  vt1/
  vt2/
  vt3/
  one_file
</code>```

one_file is already in the repo, vt folders are not in the repo.

(I was trying all below when outside of the folder submissions)

I tried svn propedit svn:ignore . with the subsequent submissions/vt*.
 Then did commit, just in case. This still shows all those vt folders when I call svn status (with ? mark on them).

Then I tried the same propedit command but put there submissions. The same result. I also tried submissions/* and ./submissions/*.

Then I tried to add just one of those vt folders (thus not using pattern *). It still shows that subfolder! Things become interesting...

I exhausted all my "logical" ways. Do you know how to do this?

答:
From the book:

When found on a versioned directory, the svn:ignore property is
  expected to contain a list of newline-delimited file patterns that
  Subversion should use to determine ignorable objects in that same
  directory.

You need to set the svn:ignore property on the submissions folder to vt*

From the directory in the working copy which is enclosing the submissions folder, use:

```<code>svn propset svn:ignore "vt*" submissions/
</code>```

Or from the submissions folder itself, use:

```<code>svn propset svn:ignore "vt*" .
</code>```

Body:
How to ignore all subfolders of submissions except one_file?

submissions/
  vt1/
  vt2/
  vt3/
  one_file

one_file is already in the repo, vt folders are not in the repo.

(I was trying all below when outside of the folder submissions)

I tried svn propedit svn:ignore . with the subsequent submissions/vt*.
 Then did commit, just in case. This still shows all those vt folders when I call svn status (with ? mark on them).

Then I tried the same propedit command but put there submissions. The same result. I also tried submissions/* and ./submissions/*.

Then I tried to add just one of those vt folders (thus not using pattern *). It still shows that subfolder! Things become interesting...

I exhausted all my "logical" ways. Do you know how to do this?

Body:
From the book:

When found on a versioned directory, the svn:ignore property is
  expected to contain a list of newline-delimited file patterns that
  Subversion should use to determine ignorable objects in that same
  directory.

You need to set the svn:ignore property on the submissions folder to vt*

From the directory in the working copy which is enclosing the submissions folder, use:

svn propset svn:ignore "vt*" submissions/

Or from the submissions folder itself, use:

svn propset svn:ignore "vt*" .


问:
Null-safe network response using Gson and Kotlin
Assuming you have such data-class pojo, which represents typical gson-based representation of a response which comes from a server.

```<code>data class User(
        @field:SerializedName("id")
        val id: String,
        @field:SerializedName("name")
        val name: String,
        @field:SerializedName("user_phone")
        val phone: String?)
</code>```

id and name fields are required, phone field is optional

So the appropriate json this model expects, for example:

```<code>{
   "id": "someHash",
   "name": "John Snow"
}
</code>```

Sometimes server  can send json like:

```<code>{
   "id": "someHash"
}
</code>```

Unfortunately such json is parsed successfully without any error, because gson uses unsafe reflection and was written for java. So as a result there will be corrupted kotlin model with null stored in non-null field

I want to provide validation for this model on the json-deserialization layer, because it is better to receive an error right there, not in any other part of application, which expects non-null field.

And i'm looking for any consize solution for this problem.

Of course you can provide some explicit validation function for each model like

```<code>fun User.validate() {
    if (id == null) throw JsonParseException("'id' is null!")
    if (name == null) throw JsonParseException("'name' is null!")
}
</code>```

and call it by hand in any place but it produces a lot boilerplate code, which we always try to avoid. And also ide warns this as it thinks unnecessary null checking

答:
You can use custom JsonDeserializer that will validate fields annotated by something like @RequiredField and automatically throw exception if it is null.

How to do it you can find here: Gson optional and required fields

Body:
Assuming you have such data-class pojo, which represents typical gson-based representation of a response which comes from a server.

data class User(
        @field:SerializedName("id")
        val id: String,
        @field:SerializedName("name")
        val name: String,
        @field:SerializedName("user_phone")
        val phone: String?)

id and name fields are required, phone field is optional

So the appropriate json this model expects, for example:

{
   "id": "someHash",
   "name": "John Snow"
}

Sometimes server  can send json like:

{
   "id": "someHash"
}

Unfortunately such json is parsed successfully without any error, because gson uses unsafe reflection and was written for java. So as a result there will be corrupted kotlin model with null stored in non-null field

I want to provide validation for this model on the json-deserialization layer, because it is better to receive an error right there, not in any other part of application, which expects non-null field.

And i'm looking for any consize solution for this problem.

Of course you can provide some explicit validation function for each model like

fun User.validate() {
    if (id == null) throw JsonParseException("'id' is null!")
    if (name == null) throw JsonParseException("'name' is null!")
}

and call it by hand in any place but it produces a lot boilerplate code, which we always try to avoid. And also ide warns this as it thinks unnecessary null checking