问:
How to display/print out multiple inputs from a form as a table underneath with JS?
Background:

I have the following form. Once the [verify] button is hit, I can show only 1 "first name". I would like to print out the all the input fields (empty or full) when [verify] is pressed as a table like the form is in.

Research:

JS How to output values from function into HTML table

Questions:

How can I print the inputs of the form as a table like this:

<!DOCTYPE html>

Personnel Details

       Salutation:

        <select name="gender">
          <option value=""></option>
          <option value="male">Mr.</option>
          <option value="female">Ms.</option>
        </select>

       First Name:

       <input id="first_name">

       Middle Name:

          <input id="middle_name">

       Last Name:

          <input id="last_name">

       Email:

          <input id="email">

       DOB:

          <input type="date" name="issue_date" value="" min="1900-01-01" max="2100-12-31">

            <button onclick="onVerify()">Verify</button>

      <button  onclick="onCommit()">Commit</button>
      <button  onclick="onCancel()">Cancel</button>

    Committed! :)

```

答:
I chose each input with javascript. I took the value values in Input and sent them as innerHtml into the table that I created in html. It's the easiest way you can and can use it. Everything I've just written I've stated in the comment lines.

I added some css properties so that two tables can stand in the same order.That way, even if they're empty, they'll stand in the same line.

In fact, I've added every change and task I've made as a comment line. Good Luck!

h3 {
  text-align: center;
}

.right {
  text-align: right;
  padding-right: 1em;
}

.center {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  /* I added this because I want two paintings to come down.*/
}

tr> :nth-child(2) {
  /* with this, all the fields will now have a fixed width and will be sorted into two tables.*/
  min-width: 10rem;
}

.verify {
  /* I added this because the column is set to flex-direction for the center class.*/
  display: flex;
  justify-content: center;
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

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

<body>

  <h3>Personnel Details</h3>
  <div class="center" id="form">
    <table>
      <tr>
        <td class="right">
          <label>Salutation:</label>
        </td>
        <td>
          <select name="gender" id="salutation">
            <option value=""></option>
            <option value="male">Mr.</option>
            <option value="female">Ms.</option>
          </select>
        </td>
      </tr>
      <tr>
        <td class="right">
          <label>First Name:</label>
        </td>
        <td>
          <input id="first_name" type="text">
        </td>
      </tr>
      <tr>
        <td class="right">
          <label>Middle Name:</label>
        </td>
        <td>
          <input id="middle_name" type="text">
        </td>
      </tr>
      <tr>
        <td class="right">
          <label>Last Name:</label>
        </td>
        <td>
          <input id="last_name" type="text">
        </td>
      </tr>
      <tr>
        <td class="right">
          <label>Email:</label>
        </td>
        <td>
          <input id="email" type="email">
        </td>
      </tr>
      <tr>
        <td class="right">
          <label>DOB:</label>
        </td>
        <td>
          <input type="date" name="issue_date" value="" min="1900-01-01" max="2100-12-31" id="date">
        </td>
      </tr>
      <tr>
        <td colspan="2" style="text-align:center;">
          <div>
            <button onclick="onVerify()">Verify</button>
          </div>
        </td>
      </tr>

    </table>
    <!-- Created -->
    <table id="table-output">
      <!-- Dynamicly Cretaed for javascript -->
    </table>
  </div>

  <div id="verify">
    <br>
    <br>
    <div id="verifyName" class="center">
    </div>
    <div class="verify">
      <!-- Changed center to verify  -->
      <button onclick="onCommit()">Commit</button>
      <button onclick="onCancel()">Cancel</button>
    </div>

  </div>
  <div id="committed">
    Committed! :)
  </div>

  <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

  <script>
    $(document).ready(function() {
      document.getElementById("verify").style.display = "none";
      document.getElementById("committed").style.display = "none";
    })

    function onVerify() {
      document.getElementById("verifyName").innerHTML = 'First Name: ' + document.getElementById("first_name").value

      document.getElementById("verify").style.display = "block";
      getAllValues(); //  I'm running this function here because I want to see the table after verify is done.

    }

    function onCommit() {
      document.getElementById("form").style.display = "none";
      document.getElementById("verify").style.display = "none";
      document.getElementById("committed").style.display = "block";
    }

    function onCancel() {
      document.getElementById("form").style.display = "block";
      document.getElementById("verify").style.display = "none";
      document.getElementById("name").value = ""
    }

    //  I take value from all the inputs in my table and send it to another function. I suggest you divide your operations into functions, so that you can be more comfortable when you want to modify them, since they're all in the clear.
    function getAllValues() {
      const salutation = document.getElementById("salutation").value;
      const firstName = document.getElementById("first_name").value;
      const lastName = document.getElementById("last_name").value;
      const middleName = document.getElementById("middle_name").value;
      const email = document.getElementById("email").value;
      const date = document.getElementById("date").value;
      // Formating DATE
      let newDate = date.split("-").reverse().join(".");
      showTable(salutation, firstName, lastName, middleName, email, newDate);
    }

    // this function will select the second table that we have defined on the html side and display on the screen, and place the value values that we have received according to what structure we want.
    function showTable(salutation, firstName, lastName, middleName, email, date)  {
      let table = document.getElementById("table-output");
      table.innerHTML = `

      <tr>
        <td class="right">
          <label>Salutation:</label>
        </td>
        <td>
            ${salutation}
        </td>
      </tr>
      <tr>
        <td class="right">
          <label>First Name:</label>
        </td>
        <td>
          ${firstName}
        </td>
      </tr>
      <tr>
        <td class="right">
          <label>Middle Name:</label>
        </td>
        <td>
          ${lastName}
        </td>
      </tr>
      <tr>
        <td class="right">
          <label>Last Name:</label>
        </td>
        <td>
          ${middleName}
        </td>
      </tr>
      <tr>
        <td class="right">
          <label>Email:</label>
        </td>
        <td>
          ${email}

        </td>
      </tr>
      <tr>
        <td class="right">
          <label>DOB:</label>
        </td>
        <td>
          ${date}
        </td>
      </tr>

       `

    }
  </script>

  <!-- JAVASCRIPT -->

</body>

</html></code>```

Body:
I chose each input with javascript. I took the value values in Input and sent them as innerHtml into the table that I created in html. It's the easiest way you can and can use it. Everything I've just written I've stated in the comment lines.

I added some css properties so that two tables can stand in the same order.That way, even if they're empty, they'll stand in the same line.

In fact, I've added every change and task I've made as a comment line. Good Luck!

h3 {
  text-align: center;
}

.right {
  text-align: right;
  padding-right: 1em;
}

.center {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  /* I added this because I want two paintings to come down.*/
}

tr> :nth-child(2) {
  /* with this, all the fields will now have a fixed width and will be sorted into two tables.*/
  min-width: 10rem;
}

.verify {
  /* I added this because the column is set to flex-direction for the center class.*/
  display: flex;
  justify-content: center;
  align-items: center;
}

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

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

<body>

  <h3>Personnel Details</h3>
  <div class="center" id="form">
    <table>
      <tr>
        <td class="right">
          <label>Salutation:</label>
        </td>
        <td>
          <select name="gender" id="salutation">
            <option value=""></option>
            <option value="male">Mr.</option>
            <option value="female">Ms.</option>
          </select>
        </td>
      </tr>
      <tr>
        <td class="right">
          <label>First Name:</label>
        </td>
        <td>
          <input id="first_name" type="text">
        </td>
      </tr>
      <tr>
        <td class="right">
          <label>Middle Name:</label>
        </td>
        <td>
          <input id="middle_name" type="text">
        </td>
      </tr>
      <tr>
        <td class="right">
          <label>Last Name:</label>
        </td>
        <td>
          <input id="last_name" type="text">
        </td>
      </tr>
      <tr>
        <td class="right">
          <label>Email:</label>
        </td>
        <td>
          <input id="email" type="email">
        </td>
      </tr>
      <tr>
        <td class="right">
          <label>DOB:</label>
        </td>
        <td>
          <input type="date" name="issue_date" value="" min="1900-01-01" max="2100-12-31" id="date">
        </td>
      </tr>
      <tr>
        <td colspan="2" style="text-align:center;">
          <div>
            <button onclick="onVerify()">Verify</button>
          </div>
        </td>
      </tr>

    </table>
    <!-- Created -->
    <table id="table-output">
      <!-- Dynamicly Cretaed for javascript -->
    </table>
  </div>

  <div id="verify">
    <br>
    <br>
    <div id="verifyName" class="center">
    </div>
    <div class="verify">
      <!-- Changed center to verify  -->
      <button onclick="onCommit()">Commit</button>
      <button onclick="onCancel()">Cancel</button>
    </div>

  </div>
  <div id="committed">
    Committed! :)
  </div>

  <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

  <script>
    $(document).ready(function() {
      document.getElementById("verify").style.display = "none";
      document.getElementById("committed").style.display = "none";
    })

    function onVerify() {
      document.getElementById("verifyName").innerHTML = 'First Name: ' + document.getElementById("first_name").value

      document.getElementById("verify").style.display = "block";
      getAllValues(); //  I'm running this function here because I want to see the table after verify is done.

    }

    function onCommit() {
      document.getElementById("form").style.display = "none";
      document.getElementById("verify").style.display = "none";
      document.getElementById("committed").style.display = "block";
    }

    function onCancel() {
      document.getElementById("form").style.display = "block";
      document.getElementById("verify").style.display = "none";
      document.getElementById("name").value = ""
    }

    //  I take value from all the inputs in my table and send it to another function. I suggest you divide your operations into functions, so that you can be more comfortable when you want to modify them, since they're all in the clear.
    function getAllValues() {
      const salutation = document.getElementById("salutation").value;
      const firstName = document.getElementById("first_name").value;
      const lastName = document.getElementById("last_name").value;
      const middleName = document.getElementById("middle_name").value;
      const email = document.getElementById("email").value;
      const date = document.getElementById("date").value;
      // Formating DATE
      let newDate = date.split("-").reverse().join(".");
      showTable(salutation, firstName, lastName, middleName, email, newDate);
    }

    // this function will select the second table that we have defined on the html side and display on the screen, and place the value values that we have received according to what structure we want.
    function showTable(salutation, firstName, lastName, middleName, email, date)  {
      let table = document.getElementById("table-output");
      table.innerHTML = `

      <tr>
        <td class="right">
          <label>Salutation:</label>
        </td>
        <td>
            ${salutation}
        </td>
      </tr>
      <tr>
        <td class="right">
          <label>First Name:</label>
        </td>
        <td>
          ${firstName}
        </td>
      </tr>
      <tr>
        <td class="right">
          <label>Middle Name:</label>
        </td>
        <td>
          ${lastName}
        </td>
      </tr>
      <tr>
        <td class="right">
          <label>Last Name:</label>
        </td>
        <td>
          ${middleName}
        </td>
      </tr>
      <tr>
        <td class="right">
          <label>Email:</label>
        </td>
        <td>
          ${email}

        </td>
      </tr>
      <tr>
        <td class="right">
          <label>DOB:</label>
        </td>
        <td>
          ${date}
        </td>
      </tr>

       `

    }
  </script>

  <!-- JAVASCRIPT -->

</body>

</html>


来源: stackexchange

问:
Rails simpleform pre data
How do I make a simple form association have pre data when editing?

My form:

```<code><h1>Editing kategori</h1>
<%= simple_form_for(@konkurrancer, :url => {:action => 'update', :id => @konkurrancer.id }) do |f| %>
    <%= f.association :kategoris  %>
    <%= f.button :submit, :value => 'Edit konkurrence' %>
<% end %>
</code>```

答:
You almost did it:</p>

```<code><%= f.button :submit, :value => 'Edit konkurrence', :data_pre => "whatever here" %>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Rails simpleform pre data

Body:
How do I make a simple form association have pre data when editing?

My form:

Editing kategori

<%= simple_form_for(@konkurrancer, :url => {:action => 'update', :id => @konkurrancer.id }) do |f| %>
    <%= f.association :kategoris  %>
    <%= f.button :submit, :value => 'Edit konkurrence' %>
<% end %>

Body:
You almost did it:

<%= f.button :submit, :value => 'Edit konkurrence', :data_pre => "whatever here" %>


问:
C/C++ Printing stack bottom to top with recursion
Hey I am trying to print a "stack" from bottom to top using recusion. Everything in the code is as should and only the print function should be modified. I am not getting any recursion print and unfortunately I do not know why.

```<code>struct element{
    int i;
    element *next;
};

struct stack{
    element *top;
};

void print(stack *st);

int main(){
    element *e5 = (element*) malloc(sizeof(element));
    element *e4 = (element*) malloc(sizeof(element));
    element *e3 = (element*) malloc(sizeof(element));
    element *e2 = (element*) malloc(sizeof(element));
    element *e1 = (element*) malloc(sizeof(element));

    e5->i = 5; e5->next = NULL;
    e4->i = 4; e4->next = e5;
    e3->i = 3; e3->next = e4;
    e2->i = 2; e2->next = e3;
    e1->i = 1; e1->next = e2;

    stack start;
    start.top = e1;
    element *e;

    print(&start);

    return 0;
}

void print(stack *st){
    stack nxt;
    nxt.top = st->top->next;
    if (st->top != NULL){
        print(&nxt);
        printf("%i\n", st->top);
    }
    else
        printf("%i\n", st->top->i);
}
</code>```

Thank you for your input!

答:
There are other problems (see Botje's comment), but also:

```<code>printf("%i\n", st->top);
</code>```

What is the type of st->top? What happens if you print it with format %i?

ContentLicense: CC BY-SA 4.0

Body:
Hey I am trying to print a "stack" from bottom to top using recusion. Everything in the code is as should and only the print function should be modified. I am not getting any recursion print and unfortunately I do not know why.

struct element{
    int i;
    element *next;
};

struct stack{
    element *top;
};

void print(stack *st);

int main(){
    element *e5 = (element*) malloc(sizeof(element));
    element *e4 = (element*) malloc(sizeof(element));
    element *e3 = (element*) malloc(sizeof(element));
    element *e2 = (element*) malloc(sizeof(element));
    element *e1 = (element*) malloc(sizeof(element));

    e5->i = 5; e5->next = NULL;
    e4->i = 4; e4->next = e5;
    e3->i = 3; e3->next = e4;
    e2->i = 2; e2->next = e3;
    e1->i = 1; e1->next = e2;

    stack start;
    start.top = e1;
    element *e;

    print(&start);

    return 0;
}

void print(stack *st){
    stack nxt;
    nxt.top = st->top->next;
    if (st->top != NULL){
        print(&nxt);
        printf("%i\n", st->top);
    }
    else
        printf("%i\n", st->top->i);
}

Thank you for your input!

Body:
There are other problems (see Botje's comment), but also:

printf("%i\n", st->top);

What is the type of st->top? What happens if you print it with format %i?


问:
Nameserver update for AWS EC2 hosted website
I have deployed a simple html website running on NGINX on a AWS EC2 server. I intend to host 2-3 static websites on this server. For the time being, I have configured only 1 server block and hosted the website.

When I type the ip address/public dns name of the server in the browser, I can see my website. My domain name is registered with another service provider.

How should I update the Nameserver records in my domain registrar account? Should I just update the public ip address in the name server field or should I update the public dns name?

My domain registrar is asking for two name server details as compulsory fields. If I update the same public ip address twice, its not allowing me to save.

Please advise. I want to know the nameserver details for my EC2 based website. My website is not hosted on Amazon Route53.

答:
Do not update your nameserver records, these are records you would use to configure where your DNS records should be resolved.

Instead you need to update/create an A record that points from the domain to your new host IP.


问:
Python transform json
I have a text file with entries like this:

```<code>[
{
    "Exceptions": {
        "GUID": "028326A8206D44A736B45FE6125E59B2",
        "ExceptionName": "madrid,barcelona",
        "TargetHostname": "www.spain.com",
        "TargetName": "spain",
        "HasModule": true
    }
},

{
    "Exceptions": {
        "GUID": "028326A8206D44A736B45FE6125E59B2",
        "ExceptionName": "london,liverpool",
        "TargetHostname": "www.uk.com",
        "TargetName": "uk",
        "HasModule": true
    }
},

{
    "Exceptions": {
        "GUID": "028326A8206D44A736B45FE6125E59B2",
        "ExceptionName": "dublin,cork",
        "TargetHostname": "www.ireland.com",
        "TargetName": "ireland",
        "HasModule": true
    }
}
]
</code>```

I would like a rule for each city, I need to modify this json.

I tried some things with python for, but I didn't get anything like that

I need a pyhton script that converts this input rule to the model below.
The expected result is, I would like the result to be like this:

So i need each city to give me a rule like that inside json.
Thank you all for your help.

I needed each rule of each country ... to stay within the specific json of the country.

example spain.json

```<code>[
{
"Exceptions": {
    "GUID": "028326A8206D44A736B45FE6125E59B2",
    "ExceptionName": "madrid",
    "TargetHostname": "www.spain.com",
    "TargetName": "spain",
    "HasModule": true
  }
 },
 {
"Exceptions": {
    "GUID": "028326A8206D44A736B45FE6125E59B2",
    "ExceptionName": "barcelona",
    "TargetHostname": "www.spain.com",
    "TargetName": "spain",
    "HasModule": true
  }
 }
]
</code>```

example uk.json

```<code>[
{
"Exceptions": {
    "GUID": "028326A8206D44A736B45FE6125E59B2",
    "ExceptionName": "london",
    "TargetHostname": "www.uk.com",
    "TargetName": "uk",
    "HasModule": true
  }
 },
 {
"Exceptions": {
    "GUID": "028326A8206D44A736B45FE6125E59B2",
    "ExceptionName": "liverpool",
    "TargetHostname": "www.uk.com",
    "TargetName": "uk",
    "HasModule": true
  }
 }
]
</code>```

You can help me with that.

答:
import copy
import json
mylist = []
for e in a: #a is the original list.
    mylist = []
    for city in e["Exceptions"]["ExceptionName"].split(","):
        new = copy.deepcopy(e)
        new["Exceptions"]["ExceptionName"] = city
        mylist.append(new)
    with open(f"{new['Exceptions']['TargetName']}.json", "w") as f:
        json.dump(mylist, f)
```

Title: Python transform json

Body:
I have a text file with entries like this:

[
{
    "Exceptions": {
        "GUID": "028326A8206D44A736B45FE6125E59B2",
        "ExceptionName": "madrid,barcelona",
        "TargetHostname": "www.spain.com",
        "TargetName": "spain",
        "HasModule": true
    }
},

{
    "Exceptions": {
        "GUID": "028326A8206D44A736B45FE6125E59B2",
        "ExceptionName": "london,liverpool",
        "TargetHostname": "www.uk.com",
        "TargetName": "uk",
        "HasModule": true
    }
},

{
    "Exceptions": {
        "GUID": "028326A8206D44A736B45FE6125E59B2",
        "ExceptionName": "dublin,cork",
        "TargetHostname": "www.ireland.com",
        "TargetName": "ireland",
        "HasModule": true
    }
}
]

I would like a rule for each city, I need to modify this json.

I tried some things with python for, but I didn't get anything like that

I need a pyhton script that converts this input rule to the model below.
The expected result is, I would like the result to be like this:

So i need each city to give me a rule like that inside json.
Thank you all for your help.

I needed each rule of each country ... to stay within the specific json of the country.

example spain.json

[
{
"Exceptions": {
    "GUID": "028326A8206D44A736B45FE6125E59B2",
    "ExceptionName": "madrid",
    "TargetHostname": "www.spain.com",
    "TargetName": "spain",
    "HasModule": true
  }
 },
 {
"Exceptions": {
    "GUID": "028326A8206D44A736B45FE6125E59B2",
    "ExceptionName": "barcelona",
    "TargetHostname": "www.spain.com",
    "TargetName": "spain",
    "HasModule": true
  }
 }
]

example uk.json

[
{
"Exceptions": {
    "GUID": "028326A8206D44A736B45FE6125E59B2",
    "ExceptionName": "london",
    "TargetHostname": "www.uk.com",
    "TargetName": "uk",
    "HasModule": true
  }
 },
 {
"Exceptions": {
    "GUID": "028326A8206D44A736B45FE6125E59B2",
    "ExceptionName": "liverpool",
    "TargetHostname": "www.uk.com",
    "TargetName": "uk",
    "HasModule": true
  }
 }
]

You can help me with that.


问:
Project <PROJECT NAME> is not up to date. Missing input file 'netframework,version=v4.0,profile=client.assemblyattributes.cs
I have a sln with > 50 projects, and recently, when I moved to VS2013, every time I press F5 for a build, it will rebuild all the projects, even though I have just performed a build. The diagnostics show, that each project is marked as not up to date with the following error:

```<code>Project <PROJECT NAME> is not up to date. Missing input file 'c:\users\USER\appdata\local\temp\2\.netframework,version=v4.0,profile=client.assemblyattributes.cs
</code>```

I have read these threads:

In Visual Studio 2010 why is the .NETFramework,Version=v4.0.AssemblyAttributes.cpp file created, and can I disable this?

https://social.msdn.microsoft.com/Forums/vstudio/en-US/15d65667-ac47-4234-9285-32a2cb397e32/migration-from-vs2008-to-vs2010-and-netframeworkversionv40assemblyattributescpp?forum=vcgeneral

but the suggestion there is to add the following line to the proj file:

```<code>  <Target Name="GenerateTargetFrameworkMonikerAttribute" />
</code>```

I did and it did not work. Suppressing the warning as MS suggestion will also not work as the project will remain "not up to date".

I am using VS2013, C# and VB projects. With the very same project and VS2012, such error is not raised and the projects are up to date.

Any suggestions?

UPDATE
Perhaps it is worth mentioning that I do have a few build definitions in the solution, where all of the projects are building for AnyCPU except one: http://screencast.com/t/fuw9k4IubN

答:
I had the same problem and solved it by upgrading the ToolsVersion attribute in *.csproj files:

ToolsVersion="4.0" replaced with ToolsVersion="16.0"

(I’m using Visual Studio 2019, which is v16.x internally).

Body:
I have a sln with > 50 projects, and recently, when I moved to VS2013, every time I press F5 for a build, it will rebuild all the projects, even though I have just performed a build. The diagnostics show, that each project is marked as not up to date with the following error:

Project <PROJECT NAME> is not up to date. Missing input file 'c:\users\USER\appdata\local\temp\2\.netframework,version=v4.0,profile=client.assemblyattributes.cs

I have read these threads:

In Visual Studio 2010 why is the .NETFramework,Version=v4.0.AssemblyAttributes.cpp file created, and can I disable this?

https://social.msdn.microsoft.com/Forums/vstudio/en-US/15d65667-ac47-4234-9285-32a2cb397e32/migration-from-vs2008-to-vs2010-and-netframeworkversionv40assemblyattributescpp?forum=vcgeneral

but the suggestion there is to add the following line to the proj file:

  <Target Name="GenerateTargetFrameworkMonikerAttribute" />

I did and it did not work. Suppressing the warning as MS suggestion will also not work as the project will remain "not up to date".

I am using VS2013, C# and VB projects. With the very same project and VS2012, such error is not raised and the projects are up to date.

Any suggestions?

UPDATE
Perhaps it is worth mentioning that I do have a few build definitions in the solution, where all of the projects are building for AnyCPU except one: http://screencast.com/t/fuw9k4IubN


问:
React Router changes route but does not render the component
I'm having an issue where changing the route in my react app does not render the components. After hitting refresh the components render as expected. Is this just a development runtime thing that won't appear in production or am I missing something here?

```<code>//all  required imports are correctly imported

export default function App() {
    return pug`
            Router
                    Switch
                            Route(path="/" exact component=Home)

                            Route(path="/character" exact component=Character)

                            Route(path="/story" exact component=Story)

                            Route(path="/pay" exact component=Payment)
    `
}
</code>```

Using a Link component to change the route does not render the new component. Changing the route in the address bar directly does though. I'm guessing this is because the browser refreshes the page anyways.

答:
index.js

import { BrowserRouter } from 'react-router-dom';

const defaultRender = () => {
    ReactDOM.render(
      <BrowserRouter>
        <App />
      </BrowserRouter>,
      document.getElementById('root')
    );
};
defaultRender();```
</div>
</div>
</p>

<p>App.js
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React from 'react';
import { Route, Switch } from 'react-router-dom';
import {Page1, Page2} from './pages';

const App = () => {
  return (
    <div className="App">
        <Switch>
          <Route exact path="/page1" component={Page1} />
          <Route exact path="/page2" component={Page2} />
        </Switch>
    </div>
  );
}

export default App;</code>```

Body:
I'm having an issue where changing the route in my react app does not render the components. After hitting refresh the components render as expected. Is this just a development runtime thing that won't appear in production or am I missing something here?

//all  required imports are correctly imported

export default function App() {
    return pug`
            Router
                    Switch
                            Route(path="/" exact component=Home)

                            Route(path="/character" exact component=Character)

                            Route(path="/story" exact component=Story)

                            Route(path="/pay" exact component=Payment)
    `
}

Using a Link component to change the route does not render the new component. Changing the route in the address bar directly does though. I'm guessing this is because the browser refreshes the page anyways.

Body:
index.js

import { BrowserRouter } from 'react-router-dom';

const defaultRender = () => {
    ReactDOM.render(
      <BrowserRouter>
        <App />
      </BrowserRouter>,
      document.getElementById('root')
    );
};
defaultRender();

App.js

import React from 'react';
import { Route, Switch } from 'react-router-dom';
import {Page1, Page2} from './pages';

const App = () => {
  return (
    <div className="App">
        <Switch>
          <Route exact path="/page1" component={Page1} />
          <Route exact path="/page2" component={Page2} />
        </Switch>
    </div>
  );
}

export default App;


问:
Dynamics CRM: Scheduling workflows
In my CRM I've applications which should be checked and processed by a workflow once a minute.
I was wondering if there anyway to automate this stuff using some sort of cron task or scheduling. I'm relatively new to CRM.

What should I do to make the stuff above, using standard CRM tools, or third party plugins?

Sultan.

答:
CRM doesn't have a good way of handling this. Here are the options generally available inside CRM:

Create a workflow that runs, checks what you need it to do, waits for a period of time and calls itself recursively. If the interval you needed to check at was longer than a minute, this might work, however, CRM has loop detection built into the workflows, and running them once a minute will definitely trigger that.

Create an entity that represents one of your processes. Create a workflow that kicks off after create of this entity, waits one minute, and then creates a new record of your entity. This way, the workflow isn't calling itself recursively and it shouldn't trigger CRM's loop detection. However, you're creating a lot of dummy records and workflow instances that you'll need to clean up in this scenario.

I think both of these are kind of hacky. I would say that if you need to check something once every minute, I'd put it outside CRM in a Windows Service or a Scheduled Task. CRM just doesn't have this capability built in.

Title: Dynamics CRM: Scheduling workflows


问:
Java .xml creating a drawable button background
New to programming, 3 weeks beginner.
I am making a button with stacked rectangles through drawable xml.

This is my button .xml code, very straight forward:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#D5A04F"
    tools:context=".MainActivity">

    <android.support.design.widget.NavigationView
        <Button
            android:id="@+id/leftnavbar"
            android:layout_width="212dp"
            android:layout_height="279dp"

            android:layout_marginTop="16sp"
            android:layout_marginBottom="500sp"
            android:background="@drawable/rounded_rectangle"
             />
    </android.support.design.widget.NavigationView>

</android.support.constraint.ConstraintLayout>
</code>```

and this is my drawable .xml

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:paddingBottom="@dimen/mr_dialog_fixed_width_minor"
    android:paddingTop="@dimen/mr_dialog_fixed_width_major"
    >

    <item
        android:top="5sp"
        android:left="5sp"
        android:right="5sp"
        android:bottom="50sp">
        <shape android:shape="rectangle">
            <solid android:color="#D3AE71" />
            <corners android:radius="20sp"/>
        </shape>
    </item>

    <item
        android:top="30sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="600sp">s
            <shape android:shape="rectangle">
                <solid android:color="#E6E5E5" />
                <corners android:radius="20sp"/>
            </shape>
    </item>

    <item
        android:top="160sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="470sp">
        <shape android:shape="rectangle">
            <solid android:color="#E6E5E5" />
            <corners android:radius="20sp"/>
        </shape>
    </item>

    <item
        android:top="290sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="340sp">
        <shape android:shape="rectangle">
            <solid android:color="#E6E5E5" />
            <corners android:radius="20sp"/>
        </shape>
    </item>

    <item
        android:top="420sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="210sp"
        >
        <shape android:shape="rectangle">
            <solid android:color="#E6E5E5" />
            <corners android:radius="20sp"/>
        </shape>
    </item>

    <item
        android:top="550sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="80sp">
        <shape android:shape="rectangle">
            <solid android:color="#E6E5E5" />
            <corners android:radius="20sp"/>
        </shape>
    </item>
</layer-list>
</code>```

The only item that is shown in drawable is the first, the rest of the rectangles fail to show.
Suggestions or pointers to the reason will be much apreciated. thank you for your time and attention...

答:
First of all please do not use "sp" for things other than text font size.

Second, pls look into excessive size of your android:bottom, like 600sp for example - they are leaving no space for respective shapes.

Body:
New to programming, 3 weeks beginner.
I am making a button with stacked rectangles through drawable xml.

This is my button .xml code, very straight forward:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#D5A04F"
    tools:context=".MainActivity">

    <android.support.design.widget.NavigationView
        <Button
            android:id="@+id/leftnavbar"
            android:layout_width="212dp"
            android:layout_height="279dp"

            android:layout_marginTop="16sp"
            android:layout_marginBottom="500sp"
            android:background="@drawable/rounded_rectangle"
             />
    </android.support.design.widget.NavigationView>

</android.support.constraint.ConstraintLayout>

and this is my drawable .xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:paddingBottom="@dimen/mr_dialog_fixed_width_minor"
    android:paddingTop="@dimen/mr_dialog_fixed_width_major"
    >

    <item
        android:top="5sp"
        android:left="5sp"
        android:right="5sp"
        android:bottom="50sp">
        <shape android:shape="rectangle">
            <solid android:color="#D3AE71" />
            <corners android:radius="20sp"/>
        </shape>
    </item>

    <item
        android:top="30sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="600sp">s
            <shape android:shape="rectangle">
                <solid android:color="#E6E5E5" />
                <corners android:radius="20sp"/>
            </shape>
    </item>

    <item
        android:top="160sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="470sp">
        <shape android:shape="rectangle">
            <solid android:color="#E6E5E5" />
            <corners android:radius="20sp"/>
        </shape>
    </item>

    <item
        android:top="290sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="340sp">
        <shape android:shape="rectangle">
            <solid android:color="#E6E5E5" />
            <corners android:radius="20sp"/>
        </shape>
    </item>

    <item
        android:top="420sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="210sp"
        >
        <shape android:shape="rectangle">
            <solid android:color="#E6E5E5" />
            <corners android:radius="20sp"/>
        </shape>
    </item>

    <item
        android:top="550sp"
        android:left="30sp"
        android:right="30sp"
        android:bottom="80sp">
        <shape android:shape="rectangle">
            <solid android:color="#E6E5E5" />
            <corners android:radius="20sp"/>
        </shape>
    </item>
</layer-list>

The only item that is shown in drawable is the first, the rest of the rectangles fail to show.
Suggestions or pointers to the reason will be much apreciated. thank you for your time and attention...


问:
How to extract a substring from a string in a column, that matches another string in a list in python
I have a dataframe which is as follows:

```<code>     col 1                                     col 2
0       59       538 Walton Avenue, Chester, FY6 7NP
1       62 42 Chesterton Road, Peterborough, FR7 2NY
2      179       3 Wallbridge Street, Essex, 4HG 3HT
3      180     6 Stevenage Avenue, Coventry, 7PY 9NP
</code>```

With a list similar to:

```<code>[Stevenage, Essex, Coventry, Chester]
</code>```

Following the solution from here: How to check if Pandas rows contain any full string or substring of a list? which went like this:

```<code>city_list = list(cities["name"])
df["col3"] = np.where(df["col2"].str.contains('|'.join(city_list)), df["col2"], '')
</code>```

I found that some in col 2 match the strings in a list but that the col3 is the same as col2. I want col3 to be the values in the list rather the same as col3. This would be:

```<code>     col 1                                     col 2     col3
0       59       538 Walton Avenue, Chester, FY6 7NP  Chester
1       62 42 Chesterton Road, Peterborough, FR7 2NY
2      179       3 Wallbridge Street, Essex, 4HG 3HT    Essex
3      180     6 Stevenage Avenue, Coventry, 7PY 9NP Coventry
</code>```

I have tried:

```<code>pat = "|".join(cities.name)
df.insert(0, "name", df["col2"].str.extract('(' + pat + ')', expand = False))
</code>```

But this returned an error saying 456 inputs when expecting 1.

Also:

```<code>df["col2"] = df["col2"].apply(lambda x: difflib.get_close_matches(x, cities["name"])[0])
df.merge(cities)
</code>```

But this came back with the error list index out of range.

Is there anyway to do this? df1 is around 160,000 entries with each address in col2 from different countries so there is no standard way they are written, while the city list is around 170,000 entries

Thank you

答:
You could do as follows:

city_list = ["Stevenage", "Essex", "Coventry", "Chester"]

def get_match(row):
    col_2 = row["col 2"].replace(",", " ").split() # Here you should process the string as you want
    for c in city_list:
        if difflib.get_close_matches(col_2, c)
            return c
    return ""

df["col 3"] = df.apply(lambda row: get_match(row), axis=1)
```

Body:
I have a dataframe which is as follows:

     col 1                                     col 2
0       59       538 Walton Avenue, Chester, FY6 7NP
1       62 42 Chesterton Road, Peterborough, FR7 2NY
2      179       3 Wallbridge Street, Essex, 4HG 3HT
3      180     6 Stevenage Avenue, Coventry, 7PY 9NP

With a list similar to:

[Stevenage, Essex, Coventry, Chester]

Following the solution from here: How to check if Pandas rows contain any full string or substring of a list? which went like this:

city_list = list(cities["name"])
df["col3"] = np.where(df["col2"].str.contains('|'.join(city_list)), df["col2"], '')

I found that some in col 2 match the strings in a list but that the col3 is the same as col2. I want col3 to be the values in the list rather the same as col3. This would be:

     col 1                                     col 2     col3
0       59       538 Walton Avenue, Chester, FY6 7NP  Chester
1       62 42 Chesterton Road, Peterborough, FR7 2NY
2      179       3 Wallbridge Street, Essex, 4HG 3HT    Essex
3      180     6 Stevenage Avenue, Coventry, 7PY 9NP Coventry

I have tried:

pat = "|".join(cities.name)
df.insert(0, "name", df["col2"].str.extract('(' + pat + ')', expand = False))

But this returned an error saying 456 inputs when expecting 1.

Also:

df["col2"] = df["col2"].apply(lambda x: difflib.get_close_matches(x, cities["name"])[0])
df.merge(cities)

But this came back with the error list index out of range.

Is there anyway to do this? df1 is around 160,000 entries with each address in col2 from different countries so there is no standard way they are written, while the city list is around 170,000 entries

Thank you


问:
GenSA and SA giving nonsense output for Knapsack problem
I have the following CSV:

Knapsack.CSV

```<code>,gewichten(gr),waarde
Voorwerp 1,70,135
Voorwerp 2,73,139
Voorwerp 3,77,149
Voorwerp 4,80,150
Voorwerp 5,82,156
Voorwerp 6,87,163
Voorwerp 7,90,173
Voorwerp 8,94,184
Voorwerp 9,98,192
Voorwerp 10,106,201
Voorwerp 11,110,210
Voorwerp 12,113,214
Voorwerp 13,115,221
Voorwerp 14,118,229
Voorwerp 15,120,240
</code>```

I am trying to solve the Knapsack problem by using GenSA and GA. The solution for this set of data should be around 1458.

However, with this code:

```<code>install.packages("GenSA")
install.packages("GA")
require(GenSA)
library(GenSA)
require(GA)
library(GA)

#Loading data
df <- read.csv("knapsack.csv", header=TRUE, sep=",")

#Define function
knapsack <- function(x) {
  f <- sum(x * df[3])
  penalty <- sum(df[2]) * abs(sum(x*df[2]) - 750)
  f - penalty
}

init <- runif(1, -5000, 5000)

onder <- rep(-5000, length(init))
boven <- rep(5000, length(init))

controlelijst <- list(max.time=25, nb.stop.improvement = 100)

resultaatSA <- GenSA(par=init, lower = onder, upper = boven, fn=knapsack, control=controlelijst)

resultaatSA$par

# Solution num 2
SGA <- ga(type="binary", fitness=knapsack, nBits=length(df[1]), maxiter=150, run=250, popSize=100, seed=101)

SGA
SGA@solution
</code>```

I get a lot of nonsense output. GenSA for example says the solution is -5000, or sometimes 5000. Which are boundaries/constraints I have set.

SA gives 1 as solution.

What exactly am I doing wrong, and how do I need to use those two functions correctly?

答:
I think John Coleman is correct, and that you have to simply change the sign of your cost function so that it is minimized. Below is a (slightly overkill) example of how this small addition of a minus to your function will result in a very different solution (hopefully the correct one). I have plotted the results in a similar way as GA does, as I saw from your code that you were also looking into that as an option (quite a good one in fact). For GA, the cost function is maximized, so you would need to remove the minus.

```<code>library(GenSA)
library(GA)

df <- read.table(text = ",gewichten(gr),waarde
Voorwerp 1,70,135
Voorwerp 2,73,139
Voorwerp 3,77,149
Voorwerp 4,80,150
Voorwerp 5,82,156
Voorwerp 6,87,163
Voorwerp 7,90,173
Voorwerp 8,94,184
Voorwerp 9,98,192
Voorwerp 10,106,201
Voorwerp 11,110,210
Voorwerp 12,113,214
Voorwerp 13,115,221
Voorwerp 14,118,229
Voorwerp 15,120,240", sep = ",", header = T
)

#Define function
knapsack <- function(x) {
  f <- sum(x * df[3])
  penalty <- sum(df[2]) * abs(sum(x*df[2]) - 750)
  -(f - penalty) # SIMPLY ADDED A MINUS SIGN
}

init <- runif(1, -5000, 5000)

onder <- rep(-5000, length(init))
boven <- rep(5000, length(init))

controlelijst <- list(max.time=25, nb.stop.improvement = 100)

resultaatSA <- GenSA(par=init, lower = onder, upper = boven, fn=knapsack, control=controlelijst)

resultaatSA$par # 0.5233775
head(resultaatSA$trace.mat)

# summarize results
tmp <- as.data.frame(resultaatSA$trace.mat)
meani <- aggregate(tmp$function.value, list(step = tmp$nb.steps),mean, na.rm = TRUE)
exe <- aggregate(tmp$current.minimum, list(step = tmp$nb.steps),mean, na.rm = TRUE)
medi <- aggregate(tmp$function.value, list(step = tmp$nb.steps),median, na.rm = TRUE)
ylim <- c(min(range(exe$x,na.rm = TRUE, finite = TRUE)),
          max(range(meani$x, na.rm = TRUE, finite = TRUE)))

# plot
op <- par(mar=c(5.1, 4.1, 1, 4.1))
plot(tmp$nb.steps, tmp$function.value, type = "n", ylim = ylim, xlab = "Iteration",
     ylab = "Cost value")
graphics::grid(equilogs = FALSE)
points(tmp$nb.steps, tmp$current.minimum, type = "o", pch = 16, lty = 1,
       col = "green3", cex = 0.7)
points(meani$step, meani$x, type = "o", pch = 1, lty = 2,
       col = "dodgerblue3", cex = 0.7)
polygon(c(meani$step, rev(meani$step)),
        c(exe$x, rev(medi$x)),
        border = FALSE, col = adjustcolor("green3", alpha.f = 0.1))
par(new=TRUE)
plot(tmp$nb.steps, tmp$temperature, t="l", col=2, lty=2, log="y", axes = FALSE, xlab = "", ylab = "")
axis(4, col=2, col.axis=2); mtext(text = "Temperature", side = 4, line = par()$mgp[1], col=2)
legend("topright", legend = c("Best", "Mean", "Median", "Temperature"),
       col = c("green3", "dodgerblue3", adjustcolor("green3", alpha.f = 0.1), 2),
       pch = c(16, 1, NA, NA), lty = c(1,2,1,2),
       lwd = c(1, 1, 10, 1), pt.cex = c(rep(0.7,2), 2, NA),
       inset = 0.02)
par(op)
</code>```

Body:
I have the following CSV:

Knapsack.CSV

,gewichten(gr),waarde
Voorwerp 1,70,135
Voorwerp 2,73,139
Voorwerp 3,77,149
Voorwerp 4,80,150
Voorwerp 5,82,156
Voorwerp 6,87,163
Voorwerp 7,90,173
Voorwerp 8,94,184
Voorwerp 9,98,192
Voorwerp 10,106,201
Voorwerp 11,110,210
Voorwerp 12,113,214
Voorwerp 13,115,221
Voorwerp 14,118,229
Voorwerp 15,120,240

I am trying to solve the Knapsack problem by using GenSA and GA. The solution for this set of data should be around 1458.

However, with this code:

install.packages("GenSA")
install.packages("GA")
require(GenSA)
library(GenSA)
require(GA)
library(GA)

#Loading data
df <- read.csv("knapsack.csv", header=TRUE, sep=",")

#Define function
knapsack <- function(x) {
  f <- sum(x * df[3])
  penalty <- sum(df[2]) * abs(sum(x*df[2]) - 750)
  f - penalty
}

init <- runif(1, -5000, 5000)

onder <- rep(-5000, length(init))
boven <- rep(5000, length(init))

controlelijst <- list(max.time=25, nb.stop.improvement = 100)

resultaatSA <- GenSA(par=init, lower = onder, upper = boven, fn=knapsack, control=controlelijst)

resultaatSA$par

# Solution num 2
SGA <- ga(type="binary", fitness=knapsack, nBits=length(df[1]), maxiter=150, run=250, popSize=100, seed=101)

SGA
SGA@solution

I get a lot of nonsense output. GenSA for example says the solution is -5000, or sometimes 5000. Which are boundaries/constraints I have set.

SA gives 1 as solution.

What exactly am I doing wrong, and how do I need to use those two functions correctly?

Body:
I think John Coleman is correct, and that you have to simply change the sign of your cost function so that it is minimized. Below is a (slightly overkill) example of how this small addition of a minus to your function will result in a very different solution (hopefully the correct one). I have plotted the results in a similar way as GA does, as I saw from your code that you were also looking into that as an option (quite a good one in fact). For GA, the cost function is maximized, so you would need to remove the minus.

library(GenSA)
library(GA)

df <- read.table(text = ",gewichten(gr),waarde
Voorwerp 1,70,135
Voorwerp 2,73,139
Voorwerp 3,77,149
Voorwerp 4,80,150
Voorwerp 5,82,156
Voorwerp 6,87,163
Voorwerp 7,90,173
Voorwerp 8,94,184
Voorwerp 9,98,192
Voorwerp 10,106,201
Voorwerp 11,110,210
Voorwerp 12,113,214
Voorwerp 13,115,221
Voorwerp 14,118,229
Voorwerp 15,120,240", sep = ",", header = T
)

#Define function
knapsack <- function(x) {
  f <- sum(x * df[3])
  penalty <- sum(df[2]) * abs(sum(x*df[2]) - 750)
  -(f - penalty) # SIMPLY ADDED A MINUS SIGN
}

init <- runif(1, -5000, 5000)

onder <- rep(-5000, length(init))
boven <- rep(5000, length(init))

controlelijst <- list(max.time=25, nb.stop.improvement = 100)

resultaatSA <- GenSA(par=init, lower = onder, upper = boven, fn=knapsack, control=controlelijst)

resultaatSA$par # 0.5233775
head(resultaatSA$trace.mat)

# summarize results
tmp <- as.data.frame(resultaatSA$trace.mat)
meani <- aggregate(tmp$function.value, list(step = tmp$nb.steps),mean, na.rm = TRUE)
exe <- aggregate(tmp$current.minimum, list(step = tmp$nb.steps),mean, na.rm = TRUE)
medi <- aggregate(tmp$function.value, list(step = tmp$nb.steps),median, na.rm = TRUE)
ylim <- c(min(range(exe$x,na.rm = TRUE, finite = TRUE)),
          max(range(meani$x, na.rm = TRUE, finite = TRUE)))

# plot
op <- par(mar=c(5.1, 4.1, 1, 4.1))
plot(tmp$nb.steps, tmp$function.value, type = "n", ylim = ylim, xlab = "Iteration",
     ylab = "Cost value")
graphics::grid(equilogs = FALSE)
points(tmp$nb.steps, tmp$current.minimum, type = "o", pch = 16, lty = 1,
       col = "green3", cex = 0.7)
points(meani$step, meani$x, type = "o", pch = 1, lty = 2,
       col = "dodgerblue3", cex = 0.7)
polygon(c(meani$step, rev(meani$step)),
        c(exe$x, rev(medi$x)),
        border = FALSE, col = adjustcolor("green3", alpha.f = 0.1))
par(new=TRUE)
plot(tmp$nb.steps, tmp$temperature, t="l", col=2, lty=2, log="y", axes = FALSE, xlab = "", ylab = "")
axis(4, col=2, col.axis=2); mtext(text = "Temperature", side = 4, line = par()$mgp[1], col=2)
legend("topright", legend = c("Best", "Mean", "Median", "Temperature"),
       col = c("green3", "dodgerblue3", adjustcolor("green3", alpha.f = 0.1), 2),
       pch = c(16, 1, NA, NA), lty = c(1,2,1,2),
       lwd = c(1, 1, 10, 1), pt.cex = c(rep(0.7,2), 2, NA),
       inset = 0.02)
par(op)


问:
Is it possible to determine if a number is recursive in Google Sheets?
So I'd like 1/3 (which equals 0.33333 recurring) to return true and 1/8 (which equals 0.125 non-recurring) to be false.

Something like =ISRECURRING(A1) which returns a boolean.

The reason for this is that I want to highlight cells that have had rounding applied to them.

答:
Credit to @Ron Rosenfeld.

=A1-ROUND(A1,14) <> 0 works a treat. Where A1 is the number in question.

I can't guarantee that every rounded number works but it appears to work on all the examples I've tried.


问:
Get Samsung KNOX api version on old devices like Jelly Bean
I have a Samsung Galaxy Camera 2 with Android 4.3 Jelly Bean (it's about the same age as the Samsung Galaxy S3).

Their docs tells me, on Jelly Bean I can find KNOX Api level 5 - 10.

So, how do I find out which KNOX Api level I actually have?

I couldn't find it in the system info page in the settings

I haven't found a way to retrieve it programmatically

答:
Manually

Newer devices

Settings > About Device > Software Information > Knox Version

Older devices

Find your device here: Devices Secured by Knox

Programmatically

For API level 24 and higher you can retrieve the API level with EnterpriseDeviceManager.getAPILevel(). It returns any of the constants defined in EnterpriseDeviceManager.KNOX_VERSION_CODES.

With that integer value you can then go to the reference table and see more details.


问:
i get the following error ;undefined variable, in codeigniter
Controller
when i run the code i get the error :
Severity: Notice

Message: Undefined variable: id

Filename: controllers/User.php

Line Number: 293

```<code>public function edit()
    {
    $this->load->library('session');
    $this->load->model('Users_model');
    $this->load->model('Images_model');
    $this->load->view('edit');
    $this->session->set_userdata('user_id',$id);

    }
</code>```

model

```<code>public function edit($data,$id)
    {
   $this->db->where('id', $id);
   $this->db->update('user',$data);
     }
</code>```

答:
It's because you haven't defined $id anywhere in your controller, if you want to use the id in the controller then you must define it. Now since you're editing something you must send it via URL-

```<code>public function edit($id = false) // default value is null if you don't provide anything in your URL
{
    $this->load->library('session');
    $this->load->model('Users_model');
    $this->load->model('Images_model');
    $this->load->view('edit');
    $this->session->set_userdata('user_id', $id);

}
</code>```

Hope this helps you. :)

Body:
Controller
when i run the code i get the error :
Severity: Notice

Message: Undefined variable: id

Filename: controllers/User.php

Line Number: 293

public function edit()
    {
    $this->load->library('session');
    $this->load->model('Users_model');
    $this->load->model('Images_model');
    $this->load->view('edit');
    $this->session->set_userdata('user_id',$id);

    }

model

public function edit($data,$id)
    {
   $this->db->where('id', $id);
   $this->db->update('user',$data);
     }

Body:
It's because you haven't defined $id anywhere in your controller, if you want to use the id in the controller then you must define it. Now since you're editing something you must send it via URL-

public function edit($id = false) // default value is null if you don't provide anything in your URL
{
    $this->load->library('session');
    $this->load->model('Users_model');
    $this->load->model('Images_model');
    $this->load->view('edit');
    $this->session->set_userdata('user_id', $id);

}

Hope this helps you. :)


问:
Where my application's database is stored
I`m new to Android developement.  I want to know by adding this code where the database physically exists in my application folder.</p>

```<code>SQLiteDatabase myDB = info.this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
 myDB.execSQL("CREATE TABLE IF NOT EXISTS "
     + TableName
     + " (Field1 VARCHAR, Field2 INT(3));");
 Toast.makeText(this,"Database Created", Toast.LENGTH_SHORT).show();
   /* Insert data to a Table*/
   myDB.execSQL("INSERT INTO "
     + TableName
     + " (Field1, Field2)"
     + " VALUES ('Raj Gaurav', 24);");
</code>```

答:
If you want to access you data base you can use path as:

```<code>private String DB_PATH = "/data/data/"
                        + mycontext.getApplicationContext().getPackageName()
                        + "/databases/";
</code>```

refer this link for more info

adding your own SQLite database to an android application

Body:
I`m new to Android developement.  I want to know by adding this code where the database physically exists in my application folder.

SQLiteDatabase myDB = info.this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
 myDB.execSQL("CREATE TABLE IF NOT EXISTS "
     + TableName
     + " (Field1 VARCHAR, Field2 INT(3));");
 Toast.makeText(this,"Database Created", Toast.LENGTH_SHORT).show();
   /* Insert data to a Table*/
   myDB.execSQL("INSERT INTO "
     + TableName
     + " (Field1, Field2)"
     + " VALUES ('Raj Gaurav', 24);");

Body:
If you want to access you data base you can use path as:

private String DB_PATH = "/data/data/"
                        + mycontext.getApplicationContext().getPackageName()
                        + "/databases/";

refer this link for more info

adding your own SQLite database to an android application


问:
TLS setting in Chrome vs IE - ERR_CONNECTION_RESET
I'm trying to connect to IIS (on WS2016 where TLS 1.2 is only available TLS version - the other ones are disabled).

Exploring with IE works fine

Exploring with Chrome (up to date)  finishes with ERR_CONNECTION_RESET

I tried many configurations with Registry SCHANNEL / IE Options.
Moreover Wireshark logs that:

IE makes Client Hello with TLSv1.2 - what works fine.

Chrome makes Client Hello with TLSv1 - what finishes with ERR_CONNECTION_RESET

Any idea what configuration force Chrome to use TLSv1 instead of configured TLSv1.2?

答:
Are you using client certificates? Because your description sounds very similar to a problem I'm currently facing since Chrome updated from v81 to v83.
I have no clue about the source of the problem yet but if I disable client certificates completely the problem disappears.
I can reproduces the problem with a fresh installed Win Server 2019.  </p>


问:
How to connect to Oracle Database with php?
I am currently working on a website that connects to an Oracle Database. I have two php files, one for connection with the database and the other is the html structure itself.

Connect.php:

```<code><?php

$servername = "//////";
$username = "/////";
$password = "/////";

$conn = oci_connect($servername, $username, $password);

 if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
 }
 echo "Connected!";

?>
</code>```

I have been having a very hard time connecting to the database. I followed the Oracle tutorial and edited the oci8.connection_class = MYPHPAPP in php.ini, but everytime I run the Connect.php, I get the HTTP Error 500. Did I miss anything? What should I do?

Edit 1: I used display_errors and the error I am getting is Call to undefined function oci_connect()

Edit 2: I tried everything at this point to make the oci_connect work. I downloaded the oracle client and made it an environmental variable but oci_connect is still not working. I would really appreciate if any mac users could help me with this.

答:
Forth link in google after searching for your exact questions brought up the following link: http://me2learn.wordpress.com/2008/10/18/connect-php-with-oracle-database/</p>

```<code><?php
    $db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.1.34)(PORT = 1521)))(CONNECT_DATA=(SID=orcl)))" ;

    if($c = OCILogon("system", "your database password", $db))
    {
        echo "Successfully connected to Oracle.\n";
        OCILogoff($c);
    }
    else
    {
        $err = OCIError();
        echo "Connection failed." . $err[text];
    }
?>
</code>```

Body:
I am currently working on a website that connects to an Oracle Database. I have two php files, one for connection with the database and the other is the html structure itself.

Connect.php:

<?php

$servername = "//////";
$username = "/////";
$password = "/////";

$conn = oci_connect($servername, $username, $password);

 if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
 }
 echo "Connected!";

?>

I have been having a very hard time connecting to the database. I followed the Oracle tutorial and edited the oci8.connection_class = MYPHPAPP in php.ini, but everytime I run the Connect.php, I get the HTTP Error 500. Did I miss anything? What should I do?

Edit 1: I used display_errors and the error I am getting is Call to undefined function oci_connect()

Edit 2: I tried everything at this point to make the oci_connect work. I downloaded the oracle client and made it an environmental variable but oci_connect is still not working. I would really appreciate if any mac users could help me with this.

Body:
Forth link in google after searching for your exact questions brought up the following link: http://me2learn.wordpress.com/2008/10/18/connect-php-with-oracle-database/

<?php
    $db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.1.34)(PORT = 1521)))(CONNECT_DATA=(SID=orcl)))" ;

    if($c = OCILogon("system", "your database password", $db))
    {
        echo "Successfully connected to Oracle.\n";
        OCILogoff($c);
    }
    else
    {
        $err = OCIError();
        echo "Connection failed." . $err[text];
    }
?>


问:
lateinit property mock object has not been initialized
I'm trying to initialize (by mocking) two objects with the annotation @MockBean

It seems only to work if i call the method mock(className), but since i want to use the mocked class on multiple methods i don't want to keep repeating the same code in my test methods.

This is my test class:

```<code>@RunWith(MockitoJUnitRunner::class)
class WordServiceTest {

    @MockBean
    lateinit var wordRepositoryMock: WordRepository

    @MockBean
    private lateinit var wordMapperMock: WordMapper

    @Test
    fun findAllTest() {
        // Error: lateinit property wordRepositoryMock has not been initialized
        val wordService = WordService(wordRepositoryMock, wordMapperMock)
        `when`(wordRepositoryMock.findAll()).thenReturn(listOf(
                WordEntity(UUID.randomUUID(), "xxx"),
                WordEntity(UUID.randomUUID(), "xxx")))
        assertEquals(2, wordService.findAll().size)
    }

    @Test
    fun wordExistsTest() {
        // This works fine
        val wordRepositoryMock = mock(WordRepository::class.java)
        val wordMapperMock = mock(WordMapper::class.java)
        val wordService = WordService(wordRepositoryMock, wordMapperMock)
        val word = "xxx"
        `when`(wordRepositoryMock.existsWordEntityByName(word)).thenReturn(true)
        assertEquals(true, wordService.wordExists(word))
    }
}
</code>```

I don't want to use the Spring Boot @Autowired annotation because my spring application requires  contexts which i don't want to load.

The error i'm getting:

```<code>lateinit property wordRepositoryMock has not been initialized
kotlin.UninitializedPropertyAccessException: lateinit property wordRepositoryMock has not been initialized
</code>```

Dependencies:

```<code>dependencies {
    ...
    testImplementation("org.springframework.security:spring-security-test")
    testImplementation ('org.springframework.boot:spring-boot-starter-test')
    testImplementation("org.junit.jupiter:junit-jupiter:5.6.2")
    testImplementation "org.junit.jupiter:junit-jupiter-params:5.5.2"
    testImplementation "org.junit.jupiter:junit-jupiter-api:5.6.2"
    testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.6.2"
    testImplementation("io.rest-assured:spring-mock-mvc:4.0.0")
    testImplementation("io.mockk:mockk:1.9.3")
    testImplementation "org.testcontainers:postgresql:1.11.3"
    testImplementation "org.springframework.kafka:spring-kafka-test:2.2.7.RELEASE"
    runtimeOnly('org.postgresql:postgresql')
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    testImplementation "org.mockito:mockito-junit-jupiter:3.3.3"
}
</code>```

答:
MockitoJUnitRunner works with the @Mock annotation.

@MockBean is coming from Spring so you need to use the @SpringRunner.

However, it looks like your examples don't need Spring, so you can switch to @Mock:

@RunWith(MockitoJUnitRunner::class)
class WordServiceTest {

    @Mock
    private lateinit var wordRepositoryMock: WordRepository

    @Mock
    private lateinit var wordMapperMock: WordMapper
}
```

<p>There's a further improvement you could make if you upgraded to Junit5 (I only tested it in Junit5). Constructor arguments are a good alternative to <code>lateinit</code>:</p>

<pre class="lang-kotlin prettyprint-override"><code>@ExtendWith(MockitoExtension::class)
class WordServiceTest(
    @Mock val wordRepositoryMock: WordRepository,
    @Mock val wordMapperMock: WordMapper
) {

}
</code>```

Body:
I'm trying to initialize (by mocking) two objects with the annotation @MockBean

It seems only to work if i call the method mock(className), but since i want to use the mocked class on multiple methods i don't want to keep repeating the same code in my test methods.

This is my test class:

@RunWith(MockitoJUnitRunner::class)
class WordServiceTest {

    @MockBean
    lateinit var wordRepositoryMock: WordRepository

    @MockBean
    private lateinit var wordMapperMock: WordMapper

    @Test
    fun findAllTest() {
        // Error: lateinit property wordRepositoryMock has not been initialized
        val wordService = WordService(wordRepositoryMock, wordMapperMock)
        `when`(wordRepositoryMock.findAll()).thenReturn(listOf(
                WordEntity(UUID.randomUUID(), "xxx"),
                WordEntity(UUID.randomUUID(), "xxx")))
        assertEquals(2, wordService.findAll().size)
    }

    @Test
    fun wordExistsTest() {
        // This works fine
        val wordRepositoryMock = mock(WordRepository::class.java)
        val wordMapperMock = mock(WordMapper::class.java)
        val wordService = WordService(wordRepositoryMock, wordMapperMock)
        val word = "xxx"
        `when`(wordRepositoryMock.existsWordEntityByName(word)).thenReturn(true)
        assertEquals(true, wordService.wordExists(word))
    }
}

I don't want to use the Spring Boot @Autowired annotation because my spring application requires  contexts which i don't want to load.

The error i'm getting:

lateinit property wordRepositoryMock has not been initialized
kotlin.UninitializedPropertyAccessException: lateinit property wordRepositoryMock has not been initialized

Dependencies:

dependencies {
    ...
    testImplementation("org.springframework.security:spring-security-test")
    testImplementation ('org.springframework.boot:spring-boot-starter-test')
    testImplementation("org.junit.jupiter:junit-jupiter:5.6.2")
    testImplementation "org.junit.jupiter:junit-jupiter-params:5.5.2"
    testImplementation "org.junit.jupiter:junit-jupiter-api:5.6.2"
    testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.6.2"
    testImplementation("io.rest-assured:spring-mock-mvc:4.0.0")
    testImplementation("io.mockk:mockk:1.9.3")
    testImplementation "org.testcontainers:postgresql:1.11.3"
    testImplementation "org.springframework.kafka:spring-kafka-test:2.2.7.RELEASE"
    runtimeOnly('org.postgresql:postgresql')
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    testImplementation "org.mockito:mockito-junit-jupiter:3.3.3"
}

Body:
MockitoJUnitRunner works with the @Mock annotation.

@MockBean is coming from Spring so you need to use the @SpringRunner.

However, it looks like your examples don't need Spring, so you can switch to @Mock:

@RunWith(MockitoJUnitRunner::class)
class WordServiceTest {

    @Mock
    private lateinit var wordRepositoryMock: WordRepository

    @Mock
    private lateinit var wordMapperMock: WordMapper
}

There's a further improvement you could make if you upgraded to Junit5 (I only tested it in Junit5). Constructor arguments are a good alternative to lateinit:

@ExtendWith(MockitoExtension::class)
class WordServiceTest(
    @Mock val wordRepositoryMock: WordRepository,
    @Mock val wordMapperMock: WordMapper
) {

}


问:
Django AttributeError: 'str' object has no attribute 'tzinfo'
I am getting this error at the following code, when I try to get all the objects from my database:

```<code>data1 = Data.objects.all()
for dataset in data1:
</code>```

Here is my model:

```<code>class Data(models.Model):
id = models.AutoField(db_column='ID', primary_key=True)  # Field name made lowercase.
path = models.TextField(db_column='Path')  # Field name made lowercase.
username = models.ForeignKey('Users', models.DO_NOTHING, db_column='Username')  # Field name made lowercase.
datatype = models.CharField(db_column='Datatype', max_length=20, blank=True, null=True)  # Field name made lowercase.
filesize = models.FloatField(db_column='Filesize', blank=True, null=True)  # Field name made lowercase.
creationdate = models.DateTimeField(db_column='CreationDate')  # Field name made lowercase.
modificationdate = models.DateTimeField(db_column='ModificationDate')  # Field name made lowercase.
diskname = models.CharField(db_column='Diskname', max_length=100, blank=True, null=True)  # Field name made lowercase.

class Meta:
    managed = False
    db_table = 'Data'
</code>```

The full error message is:

```<code>    Internal Server Error: /files/
Traceback (most recent call last):
  File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/pi/.local/lib/python3.7/site-packages/django/views/decorators/cache.py", line 31, in _cache_controlled
    response = viewfunc(request, *args, **kw)
  File "/home/pi/.local/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/pi/MakMakula/FileManager/app/views.py", line 57, in index
    for dataset in data1:
  File "/home/pi/.local/lib/python3.7/site-packages/django/db/models/query.py", line 276, in __iter__
    self._fetch_all()
  File "/home/pi/.local/lib/python3.7/site-packages/django/db/models/query.py", line 1261, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/home/pi/.local/lib/python3.7/site-packages/django/db/models/query.py", line 74, in __iter__
    for row in compiler.results_iter(results):
  File "/home/pi/.local/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1095, in apply_converters
    value = converter(value, expression, connection)
  File "/home/pi/.local/lib/python3.7/site-packages/django/db/backends/mysql/operations.py", line 265, in convert_datetimefield_value
    value = timezone.make_aware(value, self.connection.timezone)
  File "/home/pi/.local/lib/python3.7/site-packages/django/utils/timezone.py", line 270, in make_aware
    return timezone.localize(value, is_dst=is_dst)
  File "/home/pi/.local/lib/python3.7/site-packages/pytz/__init__.py", line 237, in localize
    if dt.tzinfo is not None:
AttributeError: 'str' object has no attribute 'tzinfo'
[02/Jun/2020 10:43:44] "GET /files/ HTTP/1.1" 500 110853
</code>```

Does anybody have any ideas why this comes up?

Body:
I am getting this error at the following code, when I try to get all the objects from my database:

data1 = Data.objects.all()
for dataset in data1:

Here is my model:

class Data(models.Model):
id = models.AutoField(db_column='ID', primary_key=True)  # Field name made lowercase.
path = models.TextField(db_column='Path')  # Field name made lowercase.
username = models.ForeignKey('Users', models.DO_NOTHING, db_column='Username')  # Field name made lowercase.
datatype = models.CharField(db_column='Datatype', max_length=20, blank=True, null=True)  # Field name made lowercase.
filesize = models.FloatField(db_column='Filesize', blank=True, null=True)  # Field name made lowercase.
creationdate = models.DateTimeField(db_column='CreationDate')  # Field name made lowercase.
modificationdate = models.DateTimeField(db_column='ModificationDate')  # Field name made lowercase.
diskname = models.CharField(db_column='Diskname', max_length=100, blank=True, null=True)  # Field name made lowercase.

class Meta:
    managed = False
    db_table = 'Data'

The full error message is:

    Internal Server Error: /files/
Traceback (most recent call last):
  File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/pi/.local/lib/python3.7/site-packages/django/views/decorators/cache.py", line 31, in _cache_controlled
    response = viewfunc(request, *args, **kw)
  File "/home/pi/.local/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/pi/MakMakula/FileManager/app/views.py", line 57, in index
    for dataset in data1:
  File "/home/pi/.local/lib/python3.7/site-packages/django/db/models/query.py", line 276, in __iter__
    self._fetch_all()
  File "/home/pi/.local/lib/python3.7/site-packages/django/db/models/query.py", line 1261, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/home/pi/.local/lib/python3.7/site-packages/django/db/models/query.py", line 74, in __iter__
    for row in compiler.results_iter(results):
  File "/home/pi/.local/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1095, in apply_converters
    value = converter(value, expression, connection)
  File "/home/pi/.local/lib/python3.7/site-packages/django/db/backends/mysql/operations.py", line 265, in convert_datetimefield_value
    value = timezone.make_aware(value, self.connection.timezone)
  File "/home/pi/.local/lib/python3.7/site-packages/django/utils/timezone.py", line 270, in make_aware
    return timezone.localize(value, is_dst=is_dst)
  File "/home/pi/.local/lib/python3.7/site-packages/pytz/__init__.py", line 237, in localize
    if dt.tzinfo is not None:
AttributeError: 'str' object has no attribute 'tzinfo'
[02/Jun/2020 10:43:44] "GET /files/ HTTP/1.1" 500 110853

Does anybody have any ideas why this comes up?

Body:
There is an issue with your data from the DateTimeField field. The data needs to be in common DateTime format.

From the docu: https://docs.djangoproject.com/en/3.0/ref/forms/fields/#datetimefield

Normalizes to: A Python datetime.datetime object.

Validates that the given value is either a datetime.datetime, \
datetime.date or string formatted in a particular datetime format.

Your data has to match one of the below:

[
    '%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'
    '%Y-%m-%d %H:%M:%S.%f',  # '2006-10-25 14:30:59.000200'
    '%Y-%m-%d %H:%M',        # '2006-10-25 14:30'
    '%Y-%m-%d',              # '2006-10-25'
    '%m/%d/%Y %H:%M:%S',     # '10/25/2006 14:30:59'
    '%m/%d/%Y %H:%M:%S.%f',  # '10/25/2006 14:30:59.000200'
    '%m/%d/%Y %H:%M',        # '10/25/2006 14:30'
    '%m/%d/%Y',              # '10/25/2006'
    '%m/%d/%y %H:%M:%S',     # '10/25/06 14:30:59'
    '%m/%d/%y %H:%M:%S.%f',  # '10/25/06 14:30:59.000200'
    '%m/%d/%y %H:%M',        # '10/25/06 14:30'
    '%m/%d/%y',              # '10/25/06'
]


问:
Two UpdatePanels working in parallel, one not updating
I have two update panels (lets call them A and B). In A, I have a simple checkbox. AutoPostback set to true. When you check it (or uncheck it), it will enable/disable a simple dropdown within the same UpdatePanel.

UpdatePanel B has a long running process in it. It fires off a request for a dropdown to be created that takes nearly 2 minutes to construct. If I load the page and don't touch anything, the dropdown is constructed after about 2 minutes and renders perfectly. However, if during that two minutes I decide to check my checkbox (and cause a partial postback for panel A), updatepanel B never gets rendered. While debugging, I found that it is completing its retrieval successfully, but the actual panel never refreshes to show the control.

I have tried using UpdateMode = Conditional on panel B (to ensure it would not be disturbed by panel A) and it produces the same results. I have verified that B.Update() is being called also.

EDIT

Panel A:

```<code><asp:UpdatePanel ID="upMailScrub" runat="server">
    <ContentTemplate>
        <asp:Button ID="btnAnalyzeLaunch" runat="server" onclick="btnAnalyzeLaunch_Click" Text="Analyze Launch" style="display: none" />
        <table>
            <tr>
                <td><asp:CheckBox ID="cbxScrub" runat="server" Checked="true"
                        oncheckedchanged="cbxScrub_CheckedChanged" AutoPostBack="True" /></td><td><label for="cbxScrub">Scrub this campaign</label></td>
                <td style="padding-left: 10px">
                    Vendor:  <asp:DropDownList ID="ddlScrubVendor" runat="server">
                        <asp:ListItem Text="LexisNexis" Value="LexisNexis" />
                    </asp:DropDownList>
                </td>
            </tr>
        </table>
    </ContentTemplate>
</asp:UpdatePanel>
</code>```

Panel B:

```<code><asp:UpdatePanel ID="upDdlCampaigns" runat="server" UpdateMode="Conditional">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="btnAnalyzeLaunch" EventName="Click" />
    </Triggers>
    <ContentTemplate>
        <asp:HiddenField id="hidAction" runat="server" />
        <asp:Panel ID="pnlPleaseWait" runat="server"><img src="style/images/PleaseWait.gif" /> Please wait while the Five9 Campaigns are retrieved...</asp:Panel>
        <asp:DropDownList ID="ddlCampaigns" Visible="false" runat="server" class="required"
            AutoPostBack="True" OnSelectedIndexChanged="ddlCampaigns_SelectedIndexChanged" />
        <asp:Button ID="btnRefreshDDL" runat="server" onclick="btnRefreshDDL_Click" style="display: none" />
    </ContentTemplate>
</asp:UpdatePanel>
</code>```

Any suggestions? Thanks.

答:
You ask too much from UpdatePanel :)

UpdatePanel can not work with 2 parallel request that way. Consider to make some ajax call to get your results.

Why you may ask, one basic reason is that every page have only one viewstate. When you ask from the A or the B, UpdatePanel to send/get data, then the viewstate must change to a new viewstate. Now, when you ask a result from A, and before you end, you ask results from B, you going to get 2 different viewstate, and one of them is going to fail because in the middle time have change.

ViewState is not the only think, in every update panel click, the page post back all inputs post to page, both A and B inputs and all the rest inside the page, this is also a problem. Imaging this for example, you trigger A UpdatePanel with inputs A+B, and then before the A ends, you trigger B UpdatePanel with the same inputs. Now A, waits for results from A+B, the same and B, but in the middle time the A+B results from A is now different because B has change them - and fails.

Body:
I have two update panels (lets call them A and B). In A, I have a simple checkbox. AutoPostback set to true. When you check it (or uncheck it), it will enable/disable a simple dropdown within the same UpdatePanel.

UpdatePanel B has a long running process in it. It fires off a request for a dropdown to be created that takes nearly 2 minutes to construct. If I load the page and don't touch anything, the dropdown is constructed after about 2 minutes and renders perfectly. However, if during that two minutes I decide to check my checkbox (and cause a partial postback for panel A), updatepanel B never gets rendered. While debugging, I found that it is completing its retrieval successfully, but the actual panel never refreshes to show the control.

I have tried using UpdateMode = Conditional on panel B (to ensure it would not be disturbed by panel A) and it produces the same results. I have verified that B.Update() is being called also.

EDIT

Panel A:

<asp:UpdatePanel ID="upMailScrub" runat="server">
    <ContentTemplate>
        <asp:Button ID="btnAnalyzeLaunch" runat="server" onclick="btnAnalyzeLaunch_Click" Text="Analyze Launch" style="display: none" />

                <asp:CheckBox ID="cbxScrub" runat="server" Checked="true"
                        oncheckedchanged="cbxScrub_CheckedChanged" AutoPostBack="True" />	Scrub this campaign

                    Vendor:  <asp:DropDownList ID="ddlScrubVendor" runat="server">
                        <asp:ListItem Text="LexisNexis" Value="LexisNexis" />
                    </asp:DropDownList>

    </ContentTemplate>
</asp:UpdatePanel>

Panel B:

<asp:UpdatePanel ID="upDdlCampaigns" runat="server" UpdateMode="Conditional">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="btnAnalyzeLaunch" EventName="Click" />
    </Triggers>
    <ContentTemplate>
        <asp:HiddenField id="hidAction" runat="server" />
        <asp:Panel ID="pnlPleaseWait" runat="server"> Please wait while the Five9 Campaigns are retrieved...</asp:Panel>
        <asp:DropDownList ID="ddlCampaigns" Visible="false" runat="server" class="required"
            AutoPostBack="True" OnSelectedIndexChanged="ddlCampaigns_SelectedIndexChanged" />
        <asp:Button ID="btnRefreshDDL" runat="server" onclick="btnRefreshDDL_Click" style="display: none" />
    </ContentTemplate>
</asp:UpdatePanel>

Any suggestions? Thanks.


问:
Set a minimum order amount per vendor in Dokan
I want to have a minimum order amount in my Dokan store. The following code is doing the work but individual vendors can't select their own minimum value.

```<code>    //minimum order value

add_action( 'woocommerce_check_cart_items', 'required_min_cart_subtotal_amount' );
function required_min_cart_subtotal_amount() {

// Only run in the Cart or Checkout pages
if( is_cart() || is_checkout() ) {

    // HERE Set minimum cart total amount
    $min_total = 200;

    // Total (before taxes and shipping charges)
    $total = WC()->cart->subtotal;

    // Add an error notice is cart total is less than the minimum required
    if( $total <= $min_total  ) {
        // Display an error message
        wc_add_notice( '<strong>' . sprintf( __("A minimum total purchase amount of %s is required to checkout."), wc_price($min_total) ) . '<strong>', 'error' );
         }
    }
}
</code>```

So I added a custom field to the Dokan settings page

```<code>    //Extra field on the seller settings and show the value on the store banner -Dokan

// Add an extra field in seller settings

add_filter( 'dokan_settings_form_bottom', 'extra_fields', 10, 2);

function extra_fields( $current_user, $profile_info ){
$minimum_order= isset( $profile_info['minimum_order'] ) ? $profile_info['minimum_order'] : '';
?>
 <div class="gregcustom dokan-form-group">
    <label class="dokan-w3 dokan-control-label" for="setting_address">
        <?php _e( 'Minimum order value', 'dokan' ); ?>
    </label>
    <div class="dokan-w5">
        <input type="number" class="dokan-form-control input-md valid" name="minimum_order" id="reg_minimum_order" value="<?php echo $minimum_order; ?>" />
    </div>
</div>
<?php
}

//save the field value

add_action( 'dokan_store_profile_saved', 'save_extra_fields', 15 );
function save_extra_fields( $store_id ) {
$dokan_settings = dokan_get_store_info($store_id);
if ( isset( $_POST['minimum_order'] ) ) {
    $dokan_settings['minimum_order'] = $_POST['minimum_order'];
}
 update_user_meta( $store_id, 'dokan_profile_settings', $dokan_settings );
}
</code>```

Now I want some code to use in here,

$min_total = 200;

to get vendor id from items of the cart and use it to get user meta and to show that minimum_order value in above. (200)
Sorry for my bad English.

答:
Keep your extra field function and try to add this in your function.php. Just a little tricky but seems to work :) </p>

```<code>add_action( 'woocommerce_check_cart_items', 'dokan_minimum_order_amount' );
function dokan_minimum_order_amount()
{

    $eachVendorCartTotal = array();
    $items = WC()->cart->get_cart();

    //build the array: [vendor_id][sub_total]
    foreach ($items as $item => $values) {

        $product_id = $values['product_id'];
        $product_qty = $values['quantity'];
        $product_price = get_post_meta($values['product_id'], '_price', true) * $product_qty;
        $vendor_id = get_post_field('post_author', $product_id);

        if (!array_key_exists($vendor_id, $eachVendorCartTotal)) {
            $eachVendorCartTotal[$vendor_id] = $product_price;
        } else {
            $sub_total = $product_price + $eachVendorCartTotal[$vendor_id];
            $eachVendorCartTotal[$vendor_id] = $sub_total;
        }

    }

    if (!empty($eachVendorCartTotal)) {
        foreach ($eachVendorCartTotal as $vendor_id => $value) {
            $errorMessage = "Your current order total for %s is %s — you must have an order with a minimum of %s to place your order for this vendor";
            $store_info = dokan_get_store_info($vendor_id);
            $store_name = $store_info['store_name'];
            if(!empty($store_info['minimum_order'])) {
                $vendor_minimum = !empty($store_info['minimum_order']) ? $store_info['minimum_order'] : 0;
                if ($value < $vendor_minimum) {
                    if (is_cart()) {

                        wc_print_notice(
                            sprintf($errorMessage,
                                $store_name,
                                wc_price($value),
                                wc_price($vendor_minimum)
                            ), 'error'
                        );

                    } else {
                        wc_add_notice(
                            sprintf($errorMessage,
                                $store_name,
                                wc_price($value),
                                wc_price($vendor_minimum)
                            ), 'error'
                        );
                    }
                }
            }
        }
    }
}
</code>```

Body:
I want to have a minimum order amount in my Dokan store. The following code is doing the work but individual vendors can't select their own minimum value.

    //minimum order value

add_action( 'woocommerce_check_cart_items', 'required_min_cart_subtotal_amount' );
function required_min_cart_subtotal_amount() {

// Only run in the Cart or Checkout pages
if( is_cart() || is_checkout() ) {

    // HERE Set minimum cart total amount
    $min_total = 200;

    // Total (before taxes and shipping charges)
    $total = WC()->cart->subtotal;

    // Add an error notice is cart total is less than the minimum required
    if( $total <= $min_total  ) {
        // Display an error message
        wc_add_notice( '' . sprintf( __("A minimum total purchase amount of %s is required to checkout."), wc_price($min_total) ) . '', 'error' );
         }
    }
}

So I added a custom field to the Dokan settings page

    //Extra field on the seller settings and show the value on the store banner -Dokan

// Add an extra field in seller settings

add_filter( 'dokan_settings_form_bottom', 'extra_fields', 10, 2);

function extra_fields( $current_user, $profile_info ){
$minimum_order= isset( $profile_info['minimum_order'] ) ? $profile_info['minimum_order'] : '';
?>

        <?php _e( 'Minimum order value', 'dokan' ); ?>

        <input type="number" class="dokan-form-control input-md valid" name="minimum_order" id="reg_minimum_order" value="<?php echo $minimum_order; ?>" />

<?php
}

//save the field value

add_action( 'dokan_store_profile_saved', 'save_extra_fields', 15 );
function save_extra_fields( $store_id ) {
$dokan_settings = dokan_get_store_info($store_id);
if ( isset( $_POST['minimum_order'] ) ) {
    $dokan_settings['minimum_order'] = $_POST['minimum_order'];
}
 update_user_meta( $store_id, 'dokan_profile_settings', $dokan_settings );
}

Now I want some code to use in here,

$min_total = 200;

to get vendor id from items of the cart and use it to get user meta and to show that minimum_order value in above. (200)
Sorry for my bad English.

Body:
Keep your extra field function and try to add this in your function.php. Just a little tricky but seems to work :)

add_action( 'woocommerce_check_cart_items', 'dokan_minimum_order_amount' );
function dokan_minimum_order_amount()
{

    $eachVendorCartTotal = array();
    $items = WC()->cart->get_cart();

    //build the array: [vendor_id][sub_total]
    foreach ($items as $item => $values) {

        $product_id = $values['product_id'];
        $product_qty = $values['quantity'];
        $product_price = get_post_meta($values['product_id'], '_price', true) * $product_qty;
        $vendor_id = get_post_field('post_author', $product_id);

        if (!array_key_exists($vendor_id, $eachVendorCartTotal)) {
            $eachVendorCartTotal[$vendor_id] = $product_price;
        } else {
            $sub_total = $product_price + $eachVendorCartTotal[$vendor_id];
            $eachVendorCartTotal[$vendor_id] = $sub_total;
        }

    }

    if (!empty($eachVendorCartTotal)) {
        foreach ($eachVendorCartTotal as $vendor_id => $value) {
            $errorMessage = "Your current order total for %s is %s — you must have an order with a minimum of %s to place your order for this vendor";
            $store_info = dokan_get_store_info($vendor_id);
            $store_name = $store_info['store_name'];
            if(!empty($store_info['minimum_order'])) {
                $vendor_minimum = !empty($store_info['minimum_order']) ? $store_info['minimum_order'] : 0;
                if ($value < $vendor_minimum) {
                    if (is_cart()) {

                        wc_print_notice(
                            sprintf($errorMessage,
                                $store_name,
                                wc_price($value),
                                wc_price($vendor_minimum)
                            ), 'error'
                        );

                    } else {
                        wc_add_notice(
                            sprintf($errorMessage,
                                $store_name,
                                wc_price($value),
                                wc_price($vendor_minimum)
                            ), 'error'
                        );
                    }
                }
            }
        }
    }
}


问:
BigBlueButton Crashing after upgrading VM RAM
Recently I Installed BigBlueButton with 4core CPU and 4GB Ram.
After one month I upgrade RAM to 8GB there was no problem
After two months I needed to Upgrade it so I  Upgrade it to 12GB RAM but it's crashed and it didn't work so I recovered snapshot.

Has anyone ever had same problem?

答:
I found the way to make it fixed

The only way to fix this issue is to reinstall the BigBlueButton again:

wget -qO- https://ubuntu.bigbluebutton.org/bbb-install.sh | bash -s -- -v xenial-220 -s bbb.domain.ir -e info@domain.ir -g

Don't worry about your data, your data will NOT lose and database will stable


问:
combobox binding
Please can you tell me how can I bind combobox.

I had combobox which Itemsource is ObservableCollection<strings>. I wont to set Selected Combobox value to MainObject.SomeValue and vice versa.

Which is the easiest way

答:
here's a little example.
I have two classes:

```<code> public class Person
    {
        private string _name = "Test2";
        public String Name
        {
            get { return _name; }
            set { _name = value; }
        }
    }

    public class DataProvider
    {
        public ObservableCollection<String> Data { get; set; }

        public DataProvider()
        {
            Data = new ObservableCollection<string>();
            Data.Add("Test");
            Data.Add("Test2");
            Data.Add("Test3");
            Data.Add("Test4");
        }
    }
</code>```

The DataProvider provides the string data for the combo box and the Person is the object where you want to bind the name. This can be done as followed:

```<code><Grid.Resources>
            <myNamespace:DataProvider x:Key="DataProvider"/>
            <myNamespace:Person x:Key="Person"/>
        </Grid.Resources>
        <ComboBox
            Height="25"
            DataContext="{StaticResource DataProvider}"
            ItemsSource="{Binding Data}"
            SelectedItem="{Binding Name, Source={StaticResource Person}, Mode=TwoWay}"/>
</code>```

This is just a quick example. Have a look at SelectedItem, SelectedValue, SelectedValuePath if you don't want to use string as input data...

Is this what you needed?

BR,

TJ

Title: combobox binding

Body:
here's a little example.
I have two classes:

 public class Person
    {
        private string _name = "Test2";
        public String Name
        {
            get { return _name; }
            set { _name = value; }
        }
    }

    public class DataProvider
    {
        public ObservableCollection<String> Data { get; set; }

        public DataProvider()
        {
            Data = new ObservableCollection<string>();
            Data.Add("Test");
            Data.Add("Test2");
            Data.Add("Test3");
            Data.Add("Test4");
        }
    }

The DataProvider provides the string data for the combo box and the Person is the object where you want to bind the name. This can be done as followed:

<Grid.Resources>
            <myNamespace:DataProvider x:Key="DataProvider"/>
            <myNamespace:Person x:Key="Person"/>
        </Grid.Resources>
        <ComboBox
            Height="25"
            DataContext="{StaticResource DataProvider}"
            ItemsSource="{Binding Data}"
            SelectedItem="{Binding Name, Source={StaticResource Person}, Mode=TwoWay}"/>

This is just a quick example. Have a look at SelectedItem, SelectedValue, SelectedValuePath if you don't want to use string as input data...

Is this what you needed?

BR,

TJ


问:
Pandas: create columns with deviation from mean in each group
Consider the following DataFrame in Python:

```<code>import pandas as pd
df = pd.DataFrame({'id':[0]*3+[1]*3,'y':np.random.randn(6),'x':np.random.randn(6)})
</code>```

which gives

```<code>   id         y         x
0   0  0.721757  1.595646
1   0  0.359601  1.128473
2   0  1.134922  2.317929
3   1  0.290152 -1.901336
4   1  0.128742  0.982683
5   1  0.556914  0.745208
</code>```

Note that y and x are grouped according to id. I want to creat the following DataFrame

```<code>   id         y         x      y_md      x_md
0   0  0.721757  1.595646 -0.017003 -0.085037
1   0  0.359601  1.128473 -0.379159 -0.552209
2   0  1.134922  2.317929  0.396162  0.637246
3   1  0.290152 -1.901336 -0.035117 -1.843521
4   1  0.128742  0.982683 -0.196527  1.040498
5   1  0.556914  0.745208  0.231644  0.803023
</code>```

where

y_md contains the value of deviation from its group mean (id=0 & 1)

x_md contains the value of deviation from its group mean (id=0 & 1)

What I came up with is

```<code>df_g = df.groupby('id')
yy = pd.Series( df['y'].values - df_g['y'].mean().repeat(3).values )
xx = pd.Series( df['x'].values - df_g['x'].mean().repeat(3).values )
pd.concat([df,yy.rename('y_md'), xx.rename('x_md')],axis=1)
</code>```

but it does not look good to me. I wonder if there is an elegant one liner or similar for the same result? I would appreciate your help.

Body:
Consider the following DataFrame in Python:

import pandas as pd
df = pd.DataFrame({'id':[0]*3+[1]*3,'y':np.random.randn(6),'x':np.random.randn(6)})

which gives

   id         y         x
0   0  0.721757  1.595646
1   0  0.359601  1.128473
2   0  1.134922  2.317929
3   1  0.290152 -1.901336
4   1  0.128742  0.982683
5   1  0.556914  0.745208

Note that y and x are grouped according to id. I want to creat the following DataFrame

   id         y         x      y_md      x_md
0   0  0.721757  1.595646 -0.017003 -0.085037
1   0  0.359601  1.128473 -0.379159 -0.552209
2   0  1.134922  2.317929  0.396162  0.637246
3   1  0.290152 -1.901336 -0.035117 -1.843521
4   1  0.128742  0.982683 -0.196527  1.040498
5   1  0.556914  0.745208  0.231644  0.803023

where

y_md contains the value of deviation from its group mean (id=0 & 1)

x_md contains the value of deviation from its group mean (id=0 & 1)

What I came up with is

df_g = df.groupby('id')
yy = pd.Series( df['y'].values - df_g['y'].mean().repeat(3).values )
xx = pd.Series( df['x'].values - df_g['x'].mean().repeat(3).values )
pd.concat([df,yy.rename('y_md'), xx.rename('x_md')],axis=1)

but it does not look good to me. I wonder if there is an elegant one liner or similar for the same result? I would appreciate your help.

Body:
Set id as index, groupby the index and subtract the mean of the grouping from df :

df = df.set_index("id")

df[['y_md','x_md']] = df.sub(df.groupby("id").agg("mean"))

df

       y           x            y_md      x_md
id
0   0.721757    1.595646    -0.017003   -0.085037
0   0.359601    1.128473    -0.379159   -0.552210
0   1.134922    2.317929    0.396162    0.637246
1   0.290152    -1.901336   -0.035117   -1.843521
1   0.128742    0.982683    -0.196527   1.040498
1   0.556914    0.745208    0.231645    0.803023


问:
How can I create an On-Demand DynamoDB table in C#?
I cannot seem to find an example of creating an On-Demand DynamoDB table in C#.

The C# examples on AWS only describes how to create a table with provisioned throughput.

答:
In my opinion the way this is supported in the SDK is unintuitive.

One would need to first create a table with a default ProvisionedThroughput then update the table and set the billing to: PAY_PER_REQUEST

```<code>CreateTableRequest createRequest = new CreateTableRequest
{
    TableName = "Foo",
    AttributeDefinitions = new List<AttributeDefinition> {
        new AttributeDefinition {
            AttributeName = "Id",
            AttributeType = ScalarAttributeType.S,
        }
    },
    KeySchema = new List<KeySchemaElement> {
        new KeySchemaElement("Id", KeyType.HASH)
    },
    ProvisionedThroughput = new ProvisionedThroughput(1, 1)
};

await client.CreateTableAsync(createRequest);
// Wait for it to be created

await client.UpdateTableAsync(new UpdateTableRequest
{
    TableName = name,
    BillingMode = BillingMode.PAY_PER_REQUEST
});
</code>```

Body:
In my opinion the way this is supported in the SDK is unintuitive.

One would need to first create a table with a default ProvisionedThroughput then update the table and set the billing to: PAY_PER_REQUEST

CreateTableRequest createRequest = new CreateTableRequest
{
    TableName = "Foo",
    AttributeDefinitions = new List<AttributeDefinition> {
        new AttributeDefinition {
            AttributeName = "Id",
            AttributeType = ScalarAttributeType.S,
        }
    },
    KeySchema = new List<KeySchemaElement> {
        new KeySchemaElement("Id", KeyType.HASH)
    },
    ProvisionedThroughput = new ProvisionedThroughput(1, 1)
};

await client.CreateTableAsync(createRequest);
// Wait for it to be created

await client.UpdateTableAsync(new UpdateTableRequest
{
    TableName = name,
    BillingMode = BillingMode.PAY_PER_REQUEST
});