问:
How to reset a filter list search box?
I created a search box to filter a list following this W3Schools guideline:

function myFunction() {
    var input, filter, ul, li, a, i, txtValue;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    ul = document.getElementById("myUL");
    li = ul.getElementsByTagName("li");
    for (i = 0; i
 -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}
#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}
#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}
#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}
#myUL li a:hover:not(.header) {
  background-color: #eee;
}</code>```

My Phonebook

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

Adele

Agnes

Billy

Bob

Calvin

Christina

Cindy

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

<p>I now need a button which would in one click:<br>- Reset the search box<br>- <strong>And</strong> display the full list again</p>

<p>I searched on stackoverflow and elsewhere on the internet but didn't find a solution.</p>

<p>As the code below shows, I added a reset button linked to a javascript function that was supposed to do the job. However the button only clears the search box, and although the search box appears as empty, I then need to click into the search box and push ‘delete’ once to restore the full list:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// CREATE A FILTER/SEARCH LIST
function myFunction() {
  // Declare variables
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById('myInput');
  filter = input.value.toUpperCase();
  ul = document.getElementById("myUL");
  li = ul.getElementsByTagName('li');

  // Loop through all list items, and hide those who don't match the search query
  for (i = 0; i < li.length; i++) {
    a = li[i].getElementsByTagName("a")[0];
    txtValue = a.textContent || a.innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

  // CLEAR SEARCH BOX
function clearInputFields(divElement) {
        var ele = document.getElementById(divElement);

        // IT WILL READ ALL THE ELEMENTS. <p>, <div>, <input> ETC.
        for (i = 0; i < ele.childNodes.length; i++) {

            // SINCE THE <input> FIELDS ARE INSIDE A <p> TAG,
            // I'LL USE THE "firstChild" PROPERTY TO GET THE <input> TAG.
            var child = ele.childNodes[i].firstChild;
            //console.log(child);

            // CHECK IF CHILD NOT NULL.
            // THIS IS IMPORTANT AS IT WILL RETURN A TEXT FOR EVERY "Whitespace".
            // 'Whitespace' IS A TEXT OR NODE BETWEEN <div> AND <p> AND AFTER <p>.
            if (child) {
                switch (child.type) {
                    case 'text':
                        child.value = '';
                }
            }
        }
    }</code>```

* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>My Phonebook</h2>

<div id="searchbox">
<p><input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
<p/>
</div>

<ul id="myUL">
  <li>Adele</li>
  <li>Agnes</li>
  <li>Billy</li>
  <li>Bob</li>
  <li>Calvin</li>
  <li>Christina</li>
  <li>Cindy</li>
</ul>

<div id="title">
RESET
</div></code>```

Can someone please tell me what is wrong with my code or suggest a better one?

答:
The function that updates the current filter to the list is myFunction. Simply call it manually at the end of your reset function (clearInputFields);

// CREATE A FILTER/SEARCH LIST
function myFunction() {
  // Declare variables
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById('myInput');
  filter = input.value.toUpperCase();
  ul = document.getElementById("myUL");
  li = ul.getElementsByTagName('li');

  // Loop through all list items, and hide those who don't match the search query
  for (i = 0; i
 -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

  // CLEAR SEARCH BOX
function clearInputFields(divElement) {
        var ele = document.getElementById(divElement);

        // IT WILL READ ALL THE ELEMENTS.
,
, <input> ETC.
        for (i = 0; i < ele.childNodes.length; i++) {

            // SINCE THE <input> FIELDS ARE INSIDE A
 TAG,
            // I'LL USE THE "firstChild" PROPERTY TO GET THE <input> TAG.
            var child = ele.childNodes[i].firstChild;
            //console.log(child);

            // CHECK IF CHILD NOT NULL.
            // THIS IS IMPORTANT AS IT WILL RETURN A TEXT FOR EVERY "Whitespace".
            // 'Whitespace' IS A TEXT OR NODE BETWEEN
 AND
 AND AFTER
.
            if (child) {
                switch (child.type) {
                    case 'text':
                        child.value = '';
                }
            }
        }
        myFunction();
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}</code>```

My Phonebook

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">

Adele

Agnes

Billy

Bob

Calvin

Christina

Cindy

RESET

```

Title: How to reset a filter list search box?

Body:
I created a search box to filter a list following this W3Schools guideline:

function myFunction() {
    var input, filter, ul, li, a, i, txtValue;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    ul = document.getElementById("myUL");
    li = ul.getElementsByTagName("li");
    for (i = 0; i
 -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}

* {
  box-sizing: border-box;
}
#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}
#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}
#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}
#myUL li a:hover:not(.header) {
  background-color: #eee;
}

My Phonebook

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

Adele

Agnes

Billy

Bob

Calvin

Christina

Cindy

I now need a button which would in one click:
- Reset the search box
- And display the full list again

I searched on stackoverflow and elsewhere on the internet but didn't find a solution.

As the code below shows, I added a reset button linked to a javascript function that was supposed to do the job. However the button only clears the search box, and although the search box appears as empty, I then need to click into the search box and push ‘delete’ once to restore the full list:

// CREATE A FILTER/SEARCH LIST
function myFunction() {
  // Declare variables
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById('myInput');
  filter = input.value.toUpperCase();
  ul = document.getElementById("myUL");
  li = ul.getElementsByTagName('li');

  // Loop through all list items, and hide those who don't match the search query
  for (i = 0; i
 -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

  // CLEAR SEARCH BOX
function clearInputFields(divElement) {
        var ele = document.getElementById(divElement);

        // IT WILL READ ALL THE ELEMENTS.
,
, <input> ETC.
        for (i = 0; i < ele.childNodes.length; i++) {

            // SINCE THE <input> FIELDS ARE INSIDE A
 TAG,
            // I'LL USE THE "firstChild" PROPERTY TO GET THE <input> TAG.
            var child = ele.childNodes[i].firstChild;
            //console.log(child);

            // CHECK IF CHILD NOT NULL.
            // THIS IS IMPORTANT AS IT WILL RETURN A TEXT FOR EVERY "Whitespace".
            // 'Whitespace' IS A TEXT OR NODE BETWEEN
 AND
 AND AFTER
.
            if (child) {
                switch (child.type) {
                    case 'text':
                        child.value = '';
                }
            }
        }
    }

* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}

My Phonebook

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">

Adele

Agnes

Billy

Bob

Calvin

Christina

Cindy

RESET

Can someone please tell me what is wrong with my code or suggest a better one?

Body:
The function that updates the current filter to the list is myFunction. Simply call it manually at the end of your reset function (clearInputFields);

// CREATE A FILTER/SEARCH LIST
function myFunction() {
  // Declare variables
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById('myInput');
  filter = input.value.toUpperCase();
  ul = document.getElementById("myUL");
  li = ul.getElementsByTagName('li');

  // Loop through all list items, and hide those who don't match the search query
  for (i = 0; i < li.length; i++) {
    a = li[i].getElementsByTagName("a")[0];
    txtValue = a.textContent || a.innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

  // CLEAR SEARCH BOX
function clearInputFields(divElement) {
        var ele = document.getElementById(divElement);

        // IT WILL READ ALL THE ELEMENTS. <p>, <div>, <input> ETC.
        for (i = 0; i < ele.childNodes.length; i++) {

            // SINCE THE <input> FIELDS ARE INSIDE A <p> TAG,
            // I'LL USE THE "firstChild" PROPERTY TO GET THE <input> TAG.
            var child = ele.childNodes[i].firstChild;
            //console.log(child);

            // CHECK IF CHILD NOT NULL.
            // THIS IS IMPORTANT AS IT WILL RETURN A TEXT FOR EVERY "Whitespace".
            // 'Whitespace' IS A TEXT OR NODE BETWEEN <div> AND <p> AND AFTER <p>.
            if (child) {
                switch (child.type) {
                    case 'text':
                        child.value = '';
                }
            }
        }
        myFunction();
    }

* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}

<h2>My Phonebook</h2>

<div id="searchbox">
<p><input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
<p/>
</div>

<ul id="myUL">
  <li><a href="#">Adele</a></li>
  <li><a href="#">Agnes</a></li>
  <li><a href="#">Billy</a></li>
  <li><a href="#">Bob</a></li>
  <li><a href="#">Calvin</a></li>
  <li><a href="#">Christina</a></li>
  <li><a href="#">Cindy</a></li>
</ul>

<div id="title">
<a href="#216" onclick="clearInputFields('searchbox');">RESET</a>
</div>


来源: stackexchange

问:
Finding the array with the lowest max value of element
I have an arraylist of int[] arrays and I'm trying to find the array with the lowest max element.

For an example, from arrays [1,2,5], [0,1,2], [8,0,0] it would be the array [0,1,2] because the max element is 2.

However, my code is not working correctly. Could you help me fix my code? Thanks!

```<code>int min = Integer.MAX_VALUE;
for (int i=0; i<list.size(); i++) {
    for (int j=0; j<list.get(i).length; j++) {
        if (list.get(i)[j]<min) {
            min = list.get(i)[i];
            minIndex = i; //index of the array in arraylist
        }
    }
}
</code>```

答:
As an alternative to the for-loop you might try to resolve this issue using stream api. The idea is exactly the same:

find maximum element in each sublist.

use Comparator to find sublist with minimum element among maximum elements.

```<code>List.of(List.of(1, 2, 5), List.of(0, 1, 2), List.of(8, 0, 0))
        .stream()
        .min((a, b) ->
               a.stream().max(Integer::compare).get()
                 .compareTo(
                    b.stream().max(Integer::compare).get()
                 )
        ).get();
</code>```

There is less code it is arguably easily to understand the intention of the code.
You can even make code shorter by using Comparator::comparing method:

```<code>List.of(List.of(1, 2, 5), List.of(0, 1, 2), List.of(8, 0, 0))
        .stream()
        .min(Comparator.comparing(Collections::max))
        .get();
</code>```

Let's have a look at what is going on here in more details.

```<code>List.of(List.of(1, 2, 5), List.of(0, 1, 2), List.of(8, 0, 0))
        // lets get stream of list Stream<List<Integer>>.
        .stream()
        // find sublist which has minimum maximum element.
        .min((a, b) ->
               // a & b are sublist, for example: [1,2,5], [0,1,2]
               // find maximum from a [1,2,5] which is [5]
               a.stream().max(Integer::compare).get()
               // compare maximum from a to maximum from b
                 .compareTo(
                 // find maximum from a [0,1,2] which is [2]
                    b.stream().max(Integer::compare).get()
                 )
               // get minimum out of [5,2]
        ).get(); // [0, 1, 2]
</code>```

So the execution might look similar to this:

```<code>Initial list is: [1,2,5], [0,1,2], [8, 0, 0]
find minimum list based on maximum:
min( max([1,2,5]), max([0,1,2]))
min( [5], [2])
[2] -> list [0,1,2] contains minimum maximum element so far, go the the next iteration
find minimum list based on maximum:
min( max([0,1,2]), max([8, 0, 0]) )
min( [2], [8])
[2] -> list [0,1,2] contains minimum maximum element so far,
there no other element in the stream, [0,1,2] is final result.
</code>```

I hope you find this useful.

ContentLicense: CC BY-SA 4.0

Body:
I have an arraylist of int[] arrays and I'm trying to find the array with the lowest max element.

For an example, from arrays [1,2,5], [0,1,2], [8,0,0] it would be the array [0,1,2] because the max element is 2.

However, my code is not working correctly. Could you help me fix my code? Thanks!

int min = Integer.MAX_VALUE;
for (int i=0; i<list.size(); i++) {
    for (int j=0; j<list.get(i).length; j++) {
        if (list.get(i)[j]<min) {
            min = list.get(i)[i];
            minIndex = i; //index of the array in arraylist
        }
    }
}

Body:
As an alternative to the for-loop you might try to resolve this issue using stream api. The idea is exactly the same:

find maximum element in each sublist.

use Comparator to find sublist with minimum element among maximum elements.

List.of(List.of(1, 2, 5), List.of(0, 1, 2), List.of(8, 0, 0))
        .stream()
        .min((a, b) ->
               a.stream().max(Integer::compare).get()
                 .compareTo(
                    b.stream().max(Integer::compare).get()
                 )
        ).get();

There is less code it is arguably easily to understand the intention of the code.
You can even make code shorter by using Comparator::comparing method:

List.of(List.of(1, 2, 5), List.of(0, 1, 2), List.of(8, 0, 0))
        .stream()
        .min(Comparator.comparing(Collections::max))
        .get();

Let's have a look at what is going on here in more details.

List.of(List.of(1, 2, 5), List.of(0, 1, 2), List.of(8, 0, 0))
        // lets get stream of list Stream<List<Integer>>.
        .stream()
        // find sublist which has minimum maximum element.
        .min((a, b) ->
               // a & b are sublist, for example: [1,2,5], [0,1,2]
               // find maximum from a [1,2,5] which is [5]
               a.stream().max(Integer::compare).get()
               // compare maximum from a to maximum from b
                 .compareTo(
                 // find maximum from a [0,1,2] which is [2]
                    b.stream().max(Integer::compare).get()
                 )
               // get minimum out of [5,2]
        ).get(); // [0, 1, 2]

So the execution might look similar to this:

Initial list is: [1,2,5], [0,1,2], [8, 0, 0]
find minimum list based on maximum:
min( max([1,2,5]), max([0,1,2]))
min( [5], [2])
[2] -> list [0,1,2] contains minimum maximum element so far, go the the next iteration
find minimum list based on maximum:
min( max([0,1,2]), max([8, 0, 0]) )
min( [2], [8])
[2] -> list [0,1,2] contains minimum maximum element so far,
there no other element in the stream, [0,1,2] is final result.

I hope you find this useful.


问:
Why does calling the C abort() function from an x86_64 assembly function lead to segmentation fault (SIGSEGV) instead of an abort signal?
Consider the program:

main.c

```<code>#include <stdlib.h>

void my_asm_func(void);
__asm__(
    ".global my_asm_func;"
    "my_asm_func:;"
    "call abort;"
    "ret;"
);

int main(int argc, char **argv) {
    if (argv[1][0] == '0') {
        abort();
    } else if (argv[1][0] == '1') {
        __asm__("call abort");
    } else {
        my_asm_func();
    }
}
</code>```

Which I compile as:

```<code>gcc -ggdb3 -O0 -o main.out main.c
</code>```

Then I have:

```<code>$ ./main.out 0; echo $?
Aborted (core dumped)
134
$ ./main.out 1; echo $?
Aborted (core dumped)
134
$ ./main.out 2; echo $?
Segmentation fault (core dumped)
139
</code>```

Why do I get the segmentation fault only for the last run, and not an abort signal as expected?

man 7 signal:

```<code>   SIGABRT       6       Core    Abort signal from abort(3)
   SIGSEGV      11       Core    Invalid memory reference
</code>```

confirms the signals due to the 128 + SIGNUM rule.

As a sanity check I also tried to make other function calls from assembly as in:

```<code>#include <stdlib.h>

void my_asm_func(void);
__asm__(
    ".global my_asm_func;"
    "my_asm_func:;"
    "lea puts_message(%rip), %rdi;"
    "call puts;"
    "ret;"
    "puts_message: .asciz \"hello puts\""
);

int main(void) {
    my_asm_func();
}
</code>```

and that did work and print:

```<code>hello puts
</code>```

Tested in Ubuntu 19.04 amd64, GCC 8.3.0, glibc 2.29.

I also tried it in an Ubunt Ubuntu 18.04 docker, and the results were the same, except that the program outputs when running:

```<code>./main.out: Symbol `abort' causes overflow in R_X86_64_PC32 relocation
./main.out: Symbol `abort' causes overflow in R_X86_64_PC32 relocation
</code>```

which feels like a good clue.

答:
In this code that defines a function at global scope (with basic assembly):

```<code>void my_asm_func(void);

__asm__(
    ".global my_asm_func;"
    "my_asm_func:;"
    "call abort;"
    "ret;"
);
</code>```

You violate one of the x86-64(AMD64) System V ABI rules that requires 16 byte stack alignment (may be higher depending on the parameters) at a point just before a CALL is made.

3.2.2 The Stack Frame

In addition to registers, each function has a frame on the run-time stack. This stack grows downwards from high
  addresses. Figure 3.3 shows the stack organization.

The end of the input argument area shall be aligned on a 16 (32, if __m256 is passed
  on stack) byte boundary. In other words, the value (%rsp + 8) is
  always a multiple of 16 (32) when control is transferred to the
  function entry point. The stack pointer, %rsp, always points to the
  end of the latest allocated stack frame.

Upon entry to a function the stack will be misaligned by 8 because the 8 byte return address is now on the stack. To align the stack back on a 16 byte boundary subtract 8 from RSP at the beginning of the function and add 8 back to RSP when finished. You can also just push any register like RBP at the beginning and pop it after to get the same effect.

This version of the code should work:

```<code>void my_asm_func(void);

__asm__(
    ".global my_asm_func;"
    "my_asm_func:;"
    "push %rbp;"
    "call abort;"
    "pop %rbp;"
    "ret;"
);
</code>```

Regarding this code that happened to work:

```<code>__asm__("call abort");
</code>```

The compiler likely generated the main function in such away that the stack was aligned on a 16 byte boundary prior to this call so it happened to work. You shouldn't rely on this behavior. There are other potential issues with this code, but don't present as a failure in this case. The stack should be properly aligned before the call; you should be concerned in general about the red zone; and you should specify all the volatile registers in the calling conventions as clobbers including RAX/RCX/RDX/R8/R9/R10/R11, the FPU registers, and the SIMD registers. In this case abort never returns so this isn't an issue related to your code.

The red-zone is defined in the ABI this way:

The 128-byte area beyond the location pointed to by %rsp is considered to
  be reserved and shall not be modified by signal or interrupt handlers.8 Therefore,
  functions may use this area for temporary data that is not needed across function
  calls. In particular, leaf functions may use this area for their entire stack frame,
  rather than adjusting the stack pointer in the prologue and epilogue. This area is
  known as the red zone.

It is generally a bad idea to call a function in inline assembly. An example of calling printf can be found in this other Stackoverflow answer which shows the complexities of doing a CALL especially in 64-bit code with red-zone. David Wohlferd's Dont Use Inline Asm is always a good read.

This code happened to work:

```<code>void my_asm_func(void);
__asm__(
    ".global my_asm_func;"
    "my_asm_func:;"
    "lea puts_message(%rip), %rdi;"
    "call puts;"
    "ret;"
    "puts_message: .asciz \"hello puts\""
);
</code>```

but you were probably lucky that puts didn't need proper alignment and you happened to get no failure. You should be aligning the stack before calling puts as described earlier with the my_asm_func that called abort. Ensuring compliance with the ABI is the key to ensuring code will work as expected.

Regarding the relocation errors, that is probably because the version of Ubuntu being used is using Position Independent Code (PIC) by default for GCC code generation. You could fix the issue by making the C library calls though the Procedure Linkage Table by appending @plt to the function names you CALL. Peter Cordes wrote a related Stackoverflow answer on this topic.

Body:
Consider the program:

main.c

#include <stdlib.h>

void my_asm_func(void);
__asm__(
    ".global my_asm_func;"
    "my_asm_func:;"
    "call abort;"
    "ret;"
);

int main(int argc, char **argv) {
    if (argv[1][0] == '0') {
        abort();
    } else if (argv[1][0] == '1') {
        __asm__("call abort");
    } else {
        my_asm_func();
    }
}

Which I compile as:

gcc -ggdb3 -O0 -o main.out main.c

Then I have:

$ ./main.out 0; echo $?
Aborted (core dumped)
134
$ ./main.out 1; echo $?
Aborted (core dumped)
134
$ ./main.out 2; echo $?
Segmentation fault (core dumped)
139

Why do I get the segmentation fault only for the last run, and not an abort signal as expected?

man 7 signal:

   SIGABRT       6       Core    Abort signal from abort(3)
   SIGSEGV      11       Core    Invalid memory reference

confirms the signals due to the 128 + SIGNUM rule.

As a sanity check I also tried to make other function calls from assembly as in:

#include <stdlib.h>

void my_asm_func(void);
__asm__(
    ".global my_asm_func;"
    "my_asm_func:;"
    "lea puts_message(%rip), %rdi;"
    "call puts;"
    "ret;"
    "puts_message: .asciz \"hello puts\""
);

int main(void) {
    my_asm_func();
}

and that did work and print:

hello puts

Tested in Ubuntu 19.04 amd64, GCC 8.3.0, glibc 2.29.

I also tried it in an Ubunt Ubuntu 18.04 docker, and the results were the same, except that the program outputs when running:

./main.out: Symbol `abort' causes overflow in R_X86_64_PC32 relocation
./main.out: Symbol `abort' causes overflow in R_X86_64_PC32 relocation

which feels like a good clue.

Body:
In this code that defines a function at global scope (with basic assembly):

void my_asm_func(void);

__asm__(
    ".global my_asm_func;"
    "my_asm_func:;"
    "call abort;"
    "ret;"
);

You violate one of the x86-64(AMD64) System V ABI rules that requires 16 byte stack alignment (may be higher depending on the parameters) at a point just before a CALL is made.

3.2.2 The Stack Frame

In addition to registers, each function has a frame on the run-time stack. This stack grows downwards from high
  addresses. Figure 3.3 shows the stack organization.

The end of the input argument area shall be aligned on a 16 (32, if __m256 is passed
  on stack) byte boundary. In other words, the value (%rsp + 8) is
  always a multiple of 16 (32) when control is transferred to the
  function entry point. The stack pointer, %rsp, always points to the
  end of the latest allocated stack frame.

Upon entry to a function the stack will be misaligned by 8 because the 8 byte return address is now on the stack. To align the stack back on a 16 byte boundary subtract 8 from RSP at the beginning of the function and add 8 back to RSP when finished. You can also just push any register like RBP at the beginning and pop it after to get the same effect.

This version of the code should work:

void my_asm_func(void);

__asm__(
    ".global my_asm_func;"
    "my_asm_func:;"
    "push %rbp;"
    "call abort;"
    "pop %rbp;"
    "ret;"
);

Regarding this code that happened to work:

__asm__("call abort");

The compiler likely generated the main function in such away that the stack was aligned on a 16 byte boundary prior to this call so it happened to work. You shouldn't rely on this behavior. There are other potential issues with this code, but don't present as a failure in this case. The stack should be properly aligned before the call; you should be concerned in general about the red zone; and you should specify all the volatile registers in the calling conventions as clobbers including RAX/RCX/RDX/R8/R9/R10/R11, the FPU registers, and the SIMD registers. In this case abort never returns so this isn't an issue related to your code.

The red-zone is defined in the ABI this way:

The 128-byte area beyond the location pointed to by %rsp is considered to
  be reserved and shall not be modified by signal or interrupt handlers.8 Therefore,
  functions may use this area for temporary data that is not needed across function
  calls. In particular, leaf functions may use this area for their entire stack frame,
  rather than adjusting the stack pointer in the prologue and epilogue. This area is
  known as the red zone.

It is generally a bad idea to call a function in inline assembly. An example of calling printf can be found in this other Stackoverflow answer which shows the complexities of doing a CALL especially in 64-bit code with red-zone. David Wohlferd's Dont Use Inline Asm is always a good read.

This code happened to work:

void my_asm_func(void);
__asm__(
    ".global my_asm_func;"
    "my_asm_func:;"
    "lea puts_message(%rip), %rdi;"
    "call puts;"
    "ret;"
    "puts_message: .asciz \"hello puts\""
);

but you were probably lucky that puts didn't need proper alignment and you happened to get no failure. You should be aligning the stack before calling puts as described earlier with the my_asm_func that called abort. Ensuring compliance with the ABI is the key to ensuring code will work as expected.

Regarding the relocation errors, that is probably because the version of Ubuntu being used is using Position Independent Code (PIC) by default for GCC code generation. You could fix the issue by making the C library calls though the Procedure Linkage Table by appending @plt to the function names you CALL. Peter Cordes wrote a related Stackoverflow answer on this topic.


问:
Visual Studio Code window has crashed
I'm getting the below error in visual studio code:

When I click on reopen this alert kept coming and not allowing me to write the code inside the editor. I have uninstall and reinstall visual studio code but still its showing this error.

答: Visual Studio Code states probable reason for that:

Title: Visual Studio Code window has crashed


问:
React native project change name for ios
I have renamed my project using the react-native-rename package.

It works fine on Android, however all the files in my ios folder still have refs to my old project name. How can I change them?

答:
Delete the IOS folder, then rebuild it again in with react-native.
I guess that's your easiest solution.</p>


问:
How is the conversion from one class to another possible?
I'm learning BST in data structures. I encountered some code in my textbook that I can't understand.

I've simplified it this way:

Tree should be the binary search Tree.

Node is a nested struct in Tree.

Element is used to store data in the Node.(All of them originally should be template class and
 node originally should also store key, etc. However in this case I omit these details.)

#include <iostream>

class Element {

};

class Tree {
   public:
    struct Node {
        Element *element;
    };

    Node *root;
    Element* find() {
        Node *tmp = root;
        return (Element *) tmp; // this line
    }
};

int main() {
    Tree t;
    std::cout << t.find() << '\n';
    return 0;
}
```

In line 16(as commented), what's the function of (Element *) ?
I suppose it's a conversion, but how is the conversion between two different classes possible? (if my assumption is right)

答:
In line 16(as commented), what's the function of (Element *) ?

I suppose it's a conversion

That's right. It's an explicit conversion; also called C-style cast.

but how is the conversion between two different classes possible?

Conversion between two classes is possible in two cases: One class has a converting constructor, or the other has a conversion operator.

Node and Element have neither converting constructors nor conversion operators, so they are not convertible to each other. However, the shown program doesn't convert between classes. It converts between pointers to classes.

C-style cast performs one or a combination of static cast, const cast and reinterpret cast depending on what the source and target types are. For pointers to unrelated classes, there is no valid static cast, so reinterpret cast is performed.

Reinterpreting a pointer to an unrelated type results in a pointer that has only limited uses. You can compare its equality to another pointer or convert it back to the correct type, but indirecting such reinterpreted pointer has undefined behaviour except in few cases. This is not one of the exceptional cases, so we can conclude that the "function" of the cast is to make the result mostly useless.

P.S. There is another problem. t.root was never initialised, so it has indeterminate value, and so Node *tmp = root reads an indeterminate value, and so the behaviour of the program is undefined.

Body:
I'm learning BST in data structures. I encountered some code in my textbook that I can't understand.

I've simplified it this way:

Tree should be the binary search Tree.

Node is a nested struct in Tree.

Element is used to store data in the Node.(All of them originally should be template class and
 node originally should also store key, etc. However in this case I omit these details.)

#include <iostream>

class Element {

};

class Tree {
   public:
    struct Node {
        Element *element;
    };

    Node *root;
    Element* find() {
        Node *tmp = root;
        return (Element *) tmp; // this line
    }
};

int main() {
    Tree t;
    std::cout << t.find() << '\n';
    return 0;
}

In line 16(as commented), what's the function of (Element *) ?
I suppose it's a conversion, but how is the conversion between two different classes possible? (if my assumption is right)


问:
Why textarea and input text with same font-size, line-height, padding and height are vertically aligned differently?

QUESTION 1:

Why do the following textarea and text input have different vertical text alignment if they both have the same font-size, line-height, height, padding ?

QUESTION 1.1

How can I make the textarea have the same vertical alignment as the input ?

.myTextarea {
  display: block;
  font-family: Arial;
  font-size: 14px;
  line-height: 21px;
  height: 32px;
  padding: 2px 5px;

  resize: none;
}

.myInput {
  display: block;
  font-family: Arial;
  font-size: 14px;
  line-height: 21px;
  height: 32px;
  padding: 2px 5px;
}

.myDiv {
  margin-top: 20px;
  margin-bottom: 5px;
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <div class="myDiv">Textarea</div>
  <textarea class="myTextarea" rows="1">12345</textarea>
  <div class="myDiv">Input</div>
  <input class="myInput" type="text" value="12345"/>
</div></code>```

答:
Textareas are for multiline texts while inputs are made for single line.

That's why line height won't have effect on input as it's considered to be equal to the input's height.

You can remove line height on your input since it has no effect on it.

Beside you should have the same line height as height for your textarea to reproduce the same effect than the input.

.myTextarea {
  display: block;
  font-family: Arial;
  font-size: 14px;
  line-height: 32px;
  height: 32px;
  padding: 2px 5px;

  resize: none;
}

.myInput {
  display: block;
  font-family: Arial;
  font-size: 14px;
  height: 32px;
  padding: 2px 5px;
}

.myDiv {
  margin-top: 20px;
  margin-bottom: 5px;
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <div class="myDiv">Textarea</div>
  <textarea class="myTextarea" rows="1">12345</textarea>
  <div class="myDiv">Input</div>
  <input class="myInput" type="text" value="12345"/>
</div></code>```

Body:
QUESTION 1:

Why do the following textarea and text input have different vertical text alignment if they both have the same font-size, line-height, height, padding ?

QUESTION 1.1

How can I make the textarea have the same vertical alignment as the input ?

.myTextarea {
  display: block;
  font-family: Arial;
  font-size: 14px;
  line-height: 21px;
  height: 32px;
  padding: 2px 5px;

  resize: none;
}

.myInput {
  display: block;
  font-family: Arial;
  font-size: 14px;
  line-height: 21px;
  height: 32px;
  padding: 2px 5px;
}

.myDiv {
  margin-top: 20px;
  margin-bottom: 5px;
  font-weight: bold;
}

Textarea

  <textarea class="myTextarea" rows="1">12345</textarea>

Input

  <input class="myInput" type="text" value="12345"/>

Body:
Textareas are for multiline texts while inputs are made for single line.

That's why line height won't have effect on input as it's considered to be equal to the input's height.

You can remove line height on your input since it has no effect on it.

Beside you should have the same line height as height for your textarea to reproduce the same effect than the input.

.myTextarea {
  display: block;
  font-family: Arial;
  font-size: 14px;
  line-height: 32px;
  height: 32px;
  padding: 2px 5px;

  resize: none;
}

.myInput {
  display: block;
  font-family: Arial;
  font-size: 14px;
  height: 32px;
  padding: 2px 5px;
}

.myDiv {
  margin-top: 20px;
  margin-bottom: 5px;
  font-weight: bold;
}

<div>
  <div class="myDiv">Textarea</div>
  <textarea class="myTextarea" rows="1">12345</textarea>
  <div class="myDiv">Input</div>
  <input class="myInput" type="text" value="12345"/>
</div>


问:
Bash function return seems not to work as it should
I have a the function is_mysql_db() to identify if the installed database in the server is a mysql server. So ideally the code in main body should call the function to determine whether I should consider this server a mysql server or not.

I tried at the end of the function to put double brackets, single "=", using or not variable for comparison. I am honestly out of ideas and I would like this code to look as clear as possible as this is only a small part of it.

Below my sample code:

```<code>#!/bin/bash

is_mysql_db(){
    yum_mysql_out=$(yum list installed | grep mysql-community | awk '{ print $1 }' | tail -n1)
    [ $yum_mysql_out == "mysql-community-server.x86_64" ]
}

if [ is_mysql_db ]
then
        echo "Installed"
else
        echo "Not Installed"
fi
</code>```

I would expect if the MySQL yum package is installed to detect it and return the package is installed and if its not to return Not Installed. Simple but not that much apparently.

答:
It's not the shell function that is wrong, it's your call to it.

Putting a string inside square brackets does not run that command, it just tests that the string itself is non-empty.

Don't put the function in the square brackets, and it will run it as a command.

Example:

```<code>$ if [ false ] ; then echo "false is true??"; else echo "false is false as expected" ; fi

false is true??

$ if false ; then echo "false is true??"; else echo "false is false as expected" ; fi

false is false as expected
</code>```

By the way, your function could be simpler:

```<code>is_mysql_db(){
    yum list installed | grep -q mysql-community-server
}
</code>```

Or even use rpm directly, so yum doesn't re-load its package indexes:

```<code>is_mysql_db(){
    rpm --quiet -q mysql-community-server
}
</code>```

Body:
I have a the function is_mysql_db() to identify if the installed database in the server is a mysql server. So ideally the code in main body should call the function to determine whether I should consider this server a mysql server or not.

I tried at the end of the function to put double brackets, single "=", using or not variable for comparison. I am honestly out of ideas and I would like this code to look as clear as possible as this is only a small part of it.

Below my sample code:

#!/bin/bash

is_mysql_db(){
    yum_mysql_out=$(yum list installed | grep mysql-community | awk '{ print $1 }' | tail -n1)
    [ $yum_mysql_out == "mysql-community-server.x86_64" ]
}

if [ is_mysql_db ]
then
        echo "Installed"
else
        echo "Not Installed"
fi

I would expect if the MySQL yum package is installed to detect it and return the package is installed and if its not to return Not Installed. Simple but not that much apparently.

Body:
It's not the shell function that is wrong, it's your call to it.

Putting a string inside square brackets does not run that command, it just tests that the string itself is non-empty.

Don't put the function in the square brackets, and it will run it as a command.

Example:

$ if [ false ] ; then echo "false is true??"; else echo "false is false as expected" ; fi

false is true??

$ if false ; then echo "false is true??"; else echo "false is false as expected" ; fi

false is false as expected

By the way, your function could be simpler:

is_mysql_db(){
    yum list installed | grep -q mysql-community-server
}

Or even use rpm directly, so yum doesn't re-load its package indexes:

is_mysql_db(){
    rpm --quiet -q mysql-community-server
}


问:
How to change the background-color of jumbrotron?
I want to know how to change the background-color of 'jumbotron' class, it has a default background-color #eee in bootstrap.css.

I tried to override by erasing this and giving the attribute none,none !important, transparent into my custom css and still doesn't work.

I tried inspecting the element in the browser window and removing the property there to see if there was any change, it's still the same problem.

It will adopt any other color, except removing the color entirely. The reason I'm asking this is because I have a full background image and want jumbotron to simply transparent with no background or color to it. Unless,

I'm missing something from the BootStrap 3.1.1 documentation in which I checked there as well.

NOTE: I would use jsfiddle.net to easily show you, but it doesn't support 3.1.1 and not sure how to implement bootstrap into it.

HTML

```<code><title>Full Page Image Background Template for Bootstrap 3</title>

<!-- Bootstrap core CSS -->
<link href="css/bootstrap.css" rel="stylesheet">

<!-- Custom CSS for the 'Full' Template -->
<link href="css/full.css" rel="stylesheet">
</code>```

```<code><!--Displays the Navigation Bar Style-->
<div class="navbar navbar-default navbar-fixed-top">
    <!--Displays the Navigation Bar Content-->
    <div class="navbar-header">
        <!-- displays the icon bar in responsive view; when clicked reveals a list-->
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse">
            <!-- displays the icon bars in responsive view;-->
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <!--Brand, Logo of your website-->
        <a class="navbar-brand" href="#">Virtual Productionz, Inc.</a>
    </div>

    <!-- Allows collapse/show navbar in responsive view-->
    <div class="navbar-collapse collapse navbar-responsive-collapse">
        <ul class="nav navbar-nav">
          <li class="active"><a href="#">Home</a></li>
          <li><a href="#">About Us</a></li>
          <!-- Dropdown menu-->
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Products <b class="caret"></b></a>
            <ul class="dropdown-menu">
              <li><a href="#">Integrated Laser Keyboard</a></li>
              <li><a href="#">More...</a></li>
            </ul>
          </li>
          <li><a href="#">Contact Us</a></li>
        </ul>
    </div>
</div>

<div class="jumbotron">
    <h1>Welcome!</h1>
    <p>We're an awesome company that creates virtual things for portable devices.</p>
    <p><a class="btn btn-primary btn-lg" role="button">Learn more</a></p>
</div>

<!-- JavaScript -->
<script src="js/jquery-1.10.2.js"></script>
<script src="js/bootstrap.js"></script>
</code>```

CSS (w/ bootstrap.css)

```<code>@import url("bootstrap.min.css");
@import url("bootstrap-theme.css");

body {
margin-top: 50px; /* 50px is the height of the navbar - change this if the navbarn height changes */
}

.full {
 /*background: url(http://placehold.it/1920x1080) no-repeat center center fixed;*/
 background: url("../images/laser_keyboard.jpg") no-repeat center center fixed;
 -webkit-background-size: cover;
 -moz-background-size: cover;
 -o-background-size: cover;
 background-size: cover;
}

.jumbotron{
color: #FFFFFF;
/*background-color:none !important;*/
}
</code>```

答:
just and another class to jumbotron

```<code>bg-transparent
</code>```

It will work perfectly

bootstrap color documentation: https://getbootstrap.com/docs/4.3/utilities/colors/

ContentLicense: CC BY-SA 3.0

Body:
I want to know how to change the background-color of 'jumbotron' class, it has a default background-color #eee in bootstrap.css.

I tried to override by erasing this and giving the attribute none,none !important, transparent into my custom css and still doesn't work.

I tried inspecting the element in the browser window and removing the property there to see if there was any change, it's still the same problem.

It will adopt any other color, except removing the color entirely. The reason I'm asking this is because I have a full background image and want jumbotron to simply transparent with no background or color to it. Unless,

I'm missing something from the BootStrap 3.1.1 documentation in which I checked there as well.

NOTE: I would use jsfiddle.net to easily show you, but it doesn't support 3.1.1 and not sure how to implement bootstrap into it.

HTML

<title>Full Page Image Background Template for Bootstrap 3</title>

<link href="css/bootstrap.css" rel="stylesheet">

<link href="css/full.css" rel="stylesheet">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse">

        </button>

        Virtual Productionz, Inc.

Home

About Us

            Products

Integrated Laser Keyboard

More...

Contact Us

Welcome!

We're an awesome company that creates virtual things for portable devices.

Learn more

CSS (w/ bootstrap.css)

@import url("bootstrap.min.css");
@import url("bootstrap-theme.css");

body {
margin-top: 50px; /* 50px is the height of the navbar - change this if the navbarn height changes */
}

.full {
 /*background: url(http://placehold.it/1920x1080) no-repeat center center fixed;*/
 background: url("../images/laser_keyboard.jpg") no-repeat center center fixed;
 -webkit-background-size: cover;
 -moz-background-size: cover;
 -o-background-size: cover;
 background-size: cover;
}

.jumbotron{
color: #FFFFFF;
/*background-color:none !important;*/
}

Body:
just and another class to jumbotron

bg-transparent

It will work perfectly

bootstrap color documentation: https://getbootstrap.com/docs/4.3/utilities/colors/


问:
Get trouble of updating tableview rows when deleting Firebase data
something goes wrong when trying to update rows of tableview after delete of Firebase data.

Below is method I use.

```<code>func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let delete = UITableViewRowAction(style: .destructive, title: "Delete") { (action, indexPath) in

        let cell = self.messages[indexPath.row]
        let b = cell.msgNo

        let action = MyGlobalVariables.refMessages.child(MyGlobalVariables.uidUser!)
        action.queryOrdered(byChild: "msgNo").queryEqual(toValue: b).observe(.childAdded, with: { snapshot in

            if snapshot.exists() { let a = snapshot.value as? [String: AnyObject]

                let autoId = a?["autoID"]

                action.child(autoId as! String).removeValue()

                self.messages.remove(at: indexPath.row)

                tableView.deleteRows(at: [indexPath], with: .automatic)
            } else {
                print("snapshot empty")
            }}) }
   ...
   return [delete, edit, preview]
}
</code>```

Initially I checked whole logic without including line /*action.child(autoId as! String).removeValue()*/ then it works normally and removes rows as should be. But once I add this line it removes data from Firebase but tableview is updated in strange way by adding new rows below existing

答:
My guess is that somewhere else in your application you have code like action .observe(.value, which shows the data in the table view. When you delete a node from the database, the code that populates the database gets triggered again, and it adds the same data (minus the node that you removed) to the table view again.

When working with Firebase it's best to follow the command query responsibility segregation principle, meaning that you keep the code that modifies the data completely separate from the flow that displays the data. That means that your code that deletes the data, should not try to update the table view. So something more like:

```<code>let action = MyGlobalVariables.refMessages.child(MyGlobalVariables.uidUser!)
action.queryOrdered(byChild: "msgNo").queryEqual(toValue: b).observe(.childAdded, with: { snapshot in
    if snapshot.exists() { let a = snapshot.value as? [String: AnyObject]
        let autoId = a?["autoID"]
        action.child(autoId as! String).removeValue()
    } else {
        print("snapshot empty")
    }}) }
</code>```

All the above does is remove the selected message from the database.

Now you can focus on your observer, and ensuring it only shows the messages once. There are two options for this:

Always clear self.messages when your .value completion handler gets called before you add the messages from the database. This is by far the simplest method, but may cause some flicker if you're showing a lot of data.

Listen to the more granular messages like .childAdded and .childRemoved and update self.messages based on those. This is more work in your code, but will result in a smoother UI when there are many messages.

Body:
something goes wrong when trying to update rows of tableview after delete of Firebase data.

Below is method I use.

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let delete = UITableViewRowAction(style: .destructive, title: "Delete") { (action, indexPath) in

        let cell = self.messages[indexPath.row]
        let b = cell.msgNo

        let action = MyGlobalVariables.refMessages.child(MyGlobalVariables.uidUser!)
        action.queryOrdered(byChild: "msgNo").queryEqual(toValue: b).observe(.childAdded, with: { snapshot in

            if snapshot.exists() { let a = snapshot.value as? [String: AnyObject]

                let autoId = a?["autoID"]

                action.child(autoId as! String).removeValue()

                self.messages.remove(at: indexPath.row)

                tableView.deleteRows(at: [indexPath], with: .automatic)
            } else {
                print("snapshot empty")
            }}) }
   ...
   return [delete, edit, preview]
}

Initially I checked whole logic without including line /*action.child(autoId as! String).removeValue()*/ then it works normally and removes rows as should be. But once I add this line it removes data from Firebase but tableview is updated in strange way by adding new rows below existing

Body:
My guess is that somewhere else in your application you have code like action .observe(.value, which shows the data in the table view. When you delete a node from the database, the code that populates the database gets triggered again, and it adds the same data (minus the node that you removed) to the table view again.

When working with Firebase it's best to follow the command query responsibility segregation principle, meaning that you keep the code that modifies the data completely separate from the flow that displays the data. That means that your code that deletes the data, should not try to update the table view. So something more like:

let action = MyGlobalVariables.refMessages.child(MyGlobalVariables.uidUser!)
action.queryOrdered(byChild: "msgNo").queryEqual(toValue: b).observe(.childAdded, with: { snapshot in
    if snapshot.exists() { let a = snapshot.value as? [String: AnyObject]
        let autoId = a?["autoID"]
        action.child(autoId as! String).removeValue()
    } else {
        print("snapshot empty")
    }}) }

All the above does is remove the selected message from the database.

Now you can focus on your observer, and ensuring it only shows the messages once. There are two options for this:

Always clear self.messages when your .value completion handler gets called before you add the messages from the database. This is by far the simplest method, but may cause some flicker if you're showing a lot of data.

Listen to the more granular messages like .childAdded and .childRemoved and update self.messages based on those. This is more work in your code, but will result in a smoother UI when there are many messages.


问:
How to setup a Cucumber feature that needs to be run before each other feature?
I'm currently writing some end-to-end tests using Cucumber and Selenium for an application that has a session based login/authentication.

Keeping the Cucumber approach, I am trying to keep each tested feature completely independent of one another. The problem is, because the application uses session based authentication, every time the WebDriver is closed (after each feature tested), the next feature tested will create a new WebDriver object, which will subsequently need to pass the login screen to execute the test.

What's the best approach here? I still want to test the login feature, but feel like I have a lot of duplication by running the login feature tests before any other feature test.

For example, say I have a Product List feature that I want to test if a list is displayed or not, based on what type of account the user is logged in with. My Given step for one of the the Product list feature scenarios might be 'Given I am logged in as a admin user', while the Given step for a different scenario might be 'Given I am logged in as a non-admin user'.

How might I direct these two Given steps to the appropriate login scenarios that have already been written?

答:
Cucumber Background feature may give you some additional thought to avoid duplication and could perform required action which would give you readiness needed before executing the actual scenario. We can pass user type : admin/non-admin steps in the background and using datatable, do the right things you need actually before scenario execution.

```<code>Feature: Product listing

  Background: User is Logged In
    Given I am logged in as a admin/non-admin user using below set of credentials
      | User_Type  | Email_ID   | Password  |
      | admin      | TestData1  | TestData1 |
      | non-admin  | TestData2  | TestData2 |

  @Sanity
  Scenario: Validation of product listing based on user-type
    Given User is already logged on to My Account Section
    When Clicking on Super & Sub Category shall take user to PLP Page
</code>```

Body:
Cucumber Background feature may give you some additional thought to avoid duplication and could perform required action which would give you readiness needed before executing the actual scenario. We can pass user type : admin/non-admin steps in the background and using datatable, do the right things you need actually before scenario execution.

Feature: Product listing

  Background: User is Logged In
    Given I am logged in as a admin/non-admin user using below set of credentials
      | User_Type  | Email_ID   | Password  |
      | admin      | TestData1  | TestData1 |
      | non-admin  | TestData2  | TestData2 |

  @Sanity
  Scenario: Validation of product listing based on user-type
    Given User is already logged on to My Account Section
    When Clicking on Super & Sub Category shall take user to PLP Page


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

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

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

INPUT:

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

OUTPUT:

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

答:
You probably want to store the first and second line into 2 variables (prev, cur) outside of the for loop first before checking whether the first start with "This" and the second start with "That"

Edit:  I have edited my answer so that it can be used on files with multiple lines. In the case of multiple lines, you probably want to store the file lines into a list of string lines instead of using 1 or 2 variables. After storing the file content into a list, you can iterate through the file lines using a while loop. I use while loop instead of for since it gives you more freedom when navigating the array index.

```<code>lines = []
with open("myfile.txt", 'r') as f:
    for line in f:
        lines.append(line.replace('\n', '').replace('\r', ''))

with open("myfile.txt", 'w') as f:
    length = len(lines)
    i = 0
    while i < length - 1:
        if lines[i].startswith('This') and lines[i + 1].startswith('That'):
            f.write(lines[i] + ' ' + lines[i + 1] + '\n')
            i += 1 # skip the next line because it is concated with the current line
        else:
            f.write(lines[i] + '\n')
        i += 1

    # when the last line doesn't concat with its previous line
    if i < length:
        f.write(lines[i] + '\n')
</code>```

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

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

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

INPUT:

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

OUTPUT:

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

Body:
You probably want to store the first and second line into 2 variables (prev, cur) outside of the for loop first before checking whether the first start with "This" and the second start with "That"

Edit:  I have edited my answer so that it can be used on files with multiple lines. In the case of multiple lines, you probably want to store the file lines into a list of string lines instead of using 1 or 2 variables. After storing the file content into a list, you can iterate through the file lines using a while loop. I use while loop instead of for since it gives you more freedom when navigating the array index.

lines = []
with open("myfile.txt", 'r') as f:
    for line in f:
        lines.append(line.replace('\n', '').replace('\r', ''))

with open("myfile.txt", 'w') as f:
    length = len(lines)
    i = 0
    while i < length - 1:
        if lines[i].startswith('This') and lines[i + 1].startswith('That'):
            f.write(lines[i] + ' ' + lines[i + 1] + '\n')
            i += 1 # skip the next line because it is concated with the current line
        else:
            f.write(lines[i] + '\n')
        i += 1

    # when the last line doesn't concat with its previous line
    if i < length:
        f.write(lines[i] + '\n')


问:
How many wiki instances to install?
I've been asked to install Mediawiki to house documentation for a company intranet. Furthermore, I've been asked to install several instances - one per contributing group: non-technical users get one, developers one, management one, etc. The idea is to provide separate web spaces for each group. Is there a way to achieve separation within one instance?

答:
While calling out your supervisor may be enjoyable...  I would have to think that it would be easiest to deploy a single Wiki like you've suggested with different categories or departments inside of the Wiki.

Also, given the current economic conditions, there may be some added job security in managing 5 or 6 Wiki implementations...

ContentLicense: CC BY-SA 2.5

Title: How many wiki instances to install?

LastEditorDisplayName: nzpcmad

OwnerDisplayName: Russell Solberg


问:
Understanding Spring context initialization order
I have a complex set of beans and dependencies between them. All beans are @Service, @Repository or @Controller annotated and I use the @PostConstruct annotation. There are some circular dependencies but still the system was correctly initialized by Spring.

Then I added a simple Controller with just a dependency to one of the Services. Theoretically, the system should be able to boot because theoretically it could first set up the system as before and then the new Controller. But Spring complains that it cannot set up the context:

Error creating bean with name 'userService': Requested bean is currently in creation: Is there an unresolvable circular reference?

Can I somehow assists Spring in how to order the context initialization? I think the main issue is the userService which is used a lot through the system for authentication purposes.

答:
Best solution would simply be to take out the circular dependency; I have not yet encountered a scenario where such a structure was warranted. But if you do want to stick with it then perhaps your above problem is due to the fact that you have constructor injection somewhere:

Circular dependencies
  If you are using predominantly constructor injection it is possible to write and configure your classes and beans such that an unresolvable circular dependency scenario is created.
  Consider the scenario where you have class A, which requires an instance of class B to be provided via constructor injection, and class B, which requires an instance of class A to be provided via constructor injection. If you configure beans for classes A and B to be injected into each other, the Spring IoC container will detect this circular reference at runtime, and throw a BeanCurrentlyInCreationException.

One possible solution to this issue is
  to edit the source code of some of
  your classes to be configured via
  setters instead of via constructors.
  Another solution is not to use
  constructor injection and stick to
  setter injection only. In other words,
  while it should generally be avoided in all but the rarest of
  circumstances, it is possible to
  configure circular dependencies with
  setter injection. Unlike the typical
  case (with no circular dependencies),
  a circular dependency between bean A
  and bean B will force one of the beans
  to be injected into the other prior to
  being fully initialized itself (a
  classic chicken/egg scenario).


问:
Is it possible to recording Agora SDK Video Call?
I am developing an application with Video call. Which SDK will support all of the features like video calling and recording(Which should store into our server) for Android, IOS and Web</p>

答:
Yes, it's possible to record the Agora Video session. Agora provides implementations to set up on-premise recording (https://docs.agora.io/en/Recording/product_recording?platform=All%20Platforms) and cloud-based recording for this purpose. It uses the Agora Recording SDK and also provides a Rest API interface to get everything set up out the box. Here is the link to the repo: https://github.com/AgoraIO/Basic-Recording

The video recording service joins the channel in which the session is going on. You have to provide the AppID and channelName and start the recorder. The video and audio files are generated separately and you need to combine them with a script provided.


问:
How to use to_date for date like '1970-01-01 00:00:01.0'
I want to convert text '1970-01-01 00:00:01.0' into date by using to_date but I am not getting which format shoud I use.

If you check some examples like :
to_date('1970-01-01 00:00:01','yyyy-mm-dd HH24:MI:SS')
which works fine but in my case I am unable to find such a format.

Could you please help which date format should I use?

答:
You can't use to_date() with your string as it is, because the .0 part represents milliseconds - and Oracle's date data type does not have millisecond precision:

```<code>select to_date('1970-01-01 00:00:01.0','YYYY-MM-DD HH24:MI:SS') from dual;

ORA-01830: date format picture ends before converting entire input string

select to_date('1970-01-01 00:00:01.0','YYYY-MM-DD HH24:MI:SS.FF') from dual;

ORA-01821: date format not recognized
</code>```

That error is because the FF part of the model doesn't apply for dates.

You can convert to a timestamp:

```<code>select to_timestamp('1970-01-01 00:00:01.0','YYYY-MM-DD HH24:MI:SS.FF') from dual;

TO_TIMESTAMP('1970-01-0
-----------------------
1970-01-01 00:00:01.000
</code>```

and then if you really do only want it as a date, cast that to be a date:

```<code>select cast(to_timestamp('1970-01-01 00:00:01.0','YYYY-MM-DD HH24:MI:SS.FF') as date) from dual;

CAST(TO_TIMESTAMP('
-------------------
1970-01-01 00:00:01
</code>```

Or you could use string manipulation to remove the fractional seconds part before using to_date(), or if it it always going to be .0 - with no variation - you could treat that as a constant part of the format model [as @mathguy has already shown].

Also notice that the value you have could be treated as a timestamp literal, but only if the whole thing is a fixed value:

```<code>select timestamp '1970-01-01 00:00:01.0' from dual;

TIMESTAMP'1970-01-0100:
-----------------------
1970-01-01 00:00:01.000
</code>```

and again you could cast that to a date if needed.

Body:
You can't use to_date() with your string as it is, because the .0 part represents milliseconds - and Oracle's date data type does not have millisecond precision:

select to_date('1970-01-01 00:00:01.0','YYYY-MM-DD HH24:MI:SS') from dual;

ORA-01830: date format picture ends before converting entire input string

select to_date('1970-01-01 00:00:01.0','YYYY-MM-DD HH24:MI:SS.FF') from dual;

ORA-01821: date format not recognized

That error is because the FF part of the model doesn't apply for dates.

You can convert to a timestamp:

select to_timestamp('1970-01-01 00:00:01.0','YYYY-MM-DD HH24:MI:SS.FF') from dual;

TO_TIMESTAMP('1970-01-0
-----------------------
1970-01-01 00:00:01.000

and then if you really do only want it as a date, cast that to be a date:

select cast(to_timestamp('1970-01-01 00:00:01.0','YYYY-MM-DD HH24:MI:SS.FF') as date) from dual;

CAST(TO_TIMESTAMP('
-------------------
1970-01-01 00:00:01

Or you could use string manipulation to remove the fractional seconds part before using to_date(), or if it it always going to be .0 - with no variation - you could treat that as a constant part of the format model [as @mathguy has already shown].

Also notice that the value you have could be treated as a timestamp literal, but only if the whole thing is a fixed value:

select timestamp '1970-01-01 00:00:01.0' from dual;

TIMESTAMP'1970-01-0100:
-----------------------
1970-01-01 00:00:01.000

and again you could cast that to a date if needed.


问:
Arithmatic overflow error converting varchar to data type numeric (SQL)
I have an MS SQL 2017 database setup and I am sending RFID tags to a table and then querying the table later to see if a user exists on the system.

I am getting error:

'Arithmatic overflow error converting varchar to data type numeric'.

I have tried to change the 'rfid_id' type to VARCHAR(MAX) but no success.

My table:

```<code>CREATE TABLE worker_table ('worker_id INT IDENTITY(1,1) PRIMARY KEY,
rfid_id VARCHAR(30) NOT NULL,
worker_customer_name VARCHAR(30) NOT NULL,
site_id INTEGER NOT NULL REFERENCES site_table(site_id))
</code>```

This works fine.

Data that I insert into the table for a given RFID:

```<code>INSERT INTO worker_table(rfid_id, worker_customer_name, site_id, worker_id
VALUES ($'10103967375$', $'USER_1$', $'1$', $'1'))
</code>```

This also works fine for most RFID tags.

However, some tags are different length e.g 330004531017 or 9600007487626. Some tags write in OK to the data base but some return the error.

Also if I query the data base with:

```<code>SELECT CASE WHEN EXISTS(SELECT * FROM worker_table WHERE rfid_id =9600007487626) THEN 100 ELSE 200 END)
</code>```

This works fine for most tags but returns the same error for some.

PS I am currently sending rfid_id as a string from my PLC.

My knowledge is limited in SQL so any help would be greatly appreciated, please and thank you.

答:
In SQL Server , default maximum precision of numeric datatype is  38 and  in earlier version

which was supported only  upto characters

Due the reason while you convert varchar to numeric overflow occurred

Body:
I have an MS SQL 2017 database setup and I am sending RFID tags to a table and then querying the table later to see if a user exists on the system.

I am getting error:

'Arithmatic overflow error converting varchar to data type numeric'.

I have tried to change the 'rfid_id' type to VARCHAR(MAX) but no success.

My table:

CREATE TABLE worker_table ('worker_id INT IDENTITY(1,1) PRIMARY KEY,
rfid_id VARCHAR(30) NOT NULL,
worker_customer_name VARCHAR(30) NOT NULL,
site_id INTEGER NOT NULL REFERENCES site_table(site_id))

This works fine.

Data that I insert into the table for a given RFID:

INSERT INTO worker_table(rfid_id, worker_customer_name, site_id, worker_id
VALUES ($'10103967375$', $'USER_1$', $'1$', $'1'))

This also works fine for most RFID tags.

However, some tags are different length e.g 330004531017 or 9600007487626. Some tags write in OK to the data base but some return the error.

Also if I query the data base with:

SELECT CASE WHEN EXISTS(SELECT * FROM worker_table WHERE rfid_id =9600007487626) THEN 100 ELSE 200 END)

This works fine for most tags but returns the same error for some.

PS I am currently sending rfid_id as a string from my PLC.

My knowledge is limited in SQL so any help would be greatly appreciated, please and thank you.


问:
Ensuring template argument type matches that of its variadic constructor
I would like to have a class like this:

```<code>template<typename T>
struct Foo {
    T* data_;

    template<typename... Ts, std::enable_if<std::is_same<T,Ts>...>...>
    explicit Foo(Ts...ts) : data_{ ts... } {}
};
</code>```

However; something with the syntax is wrong, and I'm not sure if you can set parameters into a pointer directly like this upon initialization.

What I would like for this to do is simply this:

```<code>Foo<int> f1{ 1, 3, 5, 7 }; // Or
// Foo<int> f1( 1, 3, 5 7 );
// f1.data_[0] = 1
// f1.data_[1] = 3
// f1.data_[2] = 5
// f1.data_[3] = 7
// f1.data_[4] = ... not our memory either garbage or undefined...

Foo<float> f2{ 3.5f, 7.2f, 9.8f }; // Or
// Foo<float> f2( 3.5f, 7.2f, 9.8f );
// f2.data_[0] = 3.5
// f2.data_[1] = 7.2
// f2.data_[2] = 9.8
// f2.data_[3] = ... not our memory
</code>```

I would also like to have the constructor check to make sure that each and every parameter that is passed into the constructor is of type <T>; simply put for each Ts it must be a T.

I might be overthinking this but for the life of me I can not get this or something similar to compile. I don't know if it's within enable_if, is_same or through the class's initializer list and trying to store the contents into a pointer. I don't know if I should use an array of T instead but the array's size won't be known until the arguments are passed into the constructor. I'm also trying to do this without using a basic container such as std::vector; it's more for self education than practical source code. I just want to see how this could be done with raw pointers.

Edit

I've changed my class to something like this:

```<code>template<typename T>
struct Foo {
    T* data_;

    template<typename... Ts, std::enable_if_t<std::is_same<T, Ts...>::value>* = nullptr>
    explicit Foo( const Ts&&... ts ) : data_{ std::move(ts)... } {}
 };
</code>```

And when trying to use it:

```<code> int a = 1, b = 3, c = 5, d = 7;
 Foo<int> f1( a, b, c, d );
 Foo<int> f2{ a, b, c, d };
</code>```

I'm a little closer with this iteration; but they both give different compiler errors.

The first being: C2661: "No overloaded function takes 4 arguments"

And the second:  C2440: "initializing, cannot convert from initializer list to Container, no constructor could take the source type, or constructor overload resolution was ambiguous."

答:
The most idiomatic way to do this in C++17 is using std::cunjunction_v. It lazily evaluates subsequent values and allows you to avoid fold expressions. Also  messages generated by the compiler are the same for both of casese you mentioned in edited piece of code.

Also, passing data by const-rvalue-ref makes no sense, since it is impossible to move data from const objects. Additionaly you were moving pack of arguments to a pointer. I didn't know what to do about it so just removed it.

Additionaly, take a look at the std::decay_t - without it it would not work, as sometimes Ts is deduced not as int but as const int & or int &. This leads to std::is_same_v being false.

The code below compiles fine at godbolt:

```<code>template<typename T>
struct Foo {
    T* data_;

    template<
        typename... Ts,
        std::enable_if_t<
            std::conjunction_v<
                std::is_same<T, std::decay_t<Ts>>...
            >
        > * = nullptr
    >
    explicit Foo( Ts&&... ts ) : data_{ } {}
 };
</code>```

Body:
I would like to have a class like this:

template<typename T>
struct Foo {
    T* data_;

    template<typename... Ts, std::enable_if<std::is_same<T,Ts>...>...>
    explicit Foo(Ts...ts) : data_{ ts... } {}
};

However; something with the syntax is wrong, and I'm not sure if you can set parameters into a pointer directly like this upon initialization.

What I would like for this to do is simply this:

Foo<int> f1{ 1, 3, 5, 7 }; // Or
// Foo<int> f1( 1, 3, 5 7 );
// f1.data_[0] = 1
// f1.data_[1] = 3
// f1.data_[2] = 5
// f1.data_[3] = 7
// f1.data_[4] = ... not our memory either garbage or undefined...

Foo<float> f2{ 3.5f, 7.2f, 9.8f }; // Or
// Foo<float> f2( 3.5f, 7.2f, 9.8f );
// f2.data_[0] = 3.5
// f2.data_[1] = 7.2
// f2.data_[2] = 9.8
// f2.data_[3] = ... not our memory

I would also like to have the constructor check to make sure that each and every parameter that is passed into the constructor is of type <T>; simply put for each Ts it must be a T.

I might be overthinking this but for the life of me I can not get this or something similar to compile. I don't know if it's within enable_if, is_same or through the class's initializer list and trying to store the contents into a pointer. I don't know if I should use an array of T instead but the array's size won't be known until the arguments are passed into the constructor. I'm also trying to do this without using a basic container such as std::vector; it's more for self education than practical source code. I just want to see how this could be done with raw pointers.

Edit

I've changed my class to something like this:

template<typename T>
struct Foo {
    T* data_;

    template<typename... Ts, std::enable_if_t<std::is_same<T, Ts...>::value>* = nullptr>
    explicit Foo( const Ts&&... ts ) : data_{ std::move(ts)... } {}
 };

And when trying to use it:

 int a = 1, b = 3, c = 5, d = 7;
 Foo<int> f1( a, b, c, d );
 Foo<int> f2{ a, b, c, d };

I'm a little closer with this iteration; but they both give different compiler errors.

The first being: C2661: "No overloaded function takes 4 arguments"

And the second:  C2440: "initializing, cannot convert from initializer list to Container, no constructor could take the source type, or constructor overload resolution was ambiguous."

Body:
The most idiomatic way to do this in C++17 is using std::cunjunction_v. It lazily evaluates subsequent values and allows you to avoid fold expressions. Also  messages generated by the compiler are the same for both of casese you mentioned in edited piece of code.

Also, passing data by const-rvalue-ref makes no sense, since it is impossible to move data from const objects. Additionaly you were moving pack of arguments to a pointer. I didn't know what to do about it so just removed it.

Additionaly, take a look at the std::decay_t - without it it would not work, as sometimes Ts is deduced not as int but as const int & or int &. This leads to std::is_same_v being false.

The code below compiles fine at godbolt:

template<typename T>
struct Foo {
    T* data_;

    template<
        typename... Ts,
        std::enable_if_t<
            std::conjunction_v<
                std::is_same<T, std::decay_t<Ts>>...
            >
        > * = nullptr
    >
    explicit Foo( Ts&&... ts ) : data_{ } {}
 };


问:
Memory leak when dynamically refreshing an image using javascript
I'm trying to get rid of a nasty memory leak in my browser.

This is what I am trying to do:

- I am periodically trying to refresh an image in an HTML page using javascript.

- All code should be compatible with internet explorer 6 or higher and firefox.

You can find my code below.

This is what I observed:
Every time I poll for a new image it seems that the browser keeps the previous image in its cache. Hence, the memory usage of chrome9/Internet Explorer 6&8/ Safari 5 keeps growing linear in time. Only firefox (3.6) seems to behave normal when I add no-cache headers to the image. I've set the refresh rate quite high (10ms) in order to quickly see the memory grow.

What I already tried:

-Adding headers to the image that disables the caching: only works for firefox

This is the response header:

    HTTP/1.1 200 OK
    Date: Mon, 14 Feb 2011 11:17:02 GMT
    Server: Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny9 with Suhosin-Patch mod_python/3.3.1 Python/2.5.2
    X-Powered-By: PHP/5.2.6-1+lenny9
    Pragma: no-cache
    Cache-control: no-cache, no-store, must-revalidate, max-age=1, max-stale=0, post-check=0, pre-check=0, max-age=0
    Expires: Mon, 14 Feb 2011 11:17:02 GMT
    Content-Length: 358
    Keep-Alive: timeout=15, max=100
    Connection: Keep-Alive
    Content-Type: image/png

-Requesting the image in base64 string format through a POST method (POST requests are by default not cached): makes no difference

-Trying various things like settings variables to null and calling clearInterval or comparable methods.

-Changing/not changing the image name every time I do a request.

-Loading the code below in an iFrame and refreshing the iFrame every 5 seconds seems to clean up the memory in all browsers except for IE6, so this isn't a solution.

-Lots of other things that didn't seem to work.

I hope any of you smart fellas may be able to help me. I'm getting quite desperate =)

```<code><html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate, max-age=-1, max-stale=0, post-check=0, pre-check=0">
    <meta http-equiv="expires" content="-1">
    <style type="text/css">
        body {
            padding: 0px;
            margin: 0px;
            background-color: #B0B9C0;
        }

        img {
            width: 167px;
            height: 125px;
            background-color: #B0B9C0;
            border: none;
        }
    </style>
    <script type="text/javascript">
        var previewUrl     = "http://nick-desktop/image/";
        var previewImage   = document.createElement("img");
        var previewTimeout = 10;
        var previewWidth   = 200;
        var previewHeight  = 80;
        var timerID = 0;

        function initialize() {
            if(previewTimeout==null || previewUrl == null || previewWidth==null || previewHeight==null) return;
            document.body.appendChild(previewImage);
            previewImage.src = previewUrl;
            previewImage.style.width = previewWidth+"px";
            previewImage.style.height = previewHeight+"px";
            timerID = setInterval(doPoll, previewTimeout);
        }

        function doPoll() {
            previewImage.src = previewUrl + new Date().getTime()+".png";
        }
    </script>
</head>
<body onload="initialize()">
</body>
</code>```

答:
Try this:</p>

```<code><html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate, max-age=-1, max-stale=0, post-check=0, pre-check=0">
    <meta http-equiv="expires" content="-1">
    <style type="text/css">
        body {
            padding: 0px;
            margin: 0px;
            background-color: #B0B9C0;
        }

        img {
            width: 167px;
            height: 125px;
            background-color: #B0B9C0;
            border: none;
        }
    </style>
    <script type="text/javascript">
        var previewUrl     = "http://nick-desktop/image/";
        var previewTimeout = 10;
        var previewWidth   = 200;
        var previewHeight  = 80;
        var timeout;

        window.onload = function() {
            if(previewTimeout==null || previewUrl == null || previewWidth==null || previewHeight==null) return;
            doPoll();
        }

        function doPoll() {
            clearTimeout(timeout);
            document.body.innerHTML = "";
            var previewImage = null;

            previewImage = document.createElement("img");
            previewImage.style.width = previewWidth+"px";
            previewImage.style.height = previewHeight+"px";
            previewImage.onload = function() { timeout = setTimeout(doPoll, previewTimeout); };
            document.body.appendChild(previewImage);

            previewImage.src = previewUrl + "image.png?datetime=" + new Date().getTime();
        }
    </script>
</head>
<body>
</body>
</html>
</code>```

Body:
I'm trying to get rid of a nasty memory leak in my browser.

This is what I am trying to do:

- I am periodically trying to refresh an image in an HTML page using javascript.

- All code should be compatible with internet explorer 6 or higher and firefox.

You can find my code below.

This is what I observed:
Every time I poll for a new image it seems that the browser keeps the previous image in its cache. Hence, the memory usage of chrome9/Internet Explorer 6&8/ Safari 5 keeps growing linear in time. Only firefox (3.6) seems to behave normal when I add no-cache headers to the image. I've set the refresh rate quite high (10ms) in order to quickly see the memory grow.

What I already tried:

-Adding headers to the image that disables the caching: only works for firefox

This is the response header:

    HTTP/1.1 200 OK
    Date: Mon, 14 Feb 2011 11:17:02 GMT
    Server: Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny9 with Suhosin-Patch mod_python/3.3.1 Python/2.5.2
    X-Powered-By: PHP/5.2.6-1+lenny9
    Pragma: no-cache
    Cache-control: no-cache, no-store, must-revalidate, max-age=1, max-stale=0, post-check=0, pre-check=0, max-age=0
    Expires: Mon, 14 Feb 2011 11:17:02 GMT
    Content-Length: 358
    Keep-Alive: timeout=15, max=100
    Connection: Keep-Alive
    Content-Type: image/png

-Requesting the image in base64 string format through a POST method (POST requests are by default not cached): makes no difference

-Trying various things like settings variables to null and calling clearInterval or comparable methods.

-Changing/not changing the image name every time I do a request.

-Loading the code below in an iFrame and refreshing the iFrame every 5 seconds seems to clean up the memory in all browsers except for IE6, so this isn't a solution.

-Lots of other things that didn't seem to work.

I hope any of you smart fellas may be able to help me. I'm getting quite desperate =)

<meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate, max-age=-1, max-stale=0, post-check=0, pre-check=0">
    <meta http-equiv="expires" content="-1">

Body:
Try this:

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate, max-age=-1, max-stale=0, post-check=0, pre-check=0">
    <meta http-equiv="expires" content="-1">
    <style type="text/css">
        body {
            padding: 0px;
            margin: 0px;
            background-color: #B0B9C0;
        }

        img {
            width: 167px;
            height: 125px;
            background-color: #B0B9C0;
            border: none;
        }
    </style>
    <script type="text/javascript">
        var previewUrl     = "http://nick-desktop/image/";
        var previewTimeout = 10;
        var previewWidth   = 200;
        var previewHeight  = 80;
        var timeout;

        window.onload = function() {
            if(previewTimeout==null || previewUrl == null || previewWidth==null || previewHeight==null) return;
            doPoll();
        }

        function doPoll() {
            clearTimeout(timeout);
            document.body.innerHTML = "";
            var previewImage = null;

            previewImage = document.createElement("img");
            previewImage.style.width = previewWidth+"px";
            previewImage.style.height = previewHeight+"px";
            previewImage.onload = function() { timeout = setTimeout(doPoll, previewTimeout); };
            document.body.appendChild(previewImage);

            previewImage.src = previewUrl + "image.png?datetime=" + new Date().getTime();
        }
    </script>
</head>
<body>
</body>
</html>


问:
Finding a certain header and copying a certain amount of entries below it
I'm trying to search for a certain header (Header 1 in this example) and copy a certain amount of cells below this header to a range. The text of the header itself isn't supposed to get copied but everything below it.

The following code works, but it copies too many lines. When I use For x = 0 To 3 it copies the next 10 lines below "Header 1" instead of only 3. I can't find my mistake.

```<code>Sub FindCopyPasteV2()

    With Worksheets("Sheet1").Range("A:FF")

        Dim FindEQ3 As Range
        Dim TestR As Range
        Dim x As Long

           Set FindEQ3 = .Find(What:="Header 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

              For x = 0 To 3

                 Set FindEQ3 = FindEQ3.Resize(FindEQ3.Rows.Count + x).Offset(1)
                 Set TestR = .Range("K" & 5 + x)

                 FindEQ3.Copy TestR

              Next x

    End With

End Sub
</code>```

答:
I am not sure why you want to use a for loop to copy a number of cells across. Please find below code. This should find the header you are after, then "copy" across the values else where. </p>

```<code>Option Explicit

Sub FindCopyPaste()

    Dim mRng As Range
    Dim fRng As Range
    Dim xOff As Long
    Dim mSheet As Worksheet

    'number of cells to "copy" across
    xOff = 3

    Set mSheet = Sheets("Sheet1")
    Set mRng = mSheet.Range("A:FF")
    Set fRng = mRng.Find(What:="Header 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

    If Not fRng Is Nothing Then
        'if it finds the header
        'now set values
        mSheet.Range("K5").Resize(xOff, 1).Value = mSheet.Range(mSheet.Cells(fRng.Row + 1, fRng.Column), mSheet.Cells(fRng.Row + xOff, fRng.Column)).Value
    Else
        MsgBox "Error! Could not find Header 1!"
    End If

End Sub
</code>```

Body:
I'm trying to search for a certain header (Header 1 in this example) and copy a certain amount of cells below this header to a range. The text of the header itself isn't supposed to get copied but everything below it.

The following code works, but it copies too many lines. When I use For x = 0 To 3 it copies the next 10 lines below "Header 1" instead of only 3. I can't find my mistake.

Sub FindCopyPasteV2()

    With Worksheets("Sheet1").Range("A:FF")

        Dim FindEQ3 As Range
        Dim TestR As Range
        Dim x As Long

           Set FindEQ3 = .Find(What:="Header 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

              For x = 0 To 3

                 Set FindEQ3 = FindEQ3.Resize(FindEQ3.Rows.Count + x).Offset(1)
                 Set TestR = .Range("K" & 5 + x)

                 FindEQ3.Copy TestR

              Next x

    End With

End Sub

Body:
I am not sure why you want to use a for loop to copy a number of cells across. Please find below code. This should find the header you are after, then "copy" across the values else where.

Option Explicit

Sub FindCopyPaste()

    Dim mRng As Range
    Dim fRng As Range
    Dim xOff As Long
    Dim mSheet As Worksheet

    'number of cells to "copy" across
    xOff = 3

    Set mSheet = Sheets("Sheet1")
    Set mRng = mSheet.Range("A:FF")
    Set fRng = mRng.Find(What:="Header 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

    If Not fRng Is Nothing Then
        'if it finds the header
        'now set values
        mSheet.Range("K5").Resize(xOff, 1).Value = mSheet.Range(mSheet.Cells(fRng.Row + 1, fRng.Column), mSheet.Cells(fRng.Row + xOff, fRng.Column)).Value
    Else
        MsgBox "Error! Could not find Header 1!"
    End If

End Sub


问:
How to Show Video and Images in the Same View Using Typscript
I am trying to Create a List in Ionic where i have a common array for videos and image url's

```<code>body = [{media: "https://firebasestorage.googleapis.com/v0/b/gymtest-ed199.appspot.com/o/uploads%2Fg2VZAx27ABOBG7fpo7LyRiIIe8c2%2F20190527_163701.mp4?alt=media&token=0ce4a8d2-3334-49de-99a7-24724e986f80"},
              {media:"https://firebasestorage.googleapis.com/v0/b/gymtest-ed199.appspot.com/o/uploads%2FgtNphS09UEQKFbzTzPn9CdZyKyM2%2F1558535656752.jpg?alt=media&token=5885af85-d5c9-43e5-a852-b974ce5b49ba"}]
</code>```

The first Url is Video and the Second Url is Image

Here is my HTML:-

```<code><ion-item *ngFor= "let d of body">
  <video height="150px" width="300px" controls="controls" preload="metadata" autoplay="autoplay" webkit-playsinline="webkit-playsinline" class="videoPlayer">
   <source [src]="d.media" type="video/mp4" />
  </video>
  <ion-thumbnail>
   <img [src]="d.media"/>
  </ion-thumbnail>
</ion-item>
</code>```

I want to implement *ngIf to determine if the url is .mp4, load to video tag and if url is .jpg, load to img tag

P.S I am a rookie in ionic..

答:
modify your array’s elements to have content type property:

```<code>body = [
    { media: yourVideoUrlHere, type: “video” },
    { media: yourImageUrlHere, type: “image” },
]
</code>```

Then in your template for videos add structural directive:

```<code>*ngIf=“d.type==‘video’”
</code>```

For images:

```<code>*ngIf=“d.type==‘image’”
</code>```

Body:
I am trying to Create a List in Ionic where i have a common array for videos and image url's

body = [{media: "https://firebasestorage.googleapis.com/v0/b/gymtest-ed199.appspot.com/o/uploads%2Fg2VZAx27ABOBG7fpo7LyRiIIe8c2%2F20190527_163701.mp4?alt=media&token=0ce4a8d2-3334-49de-99a7-24724e986f80"},
              {media:"https://firebasestorage.googleapis.com/v0/b/gymtest-ed199.appspot.com/o/uploads%2FgtNphS09UEQKFbzTzPn9CdZyKyM2%2F1558535656752.jpg?alt=media&token=5885af85-d5c9-43e5-a852-b974ce5b49ba"}]

The first Url is Video and the Second Url is Image

Here is my HTML:-

<ion-item *ngFor= "let d of body">
  <video height="150px" width="300px" controls="controls" preload="metadata" autoplay="autoplay" webkit-playsinline="webkit-playsinline" class="videoPlayer">
   <source [src]="d.media" type="video/mp4" />
  </video>
  <ion-thumbnail>

  </ion-thumbnail>
</ion-item>

I want to implement *ngIf to determine if the url is .mp4, load to video tag and if url is .jpg, load to img tag

P.S I am a rookie in ionic..

Body:
modify your array’s elements to have content type property:

body = [
    { media: yourVideoUrlHere, type: “video” },
    { media: yourImageUrlHere, type: “image” },
]

Then in your template for videos add structural directive:

*ngIf=“d.type==‘video’”

For images:

*ngIf=“d.type==‘image’”


问:
Update from Windows 1607 to 1809 using PowerShell
I was wondering if there are any relevant documentation explaining how we can do the windows update using dism powershell module.

I want to update from windows 1607 version to windows 1809.
Or is there any other way to do the update of windows using powershell apart from manual installation of windows 1809.

I tried using PSWindowsUpdate Powershell Module, but failed to do the windows feature update using this module. However could do the Windows cummulative update using the same.

I am very new to this area, but familiar with Powershell. Can anybody recommend the right path for me?

答:
It depends a lot how you want to do it.
Do you want to update a local computer ? And directly 1607 to 1809 without going through all other version (1709 as exemple) ?

The easiest would be I think to make a dism and to install each "big update".

1703

1709

1803

What do you use the computer for ? If you have some "special" application, it could be a good idea to do it for each version and test that everything works.

Hope it helps