问:
Using Jquery Autocomplete with C#
I am new to webdev, Jquery and asp.NET, I have tried to follow other's questions, and have been working on this problem for about a week now. I cannot seem to get it work with my database.

I am trying to implement a simple autocomplete feature for a text box on my asp.NET webpage using Jquery, C#, and a SQL database. So far I have a  C# function "Search()" which grabs the results similar to a local string. However I currently don't know how to pass the input text to this C# function.

Here is my .cs:

```<code>protected void Page_Load(object sender, EventArgs e)
{

}

protected void Search(object sender, EventArgs e)
{
    List<string> results;
    //ListBox1.Items.Clear();
    results = OleDb.fDbReadToArray(@"SELECT Project_Name from tProjectNames where Project_Name like '" + Local_String_to_be_passed from asp.NET + "%'");
   //foreach (string item in results)
   //{
   //    ListBox1.Items.Add(item);
   //}
}
</code>```

From what I've read online a good way to achieve this would to use Jquery and ajax to post the users input from the text box to my c# code and then get the results. I am trying to follow the Jquery example for autocomplete with a remote data source
(see https://jqueryui.com/autocomplete/#remote).

But I am struggling to make the Jquery go to my c# function. Here is my asp.NET:

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

 <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>jQuery UI Autocomplete - Default functionality</title>
      <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
      <link rel="stylesheet" href="/resources/demos/style.css">
      <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
      <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
      <script>
          $(function () {
              $("#ProjectNames").autocomplete({
                  source: "live_search.aspx.cs/Search()",
                  select: function (event, ui) {
                      log("Selected: " + ui.item.value + " aka " + ui.item.id);
                  }
              });
          });
      </script>
    </head>
    <body>

    <div>
      <label for="ProjectNames">Project Names: </label>
      <input id="ProjectNames" type ="text" oninput="Search()" />
    </div>

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

Can anyone tell me how to get what the user types in the input text box go to my C# function and then post the results back to the Jquery suggestion box?

Thank you

EDIT:
Here is the solution that ended up working for me, credit Chetan Ranpariya.

```<code><!DOCTYPE html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="jquery-1.12.4.js"></script>
  <script src="jquery-ui.js"></script>
  <script type="text/javascript">
      $(document).ready(function () {
          $(function () {
              $("#ProjectNames").autocomplete({
                  source: function (request, response) {
                      var objdata = JSON.stringify({
                          obj: {
                              query: $("#ProjectNames").val()
                          }

                      });
                      $.ajax({
                          url: "Live_Search1.aspx/Search",
                          data: objdata,
                          type: "POST",
                          contentType: "application/json; charset=utf-8",
                          dataFilter: function (data) { return data; },
                          success: function (data) {
                              response($.map(data.d, function (item) {
                                  return {
                                      label: item,
                                      value: item
                                  }
                              }))
                          }
                      });
                  }
              });
          });
      });
  </script>
</head>
<body>
    <form id="form" runat="server">
         <div>
              <asp:label for="ProjectNames" runat="server">Project Names: </asp:label>
              <input ID="ProjectNames" type ="text" runat="server" />
         </div>
    </form>
</body>
</html>
</code>```

.cs:

```<code>    public class Myobj
{
    public string query { get; set; }
}

[System.Web.Services.WebMethod]
public static List<string> Search(Myobj obj)
{

    List<string> projectList = new List<string>() { "project", "sam", "daniel" };
    List<string> results = new List<string>() { };
    foreach(string project in projectList)
    {
        if(project.Contains(obj.query))
        {
            results.Add(project);
        }
    }
    return results;
}
</code>```

If anybody has any edit's on how this can be improved computationally please let me know, keep in mind that project List will probably grow to be in the thousands. Thanks again Chetan Ranpariya!

答:
You need to create a static web method in the code behind of the page and then you can call it from Client side by using url {yourpage}.aspx/{yourmethod}. And it also should return data which you can capture in client side and use it.

So the Search method should be created as following. Here Search method does not accept any parameter.
I am returning list of searched string values from this method which will be captured as JSON at the client side which I can use whatever way I want to.

```<code>[System.Web.Services.WebMethod]
public static List<string> Search()
{
    List<string> results;
    //ListBox1.Items.Clear();
    results = OleDb.fDbReadToArray(@"SELECT Project_Name from tProjectNames where Project_Name like '" + Local_String_to_be_passed from asp.NET + "%'");

    //foreach (string item in results)
    //{
    //    ListBox1.Items.Add(item);
    //}
    return results;
}
</code>```

And you call the method from JQuery as following.

```<code>$(function () {
    $("#ProjectNames").autocomplete({
        source: function (request, response) {
            var objdata = {

            };

            $.ajax({
                url: "live_search.aspx/Search",
                data: JSON.stringify(objdata),
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataFilter: function (data) { return data; },
                success: function (data) {
                    response($.map(data.d, function (item) {
                        //item here is a string value coming from server.
                        return {
                            label: item,
                            value: item
                        }
                    }))
                }
            });
        }
     });
});
</code>```

Title: Using Jquery Autocomplete with C#

Body:
I am new to webdev, Jquery and asp.NET, I have tried to follow other's questions, and have been working on this problem for about a week now. I cannot seem to get it work with my database.

I am trying to implement a simple autocomplete feature for a text box on my asp.NET webpage using Jquery, C#, and a SQL database. So far I have a  C# function "Search()" which grabs the results similar to a local string. However I currently don't know how to pass the input text to this C# function.

Here is my .cs:

protected void Page_Load(object sender, EventArgs e)
{

}

protected void Search(object sender, EventArgs e)
{
    List<string> results;
    //ListBox1.Items.Clear();
    results = OleDb.fDbReadToArray(@"SELECT Project_Name from tProjectNames where Project_Name like '" + Local_String_to_be_passed from asp.NET + "%'");
   //foreach (string item in results)
   //{
   //    ListBox1.Items.Add(item);
   //}
}

From what I've read online a good way to achieve this would to use Jquery and ajax to post the users input from the text box to my c# code and then get the results. I am trying to follow the Jquery example for autocomplete with a remote data source
(see https://jqueryui.com/autocomplete/#remote).

But I am struggling to make the Jquery go to my c# function. Here is my asp.NET:

      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>jQuery UI Autocomplete - Default functionality</title>
      <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
      <link rel="stylesheet" href="/resources/demos/style.css">

      Project Names:
      <input id="ProjectNames" type ="text" oninput="Search()" />

Can anyone tell me how to get what the user types in the input text box go to my C# function and then post the results back to the Jquery suggestion box?

Thank you

EDIT:
Here is the solution that ended up working for me, credit Chetan Ranpariya.

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

    <form id="form" runat="server">

              <asp:label for="ProjectNames" runat="server">Project Names: </asp:label>
              <input ID="ProjectNames" type ="text" runat="server" />

    </form>

.cs:

    public class Myobj
{
    public string query { get; set; }
}

[System.Web.Services.WebMethod]
public static List<string> Search(Myobj obj)
{

    List<string> projectList = new List<string>() { "project", "sam", "daniel" };
    List<string> results = new List<string>() { };
    foreach(string project in projectList)
    {
        if(project.Contains(obj.query))
        {
            results.Add(project);
        }
    }
    return results;
}

If anybody has any edit's on how this can be improved computationally please let me know, keep in mind that project List will probably grow to be in the thousands. Thanks again Chetan Ranpariya!

Body:
You need to create a static web method in the code behind of the page and then you can call it from Client side by using url {yourpage}.aspx/{yourmethod}. And it also should return data which you can capture in client side and use it.

So the Search method should be created as following. Here Search method does not accept any parameter.
I am returning list of searched string values from this method which will be captured as JSON at the client side which I can use whatever way I want to.

[System.Web.Services.WebMethod]
public static List<string> Search()
{
    List<string> results;
    //ListBox1.Items.Clear();
    results = OleDb.fDbReadToArray(@"SELECT Project_Name from tProjectNames where Project_Name like '" + Local_String_to_be_passed from asp.NET + "%'");

    //foreach (string item in results)
    //{
    //    ListBox1.Items.Add(item);
    //}
    return results;
}

And you call the method from JQuery as following.

$(function () {
    $("#ProjectNames").autocomplete({
        source: function (request, response) {
            var objdata = {

            };

            $.ajax({
                url: "live_search.aspx/Search",
                data: JSON.stringify(objdata),
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataFilter: function (data) { return data; },
                success: function (data) {
                    response($.map(data.d, function (item) {
                        //item here is a string value coming from server.
                        return {
                            label: item,
                            value: item
                        }
                    }))
                }
            });
        }
     });
});


来源: stackexchange

问:
Weird sorting algorithm
I need to print a linked list in order but I need it to be sorted in a weird way and I couldnt find an answer. So I need it to be sorted first by the integer data(obviously bigger comes first), then within that I need it to be sorted by word. So lets say two nodes have the same data integer, then they would be sorted lexicographically by the word.
The linked list is like this

```<code>struct node {
    int data;
    char word[125];
    struct node* next;
}
</code>```

Any suggestions? It doesn't necessarily have to be sorted, I just have to print them in sorted order

答:
Since you're only processing so few elements, you could just fit the whole list into an array, then sort it with qsort. Here's a quick example. Be careful not to overflow the nodes array in print_sorted - for such few nodes, you could just go through the linked list once to get the size, then malloc the space you need.

Notice that in the example, node_compare works with an array of pointers to node. If you want to work directly with an array of nodes, just remove the dereferences at the start of the function and cast them to const struct node * instead of const struct node **.

```<code>// for qsort
#include <stdlib.h>
// for strcmp
#include <string.h>

struct node {
    int data;
    char word[125];
    struct node* next;
};

int node_compare(const void *a, const void *b) {
    const struct node *first = *(const struct node **) a;
    const struct node *second = *(const struct node **) b;

    // Order nodes with same data alphabetically
    if (first->data == second->data) {
        return strcmp(first->word, second->word);
    } else {
        return first->data - second->data;
    }
}

void print_sorted(struct node *list) {
    struct node *nodes[512];

    // gather whole list into the array
    struct node *current = list;
    int arrayIndex = 0;
    while (current != NULL) {
        nodes[arrayIndex++] = current;
        current = current->next;
    }

    // sort the array
    qsort(nodes, arrayIndex, sizeof(struct node *), node_compare);

    // print em
    for (int i = 0; i < arrayIndex; i++) {
        printf("data: %d, word: %s\n", nodes[i]->data, nodes[i]->word);
    }
}

int main() {
    struct node a = { .data = 3, .word = "ayy", .next = NULL };
    struct node b = { .data = 3, .word = "zzz", .next = &a };
    struct node c = { .data = 3, .word = "ddd", .next = &b };
    struct node d = { .data = 10, .word = "toaster", .next = &c };
    struct node e = { .data = 0, .word = "box", .next = &d };

    print_sorted(&e);
    return 0;
}
</code>```

This prints out:

```<code>data: 0, word: box
data: 3, word: ayy
data: 3, word: ddd
data: 3, word: zzz
data: 10, word: toaster
</code>```

If you want descending order, change the bottom part of node_compare() to the following:

```<code>if (first->data == second->data) {
    return strcmp(second->word, first->word);
} else {
    return second->data - first->data;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Weird sorting algorithm

Body:
I need to print a linked list in order but I need it to be sorted in a weird way and I couldnt find an answer. So I need it to be sorted first by the integer data(obviously bigger comes first), then within that I need it to be sorted by word. So lets say two nodes have the same data integer, then they would be sorted lexicographically by the word.
The linked list is like this

struct node {
    int data;
    char word[125];
    struct node* next;
}

Any suggestions? It doesn't necessarily have to be sorted, I just have to print them in sorted order

Body:
Since you're only processing so few elements, you could just fit the whole list into an array, then sort it with qsort. Here's a quick example. Be careful not to overflow the nodes array in print_sorted - for such few nodes, you could just go through the linked list once to get the size, then malloc the space you need.

Notice that in the example, node_compare works with an array of pointers to node. If you want to work directly with an array of nodes, just remove the dereferences at the start of the function and cast them to const struct node * instead of const struct node **.

// for qsort
#include <stdlib.h>
// for strcmp
#include <string.h>

struct node {
    int data;
    char word[125];
    struct node* next;
};

int node_compare(const void *a, const void *b) {
    const struct node *first = *(const struct node **) a;
    const struct node *second = *(const struct node **) b;

    // Order nodes with same data alphabetically
    if (first->data == second->data) {
        return strcmp(first->word, second->word);
    } else {
        return first->data - second->data;
    }
}

void print_sorted(struct node *list) {
    struct node *nodes[512];

    // gather whole list into the array
    struct node *current = list;
    int arrayIndex = 0;
    while (current != NULL) {
        nodes[arrayIndex++] = current;
        current = current->next;
    }

    // sort the array
    qsort(nodes, arrayIndex, sizeof(struct node *), node_compare);

    // print em
    for (int i = 0; i < arrayIndex; i++) {
        printf("data: %d, word: %s\n", nodes[i]->data, nodes[i]->word);
    }
}

int main() {
    struct node a = { .data = 3, .word = "ayy", .next = NULL };
    struct node b = { .data = 3, .word = "zzz", .next = &a };
    struct node c = { .data = 3, .word = "ddd", .next = &b };
    struct node d = { .data = 10, .word = "toaster", .next = &c };
    struct node e = { .data = 0, .word = "box", .next = &d };

    print_sorted(&e);
    return 0;
}

This prints out:

data: 0, word: box
data: 3, word: ayy
data: 3, word: ddd
data: 3, word: zzz
data: 10, word: toaster

If you want descending order, change the bottom part of node_compare() to the following:

if (first->data == second->data) {
    return strcmp(second->word, first->word);
} else {
    return second->data - first->data;
}


问:
mkdir: missing operand - ssh -tt ${REMOTE_SERVER} sudo sh -c "mkdir -p /opt/migration"
Given:

```<code>MIGRATION_FOLDER=/opt/migration
</code>```

Either this:

```<code>ssh -tt ${REMOTE_SERVER} sudo sh -c "mkdir -p /opt/migration"
</code>```

or this:

```<code>ssh -tt ${REMOTE_SERVER} sudo sh -c "mkdir -p '$MIGRATION_FOLDER'"
</code>```

returns:

mkdir: missing operand

Help appreciated.

答:
You need an extra level of quoting.

```<code>ssh -tt ${REMOTE_SERVER} sudo sh -c "'mkdir -p \"$MIGRATION_FOLDER\"'"
</code>```

or:

```<code>ssh -tt ${REMOTE_SERVER} "sudo sh -c 'mkdir -p \"$MIGRATION_FOLDER\"'"
</code>```

If you need to execute multiple commands, put them all inside the single quotes.

```<code>ssh -tt ${REMOTE_SERVER} "sudo sh -c 'rm -rf \"$MIGRATION_FOLDER\"; mkdir -p \"$MIGRATION_FOLDER\"'"
</code>```

Body:
Given:

MIGRATION_FOLDER=/opt/migration

Either this:

ssh -tt ${REMOTE_SERVER} sudo sh -c "mkdir -p /opt/migration"

or this:

ssh -tt ${REMOTE_SERVER} sudo sh -c "mkdir -p '$MIGRATION_FOLDER'"

returns:

mkdir: missing operand

Help appreciated.

Body:
You need an extra level of quoting.

ssh -tt ${REMOTE_SERVER} sudo sh -c "'mkdir -p \"$MIGRATION_FOLDER\"'"

or:

ssh -tt ${REMOTE_SERVER} "sudo sh -c 'mkdir -p \"$MIGRATION_FOLDER\"'"

If you need to execute multiple commands, put them all inside the single quotes.

ssh -tt ${REMOTE_SERVER} "sudo sh -c 'rm -rf \"$MIGRATION_FOLDER\"; mkdir -p \"$MIGRATION_FOLDER\"'"


问:
switch line class in clojurescript with if boolean variable
how can I switch the li class in a list with clojurescript, when the @switchvar is true all odd lines should be active, in the other case the even lines should be active

I tried an if statement, nothing happens.

```<code>(defn listitems [items]
  [:ul
   (for [item items]
     ^{:key item} [:li {:class
        (if (@switchvar true)
            ((odd? item) "active")
            ((even? item) "active") )
      } "Item " item ])])
</code>```

答:
You are calling the function that is within the switchvar atom, and giving it true as a parameter. Better to just deref (@) it:

```<code>(defn listitems [items]
  [:ul
   (for [item items
         idx (range (count items))]
     ^{:key item} [:li {:class
                        (if (and (odd? idx) (odd? @switchvar))
                          "active"
                          "inactive")
                        } "Item " item])])
</code>```

I made a change so that there's an idx that will vary with each list item. So both @switchvar and idx can change. I hope you can alter this code to suit your exact needs.

Body:
how can I switch the li class in a list with clojurescript, when the @switchvar is true all odd lines should be active, in the other case the even lines should be active

I tried an if statement, nothing happens.

(defn listitems [items]
  [:ul
   (for [item items]
     ^{:key item} [:li {:class
        (if (@switchvar true)
            ((odd? item) "active")
            ((even? item) "active") )
      } "Item " item ])])

Body:
You are calling the function that is within the switchvar atom, and giving it true as a parameter. Better to just deref (@) it:

(defn listitems [items]
  [:ul
   (for [item items
         idx (range (count items))]
     ^{:key item} [:li {:class
                        (if (and (odd? idx) (odd? @switchvar))
                          "active"
                          "inactive")
                        } "Item " item])])

I made a change so that there's an idx that will vary with each list item. So both @switchvar and idx can change. I hope you can alter this code to suit your exact needs.


问:
MVC project complaining it is unable to find Nhibernate.dll version 2.1.0.4000
In my MVC project, I am trying to use the latest Fluent Nhibernate, and NHibernate.linq.  I am using the Nhibernate.dll that came with the latest Fluent Nhibernate released build.  However, I have only been able to find NHibernate.linq 1.0.

When attempting to run I get the error:

```<code>Could not load file or assembly 'NHibernate, Version=2.1.0.4000, Culture=neutral,
PublicKeyToken=aa95f207798dfdb4' or one of its dependencies. The located assembly's
manifest definition does not match the assembly reference. (Exception from HRESULT:
0x80131040)
</code>```

I see at SourceForge in the NHibernate project, they have a NHibernate.Linq 2.1.2 version under the NHibernate 2.1.2 project, but if you download this zip, it is empty.

My thoughts is that Linq is referencing the older NHibernate.dll, but how can I get the NHibernate.linq.dll 2.1.2 version?

There is another question with this same error, and I tried all their suggestions with making sure that all the other NHibernate.dll's are included.  I didn't rebuild the NHibernate.linq project with the same NHibernate.dll that Fluent uses, since I was hoping to get a newer version of NHibernate.linq.

答:
Try adding the following XML into your Web/App.config file inside the <configuration> root tag.

```<code>   <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="NHibernate" publicKeyToken="AA95F207798DFDB4" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.1.1.4000" newVersion="2.1.2.4000" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In my MVC project, I am trying to use the latest Fluent Nhibernate, and NHibernate.linq.  I am using the Nhibernate.dll that came with the latest Fluent Nhibernate released build.  However, I have only been able to find NHibernate.linq 1.0.

When attempting to run I get the error:

Could not load file or assembly 'NHibernate, Version=2.1.0.4000, Culture=neutral,
PublicKeyToken=aa95f207798dfdb4' or one of its dependencies. The located assembly's
manifest definition does not match the assembly reference. (Exception from HRESULT:
0x80131040)

I see at SourceForge in the NHibernate project, they have a NHibernate.Linq 2.1.2 version under the NHibernate 2.1.2 project, but if you download this zip, it is empty.

My thoughts is that Linq is referencing the older NHibernate.dll, but how can I get the NHibernate.linq.dll 2.1.2 version?

There is another question with this same error, and I tried all their suggestions with making sure that all the other NHibernate.dll's are included.  I didn't rebuild the NHibernate.linq project with the same NHibernate.dll that Fluent uses, since I was hoping to get a newer version of NHibernate.linq.

Body:
Try adding the following XML into your Web/App.config file inside the <configuration> root tag.

   <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="NHibernate" publicKeyToken="AA95F207798DFDB4" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.1.1.4000" newVersion="2.1.2.4000" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>


问:
How can I make this codepen work with multiple pages?
I am using this page transition effect that I found on codepen for all of my buttons. It works fine for my contact button, but when I try to create other pages it doesnt work. So if I try to create a page for my "about" button it will not work and it will just use the same page from my contact page. So basically my question is how can I use this codepen to create multiple buttons with different content on each button.

Here is the codepen: https://codepen.io/fralec/pen/xZBKzO

and here is the buttons from my site

/* JS scripts are added see github repo for more
https://github.com/fralec/ElegantJS */

$('#contact').elegant({
    clickNextToClose: true,
    newTab: true,
    github: {
        id: ''
    },
    twitter: {
        id: ''
    },
    mail: {
        id: ''
    },
    steam: {
        id: ''
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: black;
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color:black;
}

#home {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 20%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#about {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 37%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#projects {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 54%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#contact {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 71%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#home:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

#about:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

#projects:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

#contact:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

@keyframes grain {
  0%, 100% { transform:translate(0, 0) }
  10% { transform:translate(-5%, -10%) }
  20% { transform:translate(-15%, 5%) }
  30% { transform:translate(7%, -25%) }
  40% { transform:translate(-5%, 25%) }
  50% { transform:translate(-15%, 10%) }
  60% { transform:translate(15%, 0%) }
  70% { transform:translate(0%, 15%) }
  80% { transform:translate(3%, 35%) }
  90% { transform:translate(-10%, 10%) }
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>
    <link rel='stylesheet prefetch' href='http://rawgit.com/fralec/elegantShareJS/master/css/elegant.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">

    <button id="home">Home</button>
    <button id="about">About</button>
    <button id="projects">Projects</button>
    <button id="contact">Contact</button>

```

答:
Copy the JS code from here: https://github.com/fralec/ElegantJS/blob/master/script/elegant.js
and use this new file as your script source for elegant.js instead of the rawgit url script source.

And then add your new buttons into the code following the same format like this:

facebook: {
    id: null,
    faIcon: "facebook",
    color: "#3b5998",
    url: "https://www.facebook.com/",
    target: null},

facebook - name of your new button

id - //If you need an id for this site put it here else keep null

faIcon - //put the Font Awesome icon you want for the button here

color - //This is the hover color

url - The url you want the button to take you to

Now in your js file, instead of this:

facebook: {
        id: ''
    }

do this

newButtonName: {
  id: ''
},
 otherNewButtonName: {
  id: ''
}

Now go and have fun hijacking someone else's code ;-)

Body:
I am using this page transition effect that I found on codepen for all of my buttons. It works fine for my contact button, but when I try to create other pages it doesnt work. So if I try to create a page for my "about" button it will not work and it will just use the same page from my contact page. So basically my question is how can I use this codepen to create multiple buttons with different content on each button.

Here is the codepen: https://codepen.io/fralec/pen/xZBKzO

and here is the buttons from my site

/* JS scripts are added see github repo for more
https://github.com/fralec/ElegantJS */

$('#contact').elegant({
    clickNextToClose: true,
    newTab: true,
    github: {
        id: ''
    },
    twitter: {
        id: ''
    },
    mail: {
        id: ''
    },
    steam: {
        id: ''
    }
});

body {
  background-color: black;
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color:black;
}

#home {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 20%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#about {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 37%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#projects {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 54%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#contact {
    position: absolute;
    width: 16%;
    background-color: transparent;
    border: 2px solid #FFF;
    margin-top: 12%;
    margin-left: 71%;
    height: 3em;
    color: #FFF;
    font-size: 1em;
    cursor: pointer;
    text-transform: uppercase;
    border-radius: 4px;
    animation: fadein 2s;
    -moz-animation: fadein 2s; /* Firefox */
    -webkit-animation: fadein 2s; /* Safari and Chrome */
}

#home:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

#about:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

#projects:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

#contact:hover {
    color: #1dd2e2;
    border: 3px solid #18bdef;
    font-weight: bold;
}

@keyframes grain {
  0%, 100% { transform:translate(0, 0) }
  10% { transform:translate(-5%, -10%) }
  20% { transform:translate(-15%, 5%) }
  30% { transform:translate(7%, -25%) }
  40% { transform:translate(-5%, 25%) }
  50% { transform:translate(-15%, 10%) }
  60% { transform:translate(15%, 0%) }
  70% { transform:translate(0%, 15%) }
  80% { transform:translate(3%, 35%) }
  90% { transform:translate(-10%, 10%) }
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>
    <link rel='stylesheet prefetch' href='http://rawgit.com/fralec/elegantShareJS/master/css/elegant.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">

    <button id="home">Home</button>
    <button id="about">About</button>
    <button id="projects">Projects</button>
    <button id="contact">Contact</button>


问:
unique_together does not work in Django shell
I have below model:

```<code>class Property(models.Model):
    job = models.ForeignKey(Job, on_delete=models.CASCADE)
    app = models.ForeignKey(App, on_delete=models.CASCADE)
    name = models.CharField(max_length=120)
    value = models.CharField(max_length=350, blank=True)
    description = models.TextField(blank=True)
    pub_date = models.DateTimeField('date_published', default=timezone.now)

    class Meta:
        verbose_name_plural = "properties"
        unique_together = (('value', 'name'),)

    def __str__(self):
        return self.name
</code>```

When I try to create a Property object in admin page (I'm using Django Suit) with name/value which are already exist I get the exception: "Property with this Value and Name already exists." So it works perfect.

But in manage.py shell:

```<code>>>>from myapp.models import App, Property, Job
>>>from django.shortcuts import get_object_or_404
>>>app = get_object_or_404(App, app_name='BLABLA')
>>>job = get_object_or_404(Job, job_name='BLABLA2')
>>> Property.objects.create(job=job, app=app, name='1', value='1')
<Property: 1>
>>> Property.objects.create(job=job, app=app, name='1', value='1')
<Property: 1>
</code>```

In this case I do not get any exceptions and objects are added in database.

I tried makemigrations, migrate and migrate --run-syncdb.
Django 1.9.12, sqlite3

答:
The unique constraints are enforced at database level. You're not getting any error probably because SQLite doesn't support this type of constraint. You cannot add constraint to existing table in SQLite. If you're in early development stage, drop the table and recreate it with updated constraints. Then it should work fine in shell.

Check SQLite alter table docs for allowed updates on an existing table.

The admin form throws error because it checks uniqueness by itself without relying on database constraints.

Body:
I have below model:

class Property(models.Model):
    job = models.ForeignKey(Job, on_delete=models.CASCADE)
    app = models.ForeignKey(App, on_delete=models.CASCADE)
    name = models.CharField(max_length=120)
    value = models.CharField(max_length=350, blank=True)
    description = models.TextField(blank=True)
    pub_date = models.DateTimeField('date_published', default=timezone.now)

    class Meta:
        verbose_name_plural = "properties"
        unique_together = (('value', 'name'),)

    def __str__(self):
        return self.name

When I try to create a Property object in admin page (I'm using Django Suit) with name/value which are already exist I get the exception: "Property with this Value and Name already exists." So it works perfect.

But in manage.py shell:

>>>from myapp.models import App, Property, Job
>>>from django.shortcuts import get_object_or_404
>>>app = get_object_or_404(App, app_name='BLABLA')
>>>job = get_object_or_404(Job, job_name='BLABLA2')
>>> Property.objects.create(job=job, app=app, name='1', value='1')
<Property: 1>
>>> Property.objects.create(job=job, app=app, name='1', value='1')
<Property: 1>

In this case I do not get any exceptions and objects are added in database.

I tried makemigrations, migrate and migrate --run-syncdb.
Django 1.9.12, sqlite3


问:
python command line syntax error
I tried running a simple python file from the command line. I created a python file called script0.py with the following content

```<code> print 2**2
</code>```

I get a syntax error.

```<code>>>> python script0.py
  File "<stdin>", line 1
    python script0.py
                 ^
SyntaxError: invalid syntax
>>>
</code>```

What is that? My first try with python has been really bad and the book of Mark Lutz is not helping. I use Python 2.7.

Thanks

答:
You are running that code from inside the python interpreter. If your terminal is showing a leading >>> it means your inside python already, in there you can either type print 2**2 directly, or exit and call python script0.py

My guess is that you inadvertently entered the python interpreter and thought you were still at the command prompt. Type exit() and try again.

Title: python command line syntax error

Body:
I tried running a simple python file from the command line. I created a python file called script0.py with the following content

 print 2**2

I get a syntax error.

>>> python script0.py
  File "<stdin>", line 1
    python script0.py
                 ^
SyntaxError: invalid syntax
>>>

What is that? My first try with python has been really bad and the book of Mark Lutz is not helping. I use Python 2.7.

Thanks


问:
Why is this GoLang solution faster then the equivalent Java Solution?
Recently at work we were playing around with the following quiz question asked by IBM https://www.research.ibm.com/haifa/ponderthis/challenges/May2015.html

After a bit of effort a colleague and I have arrived at two solutions, one in GoLang https://gist.github.com/walesey/e2427c28a859c4f7bc920c9af2858492#file-main-go-L57 and the other in Java https://gist.github.com/boyter/42df7f203c0932e37980f7974c017ec5#file-puzzle-java-L63 with the performance critical method for both being playGames in Java and game in GoLang (both linked in above).

The Go program is almost a literal copy of the Java one, and yet its runtime is ~6 seconds whereas the Java one is about ~26 seconds (on my local machine). Similar numbers were replicated on a few other machines with the Go program being about ~5x faster.

The Go program is compiled using 1.7.5 and Java using version 1.8.0_65 both running on macOS Sierra 10.12.3 on a late 2013 retina Macbook Pro with 2.6GHz i5 CPU.

Why is it that the Go program is 5x faster then the Java one when most benchmarks indicate that Java should about the same runtime? It is just basic math in a loop so it seems that they should run about the same time. I could understand a second or so for the JVM start time, but this seems off.

Both programs use pretty much the same loop. All of the possible permutations of game results are created and iterated over for each starting amount of money. It just seems that for any number of looping operations in the main loop that Go is running rings around Java.

I understand that this is a "micro" benchmark, but I am wondering why exactly the Go code is massively outperforming the Java code. Is it just that Go for simple loops/math is more efficient and hence faster? Is it able to unroll the loop perhaps (although this seems unlikely to produce such a massive difference)?

If not how should you structure a Java program to get the most performance out of a simple loop and math operation?

EDIT - Thanks to Dolda2000 I have modified the Java version. It is now about the same speed as the GoLang version. Indeed the issue was the the games were created causing the Java version to have to simulate more games to determine if the game went long enough. With the changes it is running in about ~6 seconds now and has restored my faith in Java.

Update - Here is an expanded essay which discusses the background of this question in further detail.

答:
As it turns out, your programs aren't as equal as you believe them to be. I instrumented them to see how many games (that is, individual betting rounds) they simulated, and while the Go version simulated 1 612 629 805 games, the Java version simulated 12 323 903 502 games, almost an order of magnitude more.

On my machine, turning off multithreading for more predictable results, the Java program clocked in on around 75 seconds, and the Go program on 12.5 seconds. Matching that against the total runtime, it appears that the Java program is actually slightly faster per simulated game, at about 6.1 ns, as compared to 7.8 ns for the Go program.

Not sure yet why they simulate such vastly different numbers of games, though. Perhaps the way the Go version generates the rounds simply happens to find a lot more quicker terminations.

EDIT: Actually, that last guess makes a lot of sense. The Go version starts off by modulating the initial rounds of a game, while the Java version starts off by modulating the last rounds of a game (in other words, looking at the list of rounds as a list of increasing 11-digit base-3 numbers, the Go version is little-endian, while the Java version is big-endian, so to speak), so the Java version will have to simulate through a lot more identical starts to get to the variations that terminate. I haven't tried to verify this hypothesis, but I'm sure enough about it that I don't feel the need to.


问:
How can i do this query by linq ,extensions methods or pure sql?
I have a table below

```<code> first      second
-------     ----------
100        0
200        0
0           400
</code>```

I want to get below result

```<code> first      second      result
-------     ---------- ----------
100        0            100
200        0            300
0           400         -100
</code>```

As you can see that result parameter is sum of previous (first-sum)
How can i write such a query ?

答:
```<code>public class DataItem
{
    public int First { get; set; }
    public int Second { get; set; }
}

public static void Main(string[] args)
{
    List<DataItem> data = new List<DataItem>
        {
            new DataItem { First = 100, Second = 0 },
            new DataItem { First = 200, Second = 0 },
            new DataItem { First = 0, Second = 400 }
        };

    var result = data.Select((item, index) => new
        {
            First = item.First,
            Second = item.Second,
            Result = data.Take(index + 1).Sum(x => x.First - x.Second)
        });
}
</code>```

Body:
I have a table below

 first      second
-------     ----------
100        0
200        0
0           400

I want to get below result

 first      second      result
-------     ---------- ----------
100        0            100
200        0            300
0           400         -100

As you can see that result parameter is sum of previous (first-sum)
How can i write such a query ?


问:
Binary Operator '==' can not be applied to operands of type 'Int8' and 'Int'
since i converted the code to Swift 3 i get this error:

```<code>Binary Operator '==' can not be applied to operands of type 'Int8' and 'Int'
</code>```

In Swift 2 it worked with this:

```<code>    var flags : UInt8
    var count : Int = 1
    var zw = [UInt8](repeating: 0, count: 2)

    let countTotal = data.count / MemoryLayout<UInt8>.size

    var bytes = [UInt8](repeating: 0, count: countTotal)

    data.copyBytes(to: &bytes, count: countTotal*MemoryLayout<UInt8>.size)

    flags = bytes[0]
    if([0x01 & flags] == [0 & 0x01]) // **<--ERROR**
    {
        zw[0] = bytes[count]
        zw[1] = bytes[count + 1
        let bpsys = UnsafePointer(zw).withMemoryRebound(to: UInt16.self, capacity: 1)
        {
            $0.pointee
        }
</code>```

答:
You used the wrong bracket ([ instead of () to begin with. But it looks like Swift 3 changed the type inference system in a subtle way that broke your program. Try this:

```<code>if (0x01 & flags) == (0 & 0x01) {

}
</code>```

Last question is why? 0 & 0x01 always return 0. You may as well write:

```<code>if 0x01 & flag == 0 {

}
</code>```

Body:
since i converted the code to Swift 3 i get this error:

Binary Operator '==' can not be applied to operands of type 'Int8' and 'Int'

In Swift 2 it worked with this:

    var flags : UInt8
    var count : Int = 1
    var zw = [UInt8](repeating: 0, count: 2)

    let countTotal = data.count / MemoryLayout<UInt8>.size

    var bytes = [UInt8](repeating: 0, count: countTotal)

    data.copyBytes(to: &bytes, count: countTotal*MemoryLayout<UInt8>.size)

    flags = bytes[0]
    if([0x01 & flags] == [0 & 0x01]) // **<--ERROR**
    {
        zw[0] = bytes[count]
        zw[1] = bytes[count + 1
        let bpsys = UnsafePointer(zw).withMemoryRebound(to: UInt16.self, capacity: 1)
        {
            $0.pointee
        }

Body:
You used the wrong bracket ([ instead of () to begin with. But it looks like Swift 3 changed the type inference system in a subtle way that broke your program. Try this:

if (0x01 & flags) == (0 & 0x01) {

}

Last question is why? 0 & 0x01 always return 0. You may as well write:

if 0x01 & flag == 0 {

}


问:
Bcrypt salt treating byte object as string and wont hash password
Answered

I have a Flask web app with a Postgres DB. I'm trying to implement database
salting with bcrypt, but it seems as though my byte representation is being viewed as a string. To be clear: I'm creating the hashed password with no problem, but when authorizing a login attempt, generating the comparison hash with the passed salt isn't working. Here's the error stack that occurs when I attempt to login:

```<code>lost/app/views/login.py", line 37, in login
authorized = helpers.authorize(username, password)

lost/app/helpers.py", line 108, in authorize
return _check_hash_for_user(username, password)

lost/app/helpers.py", line 93, in _check_hash_for_user
generated_hash = _recreate_hash(password, _get_salt_for_user(username))

lost/app/helpers.py", line 100, in _recreate_hash
hash_pass = bcrypt.hashpw(password.encode('utf-8'), salt)

lost/venv/lib/python3.6/site-packages/bcrypt/__init__.py", line 62, in hashpw
raise TypeError("Unicode-objects must be encoded before hashing")
</code>```

How my users table is created:

```<code>CREATE TABLE users (
    user_pk     SERIAL PRIMARY KEY,
    username    VARCHAR(16) UNIQUE NOT NULL,
    salt        VARCHAR(72) NOT NULL,
    password    VARCHAR(256) NOT NULL
</code>```

Relevant aspects of my login view

```<code>username = request.form.get('username', None)
password = request.form.get('password', None)

# If user exists...
authorized = helpers.authorize(username, password)

if authorized:
    # login...
</code>```

Here's how I created the user's password and salt

```<code>salt = bcrypt.gensalt(12)
password = bcrypt.hashpw(password.encode('utf-8'), salt)
</code>```

The auth aspect of helpers.py

```<code>def _get_hash_for_user(username):
    password = db_query("SELECT password FROM users WHERE username=%s;", [username])[0][0]
    return password

def _get_salt_for_user(username):
    salt = db_query("SELECT salt FROM users WHERE username=%s;", [username])[0][0]
    return salt

def _create_password_hash(password):
    salt = bcrypt.gensalt(16)
    hashed_pass = bcrypt.hashpw(password, salt)
    return hashed_pass, salt

def _check_hash_for_user(username, password):
    stored_hash = _get_hash_for_user(username)
    generated_hash = _recreate_hash(password, _get_salt_for_user(username))
    return stored_hash == generated_hash

def _recreate_hash(password, salt):
    hash_pass = bcrypt.hashpw(password.encode('utf-8'), salt)
    return hash_pass

def authorize(username, password):
    return _check_hash_for_user(username, password)
</code>```

edit:
At the behest of somebody trying to help me through this issue, I am now creating the users table with password and salt using BYTEA data type instead of VARCHAR() - other issues ensued, but I'll be working through them.

答:
OP answering his own question - thanks to everybody's help

It wasn't intelligent to store hashes as varchars in my database and continue flipping them within my code. Instead, I changed the users table to store the hashed password and the salt as BYTEA data types.

After that, I changed my password and salt getter functions (in auth.py) by casting the return type as byte()

so...

```<code>def _get_hash_for_user(username):
    password = byte(db_query("SELECT password FROM users WHERE username=%s;", [username])[0][0])
    return password

def _get_salt_for_user(username):
    salt = byte(db_query("SELECT salt FROM users WHERE username=%s;", [username])[0][0])
    return salt
</code>```

Body:
Answered

I have a Flask web app with a Postgres DB. I'm trying to implement database
salting with bcrypt, but it seems as though my byte representation is being viewed as a string. To be clear: I'm creating the hashed password with no problem, but when authorizing a login attempt, generating the comparison hash with the passed salt isn't working. Here's the error stack that occurs when I attempt to login:

lost/app/views/login.py", line 37, in login
authorized = helpers.authorize(username, password)

lost/app/helpers.py", line 108, in authorize
return _check_hash_for_user(username, password)

lost/app/helpers.py", line 93, in _check_hash_for_user
generated_hash = _recreate_hash(password, _get_salt_for_user(username))

lost/app/helpers.py", line 100, in _recreate_hash
hash_pass = bcrypt.hashpw(password.encode('utf-8'), salt)

lost/venv/lib/python3.6/site-packages/bcrypt/__init__.py", line 62, in hashpw
raise TypeError("Unicode-objects must be encoded before hashing")

How my users table is created:

CREATE TABLE users (
    user_pk     SERIAL PRIMARY KEY,
    username    VARCHAR(16) UNIQUE NOT NULL,
    salt        VARCHAR(72) NOT NULL,
    password    VARCHAR(256) NOT NULL

Relevant aspects of my login view

username = request.form.get('username', None)
password = request.form.get('password', None)

# If user exists...
authorized = helpers.authorize(username, password)

if authorized:
    # login...

Here's how I created the user's password and salt

salt = bcrypt.gensalt(12)
password = bcrypt.hashpw(password.encode('utf-8'), salt)

The auth aspect of helpers.py

def _get_hash_for_user(username):
    password = db_query("SELECT password FROM users WHERE username=%s;", [username])[0][0]
    return password

def _get_salt_for_user(username):
    salt = db_query("SELECT salt FROM users WHERE username=%s;", [username])[0][0]
    return salt

def _create_password_hash(password):
    salt = bcrypt.gensalt(16)
    hashed_pass = bcrypt.hashpw(password, salt)
    return hashed_pass, salt

def _check_hash_for_user(username, password):
    stored_hash = _get_hash_for_user(username)
    generated_hash = _recreate_hash(password, _get_salt_for_user(username))
    return stored_hash == generated_hash

def _recreate_hash(password, salt):
    hash_pass = bcrypt.hashpw(password.encode('utf-8'), salt)
    return hash_pass

def authorize(username, password):
    return _check_hash_for_user(username, password)

edit:
At the behest of somebody trying to help me through this issue, I am now creating the users table with password and salt using BYTEA data type instead of VARCHAR() - other issues ensued, but I'll be working through them.

Body:
OP answering his own question - thanks to everybody's help

It wasn't intelligent to store hashes as varchars in my database and continue flipping them within my code. Instead, I changed the users table to store the hashed password and the salt as BYTEA data types.

After that, I changed my password and salt getter functions (in auth.py) by casting the return type as byte()

so...

def _get_hash_for_user(username):
    password = byte(db_query("SELECT password FROM users WHERE username=%s;", [username])[0][0])
    return password

def _get_salt_for_user(username):
    salt = byte(db_query("SELECT salt FROM users WHERE username=%s;", [username])[0][0])
    return salt


问:
jQuery HTML Replace Dynamically Loaded Ajax Content After Second Load
After about 20 hours of compulsive searching I have managed to get text replace to start working after dynamic content is executed to apply on the dynamic content.

```<code>$("body").one("mouseover", "span.help-more", function(index) {
    $('li#li').each(function(index) {
        var $this = $(this);
        var t = $this.text();
        $this.html(t.replace("&lt", "<").replace("&gt", ">"));
    });
});
</code>```

However, once dynamic content is once again retrieved the second time or any time after that, the text is no longer replaced.

I tried to get around this (see example below) by removing "one" and changing it with "on", then copying the code to undo the events (reversing the t.replace) but that didn't work.

```<code>$("body").on("mouseover", "span.help-more", function(index) {
    $('li#li').each(function(index) {
        var $this = $(this);
        var t = $this.text();
        $this.html(t.replace("&lt", "<").replace("&gt", ">"));
    });
});

$("body").on("mouseout", "span.help-more", function(index) {
    $('li#li').each(function(index) {
        var $this = $(this);
        var t = $this.text();
        $this.html(t.replace("<", "&lt").replace(">", "&gt"));
    });
});
</code>```

Can someone please help me? I've given this about 20 hours so far. I would be happy with any solutions.

I should mention: I would just run it "on", but then somehow the HTML tags get stripped away upon second execution, that's why I tried to execute, undo.

I would be happy if either:
-(1) "one" is refired after every click
-(2) "on" if i can undo changes onmouseout
-(3) "on" and it stops stripping away tags on second run
..or any option you may suggest that is effective..

Your help would be immensely appreciated!

edit:in case this helps The Relevant HTML:

```<code>    <ul>
    <li class="stone-list ng-scope" id="stone_913"><span class="check-span"><span class="check-span-botton"></span></span> <span class="shape-span ng-binding">pear</span> <span class="carat-span ng-binding">0.5</span> <span class="cut-span ng-binding">excellent</span> <span class="colour-span ng-binding">G</span> <span class="clarity-span ng-binding">VS2</span> <span class="price-span" content="stone.price" dir=""><span class="ng-scope">$ 1412</span></span> <span class="help-span"><span class="help-more"><span class="information-help-more"><span class="top-help-more"></span> <span class="center-help-more"></span></span></span></span></li>
</ul>
<ul>
    <!-- ngRepeat: row in stone.tooltrip -->
    <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Shape pear</span></li><!-- end ngRepeat: row in stone.tooltrip -->
    <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Carat Weight 0.5</span></li><!-- end ngRepeat: row in stone.tooltrip -->
    <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Clarity VS2</span></li><!-- end ngRepeat: row in stone.tooltrip -->
    <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Color G</span></li><!-- end ngRepeat: row in stone.tooltrip -->
    <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Color Shade WH</span></li><!-- end ngRepeat: row in stone.tooltrip -->
    <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Cut excellent</span></li><!-- end ngRepeat: row in stone.tooltrip -->
    <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Polish VG</span></li><!-- end ngRepeat: row in stone.tooltrip -->
    <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Symmetry VG</span></li><!-- end ngRepeat: row in stone.tooltrip -->
    <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Fluoresence N</span></li><!-- end ngRepeat: row in stone.tooltrip -->
    <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Depth (%) 62.5</span></li><!-- end ngRepeat: row in stone.tooltrip -->
    <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Table (%) 61</span></li><!-- end ngRepeat: row in stone.tooltrip -->
    <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Certificate Type</span></li><!-- end ngRepeat: row in stone.tooltrip -->
    <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Number 6255152356</span></li><!-- end ngRepeat: row in stone.tooltrip -->
    <li class="ng-binding ng-scope" id="li"><span class="center-help-more"><a href="[link]" style="color:yellow">Video Link</a></span></li>
    <li style="list-style: none"><span class="center-help-more"><!-- end ngRepeat: row in stone.tooltrip --></span></li>
</ul><span class="bottom-help-more"></span> <span class="change-span"><span class="change-span-botton">Choose</span></span>
<ul></ul>
</code>```

It's some crappy html tag replace by WordPress that's causing me to find a workaround.

答:
Number of fixes to make. Here is a Working Example: https://jsfiddle.net/Twisty/3cp2kddm/

HTML

```<code><ul>
  <li class="stone-list ng-scope" id="stone_913">
    <span class="check-span">
    <span class="check-span-botton"></span>
    </span>
    <span class="shape-span ng-binding">pear</span>
    <span class="carat-span ng-binding">0.5</span>
    <span class="cut-span ng-binding">excellent</span>
    <span class="colour-span ng-binding">G</span>
    <span class="clarity-span ng-binding">VS2</span>
    <span class="price-span" content="stone.price" dir="">
    <span class="ng-scope">$ 1412</span>
    </span>
    <span class="help-span">
    <span class="help-more">
      <span class="information-help-more ui-icon ui-icon-info">
        <span class="top-help-more"></span>
    <span class="center-help-more"></span>
    </span>
    </span>
    </span>
  </li>
</ul>
<ul>
  <!-- ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Shape pear</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Carat Weight 0.5</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Clarity VS2</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Color G</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Color Shade WH</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Cut excellent</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Polish VG</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Symmetry VG</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Fluoresence N</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Depth (%) 62.5</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Table (%) 61</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Certificate Type</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Number 6255152356</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more"><a href="[link]" style="color:yellow">Video Link</a></span></li>
  <li style="list-style: none"><span class="center-help-more"><!-- end ngRepeat: row in stone.tooltrip --></span></li>
</ul><span class="bottom-help-more"></span> <span class="change-span"><span class="change-span-botton">Choose</span></span>
<ul></ul>
</code>```

JavaScript

```<code>$(function() {
  $(".stone-list").on("mousein mouseenter mouseleave mouseout", ".help-more", function(e) {
    $('.ng-binding').each(function(ind, el) {
      var $this = $(el);
      var t = $this.prop("innerHTML");
      console.log("HTML Content: ", t);
      if (e.type == "mouseleave") {
        t = t.replace(/</g, "<");
        t = t.replace(/>/g, ">");
      } else {
        t = t.replace(/</g, "<");
        t = t.replace(/>/g, ">");
      }
      console.log("HTML Converted: ", t.toString());
      $this.html(t);
    });
  });
});
</code>```

First, you have non-unique id attribute #li on almost all of your li elements. This defeats your .each() function. The id attribute should be unique. I would suggest

 where each id has a unique number.

Second, I assume your script has some object or image inside of  such that the user can mouse over it. I made use of jQuery UI to do this in my example. Since the event could be worded differently in different browsers, I suggest binding to a number of them. Then performing an action conditionally based on the event you are looking for. This can be done with:

```<code>$( selector ).on( "mouseenter mouseleave", handlerInOut );
</code>```

As you want to replace < or > with their HTML Entities, those being < and >, make sure you're using the right entities. Your replacement function did not work globally; hence, it only replaced the first occurrence. Switching to a regular expression with the global flag addresses this.

```<code>t = t.replace(/</g, "<");
t = t.replace(/>/g, ">");
</code>```

Calling .text() will only get you the actual text value and not the HTML value. Advise using .html() or .prop("innerHTML"). Both supply the same results.

Hope that helps.

Body:
After about 20 hours of compulsive searching I have managed to get text replace to start working after dynamic content is executed to apply on the dynamic content.

$("body").one("mouseover", "span.help-more", function(index) {
    $('li#li').each(function(index) {
        var $this = $(this);
        var t = $this.text();
        $this.html(t.replace("&lt", "<").replace("&gt", ">"));
    });
});

However, once dynamic content is once again retrieved the second time or any time after that, the text is no longer replaced.

I tried to get around this (see example below) by removing "one" and changing it with "on", then copying the code to undo the events (reversing the t.replace) but that didn't work.

$("body").on("mouseover", "span.help-more", function(index) {
    $('li#li').each(function(index) {
        var $this = $(this);
        var t = $this.text();
        $this.html(t.replace("&lt", "<").replace("&gt", ">"));
    });
});

$("body").on("mouseout", "span.help-more", function(index) {
    $('li#li').each(function(index) {
        var $this = $(this);
        var t = $this.text();
        $this.html(t.replace("<", "&lt").replace(">", "&gt"));
    });
});

Can someone please help me? I've given this about 20 hours so far. I would be happy with any solutions.

I should mention: I would just run it "on", but then somehow the HTML tags get stripped away upon second execution, that's why I tried to execute, undo.

I would be happy if either:
-(1) "one" is refired after every click
-(2) "on" if i can undo changes onmouseout
-(3) "on" and it stops stripping away tags on second run
..or any option you may suggest that is effective..

Your help would be immensely appreciated!

edit:in case this helps The Relevant HTML:

 pear 0.5 excellent G VS2 $ 1412

Shape pear

Carat Weight 0.5

Clarity VS2

Color G

Color Shade WH

Cut excellent

Polish VG

Symmetry VG

Fluoresence N

Depth (%) 62.5

Table (%) 61

Certificate Type

Number 6255152356

Video Link

 Choose

It's some crappy html tag replace by WordPress that's causing me to find a workaround.

Body:
Number of fixes to make. Here is a Working Example: https://jsfiddle.net/Twisty/3cp2kddm/

HTML

<ul>
  <li class="stone-list ng-scope" id="stone_913">
    <span class="check-span">
    <span class="check-span-botton"></span>
    </span>
    <span class="shape-span ng-binding">pear</span>
    <span class="carat-span ng-binding">0.5</span>
    <span class="cut-span ng-binding">excellent</span>
    <span class="colour-span ng-binding">G</span>
    <span class="clarity-span ng-binding">VS2</span>
    <span class="price-span" content="stone.price" dir="">
    <span class="ng-scope">$ 1412</span>
    </span>
    <span class="help-span">
    <span class="help-more">
      <span class="information-help-more ui-icon ui-icon-info">
        <span class="top-help-more"></span>
    <span class="center-help-more"></span>
    </span>
    </span>
    </span>
  </li>
</ul>
<ul>
  <!-- ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Shape pear</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Carat Weight 0.5</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Clarity VS2</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Color G</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Color Shade WH</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Cut excellent</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Polish VG</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Symmetry VG</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Fluoresence N</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Depth (%) 62.5</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Table (%) 61</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Certificate Type</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more">Number 6255152356</span></li>
  <!-- end ngRepeat: row in stone.tooltrip -->
  <li class="ng-binding ng-scope" id="li"><span class="center-help-more"><a href="[link]" style="color:yellow">Video Link</a></span></li>
  <li style="list-style: none"><span class="center-help-more"><!-- end ngRepeat: row in stone.tooltrip --></span></li>
</ul><span class="bottom-help-more"></span> <span class="change-span"><span class="change-span-botton">Choose</span></span>
<ul></ul>

JavaScript

$(function() {
  $(".stone-list").on("mousein mouseenter mouseleave mouseout", ".help-more", function(e) {
    $('.ng-binding').each(function(ind, el) {
      var $this = $(el);
      var t = $this.prop("innerHTML");
      console.log("HTML Content: ", t);
      if (e.type == "mouseleave") {
        t = t.replace(/&lt;/g, "<");
        t = t.replace(/&gt;/g, ">");
      } else {
        t = t.replace(/</g, "&lt;");
        t = t.replace(/>/g, "&gt;");
      }
      console.log("HTML Converted: ", t.toString());
      $this.html(t);
    });
  });
});

First, you have non-unique id attribute #li on almost all of your li elements. This defeats your .each() function. The id attribute should be unique. I would suggest <li id="li-1"></li> where each id has a unique number.

Second, I assume your script has some object or image inside of <span class="help-more"></span> such that the user can mouse over it. I made use of jQuery UI to do this in my example. Since the event could be worded differently in different browsers, I suggest binding to a number of them. Then performing an action conditionally based on the event you are looking for. This can be done with:

$( selector ).on( "mouseenter mouseleave", handlerInOut );

As you want to replace < or > with their HTML Entities, those being &lt; and &gt;, make sure you're using the right entities. Your replacement function did not work globally; hence, it only replaced the first occurrence. Switching to a regular expression with the global flag addresses this.

t = t.replace(/</g, "&lt;");
t = t.replace(/>/g, "&gt;");

Calling .text() will only get you the actual text value and not the HTML value. Advise using .html() or .prop("innerHTML"). Both supply the same results.

Hope that helps.


问:
Condition <xsl:output> in XSLT 1.0?
I have an XSLT 1.0 (2.0 is not an option) stylesheet which produces
XHTML. It can, depending on a parameter, produce a full XHTML
validable document or just a
...
 snippet, intended for
inclusion in a Web page.

My problem is to produce different XML declarations in these two
cases. For the standalone page, I need:

```<code><xsl:output doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"
       doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"/>
</code>```

And for the
 one:

```<code><xsl:output omit-xml-declaration="yes"/>
</code>```

But <xsl:output> cannot be included in an <xsl:if>. It can only be the direct child of <xsl:stylesheet>.

The only solution I see is to create a stylesheet with most of the templates and then two small "wrappers" with the right <xsl:output> and which will <xsl:import> the main stylesheet.

I was looking for a better idea but apparently there is none. Following advice from Andrew Hare and jelovirt, I wrote two "drivers", two simple stylesheets which call the proper <xsl:output> and then the main stylesheet. Here is one of these drivers, the one for standalone HTML:

```<code><?xml version="1.0" encoding="us-ascii"?>
<!-- This file is intended to be used as the main stylesheet, it creates a
 standalone Web page.
-->
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">

  <xsl:import href="traceroute2html.xsl"/>

  <xsl:param name="standalone" select="'true'"/>

  <xsl:output doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"
      doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"/>

</xsl:stylesheet>
</code>```

答:
Another option, which I recently had to employ, is to:

Omit the XML declaration in all cases.

Conditionally, output the declaration as unescaped text.

This only works in XSLT 1.0 and 2.0 if you're outputting to a file -- this won't work if you need to process the output as XML in the same pass, such as when storing in a variable.

(Note that XSLT 2.0 extension functions might make it possible to take this output and treat it as XML in one go, and XSLT 3.0 has a built-in function to parse an input string as XML.)

Example snippet:

```<code><!-- Omit the XML declaration as the base case:
    we can conditionally output a declaration
    as text, but we *cannot* apply conditions on
    this `omit-xml-declaration` attribute here.  -->
<xsl:output method="xml" indent="no"
    omit-xml-declaration="yes"
/>

<!-- Root element match: evaluate different cases, output XML declaration,
    XHTML DOCTYPE, or something else, then process the rest of the input. -->
<xsl:template match="/">
    <xsl:choose>
        <xsl:when test="'... some condition ...'">
            <xsl:text disable-output-escaping="yes"><?xml version="1.0" encoding="UTF-8"?></xsl:text>
        </xsl:when>
        <xsl:when test="'... some other condition ...'">
            <xsl:text disable-output-escaping="yes"><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"></xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <!-- ... some third kind of output ... -->
        </xsl:otherwise>
    </xsl:choose>
    <!-- Just process the rest -->
    <xsl:apply-templates/>
</xsl:template>

... [ other code ] ...
</code>```

OwnerDisplayName: bortzmeyer

Title: Condition <xsl:output> in XSLT 1.0?

Body:
I have an XSLT 1.0 (2.0 is not an option) stylesheet which produces
XHTML. It can, depending on a parameter, produce a full XHTML
validable document or just a
...
 snippet, intended for
inclusion in a Web page.

My problem is to produce different XML declarations in these two
cases. For the standalone page, I need:

<xsl:output doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"
       doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"/>

And for the
 one:

<xsl:output omit-xml-declaration="yes"/>

But <xsl:output> cannot be included in an <xsl:if>. It can only be the direct child of <xsl:stylesheet>.

The only solution I see is to create a stylesheet with most of the templates and then two small "wrappers" with the right <xsl:output> and which will <xsl:import> the main stylesheet.

I was looking for a better idea but apparently there is none. Following advice from Andrew Hare and jelovirt, I wrote two "drivers", two simple stylesheets which call the proper <xsl:output> and then the main stylesheet. Here is one of these drivers, the one for standalone HTML:

<?xml version="1.0" encoding="us-ascii"?>

<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">

  <xsl:import href="traceroute2html.xsl"/>

  <xsl:param name="standalone" select="'true'"/>

  <xsl:output doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"
      doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"/>

</xsl:stylesheet>

LastEditorDisplayName: bortzmeyer

Body:
Another option, which I recently had to employ, is to:

Omit the XML declaration in all cases.

Conditionally, output the declaration as unescaped text.

This only works in XSLT 1.0 and 2.0 if you're outputting to a file -- this won't work if you need to process the output as XML in the same pass, such as when storing in a variable.

(Note that XSLT 2.0 extension functions might make it possible to take this output and treat it as XML in one go, and XSLT 3.0 has a built-in function to parse an input string as XML.)

Example snippet:

<!-- Omit the XML declaration as the base case:
    we can conditionally output a declaration
    as text, but we *cannot* apply conditions on
    this `omit-xml-declaration` attribute here.  -->
<xsl:output method="xml" indent="no"
    omit-xml-declaration="yes"
/>

<!-- Root element match: evaluate different cases, output XML declaration,
    XHTML DOCTYPE, or something else, then process the rest of the input. -->
<xsl:template match="/">
    <xsl:choose>
        <xsl:when test="'... some condition ...'">
            <xsl:text disable-output-escaping="yes">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</xsl:text>
        </xsl:when>
        <xsl:when test="'... some other condition ...'">
            <xsl:text disable-output-escaping="yes">&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&quot;&gt;</xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <!-- ... some third kind of output ... -->
        </xsl:otherwise>
    </xsl:choose>
    <!-- Just process the rest -->
    <xsl:apply-templates/>
</xsl:template>

... [ other code ] ...


问:
Unique constraint between several columns derived from the same one to many relationship
I'm not sure if I titled this correctly or if it is even possible.

I have three columns that are populated from the same one to many relationship from another table.

For example:

```<code>User_Id | Security Question 1 | Security Question 2 | Security Question 3
</code>```

And a table of questions:

```<code>Id | Question
1  | Are you x?
2  | Are you y?
3  | Are you z?
</code>```

When a row is written into the first table it requires a security question from the second table. However, the possible choices are all the questions from the second table. I want to enforce a restriction that any user didn't pick any question twice.

How can I do this? Should this be relegated to my application code?

答:
If you normalize your table it is pretty straight-forward.

```<code>create table t (
  UserId int
, QuestionOrdinal tinyint
, QuestionId int
, constraint uc_UserId_QuestionOrdinal unique (UserId, QuestionOrdinal)
, constraint uc_UserId_QuestionId unique (UserId, QuestionId)
);
insert into t values (1,1,1),(1,2,2);
insert into t values (1,3,1) -- constraint violation
</code>```

rextester demo: http://rextester.com/FEHY66465

Body:
I'm not sure if I titled this correctly or if it is even possible.

I have three columns that are populated from the same one to many relationship from another table.

For example:

User_Id | Security Question 1 | Security Question 2 | Security Question 3

And a table of questions:

Id | Question
1  | Are you x?
2  | Are you y?
3  | Are you z?

When a row is written into the first table it requires a security question from the second table. However, the possible choices are all the questions from the second table. I want to enforce a restriction that any user didn't pick any question twice.

How can I do this? Should this be relegated to my application code?

Body:
If you normalize your table it is pretty straight-forward.

create table t (
  UserId int
, QuestionOrdinal tinyint
, QuestionId int
, constraint uc_UserId_QuestionOrdinal unique (UserId, QuestionOrdinal)
, constraint uc_UserId_QuestionId unique (UserId, QuestionId)
);
insert into t values (1,1,1),(1,2,2);
insert into t values (1,3,1) -- constraint violation

rextester demo: http://rextester.com/FEHY66465


问:
Modifying iterator inside for loop
I have a problem like this:
I got size of array and the array itself (all the elements) and i need to sort the array in the way that first item in array (lets call it key item) is placed so all items smaller then key item go left from key item and all items larger then key item go right form key item, but the items need to be i a same order as they was in declaration like so:
array input:

```<code>4 7 3 5 6 2 9 1 10 8
</code>```

array output:

```<code>3 2 1 4 7 5 6 9 10 8
</code>```

so i thought i can just go one time through array and if value is smaller then key item swap them and if value is larger then key item, place that value (item ) at the  end (if there is n items in array place it on n+1 place) and then to shift all items from current index one place to the left like:

```<code>| 4 | 7 | 3 | 5 | 6 | 2 | 9 | 1  | 10 | 8 |

| 4 |   | 3 | 5 | 6 | 2 | 9 | 1  | 10 | 8 | 7 |

| 4 | 3 | 5 | 6 | 2 | 9 | 1 | 10 | 8 | 7 |
</code>```

but like that i would need to after every shifting make iterator stay same (so it can check that place again.
I have a code like this :

```<code>int u=1;
for (int i=1;i<n;i++){
    if (x[i]<x[u]){
       swap(x[i],x[u]);
       u+=1;
    }else {
        x[i]=x[n];
        for (int k=i;k<n-1;k++){x[k]=x[k+1];}
        i--;
    }
}
</code>```

i think i made a mistake in the swapping part but i cant figure it out.

答:
What you are looking for can be done using the STL's std::stable_partition() algorithm:

divides elements into two groups while preserving their relative order

Let it do the hard work for you, eg:

```<code>#include <iostream>
#include <algorithm>

struct doPartitionOn
{
    int m_key;

    doPartitionOn(int key) : m_key(key) {}

    bool operator()(int a)
    {
        return (a < m_key);
    }
};

int main()
{
    int arr[] = {4, 7, 3, 5, 6, 2, 9, 1, 10, 8};

    for(int i = 0; i < 10; ++i)
        std::cout << arr[i] << ' ';
    std::cout << std::endl;

    std::stable_partition(arr, arr+10, doPartitionOn(arr[0]));

    for(int i = 0; i < 10; ++i)
        std::cout << arr[i] << ' ';
    std::cout << std::endl;

    std::cin.get();
    return 0;
}
</code>```

4 7 3 5 6 2 9 1 10 8

  3 2 1 4 7 5 6 9 10 8

Live demo

Or, if using C++11 or later, you can use a lambda instead of a manual functor:

```<code>#include <iostream>
#include <algorithm>

int main()
{
    int arr[] = {4, 7, 3, 5, 6, 2, 9, 1, 10, 8};

    for(int value: arr)
        std::cout << value << ' ';
    std::cout << std::endl;

    std::stable_partition(arr, arr+10, [&arr](int a){ return (a < arr[0]); });

    for(int value: arr)
        std::cout << value << ' ';
    std::cout << std::endl;

    std::cin.get();
    return 0;
}
</code>```

4 7 3 5 6 2 9 1 10 8

  3 2 1 4 7 5 6 9 10 8

Live demo

Title: Modifying iterator inside for loop

Body:
I have a problem like this:
I got size of array and the array itself (all the elements) and i need to sort the array in the way that first item in array (lets call it key item) is placed so all items smaller then key item go left from key item and all items larger then key item go right form key item, but the items need to be i a same order as they was in declaration like so:
array input:

4 7 3 5 6 2 9 1 10 8

array output:

3 2 1 4 7 5 6 9 10 8

so i thought i can just go one time through array and if value is smaller then key item swap them and if value is larger then key item, place that value (item ) at the  end (if there is n items in array place it on n+1 place) and then to shift all items from current index one place to the left like:

| 4 | 7 | 3 | 5 | 6 | 2 | 9 | 1  | 10 | 8 |

| 4 |   | 3 | 5 | 6 | 2 | 9 | 1  | 10 | 8 | 7 |

| 4 | 3 | 5 | 6 | 2 | 9 | 1 | 10 | 8 | 7 |

but like that i would need to after every shifting make iterator stay same (so it can check that place again.
I have a code like this :

int u=1;
for (int i=1;i<n;i++){
    if (x[i]<x[u]){
       swap(x[i],x[u]);
       u+=1;
    }else {
        x[i]=x[n];
        for (int k=i;k<n-1;k++){x[k]=x[k+1];}
        i--;
    }
}

i think i made a mistake in the swapping part but i cant figure it out.

Body:
What you are looking for can be done using the STL's std::stable_partition() algorithm:

divides elements into two groups while preserving their relative order

Let it do the hard work for you, eg:

#include <iostream>
#include <algorithm>

struct doPartitionOn
{
    int m_key;

    doPartitionOn(int key) : m_key(key) {}

    bool operator()(int a)
    {
        return (a < m_key);
    }
};

int main()
{
    int arr[] = {4, 7, 3, 5, 6, 2, 9, 1, 10, 8};

    for(int i = 0; i < 10; ++i)
        std::cout << arr[i] << ' ';
    std::cout << std::endl;

    std::stable_partition(arr, arr+10, doPartitionOn(arr[0]));

    for(int i = 0; i < 10; ++i)
        std::cout << arr[i] << ' ';
    std::cout << std::endl;

    std::cin.get();
    return 0;
}

4 7 3 5 6 2 9 1 10 8

  3 2 1 4 7 5 6 9 10 8

Live demo

Or, if using C++11 or later, you can use a lambda instead of a manual functor:

#include <iostream>
#include <algorithm>

int main()
{
    int arr[] = {4, 7, 3, 5, 6, 2, 9, 1, 10, 8};

    for(int value: arr)
        std::cout << value << ' ';
    std::cout << std::endl;

    std::stable_partition(arr, arr+10, [&arr](int a){ return (a < arr[0]); });

    for(int value: arr)
        std::cout << value << ' ';
    std::cout << std::endl;

    std::cin.get();
    return 0;
}

4 7 3 5 6 2 9 1 10 8

  3 2 1 4 7 5 6 9 10 8

Live demo


问:
System.Net.WebException not intercepted on Windows Phone 8
I am trying to call a web service using RestSharp (this has to be done for WP8 onwards).

This is my triggered method:

```<code> private async void postRest()
 {
     string getSyncService = "MyService";
     var client = new RestClient(ip);
     var request = new RestRequest(getSyncService, Method.POST);
     request.RequestFormat = DataFormat.Json;
     JsonObject jsonGenericRequest = new JsonObject();
     jsonGenericRequest.Add("companyid", "123");
     jsonGenericRequest.Add("token", "123");            ...
     request.AddParameter("GenMobileRequest", jsonGenericRequest);
     request.AddHeader("Access-Control-Allow-Methods", "POST");
     request.AddHeader("Content-Type", "application/json; charset=utf-8");
     request.AddHeader("Accept", "application/json");

     try
     {
         // easy async support
         client.ExecuteAsync(request, response =>
         {
             Console.WriteLine("response content: " + response.Content);
             if (response.ResponseStatus == ResponseStatus.Completed)
             {
                 MessageBox.Show("errorMsg: " + response.ErrorMessage);
             }
         });
     }
     catch (System.Net.WebException ex)
     {
         MessageBox.Show(" "  + ex.InnerException.ToString());
     }
 }
</code>```

On my log I am getting this exception:

An exception of type 'System.Net.WebException' occurred in
  System.Windows.ni.dll  and wasn't handled before a managed/native
  boundary

I cant even keep any information in my handler

```<code>// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
    Console.WriteLine(" ---Application_UnhandledException---");
    if (Debugger.IsAttached)
    {
        // An unhandled exception has occurred; break into the debugger
        Debugger.Break();
    }
}
</code>```

How can I get more info about what is wrong?

Any additional information on the proper way to call a WS would be appreciated.

Thanks

答:
source: https://blogs.msdn.microsoft.com/ptorr/2014/12/10/async-exceptions-in-c/

```<code>  using System;
  using System.Runtime.CompilerServices;
  using System.Threading;
  using System.Threading.Tasks;

  namespace AsyncAndExceptions
  {
class Program
{
  static void Main(string[] args)
  {
    AppDomain.CurrentDomain.UnhandledException += (s, e) => Log("*** Crash! ***", "UnhandledException");
    TaskScheduler.UnobservedTaskException += (s, e) => Log("*** Crash! ***", "UnobservedTaskException");

    RunTests();

    // Let async tasks complete...
    Thread.Sleep(500);
    GC.Collect(3, GCCollectionMode.Forced, true);
  }

  private static async Task RunTests()
  {
    try
    {
      // crash
      // _1_VoidNoWait();

      // crash
      // _2_AsyncVoidAwait();

      // OK
      // _3_AsyncVoidAwaitWithTry();

      // crash - no await
      // _4_TaskNoWait();

      // crash - no await
      // _5_TaskAwait();

      // OK
      // await _4_TaskNoWait();

      // OK
      // await _5_TaskAwait();
    }
    catch (Exception ex) { Log("Exception handled OK"); }

    // crash - no try
    // await _4_TaskNoWait();

    // crash - no try
    // await _5_TaskAwait();
  }

  // Unsafe
  static void _1_VoidNoWait()
  {
    ThrowAsync();
  }

  // Unsafe
  static async void _2_AsyncVoidAwait()
  {
    await ThrowAsync();
  }

  // Safe
  static async void _3_AsyncVoidAwaitWithTry()
  {
    try { await ThrowAsync(); }
    catch (Exception ex) { Log("Exception handled OK"); }
  }

  // Safe only if caller uses await (or Result) inside a try
  static Task _4_TaskNoWait()
  {
    return ThrowAsync();
  }

  // Safe only if caller uses await (or Result) inside a try
  static async Task _5_TaskAwait()
  {
    await ThrowAsync();
  }

  // Helper that sets an exception asnychronously
  static Task ThrowAsync()
  {
    TaskCompletionSource tcs = new TaskCompletionSource();
    ThreadPool.QueueUserWorkItem(_ => tcs.SetException(new Exception("ThrowAsync")));
    return tcs.Task;
  }
  internal static void Log(string message, [CallerMemberName] string caller = "")
  {
    Console.WriteLine("{0}: {1}", caller, message);
  }
}
</code>```

}

Body:
I am trying to call a web service using RestSharp (this has to be done for WP8 onwards).

This is my triggered method:

 private async void postRest()
 {
     string getSyncService = "MyService";
     var client = new RestClient(ip);
     var request = new RestRequest(getSyncService, Method.POST);
     request.RequestFormat = DataFormat.Json;
     JsonObject jsonGenericRequest = new JsonObject();
     jsonGenericRequest.Add("companyid", "123");
     jsonGenericRequest.Add("token", "123");            ...
     request.AddParameter("GenMobileRequest", jsonGenericRequest);
     request.AddHeader("Access-Control-Allow-Methods", "POST");
     request.AddHeader("Content-Type", "application/json; charset=utf-8");
     request.AddHeader("Accept", "application/json");

     try
     {
         // easy async support
         client.ExecuteAsync(request, response =>
         {
             Console.WriteLine("response content: " + response.Content);
             if (response.ResponseStatus == ResponseStatus.Completed)
             {
                 MessageBox.Show("errorMsg: " + response.ErrorMessage);
             }
         });
     }
     catch (System.Net.WebException ex)
     {
         MessageBox.Show(" "  + ex.InnerException.ToString());
     }
 }

On my log I am getting this exception:

An exception of type 'System.Net.WebException' occurred in
  System.Windows.ni.dll  and wasn't handled before a managed/native
  boundary

I cant even keep any information in my handler

// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
    Console.WriteLine(" ---Application_UnhandledException---");
    if (Debugger.IsAttached)
    {
        // An unhandled exception has occurred; break into the debugger
        Debugger.Break();
    }
}

How can I get more info about what is wrong?

Any additional information on the proper way to call a WS would be appreciated.

Thanks

Body:
source: https://blogs.msdn.microsoft.com/ptorr/2014/12/10/async-exceptions-in-c/

  using System;
  using System.Runtime.CompilerServices;
  using System.Threading;
  using System.Threading.Tasks;

  namespace AsyncAndExceptions
  {
class Program
{
  static void Main(string[] args)
  {
    AppDomain.CurrentDomain.UnhandledException += (s, e) => Log("*** Crash! ***", "UnhandledException");
    TaskScheduler.UnobservedTaskException += (s, e) => Log("*** Crash! ***", "UnobservedTaskException");

    RunTests();

    // Let async tasks complete...
    Thread.Sleep(500);
    GC.Collect(3, GCCollectionMode.Forced, true);
  }

  private static async Task RunTests()
  {
    try
    {
      // crash
      // _1_VoidNoWait();

      // crash
      // _2_AsyncVoidAwait();

      // OK
      // _3_AsyncVoidAwaitWithTry();

      // crash - no await
      // _4_TaskNoWait();

      // crash - no await
      // _5_TaskAwait();

      // OK
      // await _4_TaskNoWait();

      // OK
      // await _5_TaskAwait();
    }
    catch (Exception ex) { Log("Exception handled OK"); }

    // crash - no try
    // await _4_TaskNoWait();

    // crash - no try
    // await _5_TaskAwait();
  }

  // Unsafe
  static void _1_VoidNoWait()
  {
    ThrowAsync();
  }

  // Unsafe
  static async void _2_AsyncVoidAwait()
  {
    await ThrowAsync();
  }

  // Safe
  static async void _3_AsyncVoidAwaitWithTry()
  {
    try { await ThrowAsync(); }
    catch (Exception ex) { Log("Exception handled OK"); }
  }

  // Safe only if caller uses await (or Result) inside a try
  static Task _4_TaskNoWait()
  {
    return ThrowAsync();
  }

  // Safe only if caller uses await (or Result) inside a try
  static async Task _5_TaskAwait()
  {
    await ThrowAsync();
  }

  // Helper that sets an exception asnychronously
  static Task ThrowAsync()
  {
    TaskCompletionSource tcs = new TaskCompletionSource();
    ThreadPool.QueueUserWorkItem(_ => tcs.SetException(new Exception("ThrowAsync")));
    return tcs.Task;
  }
  internal static void Log(string message, [CallerMemberName] string caller = "")
  {
    Console.WriteLine("{0}: {1}", caller, message);
  }
}

}