问:
How to return count of function calls between calls with the same input?
I'm trying to get the value of when was the last time function was called with the same input. If it's the first time, return -1. For example:

```<code>System.out.println(newNumber(1)); // returns -1
System.out.println(newNumber(2)); // returns -1
System.out.println(newNumber(3)); // returns -1
System.out.println(newNumber(1)); // returns 2
System.out.println(newNumber(2)); // returns 2
System.out.println(newNumber(1)); // returns 1
System.out.println(newNumber(4)); // returns -1
System.out.println(newNumber(1)); // returns 1
</code>```

Having really hard time finding the right way to start doing this. I'm pretty new to hash maps, and I think that's what you have to use?

答:
I think this works as required.  </p>

```<code>    static Map<Integer, Integer> map = new HashMap<>();

    public static int newNumber(int n) {
        // store the call count at the null key
        int calls = map.compute(null, (k,v)-> v == null ? 0 : v + 1);

        // initialize the argument entry first time encountered
        map.computeIfAbsent(n, v->calls);

        int c = calls - map.get(n) - 1;
        map.put(n, calls);
        return c;
    }
</code>```

Body:
I'm trying to get the value of when was the last time function was called with the same input. If it's the first time, return -1. For example:

System.out.println(newNumber(1)); // returns -1
System.out.println(newNumber(2)); // returns -1
System.out.println(newNumber(3)); // returns -1
System.out.println(newNumber(1)); // returns 2
System.out.println(newNumber(2)); // returns 2
System.out.println(newNumber(1)); // returns 1
System.out.println(newNumber(4)); // returns -1
System.out.println(newNumber(1)); // returns 1

Having really hard time finding the right way to start doing this. I'm pretty new to hash maps, and I think that's what you have to use?

Body:
I think this works as required.

    static Map<Integer, Integer> map = new HashMap<>();

    public static int newNumber(int n) {
        // store the call count at the null key
        int calls = map.compute(null, (k,v)-> v == null ? 0 : v + 1);

        // initialize the argument entry first time encountered
        map.computeIfAbsent(n, v->calls);

        int c = calls - map.get(n) - 1;
        map.put(n, calls);
        return c;
    }


来源: stackexchange

问:
javascript regular expression
How do you write a JS regular expression to extract the first "2" from "/?page=2&promo_id=1234". (ie page number 2)

Thanks!

答:
It depend on what may vary in your string. If the number is the only variable, then:

```<code>var match, pageNumber;
if(pageNumber = "/?page=2&promo_id=1234".match(/page=(\d+)/))
    pageNumber = match[1];
</code>```

Or the ugly (but shorter) way

```<code>var pageNumber = ("/?page=223&promo_id=a".match(/page=(\d+)/)||[,undefined])[1]
</code>```

ContentLicense: CC BY-SA 3.0

Title: javascript regular expression

Body:
It depend on what may vary in your string. If the number is the only variable, then:

var match, pageNumber;
if(pageNumber = "/?page=2&promo_id=1234".match(/page=(\d+)/))
    pageNumber = match[1];

Or the ugly (but shorter) way

var pageNumber = ("/?page=223&promo_id=a".match(/page=(\d+)/)||[,undefined])[1]


问:
using html and css only flexbox
How to align like this because the text with progress bar are hard to align using flex box.

should i make 3 seperate div or 2 div? because text with progressbar content are hard to align

https://jsfiddle.net/ypsmkLrb/1/ MY CODE

```<code>*{
    padding:0;
    margin:0;
}
body{
    font-family:Verdana, Geneva, Tahoma, sans-serif;
}
.container{
    width:1200px;
    margin:auto;
    background-color:teal;
}
.about-header{
    padding-bottom:25px;
    text-align: center;
}
.about-img img{
    height:200px;
    width:auto;
}
.about-img{
    height:200px;
    width:auto;
}
.about-row{
    display: flex;
    flex-wrap: wrap;
    font-size: 11px;
}
.about-content{
    line-height:1.6;
    padding-left: 20px;
    border:solid
}
.about-content img{
    height:15px;
    width:auto;
 }
.bar-row-one{
    display:flex;
    align-items:flex-start;
    justify-content:space-around;
}
 .bar-row-two{
    display:flex;
    justify-content:space-around;
}
</code>```

答:
If you need to just align the progressbars, I'd suggest setting an explicit width to the labels before so the progress bar starts at the same point for all of them

* {
  padding: 0;
  margin: 0;
}

body {
  font-family: Verdana, Geneva, Tahoma, sans-serif;
}

.container {
  width: 1200px;
  margin: auto;
  background-color: teal;
}

.about-header {
  padding-bottom: 25px;
  text-align: center;
}

.about-img img {
  height: 200px;
  width: auto;
}

.about-img {
  height: 200px;
  width: auto;
}

.about-row {
  display: flex;
  flex-wrap: wrap;
  font-size: 11px;
}

.about-content {
  line-height: 1.6;
  padding-left: 20px;
  border: solid
}

.about-content img {
  height: 15px;
  width: auto;
}

.bar-row-one {
  display: flex;
  align-items: flex-start;
  justify-content: space-around;
}

.bar-row-two {
  display: flex;
  justify-content: space-around;
}

label {
  width: 50px;
  display: inline-block;
}

.bar {
  display: flex;
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Mockup Template</title>
  <link rel="stylesheet" href="css/style.css">
</head>

<body>
  <section id="about">
    <div class="container">
      <div class="about-header">
        <h1>About</h1>
      </div>
      <div class="about-row">
        <div class="about-img">
          <img src="https://cdn.pixabay.com/photo/2015/02/24/15/41/dog-647528_1280.jpg" alt="farm_5">
        </div>
        <div class="about-content">
          <p>Lorem Ipsum dolor sit amet, vix vocent habemus petentium ea , ex vix nonumy scripta.<br/> Per ne alia stet clita. No admodum detracto pericula vim, te dicit utamur molestie nec. No phaedrum molestiae assueverit duo
          </p>
          </br>
          <p>Et tritani recusabo oportere sea, per at noster vivedum deterruisset. Mea te libris mandamus deseruisse.<br/> Dicat zril epicurei ex pri, ad posse occurreret posidonium mei, ut vis sint explicari.<br/> In vidisse volucptatibus vix. Ectram dissentiunt
            an sit, duo ea utinam imperdiet. His et nobis hendrerit,<br/> Illum delicata no sea, cu fabulas recusabo adhorreant has. Probo luciluis perfecto ei vix, purto noluisse constetur an pro.
          </p>
          <div class="bar-row-one">
            <div class="bar bar1">
              <label class="bar-label">Graphic</label><img src="https://i.dlpng.com/static/png/6659952_preview.png" alt="bars">
            </div>
            <div class="bar bar2">
              <label class="bar-label">System</label><img src="https://i.dlpng.com/static/png/6659952_preview.png" alt="bars">
            </div>
          </div>
          <div class="bar-row-two">
            <div class="bar bar3">
              <label class="bar-label-web"> Web</label><img src="https://i.dlpng.com/static/png/6659952_preview.png" alt="bars">
            </div>
            <div class="bar bar4">
              <label class="bar-label-ui">UI/UX</label><img src="https://i.dlpng.com/static/png/6659952_preview.png" alt="bars">
            </div>
          </div>
        </div>
      </div>
  </section>
</body>

</html></code>```

ContentLicense: CC BY-SA 4.0

Title: using html and css only flexbox

Body:
How to align like this because the text with progress bar are hard to align using flex box.

should i make 3 seperate div or 2 div? because text with progressbar content are hard to align

https://jsfiddle.net/ypsmkLrb/1/ MY CODE

*{
    padding:0;
    margin:0;
}
body{
    font-family:Verdana, Geneva, Tahoma, sans-serif;
}
.container{
    width:1200px;
    margin:auto;
    background-color:teal;
}
.about-header{
    padding-bottom:25px;
    text-align: center;
}
.about-img img{
    height:200px;
    width:auto;
}
.about-img{
    height:200px;
    width:auto;
}
.about-row{
    display: flex;
    flex-wrap: wrap;
    font-size: 11px;
}
.about-content{
    line-height:1.6;
    padding-left: 20px;
    border:solid
}
.about-content img{
    height:15px;
    width:auto;
 }
.bar-row-one{
    display:flex;
    align-items:flex-start;
    justify-content:space-around;
}
 .bar-row-two{
    display:flex;
    justify-content:space-around;
}

Body:
If you need to just align the progressbars, I'd suggest setting an explicit width to the labels before so the progress bar starts at the same point for all of them

* {
  padding: 0;
  margin: 0;
}

body {
  font-family: Verdana, Geneva, Tahoma, sans-serif;
}

.container {
  width: 1200px;
  margin: auto;
  background-color: teal;
}

.about-header {
  padding-bottom: 25px;
  text-align: center;
}

.about-img img {
  height: 200px;
  width: auto;
}

.about-img {
  height: 200px;
  width: auto;
}

.about-row {
  display: flex;
  flex-wrap: wrap;
  font-size: 11px;
}

.about-content {
  line-height: 1.6;
  padding-left: 20px;
  border: solid
}

.about-content img {
  height: 15px;
  width: auto;
}

.bar-row-one {
  display: flex;
  align-items: flex-start;
  justify-content: space-around;
}

.bar-row-two {
  display: flex;
  justify-content: space-around;
}

label {
  width: 50px;
  display: inline-block;
}

.bar {
  display: flex;
  align-items: center;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Mockup Template</title>
  <link rel="stylesheet" href="css/style.css">
</head>

<body>
  <section id="about">
    <div class="container">
      <div class="about-header">
        <h1>About</h1>
      </div>
      <div class="about-row">
        <div class="about-img">
          <img src="https://cdn.pixabay.com/photo/2015/02/24/15/41/dog-647528_1280.jpg" alt="farm_5">
        </div>
        <div class="about-content">
          <p>Lorem Ipsum dolor sit amet, vix vocent habemus petentium ea , ex vix nonumy scripta.<br/> Per ne alia stet clita. No admodum detracto pericula vim, te dicit utamur molestie nec. No phaedrum molestiae assueverit duo
          </p>
          </br>
          <p>Et tritani recusabo oportere sea, per at noster vivedum deterruisset. Mea te libris mandamus deseruisse.<br/> Dicat zril epicurei ex pri, ad posse occurreret posidonium mei, ut vis sint explicari.<br/> In vidisse volucptatibus vix. Ectram dissentiunt
            an sit, duo ea utinam imperdiet. His et nobis hendrerit,<br/> Illum delicata no sea, cu fabulas recusabo adhorreant has. Probo luciluis perfecto ei vix, purto noluisse constetur an pro.
          </p>
          <div class="bar-row-one">
            <div class="bar bar1">
              <label class="bar-label">Graphic</label><img src="https://i.dlpng.com/static/png/6659952_preview.png" alt="bars">
            </div>
            <div class="bar bar2">
              <label class="bar-label">System</label><img src="https://i.dlpng.com/static/png/6659952_preview.png" alt="bars">
            </div>
          </div>
          <div class="bar-row-two">
            <div class="bar bar3">
              <label class="bar-label-web"> Web</label><img src="https://i.dlpng.com/static/png/6659952_preview.png" alt="bars">
            </div>
            <div class="bar bar4">
              <label class="bar-label-ui">UI/UX</label><img src="https://i.dlpng.com/static/png/6659952_preview.png" alt="bars">
            </div>
          </div>
        </div>
      </div>
  </section>
</body>

</html>


问:
Problems with getElementById
I'm trying to write simple web app in VSCode. I have little misunderstanding. May be its really simple thing, but i don't know why it doesn't work normally like in examples which i saw.

i have js file (script.js)

```<code> function getHistory(){
    return document.getElementById("history-value").innerText;
}
alert( getHistory());
</code>```

and my index.html where i'm using div's tags

```<code>     <div class="result">
        <div class="history">
            <p  id="history-value">55555</p>
        </div>
        <div class="output">
            <p id="output-value" class="output-value">7777777</p>
        </div>
    </div>
</code>```

in beginning of course referense to js

```<code><head>
    <title>Calculator</title>
    <meta charset="utf-8" >
    <link rel="stylesheet" href="style.css">
    <script src="script.js">
        </script>
</head>
</code>```

But allert are not working. I can't see nothing. If i use

```<code>console.log (document.getElementById("history-value").innerText );
</code>```

it shows null in console window.

Please explain me what's wrong with it?

答:
1) As Java script is loaded before html page so you have to add script tage at bottom of the page in your case as you are taking value of history-value element which you have added after script tag so when script tag is loaded there is no element with id history-value so you will get null. So you have to add this script after this element

index.html

```<code><head>
    <title>Calculator</title>
    <meta charset="utf-8" >
    <link rel="stylesheet" href="style.css">
</head>

<div class="result">
        <div class="history">
            <p  id="history-value">55555</p>
        </div>
        <div class="output">
            <p id="output-value" class="output-value">7777777</p>
        </div>
    </div>

    <script src="script.js"></script>
</code>```

script.js

```<code>function getHistory(){
    return document.getElementById("history-value").innerText;
}
alert( getHistory());
</code>```

Title: Problems with getElementById

Body:
I'm trying to write simple web app in VSCode. I have little misunderstanding. May be its really simple thing, but i don't know why it doesn't work normally like in examples which i saw.

i have js file (script.js)

 function getHistory(){
    return document.getElementById("history-value").innerText;
}
alert( getHistory());

and my index.html where i'm using div's tags

55555

7777777

in beginning of course referense to js

    <title>Calculator</title>
    <meta charset="utf-8" >
    <link rel="stylesheet" href="style.css">

But allert are not working. I can't see nothing. If i use

console.log (document.getElementById("history-value").innerText );

it shows null in console window.

Please explain me what's wrong with it?

Body:
1) As Java script is loaded before html page so you have to add script tage at bottom of the page in your case as you are taking value of history-value element which you have added after script tag so when script tag is loaded there is no element with id history-value so you will get null. So you have to add this script after this element

index.html

<head>
    <title>Calculator</title>
    <meta charset="utf-8" >
    <link rel="stylesheet" href="style.css">
</head>

<div class="result">
        <div class="history">
            <p  id="history-value">55555</p>
        </div>
        <div class="output">
            <p id="output-value" class="output-value">7777777</p>
        </div>
    </div>

    <script src="script.js"></script>

script.js

function getHistory(){
    return document.getElementById("history-value").innerText;
}
alert( getHistory());


答:
That's the solution:

Live demo: https://jsfiddle.net/6qwkmtfx/1/

Or the CSS code.

* {
  padding: 0;
  margin: 0;
}

body {
  font-family: Verdana, Geneva, Tahoma, sans-serif; /* ohhh. a lot of fonts */
}

.container {
  width: 100%; /* orginally "width: 1200px" */
  margin: auto;
  background-color: teal; /* or "white" // "#fff" */
}

.about-header {
  padding-bottom: 25px;
  /* padding-top: 25px; */
  text-align: center;
}

.about-img img {
  height: 200px;
}

.about-img {
  height: 200px;
}

.about-row {
  display: flex;
  flex-direction: row;
  font-size: 11px;
  justify-content: center; /* to grid */
  align-items: flex-start; /* to grid */
}

.about-content {
  line-height: 1.6; /* Missing value? */
  padding-left: 20px;
  border: solid;
}

.about-content img {
  height: 15px;
  width: auto;
}

.bar-row-one {
  display: flex;
  align-items: flex-start;
  justify-content: space-around;
}

.bar-row-two {
  display: flex;
  justify-content: space-around;
}
```

Title: using html and css only flexbox


问:
Can't get outer html of WebView in HTML when site is on cookiebot
when I load my web, it returns html corretly.

But when I load any page of geocaching.com, I get source like that (you must be logined, otherwise it give other but still wrong content):

```<code>`https://pastebin.com/QJLS1Py3`
</code>```

I'm logined and accepted all cookies (visible on https://www.geocaching.com/account/documents/cookies).

When anyone will have solution which use HttpRequest / WebClient it's also appreciate, when it will be returning content like user is logined (many of data is hidden when user is not logined).

How can I get outer html of page?

Video of behaviours: https://vimeo.com/391693855

Thanks for help!

答:
Solveeeed! I have to do it several second delayed. Was enough insert something like in before eval.</p>

```<code>await Task.Delay(5000);
</code>```

Body:
when I load my web, it returns html corretly.

But when I load any page of geocaching.com, I get source like that (you must be logined, otherwise it give other but still wrong content):

`https://pastebin.com/QJLS1Py3`

I'm logined and accepted all cookies (visible on https://www.geocaching.com/account/documents/cookies).

When anyone will have solution which use HttpRequest / WebClient it's also appreciate, when it will be returning content like user is logined (many of data is hidden when user is not logined).

How can I get outer html of page?

Video of behaviours: https://vimeo.com/391693855

Thanks for help!

Body:
Solveeeed! I have to do it several second delayed. Was enough insert something like in before eval.

await Task.Delay(5000);


问:
How to pretend ordering records just like line numbers of an editor
This is about storing commands in a database instead of a text file or spreadsheet.
I am looking for a solution, which mimics the behavior of line numbers in a text editor.

E.g. Given the table below with the column "Order" as the primary key, when I delete the second row (Order = 2), I would end up with a gap in the order column (1, 3), which needs to be corrected to (1, 2)

```<code>| Order | Command      |     | Order | Command      |     | Order | Command      |
|-------|--------------|     |-------|--------------|     |-------|--------------|
|   1   | CAM - ON     | ==> |   1   | CAM - ON     | ==> |   1   | CAM - ON     |
|   2   | Turn left    |     |   3   | Take picture |     |   2   | Take picture |
|   3   | Take picture |
</code>```

I have already experimented with triggers. Before the record gets deleted, a trigger updates the relevant order numbers of the other records. I have also triggers to deal with appending or inserting a new record "before" an existing one.

I know the physical order on disk is different and irrelevant. So, I just manipulate the "Order" column to mimic the behaviour of line numbers.

The same works fine with updating records. E.g. if I want to "move" the "Turn left" command to the first position, implementing a trigger before update to reorder the other records does the trick too. E.g. set the order of the "Turn left" command to 1 and the trigger updates the other records first:

```<code>| Order | Command      |     | Order | Command      |
|-------|--------------|     |-------|--------------|
|   1   | CAM - ON     | ==> |   2   | CAM - ON     |
|   2   | Turn left    |     |   1   | Turn left    |
|   3   | Take picture |     |   3   | Take picture |
</code>```

However, this one introduces a problem. Deleting or inserting a record triggers a procedure, which updates records, which now triggers the update procedure. This seems to make things recursive and complicated.

I tried to disable and enable the update trigger from within the other trigger procedures, but (in postgresl) this requires altering the table, which is not allowed during a query..

My question is: Is there a more straight forward solution, which covers all four CRUD Operations? Perhaps involving other data types for the order column instead of integer or completely different techniques?

答:
Your data is not really a good match for a relational database - if it was me, and the number of commands is not too large, I'd just store it as a JSON or XML clob.

But if you must use relational storage, I think that having to update on the average half of all rows after each insert
is not a good design.

I'd suggest not storing the actual number, but just have the ord column
define a relative order. As @GMB already wrote, you can then use
row_number to get your consecutive numbers starting with 1.

To insert new rows without having to renumber existing ones, leave "holes"
in the numbering:

Let MIN and MAX be the minimum and maximum numbers you want to use in the
ord column. Then the very first row you insert should get

```<code>ord = (MIN + MAX) / 2
</code>```

To insert a new row between two existing rows with order numbers
o1 and o2, use

```<code>ord = (o1 + o2) / 2
</code>```

Depending on the number of rows and number of inserts/updates you expect,
a collision (i.e. no space between o1 and o2) may occur, so
you should also have a renumbering procedure for that case.
E.g. if you insert already ordered items this will very quickly
(after log(max - min) inserts).

Here's pseudocode to get the ord number for insertion after a given row
with ord == o1:

```<code>let next = SELECT MIN(ord) FROM commands WHERE ord > :o1
if next IS NULL then
    if o1 == MAX     then panic_or_renumber
    if o1 == MAX - 1 then MAX
    else (o1 + MAX) / 2
else
    if next == o1 + 1 then panic_or_renumber
    else (o1 + next) / 2
</code>```

(Note that (a + b) / 2 can overflow when using signed arithmetic. Choose your
bounds accordingly or use safer arithmetic if you need huge numbers of rows).

Body:
This is about storing commands in a database instead of a text file or spreadsheet.
I am looking for a solution, which mimics the behavior of line numbers in a text editor.

E.g. Given the table below with the column "Order" as the primary key, when I delete the second row (Order = 2), I would end up with a gap in the order column (1, 3), which needs to be corrected to (1, 2)

| Order | Command      |     | Order | Command      |     | Order | Command      |
|-------|--------------|     |-------|--------------|     |-------|--------------|
|   1   | CAM - ON     | ==> |   1   | CAM - ON     | ==> |   1   | CAM - ON     |
|   2   | Turn left    |     |   3   | Take picture |     |   2   | Take picture |
|   3   | Take picture |

I have already experimented with triggers. Before the record gets deleted, a trigger updates the relevant order numbers of the other records. I have also triggers to deal with appending or inserting a new record "before" an existing one.

I know the physical order on disk is different and irrelevant. So, I just manipulate the "Order" column to mimic the behaviour of line numbers.

The same works fine with updating records. E.g. if I want to "move" the "Turn left" command to the first position, implementing a trigger before update to reorder the other records does the trick too. E.g. set the order of the "Turn left" command to 1 and the trigger updates the other records first:

| Order | Command      |     | Order | Command      |
|-------|--------------|     |-------|--------------|
|   1   | CAM - ON     | ==> |   2   | CAM - ON     |
|   2   | Turn left    |     |   1   | Turn left    |
|   3   | Take picture |     |   3   | Take picture |

However, this one introduces a problem. Deleting or inserting a record triggers a procedure, which updates records, which now triggers the update procedure. This seems to make things recursive and complicated.

I tried to disable and enable the update trigger from within the other trigger procedures, but (in postgresl) this requires altering the table, which is not allowed during a query..

My question is: Is there a more straight forward solution, which covers all four CRUD Operations? Perhaps involving other data types for the order column instead of integer or completely different techniques?

Body:
Your data is not really a good match for a relational database - if it was me, and the number of commands is not too large, I'd just store it as a JSON or XML clob.

But if you must use relational storage, I think that having to update on the average half of all rows after each insert
is not a good design.

I'd suggest not storing the actual number, but just have the ord column
define a relative order. As @GMB already wrote, you can then use
row_number to get your consecutive numbers starting with 1.

To insert new rows without having to renumber existing ones, leave "holes"
in the numbering:

Let MIN and MAX be the minimum and maximum numbers you want to use in the
ord column. Then the very first row you insert should get

ord = (MIN + MAX) / 2

To insert a new row between two existing rows with order numbers
o1 and o2, use

ord = (o1 + o2) / 2

Depending on the number of rows and number of inserts/updates you expect,
a collision (i.e. no space between o1 and o2) may occur, so
you should also have a renumbering procedure for that case.
E.g. if you insert already ordered items this will very quickly
(after log(max - min) inserts).

Here's pseudocode to get the ord number for insertion after a given row
with ord == o1:

let next = SELECT MIN(ord) FROM commands WHERE ord > :o1
if next IS NULL then
    if o1 == MAX     then panic_or_renumber
    if o1 == MAX - 1 then MAX
    else (o1 + MAX) / 2
else
    if next == o1 + 1 then panic_or_renumber
    else (o1 + next) / 2

(Note that (a + b) / 2 can overflow when using signed arithmetic. Choose your
bounds accordingly or use safer arithmetic if you need huge numbers of rows).


问:
Hide columns in one sheet based on whether checkbox in another sheet is FALSE
I am trying to run a script on my spreadsheet that hides columns on one sheet based on whether a checkbox in another sheet is ticked.

I have created the below code but this doesn't seem to work:

```<code>function onEdit(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = SpreadsheetApp.getActive().getSheetByName('BALANCE SHEET');
  var sheet2 = SpreadsheetApp.getActive().getSheetByName('OVERVIEW')
  var cell = sheet2.getRange(7, 5);

  if(cell == "TRUE"){
    sheet1.hideColumns(21,2)};
  if(cell == "FALSE"){
    sheet1.showColumns(21,2)};
}
</code>```

The tickbox is on the sheet OVERVIEW in cell E7 and I want this to hide columns V & W on the BALANCE SHEET.

When the tickbox is TRUE, I want the columns to be displayed and when the tickbox is FALSE the columns will be hidden.

Can anyone help on this please?

答:
This works:

Note: you can't run this from the script editor as it requires having the onedit trigger object.  I have my checkbox at 'OVERVIEW!E7';

```<code>function onEdit(e){
  //e.source.toast('Test');
  var sh=e.range.getSheet();
  if(sh.getName()!='OVERVIEW')return;
  if(e.range.columnStart==5 && e.range.rowStart==7) {
    //e.source.toast('Test1');
    var sheet1=e.source.getSheetByName('BALANCE SHEET');
    if(e.value=="TRUE"){sheet1.hideColumns(21,2)};
    if(e.value=="FALSE"){sheet1.showColumns(21,2)};
  }
}
</code>```

Body:
I am trying to run a script on my spreadsheet that hides columns on one sheet based on whether a checkbox in another sheet is ticked.

I have created the below code but this doesn't seem to work:

function onEdit(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = SpreadsheetApp.getActive().getSheetByName('BALANCE SHEET');
  var sheet2 = SpreadsheetApp.getActive().getSheetByName('OVERVIEW')
  var cell = sheet2.getRange(7, 5);

  if(cell == "TRUE"){
    sheet1.hideColumns(21,2)};
  if(cell == "FALSE"){
    sheet1.showColumns(21,2)};
}

The tickbox is on the sheet OVERVIEW in cell E7 and I want this to hide columns V & W on the BALANCE SHEET.

When the tickbox is TRUE, I want the columns to be displayed and when the tickbox is FALSE the columns will be hidden.

Can anyone help on this please?

Body:
This works:

Note: you can't run this from the script editor as it requires having the onedit trigger object.  I have my checkbox at 'OVERVIEW!E7';

function onEdit(e){
  //e.source.toast('Test');
  var sh=e.range.getSheet();
  if(sh.getName()!='OVERVIEW')return;
  if(e.range.columnStart==5 && e.range.rowStart==7) {
    //e.source.toast('Test1');
    var sheet1=e.source.getSheetByName('BALANCE SHEET');
    if(e.value=="TRUE"){sheet1.hideColumns(21,2)};
    if(e.value=="FALSE"){sheet1.showColumns(21,2)};
  }
}


问:
How to render string as custom React component?
So I have this code

```<code>ReactDom.render(<Home />, document.getElementById("main"));
</code>```

This works perfectly and it renders Home component.
I want to make this code dynamic
instead Home component, it can be any component like Apartment or Building component.

I have tried to do this by the following code.

```<code>const tag = `<${main} />`;
ReactDom.render(tag, document.getElementById("main"));
</code>```

This doesn't work.

I would like to know if it is possible. I would prefer to do this without any third party library.

答:
What I would do as also mentioned in the comment section is creating first an <App /> component and handling there which one to render in your screen. This won't render all the components as you might expect based on your comment.

For example in the <App /> component based on a string value you can render different components. This string value can be manipulated with button components' onClick handlers what I leave it to you how to deal with.

The main <App /> component would look like this then:

```<code>import React, { useState } from 'react';
// import other components

function App() {
   const [current, setCurrent] = useState('home');

   if (current === 'home') { return <Home /> }
   else if (current === 'contact') { return <Contact /> }
   else { return <DifferentComponent /> }
}

export default App;
</code>```

The index.js would be like the following:

```<code>ReactDOM.render(<App />, document.getElementById('root'));
</code>```

At the end you can create different buttons in your return where you can call setCurrent in order to manipulate which one to render.

Or as I suggested in the comments like a second option, you can go with react-router, this will help you to render different components based on the current route. Take a look at here to this good quick start training if you would like achieve that.

I hope this explanation helps!

Body:
So I have this code

ReactDom.render(<Home />, document.getElementById("main"));

This works perfectly and it renders Home component.
I want to make this code dynamic
instead Home component, it can be any component like Apartment or Building component.

I have tried to do this by the following code.

const tag = `<${main} />`;
ReactDom.render(tag, document.getElementById("main"));

This doesn't work.

I would like to know if it is possible. I would prefer to do this without any third party library.

Body:
What I would do as also mentioned in the comment section is creating first an <App /> component and handling there which one to render in your screen. This won't render all the components as you might expect based on your comment.

For example in the <App /> component based on a string value you can render different components. This string value can be manipulated with button components' onClick handlers what I leave it to you how to deal with.

The main <App /> component would look like this then:

import React, { useState } from 'react';
// import other components

function App() {
   const [current, setCurrent] = useState('home');

   if (current === 'home') { return <Home /> }
   else if (current === 'contact') { return <Contact /> }
   else { return <DifferentComponent /> }
}

export default App;

The index.js would be like the following:

ReactDOM.render(<App />, document.getElementById('root'));

At the end you can create different buttons in your return where you can call setCurrent in order to manipulate which one to render.

Or as I suggested in the comments like a second option, you can go with react-router, this will help you to render different components based on the current route. Take a look at here to this good quick start training if you would like achieve that.

I hope this explanation helps!


问:
How to report console.error with Sentry?
I have application where some critical issues are reported with console.error but are not thrown so application might continue to run - possibly in crippled state.

It's necessary to report also console.error issues, but Sentry (Raven) library send to server only thrown exceptions.

Does someone knows how to solve this nicely ?

(ideally without need to rewrite all console.error calls, cause also some vendor libraries might still write output just into console)

答:
I wrote a library that is going this using your Sentry instance.
https://github.com/aneldev/dyna-sentry</p>


问:
Pipe text to Python script or prompt
I'm trying to write a very simple email script in python. It's basically a poor man's mutt. At work, we send a lot of data from servers around, and it would be much easier to send it directly from the server.

The part that I'm stuck on is dealing with the message. I want users to to be able to do the following:

```<code>$ cat message.txt | emailer.py fandingo@example.com
$ tail -n 2000 /var/log/messages | emailer.py fandingo@example.com
</code>```

Both of those are easy enough. I can just sys.stdin.read() and get my data.

The problem that I'm having is that I also want to support a prompt for typing a message with the following usage:

```<code>emailer.py --attach-file /var/log/messages fandingo@example.com

Enter Your message. Use ^D when finished.
>>   Steve,
>>   See the attached system log. See all those NFS errors around 2300 UTC today.
>>
>>   ^D
</code>```

The trouble that I'm having is that if I try to sys.stdin.read(), and there's no data, then my program blocks until stdin gets data, but I can't print my prompt.
I could take a safe approach and use raw_input("Enter Your message. Use ^D when finished.") instead of stdin.read(), but then I always print the prompt.

Is there a way to see if a user piped text into python without using a method that will block?

答:
You can use sys.stdin.isatty to check if the script is being run interactively. Example:

```<code>if sys.stdin.isatty():
    message = raw_input('Enter your message ')
else:
    message = sys.stdin.read()
</code>```

Title: Pipe text to Python script or prompt

Body:
I'm trying to write a very simple email script in python. It's basically a poor man's mutt. At work, we send a lot of data from servers around, and it would be much easier to send it directly from the server.

The part that I'm stuck on is dealing with the message. I want users to to be able to do the following:

$ cat message.txt | emailer.py fandingo@example.com
$ tail -n 2000 /var/log/messages | emailer.py fandingo@example.com

Both of those are easy enough. I can just sys.stdin.read() and get my data.

The problem that I'm having is that I also want to support a prompt for typing a message with the following usage:

emailer.py --attach-file /var/log/messages fandingo@example.com

Enter Your message. Use ^D when finished.
>>   Steve,
>>   See the attached system log. See all those NFS errors around 2300 UTC today.
>>
>>   ^D

The trouble that I'm having is that if I try to sys.stdin.read(), and there's no data, then my program blocks until stdin gets data, but I can't print my prompt.
I could take a safe approach and use raw_input("Enter Your message. Use ^D when finished.") instead of stdin.read(), but then I always print the prompt.

Is there a way to see if a user piped text into python without using a method that will block?

Body:
You can use sys.stdin.isatty to check if the script is being run interactively. Example:

if sys.stdin.isatty():
    message = raw_input('Enter your message ')
else:
    message = sys.stdin.read()


问:
Access Environment based application.properties file in class not managed by spring
I am working on spring boot project having version 2.1.6.RELEASE and xslt 1.0.

I have a class that has a set of static methods used to generate the set of URL's using custom logic related to the application.

```<code>public class URLGenerator{

    public static String generateURLA(String param1,String param2,String param3)
    {
        String restServiceUrl=<acess url from application.properties>
        //code to invoke third party service
        RestTemplate restTemplate=new RestTemplate();
        String url=restTemplate.invoke()
        return url;
    }
}
</code>```

In the above method, I have to make a rest call to third party service to retrieve the final URL. The URL to invoke the service is different for every environment so I have stored the URL inside the application-{env}.properties file.

I will not be able to change the above method to non static as there are several xsl files invoke the above method.

What is the best way to access the environment based application.properties file in class which is not managed by Spring?

答:
You can use plain old properties here.

```<code>final Properties props = new Properties();
props.load(new FileInputStream("/path/application.properties"));
props.getProperty("urls.foo"));
props.getProperty("urls.bar"));
</code>```

OR

```<code>final Properties props = new Properties();
try (InputStream is = getClass().getResourceAsStream("application.properties")) {
  props.load(is);
  props.getProperty("urls.foo"));
  props.getProperty("urls.bar"));
}
</code>```

Body:
I am working on spring boot project having version 2.1.6.RELEASE and xslt 1.0.

I have a class that has a set of static methods used to generate the set of URL's using custom logic related to the application.

public class URLGenerator{

    public static String generateURLA(String param1,String param2,String param3)
    {
        String restServiceUrl=<acess url from application.properties>
        //code to invoke third party service
        RestTemplate restTemplate=new RestTemplate();
        String url=restTemplate.invoke()
        return url;
    }
}

In the above method, I have to make a rest call to third party service to retrieve the final URL. The URL to invoke the service is different for every environment so I have stored the URL inside the application-{env}.properties file.

I will not be able to change the above method to non static as there are several xsl files invoke the above method.

What is the best way to access the environment based application.properties file in class which is not managed by Spring?

Body:
You can use plain old properties here.

final Properties props = new Properties();
props.load(new FileInputStream("/path/application.properties"));
props.getProperty("urls.foo"));
props.getProperty("urls.bar"));

OR

final Properties props = new Properties();
try (InputStream is = getClass().getResourceAsStream("application.properties")) {
  props.load(is);
  props.getProperty("urls.foo"));
  props.getProperty("urls.bar"));
}


问:
How to set a default value to datetime_field
I am trying to set a default value for datetime_field inside the view. I have checked multiple sources and all fail to give the correct results.

For instance this example does not work
https://edgeapi.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html

```<code>datetime_field("user", "born_on", min: "2014-05-20T00:00:00")
# => <input id="user_born_on" name="user[born_on]" type="datetime-local" min="2014-05-20T00:00:00.000" />
</code>```

Here is my code:

```<code><div class="form-group">
   <%= f.datetime_field(:date_reported, class: "form-control col-sm-3", min: "2014-05-20T00:00:00") %>
</div>
</code>```

My code displays this:

答:
The object linked to your form object (f), needs to have its attribute set to the default value you want to input.

If you do something like this, it should work

```<code><% f.object.date_reported = Date.new(1984, 1, 12) %>
<div class="form-group">
   <%= f.datetime_field(:date_reported, class: "form-control col-sm-3", min: "2014-05-20T00:00:00") %>
</div>

</code>```

Please note that normally, setting a default value on your form should be done in the related controller, rather than in the view.

Body:
I am trying to set a default value for datetime_field inside the view. I have checked multiple sources and all fail to give the correct results.

For instance this example does not work
https://edgeapi.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html

datetime_field("user", "born_on", min: "2014-05-20T00:00:00")
# => <input id="user_born_on" name="user[born_on]" type="datetime-local" min="2014-05-20T00:00:00.000" />

Here is my code:

   <%= f.datetime_field(:date_reported, class: "form-control col-sm-3", min: "2014-05-20T00:00:00") %>

My code displays this:

Body:
The object linked to your form object (f), needs to have its attribute set to the default value you want to input.

If you do something like this, it should work

<% f.object.date_reported = Date.new(1984, 1, 12) %>
<div class="form-group">
   <%= f.datetime_field(:date_reported, class: "form-control col-sm-3", min: "2014-05-20T00:00:00") %>
</div>

Please note that normally, setting a default value on your form should be done in the related controller, rather than in the view.


问:
What Does This Script Do?
I'm reviewing the tutorial "Advanced Auto-Dependency Generation" and found a script with this:

```<code> %.P : %.c
   ....; [ -s $@ ] || rm -f $@
</code>```

What does that part of the target do?  I know I've seen this syntax:
[...]||... before in bash scripts, but I can't recall how it works exactly...

Thanks in advance!!

答:
The test [ -s $@ ] tests for a file that is not empty.

If the file is not empty, do not remove it.

If the file is empty, remove the (empty) file.

The sequence [ -s $@ ] || rm -f $@ therefore removes the current target file ($@ in make notation) if it is an empty file.

This is an interesting combination of shell and make notations.  The $@ part is make notation for the target being built.  (It is also a shell notation for the complete list of arguments to a shell script, but in this context, the make notation takes precedence over the shell notation — the shell doesn't see $@.)

Title: What Does This Script Do?

Body:
I'm reviewing the tutorial "Advanced Auto-Dependency Generation" and found a script with this:

 %.P : %.c
   ....; [ -s $@ ] || rm -f $@

What does that part of the target do?  I know I've seen this syntax:
[...]||... before in bash scripts, but I can't recall how it works exactly...

Thanks in advance!!


问:
Jenkins - Storing curl output into file for future use
I'm currently trying to make Jenkins job that runs if there's difference between the version number between 2 runs.

What I'm currently thinking on doing is by running curl on my webapp endpoint to get the webapp version. I'm looking to store this webapp version information onto jenkinsfile or any file.

The next time the jenkins job runs, it will do curl again to my webapp endpoint and compare the version between the current curl output and the saved version information from last run.

However, as I'm still kind of new to Jenkins, i have no idea on where to start to create the file to store the information i want, anyone have some recommendation or advice for me on how to solve this problem ?

Thanks

答: you can write version number to any file(JSON,txt..etc) and read file into your workspace by using pipeline-utility-steps by specifying the path in your jenkinsfile</p>


问:
Accessing an element inside an array with multiple objects
I'm trying to use an api with football teams, I want to simply render the name of the teams in a div or a list. But it just render the last one.

When I console.log it, it shows all the teams

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      teams: [],
      isLoaded: false
    }
  }
  componentDidMount() {
    fetch('https://www.thesportsdb.com/api/v1/json/1/search_all_teams.php?l=English%20Premier%20League')
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          data: json,
        })
      })
  }
  render() {
    var {
      isLoaded,
      data
    } = this.state;
    if (!isLoaded) {
      return
 Loading...

    } else {
      for (var key in data.teams) {
        if (data.teams.hasOwnProperty(key))
          console.log(data.teams[key].strTeam)
      }
      return (

        Premier League Teams!{
          data.teams[key].strTeam
        }

      );
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

答:
Try this:

```<code>return (
    <div className="App">
        Premier League Teams!{data.teams.map(team => team.strTeam)}
    </div>
);
</code>```

This will loop through the teams array with map and render each one.

Body:
Try this:

return (
    <div className="App">
        Premier League Teams!{data.teams.map(team => team.strTeam)}
    </div>
);

This will loop through the teams array with map and render each one.


问:
How to run a shell script in OS X by double-clicking?
I have a shell script that has user execution permission on OS X, but when I double click on it, it opens in a text editor. How can I get it to run by double-clicking it?</p>

答:
chmod 774 filename

Note: The file with name 'filename' that has the bash script has no extension

ContentLicense: CC BY-SA 2.5


问:
"no matching function for call to 'Vector::Vector'" error
How to solve the error in the title?

Vector class code:

```<code>class Vector
{
public:
    uint32_t x;
    uint32_t y;
    Vector(uint32_t x, uint32_t y);
};

Vector::Vector(uint32_t x, uint32_t y)
{
    this->x = x;
    this->y = y;
}
</code>```

Other class code:

```<code>class Test
{
    Test(Vector c1);
    Test(Vector c1, Vector c2);
    Vector c1, c2;
};

Test::Test(Vector c1) // << error here
{
    this->c1 = c1;
}

Test::Test(Vector c1, Vector c2) // << error here too
{
    this->c1 = c1;
    this->c2 = c2;
}
</code>```

I tryed to rename arguments to not be the same as in class.

答:
```<code> Vector c1, c2;
</code>```

This cannot work in your class Test, because this class (Vector) has no default constructor.

You can edit your Vector class:

```<code>class Vector
{
public:
    uint32_t x = 0;
    uint32_t y = 0;
    Vector(uint32_t x = 0, uint32_t y = 0);
};
</code>```

Now there are default arguments so a statement like Vector x; is valid.

OwnerDisplayName: anon

Body:
How to solve the error in the title?

Vector class code:

class Vector
{
public:
    uint32_t x;
    uint32_t y;
    Vector(uint32_t x, uint32_t y);
};

Vector::Vector(uint32_t x, uint32_t y)
{
    this->x = x;
    this->y = y;
}

Other class code:

class Test
{
    Test(Vector c1);
    Test(Vector c1, Vector c2);
    Vector c1, c2;
};

Test::Test(Vector c1) // << error here
{
    this->c1 = c1;
}

Test::Test(Vector c1, Vector c2) // << error here too
{
    this->c1 = c1;
    this->c2 = c2;
}

I tryed to rename arguments to not be the same as in class.

Body:
 Vector c1, c2;

This cannot work in your class Test, because this class (Vector) has no default constructor.

You can edit your Vector class:

class Vector
{
public:
    uint32_t x = 0;
    uint32_t y = 0;
    Vector(uint32_t x = 0, uint32_t y = 0);
};

Now there are default arguments so a statement like Vector x; is valid.


问:
Android Studio project files change text to weird text
Its been a while when I open android studio I always get weird texts instead of the real file, like if I open a java file or xml, some of them would show me something different than the actual file looks like, and if I open the file manually from file explorer using notepad I find the original one, and it keep happening.

```<code>Êþº¾   4X
SUV %abc_action_bar_content_inset_material I
ConstantValue   %abc_action_bar_content_inset_with_nav  &abc_action_bar_default_height_material  +abc_action_bar_default_padding_end_material  -abc_action_bar_default_padding_start_material  !abc_action_bar_elevation_material  -abc_action_bar_icon_vertical_padding_material  ,abc_action_bar_overflow_padding_end_material  .abc_action_bar_overflow_padding_start_material  !abc_action_bar_stacked_max_height    $abc_action_bar_stacked_tab_max_width
.abc_action_bar_subtitle_bottom_margin_material  +abc_action_bar_subtitle_
</code>```

and most of the time its text weirder than that and cant be read.
if i run the application it will work just fine though.

FYI this file is gradle project

this is xml file.. this is not the one i wrote but if open it in file explorer it will be different.

```<code>"logs": [
    {
        "outputFile": "C:\\Users\\saadm\\OneDrive\\Desktop\\flowers\\app\\build\\intermediates\\incremental\\mergeDebugResources\\merged.dir\\values-en-rCA\\values-en-rCA.xml",
        "map": [
            {
                "source": "D:\\Users\\saadm\\.gradle\\caches\\transforms-2\\files-2.1\\331630a23dfa1f0594bcf54d5352aa36\\core-1.1.0\\res\\values-en-rCA\\values-en-rCA.xml",
                "from": {
                    "startLines": "2",
                    "startColumns": "4",
</code>```

答:
It’s possible that you are using a non-unicode file and android studio does not know what the encoding is (like cp1256).

Notepad knows it is a windows-1256 (I am just guessing the code page) because you have already told it in Region and Language section of your Control Panel in Locale tab.

To convert your files into utf8 — so it would be opened in Android Studio in correct form — you may open it with notepad and save as it again as a text or whatever extension you ike, BUT change the target encoding to utf8.

The resulting file should be fine to view on Android Studio.

Body:
Its been a while when I open android studio I always get weird texts instead of the real file, like if I open a java file or xml, some of them would show me something different than the actual file looks like, and if I open the file manually from file explorer using notepad I find the original one, and it keep happening.

Êþº¾   4X
SUV %abc_action_bar_content_inset_material I
ConstantValue   %abc_action_bar_content_inset_with_nav  &abc_action_bar_default_height_material  +abc_action_bar_default_padding_end_material  -abc_action_bar_default_padding_start_material  !abc_action_bar_elevation_material  -abc_action_bar_icon_vertical_padding_material  ,abc_action_bar_overflow_padding_end_material  .abc_action_bar_overflow_padding_start_material  !abc_action_bar_stacked_max_height    $abc_action_bar_stacked_tab_max_width
.abc_action_bar_subtitle_bottom_margin_material  +abc_action_bar_subtitle_

and most of the time its text weirder than that and cant be read.
if i run the application it will work just fine though.

FYI this file is gradle project

this is xml file.. this is not the one i wrote but if open it in file explorer it will be different.

"logs": [
    {
        "outputFile": "C:\\Users\\saadm\\OneDrive\\Desktop\\flowers\\app\\build\\intermediates\\incremental\\mergeDebugResources\\merged.dir\\values-en-rCA\\values-en-rCA.xml",
        "map": [
            {
                "source": "D:\\Users\\saadm\\.gradle\\caches\\transforms-2\\files-2.1\\331630a23dfa1f0594bcf54d5352aa36\\core-1.1.0\\res\\values-en-rCA\\values-en-rCA.xml",
                "from": {
                    "startLines": "2",
                    "startColumns": "4",


问:
Why doesn't my delete button work in PHP?
I'm just starting out with PHP and am a bit lost. I feel like it's probably something small I'm missing but when I click the delete button it does not work. It doesn't give me any errors, the button just clicks and does nothing. Any ideas why? I've spent hours trying to figure it out but I have come up with nothing. I've done add user and show users in much the same way and it works but this has me stumped. Thanks in advance :)

users.controller.php

```<code>static public function DeleteUserController(){

        if(isset($_GET["userId"])){

            $table ="users";
            $data = $_GET["userId"];
            var_dump($data);
            $answer = UserModel::DeleteUserModel($table, $data);

            if($answer == "ok"){

                echo'<script>

                swal({
                      type: "success",
                      title: "User has been Deleted",
                      showConfirmButton: true,
                      confirmButtonText: "Close"

                      }).then(function(result){

                        if (result.value) {

                        window.location = "users";

                        }
                    })

                </script>';

            }

        }

    }
</code>```

users.model.php

```<code>static public function DeleteUserModel($table, $data){

        $stmt = Connection::connect()->prepare("DELETE FROM $table WHERE id = :id");

        $stmt -> bindParam(":id", $data, PDO::PARAM_STR);

        if ($stmt->execute()) {

            return 'ok';

        } else {

            return 'error';

        }

        $stmt -> close();

        $stmt = null;
    }
</code>```

users.js

```<code>$(".btnDeleteUser").click(function(){
    var userId = $(this).attr("userId");
    var username = $(this).attr("username");

    swal({
        title: 'Are you sure you want to delete user?',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          cancelButtonText: 'Cancel',
          confirmButtonText: 'Confirm'
        }).then((result)=>{

        if(result.value){

          window.location = "index.php?route=users&userId="+userId+"&username="+username;

        }

    })

})

</code>```

users.php

```<code><button class="btn btn-danger btnDeleteUser" userId="'.$value["id"].'" username="'.$value["user"].'"><i class="fa fa-times"></i></button>
</code>```

users.php

```<code><?php

  $deleteUser = new ControllerUsers();
  $deleteUser -> DeleteUserController();

?>
</code>```

index.php

```<code><?php

require_once "controllers/template.controller.php";
require_once "controllers/products.controller.php";
require_once "controllers/sales.controller.php";
require_once "controllers/users.controller.php";

require_once "models/products.model.php";
require_once "models/sales.model.php";
require_once "models/users.model.php";

$template = new TemplateController();
$template -> tempController();
</code>```

答:
I see a few issues going on in this script that we can start with. First, it's public static function, not static public function as per the documentation, php Static. Next, you are instantiating the ControllerUsers with new ControllerUsers() and calling the DeleteUserController as an instantiated method. When you use static methods or variables, you do not instantiate the class, you call it directly using ControllerUsers::DeleteUserController(). Again, see php Static from above. That's the purpose of using static methods, you can call them without instantiating a class.

My recommendation is to not use static methods at all when you are first learning PHP unless you are familiar with other programming languages and their use of Static Methods. Static methods are generally frowned upon and have limited real world use anyway, so it's best to instantiate the class and work with methods that way instead.

Anyway, back to the script. When you are creating a program to delete a user, it is more accepted to use POST instead of GET, as it does not transfer data in the URL, which makes it more secure. I would recommend switching to a POST action instead of a GET action.

Also, can you post the index.php file? I am curious to see how these routes work in the context of your program.

Let's start with these before continuing.

Update:

So, if you click the Delete User Button and nothing happens, not even any errors, there can be a few different reasons for that. The first big one is that the users.js file has not been added to the page that has the Delete User button, so make sure that it's been added to that page.

Next, you need to make sure that the page is loaded before using the click function in Jquery. Check here for reference, Jquery Click.

For me personally, I have had issues using the .click method in Jquery, so I normally use the .on method instead. It's a newer method with better functionality, I've found, so give it a try as well. An example can be found in Jquery Click from above as well for you.

Body:
I'm just starting out with PHP and am a bit lost. I feel like it's probably something small I'm missing but when I click the delete button it does not work. It doesn't give me any errors, the button just clicks and does nothing. Any ideas why? I've spent hours trying to figure it out but I have come up with nothing. I've done add user and show users in much the same way and it works but this has me stumped. Thanks in advance :)

users.controller.php

static public function DeleteUserController(){

        if(isset($_GET["userId"])){

            $table ="users";
            $data = $_GET["userId"];
            var_dump($data);
            $answer = UserModel::DeleteUserModel($table, $data);

            if($answer == "ok"){

                echo'';

            }

        }

    }

users.model.php

static public function DeleteUserModel($table, $data){

        $stmt = Connection::connect()->prepare("DELETE FROM $table WHERE id = :id");

        $stmt -> bindParam(":id", $data, PDO::PARAM_STR);

        if ($stmt->execute()) {

            return 'ok';

        } else {

            return 'error';

        }

        $stmt -> close();

        $stmt = null;
    }

users.js

$(".btnDeleteUser").click(function(){
    var userId = $(this).attr("userId");
    var username = $(this).attr("username");

    swal({
        title: 'Are you sure you want to delete user?',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          cancelButtonText: 'Cancel',
          confirmButtonText: 'Confirm'
        }).then((result)=>{

        if(result.value){

          window.location = "index.php?route=users&userId="+userId+"&username="+username;

        }

    })

})

users.php

<button class="btn btn-danger btnDeleteUser" userId="'.$value["id"].'" username="'.$value["user"].'"></button>

users.php

<?php

  $deleteUser = new ControllerUsers();
  $deleteUser -> DeleteUserController();

?>

index.php

<?php

require_once "controllers/template.controller.php";
require_once "controllers/products.controller.php";
require_once "controllers/sales.controller.php";
require_once "controllers/users.controller.php";

require_once "models/products.model.php";
require_once "models/sales.model.php";
require_once "models/users.model.php";

$template = new TemplateController();
$template -> tempController();


问:
How to create a new branch under feature branch using Git commands?
For example, I have a branch named /feature and I wanted to create a new feature branch under it, like feature/MyTask-01.

I tried using command git branch feature/MyTask-01 but it always gives me this error:

```<code>$ git branch feature/My-Task-01
fatal: cannot lock ref 'refs/heads/feature/My-Task-01`: 'refs/heads/feature' exists; cannot create 'refs/heads/feature/My-Task-01'
</code>```

答:
Git stores branches in refs/heads/.

Creating a branch branch feature stores a file: refs/heads/feature.

Creating a branch feature/abc attempts to store a file refs/heads/feature/abc.

Both cannot be possible, since refs/heads/feature would need to be a file and a folder at the same time.

To resolve this, either

delete the feature branch and stick to using feature/x, or

call your second branch something which doesn't attempt to create the feature/ folder, such as feature_x.

Body:
For example, I have a branch named /feature and I wanted to create a new feature branch under it, like feature/MyTask-01.

I tried using command git branch feature/MyTask-01 but it always gives me this error:

$ git branch feature/My-Task-01
fatal: cannot lock ref 'refs/heads/feature/My-Task-01`: 'refs/heads/feature' exists; cannot create 'refs/heads/feature/My-Task-01'


问:
Button can't be clicked while keyboard is visible - react native
I have an textInput and a button. While the textInput is focused, the keyboard comes up but if you tap the button with keyboard visible, first the keyboard disappears and then only you can tap button. Why is it? How can I make it work so that the button can be tapped with keyboard visible? The apps developed in android studio (android native) can get the click listener with keyboard visible. But in react native, it is not working. If you tap anywhere but button, then the keyboard should disappear, isn't it? But if you tap on the button with keyboard visible, the btn should receive the listener. I'm testing it in android devices.

P.S you can try it here: https://snack.expo.io/@codebyte99/addcomponents

```<code><TextInput
    placeholder={'Type smth'}
    style={[{ borderBottomColor: 'gray', borderBottomWidth: 1 }]}
/>

<TouchableOpacity onPress={() => { this._onPressOut(); }}>
  <Text>click here</Text>
</TouchableOpacity>
</code>```

答:
As an addition to @thakur-karthik answer:

It's very important to note that in the scrollview scenario, some oddity occurs when you have a scrollview in a react-native modal.

Just adding keyboardShouldPersistTaps={'always'} on the scrollview in the modal alone will not work.

If you have scrollviews in any ancestors, they must also have keyboardShouldPersistTaps={'always'} declared on their components

Body:
I have an textInput and a button. While the textInput is focused, the keyboard comes up but if you tap the button with keyboard visible, first the keyboard disappears and then only you can tap button. Why is it? How can I make it work so that the button can be tapped with keyboard visible? The apps developed in android studio (android native) can get the click listener with keyboard visible. But in react native, it is not working. If you tap anywhere but button, then the keyboard should disappear, isn't it? But if you tap on the button with keyboard visible, the btn should receive the listener. I'm testing it in android devices.

P.S you can try it here: https://snack.expo.io/@codebyte99/addcomponents

<TextInput
    placeholder={'Type smth'}
    style={[{ borderBottomColor: 'gray', borderBottomWidth: 1 }]}
/>

<TouchableOpacity onPress={() => { this._onPressOut(); }}>
  <Text>click here</Text>
</TouchableOpacity>


问:
NodeJS, MIME type ('text/html') is not a supported stylesheet MIME type
Everytime I connect to my local server on Google Chrome, I get this error :

Refused to apply style from 'http://localhost:2000/app.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

I can access my css file by typing its path so the problem doesn't come from there.
I also searched for informations about this topic but nothing worked.

Here's my code

Server Side

```<code>const Game = require("./class/game");
const express = require("express");
const app = express();
const serv = require("http").Server(app);

// Server
app.get("/", function(req, res) {
    res.sendFile(__dirname + "/client/index.html");
});
app.use("/client", express.static(__dirname + "/client"));

serv.listen(2000);
console.log("Server started on port 2000");

var io = require("socket.io")(serv, {});
io.sockets.on("connection", function(socket) {
    console.log("Connection done");
});
</code>```

Client side

HTML

```<code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
    <link rel="stylesheet" type="text/css" href="./app.css">
    <title>Games</title>
</head>

<script>
    var socket = io();
</script>

<body>
    test
</body>

</html>
</code>```

CSS

```<code>* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background-color: aquamarine;
}
</code>```

答:
app.css should be served from /client dir. Change href as below

href="/client/app.css">

In your case browser is not able to found the app.css and browser might be receiving a similar response as below

Which is clearly not a valid response and Mime-type for CSS file. That's why you are getting the above error.

As you have defined static content to be served as below

```<code>app.use("/client", express.static(__dirname + "/client"));
</code>```

Changing href /app.css to /client/app.css will solve your issue provided app.css is present in that directory.

Body:
Everytime I connect to my local server on Google Chrome, I get this error :

Refused to apply style from 'http://localhost:2000/app.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

I can access my css file by typing its path so the problem doesn't come from there.
I also searched for informations about this topic but nothing worked.

Here's my code

Server Side

const Game = require("./class/game");
const express = require("express");
const app = express();
const serv = require("http").Server(app);

// Server
app.get("/", function(req, res) {
    res.sendFile(__dirname + "/client/index.html");
});
app.use("/client", express.static(__dirname + "/client"));

serv.listen(2000);
console.log("Server started on port 2000");

var io = require("socket.io")(serv, {});
io.sockets.on("connection", function(socket) {
    console.log("Connection done");
});

Client side

HTML

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link rel="stylesheet" type="text/css" href="./app.css">
    <title>Games</title>

    test

CSS

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background-color: aquamarine;
}

Body:
app.css should be served from /client dir. Change href as below

href="/client/app.css">

In your case browser is not able to found the app.css and browser might be receiving a similar response as below

Which is clearly not a valid response and Mime-type for CSS file. That's why you are getting the above error.

As you have defined static content to be served as below

app.use("/client", express.static(__dirname + "/client"));

Changing href /app.css to /client/app.css will solve your issue provided app.css is present in that directory.


问:
What does the fdim acronym stand for?
All C math functions seems to have an understandable name, but I can't find what the fdim acronym stands for.
(fdim computes the positive difference of it two floating-point inputs).</p>

答:
I searched the ISO-C working group's document archive, and noticed that most of the proposals for the floating-point enhancements to what would become C99 were contributed by Jim Thomas. Best I can tell, fdim was included in the draft new standard prior to 1996, and unfortunately the archive does not provide links to electronic copies for proposals from that time.

So I contacted Mr. Thomas directly via email and received a response, the relevant portion of which I quote here with his permission:

From: Jim Thomas

  To: Norbert Juffa

  Time: Sat 2/15/2020 8:42 AM

  Subject: Re: Naming of, and rationale for, the fdim() function in ISO-C99

  [...]

  The C fdim function is the C versions for the Fortran DIM (positive difference) function. The C function, and its name, were intended for programmers porting code form Fortran to C.

This confirms the linkage with Fortran alluded to in comments. As for the name DIM itself, Ctx's answer addresses this as well as one could hope for in the case of a minor function that has been around for fifty years.

In comments below the question, Mark Dickinson pointed to the Fortran 66 standard, which on page 23 defined Fortran's DIM function as a₁ - Min (a₁, a₂). This provides further evidence that the name DIM is a contraction of DIfference and Minimum.

Title: What does the fdim acronym stand for?


问:
How to disable Bootstrap's html,body attribute overriding?
Imports

```<code> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
      <link rel="stylesheet" type="text/css" href="resources/css/style.css">
      <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.css">
      <link href="https://fonts.googleapis.com/css?family=Lato:100,300,400,300italic" rel="stylesheet">
</code>```

I defined main properties for my css classes as a parent class like below.Especially to make it easier for media queries.

```<code>html,body{
    background-color: #ffffff;
    color: #555;
    font-family:'Lato' ,'Arial',sans-serif;
    font-weight:300;
    font-size:20px;
    text-rendering: optimizeLegibility;
}
</code>```

But bootstrap overrides all these properties.For example I have code below but doesn't come with 300 font-weight.Instead of it,comes with 500 font-weight.

```<code>  <div class="container">
            <div class="row">
                <h1>Goodbye junk food.<br>Hello super healthy meals.</h1>
              </div>
          </div>
</code>```

I want to specify font-weight through parent class which has 300 in my example like below

```<code>h1{
    color:#fff;
    font-weight: 90%;
}
</code>```

But it doesn't work bootstrap overrides everything

答:
In your index.html file:

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

Put your styles below bootstrap.css import. Last ones overrides styles above.

Edit

You should override specific types again. If it were what you thought; your

```<code>color: #555;
</code>```

should override all color classes in bootstrap.

```<code>html,body {
    background-color: #ffffff;
    color: #555;
    font-size:20px;
    font-family:'Lato' ,'Arial',sans-serif;
    text-rendering: optimizeLegibility;
}

.container,
h1 {
    font-weight:300;
}
</code>```

OR

You can customize and download bootstrap.css

bootstrap.build

bootstrapcustomizer

Body:
Imports

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
      <link rel="stylesheet" type="text/css" href="resources/css/style.css">
      <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.css">
      <link href="https://fonts.googleapis.com/css?family=Lato:100,300,400,300italic" rel="stylesheet">

I defined main properties for my css classes as a parent class like below.Especially to make it easier for media queries.

html,body{
    background-color: #ffffff;
    color: #555;
    font-family:'Lato' ,'Arial',sans-serif;
    font-weight:300;
    font-size:20px;
    text-rendering: optimizeLegibility;
}

But bootstrap overrides all these properties.For example I have code below but doesn't come with 300 font-weight.Instead of it,comes with 500 font-weight.

Goodbye junk food.
Hello super healthy meals.

I want to specify font-weight through parent class which has 300 in my example like below

h1{
    color:#fff;
    font-weight: 90%;
}

But it doesn't work bootstrap overrides everything

Body:
In your index.html file:

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

Put your styles below bootstrap.css import. Last ones overrides styles above.

Edit

You should override specific types again. If it were what you thought; your

color: #555;

should override all color classes in bootstrap.

html,body {
    background-color: #ffffff;
    color: #555;
    font-size:20px;
    font-family:'Lato' ,'Arial',sans-serif;
    text-rendering: optimizeLegibility;
}

.container,
h1 {
    font-weight:300;
}

OR

You can customize and download bootstrap.css

bootstrap.build

bootstrapcustomizer


问:
Apparent inconsistency during type casting in C++ (and C)
By any chance can anyone explain the output here? I have been trying to understand why type casting a literal is having a result different from type casting a variable in this code.

```<code>#include <iostream>
#include <cstdint>

using namespace std;

int main()
{
    double intermediate;
    intermediate = -1.0;
    cout << "intermediate = " << intermediate << endl;
    cout << "uint64_t(intermediate) = " << uint64_t(intermediate) << endl;
    cout << "uint64_t((double)(-1)) = " << uint64_t((double)(-1)) << endl;

    return 0;
}
</code>```

The output I get is:

```<code>intermediate = -1
uint64_t(intermediate) = 18446744073709551615
uint64_t((double)(-1)) = 0
</code>```

答:
You're performing an out-of-range conversion from a floating point type to an integer type.

Since the double value -1.0 cannot fit in a uint64_t, this is considered an out-of-range conversion.  Such a conversion invokes undefined behavior.  This means, among other things, that the two attempts at conversion need not produce the same results.

Note that this differs from signed integer to unsigned integer conversion which is well defined in all cases.

This is dictated by 7.10p1 of the C++17 standard:

A prvalue of a floating-point type can be converted to a prvalue of an
  integer type. The conversion truncates;that is, the fractional part is
  discarded. The behavior is undefined if the truncated value cannot be
  represented in the destination type.

Section 6.3.1.4p1 of the C11 standard has similar language:

When a finite value of real floating type is converted to an integer
  type other than _Bool, the  fractional  part  is  discarded  (i.e.,
  the  value  is  truncated  toward  zero).  If  the  value  of the
  integral part cannot be represented by the integer type, the behavior
  is undefined. 61)

...

61)   The  remaindering  operation  performed  when  a  value  of
  integer  type  is  converted  to  unsigned  type need  not  be
  performed  when  a  value  of  real  floating  type  is  converted  to
  unsigned  type.  Thus,  the range of portable real floating values is
  (−1,Utype_MAX+1)

To get a consistent result, you would first need to cast to a signed integer type, then an unsigned type.

```<code>cout << "uint64_t(intermediate) = " <<
        static_cast<uint64_t>(static_cast<int>(intermediate)) << endl;
</code>```

For C:

```<code>printf("uint64_t(intermediate) = %llu\n", (uint64_t)(int)intermediate);
</code>```

Body:
By any chance can anyone explain the output here? I have been trying to understand why type casting a literal is having a result different from type casting a variable in this code.

#include <iostream>
#include <cstdint>

using namespace std;

int main()
{
    double intermediate;
    intermediate = -1.0;
    cout << "intermediate = " << intermediate << endl;
    cout << "uint64_t(intermediate) = " << uint64_t(intermediate) << endl;
    cout << "uint64_t((double)(-1)) = " << uint64_t((double)(-1)) << endl;

    return 0;
}

The output I get is:

intermediate = -1
uint64_t(intermediate) = 18446744073709551615
uint64_t((double)(-1)) = 0

Body:
You're performing an out-of-range conversion from a floating point type to an integer type.

Since the double value -1.0 cannot fit in a uint64_t, this is considered an out-of-range conversion.  Such a conversion invokes undefined behavior.  This means, among other things, that the two attempts at conversion need not produce the same results.

Note that this differs from signed integer to unsigned integer conversion which is well defined in all cases.

This is dictated by 7.10p1 of the C++17 standard:

A prvalue of a floating-point type can be converted to a prvalue of an
  integer type. The conversion truncates;that is, the fractional part is
  discarded. The behavior is undefined if the truncated value cannot be
  represented in the destination type.

Section 6.3.1.4p1 of the C11 standard has similar language:

When a finite value of real floating type is converted to an integer
  type other than _Bool, the  fractional  part  is  discarded  (i.e.,
  the  value  is  truncated  toward  zero).  If  the  value  of the
  integral part cannot be represented by the integer type, the behavior
  is undefined. 61)

...

61)   The  remaindering  operation  performed  when  a  value  of
  integer  type  is  converted  to  unsigned  type need  not  be
  performed  when  a  value  of  real  floating  type  is  converted  to
  unsigned  type.  Thus,  the range of portable real floating values is
  (−1,Utype_MAX+1)

To get a consistent result, you would first need to cast to a signed integer type, then an unsigned type.

cout << "uint64_t(intermediate) = " <<
        static_cast<uint64_t>(static_cast<int>(intermediate)) << endl;

For C:

printf("uint64_t(intermediate) = %llu\n", (uint64_t)(int)intermediate);


问:
Find matching sequence between two arrays (pattern matching) C#
I have two arrays, one is a main array I am comparing against, and the second array has a number of integers whose order might be shifted to the right or left and it also might contain default values.

The result (true/false) of this comparison looks like this:

```<code>x = -9; //unknown number

int[] mainArray = new int[]{3,1,0,1};

int[] a = new int[]{x,x,x,x}; // true
int[] b = new int[]{x,x,1,x}; // true
int[] c = new int[]{x,x,1,0}; // true
int[] d = new int[]{x,x,1,0}; // true
int[] e = new int[]{x,3,1,0}; // true
int[] f = new int[]{1,3,1,0}; // true
int[] g = new int[]{3,1,0,x}; // true
int[] h = new int[]{3,1,1,0}; // false
int[] i = new int[]{x,1,1,x}; // false
int[] j = new int[]{0,1,1,x}; // false
int[] k = new int[]{3,1,x,x}; // true
</code>```

What would be the a way to search if the sequence exists in the main array?
There are two problem I cannot figure out:
1) the array might be shifted to the right or left, but the result is true even if it is shifted
2) the x value which is skipped in comparison

I end up in doing lots of if statements, but I am sure this problem was solved elegantly by someone else.

答:
Idea: convert the input to a string and duplicate it, so that it contains shifted variants:

```<code>{ 3, 1, 0, 1 } ==> ",3,1,0,1,3,1,0,1,"
</code>```

Convert the pattern array to a regular expression. Every x is replaced by \d+, which means one or more digits:

```<code>{ 3, 1, x, x } ==> ",3,1,\d+,\d+,"
</code>```

And then compare.

```<code>string inputAsString = String.Join(",", mainArray) + ",";
inputAsString = "," + inputAsString + inputAsString;

string pattern =
    "," + String.Join(",", input.Select(i => i == x ? @"\d+" : i.ToString())) + ",";

bool result = Regex.IsMatch(inputAsString, pattern);
</code>```

Where input is one of your arrays a to k.

Here is a version which tells you by how much the array was shifted. To do this we format the numbers, so that they all have the same length. This allows us to calculate the shift from the position of the match in the input string.

```<code>const int x = -9; //unknown number

int[] mainArray = new int[] { 3, 1, 0, 1 };

int[][] inputs = new[]{ //        is match, shift
        new int[] { x, x, x, x }, // true    0
        new int[] { x, x, 1, x }, // true    1
        new int[] { x, x, 1, 0 }, // true    1
        new int[] { x, x, 1, 0 }, // true    1
        new int[] { x, 3, 1, 0 }, // true    1
        new int[] { 1, 3, 1, 0 }, // true    1
        new int[] { 3, 1, 0, x }, // true    0
        new int[] { 3, 1, 1, 0 }, // false
        new int[] { x, 1, 1, x }, // false
        new int[] { 0, 1, 1, x }, // false
        new int[] { 3, 1, x, x },  // true   1
        //-------- all possible shifts:
        new int[] { 3, 1, 0, 1 },  // true   0 <=> -4
        new int[] { 1, 3, 1, 0 },  // true   1 <=> -3
        new int[] { 0, 1, 3, 1 },  // true   2 <=> -2
        new int[] { 1, 0, 1, 3 },  // true   3 <=> -1
};

const int digits = 3;
string format = new String('0', digits);
string inputAsString =
    String.Join(",", mainArray.Select(i => i.ToString(format))) + ",";
inputAsString = "," + inputAsString + inputAsString;
Console.WriteLine($"inputAsString = \"{inputAsString}\"");
foreach (int[] input in inputs) {
    string pattern =
        "," + String.Join(",", input.Select(i => i == x ? @"\d+" : i.ToString(format))) + ",";

    var match = Regex.Match(inputAsString, pattern);
    int shift = -match.Index / (digits + 1);
    if (shift <= -input.Length / 2) {
        shift += input.Length;
    }
    Console.WriteLine($"match = \"{match.Value}\", success = {match.Success}, index = {match.Index}, shift = {shift}");
}
</code>```

This version also writes some test output to the console.

Body:
I have two arrays, one is a main array I am comparing against, and the second array has a number of integers whose order might be shifted to the right or left and it also might contain default values.

The result (true/false) of this comparison looks like this:

x = -9; //unknown number

int[] mainArray = new int[]{3,1,0,1};

int[] a = new int[]{x,x,x,x}; // true
int[] b = new int[]{x,x,1,x}; // true
int[] c = new int[]{x,x,1,0}; // true
int[] d = new int[]{x,x,1,0}; // true
int[] e = new int[]{x,3,1,0}; // true
int[] f = new int[]{1,3,1,0}; // true
int[] g = new int[]{3,1,0,x}; // true
int[] h = new int[]{3,1,1,0}; // false
int[] i = new int[]{x,1,1,x}; // false
int[] j = new int[]{0,1,1,x}; // false
int[] k = new int[]{3,1,x,x}; // true

What would be the a way to search if the sequence exists in the main array?
There are two problem I cannot figure out:
1) the array might be shifted to the right or left, but the result is true even if it is shifted
2) the x value which is skipped in comparison

I end up in doing lots of if statements, but I am sure this problem was solved elegantly by someone else.

Body:
Idea: convert the input to a string and duplicate it, so that it contains shifted variants:

{ 3, 1, 0, 1 } ==> ",3,1,0,1,3,1,0,1,"

Convert the pattern array to a regular expression. Every x is replaced by \d+, which means one or more digits:

{ 3, 1, x, x } ==> ",3,1,\d+,\d+,"

And then compare.

string inputAsString = String.Join(",", mainArray) + ",";
inputAsString = "," + inputAsString + inputAsString;

string pattern =
    "," + String.Join(",", input.Select(i => i == x ? @"\d+" : i.ToString())) + ",";

bool result = Regex.IsMatch(inputAsString, pattern);

Where input is one of your arrays a to k.

Here is a version which tells you by how much the array was shifted. To do this we format the numbers, so that they all have the same length. This allows us to calculate the shift from the position of the match in the input string.

const int x = -9; //unknown number

int[] mainArray = new int[] { 3, 1, 0, 1 };

int[][] inputs = new[]{ //        is match, shift
        new int[] { x, x, x, x }, // true    0
        new int[] { x, x, 1, x }, // true    1
        new int[] { x, x, 1, 0 }, // true    1
        new int[] { x, x, 1, 0 }, // true    1
        new int[] { x, 3, 1, 0 }, // true    1
        new int[] { 1, 3, 1, 0 }, // true    1
        new int[] { 3, 1, 0, x }, // true    0
        new int[] { 3, 1, 1, 0 }, // false
        new int[] { x, 1, 1, x }, // false
        new int[] { 0, 1, 1, x }, // false
        new int[] { 3, 1, x, x },  // true   1
        //-------- all possible shifts:
        new int[] { 3, 1, 0, 1 },  // true   0 <=> -4
        new int[] { 1, 3, 1, 0 },  // true   1 <=> -3
        new int[] { 0, 1, 3, 1 },  // true   2 <=> -2
        new int[] { 1, 0, 1, 3 },  // true   3 <=> -1
};

const int digits = 3;
string format = new String('0', digits);
string inputAsString =
    String.Join(",", mainArray.Select(i => i.ToString(format))) + ",";
inputAsString = "," + inputAsString + inputAsString;
Console.WriteLine($"inputAsString = \"{inputAsString}\"");
foreach (int[] input in inputs) {
    string pattern =
        "," + String.Join(",", input.Select(i => i == x ? @"\d+" : i.ToString(format))) + ",";

    var match = Regex.Match(inputAsString, pattern);
    int shift = -match.Index / (digits + 1);
    if (shift <= -input.Length / 2) {
        shift += input.Length;
    }
    Console.WriteLine($"match = \"{match.Value}\", success = {match.Success}, index = {match.Index}, shift = {shift}");
}

This version also writes some test output to the console.


问:
Exporting html table with dropdowns, to excel using jquery
I have a html table with a few cells containing dropdowns which I am trying to export to Excel using table2excel jquery plugin. The plugin exports all the cells except for the ones containing the select tag. How do I get around this problem?

Sample html:

```<code><!DOCTYPE html>
<html>
<head>
    <script type="javascript">
        var tableToExcel = (function() {
        var uri = 'data:application/vnd.ms-excel;base64,'
        , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
        , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
        , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
        return function(table, name) {
        if (!table.nodeType) table = document.getElementById(table)
        var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
        window.location.href = uri + base64(format(template, ctx))
        }
        })()
    </script>
</head>
<body>

<input type="button" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel">

<table id="testTable" summary="Sample tabe to export to excel" rules="groups" frame="hsides" border="2">
    <thead valign="top">
    <tr>
        <th>Col1</th>
        <th>Col2</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>Value1</td>
        <td>
            <select>
                <option value="option1">Option 1</option>
                <option value="option2" selected="selected">Option 2</option>
            </select>
        </td>
    </tr>
    </tbody>
</table>

</body>
</html>
</code>```

答:
You can generate a table HTML dynamically, so you can format the cell as per your need

var tableToExcel = (function() {
  var uri = "data:application/vnd.ms-excel;base64,",
    template =
      '
{table}
',
    base64 = function(s) {
      return window.btoa(unescape(encodeURIComponent(s)));
    },
    format = function(s, c) {
      return s.replace(/{(\w+)}/g, function(m, p) {
        return c[p];
      });
    };
  return function(table, name) {
    if (!table.nodeType) table = document.getElementById(table);
    var ctx = { worksheet: name || "Worksheet", table: generateTable(table) };
    window.location.href = uri + base64(format(template, ctx));
  };
})();
function generateTable(table) {
  let innerHTML = `

            ${Array.from(table.querySelectorAll("thead th ")).map(function(
              columnHeader
            ) {
              return `<th>${columnHeader.innerText}</th>`;
            }).join('')}

          ${Array.from(table.querySelectorAll("tbody tr ")).map(
            function(row) {
              return `

                        ${Array.from(row.querySelectorAll("td")).map(
                          function(cell) {
                            let text = "";
                            Array.from(cell.childNodes).forEach(childNode => {
                              switch (childNode.nodeType) {
                                case 1: {
                                  if (
                                    childNode.nodeName === "SELECT" ||
                                    childNode.nodeName === "INPUT"
                                  ) {
                                    text = text + childNode.value;
                                  }
                                  break;
                                }
                                case 3: {
                                  text = text + childNode.textContent;

                                  break;
                                }
                              }
                            });

                            return `<td>${text}</td>`;
                          }
                        ).join("")}
`;
            }
          ).join("")}

      `;
  console.log(innerHTML);
  return innerHTML;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <script type="javascript">
    </script>
</head>

<body>

  <input type="button" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel">

  <table id="testTable" summary="Sample tabe to export to excel" rules="groups" frame="hsides" border="2">
    <thead valign="top">
      <tr>
        <th>Col1</th>
        <th>Col2</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Value1</td>
        <td>
          <select>
            <option value="option1">Option 1</option>
            <option value="option2" selected="selected">Option 2</option>
          </select>
        </td>
      </tr>
    </tbody>
  </table>

</body>

</html></code>```

Body:
I have a html table with a few cells containing dropdowns which I am trying to export to Excel using table2excel jquery plugin. The plugin exports all the cells except for the ones containing the select tag. How do I get around this problem?

Sample html:

<!DOCTYPE html>

<input type="button" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel">

        Col1
        Col2

        Value1

            <select>
                <option value="option1">Option 1</option>
                <option value="option2" selected="selected">Option 2</option>
            </select>

Body:
You can generate a table HTML dynamically, so you can format the cell as per your need

var tableToExcel = (function() {
  var uri = "data:application/vnd.ms-excel;base64,",
    template =
      '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
    base64 = function(s) {
      return window.btoa(unescape(encodeURIComponent(s)));
    },
    format = function(s, c) {
      return s.replace(/{(\w+)}/g, function(m, p) {
        return c[p];
      });
    };
  return function(table, name) {
    if (!table.nodeType) table = document.getElementById(table);
    var ctx = { worksheet: name || "Worksheet", table: generateTable(table) };
    window.location.href = uri + base64(format(template, ctx));
  };
})();
function generateTable(table) {
  let innerHTML = `
        <thead  valign="top">
          <tr>
            ${Array.from(table.querySelectorAll("thead th ")).map(function(
              columnHeader
            ) {
              return `<th>${columnHeader.innerText}</th>`;
            }).join('')}
           </tr>
        </thead>
        <tbody>
          ${Array.from(table.querySelectorAll("tbody tr ")).map(
            function(row) {
              return `<tr>
                        ${Array.from(row.querySelectorAll("td")).map(
                          function(cell) {
                            let text = "";
                            Array.from(cell.childNodes).forEach(childNode => {
                              switch (childNode.nodeType) {
                                case 1: {
                                  if (
                                    childNode.nodeName === "SELECT" ||
                                    childNode.nodeName === "INPUT"
                                  ) {
                                    text = text + childNode.value;
                                  }
                                  break;
                                }
                                case 3: {
                                  text = text + childNode.textContent;

                                  break;
                                }
                              }
                            });

                            return `<td>${text}</td>`;
                          }
                        ).join("")}</tr>`;
            }
          ).join("")}
        </tbody>
      `;
  console.log(innerHTML);
  return innerHTML;
}

<!DOCTYPE html>
<html>

<head>
  <script type="javascript">
    </script>
</head>

<body>

  <input type="button" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel">

  <table id="testTable" summary="Sample tabe to export to excel" rules="groups" frame="hsides" border="2">
    <thead valign="top">
      <tr>
        <th>Col1</th>
        <th>Col2</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Value1</td>
        <td>
          <select>
            <option value="option1">Option 1</option>
            <option value="option2" selected="selected">Option 2</option>
          </select>
        </td>
      </tr>
    </tbody>
  </table>

</body>

</html>


问:
Cannot set headers after they are sent to the client axios next.js

Same question on GitHub - https://github.com/axios/axios/issues/2743

I have Axios in my Next.js project and sometimes I get an error due to interceptor when return the Promise.reject.

Error: Cannot set headers after they are sent to the client.

I encounter this problem when I make a request in getInitialProps. This happens very rarely when I restart the PC and open the page again.

Axios instance:

```<code>const instance = axios.create({
  baseURL: 'https://my-api.com',
  withCredentials: true,
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
  },
})

instance.interceptors.response.use(undefined, error => {
  if (error.response.status === 401) {
    console.log("UNAUTHORIZED")
  }
  return Promise.reject(error) // <-- this cause the problem
})
</code>```

Next.js Page example:

```<code>const Index = ({myData}) => {
  return data.map(...)
}

Index.getInitialProps = async ({req}) => {
  let myData

  try {
    const res = await API.get('/my-request', {
      headers: req ? { cookie: req.headers.cookie } : undefined, //setting cookie
    })
    myData = res.data
  } catch (e) {}

  return {myData}
}
</code>```

答: This problem disappeared when I upgraded Axios 0.19.0 to 0.19.2  ¯_(ツ)_/¯</p>

Body:
Same question on GitHub - https://github.com/axios/axios/issues/2743

I have Axios in my Next.js project and sometimes I get an error due to interceptor when return the Promise.reject.

Error: Cannot set headers after they are sent to the client.

I encounter this problem when I make a request in getInitialProps. This happens very rarely when I restart the PC and open the page again.

Axios instance:

const instance = axios.create({
  baseURL: 'https://my-api.com',
  withCredentials: true,
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
  },
})

instance.interceptors.response.use(undefined, error => {
  if (error.response.status === 401) {
    console.log("UNAUTHORIZED")
  }
  return Promise.reject(error) // <-- this cause the problem
})

Next.js Page example:

const Index = ({myData}) => {
  return data.map(...)
}

Index.getInitialProps = async ({req}) => {
  let myData

  try {
    const res = await API.get('/my-request', {
      headers: req ? { cookie: req.headers.cookie } : undefined, //setting cookie
    })
    myData = res.data
  } catch (e) {}

  return {myData}
}


问:
Schedule AWS EC2 Windows server restart
Is there a way to setup a restart of a windows server on AWS at certain times or days?
For example, every saturday at 3:00 do a full restart of the server.

Is that possible?

答:
Yes, it is possible. You can schedule your instance for a stop/start.

Please refer: https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-cloudwatch/

Title: Schedule AWS EC2 Windows server restart


问:
How to Optimize in Error to create react-app?
I'm getting this error when I run npx creat-react-app

```<code>@typescript-eslint/eslint-plugin@2.19.2: The engine "node" is incompatible with this module. Expected version "^8.10.0 || ^10.13.0 || >=11.10.1". Got "10.11.0
</code>```

brew is not work in MacOs Catalina
how i fix it ?

答:
According to the error your node version is 10.11.0, while create-react-app requires a version above or equal 10.13.0.

To fix it, update your node version (download here). Probably there are some known issues with yours when using CRA.

Body:
I'm getting this error when I run npx creat-react-app

@typescript-eslint/eslint-plugin@2.19.2: The engine "node" is incompatible with this module. Expected version "^8.10.0 || ^10.13.0 || >=11.10.1". Got "10.11.0

brew is not work in MacOs Catalina
how i fix it ?