问:
convert month-day-year into day-month-year using javascript
I'm trying to convert a MM/DD/YYYY date to a long date. So for example, 02/16/2020 would convert to something like 16/02/2020.

Is there a way to make this date conversion accurately?

答:
If you want a conversion just between the exact formats you have mentioned:

function dfConvert(f) {
  var farr = f.split("/");
  return `${farr[1]}/${farr[0]}/${farr[2]}`;
}

var input = "02/16/2020";
console.log(`input: ${input}`)
console.log(`output: ${dfConvert(input)}`);```
</div>
</div>
</p>

<ol start="2">
<li>If you want the actual date object and from that you want your mentioned format for some reason:</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function toDate(f) {
  var farr = f.split("/");
  return new Date(parseInt(farr[2]), parseInt(farr[0])-1, parseInt(farr[1]))
}

function dfConvert(f) {
  var d = toDate(f)
  var day = d.getDate()
  var month = (d.getMonth() + 1)
  var year = d.getFullYear()
  return `${((day.toString().length <= 1) ? "0": "")}${day}/${((month.toString().length <= 1) ? "0": "")}${month}/${year}`
}

var input = "02/16/2020"
console.log(`input: ${input}`)
console.log(`output: ${dfConvert(input)}`)</code>```

Hope it helps

Body:
If you want a conversion just between the exact formats you have mentioned:

function dfConvert(f) {
  var farr = f.split("/");
  return `${farr[1]}/${farr[0]}/${farr[2]}`;
}

var input = "02/16/2020";
console.log(`input: ${input}`)
console.log(`output: ${dfConvert(input)}`);

If you want the actual date object and from that you want your mentioned format for some reason:

function toDate(f) {
  var farr = f.split("/");
  return new Date(parseInt(farr[2]), parseInt(farr[0])-1, parseInt(farr[1]))
}

function dfConvert(f) {
  var d = toDate(f)
  var day = d.getDate()
  var month = (d.getMonth() + 1)
  var year = d.getFullYear()
  return `${((day.toString().length <= 1) ? "0": "")}${day}/${((month.toString().length <= 1) ? "0": "")}${month}/${year}`
}

var input = "02/16/2020"
console.log(`input: ${input}`)
console.log(`output: ${dfConvert(input)}`)

Hope it helps


来源: stackexchange

问:
Postcondition on a procedure doesn't prove even though the same condition is asserted and true at the end of procedure
The code looks like this:

spec:

```<code>type Some_Record_Type is private;

procedure Deserialize_Record_Y(Record: in out Some_Record_Type)
with Post => (
    if Status_OK then (
        ...
        other postconditions
        ...
        and then
        Record_Field_X_Count(Record) = Record_Field_X_Count(Record'Old)
        and then
        Record_Field_X(Record) = Record_Field_X(Record'Old)
    )
);

function Record_Field_X(Record: Some_Record_Type) return X_Unbounded_Array_Type;
function Record_Field_X_Count(Record: Some_Record_Type) return Natural;

</code>```

body:

```<code>type Some_Record_Type is
   record
      X_Count: Natural;
      X      : X_Bounded_Array_Type;
      Y_Count: Natural;
      Y      : Y_Bounded_Array_Type;
      ...
   end record;

function Record_Field_X(Record: Some_Record_Type) return X_Unbounded_Array_Type
is (
   ...
   a bit of logic based on values of other fields of Record
   ...
)

function Record_Field_X_Count(Record: Some_Record_Type) return Natural
is (Record.X_Count);

procedure Deserialize_Record_Y(Record: in out Some_Record_Type) is
    Old_Record: Some_Record_Type := Record with Ghost;
begin
    ...
    -- updates the Y field of the Record.
    -- Note that we annot pass Record.Y and have to pass
    -- the whole Record because Record is a private type
    -- and Deserialize_Record_Y is in public spec
    ...
    pragma Assert_And_Cut (
        Status_OK
        and then
        ...
        other postconditions
        ...
        and then
        Record_Field_X_Count(Record) = Record_Field_X_Count(Record_Old)
        and then
        Record_Field_X(Record) = Record_Field_X(Record_Old)
    )
end Deserialize_Record_Y;
</code>```

There are no proof errors in the body, the error is only on the spec:

postcondition might fail, cannot prove Record_Field_X(Record) = Record_Field_X(Record'Old)

'other postconditions' are identical between the spec and the Assert_And_Cut at the end of the procedure.

Note the the checks with simpler fields, like X_Count:

Record_Field_X_Count(Record) = Record_Field_X_Count(Record'Old)

do not cause gnatprove to complain.

There's quite a lot of work for the prover inside the procedure, so usually, when there's a problem proving the postcondition it helps to assert that condition at the end of the procedure to 'remind' the prover that this is important facts. Usually, this works, but in one case it doesn't for some reason.

What are my options here?

What might be possible causes of this?

Maybe I should just increase the RAM on the machine where I run the proover, so it won't lose the Record_Field_X(Record) = Record_Field_X(Record_Old) fact between the end of the procedure and its postcondition? (I'm currently doing this on a machine with 32GB ram which is used exclusively to run gnatprove, with --memlimit=32000 --prover=cvc4,altergo --steps=0)

Maybe there are some techniques I don't know?

Maybe the only option I have is the manual proof?

I'm using the spark community 2019 version.

答:
To summarize the comments, adding z3 to the provers with

```<code>--prover=cvc4,altergo,z3
</code>```

helped to solve the problem.

ContentLicense: CC BY-SA 4.0

Body:
The code looks like this:

spec:

type Some_Record_Type is private;

procedure Deserialize_Record_Y(Record: in out Some_Record_Type)
with Post => (
    if Status_OK then (
        ...
        other postconditions
        ...
        and then
        Record_Field_X_Count(Record) = Record_Field_X_Count(Record'Old)
        and then
        Record_Field_X(Record) = Record_Field_X(Record'Old)
    )
);

function Record_Field_X(Record: Some_Record_Type) return X_Unbounded_Array_Type;
function Record_Field_X_Count(Record: Some_Record_Type) return Natural;

body:

type Some_Record_Type is
   record
      X_Count: Natural;
      X      : X_Bounded_Array_Type;
      Y_Count: Natural;
      Y      : Y_Bounded_Array_Type;
      ...
   end record;

function Record_Field_X(Record: Some_Record_Type) return X_Unbounded_Array_Type
is (
   ...
   a bit of logic based on values of other fields of Record
   ...
)

function Record_Field_X_Count(Record: Some_Record_Type) return Natural
is (Record.X_Count);

procedure Deserialize_Record_Y(Record: in out Some_Record_Type) is
    Old_Record: Some_Record_Type := Record with Ghost;
begin
    ...
    -- updates the Y field of the Record.
    -- Note that we annot pass Record.Y and have to pass
    -- the whole Record because Record is a private type
    -- and Deserialize_Record_Y is in public spec
    ...
    pragma Assert_And_Cut (
        Status_OK
        and then
        ...
        other postconditions
        ...
        and then
        Record_Field_X_Count(Record) = Record_Field_X_Count(Record_Old)
        and then
        Record_Field_X(Record) = Record_Field_X(Record_Old)
    )
end Deserialize_Record_Y;

There are no proof errors in the body, the error is only on the spec:

postcondition might fail, cannot prove Record_Field_X(Record) = Record_Field_X(Record'Old)

'other postconditions' are identical between the spec and the Assert_And_Cut at the end of the procedure.

Note the the checks with simpler fields, like X_Count:

Record_Field_X_Count(Record) = Record_Field_X_Count(Record'Old)

do not cause gnatprove to complain.

There's quite a lot of work for the prover inside the procedure, so usually, when there's a problem proving the postcondition it helps to assert that condition at the end of the procedure to 'remind' the prover that this is important facts. Usually, this works, but in one case it doesn't for some reason.

What are my options here?

What might be possible causes of this?

Maybe I should just increase the RAM on the machine where I run the proover, so it won't lose the Record_Field_X(Record) = Record_Field_X(Record_Old) fact between the end of the procedure and its postcondition? (I'm currently doing this on a machine with 32GB ram which is used exclusively to run gnatprove, with --memlimit=32000 --prover=cvc4,altergo --steps=0)

Maybe there are some techniques I don't know?

Maybe the only option I have is the manual proof?

I'm using the spark community 2019 version.

Body:
To summarize the comments, adding z3 to the provers with

--prover=cvc4,altergo,z3

helped to solve the problem.


问:
Circular references with vals in Kotlin
In Kotlin, say I have data class A (val f: B) and data class B (val f: A). I want to initialize local var a: A and var b: B such that a.f is b and b.f is a. A.f and B.f must remain vals. Is this circular instantiation possible?

```<code>data class A(val f: B)

data class B(val f: A)

fun foo() {
    var a: A
    var b: B
    // instantiate a and b here with a.f == b and b.f == a ??
}
</code>```

答:
You can do it if you explicitly declare your self-referential val as Lazy:

```<code>sealed class MyData {
    data class A(val x: Int) : MyData()
    data class B(val x : Int, val rb: Lazy<MyData>) : MyData() {
        val r: MyData by rb
    }
}

fun <A : Any> rec(body: (Lazy<A>) -> A): A {
    lateinit var a: A
    a = body(lazy { a })
    return a
}

fun MyData.print(gas: Int): String = if (gas <= 0) "..." else
    when(this) {
        is MyData.A -> "A(x=$x)"
        is MyData.B -> {
            val rbString =
                if (rb.isInitialized())
                    r.print(gas - 1)
                else
                    "<thunk>"
            "B(x=$x, rb=$rbString)"
        }
    }

fun main() {
    val a = MyData.A(42)
    val b1 = MyData.B(1, lazy { a })
    println(b1.r) // Force value
    println(b1)
    val b2 = rec<MyData.B> { b2 -> MyData.B(1, b2) }
    println(b2.r.print(4))
}
</code>```

This prints

```<code>A(x=42)
B(x=1, rb=A(x=42))
B(x=1, rb=B(x=1, rb=B(x=1, rb=B(x=1, rb=...))))
</code>```

ContentLicense: CC BY-SA 3.0

Title: Circular references with vals in Kotlin

Body:
In Kotlin, say I have data class A (val f: B) and data class B (val f: A). I want to initialize local var a: A and var b: B such that a.f is b and b.f is a. A.f and B.f must remain vals. Is this circular instantiation possible?

data class A(val f: B)

data class B(val f: A)

fun foo() {
    var a: A
    var b: B
    // instantiate a and b here with a.f == b and b.f == a ??
}

Body:
You can do it if you explicitly declare your self-referential val as Lazy:

sealed class MyData {
    data class A(val x: Int) : MyData()
    data class B(val x : Int, val rb: Lazy<MyData>) : MyData() {
        val r: MyData by rb
    }
}

fun <A : Any> rec(body: (Lazy<A>) -> A): A {
    lateinit var a: A
    a = body(lazy { a })
    return a
}

fun MyData.print(gas: Int): String = if (gas <= 0) "..." else
    when(this) {
        is MyData.A -> "A(x=$x)"
        is MyData.B -> {
            val rbString =
                if (rb.isInitialized())
                    r.print(gas - 1)
                else
                    "<thunk>"
            "B(x=$x, rb=$rbString)"
        }
    }

fun main() {
    val a = MyData.A(42)
    val b1 = MyData.B(1, lazy { a })
    println(b1.r) // Force value
    println(b1)
    val b2 = rec<MyData.B> { b2 -> MyData.B(1, b2) }
    println(b2.r.print(4))
}

This prints

A(x=42)
B(x=1, rb=A(x=42))
B(x=1, rb=B(x=1, rb=B(x=1, rb=B(x=1, rb=...))))


问:
Shorting css when values are the same
How to short css if values are the same?

For example: how to unite this into one string (with one auto!important)?

*{width: auto!important}
*{height: auto!important}
```

It seems that I have seen such possibility (as a novelty) but can't find.

答:
You can short declaration to one:

```<code>*{
width: auto!important;
height: auto!important
}
</code>```

and you can short the value to one using css custom variable
so every time you wanna change the value  do it from one place:

```<code>:root{
--foo:auto!important;
}

*{
width:var(--foo);
height: var(--foo);
}
</code>```

Title: Shorting css when values are the same

Body:
How to short css if values are the same?

For example: how to unite this into one string (with one auto!important)?

*{width: auto!important}
*{height: auto!important}

It seems that I have seen such possibility (as a novelty) but can't find.

Body:
You can short declaration to one:

*{
width: auto!important;
height: auto!important
}

and you can short the value to one using css custom variable
so every time you wanna change the value  do it from one place:

:root{
--foo:auto!important;
}

*{
width:var(--foo);
height: var(--foo);
}


问:
Add new variable created with mutate_ to data frame instead of creating a tibble
My attempt to add a new column to a dataframe with mutate gave me a tibble with the new variable, but did not add the variable as a new column in the dataframe (which is what I want to do).

I have a data frame with a character variable, DRUG_GENERIC_NAME, and created a new logical variable, Ibuprofen by combining mutate and str_detect which will be TRUE when IBUPROFEN is contained in DRUG_GENERIC_NAME:

```<code>mutate(Drug_Table, DRUG_GENERIC_NAME, Ibuprofen = str_detect (Drug_Table$DRUG_GENERIC_NAME,"IBUPROFEN", negate = FALSE))
</code>```

The result was a tibble with the new variable Ibuprofen, but the code did not add the variable to the data frame Drug_Table. How can I use this code to add the new variable to the dataframe instead of creating a tibble?

答:
Just as Calum You proposed, You have to assign the result to the original data frame using the "<-" operator:

```<code>Drug_Table <- mutate(Drug_Table, DRUG_GENERIC_NAME, Ibuprofen = str_detect (Drug_Table$DRUG_GENERIC_NAME,"IBUPROFEN", negate = FALSE))
</code>```

If You need the data frame to still be a data.frame (and not a tibble) use as.data.frame()

```<code>Drug_Table <- as.data.frame(mutate(Drug_Table, DRUG_GENERIC_NAME, Ibuprofen = str_detect (Drug_Table$DRUG_GENERIC_NAME,"IBUPROFEN", negate = FALSE)))
</code>```

Body:
My attempt to add a new column to a dataframe with mutate gave me a tibble with the new variable, but did not add the variable as a new column in the dataframe (which is what I want to do).

I have a data frame with a character variable, DRUG_GENERIC_NAME, and created a new logical variable, Ibuprofen by combining mutate and str_detect which will be TRUE when IBUPROFEN is contained in DRUG_GENERIC_NAME:

mutate(Drug_Table, DRUG_GENERIC_NAME, Ibuprofen = str_detect (Drug_Table$DRUG_GENERIC_NAME,"IBUPROFEN", negate = FALSE))

The result was a tibble with the new variable Ibuprofen, but the code did not add the variable to the data frame Drug_Table. How can I use this code to add the new variable to the dataframe instead of creating a tibble?

Body:
Just as Calum You proposed, You have to assign the result to the original data frame using the "<-" operator:

Drug_Table <- mutate(Drug_Table, DRUG_GENERIC_NAME, Ibuprofen = str_detect (Drug_Table$DRUG_GENERIC_NAME,"IBUPROFEN", negate = FALSE))

If You need the data frame to still be a data.frame (and not a tibble) use as.data.frame()

Drug_Table <- as.data.frame(mutate(Drug_Table, DRUG_GENERIC_NAME, Ibuprofen = str_detect (Drug_Table$DRUG_GENERIC_NAME,"IBUPROFEN", negate = FALSE)))


问:
Compiler-dependent OpenMP min/max reduction pragma
My C++ code uses OpenMP directives and needs to compile with GCC and Visual Studio 2019.
OpenMP min/max reduction operators were introduced in OpenMP 3.1, but Visual Studio 2019 only supports OpenMP 2.0.

I'd like my code to revert to a serial loop under Visual Studio, but I understand that the preprocessor cannot represent a conditional pragma like this:

// invalid use of preprocessor:
#ifdef _MSC_VER
#define OMP_MIN(expr)
#else
#define OMP_MIN(expr) #pragma omp parallel for reduction(min:(expr))
#endif

double x = 10.0;

OMP_MIN(x)
for (int i = 0; i < array_size; i++) {
    x = fmin(x, array[i]);
}
```

Is there a way to achieve this?

答:
You can use _Pragma() from C++11 to have a function-like macro that conditionally enables a pragma:

```<code>#include <cmath>

#ifdef _MSC_VER
#define OMP_MINX()
#else
#define OMP_MINX() _Pragma("omp parallel for reduction(min:x)")
#endif

int main() {
  double x = 10.0;
  double array[50];
  int array_size = 50;

  OMP_MINX()
  for (int i = 0; i < array_size; i++) {
    x = std::fmin(x, array[i]);
  }
}
</code>```

but I haven't figured out how to make gcc accept anything other than a literal string for the argument to allow using an arbitrary variable - not even the preprocessor's stringification operator works, meaning you might as well just use

```<code>#ifndef _MSC_VER
#pragma omp parallel for reduction(min:x)
#endif
for (int i = 0; i < array_size; i++) {
  x = std::fmin(x, array[i]);
}
</code>```

Body:
My C++ code uses OpenMP directives and needs to compile with GCC and Visual Studio 2019.
OpenMP min/max reduction operators were introduced in OpenMP 3.1, but Visual Studio 2019 only supports OpenMP 2.0.

I'd like my code to revert to a serial loop under Visual Studio, but I understand that the preprocessor cannot represent a conditional pragma like this:

// invalid use of preprocessor:
#ifdef _MSC_VER
#define OMP_MIN(expr)
#else
#define OMP_MIN(expr) #pragma omp parallel for reduction(min:(expr))
#endif

double x = 10.0;

OMP_MIN(x)
for (int i = 0; i < array_size; i++) {
    x = fmin(x, array[i]);
}

Is there a way to achieve this?

Body:
You can use _Pragma() from C++11 to have a function-like macro that conditionally enables a pragma:

#include <cmath>

#ifdef _MSC_VER
#define OMP_MINX()
#else
#define OMP_MINX() _Pragma("omp parallel for reduction(min:x)")
#endif

int main() {
  double x = 10.0;
  double array[50];
  int array_size = 50;

  OMP_MINX()
  for (int i = 0; i < array_size; i++) {
    x = std::fmin(x, array[i]);
  }
}

but I haven't figured out how to make gcc accept anything other than a literal string for the argument to allow using an arbitrary variable - not even the preprocessor's stringification operator works, meaning you might as well just use

#ifndef _MSC_VER
#pragma omp parallel for reduction(min:x)
#endif
for (int i = 0; i < array_size; i++) {
  x = std::fmin(x, array[i]);
}


问:
This site can’t be reached http://127.0.0.1:8000/hello using Flask as web framework
I am trying to run a simple "hello world" code using flask version 1.1.1 and python 3.7. the server is running but the web page is not loading. Can anyone please help???

```<code>from flask import Flask
app = Flask(__name__)

@app.route('/hello')
def hello_world():
    return "Hello world"

if __name__ == '__main__':
    app.run(host='127.0.0.1',port=8000, debug=True)
</code>```

Output is as below

But the web page(http://127.0.0.1:8000/hello) displays "This site can’t be reached"

答: I tried using different port like 8000,8080,5000. finally worked for 7999 port number. The appropriate solution for this kind of problem is to experiment with different port numbers</p>

Body:
I am trying to run a simple "hello world" code using flask version 1.1.1 and python 3.7. the server is running but the web page is not loading. Can anyone please help???

from flask import Flask
app = Flask(__name__)

@app.route('/hello')
def hello_world():
    return "Hello world"

if __name__ == '__main__':
    app.run(host='127.0.0.1',port=8000, debug=True)

Output is as below

But the web page(http://127.0.0.1:8000/hello) displays "This site can’t be reached"


问:
Input loses focus after one character in React
Input loses focus after one character is entered, it's on every single input in every component, I followed some videos exactly on React input but none of them work properly for me at all. I've tried using keys and rendering the inputs in separate components but nothing seems to work.

input and textarea is where its happening.

```<code>import React, { Component } from "react";

import "./bootstrap/css/landing-page.min.css";
import "./vendor/fontawesome-free/css/all.min.css";
import "./vendor/bootstrap/css/bootstrap.min.css";
import "./vendor/simple-line-icons/css/simple-line-icons.css";

import "./App.css";
import "./Group.css";

import store from "./store";
import Home from "./App";

import { Provider } from "react-redux";
import { connect } from "react-redux";
import {
  addBug,
  updateGroupID,
  getBugs,
  createAccount,
  deleteBug
} from "./actions/itemAction";

import { Container } from "reactstrap";

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Redirect
} from "react-router-dom";
import { Link } from "react-router-dom";
import Select from "react-select";

class Group extends Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
      modalBug: []
    };
  }

  showModal = bug => {
    this.setState({ modalBug: bug });
    this.setState({ show: true });
  };

  hideModal = () => {
    this.setState({ show: false });
  };

  setBugTitle = e => {
    this.setState({ BugTitle: e.target.value });
    console.log(this.state.BugTitle);
  };
  setBugDescription = e => {
    this.setState({ BugDescription: e.target.value });
    console.log(this.state.BugDescription);
  };

  render() {

      if (
        this.props.user.loggedIn === true &&
        this.props.user.user.GroupID !== "NOGROUP"
      ) {
        return (
          <Provider store={store}>
            <div className="App">
              <link
                href="https://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic"
                rel="stylesheet"
                type="text/css"
              />

              <nav className="navbar navbar-light bg-light static-top">
                <div className="container">
                  <Link to="/">
                    <div className="navbar-brand">Bug Buster</div>
                  </Link>
                  <button className="btn btn-primary" onClick={this.authCheck}>
                    Log out
                  </button>
                </div>
              </nav>
              <div className="flex-container">
                <div className="bugSubmission">
                  <ul id="newBug">
                    <h3>Submit New Bug</h3>
                    <li>
                      //Input for Bug Title
                      <input
                        type="text"
                        placeholder="Enter Title..."
                        onChange={this.setBugTitle}
                        value={this.state.BugTitle}
                      ></input>
                    </li>
                    <li>
                      //Input for Bug Description
                      <textarea
                        placeholder="Enter Description..."
                        onChange={this.setBugDescription}
                        value={this.state.BugDescription}
                      ></textarea>
                    </li>
                    <li>
                      <button
                        className="btn btn-primary"
                        onClick={() => {
                          const newBug = {
                            Title: this.state.BugTitle,
                            Description: this.state.BugDescription,
                            PosterName:
                              this.props.user.user.FirstName +
                              " " +
                              this.props.user.user.LastName,
                            PosterID: this.props.user.user.UserId,
                            GroupID: this.props.user.user.GroupID
                          };

                          this.props.addBug(newBug);
                        }}
                      >
                        Submit Bug
                      </button>
                    </li>
                  </ul>
                </div>
                <Modal
                  show={this.state.show}
                  handleClose={this.hideModal}
                  bug={this.state.modalBug}
                ></Modal>

              </div>
            </div>

            <script src="vendor/jquery/jquery.min.js"></script>
            <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
          </Provider>
        );
      } else {
        return <h2>No user logged in</h2>;
      }
    };

    return (
      <Provider store={store}>
        <Router>
          <div className="App">
            <Switch>
              <Route path="/" exact component={Home} />
              <Route path="/group" exact component={Group} />
            </Switch>
          </div>
        </Router>
      </Provider>
    );
  }
}

const mapStateToProps = state => ({
  user: state.user,
  item: state.user,
  bugs: state.bugs
});

export default connect(mapStateToProps, {
  createAccount,
  updateGroupID,
  addBug,
  getBugs,
  deleteBug
})(Group);

</code>```

答:
I think you have to initialize BugTitle in the state

  constructor(props) {
    super(props);
    this.state = {
      show: false,
      modalBug: [],
      BugTitle: ""
    };
  }
```

<p>and to invoke the <strong>setBugTitle</strong> function you can make it like that </p>

<pre class="lang-js prettyprint-override"><code>        <input
          type="text"
          placeholder="Enter Title..."
          onChange={e => this.setBugTitle(e)}
          value={this.state.BugTitle}
        />
</code>```

i hope that help you

Body:
Input loses focus after one character is entered, it's on every single input in every component, I followed some videos exactly on React input but none of them work properly for me at all. I've tried using keys and rendering the inputs in separate components but nothing seems to work.

input and textarea is where its happening.

import React, { Component } from "react";

import "./bootstrap/css/landing-page.min.css";
import "./vendor/fontawesome-free/css/all.min.css";
import "./vendor/bootstrap/css/bootstrap.min.css";
import "./vendor/simple-line-icons/css/simple-line-icons.css";

import "./App.css";
import "./Group.css";

import store from "./store";
import Home from "./App";

import { Provider } from "react-redux";
import { connect } from "react-redux";
import {
  addBug,
  updateGroupID,
  getBugs,
  createAccount,
  deleteBug
} from "./actions/itemAction";

import { Container } from "reactstrap";

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Redirect
} from "react-router-dom";
import { Link } from "react-router-dom";
import Select from "react-select";

class Group extends Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
      modalBug: []
    };
  }

  showModal = bug => {
    this.setState({ modalBug: bug });
    this.setState({ show: true });
  };

  hideModal = () => {
    this.setState({ show: false });
  };

  setBugTitle = e => {
    this.setState({ BugTitle: e.target.value });
    console.log(this.state.BugTitle);
  };
  setBugDescription = e => {
    this.setState({ BugDescription: e.target.value });
    console.log(this.state.BugDescription);
  };

  render() {

      if (
        this.props.user.loggedIn === true &&
        this.props.user.user.GroupID !== "NOGROUP"
      ) {
        return (
          <Provider store={store}>

              <link
                href="https://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic"
                rel="stylesheet"
                type="text/css"
              />

                  <Link to="/">

Bug Buster

                  </Link>
                  <button className="btn btn-primary" onClick={this.authCheck}>
                    Log out
                  </button>

Submit New Bug

                      //Input for Bug Title
                      <input
                        type="text"
                        placeholder="Enter Title..."
                        onChange={this.setBugTitle}
                        value={this.state.BugTitle}
                      ></input>

                      //Input for Bug Description
                      <textarea
                        placeholder="Enter Description..."
                        onChange={this.setBugDescription}
                        value={this.state.BugDescription}
                      ></textarea>

                      <button
                        className="btn btn-primary"
                        onClick={() => {
                          const newBug = {
                            Title: this.state.BugTitle,
                            Description: this.state.BugDescription,
                            PosterName:
                              this.props.user.user.FirstName +
                              " " +
                              this.props.user.user.LastName,
                            PosterID: this.props.user.user.UserId,
                            GroupID: this.props.user.user.GroupID
                          };

                          this.props.addBug(newBug);
                        }}
                      >
                        Submit Bug
                      </button>

                <Modal
                  show={this.state.show}
                  handleClose={this.hideModal}
                  bug={this.state.modalBug}
                ></Modal>

          </Provider>
        );
      } else {
        return
No user logged in
;
      }
    };

    return (
      <Provider store={store}>
        <Router>

            <Switch>
              <Route path="/" exact component={Home} />
              <Route path="/group" exact component={Group} />
            </Switch>

        </Router>
      </Provider>
    );
  }
}

const mapStateToProps = state => ({
  user: state.user,
  item: state.user,
  bugs: state.bugs
});

export default connect(mapStateToProps, {
  createAccount,
  updateGroupID,
  addBug,
  getBugs,
  deleteBug
})(Group);

Body:
I think you have to initialize BugTitle in the state

  constructor(props) {
    super(props);
    this.state = {
      show: false,
      modalBug: [],
      BugTitle: ""
    };
  }

and to invoke the setBugTitle function you can make it like that

        <input
          type="text"
          placeholder="Enter Title..."
          onChange={e => this.setBugTitle(e)}
          value={this.state.BugTitle}
        />

i hope that help you


问:
C#: Excel Ribbon Addin change cursor to wait while calling method
I have created an Excel Addin with a Ribbon (my first one) that has buttons that calls a method that runs a Stored Procedure.
I would like to set the cursor to wait whilst the method is running.
have tried cursor.wait but that seems to be form windows forms.

I know I should use xlMousePointer but cannot find any example code.

Many Thanks

Marc

答:
After much experimentation I have resolved the issue with the following code:</p>

```<code>private void button3_Click(object sender, RibbonControlEventArgs e)
    {
        XlMousePointer originalCursor = Globals.ThisAddIn.Application.Cursor;

        Globals.ThisAddIn.Application.Cursor = XlMousePointer.xlWait;

        Method1();

        Globals.ThisAddIn.Application.Cursor = originalCursor;
    }
</code>```

Body:
After much experimentation I have resolved the issue with the following code:

private void button3_Click(object sender, RibbonControlEventArgs e)
    {
        XlMousePointer originalCursor = Globals.ThisAddIn.Application.Cursor;

        Globals.ThisAddIn.Application.Cursor = XlMousePointer.xlWait;

        Method1();

        Globals.ThisAddIn.Application.Cursor = originalCursor;
    }


问:
CORS policy error with Java + Spring in an ajax query
working with Java 11, eclipse, Gradle and spring in an ubuntu os

While my POST calls are working fine, the GET calls to the server are blocked due to the CORS policy with below error:

Access to XMLHttpRequest at 'http://localhost:8080/dices/players?{}'
  from origin 'http://localhost' has been blocked by CORS policy:
  Response to preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

the javascript for the POST and GET calls is:

```<code>$(document).ready(function(){
    $('#newUserButton').click(function(){
        $.ajax({
            type: 'POST',
            url: 'http://localhost:8080/dices/players',
            contentType: 'application/json',
            xhrFields: { withCredentials: true },
            data: JSON.stringify({"name":$('#newUserInput').val()}),
            dataType: 'json',
            success: function(data) {
                $('#newUserJumbo').append('<div class="alert alert-success" role="alert">El usuari ' + data.name + ' ha estat creat</div>');
                },
            error: function(e){
                console.log(e);
            }
        });
    });
});

$(document).ready(function(){
    $('#searchUserButton').click(function(){
        $.ajax({
            type: 'GET',
            url: 'http://localhost:8080/dices/players',
            contentType: 'application/json',
            xhrFields: { withCredentials: true },
            data: JSON.stringify({"idPlayer":$('searchUserInput').val()}),
            dataType: 'json',
            success: function(data) {
                $('#modifyUserUl').append('<button type="button" class="list-group-item list-group-item-action" id="' + data.id + ' onclick=modifyUser(' + data.id + '>id: ' + data.id + ', nom: ' + data.name + '</button>');
            },
            error: function(e){
                console.log(e);
            }
        });
    });
});
</code>```

To handle the CORS at server side, i'm using the below class that i've found in a mozilla mdnwebDoc  here which is working fine with the POST call, but fails on the GET

the code that handles the GET call is as follows:

```<code>    @CrossOrigin(origins = "http://lvh.me:8080")
    @GetMapping("/players/player")
    public Player getPlayer(@RequestBody Player newPlayer){
        try {
            return (Player) repository.findFirstByNameLike(newPlayer.getName());
        } catch (EmptyResultDataAccessException e) {
            throw new PlayerNotFoundException(newPlayer.getName());
</code>```

UPDATE 1

As Albert commented, i've changed the http://localhost to http://lvh.me to see if by this, the code works, but no exit.
Also i have edited my controller code changing from @PathVariable to @RequestBody (as my POST request to the same controller with a json body is working) also with effect.
Fiinally, thanks to Kevin comments, i've also changed the way to handle the CORS policy from a global approach to a controller approach, also without exit.
i've changed the code above to reflec this changes.

Any comments & suggestions are welcome. Thanks
thanks

答:
You can specifically enable CORS for that endpoint using the following:

```<code>@CrossOrigin(origins = "http://localhost:8080")
@GetMapping("/players/{idPlayer}")
public Player getPlayer(@PathVariable Integer idPlayer){
    try {
        return (Player) repository.findById(idPlayer);
    } catch (EmptyResultDataAccessException e) {
        throw new PlayerNotFoundException(idPlayer);
    }
}
</code>```

If you want to address CORS at a global level you need to create a WebMvcConfigurer bean in the class with your main method:

```<code>@SpringBootApplication
public class YourApplication {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:8080");
            }
        };
    }
}
</code>```

Body:
working with Java 11, eclipse, Gradle and spring in an ubuntu os

While my POST calls are working fine, the GET calls to the server are blocked due to the CORS policy with below error:

Access to XMLHttpRequest at 'http://localhost:8080/dices/players?{}'
  from origin 'http://localhost' has been blocked by CORS policy:
  Response to preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

the javascript for the POST and GET calls is:

$(document).ready(function(){
    $('#newUserButton').click(function(){
        $.ajax({
            type: 'POST',
            url: 'http://localhost:8080/dices/players',
            contentType: 'application/json',
            xhrFields: { withCredentials: true },
            data: JSON.stringify({"name":$('#newUserInput').val()}),
            dataType: 'json',
            success: function(data) {
                $('#newUserJumbo').append('
El usuari ' + data.name + ' ha estat creat
');
                },
            error: function(e){
                console.log(e);
            }
        });
    });
});

$(document).ready(function(){
    $('#searchUserButton').click(function(){
        $.ajax({
            type: 'GET',
            url: 'http://localhost:8080/dices/players',
            contentType: 'application/json',
            xhrFields: { withCredentials: true },
            data: JSON.stringify({"idPlayer":$('searchUserInput').val()}),
            dataType: 'json',
            success: function(data) {
                $('#modifyUserUl').append('<button type="button" class="list-group-item list-group-item-action" id="' + data.id + ' onclick=modifyUser(' + data.id + '>id: ' + data.id + ', nom: ' + data.name + '</button>');
            },
            error: function(e){
                console.log(e);
            }
        });
    });
});

To handle the CORS at server side, i'm using the below class that i've found in a mozilla mdnwebDoc  here which is working fine with the POST call, but fails on the GET

the code that handles the GET call is as follows:

    @CrossOrigin(origins = "http://lvh.me:8080")
    @GetMapping("/players/player")
    public Player getPlayer(@RequestBody Player newPlayer){
        try {
            return (Player) repository.findFirstByNameLike(newPlayer.getName());
        } catch (EmptyResultDataAccessException e) {
            throw new PlayerNotFoundException(newPlayer.getName());

UPDATE 1

As Albert commented, i've changed the http://localhost to http://lvh.me to see if by this, the code works, but no exit.
Also i have edited my controller code changing from @PathVariable to @RequestBody (as my POST request to the same controller with a json body is working) also with effect.
Fiinally, thanks to Kevin comments, i've also changed the way to handle the CORS policy from a global approach to a controller approach, also without exit.
i've changed the code above to reflec this changes.

Any comments & suggestions are welcome. Thanks
thanks

Body:
You can specifically enable CORS for that endpoint using the following:

@CrossOrigin(origins = "http://localhost:8080")
@GetMapping("/players/{idPlayer}")
public Player getPlayer(@PathVariable Integer idPlayer){
    try {
        return (Player) repository.findById(idPlayer);
    } catch (EmptyResultDataAccessException e) {
        throw new PlayerNotFoundException(idPlayer);
    }
}

If you want to address CORS at a global level you need to create a WebMvcConfigurer bean in the class with your main method:

@SpringBootApplication
public class YourApplication {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:8080");
            }
        };
    }
}


问:
javascript recursive iteration is returning entire parent div in the recursive iteration
I want to implement search functionality on my div whose html is as below :

```<code><input type="search" id="mysearch" placeholder="Search here"     />
    <div  class="sken-cues-body" id="mydivbody">
         <div class="sken-cue-card" style="display: block;" >
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-title">Welcome to My Customer!</div>
                <div class="sken-cue-text">
                    Want to help every sales agent like a <b>champion !</b>
                </div>
                <div class="">
                    <a type="button" href="https://salesken.ai/sign-in.html" class="sken-button-theme">START HERE</a>
                </div>
            </div>
        </div>
        <div class="sken-cue-card salesken-flex"  style="display: block;">
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-time">2:16 pm</div>
                <div class="sken-cue-title">Talking Points</div>
                <div class="sken-cue-text" id="11">
                    <ul >
                        <li>Greet the customer</li>
                        <li>Ask if it is a good time to talk</li>
                        <li>Be polite & courteous on the call</li>
                        <li>Listen carefully</li>
                        <li>Thank the customer for their time</li>
                    </ul>
                    <p></p>
                </div>
            </div>
        </div>
         <div class="sken-cue-card salesken-flex" style="display: block;">
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-time">2:16 pm</div>
                <div class="sken-cue-title"></div>
                <div class="sken-cue-text">
                    <p>
                        Introduce yourself and why you are calling, ask if it is a good time to talk<br>
                    </p>
                </div>
            </div>
        </div>
        <div class="sken-cue-card salesken-flex" style="display: block;">
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-time">2:16 pm</div>
                <div class="sken-cue-title">
                    <p>
                        <span style="font-family: Arial; font-size: 13.3333px;">NPA Guidelines</span><br>
                    </p>
                </div>
                <div class="sken-cue-text">
                    <p>
                        If the account has not been active for more than 90 days, it will be declared an NPA and that will lead to strident actions. Need to start paying the EMIs to avoid unnecessary legal hassles<br>
                        <br>
                    </p>
                </div>
            </div>
        </div>
    </div>
</code>```

For implemention search functionality,i need to recursive iteration inside  div with ID mydivbody. Below is javascript function for recursive iteration in div with  ID mydivbody:

```<code>document.getElementById('mysearch').addEventListener('keyup',function(){
    var node = document.getElementById('mydivbody')
    allDescendants(node,this.value)
});

function allDescendants (node) {
    for (var i = 0; i < node.children.length; i++) {
      var child = node.children[i];
      allDescendants(child);
         console.log(child)
      }

      //doSomethingToNode(child,search_value);
    }
</code>```

But in this js function, i can see all child nodes where i am consoling the child along with entire parent div. for me node is getting duplicated. Please suggest how to fix this

答:
The recursive iteration of your function allDescendants() is actually correct and does not generate duplicates. If you console.log() an element it will also contain its children, which maybe makes you confused in it containing duplicates.

I expanded it with an actual return and a Level property to show you that the iteration is correct.

function allDescendants(node, list, level){
    //REM: To actually return elements, thos get stored in a list
    var tList = list || [];
    var tLevel = ~~level;

    for(var i = 0; i < node.children.length; i++){
        var child = node.children[i];

        //REM: Store children in the list
        tList.push({Level: tLevel, Element: child});

        //REM: Took the log before the call, makes it more intuitive
        //console.log(child);
        allDescendants(child, tList, tLevel+1)
    };

    return tList
};

var tResult = allDescendants(document.querySelector('#mydivbody'));

console.log(tResult);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="search" id="mysearch" placeholder="Search here"     />
    <div  class="sken-cues-body" id="mydivbody">
         <div class="sken-cue-card" style="display: block;" >
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-title">Welcome to My Customer!</div>
                <div class="sken-cue-text">
                    Want to help every sales agent like a <b>champion !</b>
                </div>
                <div class="">
                    START HERE
                </div>
            </div>
        </div>
        <div class="sken-cue-card salesken-flex"  style="display: block;">
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-time">2:16 pm</div>
                <div class="sken-cue-title">Talking Points</div>
                <div class="sken-cue-text" id="11">
                    <ul >
                        <li>Greet the customer</li>
                        <li>Ask if it is a good time to talk</li>
                        <li>Be polite & courteous on the call</li>
                        <li>Listen carefully</li>
                        <li>Thank the customer for their time</li>
                    </ul>
                    <p></p>
                </div>
            </div>
        </div>
         <div class="sken-cue-card salesken-flex" style="display: block;">
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-time">2:16 pm</div>
                <div class="sken-cue-title"></div>
                <div class="sken-cue-text">
                    <p>
                        Introduce yourself and why you are calling, ask if it is a good time to talk<br>
                    </p>
                </div>
            </div>
        </div>
        <div class="sken-cue-card salesken-flex" style="display: block;">
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-time">2:16 pm</div>
                <div class="sken-cue-title">
                    <p>
                        <span style="font-family: Arial; font-size: 13.3333px;">NPA Guidelines</span><br>
                    </p>
                </div>
                <div class="sken-cue-text">
                    <p>
                        If the account has not been active for more than 90 days, it will be declared an NPA and that will lead to strident actions. Need to start paying the EMIs to avoid unnecessary legal hassles<br>
                        <br>
                    </p>
                </div>
            </div>
        </div>
    </div></code>```

If you just want the textNodes (innerText?) you could make use of createTreeWalker().

var treeWalker = document.createTreeWalker(
  document.getElementById('mydivbody'),
  NodeFilter.SHOW_TEXT
);

var nodeList = [];
var currentNode = treeWalker.currentNode;

while(currentNode) {
  //nodeList.push(currentNode.wholeText);
  nodeList.push(currentNode.textContent);
  currentNode = treeWalker.nextNode();
};

console.log(nodeList);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="search" id="mysearch" placeholder="Search here"     />
    <div  class="sken-cues-body" id="mydivbody">
         <div class="sken-cue-card" style="display: block;" >
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-title">Welcome to My Customer!</div>
                <div class="sken-cue-text">
                    Want to help every sales agent like a <b>champion !</b>
                </div>
                <div class="">
                    START HERE
                </div>
            </div>
        </div>
        <div class="sken-cue-card salesken-flex"  style="display: block;">
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-time">2:16 pm</div>
                <div class="sken-cue-title">Talking Points</div>
                <div class="sken-cue-text" id="11">
                    <ul >
                        <li>Greet the customer</li>
                        <li>Ask if it is a good time to talk</li>
                        <li>Be polite & courteous on the call</li>
                        <li>Listen carefully</li>
                        <li>Thank the customer for their time</li>
                    </ul>
                    <p></p>
                </div>
            </div>
        </div>
         <div class="sken-cue-card salesken-flex" style="display: block;">
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-time">2:16 pm</div>
                <div class="sken-cue-title"></div>
                <div class="sken-cue-text">
                    <p>
                        Introduce yourself and why you are calling, ask if it is a good time to talk<br>
                    </p>
                </div>
            </div>
        </div>
        <div class="sken-cue-card salesken-flex" style="display: block;">
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-time">2:16 pm</div>
                <div class="sken-cue-title">
                    <p>
                        <span style="font-family: Arial; font-size: 13.3333px;">NPA Guidelines</span><br>
                    </p>
                </div>
                <div class="sken-cue-text">
                    <p>
                        If the account has not been active for more than 90 days, it will be declared an NPA and that will lead to strident actions. Need to start paying the EMIs to avoid unnecessary legal hassles<br>
                        <br>
                    </p>
                </div>
            </div>
        </div>
    </div></code>```

Body:
I want to implement search functionality on my div whose html is as below :

<input type="search" id="mysearch" placeholder="Search here"     />

Welcome to My Customer!

                    Want to help every sales agent like a champion !

                    START HERE

2:16 pm

Talking Points

Greet the customer

Ask if it is a good time to talk

Be polite & courteous on the call

Listen carefully

Thank the customer for their time

2:16 pm

                        Introduce yourself and why you are calling, ask if it is a good time to talk

2:16 pm

                        NPA Guidelines

                        If the account has not been active for more than 90 days, it will be declared an NPA and that will lead to strident actions. Need to start paying the EMIs to avoid unnecessary legal hassles

For implemention search functionality,i need to recursive iteration inside  div with ID mydivbody. Below is javascript function for recursive iteration in div with  ID mydivbody:

document.getElementById('mysearch').addEventListener('keyup',function(){
    var node = document.getElementById('mydivbody')
    allDescendants(node,this.value)
});

function allDescendants (node) {
    for (var i = 0; i < node.children.length; i++) {
      var child = node.children[i];
      allDescendants(child);
         console.log(child)
      }

      //doSomethingToNode(child,search_value);
    }

But in this js function, i can see all child nodes where i am consoling the child along with entire parent div. for me node is getting duplicated. Please suggest how to fix this

Body:
The recursive iteration of your function allDescendants() is actually correct and does not generate duplicates. If you console.log() an element it will also contain its children, which maybe makes you confused in it containing duplicates.

I expanded it with an actual return and a Level property to show you that the iteration is correct.

function allDescendants(node, list, level){
    //REM: To actually return elements, thos get stored in a list
    var tList = list || [];
    var tLevel = ~~level;

    for(var i = 0; i < node.children.length; i++){
        var child = node.children[i];

        //REM: Store children in the list
        tList.push({Level: tLevel, Element: child});

        //REM: Took the log before the call, makes it more intuitive
        //console.log(child);
        allDescendants(child, tList, tLevel+1)
    };

    return tList
};

var tResult = allDescendants(document.querySelector('#mydivbody'));

console.log(tResult);

<input type="search" id="mysearch" placeholder="Search here"     />
    <div  class="sken-cues-body" id="mydivbody">
         <div class="sken-cue-card" style="display: block;" >
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-title">Welcome to My Customer!</div>
                <div class="sken-cue-text">
                    Want to help every sales agent like a <b>champion !</b>
                </div>
                <div class="">
                    <a type="button" href="https://salesken.ai/sign-in.html" class="sken-button-theme">START HERE</a>
                </div>
            </div>
        </div>
        <div class="sken-cue-card salesken-flex"  style="display: block;">
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-time">2:16 pm</div>
                <div class="sken-cue-title">Talking Points</div>
                <div class="sken-cue-text" id="11">
                    <ul >
                        <li>Greet the customer</li>
                        <li>Ask if it is a good time to talk</li>
                        <li>Be polite &amp; courteous on the call</li>
                        <li>Listen carefully</li>
                        <li>Thank the customer for their time</li>
                    </ul>
                    <p></p>
                </div>
            </div>
        </div>
         <div class="sken-cue-card salesken-flex" style="display: block;">
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-time">2:16 pm</div>
                <div class="sken-cue-title"></div>
                <div class="sken-cue-text">
                    <p>
                        Introduce yourself and why you are calling, ask if it is a good time to talk<br>
                    </p>
                </div>
            </div>
        </div>
        <div class="sken-cue-card salesken-flex" style="display: block;">
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-time">2:16 pm</div>
                <div class="sken-cue-title">
                    <p>
                        <span style="font-family: Arial; font-size: 13.3333px;">NPA Guidelines</span><br>
                    </p>
                </div>
                <div class="sken-cue-text">
                    <p>
                        If the account has not been active for more than 90 days, it will be declared an NPA and that will lead to strident actions. Need to start&nbsp;paying the EMIs to avoid unnecessary legal hassles<br>
                        <br>
                    </p>
                </div>
            </div>
        </div>
    </div>

If you just want the textNodes (innerText?) you could make use of createTreeWalker().

var treeWalker = document.createTreeWalker(
  document.getElementById('mydivbody'),
  NodeFilter.SHOW_TEXT
);

var nodeList = [];
var currentNode = treeWalker.currentNode;

while(currentNode) {
  //nodeList.push(currentNode.wholeText);
  nodeList.push(currentNode.textContent);
  currentNode = treeWalker.nextNode();
};

console.log(nodeList);

<input type="search" id="mysearch" placeholder="Search here"     />
    <div  class="sken-cues-body" id="mydivbody">
         <div class="sken-cue-card" style="display: block;" >
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-title">Welcome to My Customer!</div>
                <div class="sken-cue-text">
                    Want to help every sales agent like a <b>champion !</b>
                </div>
                <div class="">
                    <a type="button" href="https://salesken.ai/sign-in.html" class="sken-button-theme">START HERE</a>
                </div>
            </div>
        </div>
        <div class="sken-cue-card salesken-flex"  style="display: block;">
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-time">2:16 pm</div>
                <div class="sken-cue-title">Talking Points</div>
                <div class="sken-cue-text" id="11">
                    <ul >
                        <li>Greet the customer</li>
                        <li>Ask if it is a good time to talk</li>
                        <li>Be polite &amp; courteous on the call</li>
                        <li>Listen carefully</li>
                        <li>Thank the customer for their time</li>
                    </ul>
                    <p></p>
                </div>
            </div>
        </div>
         <div class="sken-cue-card salesken-flex" style="display: block;">
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-time">2:16 pm</div>
                <div class="sken-cue-title"></div>
                <div class="sken-cue-text">
                    <p>
                        Introduce yourself and why you are calling, ask if it is a good time to talk<br>
                    </p>
                </div>
            </div>
        </div>
        <div class="sken-cue-card salesken-flex" style="display: block;">
            <div class="salesken-flex salesken-flex-column">
                <div class="sken-cue-time">2:16 pm</div>
                <div class="sken-cue-title">
                    <p>
                        <span style="font-family: Arial; font-size: 13.3333px;">NPA Guidelines</span><br>
                    </p>
                </div>
                <div class="sken-cue-text">
                    <p>
                        If the account has not been active for more than 90 days, it will be declared an NPA and that will lead to strident actions. Need to start&nbsp;paying the EMIs to avoid unnecessary legal hassles<br>
                        <br>
                    </p>
                </div>
            </div>
        </div>
    </div>


问:
mysql field="value" in elasticsearch
I want to display only the items that contain the word itself when "google" searches
How can I only search for items that have only the word "google"?

Request body
(Request created in postman)

```<code>{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "body": "google"
          }
        }
      ]
    }
  }
}
</code>```

Response body
(Request created in postman)

```<code>{
  "took": 0,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 3,
      "relation": "eq"
    },
    "max_score": 0.6587735,
    "hits": [
      {
        "_index": "s_t",
        "_type": "_doc",
        "_id": "3",
        "_score": 0.6587735,
        "_source": {
          "body": "google"
        }
      },
      {
        "_index": "s_t",
        "_type": "_doc",
        "_id": "4",
        "_score": 0.5155619,
        "_source": {
          "body": "google map"
        }
      },
      {
        "_index": "s_t",
        "_type": "_doc",
        "_id": "5",
        "_score": 0.5155619,
        "_source": {
          "body": "google-map"
        }
      }
    ]
  }
}
</code>```

I need this output
(Request created in postman)

```<code>{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 3,
      "relation": "eq"
    },
    "max_score": 0.69381464,
    "hits": [
      {
        "_index": "s_t",
        "_type": "_doc",
        "_id": "3",
        "_score": 0.69381464,
        "_source": {
          "body": "google"
        }
      }
    ]
  }
}
</code>```

In mysql with this query I reach my goal.

Similar query in mysql:

```<code>select * from s_t where body='google'
</code>```

答:
well i assume you automap or use a text in your mappings.
specify .keyword in your query. Note this is case sensitive.

```<code>{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "body.keyword": "google"
          }
        }
      ]
    }
  }
}
</code>```

If you only want to query your body field using exact match. You need to reindex it using keyword. Take a look at: Exact match in elastic search query

Title: mysql field="value" in elasticsearch

Body:
I want to display only the items that contain the word itself when "google" searches
How can I only search for items that have only the word "google"?

Request body
(Request created in postman)

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "body": "google"
          }
        }
      ]
    }
  }
}

Response body
(Request created in postman)

{
  "took": 0,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 3,
      "relation": "eq"
    },
    "max_score": 0.6587735,
    "hits": [
      {
        "_index": "s_t",
        "_type": "_doc",
        "_id": "3",
        "_score": 0.6587735,
        "_source": {
          "body": "google"
        }
      },
      {
        "_index": "s_t",
        "_type": "_doc",
        "_id": "4",
        "_score": 0.5155619,
        "_source": {
          "body": "google map"
        }
      },
      {
        "_index": "s_t",
        "_type": "_doc",
        "_id": "5",
        "_score": 0.5155619,
        "_source": {
          "body": "google-map"
        }
      }
    ]
  }
}

I need this output
(Request created in postman)

{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 3,
      "relation": "eq"
    },
    "max_score": 0.69381464,
    "hits": [
      {
        "_index": "s_t",
        "_type": "_doc",
        "_id": "3",
        "_score": 0.69381464,
        "_source": {
          "body": "google"
        }
      }
    ]
  }
}

In mysql with this query I reach my goal.

Similar query in mysql:

select * from s_t where body='google'

Body:
well i assume you automap or use a text in your mappings.
specify .keyword in your query. Note this is case sensitive.

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "body.keyword": "google"
          }
        }
      ]
    }
  }
}

If you only want to query your body field using exact match. You need to reindex it using keyword. Take a look at: Exact match in elastic search query


问:
Concept on "best constant's loss" in vowpal wabbit's output, and the stated rule of thumb in tutorial
I am trying to understand vowpal a bit more and came across this statement on the Linear Regression tutorial. (https://vowpalwabbit.org/tutorials/getting_started.html)

"At the end, some more straightforward totals are printed. The best constant and best constant's loss only work if you are using squared loss. Squared loss is the Vowpal Wabbit default. They compute the best constant’s predictor and the loss of the best constant predictor.

If average loss is not better than best constant's loss, something is wrong. In this case, we have too few examples to generalize."

Based on that context, I have 2 related questions:

Is the best constant's loss based on the loss of the null model in linear regression?

Is the general rule of thumb for "average loss" not being better than "best constant's loss" applicable to all loss functions (since the statement does state that the "best constant" only works for the default squared loss function)?

Thanks in advance for any responses!

答:
Is the best constant's loss based on the loss of the null model in linear regression?

If by null-model you mean the model which always predicts the best-constant, then yes.

Is the general rule of thumb for "average loss" not being better than "best constant's loss" applicable to all loss functions?

Yes. If by always using the same prediction (some best constant applicable to a given loss-function) you are doing better than the learned model, it means that the learned model is inferior to the simplest possible model. The simplest model for a given loss-function, is always predicting the same (best constant) result, ignoring the input-features in the data.

One of the most common cases for a learned model being inferior to the best-constant model, is a too small data-set. When the data-set is small, the learning process didn't have a chance to fully converge yet. This is also known as under-fitting.

How is the best constant calculated (for completeness)?

In the case of linear-regression (least-squares hyperplane, the vw --loss_function squared, which is the default) the best constant is the simple average (aka mean) of the labels. This minimizes the squared-loss.

In the case of quantile-loss (aka absolute-error, vw --loss_function quantile) the best constant is the median of the labels and it minimizes the sum-of-distances between the labels and the prediction.


问:
Is there any way to plot a just a static image on a webpage with plotly js api?
Hey so I am developing an app that will display certain plots based on csv data and am using the plotly js api. I have found that when a user tries to create a scatter plot with a ton of points (greater than 1000 or so) it really slows down the user's browser. So I want to generate a static plot if the data that they supply exceeds a certain threshold of points.

The problem is that I am not sure how to generate a static plot without first rendering an interactive plot.

I have tried to modify the example given on the plotly js api, but have not been able to figure it out.

Here is the code:

Javascript (CDN Included in the Pen)

```<code>function plot() {
  var d3 = Plotly.d3;
  var img_jpg = d3.select("#jpg-export");

  // Ploting the Graph

  var trace = {
    x: [3, 9, 8, 10, 4, 6, 5],
    y: [5, 7, 6, 7, 8, 9, 8],
    type: "scatter"
  };
  var trace1 = {
    x: [3, 4, 1, 6, 8, 9, 5],
    y: [4, 2, 5, 2, 1, 7, 3],
    type: "scatter"
  };
  var data = [trace, trace1];
  var layout = { title: "Simple Javascript Graph" };
  Plotly.plot("plotly_div", data, layout)

  // static image in jpg format

    .then(function(gd) {
    Plotly.toImage(gd, { height: 300, width: 300 }).then(function(url) {
      img_jpg.attr("src", url);
      return Plotly.toImage(gd, { format: "jpeg", height: 400, width: 400 });
    });
  });
}
</code>```

HTML

```<code><h1>Interactive Plot</h1>
<div id="plotly_div" />

<h1>Static Plot</h1>
<img id="jpg-export"></img>

<button onclick="plot()">Run the function</button>
</code>```

Thanks!

答:
I think you can add that as a config :</p>

```<code>Plotly.newPlot('myDiv', data, layout, {staticPlot: true});
</code>```

Body:
Hey so I am developing an app that will display certain plots based on csv data and am using the plotly js api. I have found that when a user tries to create a scatter plot with a ton of points (greater than 1000 or so) it really slows down the user's browser. So I want to generate a static plot if the data that they supply exceeds a certain threshold of points.

The problem is that I am not sure how to generate a static plot without first rendering an interactive plot.

I have tried to modify the example given on the plotly js api, but have not been able to figure it out.

Here is the code:

Javascript (CDN Included in the Pen)

function plot() {
  var d3 = Plotly.d3;
  var img_jpg = d3.select("#jpg-export");

  // Ploting the Graph

  var trace = {
    x: [3, 9, 8, 10, 4, 6, 5],
    y: [5, 7, 6, 7, 8, 9, 8],
    type: "scatter"
  };
  var trace1 = {
    x: [3, 4, 1, 6, 8, 9, 5],
    y: [4, 2, 5, 2, 1, 7, 3],
    type: "scatter"
  };
  var data = [trace, trace1];
  var layout = { title: "Simple Javascript Graph" };
  Plotly.plot("plotly_div", data, layout)

  // static image in jpg format

    .then(function(gd) {
    Plotly.toImage(gd, { height: 300, width: 300 }).then(function(url) {
      img_jpg.attr("src", url);
      return Plotly.toImage(gd, { format: "jpeg", height: 400, width: 400 });
    });
  });
}

HTML

Interactive Plot

Static Plot

<button onclick="plot()">Run the function</button>

Thanks!

Body:
I think you can add that as a config :

Plotly.newPlot('myDiv', data, layout, {staticPlot: true});


问:
linq2sql C#: How to query from a table with changing schema name
I have a webservice which tries to connect to a database of a desktop accounting application.

It have tables with same name but with different schema names such as:

```<code>[DatabaseName].[202001].[CustomerCredit]
[DatabaseName].[202002].[CustomerCredit]
.
.
.
[DatabaseName].[202014].[CustomerCredit]
[DatabaseName].[202015].[CustomerCredit]
[DatabaseName].[202016].[CustomerCredit]
...
..
[DatabaseName].[2020xx].[CustomerCredit]
</code>```

Schema name is in format [Year+IncrementalNumber] such as [202014], [202015],[202016] and etc.

Whenever I want to query customer credit information in database, I should fetch information from schema with biggest number such as [DatabaseName].[202016].[CustomerCredit] if 202016 is latest schema in my db.

Note:
Creation of new schema in accounting application database have no rules and is completely decided by user of accounting application and every instance of application installed on different place may have different number of schemas.

So when I'm developing my webservice I have no idea to connect to which schema prior to development. In run-time I can find correct schema to query from its tables but I don't know how to manage to fetch table information with correct schema name in query.
I ususally creat a linq-to-sql dbml class and use its definitions to read information from db but I don't know how to manage schema change in this way?

DBML designer manage Scehma names like this:

```<code>[global::System.Data.Linq.Mapping.TableAttribute(Name="[202001].CustomerCredit")]
</code>```

However since my app can retrieve schema name in run time, I don't know how to fix table declaration in my special case.
It is so easy to handle in ADO.NET but I don't know its equivalent in Linq2SQL:

```<code>select count(*)  from [" + Variables.FinancialYearSchemaName + "].CustomerCredit  where SFC_Status = 100;
</code>```

答:
Ultimately, no: most ORMs do not expect the schema change to vary at runtime, so most - including EF and LINQ-to-SQL do not support this scenario. One possible option would be to have different connection strings, each with different user accounts, that each has a different default schema configured at the database - and intialize your DB-context with a connection-string or connection that matches the required account. Then if EF asks the RDBMS for [CustomerCredit], it will look first in that account's schema ([202014].[CustomerCredit]). You should probably avoid having a [202014].[CustomerCredit] in that scenario, to prevent confusion. This is, however, a pretty hacky and ugly solution. But... it should work.

Alternatively, you would have to take more control over the data access, essentially writing your own SQL (presumably with a token replacement for the schema, which has problems of its own).

Body:
I have a webservice which tries to connect to a database of a desktop accounting application.

It have tables with same name but with different schema names such as:

[DatabaseName].[202001].[CustomerCredit]
[DatabaseName].[202002].[CustomerCredit]
.
.
.
[DatabaseName].[202014].[CustomerCredit]
[DatabaseName].[202015].[CustomerCredit]
[DatabaseName].[202016].[CustomerCredit]
...
..
[DatabaseName].[2020xx].[CustomerCredit]

Schema name is in format [Year+IncrementalNumber] such as [202014], [202015],[202016] and etc.

Whenever I want to query customer credit information in database, I should fetch information from schema with biggest number such as [DatabaseName].[202016].[CustomerCredit] if 202016 is latest schema in my db.

Note:
Creation of new schema in accounting application database have no rules and is completely decided by user of accounting application and every instance of application installed on different place may have different number of schemas.

So when I'm developing my webservice I have no idea to connect to which schema prior to development. In run-time I can find correct schema to query from its tables but I don't know how to manage to fetch table information with correct schema name in query.
I ususally creat a linq-to-sql dbml class and use its definitions to read information from db but I don't know how to manage schema change in this way?

DBML designer manage Scehma names like this:

[global::System.Data.Linq.Mapping.TableAttribute(Name="[202001].CustomerCredit")]

However since my app can retrieve schema name in run time, I don't know how to fix table declaration in my special case.
It is so easy to handle in ADO.NET but I don't know its equivalent in Linq2SQL:

select count(*)  from [" + Variables.FinancialYearSchemaName + "].CustomerCredit  where SFC_Status = 100;


问:
NoSuchMethodError: No virtual method setStream in class Landroid/app/WallpaperManager on older Android devices
Well, I developed a wallpaper app that is working on most of the recent devices. But one of my activity in that app is getting crashed on a few devices that include galaxy J7 prime, Vivo y53. So far I saw these devices crashed my app's activity when I am trying to set wallpaper. Below is the method to set wallpaper.

```<code>@RequiresApi(api = Build.VERSION_CODES.N)
private void setWallpaper(String url, int which) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    WallpaperManager wm ;
    InputStream ins ;
    try {
        wm = WallpaperManager.getInstance(getApplicationContext());
        ins = new URL(url).openStream();
        if (which == 0) {
            wm.setStream(ins, null, false, WallpaperManager.FLAG_SYSTEM); // Exception
        }
        if (which == 1) {
            wm.setStream(ins, null, false, WallpaperManager.FLAG_LOCK); // Exception
        }
        Toast.makeText(SetWallpaperActivity.this, "Wallpaper Set Successfully!", Toast.LENGTH_SHORT).show();
        if(ad.isLoaded()){
            ad.show();
        }
    } catch (IOException e) {
        Toast.makeText(this, "Check your Connection!", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
}
</code>```

Actually, it is generating an error when setStream method is invoked. Below is the error details

```<code> 02-19 15:18:33.514 5384-5384/com.manas.superwallpz E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.manas.supe, PID: 5384
java.lang.NoSuchMethodError: No virtual method setStream(Ljava/io/InputStream;Landroid/graphics/Rect;ZI)I in class Landroid/app/WallpaperManager; or its super classes (declaration of 'android.app.WallpaperManager' appears in /system/framework/framework.jar)
    at com.manas.superwallpz.activities.SetWallpaperActivity.setWallpaper(SetWallpaperActivity.java:278)
    at com.manas.superwallpz.activities.SetWallpaperActivity.access$600(SetWallpaperActivity.java:49)
    at com.manas.superwallpz.activities.SetWallpaperActivity$3.onClick(SetWallpaperActivity.java:257)
    at android.support.v7.app.AlertController$AlertParams$3.onItemClick(AlertController.java:1068)
    at android.widget.AdapterView.performItemClick(AdapterView.java:305)
    at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
    at android.widget.AbsListView$3.run(AbsListView.java:3860)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code>```

It is generating an Error called NoSuchMethodError. I am guessing it is something to do with requires Api annotation.

@RequiresApi(api = Build.VERSION_CODES.N)

I am new to android development so I am unable to figure out what's causing this? Your help will make my day. Please, If you are providing a solution then do explain the reason because I love to explore these problems.

答: The version of WallpaperManager.setStream that you are calling doesn't exist before API level 24 (Android N).  You'd need to check the current API level and on older Android versions, use a method that exists in that API level, such as WallpaperManager.setStream(InputStream)

Body:
Well, I developed a wallpaper app that is working on most of the recent devices. But one of my activity in that app is getting crashed on a few devices that include galaxy J7 prime, Vivo y53. So far I saw these devices crashed my app's activity when I am trying to set wallpaper. Below is the method to set wallpaper.

@RequiresApi(api = Build.VERSION_CODES.N)
private void setWallpaper(String url, int which) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    WallpaperManager wm ;
    InputStream ins ;
    try {
        wm = WallpaperManager.getInstance(getApplicationContext());
        ins = new URL(url).openStream();
        if (which == 0) {
            wm.setStream(ins, null, false, WallpaperManager.FLAG_SYSTEM); // Exception
        }
        if (which == 1) {
            wm.setStream(ins, null, false, WallpaperManager.FLAG_LOCK); // Exception
        }
        Toast.makeText(SetWallpaperActivity.this, "Wallpaper Set Successfully!", Toast.LENGTH_SHORT).show();
        if(ad.isLoaded()){
            ad.show();
        }
    } catch (IOException e) {
        Toast.makeText(this, "Check your Connection!", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
}

Actually, it is generating an error when setStream method is invoked. Below is the error details

 02-19 15:18:33.514 5384-5384/com.manas.superwallpz E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.manas.supe, PID: 5384
java.lang.NoSuchMethodError: No virtual method setStream(Ljava/io/InputStream;Landroid/graphics/Rect;ZI)I in class Landroid/app/WallpaperManager; or its super classes (declaration of 'android.app.WallpaperManager' appears in /system/framework/framework.jar)
    at com.manas.superwallpz.activities.SetWallpaperActivity.setWallpaper(SetWallpaperActivity.java:278)
    at com.manas.superwallpz.activities.SetWallpaperActivity.access$600(SetWallpaperActivity.java:49)
    at com.manas.superwallpz.activities.SetWallpaperActivity$3.onClick(SetWallpaperActivity.java:257)
    at android.support.v7.app.AlertController$AlertParams$3.onItemClick(AlertController.java:1068)
    at android.widget.AdapterView.performItemClick(AdapterView.java:305)
    at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
    at android.widget.AbsListView$3.run(AbsListView.java:3860)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

It is generating an Error called NoSuchMethodError. I am guessing it is something to do with requires Api annotation.

@RequiresApi(api = Build.VERSION_CODES.N)

I am new to android development so I am unable to figure out what's causing this? Your help will make my day. Please, If you are providing a solution then do explain the reason because I love to explore these problems.


问:
ERR_CONNECTION_REFUSED in POST data to Mysql using NodeJs and ReactJs
I am working on ReactJs and NodeJS in sending data to MySql, in my frontPage.js The problem is I already tested the API to post data using Postman and no error appears. And the problem comes when I tried in ReactJs, I coded this :

```<code>class InputEndUser extends Component {
    constructor(props){
        super(props);

        this.state = {
            project_type: '',
            status : '',
            subject : '',
            enduser_name : '',
            location : '',
            cp_1 : '',
            cp1_hp : '',
            cp1_jpos: '',
            cp_2 : '',
            cp2_hp : '',
            cp2_jpos : '',
            quot_num : '',
            quot_date : '',
            note : ''

        }
        this.handleProject_type = this.handleProject_type.bind(this);
        this.handleStatus = this.handleStatus.bind(this);
        this.handleSubject = this.handleSubject.bind(this);
        this.handleEnduser_name = this.handleEnduser_name.bind(this);
        this.handleLocation = this.handleLocation.bind(this);
        this.handleCP1 = this.handleCP1.bind(this);
        this.handleCP1_hp = this.handleCP1_hp.bind(this);
        this.handleCP1_jpos = this.handleCP1_jpos.bind(this);
        this.handleCP2 = this.handleCP2.bind(this);
        this.handleCP2 = this.handleCP2.bind(this);
        this.handleCP2_hp = this.handleCP2_hp.bind(this);
        this.handleCP2_jpos = this.handleCP2_jpos.bind(this);
        this.handleQuot_num = this.handleQuot_num.bind(this);
        this.handleQuot_date = this.handleQuot_date.bind (this);
        this.handleNotes = this.handleNotes.bind(this);
    }

    handleProject_type(event){
        this.setState ({
            project_type : event.target.value
        })
    }

    handleStatus(event){
        this.setState({
            status: event.target.value
        })
    }

    handleSubject(event){
        this.setState({
            subject: event.target.value
        })
    }

    handleEnduser_name (event) {
        this.setState({
            enduser_name: event.target.value
        })
    }

    handleLocation(event){
        this.setState({
            location: event.target.value
        })
    }

    handleCP1(event){
        this.setState({
            cp_1: event.target.value
        })
    }

    handleCP1_hp(event){
        this.setState ({
            cp1_hp : event.target.value
        })
    }

    handleCP1_jpos(event){
        this.setState ({
            cp1_jpos : event.target.value
        })
    }

    handleCP2(event){
        this.setState({
            cp_2: event.target.value
        })
    }

    handleCP2_hp(event){
        this.setState ({
            cp2_hp : event.target.value
        })
    }

    handleCP2_jpos(event){
        this.setState ({
            cp2_jpos : event.target.value
        })
    }

    handleQuot_num(event) {
        this.setState ({
            quot_num : event.target.value
        })
    }

    handleQuot_date (event) {
        this.setState({
            quot_date : event.target.value
        })
    }

    handleNotes(event) {
        this.setState({
            note : event.target.value
        })
    }

    submitEndUser(event){
        event.preventDefault();
        fetch('http://localhost:4000/enduser', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        })
        .then ((response) => {
            return response.json;
        })
        .then ((body) => {
            console.log(body);
        })
        .catch((error) => {
            console.log(error)
        })
    }
</code>```

and My API in server.js :

```<code>app.post('/enduser', (req, res) => {
  let POST_ENDUSER_QUERY =  {
    project_id: req.body.project_id,
    project_type: req.body.project_type,
    status: req.body.status,
    subject: req.body.subject,
    endUser_name: req.body.endUser_name,
    location: req.body.location,
    cp_1: req.body.cp_1,
    cp1_hp: req.body.cp1_hp,
    cp1_jpos: req.body.cp1_jpos,
    cp_2: req.body.cp_1,
    cp2_hp: req.body.cp1_hp,
    cp2_jpos: req.body.cp1_jpos,
    quot_num: req.body.quot_num,
    quot_date: req.body.quot_date,
    note: req.body.note,
    image: req.body.image,
    estimated_value: req.body.estimated_value
  };
  if (!POST_ENDUSER_QUERY) {
    return res.status(400).send({ err: true, message: 'Please project name' });
  }

  let query = `INSERT INTO enduser_tbl (project_id, project_type, status, subject, endUser_name, location, cp_1, cp1_hp, cp1_jpos, cp_2, cp2_hp, cp2_jpos, quot_num,quot_date, note, image, estimated_value) VALUES (
    '${POST_ENDUSER_QUERY.project_id}',
    '${POST_ENDUSER_QUERY.project_type}',
    '${POST_ENDUSER_QUERY.status}',
    '${POST_ENDUSER_QUERY.subject}',
    '${POST_ENDUSER_QUERY.endUser_name}',
    '${POST_ENDUSER_QUERY.location}',
    '${POST_ENDUSER_QUERY.cp_1}',
    '${POST_ENDUSER_QUERY.cp1_hp}',
    '${POST_ENDUSER_QUERY.cp1_jpos}',
    '${POST_ENDUSER_QUERY.cp_2}',
    '${POST_ENDUSER_QUERY.cp2_hp}',
    '${POST_ENDUSER_QUERY.cp2_jpos}',
    '${POST_ENDUSER_QUERY.quot_num}',
    '${POST_ENDUSER_QUERY.quot_date}',
    '${POST_ENDUSER_QUERY.note}',
    '${POST_ENDUSER_QUERY.image}',
    '${POST_ENDUSER_QUERY.estimated_value}'
    )`;
  dbConn.query(query, ( err, results) => {
    if(err) throw err;
    return res.status(200).json({"status": 200, "err" : null, "data": results});
  });
});

</code>```

and the error came :

also in terminal when I test it with some kind of data, appears like this:

答:
I got the problem for my case here ...
after trying with some suggestions...

I needed to include body in my POST like this :

```<code> fetch('http://localhost:4000/enduser', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify(this.state)
        })
</code>```

Finally I solved the problem in back-end connection with Auto Increment field in mysql database. I change project_id in values with this :

```<code> let query = `INSERT INTO enduser_tbl (project_id, project_type, status, subject, endUser_name, location, cp_1, cp1_hp, cp1_jpos, cp_2, cp2_hp, cp2_jpos, quot_num,quot_date, note, image, estimated_value) VALUES (
0,
'${POST_ENDUSER_QUERY.project_type}',
'${POST_ENDUSER_QUERY.status}',
'${POST_ENDUSER_QUERY.subject}',
'${POST_ENDUSER_QUERY.endUser_name}',
'${POST_ENDUSER_QUERY.location}',
'${POST_ENDUSER_QUERY.cp_1}',
'${POST_ENDUSER_QUERY.cp1_hp}',
'${POST_ENDUSER_QUERY.cp1_jpos}',
'${POST_ENDUSER_QUERY.cp_2}',
'${POST_ENDUSER_QUERY.cp2_hp}',
'${POST_ENDUSER_QUERY.cp2_jpos}',
'${POST_ENDUSER_QUERY.quot_num}',
'${POST_ENDUSER_QUERY.quot_date}',
'${POST_ENDUSER_QUERY.note}',
'${POST_ENDUSER_QUERY.image}',
'${POST_ENDUSER_QUERY.estimated_value}'
)`;
</code>```

and it's work and I already tested in Postman

Body:
I am working on ReactJs and NodeJS in sending data to MySql, in my frontPage.js The problem is I already tested the API to post data using Postman and no error appears. And the problem comes when I tried in ReactJs, I coded this :

class InputEndUser extends Component {
    constructor(props){
        super(props);

        this.state = {
            project_type: '',
            status : '',
            subject : '',
            enduser_name : '',
            location : '',
            cp_1 : '',
            cp1_hp : '',
            cp1_jpos: '',
            cp_2 : '',
            cp2_hp : '',
            cp2_jpos : '',
            quot_num : '',
            quot_date : '',
            note : ''

        }
        this.handleProject_type = this.handleProject_type.bind(this);
        this.handleStatus = this.handleStatus.bind(this);
        this.handleSubject = this.handleSubject.bind(this);
        this.handleEnduser_name = this.handleEnduser_name.bind(this);
        this.handleLocation = this.handleLocation.bind(this);
        this.handleCP1 = this.handleCP1.bind(this);
        this.handleCP1_hp = this.handleCP1_hp.bind(this);
        this.handleCP1_jpos = this.handleCP1_jpos.bind(this);
        this.handleCP2 = this.handleCP2.bind(this);
        this.handleCP2 = this.handleCP2.bind(this);
        this.handleCP2_hp = this.handleCP2_hp.bind(this);
        this.handleCP2_jpos = this.handleCP2_jpos.bind(this);
        this.handleQuot_num = this.handleQuot_num.bind(this);
        this.handleQuot_date = this.handleQuot_date.bind (this);
        this.handleNotes = this.handleNotes.bind(this);
    }

    handleProject_type(event){
        this.setState ({
            project_type : event.target.value
        })
    }

    handleStatus(event){
        this.setState({
            status: event.target.value
        })
    }

    handleSubject(event){
        this.setState({
            subject: event.target.value
        })
    }

    handleEnduser_name (event) {
        this.setState({
            enduser_name: event.target.value
        })
    }

    handleLocation(event){
        this.setState({
            location: event.target.value
        })
    }

    handleCP1(event){
        this.setState({
            cp_1: event.target.value
        })
    }

    handleCP1_hp(event){
        this.setState ({
            cp1_hp : event.target.value
        })
    }

    handleCP1_jpos(event){
        this.setState ({
            cp1_jpos : event.target.value
        })
    }

    handleCP2(event){
        this.setState({
            cp_2: event.target.value
        })
    }

    handleCP2_hp(event){
        this.setState ({
            cp2_hp : event.target.value
        })
    }

    handleCP2_jpos(event){
        this.setState ({
            cp2_jpos : event.target.value
        })
    }

    handleQuot_num(event) {
        this.setState ({
            quot_num : event.target.value
        })
    }

    handleQuot_date (event) {
        this.setState({
            quot_date : event.target.value
        })
    }

    handleNotes(event) {
        this.setState({
            note : event.target.value
        })
    }

    submitEndUser(event){
        event.preventDefault();
        fetch('http://localhost:4000/enduser', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        })
        .then ((response) => {
            return response.json;
        })
        .then ((body) => {
            console.log(body);
        })
        .catch((error) => {
            console.log(error)
        })
    }

and My API in server.js :

app.post('/enduser', (req, res) => {
  let POST_ENDUSER_QUERY =  {
    project_id: req.body.project_id,
    project_type: req.body.project_type,
    status: req.body.status,
    subject: req.body.subject,
    endUser_name: req.body.endUser_name,
    location: req.body.location,
    cp_1: req.body.cp_1,
    cp1_hp: req.body.cp1_hp,
    cp1_jpos: req.body.cp1_jpos,
    cp_2: req.body.cp_1,
    cp2_hp: req.body.cp1_hp,
    cp2_jpos: req.body.cp1_jpos,
    quot_num: req.body.quot_num,
    quot_date: req.body.quot_date,
    note: req.body.note,
    image: req.body.image,
    estimated_value: req.body.estimated_value
  };
  if (!POST_ENDUSER_QUERY) {
    return res.status(400).send({ err: true, message: 'Please project name' });
  }

  let query = `INSERT INTO enduser_tbl (project_id, project_type, status, subject, endUser_name, location, cp_1, cp1_hp, cp1_jpos, cp_2, cp2_hp, cp2_jpos, quot_num,quot_date, note, image, estimated_value) VALUES (
    '${POST_ENDUSER_QUERY.project_id}',
    '${POST_ENDUSER_QUERY.project_type}',
    '${POST_ENDUSER_QUERY.status}',
    '${POST_ENDUSER_QUERY.subject}',
    '${POST_ENDUSER_QUERY.endUser_name}',
    '${POST_ENDUSER_QUERY.location}',
    '${POST_ENDUSER_QUERY.cp_1}',
    '${POST_ENDUSER_QUERY.cp1_hp}',
    '${POST_ENDUSER_QUERY.cp1_jpos}',
    '${POST_ENDUSER_QUERY.cp_2}',
    '${POST_ENDUSER_QUERY.cp2_hp}',
    '${POST_ENDUSER_QUERY.cp2_jpos}',
    '${POST_ENDUSER_QUERY.quot_num}',
    '${POST_ENDUSER_QUERY.quot_date}',
    '${POST_ENDUSER_QUERY.note}',
    '${POST_ENDUSER_QUERY.image}',
    '${POST_ENDUSER_QUERY.estimated_value}'
    )`;
  dbConn.query(query, ( err, results) => {
    if(err) throw err;
    return res.status(200).json({"status": 200, "err" : null, "data": results});
  });
});

and the error came :

also in terminal when I test it with some kind of data, appears like this:

Body:
I got the problem for my case here ...
after trying with some suggestions...

I needed to include body in my POST like this :

 fetch('http://localhost:4000/enduser', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify(this.state)
        })

Finally I solved the problem in back-end connection with Auto Increment field in mysql database. I change project_id in values with this :

 let query = `INSERT INTO enduser_tbl (project_id, project_type, status, subject, endUser_name, location, cp_1, cp1_hp, cp1_jpos, cp_2, cp2_hp, cp2_jpos, quot_num,quot_date, note, image, estimated_value) VALUES (
0,
'${POST_ENDUSER_QUERY.project_type}',
'${POST_ENDUSER_QUERY.status}',
'${POST_ENDUSER_QUERY.subject}',
'${POST_ENDUSER_QUERY.endUser_name}',
'${POST_ENDUSER_QUERY.location}',
'${POST_ENDUSER_QUERY.cp_1}',
'${POST_ENDUSER_QUERY.cp1_hp}',
'${POST_ENDUSER_QUERY.cp1_jpos}',
'${POST_ENDUSER_QUERY.cp_2}',
'${POST_ENDUSER_QUERY.cp2_hp}',
'${POST_ENDUSER_QUERY.cp2_jpos}',
'${POST_ENDUSER_QUERY.quot_num}',
'${POST_ENDUSER_QUERY.quot_date}',
'${POST_ENDUSER_QUERY.note}',
'${POST_ENDUSER_QUERY.image}',
'${POST_ENDUSER_QUERY.estimated_value}'
)`;

and it's work and I already tested in Postman


问:
How to convert to camel casing after a symbol?
```<code>Input #2: profile.Address.AddressLine1
Result: profile.address.addressLine1

Input #2: MyName
Result: myName
</code>```

<hr>

```<code>using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string inputText = "profile.Business.AddressLine1"; //profile.business.addressLine1
            //string inputText = "MyName"; //myName
            string result = null;

            if (inputText.Contains('.'))
            {
                //make first character lowercase
                result = inputText.Substring(0, 1).ToLower() + inputText.Substring(1);

                //Loop to find period symbol
                //make the next character after the period symbol lowercase
            }
            else
            {
                //make first character lowercase
                result = inputText.Substring(0, 1).ToLower() + inputText.Substring(1);
            }
        }
    }
}
</code>```

答:
You should use this code:</p>

```<code>static string convertToCamelCase(string inputText)
{
    string result = string.Empty;
    if (string.IsNullOrEmpty(inputText)) return result;

    var inputs = inputText.Split('.');
    for(int i = 0; i < inputs.Length; i++)
    {
        if (String.IsNullOrEmpty(inputs[i])) continue;
        inputs[i] = inputs[i].Substring(0, 1).ToLower() + inputs[i].Substring(1);
    }

    result = string.Join(".", inputs);
    return result;
}
</code>```

Body:
Input #2: profile.Address.AddressLine1
Result: profile.address.addressLine1

Input #2: MyName
Result: myName

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string inputText = "profile.Business.AddressLine1"; //profile.business.addressLine1
            //string inputText = "MyName"; //myName
            string result = null;

            if (inputText.Contains('.'))
            {
                //make first character lowercase
                result = inputText.Substring(0, 1).ToLower() + inputText.Substring(1);

                //Loop to find period symbol
                //make the next character after the period symbol lowercase
            }
            else
            {
                //make first character lowercase
                result = inputText.Substring(0, 1).ToLower() + inputText.Substring(1);
            }
        }
    }
}

Body:
You should use this code:

static string convertToCamelCase(string inputText)
{
    string result = string.Empty;
    if (string.IsNullOrEmpty(inputText)) return result;

    var inputs = inputText.Split('.');
    for(int i = 0; i < inputs.Length; i++)
    {
        if (String.IsNullOrEmpty(inputs[i])) continue;
        inputs[i] = inputs[i].Substring(0, 1).ToLower() + inputs[i].Substring(1);
    }

    result = string.Join(".", inputs);
    return result;
}


问:
How to extract question mark surrounded texts into an array in Javascript
I have a string like this,

```<code>var str = " This is a ?sample? text to ?extract? question marks separated texts into an array in ?Javascript?. "
</code>```

I want a javascript array as below,

```<code>arr = {
        'sample',
        'extract',
        'Javascript'
      }
</code>```

答:
You can alternate between keeping and ignoring letters each time you get to a "?". This will not include the text after an opening ? if there is no closing ?.

let str = "This ?? should ?only? leave ?four words? ?in? the ?result?. Ignoring if there is no ? closing question mark"
let result = []
let openingQuestionMark = false

let substring = ""

for (let key of str) {
  if (key === "?") {
    if (openingQuestionMark) {
      substring && result.push(substring)
      substring = ""
    }
    openingQuestionMark = !openingQuestionMark
    continue
  }

  if (openingQuestionMark) {
    substring += key
  }

}

console.log(result)```

Body:
I have a string like this,

var str = " This is a ?sample? text to ?extract? question marks separated texts into an array in ?Javascript?. "

I want a javascript array as below,

arr = {
        'sample',
        'extract',
        'Javascript'
      }