问:
Get Href Link; if JPG to skip
I've created a loader for my website (the whole front end is custom,so as of right now i can edit about 95% of everything I have except for woocommerce plugin).
Super simple one, it follows this logic, if the anchor is an # or the page itself it wont do anything (which is what I wanted) but the woocommerce plugin to generate my image gallery is a link that isn't the page itself or a #. Which means I need to collect the path-name of the extension that if it ends on jpg png or any image file to continue; and skip over the rest of the animation and allow the plugin to run its course.

Ive use Barba JS, SWUP and other animations with woocommerce and this is the only one that doesnt interrupt or have so many conditions with woocommerce.

```<code>function fadeInPage() {
    if (!window.AnimationEvent) { return; }
    var fader = document.getElementById('fader');
    fader.classList.add('fade-out');
  }

  document.addEventListener('DOMContentLoaded', function() {
    if (!window.AnimationEvent) { return }

    var anchors = document.getElementsByTagName('a');

******* for (var idx = 0; idx < anchors.length; idx += 1) {
      if (anchors[idx].hostname !== window.location.hostname || anchors[idx].pathname === window.location.pathname) *******

{

        continue;
      }
      anchors[idx].addEventListener('click', function(event) {

        var fader = document.getElementById('fader'),
            anchor = event.currentTarget;

        var listener = function() {

          window.location = anchor.href;
          fader.removeEventListener('animationend', listener);
        };
        fader.addEventListener('animationend', listener);

        event.preventDefault();
        fader.classList.add('fade-in');
      });
    }
  });

  window.addEventListener('pageshow', function (event) {
    if (!event.persisted) {
      return;
    }
    var fader = document.getElementById('fader');
    fader.classList.remove('fade-in');
  });

</code>```

I starred what i need changed. the animation works, the page transition works. I need the animation to recognize if the a tag ends with an jpg or png to skip and not do the animation and treat the link as if the animation wasn't there.

答:
Never used woocommerce so I don't totally understand the use case, but you can get the file extension of a link like so:

```<code>
    for (var idx = 0; idx < anchors.length; idx += 1) {
           let fileType = anchors[idx].href.split('.').pop();
           //Do whatever
    }

</code>```

Or if you want to compare it to a preset list of extensions you can use a regex:

```<code>
    for (var idx = 0; idx < anchors.length; idx += 1) {
           if (anchors[idx].href.match(/\.(jpg|png)$/)) {
               //Do whatever
             }
    }

</code>```

Title: Get Href Link; if JPG to skip

Body:
I've created a loader for my website (the whole front end is custom,so as of right now i can edit about 95% of everything I have except for woocommerce plugin).
Super simple one, it follows this logic, if the anchor is an # or the page itself it wont do anything (which is what I wanted) but the woocommerce plugin to generate my image gallery is a link that isn't the page itself or a #. Which means I need to collect the path-name of the extension that if it ends on jpg png or any image file to continue; and skip over the rest of the animation and allow the plugin to run its course.

Ive use Barba JS, SWUP and other animations with woocommerce and this is the only one that doesnt interrupt or have so many conditions with woocommerce.

function fadeInPage() {
    if (!window.AnimationEvent) { return; }
    var fader = document.getElementById('fader');
    fader.classList.add('fade-out');
  }

  document.addEventListener('DOMContentLoaded', function() {
    if (!window.AnimationEvent) { return }

    var anchors = document.getElementsByTagName('a');

******* for (var idx = 0; idx < anchors.length; idx += 1) {
      if (anchors[idx].hostname !== window.location.hostname || anchors[idx].pathname === window.location.pathname) *******

{

        continue;
      }
      anchors[idx].addEventListener('click', function(event) {

        var fader = document.getElementById('fader'),
            anchor = event.currentTarget;

        var listener = function() {

          window.location = anchor.href;
          fader.removeEventListener('animationend', listener);
        };
        fader.addEventListener('animationend', listener);

        event.preventDefault();
        fader.classList.add('fade-in');
      });
    }
  });

  window.addEventListener('pageshow', function (event) {
    if (!event.persisted) {
      return;
    }
    var fader = document.getElementById('fader');
    fader.classList.remove('fade-in');
  });

I starred what i need changed. the animation works, the page transition works. I need the animation to recognize if the a tag ends with an jpg or png to skip and not do the animation and treat the link as if the animation wasn't there.

Body:
Never used woocommerce so I don't totally understand the use case, but you can get the file extension of a link like so:

    for (var idx = 0; idx < anchors.length; idx += 1) {
           let fileType = anchors[idx].href.split('.').pop();
           //Do whatever
    }

Or if you want to compare it to a preset list of extensions you can use a regex:

    for (var idx = 0; idx < anchors.length; idx += 1) {
           if (anchors[idx].href.match(/\.(jpg|png)$/)) {
               //Do whatever
             }
    }


来源: stackexchange

问:
How to perform a lower_bound operation on the second elements of a vector of pairs in C++?
One can copy all the v[i].second elements to a new vector and then do the lower_bound operation on the new vector and as the position of the particular value we are searching for would be the same in both vectors so it is reasonable to do. But if the vector has many elements then copying would be costly.

So, I want to know the syntax to perform a lower_bound operation on a vector<pair<int,int>> type of container if possible (specially only on the second elements of the vector).

答:
```<code>int myValue = 42;  // value to search for.
std::lower_bound(myVector.begin(), myVector.end(), myValue,
  [](const pair<int,int>& a, int b) {
    return a.second < b;
  });
</code>```

This assumes the vector is sorted by element.second.

ContentLicense: CC BY-SA 4.0

Body:
int myValue = 42;  // value to search for.
std::lower_bound(myVector.begin(), myVector.end(), myValue,
  [](const pair<int,int>& a, int b) {
    return a.second < b;
  });

This assumes the vector is sorted by element.second.


问:
Add rows to pandas dataframe using column of dictionaries
I have a dataframe like this:

```<code>matrix = [(222, {'a': 1, 'b':3, 'c':2, 'd':1}),
         (333, {'a': 1, 'b':0, 'c':0, 'd':1})]

df = pd.DataFrame(matrix, columns=['ordernum', 'dict_of item_counts'])
</code>```

```<code>   ordernum               dict_of item_counts
0       222  {'a': 1, 'b': 3, 'c': 2, 'd': 1}
1       333  {'a': 1, 'b': 0, 'c': 0, 'd': 1}
</code>```

and I would like to create a dataframe in which each ordernum is repeated for each dictionary key in dict_of_item_counts that is not 0. I would also like to create a key column that shows the corresponding dictionary key for this row as well as a value column that contains the dictionary values. Finally, I would also an ordernum_index that counts the different rows in the dataframe for each ordernum.

The final dataframe should look like this:

```<code>ordernum      ordernum_index      key     value

222           1                   a       1
222           2                   b       3
222           3                   c       2
222           4                   d       1
333           1                   a       1
333           2                   d       1
</code>```

Any help would be much appreciated :)

Body:
I have a dataframe like this:

matrix = [(222, {'a': 1, 'b':3, 'c':2, 'd':1}),
         (333, {'a': 1, 'b':0, 'c':0, 'd':1})]

df = pd.DataFrame(matrix, columns=['ordernum', 'dict_of item_counts'])

   ordernum               dict_of item_counts
0       222  {'a': 1, 'b': 3, 'c': 2, 'd': 1}
1       333  {'a': 1, 'b': 0, 'c': 0, 'd': 1}

and I would like to create a dataframe in which each ordernum is repeated for each dictionary key in dict_of_item_counts that is not 0. I would also like to create a key column that shows the corresponding dictionary key for this row as well as a value column that contains the dictionary values. Finally, I would also an ordernum_index that counts the different rows in the dataframe for each ordernum.

The final dataframe should look like this:

ordernum      ordernum_index      key     value

222           1                   a       1
222           2                   b       3
222           3                   c       2
222           4                   d       1
333           1                   a       1
333           2                   d       1

Any help would be much appreciated :)

Body:
Always try to structure your data, Can be done easily like below:

>>> matrix
[(222, {'a': 1, 'b': 3, 'c': 2, 'd': 1}), (333, {'a': 1, 'b': 0, 'c': 0, 'd': 1})]
>>> data = [[item[0]]+[i+1]+list(value) for item in matrix for i,value in enumerate(item[1].items()) if value[-1]!=0]
>>> data
[[222, 1, 'a', 1], [222, 2, 'b', 3], [222, 3, 'c', 2], [222, 4, 'd', 1], [333, 1, 'a', 1], [333, 4, 'd', 1]]
>>> pd.DataFrame(data, columns=['ordernum', 'ordernum_index', 'key', 'value'])
   ordernum  ordernum_index key  value
0       222               1   a      1
1       222               2   b      3
2       222               3   c      2
3       222               4   d      1
4       333               1   a      1
5       333               4   d      1


问:
Trunc a number and get removed value. Or cast to int?
I try to get the removed part of the math.trunc function.
Or a function supports this request.

```<code>import math
number = 1.9
newnumber, removed = math.trunc(number)
</code>```

I need the number = 1 and also the removed 0.9
So basicly i need the integer and the removed float.

Obove example will not work :/
Any suggestions ?

答:
If you use modf you can flip the order of your variables and get the result you want.</p>

```<code>import math
number = 1.9
removed, newnumber = math.modf(number)
</code>```

Body:
I try to get the removed part of the math.trunc function.
Or a function supports this request.

import math
number = 1.9
newnumber, removed = math.trunc(number)

I need the number = 1 and also the removed 0.9
So basicly i need the integer and the removed float.

Obove example will not work :/
Any suggestions ?

Body:
If you use modf you can flip the order of your variables and get the result you want.

import math
number = 1.9
removed, newnumber = math.modf(number)


问:
Filtering ID's based on specified difference in values
I am trying to filter IDs based on a specified conditions. For instance, I want to filter IDs which have a particular difference in questionnaire score from pre to post treatment. The idea is to get IDs that have improved in score, have stayed the same or have worsened. Here is a mock data set of what I'm trying to achieve:-

```<code>    ID<-c("aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","aaa","bbb","ccc","aaa","bbb","ccc")
    Condition<-c("Pre","Pre","Pre","Pre","Pre","Pre","Pre","Pre","Pre","Post","Post","Post","Post","Post","Post","Post","Post","Post","Pre","Pre","Pre","Post","Post", "Post")
    Score<-c(23,20,19,15,22,22,20,19,18,17,17,19,20,22,22,14,15,10,23,23,21,20,18,11)
    df<-cbind(ID,Condition,Score)
    df<-as.data.frame(df)
    df$Condition<-as.factor(df$Condition)
</code>```

The main issue here is that there are ID's who appear in the data, for both pre and post, twice.

I have tried using a dplyr solution to select the appropriate columns from the main data frame, and then use tidyverse, and the spread function to convert to wide format, because from there I can work out the differences easily enough. However, there is a particular problem that I've experienced. It wouldn't work because there are duplicate instances where an ID has appeared in the data again (for example, IDs aaa, bbb & ccc).

```<code>     df2<-df%>%
     group_by(ID)%>%
     spread(Condition, Score)
</code>```

This gets me the following error message:-

Error: Each row of output must be identified by a unique combination of keys.
  Keys are shared for 12 rows:
  * 10, 22
  * 11, 23
  * 12, 24
  * 1, 19
  * 2, 20
  * 3, 21
  Do you need to create unique ID with tibble::rowid_to_column()?

Ideally, the kind of result I would be looking for is like so:-

```<code>    #improved
    ID      Pre       Post     Difference
    aaa      23        17           -6
    bbb      20        17           -3
    ggg      20        14           -6
    hhh      19        15           -4
    iii      18        10           -8
    aaa      23        20           -3
    bbb      23        18           -5
    ccc      21        11           -10

    #no improvement
    ID      Pre       Post      Difference
    ccc      19         19          0
    eee      22         22          0
    fff      22         22          0

    #worsened
    ID      Pre       Post      Difference
    ddd      15         20          +5
</code>```

Or something to this effect. As long as it allows me to include the repeated IDs. Ideally, I would like to be able to conditionally filter further based on the magnitude of difference. So for instance, if I want to subset/filter IDs with an improved score of more than 5, or a worsened score of more than 5. Bare in mind, my actual data set will have far more IDs to work with than the example that I just made up and provided. Any help would be greatly appreciated, as always.

Thank you in advance :)

答:
A different tidyverse possibility could be:

```<code>df %>%
 mutate_if(is.factor, as.character) %>%
 mutate(Score = as.numeric(Score)) %>%
 group_by(Condition) %>%
 mutate(ID = make.unique(ID)) %>%
 group_by(ID) %>%
 mutate(Difference = Score - lag(Score)) %>%
 spread(Condition, Score) %>%
 summarise_all(max, na.rm = TRUE) %>%
 arrange(Difference)

   ID    Difference  Post   Pre
   <chr>      <dbl> <dbl> <dbl>
 1 ccc.1        -10    11    21
 2 iii           -8    10    18
 3 aaa           -6    17    23
 4 ggg           -6    14    20
 5 bbb.1         -5    18    23
 6 hhh           -4    15    19
 7 aaa.1         -3    20    23
 8 bbb           -3    17    20
 9 ccc            0    19    19
10 eee            0    22    22
11 fff            0    22    22
12 ddd            5    20    15
</code>```

Here it, first, creates unique IDs. Second, it calculates the difference. Finally, it transforms it into a wide format and arranges it according the differences.

If for some reasons you need to split it according differences, you can add the last line from @akrun's code:

```<code>df %>%
 mutate_if(is.factor, as.character) %>%
 mutate(Score = as.numeric(Score)) %>%
 group_by(Condition) %>%
 mutate(ID = make.unique(ID)) %>%
 group_by(ID) %>%
 mutate(Difference = Score - lag(Score)) %>%
 spread(Condition, Score) %>%
 summarise_all(max, na.rm = TRUE) %>%
 group_split(sign(Difference), keep = FALSE)

[[1]]
# A tibble: 8 x 4
  ID    Difference  Post   Pre
  <chr>      <dbl> <dbl> <dbl>
1 aaa           -6    17    23
2 aaa.1         -3    20    23
3 bbb           -3    17    20
4 bbb.1         -5    18    23
5 ccc.1        -10    11    21
6 ggg           -6    14    20
7 hhh           -4    15    19
8 iii           -8    10    18

[[2]]
# A tibble: 3 x 4
  ID    Difference  Post   Pre
  <chr>      <dbl> <dbl> <dbl>
1 ccc            0    19    19
2 eee            0    22    22
3 fff            0    22    22

[[3]]
# A tibble: 1 x 4
  ID    Difference  Post   Pre
  <chr>      <dbl> <dbl> <dbl>
1 ddd            5    20    15
</code>```

Body:
I am trying to filter IDs based on a specified conditions. For instance, I want to filter IDs which have a particular difference in questionnaire score from pre to post treatment. The idea is to get IDs that have improved in score, have stayed the same or have worsened. Here is a mock data set of what I'm trying to achieve:-

    ID<-c("aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","aaa","bbb","ccc","aaa","bbb","ccc")
    Condition<-c("Pre","Pre","Pre","Pre","Pre","Pre","Pre","Pre","Pre","Post","Post","Post","Post","Post","Post","Post","Post","Post","Pre","Pre","Pre","Post","Post", "Post")
    Score<-c(23,20,19,15,22,22,20,19,18,17,17,19,20,22,22,14,15,10,23,23,21,20,18,11)
    df<-cbind(ID,Condition,Score)
    df<-as.data.frame(df)
    df$Condition<-as.factor(df$Condition)

The main issue here is that there are ID's who appear in the data, for both pre and post, twice.

I have tried using a dplyr solution to select the appropriate columns from the main data frame, and then use tidyverse, and the spread function to convert to wide format, because from there I can work out the differences easily enough. However, there is a particular problem that I've experienced. It wouldn't work because there are duplicate instances where an ID has appeared in the data again (for example, IDs aaa, bbb & ccc).

     df2<-df%>%
     group_by(ID)%>%
     spread(Condition, Score)

This gets me the following error message:-

Error: Each row of output must be identified by a unique combination of keys.
  Keys are shared for 12 rows:
  * 10, 22
  * 11, 23
  * 12, 24
  * 1, 19
  * 2, 20
  * 3, 21
  Do you need to create unique ID with tibble::rowid_to_column()?

Ideally, the kind of result I would be looking for is like so:-

    #improved
    ID      Pre       Post     Difference
    aaa      23        17           -6
    bbb      20        17           -3
    ggg      20        14           -6
    hhh      19        15           -4
    iii      18        10           -8
    aaa      23        20           -3
    bbb      23        18           -5
    ccc      21        11           -10

    #no improvement
    ID      Pre       Post      Difference
    ccc      19         19          0
    eee      22         22          0
    fff      22         22          0

    #worsened
    ID      Pre       Post      Difference
    ddd      15         20          +5

Or something to this effect. As long as it allows me to include the repeated IDs. Ideally, I would like to be able to conditionally filter further based on the magnitude of difference. So for instance, if I want to subset/filter IDs with an improved score of more than 5, or a worsened score of more than 5. Bare in mind, my actual data set will have far more IDs to work with than the example that I just made up and provided. Any help would be greatly appreciated, as always.

Thank you in advance :)

Body:
A different tidyverse possibility could be:

df %>%
 mutate_if(is.factor, as.character) %>%
 mutate(Score = as.numeric(Score)) %>%
 group_by(Condition) %>%
 mutate(ID = make.unique(ID)) %>%
 group_by(ID) %>%
 mutate(Difference = Score - lag(Score)) %>%
 spread(Condition, Score) %>%
 summarise_all(max, na.rm = TRUE) %>%
 arrange(Difference)

   ID    Difference  Post   Pre
   <chr>      <dbl> <dbl> <dbl>
 1 ccc.1        -10    11    21
 2 iii           -8    10    18
 3 aaa           -6    17    23
 4 ggg           -6    14    20
 5 bbb.1         -5    18    23
 6 hhh           -4    15    19
 7 aaa.1         -3    20    23
 8 bbb           -3    17    20
 9 ccc            0    19    19
10 eee            0    22    22
11 fff            0    22    22
12 ddd            5    20    15

Here it, first, creates unique IDs. Second, it calculates the difference. Finally, it transforms it into a wide format and arranges it according the differences.

If for some reasons you need to split it according differences, you can add the last line from @akrun's code:

df %>%
 mutate_if(is.factor, as.character) %>%
 mutate(Score = as.numeric(Score)) %>%
 group_by(Condition) %>%
 mutate(ID = make.unique(ID)) %>%
 group_by(ID) %>%
 mutate(Difference = Score - lag(Score)) %>%
 spread(Condition, Score) %>%
 summarise_all(max, na.rm = TRUE) %>%
 group_split(sign(Difference), keep = FALSE)

[[1]]
# A tibble: 8 x 4
  ID    Difference  Post   Pre
  <chr>      <dbl> <dbl> <dbl>
1 aaa           -6    17    23
2 aaa.1         -3    20    23
3 bbb           -3    17    20
4 bbb.1         -5    18    23
5 ccc.1        -10    11    21
6 ggg           -6    14    20
7 hhh           -4    15    19
8 iii           -8    10    18

[[2]]
# A tibble: 3 x 4
  ID    Difference  Post   Pre
  <chr>      <dbl> <dbl> <dbl>
1 ccc            0    19    19
2 eee            0    22    22
3 fff            0    22    22

[[3]]
# A tibble: 1 x 4
  ID    Difference  Post   Pre
  <chr>      <dbl> <dbl> <dbl>
1 ddd            5    20    15


问:
Find the IP and Username from a huge text file
```<code>#NAM=127.0.0.1 #PRT="HomeServer:Ping Test"#HID=100#DEP=-1#DPS=5#GRP=G00000027#REM=""#UID=6038#ACT=T#LOL=F#FOL=F#VIA="#DE=__LAN__#KA=F#"#LDEFUP=5/16/2019 10:44:39 PM#LDEWHO=#TPL=F#MUT=#MFR=#RUSE=F...
</code>```

答:
I see you are trying to learn Powershell so I will help you out. Next time please provide a valid question.

What you are trying to do is use Regular Expression to search for Ips.

Powershell is using the .Net Framework. Calling a class is as easy as using [Class Here]

So we will call the regex class and then search for IP addresses in a string.

In this case i wrote a quick function to do this task

```<code>function Find-IPAddresses([string]$Data){
    [regex]::Matches($File, "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)") | %{
        $_.value
    }
}

$Info = @"
#NAM=127.0.0.1 #PRT="HomeServer:Ping Test"#HID=100#DEP=-1#DPS=5#GRP=G00000027#REM=""#UID=6038#ACT=T#LOL=F#FOL=F#VIA="#DE=__LAN__#KA=F#"#LDEFUP=5/16/2019 10:44:39 PM#LDEWHO=#TPL=F#MUT=#MFR=#RUSE=F..
"@

Find-IPAddresses -Data $Info
</code>```

it will return 127.0.0.1

Body:
I see you are trying to learn Powershell so I will help you out. Next time please provide a valid question.

What you are trying to do is use Regular Expression to search for Ips.

Powershell is using the .Net Framework. Calling a class is as easy as using [Class Here]

So we will call the regex class and then search for IP addresses in a string.

In this case i wrote a quick function to do this task

function Find-IPAddresses([string]$Data){
    [regex]::Matches($File, "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)") | %{
        $_.value
    }
}

$Info = @"
#NAM=127.0.0.1 #PRT="HomeServer:Ping Test"#HID=100#DEP=-1#DPS=5#GRP=G00000027#REM=""#UID=6038#ACT=T#LOL=F#FOL=F#VIA="#DE=__LAN__#KA=F#"#LDEFUP=5/16/2019 10:44:39 PM#LDEWHO=#TPL=F#MUT=#MFR=#RUSE=F..
"@

Find-IPAddresses -Data $Info

it will return 127.0.0.1


问:
The given path's format is not supported - Using time data
I trying to save some data to a text file inside a folder:

I have tried to change dd-MM-yyyy-hhmm To dd-MM-yyyy-hh:mm, and I tried to use the debugger to check where is the problem but I couldn't find anything.

Code:

```<code>public static string Folder(string mode)
{
    string str = DateTime.Now.ToString("dd-MM-yyyy-hhmm - ");
    Directory.CreateDirectory(str + mode);
    return str + mode;
}
</code>```

The resulting behaviour should be similar to, the user saves the data, it will create a new folder with this name.

For example:

(example - http - 26-5-2019-1514), inside the folder - Results.txt

答:
You can not have colons on the filename
https://learn.microsoft.com/en-us/windows/desktop/msi/filename

Short and long file names must not contain the following characters:

slash (/) or ()

question mark (?)

vertical bar (|)

right angle bracket (>)

left angle bracket (<)

colon (:)

asterisk (*)

quotation mark (")

In addition, short file names must not contain the following
  characters:

plus sign (+)

comma (,)

semicolon (;)

equals sign (=)

left square bracket ([)

right square bracket (])

Body:
I trying to save some data to a text file inside a folder:

I have tried to change dd-MM-yyyy-hhmm To dd-MM-yyyy-hh:mm, and I tried to use the debugger to check where is the problem but I couldn't find anything.

Code:

public static string Folder(string mode)
{
    string str = DateTime.Now.ToString("dd-MM-yyyy-hhmm - ");
    Directory.CreateDirectory(str + mode);
    return str + mode;
}

The resulting behaviour should be similar to, the user saves the data, it will create a new folder with this name.

For example:

(example - http - 26-5-2019-1514), inside the folder - Results.txt


问:
How to bind function to object property?
There is a class with methods:

```<code>public add() {}
public delete(item: Ivoice) {}
</code>```

And method for mapping these methods inside object:

```<code>    this.invoices = data.map(item => {
            item.add = this.add;
            item.edit = this.delete;
            return item;
   });
</code>```

Then in template I tried to call method as:

```<code><div *ngFor="let item of items; let i = index">
  <span (click)="item.add(item)">
</div>
</code>```

But it does not work.

答:
Although, it is not clear, what you are really trying to achieve, but technically the problem lies here:

item.add = this.add;
item.edit = this.delete;
```

<p>You are basically assigning the function/method references to the <code>item</code> object. Next time you call the method over <code>item</code>, a la item.add(item) within your template, then the method/function will invoked at <code>item</code>'s scope, and not your class", i.e. ItemComponent, scope, which apparently the desired behaviour.</p>

<p>You can use the bind method to avoid this problem:</p>

<pre class="lang-js prettyprint-override"><code>item.add = this.add.bind(this);
item.edit = this.delete.bind(this);
</code>```

Body:
There is a class with methods:

public add() {}
public delete(item: Ivoice) {}

And method for mapping these methods inside object:

    this.invoices = data.map(item => {
            item.add = this.add;
            item.edit = this.delete;
            return item;
   });

Then in template I tried to call method as:

But it does not work.

Body:
Although, it is not clear, what you are really trying to achieve, but technically the problem lies here:

item.add = this.add;
item.edit = this.delete;

You are basically assigning the function/method references to the item object. Next time you call the method over item, a la item.add(item) within your template, then the method/function will invoked at item's scope, and not your class", i.e. ItemComponent, scope, which apparently the desired behaviour.

You can use the bind method to avoid this problem:

item.add = this.add.bind(this);
item.edit = this.delete.bind(this);


问:
uasort() ? - sorting posts from a bank account
How can I sort an array with some posts from a bank account?

I need to sort by three fields: date, amount, accumulated amount

ie.

```<code>date | amount | accum_amount
01-01-11 500 500 ('amount' + previous 'accum_amount' = 'accum_amount' => 500 + 0 = 500)
01-01-11 100 600 ('amount' + previous 'accum_amount' = 'accum_amount' => 100 + 500 = 600)
01-02-11 -25 575 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 600 = 575)
01-02-11 150 725 ('amount' + previous 'accum_amount' = 'accum_amount' => 150 + 575 = 725)
01-03-11 200 925 ('amount' + previous 'accum_amount' = 'accum_amount' => 200 + 725 = 925)
01-04-11 -25 900 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 925 = 900)
</code>```

btw. the date field is an UNIX timestamp

```<code>array(
    array(
        'time' => 1200000000,
        'amount' => 500,
        'accum_amount' => 500
        ),
    array(
        'time' => 1200000000,
        'amount' => 150,
        'accum_amount' => 725
        ),
    array(
        'time' => 1200000000,
        'amount' => 100,
        'accum_amount' => 600
        ),
    array(
        'time' => 1300000000,
        'amount' => 200,
        'accum_amount' => 925
        ),
    array(
        'time' => 1300000000,
        'amount' => -25,
        'accum_amount' => 900
        ),
    array(
        'time' => 1200000000,
        'amount' => -25,
        'accum_amount' => 575
        )
    )
</code>```

答:
function usort() is made for this purpose:</p>

```<code>usort($data, "my_sort");

function my_sort($row1, $row2) {
  if ($row1['time']<$row2['time']) return -1;
  if ($row1['time']>$row2['time']) return 1;
  if ($row1['amount']<$row2['amount']) return -1;
  if ($row1['amount']>$row2['amount']) return 1;
  if ($row1['accum_amount']<$row2['accum_amount']) return -1;
  if ($row1['accum_amount']>$row2['accum_amount']) return 1;
  return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I sort an array with some posts from a bank account?

I need to sort by three fields: date, amount, accumulated amount

ie.

date | amount | accum_amount
01-01-11 500 500 ('amount' + previous 'accum_amount' = 'accum_amount' => 500 + 0 = 500)
01-01-11 100 600 ('amount' + previous 'accum_amount' = 'accum_amount' => 100 + 500 = 600)
01-02-11 -25 575 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 600 = 575)
01-02-11 150 725 ('amount' + previous 'accum_amount' = 'accum_amount' => 150 + 575 = 725)
01-03-11 200 925 ('amount' + previous 'accum_amount' = 'accum_amount' => 200 + 725 = 925)
01-04-11 -25 900 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 925 = 900)

btw. the date field is an UNIX timestamp

array(
    array(
        'time' => 1200000000,
        'amount' => 500,
        'accum_amount' => 500
        ),
    array(
        'time' => 1200000000,
        'amount' => 150,
        'accum_amount' => 725
        ),
    array(
        'time' => 1200000000,
        'amount' => 100,
        'accum_amount' => 600
        ),
    array(
        'time' => 1300000000,
        'amount' => 200,
        'accum_amount' => 925
        ),
    array(
        'time' => 1300000000,
        'amount' => -25,
        'accum_amount' => 900
        ),
    array(
        'time' => 1200000000,
        'amount' => -25,
        'accum_amount' => 575
        )
    )

Body:
function usort() is made for this purpose:

usort($data, "my_sort");

function my_sort($row1, $row2) {
  if ($row1['time']<$row2['time']) return -1;
  if ($row1['time']>$row2['time']) return 1;
  if ($row1['amount']<$row2['amount']) return -1;
  if ($row1['amount']>$row2['amount']) return 1;
  if ($row1['accum_amount']<$row2['accum_amount']) return -1;
  if ($row1['accum_amount']>$row2['accum_amount']) return 1;
  return 0;
}


问:
ng-table grouping - initialize with rows minimised
I am using the grouping example of ng-table from http://plnkr.co/edit/CBcbkc

Right now the table is initialised with rows expanded, but I would like them to be minimised as I have over 100 records. How can I do this?

答:
Just add groupOptions: {isExpanded:false} in the params section.

Below is a copy of your code with the proper add-on.

```<code>$scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 10,          // count per page
        groupOptions: {isExpanded:false}
    }, {
        groupBy: 'role',
        total: data.length,
        getData: function($defer, params) {
            var orderedData = params.sorting() ?
                    $filter('orderBy')(data, $scope.tableParams.orderBy()) :
                    data;

            $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
        }
    });
</code>```

Body:
Just add groupOptions: {isExpanded:false} in the params section.

Below is a copy of your code with the proper add-on.

$scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 10,          // count per page
        groupOptions: {isExpanded:false}
    }, {
        groupBy: 'role',
        total: data.length,
        getData: function($defer, params) {
            var orderedData = params.sorting() ?
                    $filter('orderBy')(data, $scope.tableParams.orderBy()) :
                    data;

            $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
        }
    });


问:
cornerRadius with border: Glitch around border
My application is mostly round- and borderbased.

I use the layer property of UIView to give a corner radius and a border.

But I am facing a problem that the corners are not clear.

I am getting the following results:

UIButton

UIImageView

You can observe a thin border line around the white or grey border.

This is my code:

```<code>button.layer.borderWidth = 2.0;
button.layer.borderColor = [[UIColor whiteColor] CGColor];
button.layer.cornerRadius = 4;

button.clipsToBounds = YES;
</code>```

I have searched to solve this but I'm not getting success.

I have tried button.layer.masksToBounds = YES, but with no effect.

Am I missing anything? Or are there any other methods which can give me better results compared to CALayer?

答:
de.'s answer worked much better for me  than CRDave's answer.

I had to translate it from Swift, so I thought I'd go ahead and post the translation:

```<code>extension UIView {
    func giveBorderWithCornerRadius(cornerRadius r: CGFloat, borderColor c: UIColor, strokeWidth w: CGFloat) {
        let rect = self.bounds

        let maskPath = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: r, height: r))

        let maskLayer = CAShapeLayer()

        maskLayer.frame = rect
        maskLayer.path = maskPath.cgPath

        self.layer.mask = maskLayer

        let borderPath = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: r, height: r))

        let layerName = "border_layer"
        var borderLayer: CAShapeLayer? = self.layer.sublayers?.filter({ (c) -> Bool in
            if c.name == layerName {
                return true
            } else {
                return false
            }
        }).first as? CAShapeLayer

        if borderLayer == nil {
            borderLayer = CAShapeLayer()
            borderLayer!.name = layerName
            self.layer.addSublayer(borderLayer!)
        }

        borderLayer!.frame = rect
        borderLayer!.path = borderPath.cgPath
        borderLayer!.strokeColor = c.cgColor
        borderLayer!.fillColor = UIColor.clear.cgColor
        borderLayer!.lineWidth = w
    }
}
</code>```

I'm calling the method from layoutSubviews()

Body:
My application is mostly round- and borderbased.

I use the layer property of UIView to give a corner radius and a border.

But I am facing a problem that the corners are not clear.

I am getting the following results:

UIButton

UIImageView

You can observe a thin border line around the white or grey border.

This is my code:

button.layer.borderWidth = 2.0;
button.layer.borderColor = [[UIColor whiteColor] CGColor];
button.layer.cornerRadius = 4;

button.clipsToBounds = YES;

I have searched to solve this but I'm not getting success.

I have tried button.layer.masksToBounds = YES, but with no effect.

Am I missing anything? Or are there any other methods which can give me better results compared to CALayer?

Body:
de.'s answer worked much better for me  than CRDave's answer.

I had to translate it from Swift, so I thought I'd go ahead and post the translation:

extension UIView {
    func giveBorderWithCornerRadius(cornerRadius r: CGFloat, borderColor c: UIColor, strokeWidth w: CGFloat) {
        let rect = self.bounds

        let maskPath = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: r, height: r))

        let maskLayer = CAShapeLayer()

        maskLayer.frame = rect
        maskLayer.path = maskPath.cgPath

        self.layer.mask = maskLayer

        let borderPath = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: r, height: r))

        let layerName = "border_layer"
        var borderLayer: CAShapeLayer? = self.layer.sublayers?.filter({ (c) -> Bool in
            if c.name == layerName {
                return true
            } else {
                return false
            }
        }).first as? CAShapeLayer

        if borderLayer == nil {
            borderLayer = CAShapeLayer()
            borderLayer!.name = layerName
            self.layer.addSublayer(borderLayer!)
        }

        borderLayer!.frame = rect
        borderLayer!.path = borderPath.cgPath
        borderLayer!.strokeColor = c.cgColor
        borderLayer!.fillColor = UIColor.clear.cgColor
        borderLayer!.lineWidth = w
    }
}

I'm calling the method from layoutSubviews()


问:
Tracking in_app_purchases event for subscriptions on Android
Google docs say:

This event is triggered only by versions of your app that include the Firebase SDK. Note: paid app-purchase revenue, subscription revenue (Android only), and refunds are not automatically tracked. Your reported revenue may differ from the values you see in the Google Play Developer Console. Events that are flagged as being invalid or as sandbox (test) are ignored. Only iOS events are flagged as sandbox. Learn more about testing Google Play billing.

In other words in Android only subscriptions events are not tracked automatically. Is there a way how to track them? Do you have any implementation examples?

答: Looks like Firebase enabled it's tracking for subscriptions recently. My observations: Did Firebase start reporting in_app_purchase for subscriptions recently?</p>


问:
Any reason to overload global new and delete?
Unless you're programming parts of an OS or an embedded system are there any reasons to do so? I can imagine that for some particular classes that are created and destroyed frequently overloading memory management functions or introducing a pool of objects might lower the overhead, but doing these things globally?

Addition

I've just found a bug in an overloaded delete function - memory wasn't always freed. And that was in a not-so memory critical application. Also, disabling these overloads decreases performance by ~0.5% only.

答: Overloaded new operator also enables programmers to squeeze some extra performance out of their programs. For example, In a class, to speed up the allocation of new nodes, a list of deleted nodes is maintained so that their memory can be reused when new nodes are allocated.In this case, the overloaded delete operator will add nodes to the list of deleted nodes and the overloaded new operator will allocate memory from this list rather than from the heap to speedup memory allocation. Memory from the heap can be used when the list of deleted nodes is empty.</p>


问:
jquery - how to see if a script with the src of "sub string" already exists in the head tag?
I am stumped on this one, never tried this way before but is there a solution to see if a script tag with the source of "x" already exists in the head tag?

Basically I have a site that loads in external plugins. My site loads in jquery into the head tag, and this external plugin also loads the same jquery version into the head tag. I would like to try to run a script that checks the source of all the existing script tags and if their source contains a sub string of "x" to then not load the script tag, else if no script tag with this source exists then to go ahead and load it up.

Here is my use case.

This script tag exists in my head tag

The external plugin places this script into my head tag

I would like to edit the plugin to run a check of something like this

if $('script[src="in here if this string contains jquery-1.7.1.min.js"]').length; > 0

then don't load this script into the head tag because its already there;

else load this script into the head tag because it doesn't exist yet;

I want to run this kind of check because this plugin can also run on customer web pages were they might not have jquery pre installed on their domains. So thats the rub, I want it to work in both domains. Ones were jquery is installed and ones were its not.

Do you guys have any ideas for this? If I can get this to work I can then use this type of fix for other solutions as well.

SOLUTION FOUND
I will be using this for now to solve this issue.

```<code>if($('script[src$="jquery-1.7.1.min.js"]').length; > 0 ){
    then don't load script
}else{
    load script because its not on the page yet
}
</code>```

Going to end up making this a function so I can just pass if JS file urls to see if they are already on the page or not in future projects as well. This is going to be a big help.

答:
I want to run this kind of check because this plugin can also run on customer web pages were they might not have jquery pre installed on their domains.

jQuery selectors, in 97% of cases, work just as well as ordinary CSS selectors, which work natively with querySelector and querySelectorAll. So, just use querySelector instead:

```<code>const possibleScriptTag = document.querySelector('script[src$="jquery-1.7.1.min.js"]');
if (!possibleScriptTag) {
  // insert jQuery yourself
}
</code>```

The [src$="jquery-1.7.1.min.js"] means "a src which ends in jquery-1.7.1.min.js".

Body:
I am stumped on this one, never tried this way before but is there a solution to see if a script tag with the source of "x" already exists in the head tag?

Basically I have a site that loads in external plugins. My site loads in jquery into the head tag, and this external plugin also loads the same jquery version into the head tag. I would like to try to run a script that checks the source of all the existing script tags and if their source contains a sub string of "x" to then not load the script tag, else if no script tag with this source exists then to go ahead and load it up.

Here is my use case.

This script tag exists in my head tag

The external plugin places this script into my head tag

I would like to edit the plugin to run a check of something like this

if $('script[src="in here if this string contains jquery-1.7.1.min.js"]').length; > 0

then don't load this script into the head tag because its already there;

else load this script into the head tag because it doesn't exist yet;

I want to run this kind of check because this plugin can also run on customer web pages were they might not have jquery pre installed on their domains. So thats the rub, I want it to work in both domains. Ones were jquery is installed and ones were its not.

Do you guys have any ideas for this? If I can get this to work I can then use this type of fix for other solutions as well.

SOLUTION FOUND
I will be using this for now to solve this issue.

if($('script[src$="jquery-1.7.1.min.js"]').length; > 0 ){
    then don't load script
}else{
    load script because its not on the page yet
}

Going to end up making this a function so I can just pass if JS file urls to see if they are already on the page or not in future projects as well. This is going to be a big help.

Body:
I want to run this kind of check because this plugin can also run on customer web pages were they might not have jquery pre installed on their domains.

jQuery selectors, in 97% of cases, work just as well as ordinary CSS selectors, which work natively with querySelector and querySelectorAll. So, just use querySelector instead:

const possibleScriptTag = document.querySelector('script[src$="jquery-1.7.1.min.js"]');
if (!possibleScriptTag) {
  // insert jQuery yourself
}

The [src$="jquery-1.7.1.min.js"] means "a src which ends in jquery-1.7.1.min.js".


问:
Android Asset Manager unable to load wav file assets from the assets directory
I am have a few wav files that I want to load with the help of Android's asset manager. Unfortunately, everytime I try to do so, I get the following error

java.io.FileNotFoundException: audio-file.wav not found

I would like to add the following assets to the Android sound pool.

This is the image of my application set up.

Application IDE Set up

My code

```<code>public class MyActivity extends AppCompatActivity {

  protected abstract Fragment createFragment();

  @LayoutRes
  protected int getLayoutRes() {
    return R.layout.activity_fragment;
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(getLayoutRes());

    FragmentManager fm = getSupportFragmentManager();
    Fragment fragment = fm.findFragmentById(R.id.fragment_container);
    if (fragment == null) {
      fragment = new MyActivityFragment();
      fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
    }
  }

}
</code>```

Fragment

```<code>    public class MyActivityFragment extends Fragment {

       private static final String TAG = "MyFragment";
       private static final String SOUNDS_FOLDER = "sample_sounds";
       private static final int MAX_SOUNDS = 5;

    private final AssetManager mAssetManager;

      private final List<Integer> sounds = new ArrayList<>();
      private SoundPool mSoundPool;

      @Override
      public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        this.mAssetManager = getActivity().getAssets();
        this.loadAssets();
        mSoundPool = this.buildSoundPool();
      }

      @Override
      public void onDestroy() {
        super.onDestroy();
        mSoundPool.release();
      }

  private SoundPool buildSoundPool() {
    SoundPool.Builder builder = new SoundPool.Builder();
    builder.setMaxStreams(MAX_SOUNDS);
    builder.setAudioAttributes(new AudioAttributes.Builder()
        .setUsage(AudioAttributes.USAGE_MEDIA)
        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
        .build());
    return builder.build();
  }

  private void loadAssets() {
    try {
      String[] soundNames = mAssetManager.list(SOUNDS_FOLDER);
      for (String soundName : soundNames) {
        sounds.add(load(soundName));
      }
    } catch (IOException ioe) {
      Log.e(TAG, "Could not list assets");
    }
  }

   private int load(String soundName) throws IOException {
      AssetFileDescriptor afd = mAssetManager.openFd(soundName);
      int soundId = mSoundPool.load(afd, 1);
      return soundId;
   }
}
</code>```

This method raises a FileNotFoundException.

```<code>private int load(String soundName) throws IOException {
    AssetFileDescriptor afd = mAssetManager.openFd(soundName);
    int soundId = mSoundPool.load(afd, 1);
    return soundId;
  }
</code>```

This line precisely

```<code>AssetFileDescriptor afd = mAssetManager.openFd(soundName);
</code>```

I have gone through the other posts related to this issue, but the most recent post is at least 3 years old. I don't know what I am doing wrong. Any help would be gratefully appreciated.

答:
IIRC, list() returns the names of the items in the asset directory. It does not return the paths of those items.

Try replacing:

```<code>AssetFileDescriptor afd = mAssetManager.openFd(soundName);
</code>```

with:

```<code>AssetFileDescriptor afd = mAssetManager.openFd(SOUND_FOLDER+"/"+soundName);
</code>```

Body:
I am have a few wav files that I want to load with the help of Android's asset manager. Unfortunately, everytime I try to do so, I get the following error

java.io.FileNotFoundException: audio-file.wav not found

I would like to add the following assets to the Android sound pool.

This is the image of my application set up.

Application IDE Set up

My code

public class MyActivity extends AppCompatActivity {

  protected abstract Fragment createFragment();

  @LayoutRes
  protected int getLayoutRes() {
    return R.layout.activity_fragment;
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(getLayoutRes());

    FragmentManager fm = getSupportFragmentManager();
    Fragment fragment = fm.findFragmentById(R.id.fragment_container);
    if (fragment == null) {
      fragment = new MyActivityFragment();
      fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
    }
  }

}

Fragment

    public class MyActivityFragment extends Fragment {

       private static final String TAG = "MyFragment";
       private static final String SOUNDS_FOLDER = "sample_sounds";
       private static final int MAX_SOUNDS = 5;

    private final AssetManager mAssetManager;

      private final List<Integer> sounds = new ArrayList<>();
      private SoundPool mSoundPool;

      @Override
      public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        this.mAssetManager = getActivity().getAssets();
        this.loadAssets();
        mSoundPool = this.buildSoundPool();
      }

      @Override
      public void onDestroy() {
        super.onDestroy();
        mSoundPool.release();
      }

  private SoundPool buildSoundPool() {
    SoundPool.Builder builder = new SoundPool.Builder();
    builder.setMaxStreams(MAX_SOUNDS);
    builder.setAudioAttributes(new AudioAttributes.Builder()
        .setUsage(AudioAttributes.USAGE_MEDIA)
        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
        .build());
    return builder.build();
  }

  private void loadAssets() {
    try {
      String[] soundNames = mAssetManager.list(SOUNDS_FOLDER);
      for (String soundName : soundNames) {
        sounds.add(load(soundName));
      }
    } catch (IOException ioe) {
      Log.e(TAG, "Could not list assets");
    }
  }

   private int load(String soundName) throws IOException {
      AssetFileDescriptor afd = mAssetManager.openFd(soundName);
      int soundId = mSoundPool.load(afd, 1);
      return soundId;
   }
}

This method raises a FileNotFoundException.

private int load(String soundName) throws IOException {
    AssetFileDescriptor afd = mAssetManager.openFd(soundName);
    int soundId = mSoundPool.load(afd, 1);
    return soundId;
  }

This line precisely

AssetFileDescriptor afd = mAssetManager.openFd(soundName);

I have gone through the other posts related to this issue, but the most recent post is at least 3 years old. I don't know what I am doing wrong. Any help would be gratefully appreciated.

Body:
IIRC, list() returns the names of the items in the asset directory. It does not return the paths of those items.

Try replacing:

AssetFileDescriptor afd = mAssetManager.openFd(soundName);

with:

AssetFileDescriptor afd = mAssetManager.openFd(SOUND_FOLDER+"/"+soundName);


问:
Editing the labels and position of the axis ticks on a seaborn heatmap results in an empty plot
I am trying to plot a seaborn heatmap with custom locations and labels on both axes. The dataframe looks like this:

Dataframe

I can plot this normally with seaborn.heatmap:

```<code>fig, ax = plt.subplots(figsize=(8, 8))
sns.heatmap(genome_freq.applymap(lambda x: np.log10(x+1)),
            ax=ax)
plt.show()
</code>```

Normal heatmap

I have a list of positions I'd like to set as the xticks (binned_chrom_genome_pos):

```<code>[1000000, 248000000, 491000000, 690000000, 881000000, 1062000000, 1233000000, 1392000000, 1538000000, 1679000000, 1814000000, 1948000000, 2081000000, 2195000000, 2301000000, 2402000000, 2490000000, 2569000000, 2645000000, 2709000000, 2772000000, 2819000000, 2868000000, 3023000000]
</code>```

However, when I try to modify the xticks, the plot becomes empty:

```<code>plt.xticks(binned_chrom_genome_pos)
</code>```

Modified heatmap

I also noticed that the x-axis labels do not correspond to the ticks specified.

Could someone assist me in plotting this properly?

答:
why the code does what it does

ax.get_xticks() returns the positions of the ticks. You can see that they are between 0.5 and 3000. These values refer to the index of your data. Large values, set by plt.xticks, or ax.set_xticks are still interpreted as data indices. So, if you have 10 rows of data, and set xticks to [0, 1000], the data in your figure will only occupy 1% of the x-range, hence disappearing. I am not sure if I am making myself clear, so I will give an example with synthetic data:

```<code>import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

#generating data
dic = {a:np.random.randint(0,1000,100) for a in range(0,1000000, 10000)}
genome_freq = pd.DataFrame(dic, index=range(0,1000000, 10000))

#plotting heatmaps
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))

sns.heatmap(genome_freq.applymap(lambda x: np.log10(x+1)),
            ax=ax1)

sns.heatmap(genome_freq.applymap(lambda x: np.log10(x+1)),
            ax=ax2)

old_ticks = ax2.get_xticks()
print(np.min(old_ticks), np.max(old_ticks), len(old_ticks)) # prints 0.5 99.5 34

ax2.set_xticks([0,300]) # setting xticks with values way larger than your index squishes your data

plt.show()
</code>```

what can be done to fix it

So, what you want to do, is to change the xticks based on the size of your data, and then overwrite xticklabels:

Given the new labels from your question:

```<code>new_labels = [1000000, 248000000, 491000000, 690000000, 881000000, 1062000000, 1233000000, 1392000000, 1538000000, 1679000000, 1814000000, 1948000000, 2081000000, 2195000000, 2301000000, 2402000000, 2490000000, 2569000000, 2645000000, 2709000000, 2772000000, 2819000000, 2868000000, 3023000000]

len(new_labels) # returns 24

fig, ax = plt.subplots(figsize=(4, 4))
sns.heatmap(genome_freq.applymap(lambda x: np.log10(x+1)),
            ax=ax)
</code>```

So, now we want 24 evenly spaced xticks between the former minimum and the former maximum. We can use np.linspace to achieve that:

```<code>old_ticks = ax.get_xticks()
new_ticks = np.linspace(np.min(old_ticks), np.max(old_ticks), len(new_labels))
ax.set_xticks(new_ticks)
ax.set_xticklabels(new_labels)
plt.show()
</code>```

Body:
I am trying to plot a seaborn heatmap with custom locations and labels on both axes. The dataframe looks like this:

Dataframe

I can plot this normally with seaborn.heatmap:

fig, ax = plt.subplots(figsize=(8, 8))
sns.heatmap(genome_freq.applymap(lambda x: np.log10(x+1)),
            ax=ax)
plt.show()

Normal heatmap

I have a list of positions I'd like to set as the xticks (binned_chrom_genome_pos):

[1000000, 248000000, 491000000, 690000000, 881000000, 1062000000, 1233000000, 1392000000, 1538000000, 1679000000, 1814000000, 1948000000, 2081000000, 2195000000, 2301000000, 2402000000, 2490000000, 2569000000, 2645000000, 2709000000, 2772000000, 2819000000, 2868000000, 3023000000]

However, when I try to modify the xticks, the plot becomes empty:

plt.xticks(binned_chrom_genome_pos)

Modified heatmap

I also noticed that the x-axis labels do not correspond to the ticks specified.

Could someone assist me in plotting this properly?

Body:
why the code does what it does

ax.get_xticks() returns the positions of the ticks. You can see that they are between 0.5 and 3000. These values refer to the index of your data. Large values, set by plt.xticks, or ax.set_xticks are still interpreted as data indices. So, if you have 10 rows of data, and set xticks to [0, 1000], the data in your figure will only occupy 1% of the x-range, hence disappearing. I am not sure if I am making myself clear, so I will give an example with synthetic data:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

#generating data
dic = {a:np.random.randint(0,1000,100) for a in range(0,1000000, 10000)}
genome_freq = pd.DataFrame(dic, index=range(0,1000000, 10000))

#plotting heatmaps
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))

sns.heatmap(genome_freq.applymap(lambda x: np.log10(x+1)),
            ax=ax1)

sns.heatmap(genome_freq.applymap(lambda x: np.log10(x+1)),
            ax=ax2)

old_ticks = ax2.get_xticks()
print(np.min(old_ticks), np.max(old_ticks), len(old_ticks)) # prints 0.5 99.5 34

ax2.set_xticks([0,300]) # setting xticks with values way larger than your index squishes your data

plt.show()

what can be done to fix it

So, what you want to do, is to change the xticks based on the size of your data, and then overwrite xticklabels:

Given the new labels from your question:

new_labels = [1000000, 248000000, 491000000, 690000000, 881000000, 1062000000, 1233000000, 1392000000, 1538000000, 1679000000, 1814000000, 1948000000, 2081000000, 2195000000, 2301000000, 2402000000, 2490000000, 2569000000, 2645000000, 2709000000, 2772000000, 2819000000, 2868000000, 3023000000]

len(new_labels) # returns 24

fig, ax = plt.subplots(figsize=(4, 4))
sns.heatmap(genome_freq.applymap(lambda x: np.log10(x+1)),
            ax=ax)

So, now we want 24 evenly spaced xticks between the former minimum and the former maximum. We can use np.linspace to achieve that:

old_ticks = ax.get_xticks()
new_ticks = np.linspace(np.min(old_ticks), np.max(old_ticks), len(new_labels))
ax.set_xticks(new_ticks)
ax.set_xticklabels(new_labels)
plt.show()


问:
Disabling `@tf.function` decorators for debugging?
In TensorFlow 2, the @tf.function decorator allows for Python functions to become TensorFlow graphs (more or less) and can lead to some performance improvements. However, when decorated this way, Python no longer traces the functions each time they run. This makes debugging the functions with Python debuggers a bit more difficult. Is there a way to disable all @tf.function decorators temporarily to allow for easy debugging?

答:
You could use a global boolean variable DEBUG and apply it to the autograph argument in @tf.function like this:

import tensorflow as tf
DEBUG = False

@tf.function(autograph=not DEBUG)
def foo(x):
    return x + 1
```

Otherwise, since it is autograph=True by default, not sure whether it is possible without modification of source code.

Body:
You could use a global boolean variable DEBUG and apply it to the autograph argument in @tf.function like this:

import tensorflow as tf
DEBUG = False

@tf.function(autograph=not DEBUG)
def foo(x):
    return x + 1

Otherwise, since it is autograph=True by default, not sure whether it is possible without modification of source code.


问:
DataGrid column width doesn't auto-update
```<code><DataGridTextColumn Binding="{Binding Name}" Width="*"/>
<DataGridTextColumn Binding="{Binding Change}" Width="Auto"/>
</code>```

When the value of Change updates, its column doesn't update to fit the new value. So the column stays too small and the value is clipped.

Any ideas?

答:
One way you could solve this is by defining the width property of the column in a style setting and binding that setting to a property of the object you are binding to.

```<code><DataGridTextColumn Binding="{Binding Change}" ElementStyle="{StaticResource ChangeColumnStyle}"/>
</code>```

In your ResourceDictionary:

```<code><Style TargetType="{x:Type DataGridTextColumn }" x:Key="ChangeColumnStyle">
   <Setter Property="Width" Value="{Binding ColumnWidth}"
</Style>
</code>```

ColumnWidth should be a property of your object. Now if you update this property from the setter of your 'Change' property (by using some self-defined algorithm, taking stuff like font into account), and calling:

```<code>RaisePropertyChanged("ColumnWidth");
</code>```

It should update your column width.

```<code> public int Change
   {
      get { return m_change; }
      set
      {
         if (m_change != value)
         {
            m_change = value;
            ColumnWidth = WidthAlgo(numberOfCharacters);
            RaisePropertyChanged("Change");
            RaisePropertyChanged("ColumnWidth");
         }
      }
   }
</code>```

Body:
<DataGridTextColumn Binding="{Binding Name}" Width="*"/>
<DataGridTextColumn Binding="{Binding Change}" Width="Auto"/>

When the value of Change updates, its column doesn't update to fit the new value. So the column stays too small and the value is clipped.

Any ideas?

Body:
One way you could solve this is by defining the width property of the column in a style setting and binding that setting to a property of the object you are binding to.

<DataGridTextColumn Binding="{Binding Change}" ElementStyle="{StaticResource ChangeColumnStyle}"/>

In your ResourceDictionary:

<Style TargetType="{x:Type DataGridTextColumn }" x:Key="ChangeColumnStyle">
   <Setter Property="Width" Value="{Binding ColumnWidth}"
</Style>

ColumnWidth should be a property of your object. Now if you update this property from the setter of your 'Change' property (by using some self-defined algorithm, taking stuff like font into account), and calling:

RaisePropertyChanged("ColumnWidth");

It should update your column width.

 public int Change
   {
      get { return m_change; }
      set
      {
         if (m_change != value)
         {
            m_change = value;
            ColumnWidth = WidthAlgo(numberOfCharacters);
            RaisePropertyChanged("Change");
            RaisePropertyChanged("ColumnWidth");
         }
      }
   }


问:
javascript parses date string with browser timezone
```<code>var dts = "2019-05-26" // this value came from browser query like "d=1&date=2019-05-26"

var date = new Date(dts)
console.log(JSON.stringify(date))
</code>```

which prints:

```<code>#=> "2019-05-25T19:00:00.0000Z"
</code>```

Problem

I get this date from user input. Format only contains year, month and day. Problem happens when user browser's timezone applied on parsing. Sometimes, I get correct date in a day but sometimes i get one day before. This causes wrong database querying.

How can I convert this Date object to UTC? Because I need it as a Date object not as a string.

Is there any library that can help me parsing dates at UTC and get back as Date Object?

答: Use Moment UTC to normalize the time</p>

Body:
var dts = "2019-05-26" // this value came from browser query like "d=1&date=2019-05-26"

var date = new Date(dts)
console.log(JSON.stringify(date))

which prints:

#=> "2019-05-25T19:00:00.0000Z"

Problem

I get this date from user input. Format only contains year, month and day. Problem happens when user browser's timezone applied on parsing. Sometimes, I get correct date in a day but sometimes i get one day before. This causes wrong database querying.

How can I convert this Date object to UTC? Because I need it as a Date object not as a string.

Is there any library that can help me parsing dates at UTC and get back as Date Object?

Body: Use Moment UTC to normalize the time


问:
Android source code submit patch
I want add a patch for android source code.
Have downloaded the code after the instruction from:
https://source.android.com/source/downloading.html

After that i follow the steps in:
http://source.android.com/source/submit-patches.html

When i should start a new repo branch:
repo start NAME .

I get error:
error: project . not found

Can someone tell me why?

答: This error will occur if you try to run the command repo start NAME . inside the WORKING_DIRECTORY folder. This is because the WORKING_DIRECTORY folder is not a git repository. You need to go to some inner folder in which there is a git repository you need. Inside the folder, that is the git repository, or in one of its parent folders, there must be a .git folder. For example, go to this folder: /frameworks/base/core/java/android/widget. Inside this folder, run the command repo start NAME .

Title: Android source code submit patch


问:
Angular 7 Forms - Conditionally require FormGroup
I am building a form where the user can set payment options. There is a dropdown to choose which payment method will be used.
For every payment mehod there is a FormGroup with options for the selected method:

```<code>form: FormGroup = new FormGroup({
        method: new FormControl('paypal', {
            validators: [
                Validators.required,
            ],
        }),
        paypal: new FormGroup({
            email: new FormControl(null, {
                validators: [
                    Validators.required,
                    Validators.pattern(EMAIL_PATTERN)
                ],
            }),
        }),
        other: new FormGroup({
            email: new FormControl(null, {
                validators: [
                    Validators.required,
                    Validators.pattern(EMAIL_PATTERN)
                ],
            }),
        }),
    });
</code>```

The issue here is, that the form will only be valid if both FormGroups are valid.

But the form should be valid as soon as the FormGroup for the selected payment method is valid.

答: Why not disable the controls that aren't needed - then they don't get validated?</p>

Body:
I am building a form where the user can set payment options. There is a dropdown to choose which payment method will be used.
For every payment mehod there is a FormGroup with options for the selected method:

form: FormGroup = new FormGroup({
        method: new FormControl('paypal', {
            validators: [
                Validators.required,
            ],
        }),
        paypal: new FormGroup({
            email: new FormControl(null, {
                validators: [
                    Validators.required,
                    Validators.pattern(EMAIL_PATTERN)
                ],
            }),
        }),
        other: new FormGroup({
            email: new FormControl(null, {
                validators: [
                    Validators.required,
                    Validators.pattern(EMAIL_PATTERN)
                ],
            }),
        }),
    });

The issue here is, that the form will only be valid if both FormGroups are valid.

But the form should be valid as soon as the FormGroup for the selected payment method is valid.


问:
What are preserved properties in NAnt?
What are preserved properties in NAnt?
Please help.</p>

答: Here is a list of the built-in properties: http://nant.sourceforge.net/release/latest/help/fundamentals/properties.html#built-in-properties</p>

ContentLicense: CC BY-SA 2.5

Title: What are preserved properties in NAnt?


问:
Iterating through an array of files
I am writing a program which displays some of my written poems into an JTextArea and whenever I press on JButton "Next" it should read another one of my poems into the JTextArea.

However I can only do it when I remove the filearray and read a single file only.

Creating an array of files and tried iterating by calling a number++ everytime I click on next. I've also filtrated by leaving out some irrelevant code.

```<code>public class PoemWindow extends JFrame implements ActionListener
{
    private int n=0;
    BufferedReader br;
    JTextArea textAreaOne;
    FileReader file[];
}

public PoemWindow() throws IOException{
    file[0] = new FileReader("C:/Poems/Freedom.txt");
    file[1] = new FileReader("C:/Poems/Masturbation.txt");
    file[2] = new FileReader("C:/Poems/Life.txt");
    file[3] = new FileReader("C:/Poems/Loneliness.txt");
    add(textAreaOne)
}

public void actionPerformed(ActionEvent e){
    if(e.getSource()==nextButton) {
        while(n<=4) {
            try {
                br = new BufferedReader(file[n]);
                textAreaOne.read(br,null);
                n++;
                textAreaOne.requestFocus();
            } catch(Exception b) {
                System.out.println("This is an error");
            }
        }
    }
</code>```

It works when I read a single file, but whenever I instantiate an file []
it gives me an NullPointerException and it won't even run...

答:
It works when I read a single file, but whenever I instantiate an file
  [] it gives me an NullPointerException and it won't even run...

Here's an example of creating the array w/ five slots (0 --> 4):

```<code>FileReader[] file = new FileReader[4];
</code>```

Title: Iterating through an array of files

Body:
I am writing a program which displays some of my written poems into an JTextArea and whenever I press on JButton "Next" it should read another one of my poems into the JTextArea.

However I can only do it when I remove the filearray and read a single file only.

Creating an array of files and tried iterating by calling a number++ everytime I click on next. I've also filtrated by leaving out some irrelevant code.

public class PoemWindow extends JFrame implements ActionListener
{
    private int n=0;
    BufferedReader br;
    JTextArea textAreaOne;
    FileReader file[];
}

public PoemWindow() throws IOException{
    file[0] = new FileReader("C:/Poems/Freedom.txt");
    file[1] = new FileReader("C:/Poems/Masturbation.txt");
    file[2] = new FileReader("C:/Poems/Life.txt");
    file[3] = new FileReader("C:/Poems/Loneliness.txt");
    add(textAreaOne)
}

public void actionPerformed(ActionEvent e){
    if(e.getSource()==nextButton) {
        while(n<=4) {
            try {
                br = new BufferedReader(file[n]);
                textAreaOne.read(br,null);
                n++;
                textAreaOne.requestFocus();
            } catch(Exception b) {
                System.out.println("This is an error");
            }
        }
    }

It works when I read a single file, but whenever I instantiate an file []
it gives me an NullPointerException and it won't even run...

Body:
It works when I read a single file, but whenever I instantiate an file
  [] it gives me an NullPointerException and it won't even run...

Here's an example of creating the array w/ five slots (0 --> 4):

FileReader[] file = new FileReader[4];


问:
Pygame KEYDOWN not being recognised
I am making a game in python pygame and I am on setting up the keyinput and have came across a part where I don't know what to do at all.

All of the variables are defined as there are no errors, but no key detections are being made at all so I don't know what to do.

I have had a look at other questions and tried there answers but haven't solved the problem yet

```<code>class Player(object):

    def __init__(self, x, y, velocity):
        self.x = x
        self.y = y

        self.width = 32
        self.height = 32

        self.velocity = velocity
        self.render()
        self.tick()

    def movement(self):
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                print("done")
                if event.key == pygame.K_w:
                    self.y -= self.velocity
                elif event.key == pygame.K_s:
                    self.y += self.velocity
                elif event.key == pygame.K_d:
                    self.x += self.velocity
                elif event.key == pygame.K_a:
                    self.x -= self.velocity
                elif event.key == pygame.K_ESCAPE:
                    pygame.quit()
            elif event.type == pygame.QUIT:
                pygame.quit()

    def tick(self):
        self.movement()

    def render(self):
        pygame.draw.rect(window.WINDOW, (255, 0, 0), (self.x, self.y,
        self.width, self.height))
        pygame.display.update()
</code>```

There are no errors but when it is supposed to print out "done" it doesn't so I think it has something to do with the KEYDOWN at the start or before that.

答:
Okay your code isn't complete, but I can see you're trying to move an image or object up,down,left,right on the pygame display. I recreated your code from what you gave here, and everything seems to be running fine I'm not sure about K_w,K_s,K_d,K_a keys though since I don't have the full code and you are concerned with it not printing 'done'. NOTE that I changed them to print something out instead of actually moving an object. the only errors I found is with your exit pygame.K_ESCAPE and pygame.QUIT events which is:

Traceback (most recent call last):   File
  "main.py", line 13, in
      for event in pygame.event.get(): pygame.error: video system not initialized

Solve this using pygame.quit() together with sys.exit(), first import sys on top of your code.

this how it looks and It prints out done on KEYDOWN:

```<code><code>
from pygame.locals import *
import pygame
import sys

pygame.init()

screen = pygame.display.set_mode((200,200))

while 1:
    for event in pygame.event.get():
        print(event) # logs every event happening on the pygame display

        if event.type == pygame.KEYDOWN:

            print("done")
            if event.key == pygame.K_w:
                print("self.y -= self.velocity") # not doesn't decrement it prints for testing
            elif event.key == pygame.K_s:
                print("self.y += self.velocity") # not doesn't increment it prints for testing
            elif event.key == pygame.K_d:
                print("self.x += self.velocity") # not doesn't increment it prints for testing
            elif event.key == pygame.K_a:
                print("self.x -= self.velocity") # not doesn't decrement it prints for testing
            elif event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit() # add this
            elif event.type == QUIT:
                pygame.quit()
                sys.exit() # add this
</code>
</code>```

Title: Pygame KEYDOWN not being recognised

Body:
I am making a game in python pygame and I am on setting up the keyinput and have came across a part where I don't know what to do at all.

All of the variables are defined as there are no errors, but no key detections are being made at all so I don't know what to do.

I have had a look at other questions and tried there answers but haven't solved the problem yet

class Player(object):

    def __init__(self, x, y, velocity):
        self.x = x
        self.y = y

        self.width = 32
        self.height = 32

        self.velocity = velocity
        self.render()
        self.tick()

    def movement(self):
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                print("done")
                if event.key == pygame.K_w:
                    self.y -= self.velocity
                elif event.key == pygame.K_s:
                    self.y += self.velocity
                elif event.key == pygame.K_d:
                    self.x += self.velocity
                elif event.key == pygame.K_a:
                    self.x -= self.velocity
                elif event.key == pygame.K_ESCAPE:
                    pygame.quit()
            elif event.type == pygame.QUIT:
                pygame.quit()

    def tick(self):
        self.movement()

    def render(self):
        pygame.draw.rect(window.WINDOW, (255, 0, 0), (self.x, self.y,
        self.width, self.height))
        pygame.display.update()

There are no errors but when it is supposed to print out "done" it doesn't so I think it has something to do with the KEYDOWN at the start or before that.

Body:
Okay your code isn't complete, but I can see you're trying to move an image or object up,down,left,right on the pygame display. I recreated your code from what you gave here, and everything seems to be running fine I'm not sure about K_w,K_s,K_d,K_a keys though since I don't have the full code and you are concerned with it not printing 'done'. NOTE that I changed them to print something out instead of actually moving an object. the only errors I found is with your exit pygame.K_ESCAPE and pygame.QUIT events which is:

Traceback (most recent call last):   File
  "main.py", line 13, in
      for event in pygame.event.get(): pygame.error: video system not initialized

Solve this using pygame.quit() together with sys.exit(), first import sys on top of your code.

this how it looks and It prints out done on KEYDOWN:

<code>
from pygame.locals import *
import pygame
import sys

pygame.init()

screen = pygame.display.set_mode((200,200))

while 1:
    for event in pygame.event.get():
        print(event) # logs every event happening on the pygame display

        if event.type == pygame.KEYDOWN:

            print("done")
            if event.key == pygame.K_w:
                print("self.y -= self.velocity") # not doesn't decrement it prints for testing
            elif event.key == pygame.K_s:
                print("self.y += self.velocity") # not doesn't increment it prints for testing
            elif event.key == pygame.K_d:
                print("self.x += self.velocity") # not doesn't increment it prints for testing
            elif event.key == pygame.K_a:
                print("self.x -= self.velocity") # not doesn't decrement it prints for testing
            elif event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit() # add this
            elif event.type == QUIT:
                pygame.quit()
                sys.exit() # add this
</code>


问:
String split of delimited values in 2 columns simultaneously - R
I'm looking for an elegant way to split and convert semicolon-separated values from two columns into rows. Data looks like as:

```<code>1        A0A024R442;E7ETB3;Q9ULA0;E7EMB6           443;465;447;382
2 A0A024R442;E7ETB3;Q9ULA0;E7EMB6;C9JBE1       323;345;327;262;309
</code>```

The required output is:

```<code>A0A024R442        443
    E7ETB3        465
    Q9ULA0        447
  ...................
    C9JBE1        309
</code>```

The number of elements in columns is always equal per row as depicted above. I have tried the strsplit() function but I think I can't split delimited values on multiple columns simultaneously (please correct me if I'm wrong).

I would appreciate any suggestion.

答:
The separate_rows can be used as well

```<code>library(tidyverse)
separate_rows(df1, c("V1", "V2"))
#          V1  V2
#1 A0A024R442 443
#2     E7ETB3 465
#3     Q9ULA0 447
#4     E7EMB6 382
#5 A0A024R442 323
#6     E7ETB3 345
#7     Q9ULA0 327
#8     E7EMB6 262
#9     C9JBE1 309
</code>```

Or using cSplit

```<code>library(splitstackshape)
cSplit(df1, c("V1", "V2"), ";", "long")
</code>```

data

```<code>df1 <- structure(list(V1 = c("A0A024R442;E7ETB3;Q9ULA0;E7EMB6",
      "A0A024R442;E7ETB3;Q9ULA0;E7EMB6;C9JBE1"
), V2 = c("443;465;447;382", "323;345;327;262;309")),
  row.names = c(NA,
-2L), class = "data.frame")
</code>```

Body:
I'm looking for an elegant way to split and convert semicolon-separated values from two columns into rows. Data looks like as:

1        A0A024R442;E7ETB3;Q9ULA0;E7EMB6           443;465;447;382
2 A0A024R442;E7ETB3;Q9ULA0;E7EMB6;C9JBE1       323;345;327;262;309

The required output is:

A0A024R442        443
    E7ETB3        465
    Q9ULA0        447
  ...................
    C9JBE1        309

The number of elements in columns is always equal per row as depicted above. I have tried the strsplit() function but I think I can't split delimited values on multiple columns simultaneously (please correct me if I'm wrong).

I would appreciate any suggestion.

Body:
The separate_rows can be used as well

library(tidyverse)
separate_rows(df1, c("V1", "V2"))
#          V1  V2
#1 A0A024R442 443
#2     E7ETB3 465
#3     Q9ULA0 447
#4     E7EMB6 382
#5 A0A024R442 323
#6     E7ETB3 345
#7     Q9ULA0 327
#8     E7EMB6 262
#9     C9JBE1 309

Or using cSplit

library(splitstackshape)
cSplit(df1, c("V1", "V2"), ";", "long")

data

df1 <- structure(list(V1 = c("A0A024R442;E7ETB3;Q9ULA0;E7EMB6",
      "A0A024R442;E7ETB3;Q9ULA0;E7EMB6;C9JBE1"
), V2 = c("443;465;447;382", "323;345;327;262;309")),
  row.names = c(NA,
-2L), class = "data.frame")


问:
Errors in HTML - red ending paragraph tags
This is my first webpage, and the end paragraph tags are red.

Can someone tell me what I have done wrong, please?

This is my code. It was working fine, but when I have tried to add some CSS to it, it started displaying my text in a weird way, so I assume it must have some errors in my code.

Engagement Pro

Frequently Asked Questions

Below you will find answers to the questions we get asked the most about Engagement Pro.

        Managers

Why can't log in?

A lead came through with no contact details, how do I remove it?

I have added a comment to an unlogged lead, why is it not excluded?

A guest enquired twice, but when I created the enquiry it didn't link to the other one.

Where do I find leads that are being added in my diary by reception?

        Sales associates

Why can't log in?

Why doesn't the 'Export to Pinnacle' button work?

Why do I have guests I know nothing about in my diary?

Is there an easier way to see my diary for today, other han changing the date range?

When adding an appointment, it doesn't show in my appointments diary

Why are the postcodes highlighted yellow or green sometimes?

        </ul

          Product geniuses

Why can't log in?

Why does my video have so little views?

Why can I not save a video?

For any other questions/suggestions please contact Steven Harris or Andreea Mitel.

```

答:
I found some code error in your code and fixed them with HTML comment. Hope now it will work fine for you! :)

Here one thing to remember that: ul elements are not legally allowed inside p elements. Here is the reason. In your code you also forget to close some tags/some end tags are missing.

Engagement Pro

Frequently Asked Questions

Below you will find answers to the questions we get asked the most about Engagement Pro.

Managers

Why can't log in?

A lead came through with no contact details, how do I remove it?

I have added a comment to an unlogged lead, why is it not excluded?

A guest enquired twice, but when I created the enquiry it didn't link to the other one.

Where do I find leads that are being added in my diary by reception?

Sales associates

Why can't log in?

Why doesn't the 'Export to Pinnacle' button work?

Why do I have guests I know nothing about in my diary?

Is there an easier way to see my diary for today, other han changing the date range?

When adding an appointment, it doesn't show in my appointments diary

Why are the postcodes highlighted yellow or green sometimes?

Product geniuses

Why can't log in?

Why does my video have so little views?

Why can I not save a video?

For any other questions/suggestions please contact Steven Harris or Andreea Mitel.

```

Body:
I found some code error in your code and fixed them with HTML comment. Hope now it will work fine for you! :)

Here one thing to remember that: ul elements are not legally allowed inside p elements. Here is the reason. In your code you also forget to close some tags/some end tags are missing.

<body>

  <header>
    <h1><a href="http://epro.motorparks.co.uk/?" title="Engagement Pro">Engagement Pro</a></h1>
  </header>

  <section>
    <h2>Frequently Asked Questions</h2>
    <h3>Below you will find answers to the questions we get asked the most about Engagement Pro.</h3>
    <div>

      <p>Managers</p>
      <!-- Properly closing <p> -->
      <ul>
        <li>Why can't log in?</li>
        <li>A lead came through with no contact details, how do I remove it?</li>
        <li>I have added a comment to an unlogged lead, why is it not excluded?</li>
        <li>A guest enquired twice, but when I created the enquiry it didn't link to the other one.</li>
        <li>Where do I find leads that are being added in my diary by reception?</li>
      </ul>

      <p>Sales associates</p>
      <!-- Properly closing <p> -->
      <ul>
        <li>Why can't log in?</li>
        <li>Why doesn't the 'Export to Pinnacle' button work?</li>
        <li>Why do I have guests I know nothing about in my diary?</li>
        <li>Is there an easier way to see my diary for today, other han changing the date range?</li>
        <li>When adding an appointment, it doesn't show in my appointments diary</li>
        <li>Why are the postcodes highlighted yellow or green sometimes?</li>
      </ul>
      <!-- <ul> was not properly closed -->

      <p>Product geniuses</p>
      <!-- Properly closing <p> -->
      <ul>
        <li>Why can't log in?</li>
        <li>Why does my video have so little views?</li>
        <li>Why can I not save a video?</li>
      </ul>

      <p>For any other questions/suggestions please contact Steven Harris or Andreea Mitel.</p>
    </div>
    <!-- Closing <div> was missing -->
  </section>
  <footer>
  </footer>
</body>


问:
detect cycle in directed graph with non-recursive dfs
My code is working but not for all test cases.

What I am trying to do here is creating a 'boolean ifparent array' which holds the record of the path I am traversing through.

'boolean visited array' keeps record of all the visited vertices.

I am using a stack for DFS.

```<code>//v is no of vertex, adj[] is the adjacency matrix
bool isCyclic(int v, vector<int> adj[])
{
    stack<int> st;
    st.push(0);

    vector<bool> visited(v, false);
    vector<bool> ifparent(v, false);
    int flag= 0;

    int s;
    while(!st.empty()){
        s= st.top();
        ifparent[s]= true;
        visited[s]=true;
        flag=0;

        for(auto i: adj[s]){
            if(visited[i]){
                if(ifparent[i])
                    return true;
            }
            else if(!flag){
                st.push(i);
                flag= 1;
            }
        }

        if(!flag){
            ifparent[s]= false;
            st.pop();
        }
    }

    return false;

}
</code>```

答:
If you like an iterative approach of cycle detection with DFS, I will recommend you a little reorganized version of your code, where I write DFS in a more common manner.  </p>

```<code>bool isCyclic(int V, vector<int> adj[]) {
  vector<bool> visited (V, false);
  vector<bool> on_stack (V, false);
  stack<int> st;

  for (int w = 0; w < V; w++) {

    if (visited[w])
      continue;
    st.push(w);

    while (!st.empty()) {
      int s = st.top();

      if (!visited[s]) {
        visited[s] = true;
        on_stack[s] = true;
      } else {
        on_stack[s] = false;
        st.pop();
      }

      for (const auto &v : adj[s]) {
        if (!visited[v]) {
          st.push(v);
        } else if (on_stack[v]) {
          return true;
        }
      }
    }
  }
  return false;
}
</code>```

Body:
My code is working but not for all test cases.

What I am trying to do here is creating a 'boolean ifparent array' which holds the record of the path I am traversing through.

'boolean visited array' keeps record of all the visited vertices.

I am using a stack for DFS.

//v is no of vertex, adj[] is the adjacency matrix
bool isCyclic(int v, vector<int> adj[])
{
    stack<int> st;
    st.push(0);

    vector<bool> visited(v, false);
    vector<bool> ifparent(v, false);
    int flag= 0;

    int s;
    while(!st.empty()){
        s= st.top();
        ifparent[s]= true;
        visited[s]=true;
        flag=0;

        for(auto i: adj[s]){
            if(visited[i]){
                if(ifparent[i])
                    return true;
            }
            else if(!flag){
                st.push(i);
                flag= 1;
            }
        }

        if(!flag){
            ifparent[s]= false;
            st.pop();
        }
    }

    return false;

}

Body:
If you like an iterative approach of cycle detection with DFS, I will recommend you a little reorganized version of your code, where I write DFS in a more common manner.

bool isCyclic(int V, vector<int> adj[]) {
  vector<bool> visited (V, false);
  vector<bool> on_stack (V, false);
  stack<int> st;

  for (int w = 0; w < V; w++) {

    if (visited[w])
      continue;
    st.push(w);

    while (!st.empty()) {
      int s = st.top();

      if (!visited[s]) {
        visited[s] = true;
        on_stack[s] = true;
      } else {
        on_stack[s] = false;
        st.pop();
      }

      for (const auto &v : adj[s]) {
        if (!visited[v]) {
          st.push(v);
        } else if (on_stack[v]) {
          return true;
        }
      }
    }
  }
  return false;
}


问:
Unpack, modify and re-pack files in an MSI?
I'm trying to figure out the easiest and most secure way to Authenticode sign binaries in one of my projects.

The easiest way I can see to do this is to grab the result of compilation--a completed install package containing all my binaries--extract the assemblies from it, sign them, then repack these signed assemblies in the MSI which then gets signed.

Lots of information out there about unpacking files from an MSI, but nothing about re-packing them.  How can I do it?

答:
You don't state what your build system is, but the (overly simplified) flow my projects go through are as follows (I use nant tasks for pretty much everything, triggered from CruiseControl.net)

Grab everything from source control

Build clean project

Grab unsigned files

Using signtool.exe sign all relevant files (e.g. exe, dll, ocx)

Build MSI (with WiX)

Do some custom post-build tasks on the MSI

Digitally sign the MSI

(Depending on build parameters) Compress MSI with a bootstrapper

Sign the bootstrapper

Upload to a staging area

Email Dev+QA teams that build is ready for testing.

If it fails anywhere along the way, then just email the Dev team.

You should be able to do this with MSBuild, Nant, or a variety of other tools. It'll probably involve a little custom work in places, but the end result is a reliable build system that requires zero human interaction with the build (unless someone wants to 'force' a build, even that is just clicking a button on a webpage or something)


问:
My UPDATE SQL statement results in a syntax error
The code is to update a MySQL database table.

```<code> $sql = "UPDATE test
            SET EmailID = :EmailID,
              Localite = :Localite,
              Nom = :Nom,
              Statut = :Statut,
            WHERE EmailID = :EmailID";
</code>```

The error is:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE EmailID = 'haha@haha.com''

There should not have been any error displayed.

答:
Remove the comma after Statut = :Statut,

```<code>$sql = "UPDATE test
        SET EmailID = :EmailID,
            Localite = :Localite,
            Nom = :Nom,
            Statut = :Statut
        WHERE EmailID = :EmailID";
</code>```

Body:
The code is to update a MySQL database table.

 $sql = "UPDATE test
            SET EmailID = :EmailID,
              Localite = :Localite,
              Nom = :Nom,
              Statut = :Statut,
            WHERE EmailID = :EmailID";

The error is:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE EmailID = 'haha@haha.com''

There should not have been any error displayed.

Body:
Remove the comma after Statut = :Statut,

$sql = "UPDATE test
        SET EmailID = :EmailID,
            Localite = :Localite,
            Nom = :Nom,
            Statut = :Statut
        WHERE EmailID = :EmailID";


问:
Receive different type of XML request in a orchestration
I have a Biztalk which had issues with handling  large XML message requests. So I have planned to use a custom pipeline component which saves the message to a temporary directory if the request is more than some specified size, then it creates a small XML which contains path to this temporary large file. If message is small then it sends as it is received.(
https://www.codeproject.com/Articles/180216/Transfer-Large-Files-using-BizTalk-Receive-Side)

But the problem I am facing now is how to receive this two different schema XML in the orchestration. In my existing orchestration I used to recive XML with specific schema only as I always wanted to get request of specific type. But now I receive XML of two different types. One is the the request XML I receive when size of request is small. One more is the small XML with large file path I receive from pipeline when file size is large.

I tried setting the message type in the recieve side of orchestration to system.xml.xmldocument so that it can receive any type of XML instead of XML with specific schema. It looks to solve the issue but I think this is not ideal solution as it can receive any type of XML request. So I need good approaches to solve the issue mentioned above.

答: Start with a Listen Shape in your orchestration. Then for each message type, place a receive shape (with Activate = true) in a separate branch of the listen shape. </p>


问:
Get selected multiple posts/pages by ID in Wordpress API using React/Javascript
So, I'm having no trouble getting all posts from my WP API using this endpoint:

```<code>`${appUrl}/wp-json/wp/v2/pages`;
</code>```

But, I can't for the life of me figure out the syntax to query multiple, specific pages by ID,
I've been trawling for hours now - is this even possible (of course it is - I'm just being a numpty)??

Any tips would be most welcome.

Cheers

Terry

答:
I know this is like a year ago but i couldn't seem to find a way to get all pages by id and came across this post, i tried the include[]=123&include[]=321 but it just returned blank, I finally found out you have to add a status. in my case i choose any. Hope this helps someone.</p>

```<code>/wp-json/wp/v2/pages?status=any&include[]=129&include[]=131
</code>```

Body:
So, I'm having no trouble getting all posts from my WP API using this endpoint:

`${appUrl}/wp-json/wp/v2/pages`;

But, I can't for the life of me figure out the syntax to query multiple, specific pages by ID,
I've been trawling for hours now - is this even possible (of course it is - I'm just being a numpty)??

Any tips would be most welcome.

Cheers

Terry

Body:
I know this is like a year ago but i couldn't seem to find a way to get all pages by id and came across this post, i tried the include[]=123&include[]=321 but it just returned blank, I finally found out you have to add a status. in my case i choose any. Hope this helps someone.

/wp-json/wp/v2/pages?status=any&include[]=129&include[]=131


问:
Cannot step into .NET framework source with VS2008 SP1
Somehow my VS2008 SP1 has lost the ability to step into .NET framework sources. I've played around with checkboxes to no end; I've re-deleted the Symbol cache folder a dozen times; and I've tried all kinds of debug symbol servers.

All it does is download some .PDB files, but when I try to select a stack frame in .NET, I always get the message about no source available and "do you want to view disassembly".

What gives?

Added: Web application; Windows Vista Business x32; .NET 3.5 SP1.

答: I've noticed that if this issue occurs when you're running a website, enabling HTTP keep-alives in IIS can fix it.</p>

OwnerDisplayName: Vilx-

LastEditorDisplayName: moocha


问:
What exaclty does the execute() function in php do?
I have a html website with a formular with an action to a php script.
What I want to do is to write the data from the formular in a mySQL database on my localhost.

I know the database is accessable and the data is provided to the php script correctly (I'm using MAMP server for database and files).
The prepare-statement is correct as far as I could figure it out.
The 'id' in the execute statement is an auto-increment, therefore I set it to NULL.

$link is the db-access from db_connection.php

```<code><?php
    include("db_connection.php");
?>

<html>
    <header>
        <meta charset="utf-8">
        <title>Stackoverflow Code</title>
    </header>
    <body>
        <?php
            $name           = $_POST['name'];
            $timeUnits      = $_POST['timeUnits'];
            $description    = $_POST['description'];

            $eintrag = $link->prepare("INSERT INTO `projekt`(`id`,`time-units`, `beschreibung`, `name`) VALUES (?,?,?,?)");
            echo "It's working fine till this line";
            $eintrag->execute([NULL, $timeUnits, $description, $name]);
        ?>
    </body>
</html>
</code>```

I expected it to write data in the database but what I get is an internal server error (ERROR 500) that instantly vanished from the browser console and a blank website.

答:
You can look at the error log on the webserver to see the mysql error or put execute in a try catch block to catch the exception.

the error is probably from saying id = null since you can't have a null primary key
you need to leave out id all together and it will auto increment.

```<code>$eintrag = $link->prepare("INSERT INTO `projekt`(`time-units`, `beschreibung`, `name`) VALUES (?,?,?)");
$eintrag->execute([$timeUnits, $description, $name]);
</code>```

Execute takes the query, puts in the parameters where the "?" are and then runs it. Would link to the docs but without db connect file I dont know if your using mysqli or pdo.

Body:
I have a html website with a formular with an action to a php script.
What I want to do is to write the data from the formular in a mySQL database on my localhost.

I know the database is accessable and the data is provided to the php script correctly (I'm using MAMP server for database and files).
The prepare-statement is correct as far as I could figure it out.
The 'id' in the execute statement is an auto-increment, therefore I set it to NULL.

$link is the db-access from db_connection.php

<?php
    include("db_connection.php");
?>

        <meta charset="utf-8">
        <title>Stackoverflow Code</title>

        <?php
            $name           = $_POST['name'];
            $timeUnits      = $_POST['timeUnits'];
            $description    = $_POST['description'];

            $eintrag = $link->prepare("INSERT INTO `projekt`(`id`,`time-units`, `beschreibung`, `name`) VALUES (?,?,?,?)");
            echo "It's working fine till this line";
            $eintrag->execute([NULL, $timeUnits, $description, $name]);
        ?>

I expected it to write data in the database but what I get is an internal server error (ERROR 500) that instantly vanished from the browser console and a blank website.

Body:
You can look at the error log on the webserver to see the mysql error or put execute in a try catch block to catch the exception.

the error is probably from saying id = null since you can't have a null primary key
you need to leave out id all together and it will auto increment.

$eintrag = $link->prepare("INSERT INTO `projekt`(`time-units`, `beschreibung`, `name`) VALUES (?,?,?)");
$eintrag->execute([$timeUnits, $description, $name]);

Execute takes the query, puts in the parameters where the "?" are and then runs it. Would link to the docs but without db connect file I dont know if your using mysqli or pdo.


问:
How to construct a list of tuples of all possible combinations
I just can't come up with a way to solve my problem: x is an integer. I want a list of all possibles combinations of  x-tuples where those tuples' elements are in range from 0 to x (excluding x).

So if x = 3 I have 3^3 combinations: [(0,0,0),(0,0,1),(0,0,2),(0,1,0),(0,1,1),(0,1,2),(0,2,0),(0,2,1),(0,2,2),(1,0,0),(1,0,1),(1,0,2),(1,1,0),(1,1,1),(1,1,2),(1,2,0),(1,2,1),(1,2,2),(2,0,0),(2,0,1),(2,0,2),(2,1,0),(2,1,1),(2,1,2),(2,2,0),(2,2,1),(2,2,2)].

If x = 4 I would have 4^4 combinations with 4-tuples where the elements of those tuples are in {0,1,2,3}.

答:
I think it's just a list comprehension:

```<code>mylist = [(x,y,z) for x in range(3) for y in range(3) for z in range(3)]
</code>```

Note that using itertools.permutations(range(3)) doesn't generate duplicates, just the permutations of the set (0, 1, 2). I.e. you won't get (1, 1, 2), etc.

Body:
I think it's just a list comprehension:

mylist = [(x,y,z) for x in range(3) for y in range(3) for z in range(3)]

Note that using itertools.permutations(range(3)) doesn't generate duplicates, just the permutations of the set (0, 1, 2). I.e. you won't get (1, 1, 2), etc.