问:
Toggle classes when triggered by anchor
Using Bootstrap 4.1 to build a collapsible element.

```<code><div class="card text-left mb-3 mt-3">
  <div class="card-head p-3 d-flex justify-content-between">
    <h4>How do we get started?</h4>
    <a id="ToggleElement" class="" data-toggle="collapse" href="#collapse1" aria-expanded="false" aria-controls="collapse1"><i class="fas fa-caret-down"></i></a>
  </div>
  <div class="collapse" id="collapse1">
  <div class="card card-body">
    content...
  </div>
  </div>
</div>
</code>```

How do I change the class from caret-down when closed to caret-up when open.

I know I can use something kind of like

```<code><script type="text/javascript">
    function changeClass(){
        // Code to swap the classes
    }
    $('#ToggleElement').click(changeClass);
</script>
</code>```

What do I need to make this work?

答:
You can toggle caret without JavaScript workaround.

make both up and down displayed, and hide each of them when both parent elements have collapsed  or not.

:not(.collapsed) > i.fas.fa-caret-down {
  display: none;
}

.collapsed > i.fas.fa-caret-up {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<div class="accordion" id="accordionExample">
  <div class="card">
    <div class="card-header" id="headingOne">
      <h2 class="mb-0">
        <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1 <i class="fas fa-caret-down"></i><i class="fas fa-caret-up"></i>
        </button>
      </h2>
    </div>

    <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
        on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
        raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingTwo">
      <h2 class="mb-0">
        <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
          Collapsible Group Item #2 <i class="fas fa-caret-down"></i><i class="fas fa-caret-up"></i>
        </button>
      </h2>
    </div>
    <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionExample">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
        on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
        raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingThree">
      <h2 class="mb-0">
        <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
          Collapsible Group Item #3 <i class="fas fa-caret-down"></i><i class="fas fa-caret-up"></i>
        </button>
      </h2>
    </div>
    <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionExample">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
        on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
        raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
</div></code>```

Title: Toggle classes when triggered by anchor

Body:
Using Bootstrap 4.1 to build a collapsible element.

How do we get started?

    content...

How do I change the class from caret-down when closed to caret-up when open.

I know I can use something kind of like

What do I need to make this work?

Body:
You can toggle caret without JavaScript workaround.

make both up and down displayed, and hide each of them when both parent elements have collapsed  or not.

:not(.collapsed) > i.fas.fa-caret-down {
  display: none;
}

.collapsed > i.fas.fa-caret-up {
  display: none;
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<div class="accordion" id="accordionExample">
  <div class="card">
    <div class="card-header" id="headingOne">
      <h2 class="mb-0">
        <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1 <i class="fas fa-caret-down"></i><i class="fas fa-caret-up"></i>
        </button>
      </h2>
    </div>

    <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
        on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
        raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingTwo">
      <h2 class="mb-0">
        <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
          Collapsible Group Item #2 <i class="fas fa-caret-down"></i><i class="fas fa-caret-up"></i>
        </button>
      </h2>
    </div>
    <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionExample">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
        on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
        raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingThree">
      <h2 class="mb-0">
        <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
          Collapsible Group Item #3 <i class="fas fa-caret-down"></i><i class="fas fa-caret-up"></i>
        </button>
      </h2>
    </div>
    <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionExample">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
        on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
        raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
</div>


来源: stackexchange

问:
Node.js - Only displaying last element in JSON rsponse
I am parsing a JSON response generated by a remote API. I iterate through the response and store the desired fields in values. The I create my homeCard elements from pug template and pass it the values. This issue with this is that it only displays the last element in the json response (Sexy Beach 3). How do I alter my code so that a homecard is created each time I pass through the loop?

```<code>    const axios = require('axios');

axios({
  url: "https://api-v3.igdb.com/games",
  method: 'GET',
  headers: {
      'Accept': 'application/json',
      'user-key': 'user-key'
  },
  data: "fields name,summary,url,popularity;sort popularity desc;limit 4;"
})
  .then(response => {
    /* GET home page. */
    router.get('/', (req, res, next) => {
      res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
        });
    });
    //Iterate through the JSON array
    let r = response.data;
    for (i=0; i<r.length; ++i){
      //create homecards with
        var title = r[i].name;
        var description = r[i].summary;
        var link = r[i].url;
        var homeCards = [
          {
            title: title,
            link: link,
            description: description,
          },
          {
            title: title,
            link: link,
            description: description,
          },
          {
            title: title,
            link: link,
            description: description,
          },
          {
            title: title,
            link: link,
            description: description,
          },
          ]
        console.log(title, description, link);
      }

          })
  .catch(err => {
      console.error(err);
  });
</code>```

Here is the JSON response

答:
You are assigning the same value to the homecards array object,also overwrites the same array every iteration.
You have to declare the homecards array outside the loop and push the objects to it.</p>

```<code>    const axios = require('axios');

axios({
  url: "https://api-v3.igdb.com/games",
  method: 'GET',
  headers: {
      'Accept': 'application/json',
      'user-key': 'user-key'
  },
  data: "fields name,summary,url,popularity;sort popularity desc;limit 4;"
})
  .then(response => {
    /* GET home page. */
    router.get('/', (req, res, next) => {
      res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
        });
    });
    //Iterate through the JSON array
    let r = response.data;
    var homeCards = [];
    for (i=0; i<r.length; ++i){
      //create homecards with
        var title = r[i].name;
        var description = r[i].summary;
        var link = r[i].url;
         homeCards.push({
            title: title,
            link: link,
            description: description,
          });
        console.log(title, description, link);
      }

          })
  .catch(err => {
      console.error(err);
  });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am parsing a JSON response generated by a remote API. I iterate through the response and store the desired fields in values. The I create my homeCard elements from pug template and pass it the values. This issue with this is that it only displays the last element in the json response (Sexy Beach 3). How do I alter my code so that a homecard is created each time I pass through the loop?

    const axios = require('axios');

axios({
  url: "https://api-v3.igdb.com/games",
  method: 'GET',
  headers: {
      'Accept': 'application/json',
      'user-key': 'user-key'
  },
  data: "fields name,summary,url,popularity;sort popularity desc;limit 4;"
})
  .then(response => {
    /* GET home page. */
    router.get('/', (req, res, next) => {
      res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
        });
    });
    //Iterate through the JSON array
    let r = response.data;
    for (i=0; i<r.length; ++i){
      //create homecards with
        var title = r[i].name;
        var description = r[i].summary;
        var link = r[i].url;
        var homeCards = [
          {
            title: title,
            link: link,
            description: description,
          },
          {
            title: title,
            link: link,
            description: description,
          },
          {
            title: title,
            link: link,
            description: description,
          },
          {
            title: title,
            link: link,
            description: description,
          },
          ]
        console.log(title, description, link);
      }

          })
  .catch(err => {
      console.error(err);
  });

Here is the JSON response

Body:
You are assigning the same value to the homecards array object,also overwrites the same array every iteration.
You have to declare the homecards array outside the loop and push the objects to it.

    const axios = require('axios');

axios({
  url: "https://api-v3.igdb.com/games",
  method: 'GET',
  headers: {
      'Accept': 'application/json',
      'user-key': 'user-key'
  },
  data: "fields name,summary,url,popularity;sort popularity desc;limit 4;"
})
  .then(response => {
    /* GET home page. */
    router.get('/', (req, res, next) => {
      res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
        });
    });
    //Iterate through the JSON array
    let r = response.data;
    var homeCards = [];
    for (i=0; i<r.length; ++i){
      //create homecards with
        var title = r[i].name;
        var description = r[i].summary;
        var link = r[i].url;
         homeCards.push({
            title: title,
            link: link,
            description: description,
          });
        console.log(title, description, link);
      }

          })
  .catch(err => {
      console.error(err);
  });


问:
Laravel - How to Transform Raw Query to Eloquent in Laravel
How do I transform my raw query to Laravel Eloquent

I want to transform

```<code>        $games = DB::table('game_point')
                     ->select('game_point.game_name','game_point.description','game_point.point_assigned', DB::raw("DATE(game_point.created_at) as created_at"))
                       ->paginate(15);
</code>```

to

```<code>$games= new GamePoint();
</code>```

答:
To try this,
Here you change your date format in Date() function.</p>

```<code>$data = GamePoint::select('game_point.game_name','game_point.description','game_point.point_assigned','game_point.created_at')->paginate(15);

foreach($data as $key => $val){
   $data[$key]->created_at = Date('Y-m-d',strtotime($data[$key]->created_at));
}
</code>```

Body:
How do I transform my raw query to Laravel Eloquent

I want to transform

        $games = DB::table('game_point')
                     ->select('game_point.game_name','game_point.description','game_point.point_assigned', DB::raw("DATE(game_point.created_at) as created_at"))
                       ->paginate(15);

to

$games= new GamePoint();

Body:
To try this,
Here you change your date format in Date() function.

$data = GamePoint::select('game_point.game_name','game_point.description','game_point.point_assigned','game_point.created_at')->paginate(15);

foreach($data as $key => $val){
   $data[$key]->created_at = Date('Y-m-d',strtotime($data[$key]->created_at));
}


问:
Append the next line to previous line
I have file of 5GB in this format:

```<code>dn: cn
changetype: add
objectclass: ine
hghsfgdsdsdsd
mail: surcom
surname: satya2
givenname: surya2
cn: surya2
</code>```

```<code>dn: cn
changetype: add
objectclass: inetOrgPerson
surname: sa
sddsds
givenname: s
cn: sur
</code>```

as you can see the Object class and surname are getting to the next line.
I want then in same line.
And below code achieves it, but it throws memory error for large files,
can you change this code so that it works efficiently for large files.

```<code>import re

pattern = re.compile(r"(\w+):(.*)")

with open("uservolvo2.ldif", "r") as f:
    new_lines = []

    for line in f:

        if line.endswith('\n'):
            line = line[:-1]

        if line == "":
            new_lines.append(line)
            continue

        l = pattern.search(line)

        if l:
            new_lines.append(line)
        else:
            new_lines[-1] += line

with open("user_modified.ldif", "a") as f:
    f.write("\n".join(new_lines))
    f.write("\n\n")
</code>```

答:
I don't know how efficient a regex-based solution would be, nor have I benchmarked it, but here is one possible approach using re.sub on the entire file:

```<code>input = """objectclass: ine
hghsfgdsdsdsd
mail: surcom
surname: satya2"""

output = re.sub(r'objectclass:(\s*\S+)(.*?)surname:(\s*\S+)',
                "objectclass:\\1\nsurname:\\3\\2", input, flags=re.DOTALL)
print(output)
</code>```

This prints:

```<code>objectclass: ine
surname: satya2
hghsfgdsdsdsd
mail: surcom
</code>```

The above logic is to match an objectclass: line, followed by all content until reaching the surname: line.  Then, we piece back together the text in the order you want it, with surname immediately following objectclass.

Title: Append the next line to previous line

Body:
I have file of 5GB in this format:

dn: cn
changetype: add
objectclass: ine
hghsfgdsdsdsd
mail: surcom
surname: satya2
givenname: surya2
cn: surya2

dn: cn
changetype: add
objectclass: inetOrgPerson
surname: sa
sddsds
givenname: s
cn: sur

as you can see the Object class and surname are getting to the next line.
I want then in same line.
And below code achieves it, but it throws memory error for large files,
can you change this code so that it works efficiently for large files.

import re

pattern = re.compile(r"(\w+):(.*)")

with open("uservolvo2.ldif", "r") as f:
    new_lines = []

    for line in f:

        if line.endswith('\n'):
            line = line[:-1]

        if line == "":
            new_lines.append(line)
            continue

        l = pattern.search(line)

        if l:
            new_lines.append(line)
        else:
            new_lines[-1] += line

with open("user_modified.ldif", "a") as f:
    f.write("\n".join(new_lines))
    f.write("\n\n")

Body:
I don't know how efficient a regex-based solution would be, nor have I benchmarked it, but here is one possible approach using re.sub on the entire file:

input = """objectclass: ine
hghsfgdsdsdsd
mail: surcom
surname: satya2"""

output = re.sub(r'objectclass:(\s*\S+)(.*?)surname:(\s*\S+)',
                "objectclass:\\1\nsurname:\\3\\2", input, flags=re.DOTALL)
print(output)

This prints:

objectclass: ine
surname: satya2
hghsfgdsdsdsd
mail: surcom

The above logic is to match an objectclass: line, followed by all content until reaching the surname: line.  Then, we piece back together the text in the order you want it, with surname immediately following objectclass.


问:
C# MVC Query with WHERE clause and 2 params from the View
I need to query my database with a WHERE clause and pass to parameters from my view to the controller. I am at a total loss as I am a JavaScript and PHP developer and am currently learning dotnet MVC (I am using vs10 framework4).

I need to in essence make this query:

```<code>select * from myTable where column1=16 and column2=24
</code>```

The values of column1 and column2 are in my View.  I have found a million examples on how to pull either a whole table, or a result based upon one parameter, I cannot figure out how to do that simple query.

This seems like a simple task and I would appreciate any help as I have spent 5 hours trying to figure this out.

Here are some key components of my code that will hopefully help someone help me.  I sincerely appreciate any help.

Controller:

```<code>    public class SignBuilderController : Controller
    {

        SignBuilderModel signBuilderModel = new SignBuilderModel();

        //
        // Initialize database entities
        SignBuilderEntities _db;
        public SignBuilderController()
        {
            _db = new SignBuilderEntities();
        }

 //
        // Get /SignBuilder/PrintSetup
        [Authorize]
        public ActionResult PrintSetup()
        {

            var pricesList = signBuilderModel.GetPricingList().ToList();
            return View("PrintSetup", pricesList);

        }

// get Column1 and column 2 query
public ActionResult TestPage(int column1, int column1)
{
     //do something here
     return View();
}
</code>```

And in my View I would retrieve the values for my where clause from input fields.
Example:

```<code><input type="text" name="column1value" id="column1value" />
<input type="text" name="column2value" id="column2value" />
</code>```

Obviously I am using a Model as well, so if that is needed to make this work no problem.  I am really looking for sample code I can use as an example to learn from.  I really appreciate any help, and am about to pull out my hair.

答:
I'm assuming that the entities is a Linq to Entity right? if that is the case, couldn't you use:

```<code>var model = from e in entities
            where column1=16 and column2=24
            select e;
</code>```

and then pass that model into the vew.

Basically, if entities is of the type IQueryable or IEnumerable or any of the other linq-able interfaces, you can perform that type of query.  Make sure that you are using System.Linq; in the top of your code file.

Hope that helps!

ContentLicense: CC BY-SA 3.0

Body:
I need to query my database with a WHERE clause and pass to parameters from my view to the controller. I am at a total loss as I am a JavaScript and PHP developer and am currently learning dotnet MVC (I am using vs10 framework4).

I need to in essence make this query:

select * from myTable where column1=16 and column2=24

The values of column1 and column2 are in my View.  I have found a million examples on how to pull either a whole table, or a result based upon one parameter, I cannot figure out how to do that simple query.

This seems like a simple task and I would appreciate any help as I have spent 5 hours trying to figure this out.

Here are some key components of my code that will hopefully help someone help me.  I sincerely appreciate any help.

Controller:

    public class SignBuilderController : Controller
    {

        SignBuilderModel signBuilderModel = new SignBuilderModel();

        //
        // Initialize database entities
        SignBuilderEntities _db;
        public SignBuilderController()
        {
            _db = new SignBuilderEntities();
        }

 //
        // Get /SignBuilder/PrintSetup
        [Authorize]
        public ActionResult PrintSetup()
        {

            var pricesList = signBuilderModel.GetPricingList().ToList();
            return View("PrintSetup", pricesList);

        }

// get Column1 and column 2 query
public ActionResult TestPage(int column1, int column1)
{
     //do something here
     return View();
}

And in my View I would retrieve the values for my where clause from input fields.
Example:

<input type="text" name="column1value" id="column1value" />
<input type="text" name="column2value" id="column2value" />

Obviously I am using a Model as well, so if that is needed to make this work no problem.  I am really looking for sample code I can use as an example to learn from.  I really appreciate any help, and am about to pull out my hair.

Body:
I'm assuming that the entities is a Linq to Entity right? if that is the case, couldn't you use:

var model = from e in entities
            where column1=16 and column2=24
            select e;

and then pass that model into the vew.

Basically, if entities is of the type IQueryable or IEnumerable or any of the other linq-able interfaces, you can perform that type of query.  Make sure that you are using System.Linq; in the top of your code file.

Hope that helps!


问:
H264 decoder in opencv for real time video transmission
I am writing a client-server application which does real time video transmission from an android based phone to a server. The captured video from the phone camera is encoded using the android provided h264 encoder and transmitted via UDP socket. The frames are not RTP encapsulated. I need it to reduce the overhead and hence the delay.
On the receiver, I need to decode the incoming encoded frame. The data being sent on the UDP socket not only contains the encoded frame but some other information related to the frame as a part of its header. Each frame is encoded as an nal unit.

I am able to retrieve the frames from the received packet as a byte array. I can save this byte array as raw h264 file and playback using vlc and everything works fine.
However, I need to do some processing on this frame and hence need to use it with opencv.
Can anyone help me with decoding a raw h264 byte array in opencv?
Can ffmpeg be used for this?

答:
Short answer: ffmpeg and ffplay will work directly. I remember Opencv can be built on top of those 2. so shouldn`t be difficult to use the FFMEPG/FFSHOW plug in to convert to cv::Mat. Follow the docuemnts

OpenCV can use the FFmpeg library (http://ffmpeg.org/) as backend to
  record, convert and stream audio and video. FFMpeg is a complete,
  cross-reference solution. If you enable FFmpeg while configuring
  OpenCV than CMake will download and install the binaries in
  OPENCV_SOURCE_CODE/3rdparty/ffmpeg/. To use FFMpeg at runtime, you
  must deploy the FFMepg binaries with your application.

https://docs.opencv.org/3.4/d0/da7/videoio_overview.html

Last time, I have to play with DJI PSDK. And they only allow stream at UDP port  udp://192.168.5.293:23003 with H.264
So I wrote a simple ffmpeg interface to stream to the PSDK. But I have to debug it beforehand.  So I use ffplay to show this network stream to proof it is working. This is the script to show the stream. So you have to work on top of this to work as opencv plugin

```<code>ffplay -f h264 -i udp://192.168.1.45:23003
</code>```

Body:
Short answer: ffmpeg and ffplay will work directly. I remember Opencv can be built on top of those 2. so shouldn`t be difficult to use the FFMEPG/FFSHOW plug in to convert to cv::Mat. Follow the docuemnts

OpenCV can use the FFmpeg library (http://ffmpeg.org/) as backend to
  record, convert and stream audio and video. FFMpeg is a complete,
  cross-reference solution. If you enable FFmpeg while configuring
  OpenCV than CMake will download and install the binaries in
  OPENCV_SOURCE_CODE/3rdparty/ffmpeg/. To use FFMpeg at runtime, you
  must deploy the FFMepg binaries with your application.

https://docs.opencv.org/3.4/d0/da7/videoio_overview.html

Last time, I have to play with DJI PSDK. And they only allow stream at UDP port  udp://192.168.5.293:23003 with H.264
So I wrote a simple ffmpeg interface to stream to the PSDK. But I have to debug it beforehand.  So I use ffplay to show this network stream to proof it is working. This is the script to show the stream. So you have to work on top of this to work as opencv plugin

ffplay -f h264 -i udp://192.168.1.45:23003


问:
i can't Send Mail Using Contact Form With PHPMailer and Gmail SMTP
I'm trying to send an email from contact by using PHPMailer and Gmail SMTP, I actually don't know where is the issue?
I download PHPMailer from githup.
I tried to do it as this gay did.

contact.html

```<code>  <form action="contact.php" method="POST" class="p-5 ">
            <div class="row form-group">
              <div class=" mb-3 ">
                <label class="text-black" for="first-name">الاسم الاول</label>
                <input type="text" name="first-name" class="form-control" />
              </div>
              <div class="col">
                <label class="text-black" for="last-name">الاسم الاخير</label>
                <input type="text" name="last-name" class="form-control" />
              </div>
            </div>

            <div class="row form-group">
              <div class="col">
                <label class="text-black" for="email">إيميل</label>
                <input type="email" name="email" class="form-control" />
              </div>
            </div>

            <div class="row form-group">
              <div class="col">
                <label class="text-black" for="subject">الموضوع</label>
                <input type="subject" name="subject" class="form-control" />
              </div>
            </div>

            <div class="row form-group">
              <div class="col">
                <label class="text-black" for="message"
                  >محتوى الرسالة</label
                >
                <textarea
                  name="message"
                  cols="30"
                  rows="7"
                  class="form-control"
                  placeholder="اكتب هنا ..."
                ></textarea>
              </div>
            </div>

            <div class="row form-group">
              <div class="col2">
                <input
                  type="submit"
                  name="submit"
                  value="إرسال"
                  class="px-4 text-white"
                />
              </div>
            </div>
          </form>
</code>```

contact.php

```<code> <?php

       $result="";

if (isset($_POST['submit'])){
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;

$mail->isSMTP();
$mail->Host='smtp.gmail.com';
$mail->Port=587;
$mail->SMTPAuth=true;

$mail->SMTPSecure='tls';
$mail->Username='secret';
$mail->Password='secret';

$mail->setForm($_POST['email'],$_POST['first-name']);
$mail->addAddress('secret');
$mail->addReplyTo($_POST['email'],$_POST['last-name']);

$mail->isHTML(true);
$mail->subject='Contact Us: '.$_POST['subject'];
$mail->Body='<h1 align=center>الأسم :'.$_POST['first-name'].$_POST['last-name'].' الايميل: '.$_POST['email'].' العنوان: '.$_POST['subject'].' العنوان: '.$_POST['message'].'</h1>';

if(!$mail->send()){
    $result="حدث خطاء حاول مرة اخرى ، وشكراً";
}
else{
    $result="شكراً".$_POST['fname']."لتواصلك معنا ،سيتم الرد عليكم
        قريباً";
  }
 }
 ?>
</code>```

the error message page  Doesn't exist

thank you

答: If you have 2 step verification enabled for your gmail account, gmail won't allow you to send email through your app. You have to generate app password and use it to send mails. Check here how to generate app password to use from third party apps. https://support.google.com/accounts/answer/185833?hl=en</p>

Body:
I'm trying to send an email from contact by using PHPMailer and Gmail SMTP, I actually don't know where is the issue?
I download PHPMailer from githup.
I tried to do it as this gay did.

contact.html

  <form action="contact.php" method="POST" class="p-5 ">

                الاسم الاول
                <input type="text" name="first-name" class="form-control" />

                الاسم الاخير
                <input type="text" name="last-name" class="form-control" />

                إيميل
                <input type="email" name="email" class="form-control" />

                الموضوع
                <input type="subject" name="subject" class="form-control" />

                محتوى الرسالة
                <textarea
                  name="message"
                  cols="30"
                  rows="7"
                  class="form-control"
                  placeholder="اكتب هنا ..."
                ></textarea>

                <input
                  type="submit"
                  name="submit"
                  value="إرسال"
                  class="px-4 text-white"
                />

          </form>

contact.php

 <?php

       $result="";

if (isset($_POST['submit'])){
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;

$mail->isSMTP();
$mail->Host='smtp.gmail.com';
$mail->Port=587;
$mail->SMTPAuth=true;

$mail->SMTPSecure='tls';
$mail->Username='secret';
$mail->Password='secret';

$mail->setForm($_POST['email'],$_POST['first-name']);
$mail->addAddress('secret');
$mail->addReplyTo($_POST['email'],$_POST['last-name']);

$mail->isHTML(true);
$mail->subject='Contact Us: '.$_POST['subject'];
$mail->Body='
الأسم :'.$_POST['first-name'].$_POST['last-name'].' الايميل: '.$_POST['email'].' العنوان: '.$_POST['subject'].' العنوان: '.$_POST['message'].'
';

if(!$mail->send()){
    $result="حدث خطاء حاول مرة اخرى ، وشكراً";
}
else{
    $result="شكراً".$_POST['fname']."لتواصلك معنا ،سيتم الرد عليكم
        قريباً";
  }
 }
 ?>

the error message page  Doesn't exist

thank you


问:
How to manage serialize / deserialize an enum property with Dart / Flutter to Firestore?
I need to store a Dart object from my Flutter application in Firestore

This object includes an enum property.

What is the best solution to serialize / deserialize this enum property ?

As a String

As an Int

I do not find any easy solution to do this.

答:
Gunter's answer is correct if a little incomplete.

JSON serializable does handle converting Enum's to and from a string, here is some example code of what is generated:

const _$HoursEnumMap = <Hours, dynamic>{
  Hours.FullTime: 'FullTime',
  Hours.PartTime: 'PartTime',
  Hours.Casual: 'Casual',
  Hours.Contract: 'Contract',
  Hours.Other: 'Other'
};
```

<p>and in return it converts it back with this fairly obtuse function:</p>

<pre class="lang-dart prettyprint-override"><code>T _$enumDecode<T>(Map<T, dynamic> enumValues, dynamic source) {
  if (source == null) {
    throw ArgumentError('A value must be provided. Supported values: '
        '${enumValues.values.join(', ')}');
  }
  return enumValues.entries
      .singleWhere((e) => e.value == source,
          orElse: () => throw ArgumentError(
              '`$source` is not one of the supported values: '
              '${enumValues.values.join(', ')}'))
      .key;
}
</code>```

I got so sick of this I decided to make a small package to take away the complexity, and it has come in pretty handy for me:

https://pub.dev/packages/enum_to_string

At the very least its unit tested over a copy/paste solution. Any additions or pull requests are welcome.

Body:
Gunter's answer is correct if a little incomplete.

JSON serializable does handle converting Enum's to and from a string, here is some example code of what is generated:

const _$HoursEnumMap = <Hours, dynamic>{
  Hours.FullTime: 'FullTime',
  Hours.PartTime: 'PartTime',
  Hours.Casual: 'Casual',
  Hours.Contract: 'Contract',
  Hours.Other: 'Other'
};

and in return it converts it back with this fairly obtuse function:

T _$enumDecode<T>(Map<T, dynamic> enumValues, dynamic source) {
  if (source == null) {
    throw ArgumentError('A value must be provided. Supported values: '
        '${enumValues.values.join(', ')}');
  }
  return enumValues.entries
      .singleWhere((e) => e.value == source,
          orElse: () => throw ArgumentError(
              '`$source` is not one of the supported values: '
              '${enumValues.values.join(', ')}'))
      .key;
}

I got so sick of this I decided to make a small package to take away the complexity, and it has come in pretty handy for me:

https://pub.dev/packages/enum_to_string

At the very least its unit tested over a copy/paste solution. Any additions or pull requests are welcome.


问:
Confusion regarding code access security with unverifiable code
I am confused about what I need to do in order to correctly "set up" my unverifiable method so that it conforms to code access security guidelines.

Given the following method

```<code>[MethodImpl(MethodImplOptions.ForwardRef)]
private extern void DoStuffUnverifiable();
</code>```

which is deemed unverifiable by PEVerify, what attributes do I absolutely need to apply to the method definition?

[SecurityCritical]?

[SecuritySafeCritical]?

How do I decide between those two? Further,

do I need to set [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]?

If so, do I use SecurityAction.Demand or something else?

Are there any other attributes I definitely need to apply? Are there any that I could apply, although not neccessary?

答:
In the transparency model, security-critical methods are marked with the [SecurityCritical] attribute:

```<code>[SecurityCritical]
public Key GetTVRoomKey() { ... }
</code>```

All “dangerous” methods (containing code that the CLR considers could breach security and allow an inmate to
escape) must be marked with [SecurityCritical] or [SecuritySafeCritical]. This comprises:

Unverifiable (unsafe) methods

Methods that call unmanaged code via P/Invoke or COM interop

Methods that Assert permissions or call link-demanding methods

Methods that call [SecurityCritical] methods

Methods that override virtual [SecurityCritical] methods

[SecurityCritical] means “this method could allow a partially trusted caller to escape a sandbox”.
[SecuritySafeCritical] means “this method does security-critical things—but with appropriate safeguards
and so is safe for partially trusted callers”.

So yes, in your case - [SecurityCritical] is surely needed, if you want extra safety, use [SecuritySafeCritical]

Body:
I am confused about what I need to do in order to correctly "set up" my unverifiable method so that it conforms to code access security guidelines.

Given the following method

[MethodImpl(MethodImplOptions.ForwardRef)]
private extern void DoStuffUnverifiable();

which is deemed unverifiable by PEVerify, what attributes do I absolutely need to apply to the method definition?

[SecurityCritical]?

[SecuritySafeCritical]?

How do I decide between those two? Further,

do I need to set [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]?

If so, do I use SecurityAction.Demand or something else?

Are there any other attributes I definitely need to apply? Are there any that I could apply, although not neccessary?

Body:
In the transparency model, security-critical methods are marked with the [SecurityCritical] attribute:

[SecurityCritical]
public Key GetTVRoomKey() { ... }

All “dangerous” methods (containing code that the CLR considers could breach security and allow an inmate to
escape) must be marked with [SecurityCritical] or [SecuritySafeCritical]. This comprises:

Unverifiable (unsafe) methods

Methods that call unmanaged code via P/Invoke or COM interop

Methods that Assert permissions or call link-demanding methods

Methods that call [SecurityCritical] methods

Methods that override virtual [SecurityCritical] methods

[SecurityCritical] means “this method could allow a partially trusted caller to escape a sandbox”.
[SecuritySafeCritical] means “this method does security-critical things—but with appropriate safeguards
and so is safe for partially trusted callers”.

So yes, in your case - [SecurityCritical] is surely needed, if you want extra safety, use [SecuritySafeCritical]


问:
How to display parameter only by Role ID
I have a problem when debug the code..User had been registered the field and it got to another page. But when go to the another page, all the parameter were include in URL..
example:
http://localhost:56767/Pendaftaran/VerifyEmail?Role=3&FirstName=Abu&LastName=Mutalib&ICNumber=8812511469&Gender=1&Email=abu%40gmail.com&Password=aaabbb&ConfirmPassword=aaabbb&State=16&MobileNumber=012-7415511

This is using stored procedured database on sql server.

```<code>[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult AddParticipant(RegistrationModel obj)
    {
        try
        {

            if (ModelState.IsValid)
            {

                if (this.IsCaptchaValid("Captcha is not valid")) //Added Captcha 17 May 2019 -Aidil-
                {

                    if (obj.Role == 2) //Add if else for club 17 May 2019 -Aidil-
                    {
                        if (obj.CLubRegistration != null)
                        {

                            //Add Stored Procedured -Aidil- 15 May 2019
                            connection();
                            SqlCommand com = new SqlCommand("uspRegisterParticipant", con);
                            com.CommandType = CommandType.StoredProcedure;
                            com.Parameters.AddWithValue("@Role", obj.Role);
                            com.Parameters.AddWithValue("@ClubReg", obj.CLubRegistration); //Added ClubRegistration 16 May 2019 -Aidil-
                            com.Parameters.AddWithValue("@FirstName", obj.FirstName);
                            com.Parameters.AddWithValue("@LastName", obj.LastName);
                            com.Parameters.AddWithValue("@ICNumber", obj.ICNumber);
                            com.Parameters.AddWithValue("@Gender", obj.Gender);
                            com.Parameters.AddWithValue("@Email", obj.Email);
                            com.Parameters.AddWithValue("@Password", obj.Password);
                            com.Parameters.AddWithValue("@State", obj.State);
                            com.Parameters.AddWithValue("@MobileNumber", obj.MobileNumber);  //Added MobileNumber 16 May 2019 -Aidil-
                            con.Open();
                            int i = com.ExecuteNonQuery();
                            con.Close();

                            //End Added Stored Procedured -Aidil- 15 May 2019

                        }

                    }
                    else
                    {
                        connection();
                        SqlCommand com = new SqlCommand("uspRegisterParticipant", con);
                        com.CommandType = CommandType.StoredProcedure;
                        com.Parameters.AddWithValue("@Role", obj.Role);
                        com.Parameters.AddWithValue("@FirstName", obj.FirstName);
                        com.Parameters.AddWithValue("@LastName", obj.LastName);
                        com.Parameters.AddWithValue("@ICNumber", obj.ICNumber);
                        com.Parameters.AddWithValue("@Gender", obj.Gender);
                        com.Parameters.AddWithValue("@Email", obj.Email);
                        com.Parameters.AddWithValue("@Password", obj.Password);
                        com.Parameters.AddWithValue("@State", obj.State);
                        com.Parameters.AddWithValue("@MobileNumber", obj.MobileNumber);  //Added MobileNumber 16 May 2019 -Aidil-
                        con.Open();
                        int i = com.ExecuteNonQuery();
                        con.Close();
                        //End Added Stored Procedured -Aidil- 15 May 2019
                    }

                    return RedirectToAction("VerifyEmail", obj); //Update RedirectAction 27 May 2019 -Aidil-

                }
                ViewBag.ErrMessage = "Error: captcha is not valid.";
                //return View();

            }

            return View();

        }
        catch (Exception e)
        {
            Console.WriteLine("{0} Exception caught.", e);
            return View();
        }

    }

    // GET: Pendaftaran/VerifyEmail
    //Added VerifyEmail 27 May 2019 -Aidil-
    [HttpGet]
    public ActionResult VerifyEmail(EmailVerificationModel obj)
    {
        try
        {

            //Add Stored Procedured -Aidil- 27 May 2019
            connection();
            SqlCommand com = new SqlCommand("uspDisplayNameForVerification", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@FirstName", obj.FirstName); //Added called from AddParicipant 28 May 2019 -Aidil-
            com.Parameters.AddWithValue("@LastName", obj.LastName); //Added called from AddParicipant 28 May 2019 -Aidil-

            con.Open();
            //int i = com.ExecuteNonQuery();
            SqlDataAdapter da = new SqlDataAdapter(com);
            con.Close();
            return View(obj); //Update view () to view(obj) -Aidil- 29 May 2019

        }

       catch (Exception e)
        {
            Console.WriteLine("{0} Exception caught.", e);
            return View();
        }
    }
    //End Added VerifyEmail 27 May 2019 -Aidil-

}
</code>```

Supposedly i want show only this :
http://localhost:56767/Pendaftaran/VerifyEmail?Role=3

not like this one:
http://localhost:56767/Pendaftaran/VerifyEmail?Role=3&FirstName=Abu&LastName=Mutalib&ICNumber=8812511469&Gender=1&Email=abu%40gmail.com&Password=aaabbb&ConfirmPassword=aaabbb&State=16&MobileNumber=012-7415511

答:
You are passing the whole object while redirecting i.e obj which will tale all parameters
you can just pass the required field

try

```<code>  return RedirectToAction("VerifyEmail", obj.Role);
</code>```

this will take Role parameter as query string to next page.

Body:
I have a problem when debug the code..User had been registered the field and it got to another page. But when go to the another page, all the parameter were include in URL..
example:
http://localhost:56767/Pendaftaran/VerifyEmail?Role=3&FirstName=Abu&LastName=Mutalib&ICNumber=8812511469&Gender=1&Email=abu%40gmail.com&Password=aaabbb&ConfirmPassword=aaabbb&State=16&MobileNumber=012-7415511

This is using stored procedured database on sql server.

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult AddParticipant(RegistrationModel obj)
    {
        try
        {

            if (ModelState.IsValid)
            {

                if (this.IsCaptchaValid("Captcha is not valid")) //Added Captcha 17 May 2019 -Aidil-
                {

                    if (obj.Role == 2) //Add if else for club 17 May 2019 -Aidil-
                    {
                        if (obj.CLubRegistration != null)
                        {

                            //Add Stored Procedured -Aidil- 15 May 2019
                            connection();
                            SqlCommand com = new SqlCommand("uspRegisterParticipant", con);
                            com.CommandType = CommandType.StoredProcedure;
                            com.Parameters.AddWithValue("@Role", obj.Role);
                            com.Parameters.AddWithValue("@ClubReg", obj.CLubRegistration); //Added ClubRegistration 16 May 2019 -Aidil-
                            com.Parameters.AddWithValue("@FirstName", obj.FirstName);
                            com.Parameters.AddWithValue("@LastName", obj.LastName);
                            com.Parameters.AddWithValue("@ICNumber", obj.ICNumber);
                            com.Parameters.AddWithValue("@Gender", obj.Gender);
                            com.Parameters.AddWithValue("@Email", obj.Email);
                            com.Parameters.AddWithValue("@Password", obj.Password);
                            com.Parameters.AddWithValue("@State", obj.State);
                            com.Parameters.AddWithValue("@MobileNumber", obj.MobileNumber);  //Added MobileNumber 16 May 2019 -Aidil-
                            con.Open();
                            int i = com.ExecuteNonQuery();
                            con.Close();

                            //End Added Stored Procedured -Aidil- 15 May 2019

                        }

                    }
                    else
                    {
                        connection();
                        SqlCommand com = new SqlCommand("uspRegisterParticipant", con);
                        com.CommandType = CommandType.StoredProcedure;
                        com.Parameters.AddWithValue("@Role", obj.Role);
                        com.Parameters.AddWithValue("@FirstName", obj.FirstName);
                        com.Parameters.AddWithValue("@LastName", obj.LastName);
                        com.Parameters.AddWithValue("@ICNumber", obj.ICNumber);
                        com.Parameters.AddWithValue("@Gender", obj.Gender);
                        com.Parameters.AddWithValue("@Email", obj.Email);
                        com.Parameters.AddWithValue("@Password", obj.Password);
                        com.Parameters.AddWithValue("@State", obj.State);
                        com.Parameters.AddWithValue("@MobileNumber", obj.MobileNumber);  //Added MobileNumber 16 May 2019 -Aidil-
                        con.Open();
                        int i = com.ExecuteNonQuery();
                        con.Close();
                        //End Added Stored Procedured -Aidil- 15 May 2019
                    }

                    return RedirectToAction("VerifyEmail", obj); //Update RedirectAction 27 May 2019 -Aidil-

                }
                ViewBag.ErrMessage = "Error: captcha is not valid.";
                //return View();

            }

            return View();

        }
        catch (Exception e)
        {
            Console.WriteLine("{0} Exception caught.", e);
            return View();
        }

    }

    // GET: Pendaftaran/VerifyEmail
    //Added VerifyEmail 27 May 2019 -Aidil-
    [HttpGet]
    public ActionResult VerifyEmail(EmailVerificationModel obj)
    {
        try
        {

            //Add Stored Procedured -Aidil- 27 May 2019
            connection();
            SqlCommand com = new SqlCommand("uspDisplayNameForVerification", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@FirstName", obj.FirstName); //Added called from AddParicipant 28 May 2019 -Aidil-
            com.Parameters.AddWithValue("@LastName", obj.LastName); //Added called from AddParicipant 28 May 2019 -Aidil-

            con.Open();
            //int i = com.ExecuteNonQuery();
            SqlDataAdapter da = new SqlDataAdapter(com);
            con.Close();
            return View(obj); //Update view () to view(obj) -Aidil- 29 May 2019

        }

       catch (Exception e)
        {
            Console.WriteLine("{0} Exception caught.", e);
            return View();
        }
    }
    //End Added VerifyEmail 27 May 2019 -Aidil-

}

Supposedly i want show only this :
http://localhost:56767/Pendaftaran/VerifyEmail?Role=3

not like this one:
http://localhost:56767/Pendaftaran/VerifyEmail?Role=3&FirstName=Abu&LastName=Mutalib&ICNumber=8812511469&Gender=1&Email=abu%40gmail.com&Password=aaabbb&ConfirmPassword=aaabbb&State=16&MobileNumber=012-7415511

Body:
You are passing the whole object while redirecting i.e obj which will tale all parameters
you can just pass the required field

try

  return RedirectToAction("VerifyEmail", obj.Role);

this will take Role parameter as query string to next page.


问:
How to Hot Reload shared library on Linux
I'm attempting to replicate a cool trick out of Casey Muratori's popular Handmade Hero series.  On win32, Casey was able to reload a DLL and see his code changes with only a few milliseconds of latency.

I'm trying to replicate this behavior on linux using dlopen, dlsym, dlclose and stat, but I'm running into the below behavior, and I have a hunch that I'm either misunderstanding something about ELF, the example, the linker, or perhaps the concept of shared objects all together.

I was able to get his code working without much difficult on win32, so I feel this is something specific to Linux that I'm missing.

I am using CMake to build, but I don't particularly believe CMake is the culprit.

I make a copy of the shared library dynamic.so, and load that.  Whenever the mtime of the original shared object updates, I close out the handle to the old copy, make a new copy, and then try to load the new copy.

I would like to point out that it was my intention to break the loop after the first change, since I'm just trying to figure this out.

#include <stdio.h>
#include <dlfcn.h>
#include <time.h>
#include <sys/stat.h>
#include <unistd.h>

void
CopyFile(const char* src, const char* dest)
{
  FILE* fsrc;
  FILE* fdest;
  unsigned char buffer[512];
  size_t bytes;

  fprintf(stderr, "copy from: %s to %s!\n", src, dest);

  fsrc = fopen(src, "rb");
  if ( fsrc == NULL )
    ┆   fprintf(stderr, "failed to open file: %s for reading\n", src);

  fdest = fopen(dest, "wb");
  if ( fdest == NULL )
    ┆   fprintf(stderr, "failed to open file: %s for reading\n", src);

  while ( (bytes = fread(buffer, 1, sizeof(buffer), fsrc)) > 0 )
    {
    ┆   fwrite(buffer, 1, bytes, fdest);
    }

  fclose(fsrc);
  fclose(fdest);

  fprintf(stderr, "copy complete!\n");
}

int main(int argc, char** argv)
{

const char* libpath = "/home/bacon/dynamic.so";
const char* copypath = "/home/bacon/dynamic-copy.so";
CopyFile(libpath, copypath);

void* handle = dlopen(copypath, RTLD_NOW | RTLD_GLOBAL);
if ( handle == NULL )
    fprintf(stderr, "failed to load %s, error = %s\n", copypath, dlerror());

struct stat s;
stat(libpath, &s);
time_t oldtime = s.st_mtime;
while (true)
{
    stat(libpath, &s);
    if ( oldtime != s.st_mtime )
    {
        if ( handle != NULL )
        {
            if ( dlclose(handle) )
                fprintf(stderr, "dlclose failed: %s\n", dlerror());
            else
                handle = NULL;
        }

        CopyFile(libpath, copypath);

        handle = dlopen(copypath, RTLD_NOW | RTLD_GLOBAL);
        if ( handle == NULL )
            fprintf(stderr, "failed to load %s, error = %s\n", copypath, dlerror());

        break;
    }
}
}

```

<p>As for the Dynamic Library, anything should do (example header):</p>

<pre class="lang-cpp prettyprint-override"><code>#ifndef DYNAMIC_HEADER
#define DYNAMIC_HEADER 1

#define DYNAMIC_API __attribute__ ((visibility("default")))

extern "C" DYNAMIC_API int
Add(int x, int y);

#endif /* DYNAMIC_HEADER */
</code>```

And the source file:

#include "Dynamic.h"

int
Add(int x, int y)
{
    return x + y;
}
```

<p>The shared library simply provides a few routines to add a few numbers together, and I've validated that I was able to dlopen and dlsym without the hot reload trickery.</p>

<p>I also validated my copy routine actually copies the shared object.</p>

<p>I expected the initial dlopen to succeed, and dlsym to correctly link Add (which it would).  I would then edit Dynamic.cpp and perhaps return x + x + y or something, save the file and recompile, expecting the while loop to pick up the change in st_mtime.</p>

<p>I noticed that when I ran the code and updated I received the error:</p>

<pre class="lang-sh prettyprint-override"><code>dlopen: file too short
</code>```

Sure enough, when I ls -la the directory containing the shared objects, the copy was size 0.

Somehow, the st_mtime reported by stat is updated, but the actual contents of the shared object are empty?  Is the linker locking up the shared object and preventing reads?

If my code isn't horribly wrong, how can I circumvent this sort of behavior?

I'm disinclined to sleep and retry, as this was intended to be a rather instantaneous update.

答:
If my code isn't horribly wrong

It is horribly wrong: your code is racing with the (static) linker (invoked by make or cmake).

When make runs, it (eventually) invokes:

```<code>gcc -shared -o /home/bacon/dynamic.so foo.o bar.o ...
</code>```

The linker will then perform open("/home/bacon/dynamic.so", O_WRONLY|O_CREAT, ...) (or equivalent), and some time later will write and finally close the file.

Your program will wake up when m_time has changed, which is any time after open, and will attempt to copy the file. IF your copy happens at any time before the final close, then you could end up with a partial copy (including a partial copy that contains 0 bytes).

The most obvious solution is the one suggested by Zsigmond: you must modify the Makefile to link a different file from the one you are watching, and perform a mv to final destination as the last (atomic) step.

An alternative solution is to have a make target that depends on dynamic.so, e.g.

```<code>dynamic.so.done: dynamic.so
        touch dynamic.so.done
</code>```

In your program, you would watch m_time for the dynamic.so.done, and only when that file is updated, perform the copy of dynamic.so (which is guaranteed to have been closed by that point).

Body:
I'm attempting to replicate a cool trick out of Casey Muratori's popular Handmade Hero series.  On win32, Casey was able to reload a DLL and see his code changes with only a few milliseconds of latency.

I'm trying to replicate this behavior on linux using dlopen, dlsym, dlclose and stat, but I'm running into the below behavior, and I have a hunch that I'm either misunderstanding something about ELF, the example, the linker, or perhaps the concept of shared objects all together.

I was able to get his code working without much difficult on win32, so I feel this is something specific to Linux that I'm missing.

I am using CMake to build, but I don't particularly believe CMake is the culprit.

I make a copy of the shared library dynamic.so, and load that.  Whenever the mtime of the original shared object updates, I close out the handle to the old copy, make a new copy, and then try to load the new copy.

I would like to point out that it was my intention to break the loop after the first change, since I'm just trying to figure this out.

#include <stdio.h>
#include <dlfcn.h>
#include <time.h>
#include <sys/stat.h>
#include <unistd.h>

void
CopyFile(const char* src, const char* dest)
{
  FILE* fsrc;
  FILE* fdest;
  unsigned char buffer[512];
  size_t bytes;

  fprintf(stderr, "copy from: %s to %s!\n", src, dest);

  fsrc = fopen(src, "rb");
  if ( fsrc == NULL )
    ┆   fprintf(stderr, "failed to open file: %s for reading\n", src);

  fdest = fopen(dest, "wb");
  if ( fdest == NULL )
    ┆   fprintf(stderr, "failed to open file: %s for reading\n", src);

  while ( (bytes = fread(buffer, 1, sizeof(buffer), fsrc)) > 0 )
    {
    ┆   fwrite(buffer, 1, bytes, fdest);
    }

  fclose(fsrc);
  fclose(fdest);

  fprintf(stderr, "copy complete!\n");
}

int main(int argc, char** argv)
{

const char* libpath = "/home/bacon/dynamic.so";
const char* copypath = "/home/bacon/dynamic-copy.so";
CopyFile(libpath, copypath);

void* handle = dlopen(copypath, RTLD_NOW | RTLD_GLOBAL);
if ( handle == NULL )
    fprintf(stderr, "failed to load %s, error = %s\n", copypath, dlerror());

struct stat s;
stat(libpath, &s);
time_t oldtime = s.st_mtime;
while (true)
{
    stat(libpath, &s);
    if ( oldtime != s.st_mtime )
    {
        if ( handle != NULL )
        {
            if ( dlclose(handle) )
                fprintf(stderr, "dlclose failed: %s\n", dlerror());
            else
                handle = NULL;
        }

        CopyFile(libpath, copypath);

        handle = dlopen(copypath, RTLD_NOW | RTLD_GLOBAL);
        if ( handle == NULL )
            fprintf(stderr, "failed to load %s, error = %s\n", copypath, dlerror());

        break;
    }
}
}

As for the Dynamic Library, anything should do (example header):

#ifndef DYNAMIC_HEADER
#define DYNAMIC_HEADER 1

#define DYNAMIC_API __attribute__ ((visibility("default")))

extern "C" DYNAMIC_API int
Add(int x, int y);

#endif /* DYNAMIC_HEADER */

And the source file:

#include "Dynamic.h"

int
Add(int x, int y)
{
    return x + y;
}

The shared library simply provides a few routines to add a few numbers together, and I've validated that I was able to dlopen and dlsym without the hot reload trickery.

I also validated my copy routine actually copies the shared object.

I expected the initial dlopen to succeed, and dlsym to correctly link Add (which it would).  I would then edit Dynamic.cpp and perhaps return x + x + y or something, save the file and recompile, expecting the while loop to pick up the change in st_mtime.

I noticed that when I ran the code and updated I received the error:

dlopen: file too short

Sure enough, when I ls -la the directory containing the shared objects, the copy was size 0.

Somehow, the st_mtime reported by stat is updated, but the actual contents of the shared object are empty?  Is the linker locking up the shared object and preventing reads?

If my code isn't horribly wrong, how can I circumvent this sort of behavior?

I'm disinclined to sleep and retry, as this was intended to be a rather instantaneous update.

Body:
If my code isn't horribly wrong

It is horribly wrong: your code is racing with the (static) linker (invoked by make or cmake).

When make runs, it (eventually) invokes:

gcc -shared -o /home/bacon/dynamic.so foo.o bar.o ...

The linker will then perform open("/home/bacon/dynamic.so", O_WRONLY|O_CREAT, ...) (or equivalent), and some time later will write and finally close the file.

Your program will wake up when m_time has changed, which is any time after open, and will attempt to copy the file. IF your copy happens at any time before the final close, then you could end up with a partial copy (including a partial copy that contains 0 bytes).

The most obvious solution is the one suggested by Zsigmond: you must modify the Makefile to link a different file from the one you are watching, and perform a mv to final destination as the last (atomic) step.

An alternative solution is to have a make target that depends on dynamic.so, e.g.

dynamic.so.done: dynamic.so
        touch dynamic.so.done

In your program, you would watch m_time for the dynamic.so.done, and only when that file is updated, perform the copy of dynamic.so (which is guaranteed to have been closed by that point).


问:
How to represent complex POST data in python for requests
I'm trying to automate a web form.  The payload when I actually run the query in Chrome looks like this on the inspect window...

```<code>    data: [{"property":"TimeQuick","value":"Active"},{"property":"TimeQuickDurationOptions","value":3},{"property":"TimeQuickStartDate","value":"05/15/2019 00:00:00"},{"property":"TimeQuickEndDate","value":"05/15/2019 23:59:59"},{"property":"ProviderCode","value":["FPL"]},{"property":"SellerCode","value":[""]},{"property":"Ref","value":""},{"property":"POR","value":["SOCO"]},{"property":"POD","value":["FPC"]},{"property":"Path","value":""},{"property":"ServiceIncrement","value":["DAILY"]},{"property":"TSClass","value":[""]},{"property":"TSType","value":[""]},{"property":"TSWindow","value":""},{"property":"TSPeriod","value":""},{"property":"TSSubClass","value":""},{"property":"Time","value":"Active"},{"property":"TimeDurationOptions","value":3},{"property":"TimeStartDate","value":"05/15/2019 00:00:00"},{"property":"TimeEndDate","value":"05/15/2019 23:59:59"},{"property":"ShowActiveData","value":true},{"property":"DaylightSavings","value":false}]
    sort: [{"property":"TOL","direction":"DESC","root":"data"}]
    pagingEnabled: 1
    page: 1
    limit: 50
</code>```

I tried to represent that as a python variable like this

```<code>    datareq = [
             ('data',
              {'property':'TimeQuick', 'value':'Active'},
              {"property":"TimeQuickDurationOptions","value":'3'},
              {"property":"TimeQuickStartDate","value":"05/15/2019 00:00:00"},
              {"property":"TimeQuickEndDate","value":"05/15/2019 23:59:59"},
              {"property":"ProviderCode","value":["FPL"]},
              {"property":"SellerCode","value":[""]},
              {"property":"Ref","value":""},
              {"property":"POR","value":["SOCO"]},
              {"property":"POD","value":["FPC"]},
              {"property":"Path","value":""},
              {"property":"ServiceIncrement","value":["DAILY"]},
              {"property":"TSClass","value":[""]},
              {"property":"TSType","value":[""]},
              {"property":"TSWindow","value":""},
              {"property":"TSPeriod","value":""},
              {"property":"TSSubClass","value":""},
              {"property":"Time","value":"Active"},
              {"property":"TimeDurationOptions","value":3},
              {"property":"TimeStartDate","value":"05/15/2019 00:00:00"},
              {"property":"TimeEndDate","value":"05/15/2019 23:59:59"},
              {"property":"ShowActiveData","value":'true'},
              {"property":"DaylightSavings","value":'false'}
              ),
             ('sort',
              {"property":"TOL","direction":"DESC","root":"data"}
              ),
             ('pagingEnabled', 1),
             ('limit', 50)

             ]
</code>```

When I ran s.post(myurl, data=datareq, cert=mycerts) I got the following error:

```<code>    Traceback (most recent call last):

      File "<ipython-input-78-37ee269ebbce>", line 1, in <module>
        logblah=s.post(myurl, data= datareq, cert=mycerts)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\sessions.py", line 555, in post
        return self.request('POST', url, data=data, json=json, **kwargs)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\sessions.py", line 494, in request
        prep = self.prepare_request(req)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\sessions.py", line 437, in prepare_request
        hooks=merge_hooks(request.hooks, self.hooks),

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\models.py", line 308, in prepare
        self.prepare_body(data, files, json)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\models.py", line 499, in prepare_body
        body = self._encode_params(data)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\models.py", line 97, in _encode_params
        for k, vs in to_key_val_list(data):

    ValueError: too many values to unpack (expected 2)
</code>```

I'm assuming the problem is in the way I've structured my datareq variable.  What would be the proper way to make that POST?

Edit/Update:
I've tried each of Alex and Ivan's suggestions but neither work.  They each give me a cryptic message from the server that success=false.  If I try them with json=datareq instead of data=datareq then I get a response from the server with 0 results even though it should have many so it seems like that is getting closer but still not all the way.

答:
You can put a regular JSON as an argument to post():

```<code>import json

datareq = {
    "data": [{"property":"TimeQuick","value":"Active"},{"property":"TimeQuickDurationOptions","value":3},{"property":"TimeQuickStartDate","value":"05/15/2019 00:00:00"},{"property":"TimeQuickEndDate","value":"05/15/2019 23:59:59"},{"property":"ProviderCode","value":["FPL"]},{"property":"SellerCode","value":[""]},{"property":"Ref","value":""},{"property":"POR","value":["SOCO"]},{"property":"POD","value":["FPC"]},{"property":"Path","value":""},{"property":"ServiceIncrement","value":["DAILY"]},{"property":"TSClass","value":[""]},{"property":"TSType","value":[""]},{"property":"TSWindow","value":""},{"property":"TSPeriod","value":""},{"property":"TSSubClass","value":""},{"property":"Time","value":"Active"},{"property":"TimeDurationOptions","value":3},{"property":"TimeStartDate","value":"05/15/2019 00:00:00"},{"property":"TimeEndDate","value":"05/15/2019 23:59:59"},{"property":"ShowActiveData","value":true},{"property":"DaylightSavings","value":false}],
    "sort": [{"property":"TOL","direction":"DESC","root":"data"}],
    "pagingEnabled": 1,
    "page": 1,
    "limit": 50
     }
s.post(myurl, data=json.dumps(datareq), cert=mycerts)
</code>```

Body:
I'm trying to automate a web form.  The payload when I actually run the query in Chrome looks like this on the inspect window...

    data: [{"property":"TimeQuick","value":"Active"},{"property":"TimeQuickDurationOptions","value":3},{"property":"TimeQuickStartDate","value":"05/15/2019 00:00:00"},{"property":"TimeQuickEndDate","value":"05/15/2019 23:59:59"},{"property":"ProviderCode","value":["FPL"]},{"property":"SellerCode","value":[""]},{"property":"Ref","value":""},{"property":"POR","value":["SOCO"]},{"property":"POD","value":["FPC"]},{"property":"Path","value":""},{"property":"ServiceIncrement","value":["DAILY"]},{"property":"TSClass","value":[""]},{"property":"TSType","value":[""]},{"property":"TSWindow","value":""},{"property":"TSPeriod","value":""},{"property":"TSSubClass","value":""},{"property":"Time","value":"Active"},{"property":"TimeDurationOptions","value":3},{"property":"TimeStartDate","value":"05/15/2019 00:00:00"},{"property":"TimeEndDate","value":"05/15/2019 23:59:59"},{"property":"ShowActiveData","value":true},{"property":"DaylightSavings","value":false}]
    sort: [{"property":"TOL","direction":"DESC","root":"data"}]
    pagingEnabled: 1
    page: 1
    limit: 50

I tried to represent that as a python variable like this

    datareq = [
             ('data',
              {'property':'TimeQuick', 'value':'Active'},
              {"property":"TimeQuickDurationOptions","value":'3'},
              {"property":"TimeQuickStartDate","value":"05/15/2019 00:00:00"},
              {"property":"TimeQuickEndDate","value":"05/15/2019 23:59:59"},
              {"property":"ProviderCode","value":["FPL"]},
              {"property":"SellerCode","value":[""]},
              {"property":"Ref","value":""},
              {"property":"POR","value":["SOCO"]},
              {"property":"POD","value":["FPC"]},
              {"property":"Path","value":""},
              {"property":"ServiceIncrement","value":["DAILY"]},
              {"property":"TSClass","value":[""]},
              {"property":"TSType","value":[""]},
              {"property":"TSWindow","value":""},
              {"property":"TSPeriod","value":""},
              {"property":"TSSubClass","value":""},
              {"property":"Time","value":"Active"},
              {"property":"TimeDurationOptions","value":3},
              {"property":"TimeStartDate","value":"05/15/2019 00:00:00"},
              {"property":"TimeEndDate","value":"05/15/2019 23:59:59"},
              {"property":"ShowActiveData","value":'true'},
              {"property":"DaylightSavings","value":'false'}
              ),
             ('sort',
              {"property":"TOL","direction":"DESC","root":"data"}
              ),
             ('pagingEnabled', 1),
             ('limit', 50)

             ]

When I ran s.post(myurl, data=datareq, cert=mycerts) I got the following error:

    Traceback (most recent call last):

      File "<ipython-input-78-37ee269ebbce>", line 1, in <module>
        logblah=s.post(myurl, data= datareq, cert=mycerts)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\sessions.py", line 555, in post
        return self.request('POST', url, data=data, json=json, **kwargs)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\sessions.py", line 494, in request
        prep = self.prepare_request(req)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\sessions.py", line 437, in prepare_request
        hooks=merge_hooks(request.hooks, self.hooks),

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\models.py", line 308, in prepare
        self.prepare_body(data, files, json)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\models.py", line 499, in prepare_body
        body = self._encode_params(data)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\models.py", line 97, in _encode_params
        for k, vs in to_key_val_list(data):

    ValueError: too many values to unpack (expected 2)

I'm assuming the problem is in the way I've structured my datareq variable.  What would be the proper way to make that POST?

Edit/Update:
I've tried each of Alex and Ivan's suggestions but neither work.  They each give me a cryptic message from the server that success=false.  If I try them with json=datareq instead of data=datareq then I get a response from the server with 0 results even though it should have many so it seems like that is getting closer but still not all the way.

Body:
You can put a regular JSON as an argument to post():

import json

datareq = {
    "data": [{"property":"TimeQuick","value":"Active"},{"property":"TimeQuickDurationOptions","value":3},{"property":"TimeQuickStartDate","value":"05/15/2019 00:00:00"},{"property":"TimeQuickEndDate","value":"05/15/2019 23:59:59"},{"property":"ProviderCode","value":["FPL"]},{"property":"SellerCode","value":[""]},{"property":"Ref","value":""},{"property":"POR","value":["SOCO"]},{"property":"POD","value":["FPC"]},{"property":"Path","value":""},{"property":"ServiceIncrement","value":["DAILY"]},{"property":"TSClass","value":[""]},{"property":"TSType","value":[""]},{"property":"TSWindow","value":""},{"property":"TSPeriod","value":""},{"property":"TSSubClass","value":""},{"property":"Time","value":"Active"},{"property":"TimeDurationOptions","value":3},{"property":"TimeStartDate","value":"05/15/2019 00:00:00"},{"property":"TimeEndDate","value":"05/15/2019 23:59:59"},{"property":"ShowActiveData","value":true},{"property":"DaylightSavings","value":false}],
    "sort": [{"property":"TOL","direction":"DESC","root":"data"}],
    "pagingEnabled": 1,
    "page": 1,
    "limit": 50
     }
s.post(myurl, data=json.dumps(datareq), cert=mycerts)


问:
setState called everytime I type something in input
so i'm facing an issue where whenever I write something in input, handleCommentAdded is called which calls setState, re-rendering everything. This makes everything that is typed or was typed in the input to appear as comments and i want what is in the input when I click submit to appear as comment. How can I fix this?

```<code> class WriteComments extends React.Component {
      constructor(props) {
         super(props);
         this.state = {
         commentAdded:"",
       }
      this.handleButton = this.handleButton.bind(this);
      this.handleCommentAdded = this.handleCommentAdded.bind(this);
  }

  handleCommentAdded(event) {
    this.setState({newComment: event.target.value});
  }

  handleButton() {
    return(
       <div>
       {comment}
       </div>
   )
 }

render() {
  return(
<div>
 <input type="text" value={this.state.commentAdded} onChange=
   {this.handleCommentAdded}/>

 <div className="button">
    <button
        type="button"
        onClick={e => this.handleButton(e)}
     >
     Write
    </button>
  </div>
</code>```

   )
   }
   }

答:
I created a demo where textfield value can be get by button click. Component will render everytime when setState calls. Hope it can help you!

class App extends React.Component{
  state ={ inputValue:"" };

  render(){
    return(

        <input type="text" value={this.state.inputValue} onChange={this.handleChange} />
        <button onClick={this.handleSubmit}>Submit</button>

    );
  }

  handleChange=(e)=>{
   this.setState({ inputValue: e.target.value });
  }

  handleSubmit=()=>{
    console.log("inputValue::", this.state.inputValue);
  }
}

ReactDOM.render(<App/>, document.getElementById("root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div></code>```

Body:
so i'm facing an issue where whenever I write something in input, handleCommentAdded is called which calls setState, re-rendering everything. This makes everything that is typed or was typed in the input to appear as comments and i want what is in the input when I click submit to appear as comment. How can I fix this?

 class WriteComments extends React.Component {
      constructor(props) {
         super(props);
         this.state = {
         commentAdded:"",
       }
      this.handleButton = this.handleButton.bind(this);
      this.handleCommentAdded = this.handleCommentAdded.bind(this);
  }

  handleCommentAdded(event) {
    this.setState({newComment: event.target.value});
  }

  handleButton() {
    return(

       {comment}

   )
 }

render() {
  return(

 <input type="text" value={this.state.commentAdded} onChange=
   {this.handleCommentAdded}/>

    <button
        type="button"
        onClick={e => this.handleButton(e)}
     >
     Write
    </button>

   )
   }
   }

Body:
I created a demo where textfield value can be get by button click. Component will render everytime when setState calls. Hope it can help you!

class App extends React.Component{
  state ={ inputValue:"" };

  render(){
    return(
      <div>
        <input type="text" value={this.state.inputValue} onChange={this.handleChange} />
        <button onClick={this.handleSubmit}>Submit</button>
      </div>
    );
  }

  handleChange=(e)=>{
   this.setState({ inputValue: e.target.value });
  }

  handleSubmit=()=>{
    console.log("inputValue::", this.state.inputValue);
  }
}

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>


问:
What's the difference between RESTful web service and one that isnt?
I've read and seen many videos about REST but I still don't get whats the difference between using REST and just working with http requests.</p>

答: A ReSTful web service is a web service that satisfies the constraints set out in Roy Fielding's PhD Disseration Architectural Styles and the Design of Network-based Software Architectures. If it doesn't, then it's not ReSTful.


问:
Qt - Why won't my widgets line up using a vertical layout inside a splitter?
As per the screenshot below, why won't my widgets line up using a vertical layout inside a splitter?

```<code>/********************************************************************************
** Form generated from reading UI file 'test.ui'
**
** Created: Tue Apr 12 16:51:51 2011
**      by: Qt User Interface Compiler version 4.6.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_TEST_H
#define UI_TEST_H

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QGridLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLineEdit>
#include <QtGui/QListWidget>
#include <QtGui/QMainWindow>
#include <QtGui/QSplitter>
#include <QtGui/QTreeWidget>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>

QT_BEGIN_NAMESPACE

class Ui_MainWindow
{
public:
    QWidget *centralwidget;
    QGridLayout *gridLayout;
    QSplitter *splitter;
    QTreeWidget *treeWidget;
    QWidget *widget;
    QVBoxLayout *verticalLayout;
    QLineEdit *lineEdit;
    QListWidget *listWidget;

    void setupUi(QMainWindow *MainWindow)
    {
    if (MainWindow->objectName().isEmpty())
        MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
    MainWindow->resize(800, 600);
    centralwidget = new QWidget(MainWindow);
    centralwidget->setObjectName(QString::fromUtf8("centralwidget"));
    gridLayout = new QGridLayout(centralwidget);
    gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
    splitter = new QSplitter(centralwidget);
    splitter->setObjectName(QString::fromUtf8("splitter"));
    splitter->setOrientation(Qt::Horizontal);
    treeWidget = new QTreeWidget(splitter);
    QTreeWidgetItem *__qtreewidgetitem = new QTreeWidgetItem();
    __qtreewidgetitem->setText(0, QString::fromUtf8("1"));
    treeWidget->setHeaderItem(__qtreewidgetitem);
    treeWidget->setObjectName(QString::fromUtf8("treeWidget"));
    splitter->addWidget(treeWidget);
    widget = new QWidget(splitter);
    widget->setObjectName(QString::fromUtf8("widget"));
    verticalLayout = new QVBoxLayout(widget);
    verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
    verticalLayout->setContentsMargins(0, 0, 0, 0);
    lineEdit = new QLineEdit(widget);
    lineEdit->setObjectName(QString::fromUtf8("lineEdit"));

    verticalLayout->addWidget(lineEdit);

    listWidget = new QListWidget(widget);
    listWidget->setObjectName(QString::fromUtf8("listWidget"));

    verticalLayout->addWidget(listWidget);

    splitter->addWidget(widget);

    gridLayout->addWidget(splitter, 0, 0, 1, 1);

    MainWindow->setCentralWidget(centralwidget);

    retranslateUi(MainWindow);

    QMetaObject::connectSlotsByName(MainWindow);
    } // setupUi

    void retranslateUi(QMainWindow *MainWindow)
    {
    MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class MainWindow: public Ui_MainWindow {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_TEST_H
</code>```

This is just a dummy ui uploaded here for the purpose of the question. In my real ui design I've tried every imaginable combination, but as soon as I start using splitters, it all goes out of alignment.

答: The widget on the right side of the splitter (the one containing the QLineEdit and the QListWidget) probably has default values for the layout. In QtCreator, select the QWidget, then in the property editor, scroll all the way down to the Layout section, and set the 4 values for layoutLeftMargin, layoutTopMargin, layoutRightMargin and layoutBottomMargin to 0.</p>

Body:
As per the screenshot below, why won't my widgets line up using a vertical layout inside a splitter?

/********************************************************************************
** Form generated from reading UI file 'test.ui'
**
** Created: Tue Apr 12 16:51:51 2011
**      by: Qt User Interface Compiler version 4.6.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_TEST_H
#define UI_TEST_H

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QGridLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLineEdit>
#include <QtGui/QListWidget>
#include <QtGui/QMainWindow>
#include <QtGui/QSplitter>
#include <QtGui/QTreeWidget>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>

QT_BEGIN_NAMESPACE

class Ui_MainWindow
{
public:
    QWidget *centralwidget;
    QGridLayout *gridLayout;
    QSplitter *splitter;
    QTreeWidget *treeWidget;
    QWidget *widget;
    QVBoxLayout *verticalLayout;
    QLineEdit *lineEdit;
    QListWidget *listWidget;

    void setupUi(QMainWindow *MainWindow)
    {
    if (MainWindow->objectName().isEmpty())
        MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
    MainWindow->resize(800, 600);
    centralwidget = new QWidget(MainWindow);
    centralwidget->setObjectName(QString::fromUtf8("centralwidget"));
    gridLayout = new QGridLayout(centralwidget);
    gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
    splitter = new QSplitter(centralwidget);
    splitter->setObjectName(QString::fromUtf8("splitter"));
    splitter->setOrientation(Qt::Horizontal);
    treeWidget = new QTreeWidget(splitter);
    QTreeWidgetItem *__qtreewidgetitem = new QTreeWidgetItem();
    __qtreewidgetitem->setText(0, QString::fromUtf8("1"));
    treeWidget->setHeaderItem(__qtreewidgetitem);
    treeWidget->setObjectName(QString::fromUtf8("treeWidget"));
    splitter->addWidget(treeWidget);
    widget = new QWidget(splitter);
    widget->setObjectName(QString::fromUtf8("widget"));
    verticalLayout = new QVBoxLayout(widget);
    verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
    verticalLayout->setContentsMargins(0, 0, 0, 0);
    lineEdit = new QLineEdit(widget);
    lineEdit->setObjectName(QString::fromUtf8("lineEdit"));

    verticalLayout->addWidget(lineEdit);

    listWidget = new QListWidget(widget);
    listWidget->setObjectName(QString::fromUtf8("listWidget"));

    verticalLayout->addWidget(listWidget);

    splitter->addWidget(widget);

    gridLayout->addWidget(splitter, 0, 0, 1, 1);

    MainWindow->setCentralWidget(centralwidget);

    retranslateUi(MainWindow);

    QMetaObject::connectSlotsByName(MainWindow);
    } // setupUi

    void retranslateUi(QMainWindow *MainWindow)
    {
    MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class MainWindow: public Ui_MainWindow {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_TEST_H

This is just a dummy ui uploaded here for the purpose of the question. In my real ui design I've tried every imaginable combination, but as soon as I start using splitters, it all goes out of alignment.


问:
Microsoft Teams Authentication : Unable to retrieve token in teams bot ( V4 SDK)
I have a Microsoft Teams bot and I am trying to authenticate the user using AAD (v2 endpoint). The bot uses V4 SDK and OauthPrompt.I am able to log in but unable to get the token.

I am using OAuth Card. The card is being rendered inside Teams. When the sign in button is clicked it goes to the Microsoft login page. After the user logins, the bot stops responding and hence I have no way to get the token.

The samples I am trying out are :
https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/18.bot-authentication
and
https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/24.bot-authentication-msgraph.

Both the samples are working inside the emulator.

Here is the code fragment:

```<code>               AddDialog(new OAuthPrompt(
            nameof(OAuthPrompt),
            new OAuthPromptSettings
            {
                ConnectionName = ConnectionName,
                Text = "Please Sign In",
                Title = "Sign In",
                Timeout = 300000, // User has 5 minutes to login (1000 * 60 * 5)
            }));

         AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));

        AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
        {
            PromptStepAsync,
            LoginStepAsync,
            DisplayTokenPhase1Async,
            DisplayTokenPhase2Async,
        }));
</code>```

```<code>
 private async Task<DialogTurnResult> PromptStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
           return await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken);
        }

</code>```

It never reaches the code:

```<code>        private async Task<DialogTurnResult> LoginStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        // Get the token from the previous step. Note that we could also have gotten the
        // token directly from the prompt itself. There is an example of this in the next method.
        var tokenResponse = (TokenResponse)stepContext.Result;
        if (tokenResponse != null)
        {
            await stepContext.Context.SendActivityAsync(MessageFactory.Text("You are now logged in."), cancellationToken);
            return await stepContext.PromptAsync(nameof(ConfirmPrompt), new PromptOptions { Prompt = MessageFactory.Text("Would you like to view your token?") }, cancellationToken);
        }

        await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);
        return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
    }
</code>```

I expected that the token would be received in the code once the user signs in, but the bot just stops responding.

答:
This is how I got it working. </p>

```<code>public override async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
    {

        await base.OnTurnAsync(turnContext, cancellationToken);

        // Save any state changes that might have occured during the turn.
        await ConversationState.SaveChangesAsync(turnContext, false, cancellationToken);
        await UserState.SaveChangesAsync(turnContext, false, cancellationToken);

           if (turnContext.Activity.Name == "signin/verifyState")
            {

                await Dialog.Run(turnContext, ConversationState.CreateProperty<DialogState>(nameof(DialogState)), cancellationToken);

            }

      }
</code>```

<p>It then goes to  LoginStepAsync step of Waterfall.     </p>

Body:
I have a Microsoft Teams bot and I am trying to authenticate the user using AAD (v2 endpoint). The bot uses V4 SDK and OauthPrompt.I am able to log in but unable to get the token.

I am using OAuth Card. The card is being rendered inside Teams. When the sign in button is clicked it goes to the Microsoft login page. After the user logins, the bot stops responding and hence I have no way to get the token.

The samples I am trying out are :
https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/18.bot-authentication
and
https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/24.bot-authentication-msgraph.

Both the samples are working inside the emulator.

Here is the code fragment:

               AddDialog(new OAuthPrompt(
            nameof(OAuthPrompt),
            new OAuthPromptSettings
            {
                ConnectionName = ConnectionName,
                Text = "Please Sign In",
                Title = "Sign In",
                Timeout = 300000, // User has 5 minutes to login (1000 * 60 * 5)
            }));

         AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));

        AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
        {
            PromptStepAsync,
            LoginStepAsync,
            DisplayTokenPhase1Async,
            DisplayTokenPhase2Async,
        }));

 private async Task<DialogTurnResult> PromptStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
           return await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken);
        }

It never reaches the code:

        private async Task<DialogTurnResult> LoginStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        // Get the token from the previous step. Note that we could also have gotten the
        // token directly from the prompt itself. There is an example of this in the next method.
        var tokenResponse = (TokenResponse)stepContext.Result;
        if (tokenResponse != null)
        {
            await stepContext.Context.SendActivityAsync(MessageFactory.Text("You are now logged in."), cancellationToken);
            return await stepContext.PromptAsync(nameof(ConfirmPrompt), new PromptOptions { Prompt = MessageFactory.Text("Would you like to view your token?") }, cancellationToken);
        }

        await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);
        return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
    }

I expected that the token would be received in the code once the user signs in, but the bot just stops responding.

Body:
This is how I got it working.

public override async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
    {

        await base.OnTurnAsync(turnContext, cancellationToken);

        // Save any state changes that might have occured during the turn.
        await ConversationState.SaveChangesAsync(turnContext, false, cancellationToken);
        await UserState.SaveChangesAsync(turnContext, false, cancellationToken);

           if (turnContext.Activity.Name == "signin/verifyState")
            {

                await Dialog.Run(turnContext, ConversationState.CreateProperty<DialogState>(nameof(DialogState)), cancellationToken);

            }

      }

It then goes to  LoginStepAsync step of Waterfall.


问:
How-to Keep an Android Activity Running when hitting the back key
I have an activity that essentially launches a CountDownTimer.  I need this to continue running while using other Android apps, such as Gmail, and media players etc.

When I hit the back button, my Activity seems to quit.  What do I need to do to keep it running when the user clicks the back/home keys etc.

答:
It's been referred to as a serious "hack" by a few developers, but I've successfully checked for the back button being pressed so as to successfully clean my project up. I've recently moved most of this code to onPause() event because it's called right before the app goes down after back button is pressed. However, if it's really what you desire, it's your program and here's the code I used:

```<code>if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
    killAndReturnParams(0);
}
</code>```

Again, this method has been talked down before, but I'm pretty sure it's because you're not supposed to override the back button for any reason. The user is supposed to be able to use the back button to return at any point, in any app.

Body:
It's been referred to as a serious "hack" by a few developers, but I've successfully checked for the back button being pressed so as to successfully clean my project up. I've recently moved most of this code to onPause() event because it's called right before the app goes down after back button is pressed. However, if it's really what you desire, it's your program and here's the code I used:

if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
    killAndReturnParams(0);
}

Again, this method has been talked down before, but I'm pretty sure it's because you're not supposed to override the back button for any reason. The user is supposed to be able to use the back button to return at any point, in any app.