问:
Append multiple elements and use classes in JQuery append method
I use the jquery method append to create new divs under each other by clicking a button.

But it allows me to append only one div, so it does not look like i wanted it in this example (with a close symbol) to hide the div by clicking. Is this possible?

It would mean to append another span tag:

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_alert

src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"

 $(document).ready(function () {
      $("#btn1").click(function () {
        $("#alerts").append("
New Message from Whatsapp!
");
      });
    });

    ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  #alerts>div {
    padding: 1rem 2rem;
    font-weight: bold;
    color: white;
    background: #ECECEC;
    margin-bottom: 0.5rem;
    opacity: 0.7;
    border-radius: 15px;

  }</code>```

<button id="btn1" >Whatsapp</button>

```
</div>
</div>
</p>

<p>This is the error i get when i try to put the span tag inside the div, it seems to be a syntax error:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>        $("#alerts").append(" <div> <span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>New Message from Whatsapp!</div>");</code>```

```

答:
Your code has syntax errors because you have a variety of quotes within a quoted string.  Since the string contains both single-quotes and double-quotes, you can't just pick one or the other.  So instead, pick one of them to "escape".  For example, here the string is still enclosed in double-quotes and then internally escapes its double-quote characters:

$("#alerts").append("
×New Message from Whatsapp!
");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="alerts"></div></code>```

As an alternative, you can use a more structured syntax to build your elements with jQuery.  Something like this:

let span = $('', { class: 'closebtn' }).html('×');
$('#alerts').append($('
')
    .text('New Message from Whatsapp!')
    .prepend(span));
$(span).on('click', function () {
    this.parentElement.style.display='none';
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="alerts"></div></code>```

It appears much more verbose, so I suppose it's a matter of personal preference which approach you use.  But the benefit of this latter approach is that you break apart everything into individual operations, each doing its one thing in a simple and supportable manner, without in-line JavaScript in your markup or quoting issues or any of that.

Body:
I use the jquery method append to create new divs under each other by clicking a button.

But it allows me to append only one div, so it does not look like i wanted it in this example (with a close symbol) to hide the div by clicking. Is this possible?

It would mean to append another span tag:

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_alert

src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"

 $(document).ready(function () {
      $("#btn1").click(function () {
        $("#alerts").append("
New Message from Whatsapp!
");
      });
    });

  #alerts>div {
    padding: 1rem 2rem;
    font-weight: bold;
    color: white;
    background: #ECECEC;
    margin-bottom: 0.5rem;
    opacity: 0.7;
    border-radius: 15px;

  }

<button id="btn1" >Whatsapp</button>

This is the error i get when i try to put the span tag inside the div, it seems to be a syntax error:

        $("#alerts").append("
 ×New Message from Whatsapp!
");

Body:
Your code has syntax errors because you have a variety of quotes within a quoted string.  Since the string contains both single-quotes and double-quotes, you can't just pick one or the other.  So instead, pick one of them to "escape".  For example, here the string is still enclosed in double-quotes and then internally escapes its double-quote characters:

$("#alerts").append("<div><span class=\"closebtn\" onclick=\"this.parentElement.style.display='none';\">&times;</span>New Message from Whatsapp!</div>");

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="alerts"></div>

As an alternative, you can use a more structured syntax to build your elements with jQuery.  Something like this:

let span = $('<span/>', { class: 'closebtn' }).html('&times;');
$('#alerts').append($('<div/>')
    .text('New Message from Whatsapp!')
    .prepend(span));
$(span).on('click', function () {
    this.parentElement.style.display='none';
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="alerts"></div>

It appears much more verbose, so I suppose it's a matter of personal preference which approach you use.  But the benefit of this latter approach is that you break apart everything into individual operations, each doing its one thing in a simple and supportable manner, without in-line JavaScript in your markup or quoting issues or any of that.


来源: stackexchange

问:
Making a external POST is not working in my Vue code
I have a problem and I've been trying to fix it many days and I can't solve it. I just want to send a hint to Google Analytics when I click one button (to do it, I have to make a request (POST).
This is my code, I have deleted the ID that I have in GA, just to show you the original code:

```<code>import Vue from 'vue'
import VueResource from 'vue-resource'
Vue.use(VueResource)

handleMP () {
this.$http.post('www.google-analytics.comv=1&t=pageview&tid=UA-XXXXXX-
X&cid=555&dp=%2Fanalytics')
}
</code>```

The problem is that I don't know why, when I make the POST, the URL I use it is added to http::/localhost:8080/ and I can't make the POST.
Example URL I can see in the console:
http://localhost:8080/www.google-analytics.com?v=1&t=pageview&tid=UA-XXXXXXX-X&cid=555&dp=%2Fanalytics

How can I fix this?
Thanks in advance

答:
I'm pretty sure you're missing a http:// or https:// prefix in the URL, so Vue thinks it's just a relative URL and appends what you entered to the current address.

Try adding the https://, so it looks like this:

```<code>handleMP () {
this.$http.post('https://www.google-analytics.comv=1&t=pageview&tid=UA-XXXXXX-
X&cid=555&dp=%2Fanalytics')
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a problem and I've been trying to fix it many days and I can't solve it. I just want to send a hint to Google Analytics when I click one button (to do it, I have to make a request (POST).
This is my code, I have deleted the ID that I have in GA, just to show you the original code:

import Vue from 'vue'
import VueResource from 'vue-resource'
Vue.use(VueResource)

handleMP () {
this.$http.post('www.google-analytics.comv=1&t=pageview&tid=UA-XXXXXX-
X&cid=555&dp=%2Fanalytics')
}

The problem is that I don't know why, when I make the POST, the URL I use it is added to http::/localhost:8080/ and I can't make the POST.
Example URL I can see in the console:
http://localhost:8080/www.google-analytics.com?v=1&t=pageview&tid=UA-XXXXXXX-X&cid=555&dp=%2Fanalytics

How can I fix this?
Thanks in advance

Body:
I'm pretty sure you're missing a http:// or https:// prefix in the URL, so Vue thinks it's just a relative URL and appends what you entered to the current address.

Try adding the https://, so it looks like this:

handleMP () {
this.$http.post('https://www.google-analytics.comv=1&t=pageview&tid=UA-XXXXXX-
X&cid=555&dp=%2Fanalytics')
}


问:
Issue with merge sort Algorithm
MergeSorting algorithm not working. Keep getting an IndexOutOFBoundsError. I believe the issue may be because there isn't a sentinel. I need to create a loop when the leftarray and rightarray is copying itself to k, one of the arrays runs out of numbers, which causes an error. I need some assistance creating this sentinel.

private static <T> void mergeSort(Comparable<? extends T>[] items, int begIndx, int endIndx) {
    if (items.length > 1) {
        int midIndx = items.length / 2;
        @SuppressWarnings("unchecked")
        T[] left = (T[]) new Object[midIndx];
        @SuppressWarnings("unchecked")
        T[] right = (T[]) new Object[items.length - midIndx];

        for (int i = 0; i < midIndx; i++) {
            left[i] = (T) items[i];
        }
        for (int i = midIndx; i < items.length; i++) {
            right[i] = (T) items[i];
        }

        mergeSort(items, begIndx, midIndx);
        mergeSort(items, midIndx + 1, endIndx);
        merge(items, begIndx, midIndx, endIndx);
    }
}

@SuppressWarnings("unchecked")
private static <T> void merge(Comparable<? extends T>[] array,
                              int begIndx, int midIndx, int endIndx) {
    int sizeOfLeft = midIndx - begIndx + 1;
    int sizeOfRight = endIndx - midIndx;

    /// change to generic later
    @SuppressWarnings("unchecked")
    T[] leftArr = (T[]) new Object[sizeOfLeft + 1];
    @SuppressWarnings("unchecked")
    T[] rightArr = (T[]) new Object[sizeOfRight + 1];

    for (int i = 0; i < sizeOfLeft; i++) {
        leftArr[i] = (T) array[begIndx + i];
    }
    for (int j = 0; j < sizeOfRight; j++) {
        rightArr[j] = (T) array[midIndx + j + 1];
    }

    int i = 0;
    int j = 0;

    // changed to less than or equal to rather than "less than"
    // this is because this is a zero based index system
    // and because endeIndex is not a length but an index,
    // you need to populate it.
    for (int k = begIndx; k <= endIndx; k++) {
        // use comparable here
        if (((Integer) leftArr[i]).compareTo((Integer) rightArr[j]) <= 0) {
            array[k] = (Comparable<? extends T>) leftArr[i];
            i = i + 1;
        } else if (((Integer) leftArr[i]).compareTo((Integer) rightArr[j]) >= 0) {
            /// just replaces it so don't use comparable
            array[k] = (Comparable<? extends T>) rightArr[j];
            j = j + 1;
        } else if ((Integer) leftArr[sizeOfLeft] == null) {
            array[k] =  (Comparable<? extends T>) rightArr[j];
            j = j + 1;
        } else if ((Integer) rightArr[sizeOfRight] == null) {
            array[k] = (Comparable<? extends T>) leftArr[i];
            i = i + 1;
        }
    }
}
```

I created an integer array arr = new Integer[5]. So those 5 numbers should be sorted.

答:
There are multiple problems in your code:

it is unclear if the index endIndx is included or excluded. The code is much simpler if the endIndx is excluded, and the initial call to sort the array is simply: mergesort(arr, 0, arr.length);

the initial test in mergesort is incorrect: instead of testing the array length, you should test if the slice has more than 1 element:

```<code>if (endIndx - begIndx > 1)
</code>```

the arrays left and right are unused in mergesort.

allocating an extra element in the arrays left and right in merge is not required, it is much simpler to compare the array index values against the lengths of the subarrays. This sentinel approach is confusing and should not be used.

Here is a simplified version:

private static <T> void mergeSort(Comparable<? extends T>[] items, int begIndx, int endIndx) {
    if (endIndx - begIndx > 1) {
        int midIndx = items.length / 2;
        mergeSort(items, begIndx, midIndx);
        mergeSort(items, midIndx, endIndx);
        merge(items, begIndx, midIndx, endIndx);
    }
}

@SuppressWarnings("unchecked")
private static <T> void merge(Comparable<? extends T>[] array,
                              int begIndx, int midIndx, int endIndx) {
    int sizeOfLeft = midIndx - begIndx;
    int sizeOfRight = endIndx - midIndx;

    /// change to generic later
    @SuppressWarnings("unchecked")
    T[] leftArr = (T[]) new Object[sizeOfLeft];
    @SuppressWarnings("unchecked")
    T[] rightArr = (T[]) new Object[sizeOfRight];

    for (int i = 0; i < sizeOfLeft; i++) {
        leftArr[i] = (T)array[begIndx + i];
    }
    for (int j = 0; j < sizeOfRight; j++) {
        rightArr[j] = (T)array[midIndx + j];
    }

    int i = 0;
    int j = 0;
    int k = begIndx;

    while (i < sizeOfLeft && j < sizeOfRight) {
        /// use comparable to compare actual values
        if ((Integer)leftArr[i]).compareTo((Integer)rightArr[j]) <= 0) {
            array[k] = (Comparable<? extends T>)leftArr[i];
            i++;
            k++;
        } else {
            array[k] = (Comparable<? extends T>)rightArr[j];
            j++;
            k++;
        }
    }
    while (i < sizeOfLeft) {
        array[k] = (Comparable<? extends T>)leftArr[i];
        i++;
        k++;
    }
    while (j < sizeOfRight) {
        array[k] = (Comparable<? extends T>)rightArr[j];
        j++;
        k++;
    }
}
```

Title: Issue with merge sort Algorithm

Body:
MergeSorting algorithm not working. Keep getting an IndexOutOFBoundsError. I believe the issue may be because there isn't a sentinel. I need to create a loop when the leftarray and rightarray is copying itself to k, one of the arrays runs out of numbers, which causes an error. I need some assistance creating this sentinel.

private static <T> void mergeSort(Comparable<? extends T>[] items, int begIndx, int endIndx) {
    if (items.length > 1) {
        int midIndx = items.length / 2;
        @SuppressWarnings("unchecked")
        T[] left = (T[]) new Object[midIndx];
        @SuppressWarnings("unchecked")
        T[] right = (T[]) new Object[items.length - midIndx];

        for (int i = 0; i < midIndx; i++) {
            left[i] = (T) items[i];
        }
        for (int i = midIndx; i < items.length; i++) {
            right[i] = (T) items[i];
        }

        mergeSort(items, begIndx, midIndx);
        mergeSort(items, midIndx + 1, endIndx);
        merge(items, begIndx, midIndx, endIndx);
    }
}

@SuppressWarnings("unchecked")
private static <T> void merge(Comparable<? extends T>[] array,
                              int begIndx, int midIndx, int endIndx) {
    int sizeOfLeft = midIndx - begIndx + 1;
    int sizeOfRight = endIndx - midIndx;

    /// change to generic later
    @SuppressWarnings("unchecked")
    T[] leftArr = (T[]) new Object[sizeOfLeft + 1];
    @SuppressWarnings("unchecked")
    T[] rightArr = (T[]) new Object[sizeOfRight + 1];

    for (int i = 0; i < sizeOfLeft; i++) {
        leftArr[i] = (T) array[begIndx + i];
    }
    for (int j = 0; j < sizeOfRight; j++) {
        rightArr[j] = (T) array[midIndx + j + 1];
    }

    int i = 0;
    int j = 0;

    // changed to less than or equal to rather than "less than"
    // this is because this is a zero based index system
    // and because endeIndex is not a length but an index,
    // you need to populate it.
    for (int k = begIndx; k <= endIndx; k++) {
        // use comparable here
        if (((Integer) leftArr[i]).compareTo((Integer) rightArr[j]) <= 0) {
            array[k] = (Comparable<? extends T>) leftArr[i];
            i = i + 1;
        } else if (((Integer) leftArr[i]).compareTo((Integer) rightArr[j]) >= 0) {
            /// just replaces it so don't use comparable
            array[k] = (Comparable<? extends T>) rightArr[j];
            j = j + 1;
        } else if ((Integer) leftArr[sizeOfLeft] == null) {
            array[k] =  (Comparable<? extends T>) rightArr[j];
            j = j + 1;
        } else if ((Integer) rightArr[sizeOfRight] == null) {
            array[k] = (Comparable<? extends T>) leftArr[i];
            i = i + 1;
        }
    }
}

I created an integer array arr = new Integer[5]. So those 5 numbers should be sorted.

Body:
There are multiple problems in your code:

it is unclear if the index endIndx is included or excluded. The code is much simpler if the endIndx is excluded, and the initial call to sort the array is simply: mergesort(arr, 0, arr.length);

the initial test in mergesort is incorrect: instead of testing the array length, you should test if the slice has more than 1 element:

if (endIndx - begIndx > 1)

the arrays left and right are unused in mergesort.

allocating an extra element in the arrays left and right in merge is not required, it is much simpler to compare the array index values against the lengths of the subarrays. This sentinel approach is confusing and should not be used.

Here is a simplified version:

private static <T> void mergeSort(Comparable<? extends T>[] items, int begIndx, int endIndx) {
    if (endIndx - begIndx > 1) {
        int midIndx = items.length / 2;
        mergeSort(items, begIndx, midIndx);
        mergeSort(items, midIndx, endIndx);
        merge(items, begIndx, midIndx, endIndx);
    }
}

@SuppressWarnings("unchecked")
private static <T> void merge(Comparable<? extends T>[] array,
                              int begIndx, int midIndx, int endIndx) {
    int sizeOfLeft = midIndx - begIndx;
    int sizeOfRight = endIndx - midIndx;

    /// change to generic later
    @SuppressWarnings("unchecked")
    T[] leftArr = (T[]) new Object[sizeOfLeft];
    @SuppressWarnings("unchecked")
    T[] rightArr = (T[]) new Object[sizeOfRight];

    for (int i = 0; i < sizeOfLeft; i++) {
        leftArr[i] = (T)array[begIndx + i];
    }
    for (int j = 0; j < sizeOfRight; j++) {
        rightArr[j] = (T)array[midIndx + j];
    }

    int i = 0;
    int j = 0;
    int k = begIndx;

    while (i < sizeOfLeft && j < sizeOfRight) {
        /// use comparable to compare actual values
        if ((Integer)leftArr[i]).compareTo((Integer)rightArr[j]) <= 0) {
            array[k] = (Comparable<? extends T>)leftArr[i];
            i++;
            k++;
        } else {
            array[k] = (Comparable<? extends T>)rightArr[j];
            j++;
            k++;
        }
    }
    while (i < sizeOfLeft) {
        array[k] = (Comparable<? extends T>)leftArr[i];
        i++;
        k++;
    }
    while (j < sizeOfRight) {
        array[k] = (Comparable<? extends T>)rightArr[j];
        j++;
        k++;
    }
}


问:
Find aggregated values and relative values based on a value in a table using lookup
Hello Power BI community. I have a challenge in powerbi. I searched in the forum but I could not find the answer. I have a table of costs of different categories in different years. I want to search categories and find the aggregated costs in each category in each year. But I want to be able for each to display the aggregated cost of previous year(year-1) of each selected category and year.

My output would be:

Cost of Category in year x(the year and the category would be input by user,) Cost of Category.. in previous year (it is year-1).

The table, I have looks like this:

```<code> Year   CostItem 1  CostItem2   Category
 2010   1000         24            A
 2010   1250         3115          A
 2010   455          5115          A
 2010   5848.45      4904          B
 2010   34343        3352          B
 2010   4193         2899          B
 2010   824          3031          B
 2010   3944    3394    B
 2010   1546    3527    C
 2010   2175    1391    C
 2010   4942    2336    C
 2010   2988    5803    C
 2010   2423    3520    C
 2011   4132    2077    A
 2011   1666    834 A
 2011   2043    4419    A
 2011   4307    4030    A
 2011   4303    3339    A
 2011   4989    4619    A
 2011   5977    1655    A
 2011   4338    3698    A
 2011   2734    1321    B
 2011   1662    782     B
 2011   3036    3164    B
 2011   4488    5891    B
 2011   1679    5513    B
 2011   4169    4013    B
 2011   5647    4445    C
 2011   2728    5219    C
 2012   3155    2333    A
 2012   3893    1657    A
 2012   3626    1880    A
 2012   5805    796     A
 2012   753 4137        A
 2012   5537    4230    B
 2012   542 4244        B
 2012   2811    3300    B
 2012   866 3717    C
 2012   2356    2257    C
 2012   2712    2813    C
 2012   2250    4878    C
 2012   796 1610    C
 2012   4297    4241    C
2010    1250    3115    A
 2010   455 5115    A
 2010   5848.45 4904    B
 2010   34343   3352    B
 2010   4193    2899    B
 2010   824 3031    B
 2010   3944    3394    B
 2010   1546    3527    C
 2010   2175    1391    C
 2010   4942    2336    C
 2010   2988    5803    C
 2010   2423    3520    C
 2011   4132    2077    A
 2011   1666    834     A
 2011   2043    4419    A
 2011   4307    4030    A
 2011   4303    3339    A
 2011   4989    4619    A
 2011   5977    1655    A
 2011   4338    3698    A
 2011   2734    1321    B
 2011   1662    782     B
 2011   3036    3164    B
 2011   4488    5891    B
 2011   1679    5513    B
 2011   4169    4013    B
 2011   5647    4445    C
 2011   2728    5219    C
 2012   3155    2333    A
 2012   3893    1657    A
 2012   3626    1880    A
 2012   5805    796     A
 2012   753     4137    A
 2012   5537    4230    B
 2012   542     4244    B
 2012   2811    3300    B
 2012   866     3717    C
 2012   2356    2257    C
 2012   2712    2813    C
 2012   2250    4878    C
 2012   796     1610    C
 2012   4297    4241    C
</code>```

I tried using lookup function and value functions but could not end up a solution.

答:
You should model your data a bit different, go to query editor, you starting point:

Select the 2 columns CostItem1 and CostItem2. Go to Tab Transform and select: Unpivot, the result is as below:

Now you can use the matrix visual to create 2 levels, first category and then Attributes.

End result is overview per year:

Body:
Hello Power BI community. I have a challenge in powerbi. I searched in the forum but I could not find the answer. I have a table of costs of different categories in different years. I want to search categories and find the aggregated costs in each category in each year. But I want to be able for each to display the aggregated cost of previous year(year-1) of each selected category and year.

My output would be:

Cost of Category in year x(the year and the category would be input by user,) Cost of Category.. in previous year (it is year-1).

The table, I have looks like this:

 Year   CostItem 1  CostItem2   Category
 2010   1000         24            A
 2010   1250         3115          A
 2010   455          5115          A
 2010   5848.45      4904          B
 2010   34343        3352          B
 2010   4193         2899          B
 2010   824          3031          B
 2010   3944    3394    B
 2010   1546    3527    C
 2010   2175    1391    C
 2010   4942    2336    C
 2010   2988    5803    C
 2010   2423    3520    C
 2011   4132    2077    A
 2011   1666    834 A
 2011   2043    4419    A
 2011   4307    4030    A
 2011   4303    3339    A
 2011   4989    4619    A
 2011   5977    1655    A
 2011   4338    3698    A
 2011   2734    1321    B
 2011   1662    782     B
 2011   3036    3164    B
 2011   4488    5891    B
 2011   1679    5513    B
 2011   4169    4013    B
 2011   5647    4445    C
 2011   2728    5219    C
 2012   3155    2333    A
 2012   3893    1657    A
 2012   3626    1880    A
 2012   5805    796     A
 2012   753 4137        A
 2012   5537    4230    B
 2012   542 4244        B
 2012   2811    3300    B
 2012   866 3717    C
 2012   2356    2257    C
 2012   2712    2813    C
 2012   2250    4878    C
 2012   796 1610    C
 2012   4297    4241    C
2010    1250    3115    A
 2010   455 5115    A
 2010   5848.45 4904    B
 2010   34343   3352    B
 2010   4193    2899    B
 2010   824 3031    B
 2010   3944    3394    B
 2010   1546    3527    C
 2010   2175    1391    C
 2010   4942    2336    C
 2010   2988    5803    C
 2010   2423    3520    C
 2011   4132    2077    A
 2011   1666    834     A
 2011   2043    4419    A
 2011   4307    4030    A
 2011   4303    3339    A
 2011   4989    4619    A
 2011   5977    1655    A
 2011   4338    3698    A
 2011   2734    1321    B
 2011   1662    782     B
 2011   3036    3164    B
 2011   4488    5891    B
 2011   1679    5513    B
 2011   4169    4013    B
 2011   5647    4445    C
 2011   2728    5219    C
 2012   3155    2333    A
 2012   3893    1657    A
 2012   3626    1880    A
 2012   5805    796     A
 2012   753     4137    A
 2012   5537    4230    B
 2012   542     4244    B
 2012   2811    3300    B
 2012   866     3717    C
 2012   2356    2257    C
 2012   2712    2813    C
 2012   2250    4878    C
 2012   796     1610    C
 2012   4297    4241    C

I tried using lookup function and value functions but could not end up a solution.


问:
React: Is useEffect not guaranteed to run before the component renders?
I am trying to update some components in Gatsby.js, based on what url path I am on.

I am using useEffect() to make sure the components only update when location.pathname (the part of the url after the domain) changes.

Here is the code: https://codesandbox.io/s/gatsbystarterdefault-290qv

For some reason, useEffect is not using the updated values of the location prop (which is passed to the header component, which in turn wraps every page).

To reproduce, go to the CodeSandbox above and:

Click to page 2, then back again to page 1

See console statements that isHome when re-rendering Header is true while, isHome at NavItemLink is false

Any idea why useEffect does not get the latest value of location?

答:
I would recommand using useMemo instead of useEffect or storing it inside state. useMemo will compute NavLinks only when it's dependency will change.</p>

```<code>const generateNavLinks = path => nav.map((navItem, index) => (
  <NavItemLink
    key={navItem.name}
    name={navItem.name}
    to={navItem.path}
    isHome={path === withPrefix("/")}
  />
));

const navLinks = useMemo(() => generateNavLinks(location.pathname), [location.pathname]);
</code>```

Body:
I would recommand using useMemo instead of useEffect or storing it inside state. useMemo will compute NavLinks only when it's dependency will change.

const generateNavLinks = path => nav.map((navItem, index) => (
  <NavItemLink
    key={navItem.name}
    name={navItem.name}
    to={navItem.path}
    isHome={path === withPrefix("/")}
  />
));

const navLinks = useMemo(() => generateNavLinks(location.pathname), [location.pathname]);


问:
Parameterized Table Population
I am trying to populate a table(whose name is parameterized). The program runs fine, up until the point where the command gets executed.
Here is the code:

```<code>table_name = input("Enter table name: ")
value_name = input("Enter name: ")
sql = "INSERT INTO %s (name) VALUES (%s)" % db.escape_string(table_name), (value_name)
cursor.execute(sql)
</code>```

I get the following error:
TypeError: not enough arguments for format string

Thanks to anyone who takes the time to help. Have a great rest of the day :)

答:
Just wrap the sql formatting like below and try.</p>

```<code>sql = "INSERT INTO %s (name) VALUES (%s)" % (db.escape_string(table_name), value_name)
</code>```

Title: Parameterized Table Population

Body:
I am trying to populate a table(whose name is parameterized). The program runs fine, up until the point where the command gets executed.
Here is the code:

table_name = input("Enter table name: ")
value_name = input("Enter name: ")
sql = "INSERT INTO %s (name) VALUES (%s)" % db.escape_string(table_name), (value_name)
cursor.execute(sql)

I get the following error:
TypeError: not enough arguments for format string

Thanks to anyone who takes the time to help. Have a great rest of the day :)

Body:
Just wrap the sql formatting like below and try.

sql = "INSERT INTO %s (name) VALUES (%s)" % (db.escape_string(table_name), value_name)


问:
Get the By locator of an already found WebElement
Is there an elegant way to get the By locator of a Selenium WebElement, that I already found/identified?

To be clear about the question: I want the "By locator" as used to find the element. I am in this case not interested in a specific attribute or a specific locator like the css-locator.

I know that I could parse the result of a WebElement's toString() method:

```<code>WebElement element = driver.findElement(By.id("myPreciousElement"));
System.out.println(element.toString());
</code>```

Output would be for example:

[[FirefoxDriver: firefox on WINDOWS (....)] -> id: myPreciousElement]

if you found your element by xpath:

```<code>WebElement element = driver.findElement(By.xpath("//div[@someId = 'someValue']"));
System.out.println(element.toString());
</code>```

Then your output will be:

[[FirefoxDriver: firefox on WINDOWS (....)] -> xpath: //div[@someId = 'someValue']]

So I currently wrote my own method that parses this output and gives me the "recreated" By locator.

BUT is there a more elegant way already implemented in Selenium to get the By locator used to find the element?
 I couldn't find one so far.

If you are sure, there is none out of the box, can you think of any reason why the API creators might not provide this functionality?

*Despite the fact that this has nothing to do with the question, if someone wonders why you would ever need this functionality, just 2 examples:

if you use PageFactory you most likely will not have the locators as as member variables in your Page class, but you might need them later on when working with the page's elements.

you're working with APIs of people who just use the Page Object Pattern without PageFactory and thus expect you to hand over locators instead of the element itself.*

答:
Currently there is no specific method from selenium's end to do so. What you can do is write your custom method. You will get the clue of what selector type and path is used by just printing the webElement you have.

It looks something like this

[[ChromeDriver: chrome on XP (d85e7e220b2ec51b7faf42210816285e)] -> xpath: //input[@title='Search']]

Now, what you need to do is to extract the locator and its value. You can try something like this

private By getByFromElement(WebElement element) {
    By by = null;
    //[[ChromeDriver: chrome on XP (d85e7e220b2ec51b7faf42210816285e)] -> xpath: //input[@title='Search']]
    String[] pathVariables = (element.toString().split("->")[1].replaceFirst("(?s)(.*)\\]", "$1" + "")).split(":");

    String selector = pathVariables[0].trim();
    String value = pathVariables[1].trim();

    switch (selector) {
        case "id":
            by = By.id(value);
            break;
        case "className":
            by = By.className(value);
            break;
        case "tagName":
            by = By.tagName(value);
            break;
        case "xpath":
            by = By.xpath(value);
            break;
        case "cssSelector":
            by = By.cssSelector(value);
            break;
        case "linkText":
            by = By.linkText(value);
            break;
        case "name":
            by = By.name(value);
            break;
        case "partialLinkText":
            by = By.partialLinkText(value);
            break;
        default:
            throw new IllegalStateException("locator : " + selector + " not found!!!");
    }
    return by;
}
```

ContentLicense: CC BY-SA 3.0

Body:
Is there an elegant way to get the By locator of a Selenium WebElement, that I already found/identified?

To be clear about the question: I want the "By locator" as used to find the element. I am in this case not interested in a specific attribute or a specific locator like the css-locator.

I know that I could parse the result of a WebElement's toString() method:

WebElement element = driver.findElement(By.id("myPreciousElement"));
System.out.println(element.toString());

Output would be for example:

[[FirefoxDriver: firefox on WINDOWS (....)] -> id: myPreciousElement]

if you found your element by xpath:

WebElement element = driver.findElement(By.xpath("//div[@someId = 'someValue']"));
System.out.println(element.toString());

Then your output will be:

[[FirefoxDriver: firefox on WINDOWS (....)] -> xpath: //div[@someId = 'someValue']]

So I currently wrote my own method that parses this output and gives me the "recreated" By locator.

BUT is there a more elegant way already implemented in Selenium to get the By locator used to find the element?
 I couldn't find one so far.

If you are sure, there is none out of the box, can you think of any reason why the API creators might not provide this functionality?

*Despite the fact that this has nothing to do with the question, if someone wonders why you would ever need this functionality, just 2 examples:

if you use PageFactory you most likely will not have the locators as as member variables in your Page class, but you might need them later on when working with the page's elements.

you're working with APIs of people who just use the Page Object Pattern without PageFactory and thus expect you to hand over locators instead of the element itself.*


问:
Why doesn't my String comparison code work?
this code throws

Error "Exception in thread "main"
  java.lang.ArrayIndexOutOfBoundsException: 0

at basic2.compareStrPractice.main(compareStrPractice.java:15)"

```<code>int i;
    char[] chr1 = {};
    char[] chr2 = {};
    String s1 = "man";
    String s2 = "nam";

        for ( i= 0; i<s1.length(); i++){

            chr1[i] = (char)s1.charAt(i);
            chr2[i] = (char)s2.charAt(i);

        }
        if ((chr1[0] == chr2[2]) && (chr1[1] == chr2[1]) && (chr1[2] == chr2[0])){

            System.out.println("They are Palindrom!");
        }

}
</code>```

i want to print the statement. but it throws ArrayOutOfBoundary Error.

答:
If you are trying to write a code for palindrome it is wrong in many ways but for the error, You are initializing an empty array of char of 0 size, use this</p>

```<code>char[] chr1 = new char[3];
</code>```

Body:
this code throws

Error "Exception in thread "main"
  java.lang.ArrayIndexOutOfBoundsException: 0

at basic2.compareStrPractice.main(compareStrPractice.java:15)"

int i;
    char[] chr1 = {};
    char[] chr2 = {};
    String s1 = "man";
    String s2 = "nam";

        for ( i= 0; i<s1.length(); i++){

            chr1[i] = (char)s1.charAt(i);
            chr2[i] = (char)s2.charAt(i);

        }
        if ((chr1[0] == chr2[2]) && (chr1[1] == chr2[1]) && (chr1[2] == chr2[0])){

            System.out.println("They are Palindrom!");
        }

}

i want to print the statement. but it throws ArrayOutOfBoundary Error.

Body:
If you are trying to write a code for palindrome it is wrong in many ways but for the error, You are initializing an empty array of char of 0 size, use this

char[] chr1 = new char[3];


问:
Restricting number of continuous comma in a textbox
how to limit the number of continuous 'comma' in a textbox?...ex it should not allow user to enter more than 2 comma continuously  </p>

答:
This should handle most scenarios, I believe:

```<code>private void TextBox_TextChanged(object sender, EventArgs e)
{
    TextBox tb = sender as TextBox;
    if (tb != null)
    {
        int pos = tb.SelectionStart;
        int length = tb.Text.Length;
        tb.Text = tb.Text.Replace(",,", ",");
        int diff = length- tb.Text.Length;
        tb.SelectionStart = pos == 0 || diff == 0 ? pos : pos - diff;
    }
}
</code>```

This works when you type text into the TextBox, as well as when you paste text into it.

Body:
This should handle most scenarios, I believe:

private void TextBox_TextChanged(object sender, EventArgs e)
{
    TextBox tb = sender as TextBox;
    if (tb != null)
    {
        int pos = tb.SelectionStart;
        int length = tb.Text.Length;
        tb.Text = tb.Text.Replace(",,", ",");
        int diff = length- tb.Text.Length;
        tb.SelectionStart = pos == 0 || diff == 0 ? pos : pos - diff;
    }
}

This works when you type text into the TextBox, as well as when you paste text into it.


问:
How to extract arguments using regex?
I want to extract arguments (type of command-line arguments) using regex.
Here i will take the string as input and and get the arguments as groups

Basically i want the set in regex to both exclude and include some characters.

import re

ppatt=r"( --(?P<param>([^( --)]*)))"
a=[x.group("param") for x in re.finditer(ppatt,"command --m=psrmcc;ld -  --kkk gtodf --klfj")]
print(a)
```

<p>I want the output to be</p>

```['m=psrmcc;ld - ', 'kkk gtodf', 'klfj']
```

<p>but the output is</p>

```['m=psrmcc;ld', 'kkk', 'klfj']
```

答:
We might be able to solve this problem using a char list with word boundaries, maybe with an expression similar to:

```<code>(?:.+?)(\b[A-Za-z=;\s]+\b)
</code>```

If we wish to have more chars, we will be adding it to:

```<code>[A-Za-z=;\s]
</code>```

Here, we are not capturing the undesired chars by using a non-capturing group:

```<code>(?:.+?)
</code>```

then we collect our desired chars wrapped in a capturing group, which we can simply call it using $1:

```<code>(\b[A-Za-z=;\s]+\b)
</code>```

Test

```<code># coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(?:.+?)(\b[A-Za-z=;\s]+\b)"

test_str = "command --m=psrmcc;ld -  --kkk gtodf --klfj"

subst = "\\1\\n"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
</code>```

RegEx Circuit

jex.im visualizes regular expressions:

DEMO

Title: How to extract arguments using regex?

Body:
I want to extract arguments (type of command-line arguments) using regex.
Here i will take the string as input and and get the arguments as groups

Basically i want the set in regex to both exclude and include some characters.

import re

ppatt=r"( --(?P<param>([^( --)]*)))"
a=[x.group("param") for x in re.finditer(ppatt,"command --m=psrmcc;ld -  --kkk gtodf --klfj")]
print(a)

I want the output to be

['m=psrmcc;ld - ', 'kkk gtodf', 'klfj']

but the output is

['m=psrmcc;ld', 'kkk', 'klfj']

Body:
We might be able to solve this problem using a char list with word boundaries, maybe with an expression similar to:

(?:.+?)(\b[A-Za-z=;\s]+\b)

If we wish to have more chars, we will be adding it to:

[A-Za-z=;\s]

Here, we are not capturing the undesired chars by using a non-capturing group:

(?:.+?)

then we collect our desired chars wrapped in a capturing group, which we can simply call it using $1:

(\b[A-Za-z=;\s]+\b)

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(?:.+?)(\b[A-Za-z=;\s]+\b)"

test_str = "command --m=psrmcc;ld -  --kkk gtodf --klfj"

subst = "\\1\\n"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

RegEx Circuit

jex.im visualizes regular expressions:

DEMO


问:
How to NOT fetch a single item in an array using angularjs $resource/$http fetch?
I have a list view and a detailsView displayed side by side on the same screen, and it works fine. I am looking for a way to avoid fetching one single item that is "currently active" in the details view. The code in the List and detail controllers are  as below, can post markup, etc if required.

I) detailsView

```<code>'use strict';

angular.module('states.phones.detail')
.controller('PhoneDetailCtrl', ['$scope', 'phoneService', '$http', '$stateParams', 'angularGridInstance', 'Phone',
    function($scope, phoneService, $http, $stateParams, angularGridInstance, Phone, ) {
        console.debug('[states.phones.detail.controller()]');

        Phone.query()
            .$promise
            .then(function(data) {

                $scope.phones = data;
                $scope.page = 0;
                $scope.loadingMore = false;

                $scope.select = function(phone) {
                    $scope.selected = phone;
                }
                $scope.selected = {};

                $scope.selected = Phone.get({ phoneId: $stateParams.phoneId }, function(phone) {
                    $scope.mainImageUrl = phone.images[0];
                });

                $scope.setImage = function(imageUrl) {
                    $scope.mainImageUrl = imageUrl;

                    $scope.loadingMore = false;

                    $scope.loadMore = function() {
                        for (var i = 0; i = $scope.page; i++) {
                            $scope.phones.push(i++)[i];
                        }

                    }

                }

                $scope.loadMore = function() {
                    for (var i = 0; i = $scope.page; i++) {
                        $scope.phones.push(i++)[i];
                    }

                    function select($scope, $rootScope) {
                        $scope.select = function() {
                            var phoneslist = angularGridInstance[this];

                            angularGridInstance.phones.refresh();
                            $scope.$broadcast('select()');
                        };
                    }

                    var promise = $http.get('static-assets/phones/phones.json', { params: { phoneId: 'phones' } });
                    promise.then(function(data) {
                        var phonesTmp = angular.copy($scope.phones);
                        phonesTmp = phonesTmp.concat(data.data);
                        $scope.phones = phonesTmp;

                        $scope.loadingMore = false;

                    }, function() {
                        $scope.loadingMore = false;
                    });

                    return promise;
                };
            })
    }
])
</code>```

II) ListView:

```<code>(function() {

    'use strict';

    angular.module('states.phones.list')

        .controller('PhoneListCtrl', ['$scope', 'phoneService', '$q', '$http', '$rootScope', "$localStorage", "$sessionStorage", 'angularGridInstance', 'Phone',
            function($scope, phoneService, $q, $http, $rootScope, $localStorage, $sessionStorage, angularGridInstance, Phone) {
                console.debug('[states.phones.list.controller()]');

                $scope.card = {};
                var phoneslist = angularGridInstance[this];
                $scope.page = 0;
                $scope.phones = [];
                $scope.loadingMore = false;

                $scope.loadMore = function() {
                    for (var i = 0; i = $scope.page; i++) {
                        $scope.phones.push(i++)[i];
                    }

                    function select($scope, $rootScope) {
                        $scope.select = function() {
                            var phoneslist = angularGridInstance[this];

                            angularGridInstance.phones.refresh();
                            $scope.$broadcast('select()');
                        };
                    }

                    var promise =
                        $http.get('static-assets/phones/phones.json', {
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            params: { phoneId: 'phones' }
                        });
                    promise.then(function(data) {
                        var phonesTmp = angular.copy($scope.phones || []);
                        phonesTmp = phonesTmp.concat(data.data);
                        $scope.phones = phonesTmp;

                        $scope.loadingMore = false;

                    }, function() {
                        $scope.loadingMore = false;
                    });

                    return promise;
                };
                $scope.loadMore();

            }

        ]);
}());
</code>```

答:
The technique of replacing functions on-the-fly should be avoided. It tangles state and functions in a way that makes code hard to understand, debug, test, and maintain. XHRs should only put data on scope, not functions.

How do I omit a single item from the list if it is already 'active' in detailsView?

I am more inclined to highlight the active item on the list. I also would disable the click handler, not add and remove it.

```<code><div ng-repeat="item in list" ng-class="{highlight: $index == active}">
     {{item.name}}
     <button ng-disabled="active == $index" ng-click="showDetail(item)">
        Show Detail
     </button>
</div>
</code>```

Body:
I have a list view and a detailsView displayed side by side on the same screen, and it works fine. I am looking for a way to avoid fetching one single item that is "currently active" in the details view. The code in the List and detail controllers are  as below, can post markup, etc if required.

I) detailsView

'use strict';

angular.module('states.phones.detail')
.controller('PhoneDetailCtrl', ['$scope', 'phoneService', '$http', '$stateParams', 'angularGridInstance', 'Phone',
    function($scope, phoneService, $http, $stateParams, angularGridInstance, Phone, ) {
        console.debug('[states.phones.detail.controller()]');

        Phone.query()
            .$promise
            .then(function(data) {

                $scope.phones = data;
                $scope.page = 0;
                $scope.loadingMore = false;

                $scope.select = function(phone) {
                    $scope.selected = phone;
                }
                $scope.selected = {};

                $scope.selected = Phone.get({ phoneId: $stateParams.phoneId }, function(phone) {
                    $scope.mainImageUrl = phone.images[0];
                });

                $scope.setImage = function(imageUrl) {
                    $scope.mainImageUrl = imageUrl;

                    $scope.loadingMore = false;

                    $scope.loadMore = function() {
                        for (var i = 0; i = $scope.page; i++) {
                            $scope.phones.push(i++)[i];
                        }

                    }

                }

                $scope.loadMore = function() {
                    for (var i = 0; i = $scope.page; i++) {
                        $scope.phones.push(i++)[i];
                    }

                    function select($scope, $rootScope) {
                        $scope.select = function() {
                            var phoneslist = angularGridInstance[this];

                            angularGridInstance.phones.refresh();
                            $scope.$broadcast('select()');
                        };
                    }

                    var promise = $http.get('static-assets/phones/phones.json', { params: { phoneId: 'phones' } });
                    promise.then(function(data) {
                        var phonesTmp = angular.copy($scope.phones);
                        phonesTmp = phonesTmp.concat(data.data);
                        $scope.phones = phonesTmp;

                        $scope.loadingMore = false;

                    }, function() {
                        $scope.loadingMore = false;
                    });

                    return promise;
                };
            })
    }
])

II) ListView:

(function() {

    'use strict';

    angular.module('states.phones.list')

        .controller('PhoneListCtrl', ['$scope', 'phoneService', '$q', '$http', '$rootScope', "$localStorage", "$sessionStorage", 'angularGridInstance', 'Phone',
            function($scope, phoneService, $q, $http, $rootScope, $localStorage, $sessionStorage, angularGridInstance, Phone) {
                console.debug('[states.phones.list.controller()]');

                $scope.card = {};
                var phoneslist = angularGridInstance[this];
                $scope.page = 0;
                $scope.phones = [];
                $scope.loadingMore = false;

                $scope.loadMore = function() {
                    for (var i = 0; i = $scope.page; i++) {
                        $scope.phones.push(i++)[i];
                    }

                    function select($scope, $rootScope) {
                        $scope.select = function() {
                            var phoneslist = angularGridInstance[this];

                            angularGridInstance.phones.refresh();
                            $scope.$broadcast('select()');
                        };
                    }

                    var promise =
                        $http.get('static-assets/phones/phones.json', {
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            params: { phoneId: 'phones' }
                        });
                    promise.then(function(data) {
                        var phonesTmp = angular.copy($scope.phones || []);
                        phonesTmp = phonesTmp.concat(data.data);
                        $scope.phones = phonesTmp;

                        $scope.loadingMore = false;

                    }, function() {
                        $scope.loadingMore = false;
                    });

                    return promise;
                };
                $scope.loadMore();

            }

        ]);
}());

Body:
The technique of replacing functions on-the-fly should be avoided. It tangles state and functions in a way that makes code hard to understand, debug, test, and maintain. XHRs should only put data on scope, not functions.

How do I omit a single item from the list if it is already 'active' in detailsView?

I am more inclined to highlight the active item on the list. I also would disable the click handler, not add and remove it.

<div ng-repeat="item in list" ng-class="{highlight: $index == active}">
     {{item.name}}
     <button ng-disabled="active == $index" ng-click="showDetail(item)">
        Show Detail
     </button>
</div>


问:
Downloading a file (with expo) — Why is this so hard?
I've been trying multiple ways to download a file to local storage in react native, non of which are working. Here's my code in App.js where I am calling FileSystem.downloadAsync.

```<code>import React from 'react';
import { AppRegistry, StyleSheet, Text, View, TouchableHighlight, Image, Linking, PixelRatio, ListView } from 'react-native';
import { createStackNavigator } from 'react-navigation'
import MainScreen from './Components/MainScreen'
import FileSystem from 'react-native-filesystem';

export default class App extends React.Component {

  render() {
    return (

      FileSystem.downloadAsync(
        'http://techslides.com/demos/sample-videos/small.mp4',
        FileSystem.documentDirectory + 'small.mp4'
      )
        .then(({ uri }) => {
          console.log('Finished downloading to ', uri);
        })
        .catch(error => {
          console.error(error);
        }),

      <AppStackNavigator />
    );
  }
}

const AppStackNavigator = createStackNavigator({
  Main:{
    screen: MainScreen
  }
})

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

AppRegistry.registerComponent('Recap', () => App);
</code>```

I'm getting this error:

I'm very new to react native and javascript, but why does simply downloading a file seem to be so difficult, any help?

答:
there is a solution to this! It is not a great solution, and it is a total hack but I just tested it and it works great without needing any extra packages or permissions. it works with any file.

```<code>import { CameraRoll } from 'react-native';
...
CameraRoll.saveToCameraRoll( fileURI, 'photo');
</code>```

This moves the file into the root DCIM directory. Which means it is accessible via USB, or file explorer. It is a straight up hack and probably an oversight on someones part to not check mimetype, but its working!

Body:
I've been trying multiple ways to download a file to local storage in react native, non of which are working. Here's my code in App.js where I am calling FileSystem.downloadAsync.

import React from 'react';
import { AppRegistry, StyleSheet, Text, View, TouchableHighlight, Image, Linking, PixelRatio, ListView } from 'react-native';
import { createStackNavigator } from 'react-navigation'
import MainScreen from './Components/MainScreen'
import FileSystem from 'react-native-filesystem';

export default class App extends React.Component {

  render() {
    return (

      FileSystem.downloadAsync(
        'http://techslides.com/demos/sample-videos/small.mp4',
        FileSystem.documentDirectory + 'small.mp4'
      )
        .then(({ uri }) => {
          console.log('Finished downloading to ', uri);
        })
        .catch(error => {
          console.error(error);
        }),

      <AppStackNavigator />
    );
  }
}

const AppStackNavigator = createStackNavigator({
  Main:{
    screen: MainScreen
  }
})

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

AppRegistry.registerComponent('Recap', () => App);

I'm getting this error:

I'm very new to react native and javascript, but why does simply downloading a file seem to be so difficult, any help?

Body:
there is a solution to this! It is not a great solution, and it is a total hack but I just tested it and it works great without needing any extra packages or permissions. it works with any file.

import { CameraRoll } from 'react-native';
...
CameraRoll.saveToCameraRoll( fileURI, 'photo');

This moves the file into the root DCIM directory. Which means it is accessible via USB, or file explorer. It is a straight up hack and probably an oversight on someones part to not check mimetype, but its working!


问:
Python SQL Statements with Greek Letters and UTF-8
Version:
Postgresql = 11.3
Python = 3.7.3

I have a python script that is collecting data from the web and storing it in a database for further analysis.

The below sql statement always returns false when it attempts to compare the variable that has been fetched from the web against what already exists in the database.  I think this happens because of a mismatch in the encoding of the variable.

As an example, the variable = Σ1, and Σ1 already exists in the database, so the below sql statement should return TRUE but instead returns FALSE.

```<code>cur.execute("SELECT EXISTS(SELECT 1 FROM table_name WHERE column_name = %s)", (variable,))
</code>```

When I run "cur.query" it shows the following query is being executed:

```<code>b"SELECT EXISTS(SELECT 1 FROM table_name WHERE column_name = '\xce\xa31')"
</code>```

In pgadmin4, the variable is correctly stored as Σ1.  If I run the sql query above directly in pgadmin4 with "Σ1" it returns true as expected.
 But when I query to check if that variable already exists in the database from the python script, it returns false because it's comparing "Σ1" in the database against "\xce\xa31" in the sql query.

When I run "show CLIENT_ENCODING;" in pgadmin4 it shows "UTF8" and when I print "print(conn.encoding)" immediately before the sql statement in my script it also shows "UTF8".

Where am I going wrong?

答:
If I do this:

```<code>>>> b"SELECT EXISTS(SELECT 1 FROM table_name WHERE column_name = '\xce\xa31')".decode("utf-8")
"SELECT EXISTS(SELECT 1 FROM table_name WHERE column_name = 'Σ1')"
</code>```

it shows that you're not doing anything wrong. The query that you are seeing displayed back is shown as UTF-8 bytes but it is exactly the same as the Unicode query you want. I suspect that the Greek symbol in the database isn't exactly what your select expects to find. That may be because there are in fact several Unicode sigma signs: U+03A3,    U+2211 and a few others besides.

Body:
Version:
Postgresql = 11.3
Python = 3.7.3

I have a python script that is collecting data from the web and storing it in a database for further analysis.

The below sql statement always returns false when it attempts to compare the variable that has been fetched from the web against what already exists in the database.  I think this happens because of a mismatch in the encoding of the variable.

As an example, the variable = Σ1, and Σ1 already exists in the database, so the below sql statement should return TRUE but instead returns FALSE.

cur.execute("SELECT EXISTS(SELECT 1 FROM table_name WHERE column_name = %s)", (variable,))

When I run "cur.query" it shows the following query is being executed:

b"SELECT EXISTS(SELECT 1 FROM table_name WHERE column_name = '\xce\xa31')"

In pgadmin4, the variable is correctly stored as Σ1.  If I run the sql query above directly in pgadmin4 with "Σ1" it returns true as expected.
 But when I query to check if that variable already exists in the database from the python script, it returns false because it's comparing "Σ1" in the database against "\xce\xa31" in the sql query.

When I run "show CLIENT_ENCODING;" in pgadmin4 it shows "UTF8" and when I print "print(conn.encoding)" immediately before the sql statement in my script it also shows "UTF8".

Where am I going wrong?

Body:
If I do this:

>>> b"SELECT EXISTS(SELECT 1 FROM table_name WHERE column_name = '\xce\xa31')".decode("utf-8")
"SELECT EXISTS(SELECT 1 FROM table_name WHERE column_name = 'Σ1')"

it shows that you're not doing anything wrong. The query that you are seeing displayed back is shown as UTF-8 bytes but it is exactly the same as the Unicode query you want. I suspect that the Greek symbol in the database isn't exactly what your select expects to find. That may be because there are in fact several Unicode sigma signs: U+03A3,    U+2211 and a few others besides.


问:
Stepping into a P/Invoke call in disassemby view
My C# code is calling an unmanaged third-party library function via P/Invoke, and the unmanaged function is having some strange side effects. I want to debug into it and see what it's doing.

If I debug my C# code, and try to "Step Into" the P/Invoke call, it steps over instead. No surprise there -- I expected that; it doesn't have the source for this DLL, and I didn't tell it I was okay with seeing the disassembly view.

So I switch the debugger to disassembly view (Debug > Windows > Disassembly). Now I see the individual x86 instructions in my JITted code. Again I try to step into the P/Invoke call. Again, it steps over instead -- even though I clearly told it to Step Into an x86 CALL instruction. How hard is it to step into an x86 CALL?

My Googling thus far has shown me a couple of options that can affect this, and I've already set them:

In Tools > Options > Debugging > General, "Enable Just My Code" is unchecked.

In Project > Properties > Debug tab, "Enable unmanaged code debugging" is checked.

No good. Visual Studio still refuses to step in.

I don't have a PDB for the third-party DLL, but that shouldn't matter. I don't care about source code or symbol information. (Well, actually they'd be really nice, but I already know I'm not going to get them.) Visual Studio can do x86 debugging (that's what the Disassembly view is for), and all I want to do is step into the x86 code.

What else do I need to do to get VS to allow me to step into the x86 instructions inside a P/Invoke call?

答:
This may help you solve the problem:
(by Graviton)

```<code>CallingConvention = CallingConvention.Cdecl
</code>```

Also this mentions that you need to detach managed debugger and re-attach unmanaged when crossing the boundaries. You might need to check the capabilities of mixed debugger and it's preferences from MSDN.

And finally, using Ed Dore' answer:

Under Tools.Options dialog, select the
  Debugging category, and make sure the
  "Enable Just My Code" setting is
  unchecked.  From the Project
  properties, select the Debug tab, and
  then ensure that "Enable unmanaged
  code debugging" is checked.

Once you've got these squared away,
  you should get the mixed mode
  debugging support working.

Also, if you use "Debug.Attach To
  Process" , be sure to hit the
  "Select..." button in the "Attach To
  Process" dialog, and select both
  Managed and Native debugging support.

ContentLicense: CC BY-SA 2.5

Body:
This may help you solve the problem:
(by Graviton)

CallingConvention = CallingConvention.Cdecl

Also this mentions that you need to detach managed debugger and re-attach unmanaged when crossing the boundaries. You might need to check the capabilities of mixed debugger and it's preferences from MSDN.

And finally, using Ed Dore' answer:

Under Tools.Options dialog, select the
  Debugging category, and make sure the
  "Enable Just My Code" setting is
  unchecked.  From the Project
  properties, select the Debug tab, and
  then ensure that "Enable unmanaged
  code debugging" is checked.

Once you've got these squared away,
  you should get the mixed mode
  debugging support working.

Also, if you use "Debug.Attach To
  Process" , be sure to hit the
  "Select..." button in the "Attach To
  Process" dialog, and select both
  Managed and Native debugging support.


问:
RoutedCommand in UserControl is not working as expected
I am trying to use RoutedCommands in my UserControls, following the example in this article:

https://joshsmithonwpf.wordpress.com/2008/03/18/understanding-routed-commands/

I defined the RoutedCommand and CommandBindings in the UserControl instead of in the article's example. I am trying to use it in my MainWindow, so that when the Button is clicked, the Command in the UserControl is executed. However, the Button is disabled and the Foo_CanExecute() method is never executed.

```<code><UserControl x:Class="RoutedCommandTest.ViewControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:RoutedCommandTest"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <UserControl.CommandBindings>
        <CommandBinding
            Command="{x:Static local:ViewControl.Foo}"
            PreviewCanExecute="Foo_CanExecute"
            PreviewExecuted="Foo_Executed"
        />
    </UserControl.CommandBindings>
    <Grid>

    </Grid>
</UserControl>
</code>```

Here is the code for ViewControl.xaml.cs:

```<code>    public static readonly RoutedCommand Foo = new RoutedCommand();

    void Foo_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }

    void Foo_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        MessageBox.Show("The Window is Fooing...");
    }

    public ViewControl()
    {
        InitializeComponent();
    }
</code>```

And here is the code for MainWindow.xaml:

```<code><Window x:Class="RoutedCommandTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:RoutedCommandTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <local:ViewControl/>
        <Button Content="Foo" Margin="0 5" Command="{x:Static local:ViewControl.Foo}"/>
    </Grid>
</Window>
</code>```

I would like to know how to fix the issue so that the Button is enabled and the Foo_CanExecute() method is executed when the Button is clicked.

答:
Your command is in a usercontrol, whilst the button is in mainwindow.

Which presumably contains your usercontrol.

Like bubbling and routing events ( which are used to drive them ).

Executed looks for the command bubbling UP the visual tree to the binding.

PreviewExecuted looks for the command tunnelling DOWN the visual tree to the binding.

Since your button is in the parent of the usercontrol I'm not sure whether either bubbling or tunnelling will work.

But tunnelling would be PreviewExecuted  And PreviewCanExecute.

https://learn.microsoft.com/en-us/dotnet/api/system.windows.input.commandbinding.previewexecuted?view=netframework-4.8

https://learn.microsoft.com/en-us/dotnet/api/system.windows.input.commandbinding.previewcanexecute?view=netframework-4.8

Routedcommands can be pretty tricky to get right.

One thing you sometimes have to do is to bind commandtarget to tell it where to go look.

eg:

```<code>    <Grid>
      <local:UserControl1 x:Name="UC1" Height="60" Width="100"/>
      <Button Content="Foo" TextElement.FontSize="30" Command="{x:Static local:UserControl1.Foo}"
              CommandTarget="{Binding ElementName=UC1}"
              />
    </Grid>
</code>```

Works for me.

I have rarely found them useful - this is one of the aspects makes them way less useful than you might at first imagine.

EDIT:

It's perhaps worth mentioning the other thing makes these unattractive compared to a regular icommand.  You need to either use a static which means it's only suitable for very generic commands OR you need event handlers which will be in code behind.

On the other hand.

If you're writing something has to work generically with whatever has focus. Like say a text editor with multiple textboxes and you're doing text manipulation.  A routed command might be suitable. I have never encountered such a requirement in apps I've worked on though.

Body:
I am trying to use RoutedCommands in my UserControls, following the example in this article:

https://joshsmithonwpf.wordpress.com/2008/03/18/understanding-routed-commands/

I defined the RoutedCommand and CommandBindings in the UserControl instead of in the article's example. I am trying to use it in my MainWindow, so that when the Button is clicked, the Command in the UserControl is executed. However, the Button is disabled and the Foo_CanExecute() method is never executed.

<UserControl x:Class="RoutedCommandTest.ViewControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:RoutedCommandTest"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <UserControl.CommandBindings>
        <CommandBinding
            Command="{x:Static local:ViewControl.Foo}"
            PreviewCanExecute="Foo_CanExecute"
            PreviewExecuted="Foo_Executed"
        />
    </UserControl.CommandBindings>
    <Grid>

    </Grid>
</UserControl>

Here is the code for ViewControl.xaml.cs:

    public static readonly RoutedCommand Foo = new RoutedCommand();

    void Foo_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }

    void Foo_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        MessageBox.Show("The Window is Fooing...");
    }

    public ViewControl()
    {
        InitializeComponent();
    }

And here is the code for MainWindow.xaml:

<Window x:Class="RoutedCommandTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:RoutedCommandTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <local:ViewControl/>
        <Button Content="Foo" Margin="0 5" Command="{x:Static local:ViewControl.Foo}"/>
    </Grid>
</Window>

I would like to know how to fix the issue so that the Button is enabled and the Foo_CanExecute() method is executed when the Button is clicked.

Body:
Your command is in a usercontrol, whilst the button is in mainwindow.

Which presumably contains your usercontrol.

Like bubbling and routing events ( which are used to drive them ).

Executed looks for the command bubbling UP the visual tree to the binding.

PreviewExecuted looks for the command tunnelling DOWN the visual tree to the binding.

Since your button is in the parent of the usercontrol I'm not sure whether either bubbling or tunnelling will work.

But tunnelling would be PreviewExecuted  And PreviewCanExecute.

https://learn.microsoft.com/en-us/dotnet/api/system.windows.input.commandbinding.previewexecuted?view=netframework-4.8

https://learn.microsoft.com/en-us/dotnet/api/system.windows.input.commandbinding.previewcanexecute?view=netframework-4.8

Routedcommands can be pretty tricky to get right.

One thing you sometimes have to do is to bind commandtarget to tell it where to go look.

eg:

    <Grid>
      <local:UserControl1 x:Name="UC1" Height="60" Width="100"/>
      <Button Content="Foo" TextElement.FontSize="30" Command="{x:Static local:UserControl1.Foo}"
              CommandTarget="{Binding ElementName=UC1}"
              />
    </Grid>

Works for me.

I have rarely found them useful - this is one of the aspects makes them way less useful than you might at first imagine.

EDIT:

It's perhaps worth mentioning the other thing makes these unattractive compared to a regular icommand.  You need to either use a static which means it's only suitable for very generic commands OR you need event handlers which will be in code behind.

On the other hand.

If you're writing something has to work generically with whatever has focus. Like say a text editor with multiple textboxes and you're doing text manipulation.  A routed command might be suitable. I have never encountered such a requirement in apps I've worked on though.


问:
mySQL query not returning unique prices for each option
I am running the following mySQL query which is returning the incorrect price for each product option.  (Each option has a different price for testing purposes).

How can I return the individual prices for each option?

The DB schema can be seen here:
http://www.webassist.com/tutorials/Free-eCommerce-MySQL-Database

```<code>SELECT ProductName AS productname, ProductCategoryID,
pov.OptionGroupName AS groupname,
povd.OptionName AS optionname,
pd.OptionPrice as price

FROM products p
LEFT JOIN productoptions pd ON (p.ProductID = pd.ProductID)
LEFT JOIN optiongroups pov ON (pd.OptionGroupID = pov.OptionGroupID)
LEFT JOIN options povd ON (pov.OptionGroupID = povd.OptionGroupID)

WHERE p.ProductID = 1
GROUP BY groupname, povd.OptionName
</code>```

Currently getting this (note the prices):

```<code>+-------------+-------------------+-----------+------------+-------+
| ProductName | ProductCategoryID | GroupName | OptionName | Price |
+-------------+-------------------+-----------+------------+-------+
| Item1       | 1                 | Color     | Black      | 2.00  |
| Item1       | 1                 | Color     | Red        | 2.00  |
| Item1       | 1                 | Color     | Blue       | 2.00  |
| Item1       | 1                 | Size      | Small      | 5.00  |
| Item1       | 1                 | Size      | Medium     | 5.00  |
+-------------+-------------------+-----------+------------+-------+
</code>```

Should be like this (with unique prices):

```<code>+-------------+-------------------+-----------+------------+-------+
| ProductName | ProductCategoryID | GroupName | OptionName | Price |
+-------------+-------------------+-----------+------------+-------+
| Item1       | 1                 | Color     | Black      | 2.00  |
| Item1       | 1                 | Color     | Red        | 3.00  |
| Item1       | 1                 | Color     | Blue       | 4.00  |
| Item1       | 1                 | Size      | Small      | 5.00  |
| Item1       | 1                 | Size      | Medium     | 6.00  |
+-------------+-------------------+-----------+------------+-------+
</code>```

Here are data sets for all tables concerned (thanks for the guidance, Strawberry!).

Products Table

```<code>+-----------+-------------+-------------------+
| ProductID | ProductName | ProductCategoryID |
+-----------+-------------+-------------------+
| 1         | T-Shirt1    | 1                 |
+-----------+-------------+-------------------+
</code>```

OptionGroups Table

```<code>+---------------+-----------------+
| OptionGroupID | OptionGroupName |
+---------------+-----------------+
| 1             | color           |
| 2             | size            |
+---------------+-----------------+
</code>```

ProductOptions Table

```<code>+-----------------+-----------+----------+-------------+---------------+
| ProductOptionID | ProductID | OptionID | OptionPrice | OptionGroupID |
+-----------------+-----------+----------+-------------+---------------+
| 1               | 1         | 1        | 2.00        | 1 (color)     |
| 2               | 1         | 2        | 3.00        | 1 (color)     |
| 3               | 1         | 3        | 4.00        | 1 (color)     |
| 4               | 1         | 4        | 5.00        | 2 (size)      |
| 5               | 1         | 5        | 6.00        | 2 (size)      |
+-----------------+-----------+----------+-------------+---------------+
</code>```

Options Table

```<code>+----------+---------------+------------+
| OptionID | OptionGroupID | OptionName |
+----------+---------------+------------+
| 1        | 1             | black      |
| 2        | 1             | red        |
| 3        | 1             | blue       |
| 4        | 2             | Small      |
| 5        | 2             | Small      |
+----------+---------------+------------+
</code>```

答:
I took your query, scaisEdge, and made some changes to it.  I removed the min/max stuff, changed the way the Left Join was done on ProductOptions, and changed the Where clause and Group By.  Seems to be working correctly:

```<code>+-------------+-------------------+-----------+------------+-------+
| ProductName | ProductCategoryID | GroupName | OptionName | Price |
+-------------+-------------------+-----------+------------+-------+
| Item1       | 1                 | Color     | Black      | 2.25  |
| Item1       | 1                 | Color     | Red        | 3.25  |
| Item1       | 1                 | Color     | Blue       | 4.25  |
| Item1       | 1                 | Size      | Small      | 5.25  |
| Item1       | 1                 | Size      | Medium     | 6.25  |
+-------------+-------------------+-----------+------------+-------+
</code>```

The Query at this point:

```<code>SELECT ProductName AS productname, ProductCategoryID,
  pov.OptionGroupName AS groupname,
  povd.OptionName AS optionname,
  pd.OptionPrice AS price,
  povd.OptionID AS optionid

  FROM products p

  LEFT JOIN productoptions pd ON (pd.OptionID = optionid)
  LEFT JOIN optiongroups pov ON (pd.OptionGroupID = pov.OptionGroupID)
  LEFT JOIN options povd ON (pov.OptionGroupID = povd.OptionGroupID)

  WHERE p.ProductID = 1 and povd.OptionID = pd.OptionID

  GROUP BY povd.OptionID,
  groupname, povd.OptionName
</code>```

Thanks a lot for your help on this, scaisEdge.

And thanks to Strawberry for guiding me on how to format my questions on the site.

I truly believe that if a member 'down-votes' a question they should be required to explain why, so that we newbies can learn without simply being demoted and learning nothing from it.

Body:
I am running the following mySQL query which is returning the incorrect price for each product option.  (Each option has a different price for testing purposes).

How can I return the individual prices for each option?

The DB schema can be seen here:
http://www.webassist.com/tutorials/Free-eCommerce-MySQL-Database

SELECT ProductName AS productname, ProductCategoryID,
pov.OptionGroupName AS groupname,
povd.OptionName AS optionname,
pd.OptionPrice as price

FROM products p
LEFT JOIN productoptions pd ON (p.ProductID = pd.ProductID)
LEFT JOIN optiongroups pov ON (pd.OptionGroupID = pov.OptionGroupID)
LEFT JOIN options povd ON (pov.OptionGroupID = povd.OptionGroupID)

WHERE p.ProductID = 1
GROUP BY groupname, povd.OptionName

Currently getting this (note the prices):

+-------------+-------------------+-----------+------------+-------+
| ProductName | ProductCategoryID | GroupName | OptionName | Price |
+-------------+-------------------+-----------+------------+-------+
| Item1       | 1                 | Color     | Black      | 2.00  |
| Item1       | 1                 | Color     | Red        | 2.00  |
| Item1       | 1                 | Color     | Blue       | 2.00  |
| Item1       | 1                 | Size      | Small      | 5.00  |
| Item1       | 1                 | Size      | Medium     | 5.00  |
+-------------+-------------------+-----------+------------+-------+

Should be like this (with unique prices):

+-------------+-------------------+-----------+------------+-------+
| ProductName | ProductCategoryID | GroupName | OptionName | Price |
+-------------+-------------------+-----------+------------+-------+
| Item1       | 1                 | Color     | Black      | 2.00  |
| Item1       | 1                 | Color     | Red        | 3.00  |
| Item1       | 1                 | Color     | Blue       | 4.00  |
| Item1       | 1                 | Size      | Small      | 5.00  |
| Item1       | 1                 | Size      | Medium     | 6.00  |
+-------------+-------------------+-----------+------------+-------+

Here are data sets for all tables concerned (thanks for the guidance, Strawberry!).

Products Table

+-----------+-------------+-------------------+
| ProductID | ProductName | ProductCategoryID |
+-----------+-------------+-------------------+
| 1         | T-Shirt1    | 1                 |
+-----------+-------------+-------------------+

OptionGroups Table

+---------------+-----------------+
| OptionGroupID | OptionGroupName |
+---------------+-----------------+
| 1             | color           |
| 2             | size            |
+---------------+-----------------+

ProductOptions Table

+-----------------+-----------+----------+-------------+---------------+
| ProductOptionID | ProductID | OptionID | OptionPrice | OptionGroupID |
+-----------------+-----------+----------+-------------+---------------+
| 1               | 1         | 1        | 2.00        | 1 (color)     |
| 2               | 1         | 2        | 3.00        | 1 (color)     |
| 3               | 1         | 3        | 4.00        | 1 (color)     |
| 4               | 1         | 4        | 5.00        | 2 (size)      |
| 5               | 1         | 5        | 6.00        | 2 (size)      |
+-----------------+-----------+----------+-------------+---------------+

Options Table

+----------+---------------+------------+
| OptionID | OptionGroupID | OptionName |
+----------+---------------+------------+
| 1        | 1             | black      |
| 2        | 1             | red        |
| 3        | 1             | blue       |
| 4        | 2             | Small      |
| 5        | 2             | Small      |
+----------+---------------+------------+

Body:
I took your query, scaisEdge, and made some changes to it.  I removed the min/max stuff, changed the way the Left Join was done on ProductOptions, and changed the Where clause and Group By.  Seems to be working correctly:

+-------------+-------------------+-----------+------------+-------+
| ProductName | ProductCategoryID | GroupName | OptionName | Price |
+-------------+-------------------+-----------+------------+-------+
| Item1       | 1                 | Color     | Black      | 2.25  |
| Item1       | 1                 | Color     | Red        | 3.25  |
| Item1       | 1                 | Color     | Blue       | 4.25  |
| Item1       | 1                 | Size      | Small      | 5.25  |
| Item1       | 1                 | Size      | Medium     | 6.25  |
+-------------+-------------------+-----------+------------+-------+

The Query at this point:

SELECT ProductName AS productname, ProductCategoryID,
  pov.OptionGroupName AS groupname,
  povd.OptionName AS optionname,
  pd.OptionPrice AS price,
  povd.OptionID AS optionid

  FROM products p

  LEFT JOIN productoptions pd ON (pd.OptionID = optionid)
  LEFT JOIN optiongroups pov ON (pd.OptionGroupID = pov.OptionGroupID)
  LEFT JOIN options povd ON (pov.OptionGroupID = povd.OptionGroupID)

  WHERE p.ProductID = 1 and povd.OptionID = pd.OptionID

  GROUP BY povd.OptionID,
  groupname, povd.OptionName

Thanks a lot for your help on this, scaisEdge.

And thanks to Strawberry for guiding me on how to format my questions on the site.

I truly believe that if a member 'down-votes' a question they should be required to explain why, so that we newbies can learn without simply being demoted and learning nothing from it.


问:
Show pending migrations in rails
Is there a rake task that shows the pending migrations in a rails app?</p>

答:
If you need a bash one-liner to determine whether to run a migration or not (e.g., only migrate in a Heroku release phase command when there is a pending migration), this works:</p>

```<code>(rails db:migrate:status | grep "^\s*down") && rails db:migrate || echo "No pending migrations found."
</code>```

Title: Show pending migrations in rails

Body:
If you need a bash one-liner to determine whether to run a migration or not (e.g., only migrate in a Heroku release phase command when there is a pending migration), this works:

(rails db:migrate:status | grep "^\s*down") && rails db:migrate || echo "No pending migrations found."


问:
Segemented Control for iPhone not working
I have a segmented control with the following code in its action method:

```<code>-(IBAction)toggleControls:(id)sender{
    if([sender selectedSegmentIndex] == kSwitchesSegmentIndex){
        leftSwitch.hidden = NO;
        rightSwitch.hidden = NO;
        doSomethingButton.hidden = YES;
    }

    else{
        leftSwitch.hidden = YES;
        rightSwitch.hidden = YES;
        doSomethingButton.hidden = NO;
    }
}
</code>```

However, when I run the program I'm getting an error with kSwitchesSegmentIndex. It's saying that kSwitchesSegmentIndex is an undeclared identifier. Can anyone help me with what's wrong here?

答: You have done mistakes in declaration of kSwitchesSegmentIndex.

Body:
I have a segmented control with the following code in its action method:

-(IBAction)toggleControls:(id)sender{
    if([sender selectedSegmentIndex] == kSwitchesSegmentIndex){
        leftSwitch.hidden = NO;
        rightSwitch.hidden = NO;
        doSomethingButton.hidden = YES;
    }

    else{
        leftSwitch.hidden = YES;
        rightSwitch.hidden = YES;
        doSomethingButton.hidden = NO;
    }
}

However, when I run the program I'm getting an error with kSwitchesSegmentIndex. It's saying that kSwitchesSegmentIndex is an undeclared identifier. Can anyone help me with what's wrong here?


问:
No module named 'psycopg2' Error in Scrapy
When I use

```<code>import psycopg2
</code>```

in Scrapy pipeline.py or spider.py I get the following error

```<code>ModuleNotFoundError: No module named 'psycopg2'
</code>```

I know that the error is not valid, because I am running Django server with postgresql, using same venv which contains psycopg2. And also I can connect to db in a test file and enquiry as well. In addition I can run import psycopg2 in Scrapy shell with no issue. So it has puzzled me that I might be missing something,
I appreciate if someone can help me,

答:
Since it took me hours, here is what I have found.

I tested both in windows and Linux Ubuntu, both had same error.

Apparently this is what is happening:

In windows I had Scrapy installed on Core, and in Ubuntu apparently Scrapy is already wrapped in.

I ran my crawler within venv, and it appeared that actually my Scrapy is not installed correctly in the venve. However, Since Scrapy was already in the PATH it was running from Core, where it was no psycopg2. So the above mentioned errors was actually come from come not venv.

Installing Scrapy looked like was very simple in venv at first. I checked that by trying Scrapy shell and it was running, but it was actually were running from the core again. Make sure that you have Scrapy in your pip freeze list in your venv. This is a link that has explained how to address some issues in installation.

Body:
When I use

import psycopg2

in Scrapy pipeline.py or spider.py I get the following error

ModuleNotFoundError: No module named 'psycopg2'

I know that the error is not valid, because I am running Django server with postgresql, using same venv which contains psycopg2. And also I can connect to db in a test file and enquiry as well. In addition I can run import psycopg2 in Scrapy shell with no issue. So it has puzzled me that I might be missing something,
I appreciate if someone can help me,


问:
How to allow GPS location on my browser permantly (local web application JAVASCRIPT)
I get GPS position on my local web application (javascript). It's work but I have an autorization popup each time I start my application. and i don't have the chexbox for "remember my choice".

So, how allow permantly access to the gps on my browser for local application ?

thank you in advance

答:
Thanks Randy Casburn ! </p>

<p>It's easy ! Just execute a local server (like xampp) and you rimember the choice for the gps location.
It's impossible whithout http ! </p>

Body:
Thanks Randy Casburn !

It's easy ! Just execute a local server (like xampp) and you rimember the choice for the gps location.
It's impossible whithout http !


问:
Message "flutter run: No connected devices"
I am trying to create a sample application with Flutter (fresh installation). Android Studio is also installed (fresh installation).

Here is the output of flutter run

```<code>flutter run
No connected devices.
</code>```

The output of flutter doctor:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v0.1.5, on Linux, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
[✓] Android Studio (version 3.0)
[!] VS Code (version 1.20.1)
[!] Connected devices
! No devices available

! Doctor found issues in 2 categories.
```

Is there a solution to this problem?

答:
I'm using Genymotion for testing apps. I have the same problem. When I press the run button I face this error the last two hours...

How to fix this error: Just reinstall Genymotion this error is gone.

Body:
I am trying to create a sample application with Flutter (fresh installation). Android Studio is also installed (fresh installation).

Here is the output of flutter run

flutter run
No connected devices.

The output of flutter doctor:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v0.1.5, on Linux, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
[✓] Android Studio (version 3.0)
[!] VS Code (version 1.20.1)
[!] Connected devices
! No devices available

! Doctor found issues in 2 categories.

Is there a solution to this problem?


问:
Django CreateView With ManyToManyField
I am trying to use a Django CreateView and ultimately update a ManyToMany Field if the user selects a certain value.  I can get the form to validate, but ultimately it isn't updating the manytomanyfield in the database.  Not sure what I'm doing wrong.  I have referenced this similar SO issue, Django ManyToMany CreateView Fields In Both Tables but it was of no help to me.  I recently found this link...Django CreateView: How to perform action upon save and it seems very close to the issue I'm having.  Thanks in advance for any thoughts.

My code:

```<code>class AuthorView(LoginRequiredMixin,CreateView):
    model = NewAuthor
    form_class = NewAuthorForm
    template_name = 'create_author.html'

    def form_valid(self, form):
        instance = form.save(commit=False)

        if instance.status == 'Submitted':

            if instance.choice == "Custom":
                instance.access.add(instance.created_by)
                form.save_m2m()

    return super(CreateAuthorView, self).form_valid(form)
</code>```

Here is my model:

```<code>class NewAuthor(models.Model):

CHOICES = (
    ('',''),
    ("Default",Default ),
    ("Custom",Custom ),
)

STATUS_CHOICES = (
    ("Submitted","Submitted"),
    ("Pending","Pending")
)

status = models.CharField(choices=STATUS_CHOICES,default="Submitted",max_length=20)
choice = models.CharField(choices=CHOICES,blank=True,max_length=300)
created_by = models.ForeignKey(User,null=True,on_delete=models.DO_NOTHING,related_name='created_by_user')
access = models.ManyToManyField(User,related_name="new_author_individual_access")
</code>```

This passes form validation, but doesn't save the created_by value in the manytomany field.  I have tried to incorporate form.save(commit=False) and a subsequent form.save(), but that doesn't seem to help either.  I am ultimately trying to add the created_by user to the manytomany field conditionally, but no luck so far.

As a quick update, if I add the form.save_m2m() to my code, it actually does add the created_by to the database...but I also get an error that says object has no attribute 'save_m2m'.  It actually adds the created_by but then quits because of this error.  Now if I add commit=False, no errors but the database doesn't get updated either.

答:
I think you forgot to set the value of created_by, you are saving it with a null value since it's the default in your models. Try </p>

```<code>    instance = form.save(commit=False)
    instance.created_by = request.user # or whatever value
    instance.save()
</code>```

Title: Django CreateView With ManyToManyField

Body:
I am trying to use a Django CreateView and ultimately update a ManyToMany Field if the user selects a certain value.  I can get the form to validate, but ultimately it isn't updating the manytomanyfield in the database.  Not sure what I'm doing wrong.  I have referenced this similar SO issue, Django ManyToMany CreateView Fields In Both Tables but it was of no help to me.  I recently found this link...Django CreateView: How to perform action upon save and it seems very close to the issue I'm having.  Thanks in advance for any thoughts.

My code:

class AuthorView(LoginRequiredMixin,CreateView):
    model = NewAuthor
    form_class = NewAuthorForm
    template_name = 'create_author.html'

    def form_valid(self, form):
        instance = form.save(commit=False)

        if instance.status == 'Submitted':

            if instance.choice == "Custom":
                instance.access.add(instance.created_by)
                form.save_m2m()

    return super(CreateAuthorView, self).form_valid(form)

Here is my model:

class NewAuthor(models.Model):

CHOICES = (
    ('',''),
    ("Default",Default ),
    ("Custom",Custom ),
)

STATUS_CHOICES = (
    ("Submitted","Submitted"),
    ("Pending","Pending")
)

status = models.CharField(choices=STATUS_CHOICES,default="Submitted",max_length=20)
choice = models.CharField(choices=CHOICES,blank=True,max_length=300)
created_by = models.ForeignKey(User,null=True,on_delete=models.DO_NOTHING,related_name='created_by_user')
access = models.ManyToManyField(User,related_name="new_author_individual_access")

This passes form validation, but doesn't save the created_by value in the manytomany field.  I have tried to incorporate form.save(commit=False) and a subsequent form.save(), but that doesn't seem to help either.  I am ultimately trying to add the created_by user to the manytomany field conditionally, but no luck so far.

As a quick update, if I add the form.save_m2m() to my code, it actually does add the created_by to the database...but I also get an error that says object has no attribute 'save_m2m'.  It actually adds the created_by but then quits because of this error.  Now if I add commit=False, no errors but the database doesn't get updated either.

Body:
I think you forgot to set the value of created_by, you are saving it with a null value since it's the default in your models. Try

    instance = form.save(commit=False)
    instance.created_by = request.user # or whatever value
    instance.save()