问:
Reshape the data from long to wide format
I am looking for swift way of reshaping the data from long to wide format. Right now I have tried a code with nest for loops, though the job gets done, it takes a long time to generate the output.

```<code>SN NN EE Service_tier
A  B  C  economy
B  C  C  economy
P  Q  R  regular
Q  S  R  regular
S  R  R  regular
H  I  L  economy
I  J  L  economy
J  K  L  economy
K  L  L  economy
</code>```

The output expected is as below

```<code>SN hop1 hop2 hop3 hop4 service_tier
A   B    C              economy
P   Q    S    R         regular
H   I    J    K    L    economy
</code>```

currently the below code gets the job done. Am sure there is an effective and clean way to do this.

```<code>for (i in 1:lasrow){
  sn <- raw_d[i,1]
  nn <- raw_d[i,2]
  en <- raw_d[i,3]

  lc <- 1

  if(nn == en){
    d[lr,lc]<-sn
    d[lr,lc+1]<-nn
    d[lr,lc+2]<-en
    lr <- lr+1
  }
  else{
    while(nn!=en){
      d[lr,lc]<-sn
      lc <- lc+1
      next_d <- filter(raw_d,raw_d$SN==sn,raw_d$EN==en)
      if(dim(next_d)[1]==0){
        d[lr,lc]<-"broken bf"
        lc <- lc+1
        break
      }else{
        sn <- next_d$NN
        nn <- next_d$NN
        }
      }
    d[lr,lc]<-en
    lr<-lr+1
  }
}
</code>```

答:
The crucial point here is to identify which rows belong to which group. The answers by Ronak and akrun both use rleid(Service_tier) assuming that a change in Service_tier indicate the begin of a new group.

This might be suggested by the sample dataset but cannot be taken as guaranteed. IMHO, Service_tier is rather an attribute than a key. As a matter of fact, the OP is testing for NN == EE in his code snippet to switch to a new group.

In the data.table solutions below, grouping is determined by cumsum(shift(NN == EE, fill = TRUE)) which tests for equality fo NN and EE, lags the result to the next row where the next group starts, and enumerates the groups by counting TRUE using cumsum().

In the simplified version (without reshaping), the hops are aggregated by the toString() function:

```<code>library(data.table)
setDT(d)[, .(SN = first(SN), hops = toString(NN), Service_tier = first(Service_tier)),
  by = .(grp = cumsum(shift(NN == EE, fill = TRUE)))][]
</code>```

```<code>   grp SN       hops Service_tier
1:   1  A       B, C      economy
2:   2  P    Q, S, R      regular
3:   3  H I, J, K, L      economy
</code>```

For reshaping from long to wide format, dcast() is used:

```<code>library(data.table)
library(magrittr)   # piping used to improve readability
w <- setDT(d)[, .(SN = first(SN), hops = NN, Service_tier = first(Service_tier)),
  by = .(grp = cumsum(shift(NN == EE, fill = TRUE)))] %>%
  dcast(grp + ... ~ rowid(grp, prefix = "hop"), value.var = "hops", fill = "")  %>%
  setcolorder(c(1:2, 4:ncol(.), 3))

w
</code>```

```<code>   grp SN hop1 hop2 hop3 hop4 Service_tier
1:   1  A    B    C                economy
2:   2  P    Q    S    R           regular
3:   3  H    I    J    K    L      economy
</code>```

setcolorder() is used to rearrange columns in the order expected by the OP. This is done in-place, i.e., without copying the whole data object.

Data

```<code>library(data.table)

d <- fread("SN NN EE Service_tier
A  B  C  economy
B  C  C  economy
P  Q  R  regular
Q  S  R  regular
S  R  R  regular
H  I  L  economy
I  J  L  economy
J  K  L  economy
K  L  L  economy")
</code>```

Body:
I am looking for swift way of reshaping the data from long to wide format. Right now I have tried a code with nest for loops, though the job gets done, it takes a long time to generate the output.

SN NN EE Service_tier
A  B  C  economy
B  C  C  economy
P  Q  R  regular
Q  S  R  regular
S  R  R  regular
H  I  L  economy
I  J  L  economy
J  K  L  economy
K  L  L  economy

The output expected is as below

SN hop1 hop2 hop3 hop4 service_tier
A   B    C              economy
P   Q    S    R         regular
H   I    J    K    L    economy

currently the below code gets the job done. Am sure there is an effective and clean way to do this.

for (i in 1:lasrow){
  sn <- raw_d[i,1]
  nn <- raw_d[i,2]
  en <- raw_d[i,3]

  lc <- 1

  if(nn == en){
    d[lr,lc]<-sn
    d[lr,lc+1]<-nn
    d[lr,lc+2]<-en
    lr <- lr+1
  }
  else{
    while(nn!=en){
      d[lr,lc]<-sn
      lc <- lc+1
      next_d <- filter(raw_d,raw_d$SN==sn,raw_d$EN==en)
      if(dim(next_d)[1]==0){
        d[lr,lc]<-"broken bf"
        lc <- lc+1
        break
      }else{
        sn <- next_d$NN
        nn <- next_d$NN
        }
      }
    d[lr,lc]<-en
    lr<-lr+1
  }
}

Body:
The crucial point here is to identify which rows belong to which group. The answers by Ronak and akrun both use rleid(Service_tier) assuming that a change in Service_tier indicate the begin of a new group.

This might be suggested by the sample dataset but cannot be taken as guaranteed. IMHO, Service_tier is rather an attribute than a key. As a matter of fact, the OP is testing for NN == EE in his code snippet to switch to a new group.

In the data.table solutions below, grouping is determined by cumsum(shift(NN == EE, fill = TRUE)) which tests for equality fo NN and EE, lags the result to the next row where the next group starts, and enumerates the groups by counting TRUE using cumsum().

In the simplified version (without reshaping), the hops are aggregated by the toString() function:

library(data.table)
setDT(d)[, .(SN = first(SN), hops = toString(NN), Service_tier = first(Service_tier)),
  by = .(grp = cumsum(shift(NN == EE, fill = TRUE)))][]

   grp SN       hops Service_tier
1:   1  A       B, C      economy
2:   2  P    Q, S, R      regular
3:   3  H I, J, K, L      economy

For reshaping from long to wide format, dcast() is used:

library(data.table)
library(magrittr)   # piping used to improve readability
w <- setDT(d)[, .(SN = first(SN), hops = NN, Service_tier = first(Service_tier)),
  by = .(grp = cumsum(shift(NN == EE, fill = TRUE)))] %>%
  dcast(grp + ... ~ rowid(grp, prefix = "hop"), value.var = "hops", fill = "")  %>%
  setcolorder(c(1:2, 4:ncol(.), 3))

w

   grp SN hop1 hop2 hop3 hop4 Service_tier
1:   1  A    B    C                economy
2:   2  P    Q    S    R           regular
3:   3  H    I    J    K    L      economy

setcolorder() is used to rearrange columns in the order expected by the OP. This is done in-place, i.e., without copying the whole data object.

Data

library(data.table)

d <- fread("SN NN EE Service_tier
A  B  C  economy
B  C  C  economy
P  Q  R  regular
Q  S  R  regular
S  R  R  regular
H  I  L  economy
I  J  L  economy
J  K  L  economy
K  L  L  economy")


来源: stackexchange

问:
How to merge two columns of JTable
I am retriving data from database.TableName:Contacts. There are two fields of this table.First_Name and Last_Name. I want to merge these two columns and want one column of JTable as Full Name.I've tried to create concat sql query,which was:

```<code>String queryMerge="select (First_Name||Last_Name) as Full_Name from Contacts";
</code>```

But it gave me an error:

```<code>[Microsoft][ODBC Microsoft access driver] Invalid use of vertical bars in query expression '(First_Name||Last_Name)'
</code>```

I thought to store all retrieved data in vector and use that values to build JTable.I am using AbstractTableModel.Is there any other way to solve this problem?

答:
Depends on how simplistic this application is.  If you're doing something small, then trying to concatenate in the query is fine.

If this query is going to be used in many different places I really would consider returning the individual fields and then use a custom TableModel that will do the first and last name concatenation for you.  That way in the future you won't have different sql queries for different views.  Just one query, that is manipulated by the view to display what it needs.  (Hopefully...)

ContentLicense: CC BY-SA 3.0

Title: How to merge two columns of JTable

Body:
I am retriving data from database.TableName:Contacts. There are two fields of this table.First_Name and Last_Name. I want to merge these two columns and want one column of JTable as Full Name.I've tried to create concat sql query,which was:

String queryMerge="select (First_Name||Last_Name) as Full_Name from Contacts";

But it gave me an error:

[Microsoft][ODBC Microsoft access driver] Invalid use of vertical bars in query expression '(First_Name||Last_Name)'

I thought to store all retrieved data in vector and use that values to build JTable.I am using AbstractTableModel.Is there any other way to solve this problem?


问:
How to change query plan before execution (possibly turning an optimization off)?
I have a simple spark SQL query :

```<code>SELECT x, y
FROM t1 INNER JOIN t2 ON t1.key = t2.key
WHERE expensiveFunction(t1.key)
</code>```

Where expensiveFunction is a spark UDF (User-defined function).

When I look at the query plan generated by spark, I see that it has two filter operations instead of just one: it checks not only expensiveFunction(t1.key), but also expensiveFunction(t2.key).

In general, this optimization is not a bad thing, because it reduces the number of records to join, and joining is an expensive operation. But in my case expensiveFunction(t2.key) always returns true, so I would like to remove it.

Is there a way to change the query plan before executing a query ? Is there a way to indicate to spark that I don’t want a given optimization to be applied to my query ?

答:
This is happening because of the optimizer rule org.apache.spark.sql.catalyst.optimizer.InferFiltersFromConstraints
Code comments is as follows(github)

```<code>  /**
   * Infers an additional set of constraints from a given set of equality constraints.
   * For e.g., if an operator has constraints of the form (`a = 5`, `a = b`), this returns an
   * additional constraint of the form `b = 5`.
   */
  def inferAdditionalConstraints(constraints: Set[Expression]): Set[Expression]
</code>```

You could disable this Optimizer rule using spark.sql.optimizer.excludedRules

val OPTIMIZER_EXCLUDED_RULES = buildConf("spark.sql.optimizer.excludedRules")
     .doc("Configures a list of rules to be disabled in the optimizer, in which the rules are " +
       "specified by their rule names and separated by comma. It is not guaranteed that all the " +
       "rules in this configuration will eventually be excluded, as some rules are necessary " +
       "for correctness. The optimizer will log the rules that have indeed been excluded.")
     .stringConf
     .createOptional
  That way the filter will not get propagated to both sids of join

Body:
I have a simple spark SQL query :

SELECT x, y
FROM t1 INNER JOIN t2 ON t1.key = t2.key
WHERE expensiveFunction(t1.key)

Where expensiveFunction is a spark UDF (User-defined function).

When I look at the query plan generated by spark, I see that it has two filter operations instead of just one: it checks not only expensiveFunction(t1.key), but also expensiveFunction(t2.key).

In general, this optimization is not a bad thing, because it reduces the number of records to join, and joining is an expensive operation. But in my case expensiveFunction(t2.key) always returns true, so I would like to remove it.

Is there a way to change the query plan before executing a query ? Is there a way to indicate to spark that I don’t want a given optimization to be applied to my query ?

Body:
This is happening because of the optimizer rule org.apache.spark.sql.catalyst.optimizer.InferFiltersFromConstraints
Code comments is as follows(github)

  /**
   * Infers an additional set of constraints from a given set of equality constraints.
   * For e.g., if an operator has constraints of the form (`a = 5`, `a = b`), this returns an
   * additional constraint of the form `b = 5`.
   */
  def inferAdditionalConstraints(constraints: Set[Expression]): Set[Expression]

You could disable this Optimizer rule using spark.sql.optimizer.excludedRules

val OPTIMIZER_EXCLUDED_RULES = buildConf("spark.sql.optimizer.excludedRules")
     .doc("Configures a list of rules to be disabled in the optimizer, in which the rules are " +
       "specified by their rule names and separated by comma. It is not guaranteed that all the " +
       "rules in this configuration will eventually be excluded, as some rules are necessary " +
       "for correctness. The optimizer will log the rules that have indeed been excluded.")
     .stringConf
     .createOptional
  That way the filter will not get propagated to both sids of join

ContentLicense: CC BY-SA 4.0


问:
Ansible : how to pass "{{ABC}}" as a string
Under my jinja file i ve this line

```<code>- mockString= "{{ABC}}"
</code>```

My mockString must have the exacte value "{{ABC}}" where the first letter is " , the second is { the third is also {  ect...

Now when converting my template file ; it seems that i sees "{{ABC}}" as a variable , where it tries to interpret and change by its value , what is not my purpose.

How may i pass it as a simple string

Suggestions ??

答: Try passing it like this {{'"{{ABC}}"'}} this should work

Body:
Under my jinja file i ve this line

- mockString= "{{ABC}}"

My mockString must have the exacte value "{{ABC}}" where the first letter is " , the second is { the third is also {  ect...

Now when converting my template file ; it seems that i sees "{{ABC}}" as a variable , where it tries to interpret and change by its value , what is not my purpose.

How may i pass it as a simple string

Suggestions ??


问:
Is there a way to have currency conversions from Google Finance stick?
I need to find a way to automatically copy the output of the below GoogleFinance formula into another cell and make it stick, i.e. doesn't change when the exchange rate changes.

```<code>=A1*GOOGLEFINANCE("currency:AUDGBP")
</code>```

I was going to use something like =value(x) but this would change every time the above formula generated a new value, whereas I want something to stick as soon as it's output an answer.

答:
if you want to play with button and script then:

```<code>function moveValuesOnly() { var ss = SpreadsheetApp.getActiveSpreadsheet();
                            var source = ss.getRange('Sheet1!A1');
                            source.copyTo(ss.getRange('Sheet2!A1'), {contentsOnly: true}); }
</code>```

which will copy the value from Sheet1!A1 into Sheet2!A1

otherwise CTRL + C and CTRL +
   SHIFT + V for manual copy

Body:
I need to find a way to automatically copy the output of the below GoogleFinance formula into another cell and make it stick, i.e. doesn't change when the exchange rate changes.

=A1*GOOGLEFINANCE("currency:AUDGBP")

I was going to use something like =value(x) but this would change every time the above formula generated a new value, whereas I want something to stick as soon as it's output an answer.

Body:
if you want to play with button and script then:

function moveValuesOnly() { var ss = SpreadsheetApp.getActiveSpreadsheet();
                            var source = ss.getRange('Sheet1!A1');
                            source.copyTo(ss.getRange('Sheet2!A1'), {contentsOnly: true}); }

which will copy the value from Sheet1!A1 into Sheet2!A1

otherwise CTRL + C and CTRL +
   SHIFT + V for manual copy


问:
How to access property inside property?
I have a model class like this:

```<code>public class MapModel
{
    public Field[] Fields { get; set; }
}

public class Field
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Node[] Nodes { get; set; }
    public string Icon { get; set; }
}

public class Node
{
    public float Long { get; set; }
    public float Lat { get; set; }
}
</code>```

In my view model I'm calling a service to get some map data and ObservableCollection like:

```<code>public ObservableCollection<Field> FieldsCollection { get; set; } = new ObservableCollection<Field>();

var mapData = await MapService.GetMapData(token, "sr");

foreach (var md in mapData.Fields)
{
    FieldsCollection.Add(md);
    PinIcon = Icon;
}
</code>```

Now I'm trying to set values Long and Lat from Node for position of Pin on map...

```<code>public void LoadMapTab()
{
    foreach (var item in FieldsCollection)
    {
        var pin = new Pin
                      {
                          Label = item.Name,
                          Position = new Position(/* SET VALUES FROM NODE LONG AND LAT*/),
                          Icon = BitmapDescriptorFactory.FromBundle(PinIcon)
                      };

        _map.Pins.Add(pin);
        Device.StartTimer(TimeSpan.FromMilliseconds(500), () =>
            {
                _map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(/* SET VALUES FROM NODE LONG AND LAT*/),
                Distance.FromKilometers(8)));
                return false;
            });
    }
}
</code>```

So, my question is how to access the Long and Lat values and set them in

```<code>Position = new Position(.......)
</code>```

答:
item is a Field, so it has a Nodes array.  You can use an indexer [] to specify an index in the array

```<code>Position = new Position(item.Nodes[0].Lat, item.Nodes[0].Long),
</code>```

note, attribtute has a specific meaning in C#.  These are properties, not attributes

Title: How to access property inside property?

Body:
I have a model class like this:

public class MapModel
{
    public Field[] Fields { get; set; }
}

public class Field
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Node[] Nodes { get; set; }
    public string Icon { get; set; }
}

public class Node
{
    public float Long { get; set; }
    public float Lat { get; set; }
}

In my view model I'm calling a service to get some map data and ObservableCollection like:

public ObservableCollection<Field> FieldsCollection { get; set; } = new ObservableCollection<Field>();

var mapData = await MapService.GetMapData(token, "sr");

foreach (var md in mapData.Fields)
{
    FieldsCollection.Add(md);
    PinIcon = Icon;
}

Now I'm trying to set values Long and Lat from Node for position of Pin on map...

public void LoadMapTab()
{
    foreach (var item in FieldsCollection)
    {
        var pin = new Pin
                      {
                          Label = item.Name,
                          Position = new Position(/* SET VALUES FROM NODE LONG AND LAT*/),
                          Icon = BitmapDescriptorFactory.FromBundle(PinIcon)
                      };

        _map.Pins.Add(pin);
        Device.StartTimer(TimeSpan.FromMilliseconds(500), () =>
            {
                _map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(/* SET VALUES FROM NODE LONG AND LAT*/),
                Distance.FromKilometers(8)));
                return false;
            });
    }
}

So, my question is how to access the Long and Lat values and set them in

Position = new Position(.......)

Body:
item is a Field, so it has a Nodes array.  You can use an indexer [] to specify an index in the array

Position = new Position(item.Nodes[0].Lat, item.Nodes[0].Long),

note, attribtute has a specific meaning in C#.  These are properties, not attributes


问:
Exporting CSV from API result doesn't work on Firefox JavaScript
I have a page that get the data from an API and show it to a table.

Then it has a button to export this data on a CSV file.
It is working as expected on google chrome, but on firefox is not, and it throws no error.

Disclaimer: about the regex part, I know it is ugly and badly written, but I wasn't able to make it in only one line.

Here is the code:
HTML Button

```<code><div class="export-container">
    <button class="csv request-submit-button export-button" onclick="csvButton()">
      <?xml version="1.0" encoding="UTF-8"?>
      <svg enable-background="new 0 0 29.978 29.978" version="1.1" viewBox="0 0 29.978 29.978" xml:space="preserve" xmlns="http://www.w3.org/2000/svg">
        <path d="m25.462 19.105v6.848h-20.947v-6.848h-4.026v8.861c0 1.111 0.9 2.012 2.016 2.012h24.967c1.115 0 2.016-0.9 2.016-2.012v-8.861h-4.026z"/>
        <path d="m14.62 18.426l-5.764-6.965s-0.877-0.828 0.074-0.828 3.248 0 3.248 0 0-0.557 0-1.416v-8.723s-0.129-0.494 0.615-0.494h4.572c0.536 0 0.524 0.416 0.524 0.416v8.742 1.266s1.842 0 2.998 0c1.154 0 0.285    0.867 0.285 0.867s-4.904 6.51-5.588 7.193c-0.492 0.495-0.964-0.058-0.964-0.058z"/>
      </svg>
            Exportar
    </button>
    </div>
</code>```

JS Code:

```<code>var getData = (url) => {

   fetch(url, {
            headers: {
                'Authorization': "Basic " + btoa('email/token' + ":" + token)
            },
            credentials: 'omit'
        })
            .then(response => response.json())
            .then(result => {
                TICKETS_CSV = [...TICKETS_CSV, ...result.results];
                console.log('RESULTS TicketsCSV: ', TICKETS_CSV);
                if(result.next_page !== null){
                  getData(result.next_page);
                } else {
                  _gerarCsv(TICKETS_CSV, ORG_CSV);
                  return
                }
                return (result);
            })
            .catch(error => console.error('FETCH ERROR TICKETS CSV: ', error));
    };

function csvButton(){
  if(MSG_CSV == true){
    TICKETS_CSV = [];
    getData(URL_CSV, TICKETS_CSV);
  } else {
    alert("Nenhum ticket para ser exportado");
    return;
  }
}

var _gerarCsv = function(obj, org){
  var csv = 'ID; Assunto; Tipo; Solicitante; Criado Em;  Ultima Atividade; Status; Modulo; Severidade; Organização\n';

  obj.forEach(function(row){

      var subject = row.subject;
      var status_csv = STATUS[row.status].name;
      subject = subject.replace(/,/g, '');
      subject = subject.replace(/(\r\n|\n|\r)/gm, " ");
      subject = subject.replace(/\s+/g, ' ').trim();
      subject = subject.replace(/\#\s?/g, '');

      csv += row.id;
      csv += ";" + subject;
      csv += ";" + TYPE[row.type];
      csv += ";" + getUserName(row.requester_id);
      csv += ";" + convertDate(row.created_at);
      csv += ";" + convertDate(row.updated_at);
      csv += ";" + status_csv;
      csv += ";" + getCustomFieldModulo(row.custom_fields);
      csv += ";" + getCustomFieldSeveridade(row.custom_fields);
      csv += ";" + org;
      csv += '\n';

  });

  var hiddenElement = document.createElement('a');
  hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
  hiddenElement.target = '_blank';
  hiddenElement.download = 'tickets.csv';
  hiddenElement.click();
};
</code>```

I've made all the tests and found out that the code is going ok through all its parts, it just doesn't download the file

答:
Digging a little deeper I've found the problem

To work on firefox I had to put document.body.appendChild()

```<code>var hiddenElement = document.createElement('a');
    hiddenElement.href = 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURIComponent(csv);
    hiddenElement.target = '_blank';
    hiddenElement.download = 'tickets.csv';
    document.body.appendChild(hiddenElement);
    hiddenElement.click();
    document.body.removeChild(hiddenElement);
</code>```

Thanks anyway

Body:
I have a page that get the data from an API and show it to a table.

Then it has a button to export this data on a CSV file.
It is working as expected on google chrome, but on firefox is not, and it throws no error.

Disclaimer: about the regex part, I know it is ugly and badly written, but I wasn't able to make it in only one line.

Here is the code:
HTML Button

    <button class="csv request-submit-button export-button" onclick="csvButton()">
      <?xml version="1.0" encoding="UTF-8"?>
      <svg enable-background="new 0 0 29.978 29.978" version="1.1" viewBox="0 0 29.978 29.978" xml:space="preserve" xmlns="http://www.w3.org/2000/svg">
        <path d="m25.462 19.105v6.848h-20.947v-6.848h-4.026v8.861c0 1.111 0.9 2.012 2.016 2.012h24.967c1.115 0 2.016-0.9 2.016-2.012v-8.861h-4.026z"/>
        <path d="m14.62 18.426l-5.764-6.965s-0.877-0.828 0.074-0.828 3.248 0 3.248 0 0-0.557 0-1.416v-8.723s-0.129-0.494 0.615-0.494h4.572c0.536 0 0.524 0.416 0.524 0.416v8.742 1.266s1.842 0 2.998 0c1.154 0 0.285    0.867 0.285 0.867s-4.904 6.51-5.588 7.193c-0.492 0.495-0.964-0.058-0.964-0.058z"/>
      </svg>
            Exportar
    </button>

JS Code:

var getData = (url) => {

   fetch(url, {
            headers: {
                'Authorization': "Basic " + btoa('email/token' + ":" + token)
            },
            credentials: 'omit'
        })
            .then(response => response.json())
            .then(result => {
                TICKETS_CSV = [...TICKETS_CSV, ...result.results];
                console.log('RESULTS TicketsCSV: ', TICKETS_CSV);
                if(result.next_page !== null){
                  getData(result.next_page);
                } else {
                  _gerarCsv(TICKETS_CSV, ORG_CSV);
                  return
                }
                return (result);
            })
            .catch(error => console.error('FETCH ERROR TICKETS CSV: ', error));
    };

function csvButton(){
  if(MSG_CSV == true){
    TICKETS_CSV = [];
    getData(URL_CSV, TICKETS_CSV);
  } else {
    alert("Nenhum ticket para ser exportado");
    return;
  }
}

var _gerarCsv = function(obj, org){
  var csv = 'ID; Assunto; Tipo; Solicitante; Criado Em;  Ultima Atividade; Status; Modulo; Severidade; Organização\n';

  obj.forEach(function(row){

      var subject = row.subject;
      var status_csv = STATUS[row.status].name;
      subject = subject.replace(/,/g, '');
      subject = subject.replace(/(\r\n|\n|\r)/gm, " ");
      subject = subject.replace(/\s+/g, ' ').trim();
      subject = subject.replace(/\#\s?/g, '');

      csv += row.id;
      csv += ";" + subject;
      csv += ";" + TYPE[row.type];
      csv += ";" + getUserName(row.requester_id);
      csv += ";" + convertDate(row.created_at);
      csv += ";" + convertDate(row.updated_at);
      csv += ";" + status_csv;
      csv += ";" + getCustomFieldModulo(row.custom_fields);
      csv += ";" + getCustomFieldSeveridade(row.custom_fields);
      csv += ";" + org;
      csv += '\n';

  });

  var hiddenElement = document.createElement('a');
  hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
  hiddenElement.target = '_blank';
  hiddenElement.download = 'tickets.csv';
  hiddenElement.click();
};

I've made all the tests and found out that the code is going ok through all its parts, it just doesn't download the file

Body:
Digging a little deeper I've found the problem

To work on firefox I had to put document.body.appendChild()

var hiddenElement = document.createElement('a');
    hiddenElement.href = 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURIComponent(csv);
    hiddenElement.target = '_blank';
    hiddenElement.download = 'tickets.csv';
    document.body.appendChild(hiddenElement);
    hiddenElement.click();
    document.body.removeChild(hiddenElement);

Thanks anyway


问:
C# / PdfSharp: Find out page number from bookmark entries and split
Trying to process a PDF file and split it using the bookmarks defined using PDFSharp and while I can get a list of bookmarks I can not figure out how to actually figure out what page number corresponds to the bookmark definition.

An example PDF file I am working with has three top level bookmarks defined, on pages 1, 5 and 6 and while I can see the bookmarks with the snippet below I couldn't figure out a way to map the bookmark to a page number.

Code:

```<code>using (PdfDocument document = PdfReader.Open("test.pdf", PdfDocumentOpenMode.Import))
{
    PdfDictionary outline = document.Internals.Catalog.Elements.GetDictionary("/Outlines");

    Console.WriteLine("Page count: " + document.PageCount);

    foreach(var page in document.Pages)
    {
        // any hierarchy info on the page itself? doesn't seem to have any.
        Console.WriteLine(page.ToString());

    }

    for (PdfDictionary child = outline.Elements.GetDictionary("/First"); child != null; child = child.Elements.GetDictionary("/Next"))
    {
        Console.WriteLine(child.Elements.GetString("/Title"));

        // FIXME: get page numbers?

    }

}
</code>```

Output:

```<code>Page count: 9
<< /Contents [ 1019 0 R ] /Group << /CS /DeviceRGB /S /Transparency >> /MediaBox [ 0 0 3874 2667 ] /Parent 1 0 R /Resources 1018 0 R /Type /Page >>
<< /Contents [ 1022 0 R ] /Group << /CS /DeviceRGB /S /Transparency >> /MediaBox [ 0 0 3874 2667 ] /Parent 1 0 R /Resources 1021 0 R /Type /Page >>
<< /Contents [ 1025 0 R ] /Group << /CS /DeviceRGB /S /Transparency >> /MediaBox [ 0 0 3874 2667 ] /Parent 1 0 R /Resources 1024 0 R /Type /Page >>
<< /Contents [ 1028 0 R ] /Group << /CS /DeviceRGB /S /Transparency >> /MediaBox [ 0 0 3874 2667 ] /Parent 1 0 R /Resources 1027 0 R /Type /Page >>
<< /Contents [ 1032 0 R ] /Group << /CS /DeviceRGB /S /Transparency >> /MediaBox [ 0 0 842 595 ] /Parent 1 0 R /Resources 1031 0 R /Type /Page >>
<< /Annots [ 46 0 R 48 0 R 50 0 R 52 0 R 54 0 R 56 0 R 58 0 R 60 0 R 62 0 R 64 0 R 66 0 R 68 0 R 70 0 R 72 0 R 74 0 R ] /Contents [ 1043 0 R ] /Group << /CS /DeviceRGB /S /Transparency >> /MediaBox [ 0 0 1130 799 ] /Parent 1 0 R /Resources 1042 0 R /Type /Page >>
<< /Annots [ 82 0 R 84 0 R 86 0 R 88 0 R 90 0 R 92 0 R 94 0 R 96 0 R 98 0 R 100 0 R 102 0 R 104 0 R 106 0 R 108 0 R 110 0 R 112 0 R 114 0 R 116 0 R 118 0 R 120 0 R 122 0 R 124 0 R 126 0 R 128 0 R 130 0 R 132 0 R 134 0 R 136 0 R 138 0 R 140 0 R 142 0 R 144 0 R 146 0 R 148 0 R 150 0 R 152 0 R 154 0 R 156 0 R 158 0 R ] /Contents [ 1048 0 R ] /Group << /CS /DeviceRGB /S /Transparency >> /MediaBox [ 0 0 1130 799 ] /Parent 1 0 R /Resources 1047 0 R /Type /Page >>
<< /Annots [ 166 0 R 168 0 R 170 0 R 172 0 R 174 0 R 176 0 R 178 0 R 180 0 R 182 0 R ] /Contents [ 1053 0 R ] /Group << /CS /DeviceRGB /S /Transparency >> /MediaBox [ 0 0 1130 799 ] /Parent 1 0 R /Resources 1052 0 R /Type /Page >>
<< /Annots [ 190 0 R 192 0 R 194 0 R 196 0 R ] /Contents [ 1058 0 R ] /Group << /CS /DeviceRGB /S /Transparency >> /MediaBox [ 0 0 1130 799 ] /Parent 1 0 R /Resources 1057 0 R /Type /Page >>
Bookmark 1
Bookmark 2
Bookmark 3
</code>```

I am not necessarily married to PDFSharp library.

Any pointers?  Thanks!

答:
I know this is an older question, but I wanted to help out as I recently had the same item happen to me. I was needing to split a document based on the bookmarks. I looked at "/Dest", but was unable to use. Turns out the key is setting child to a PdfOutline type.

This code takes root bookmark and moves said root + children into its own document preserving bookmarks. I know no one uses VB these days, but it should be easy enough to convert to C#.

A note: You will need to open the original document in import mode PdfSharp.Pdf.IO.PdfReader.Open(path, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import).

```<code>Dim rgx As New Regex("^[0-9]{16}$")
Dim docs As List(Of PdfDocument) = New List(Of PdfDocument)
Dim i As Integer = 0
Dim p As String = Application.UserAppDataPath + "\part{0}.pdf"
' Root Level Bookmarks
For Each rootb In document.Outlines
    ' Ensure Account Number Type
    If rgx.IsMatch(rootb.Title) Then
        Dim newdoc As PdfSharp.Pdf.PdfDocument = New PdfDocument
        Dim rp As PdfPage = newdoc.AddPage(rootb.DestinationPage)
        Dim outline As PdfOutline = newdoc.Outlines.Add(rootb.Elements.GetString("/Title"), rp, True, PdfOutlineStyle.Bold, XColors.Red)
        Dim child As PdfDictionary = rootb.Elements.GetDictionary("/First")
        While child IsNot Nothing
            Dim item As PdfOutline = child
            Dim cp As PdfPage = newdoc.AddPage(item.DestinationPage)
            outline.Outlines.Add(item.Elements.GetString("/Title"), cp, True)
            child = child.Elements.GetDictionary("/Next")
        End While

        newdoc.Save(String.Format(p, i))
        i += 1
Next
</code>```

Body:
Trying to process a PDF file and split it using the bookmarks defined using PDFSharp and while I can get a list of bookmarks I can not figure out how to actually figure out what page number corresponds to the bookmark definition.

An example PDF file I am working with has three top level bookmarks defined, on pages 1, 5 and 6 and while I can see the bookmarks with the snippet below I couldn't figure out a way to map the bookmark to a page number.

Code:

using (PdfDocument document = PdfReader.Open("test.pdf", PdfDocumentOpenMode.Import))
{
    PdfDictionary outline = document.Internals.Catalog.Elements.GetDictionary("/Outlines");

    Console.WriteLine("Page count: " + document.PageCount);

    foreach(var page in document.Pages)
    {
        // any hierarchy info on the page itself? doesn't seem to have any.
        Console.WriteLine(page.ToString());

    }

    for (PdfDictionary child = outline.Elements.GetDictionary("/First"); child != null; child = child.Elements.GetDictionary("/Next"))
    {
        Console.WriteLine(child.Elements.GetString("/Title"));

        // FIXME: get page numbers?

    }

}

Output:

Page count: 9
<< /Contents [ 1019 0 R ] /Group << /CS /DeviceRGB /S /Transparency >> /MediaBox [ 0 0 3874 2667 ] /Parent 1 0 R /Resources 1018 0 R /Type /Page >>
<< /Contents [ 1022 0 R ] /Group << /CS /DeviceRGB /S /Transparency >> /MediaBox [ 0 0 3874 2667 ] /Parent 1 0 R /Resources 1021 0 R /Type /Page >>
<< /Contents [ 1025 0 R ] /Group << /CS /DeviceRGB /S /Transparency >> /MediaBox [ 0 0 3874 2667 ] /Parent 1 0 R /Resources 1024 0 R /Type /Page >>
<< /Contents [ 1028 0 R ] /Group << /CS /DeviceRGB /S /Transparency >> /MediaBox [ 0 0 3874 2667 ] /Parent 1 0 R /Resources 1027 0 R /Type /Page >>
<< /Contents [ 1032 0 R ] /Group << /CS /DeviceRGB /S /Transparency >> /MediaBox [ 0 0 842 595 ] /Parent 1 0 R /Resources 1031 0 R /Type /Page >>
<< /Annots [ 46 0 R 48 0 R 50 0 R 52 0 R 54 0 R 56 0 R 58 0 R 60 0 R 62 0 R 64 0 R 66 0 R 68 0 R 70 0 R 72 0 R 74 0 R ] /Contents [ 1043 0 R ] /Group << /CS /DeviceRGB /S /Transparency >> /MediaBox [ 0 0 1130 799 ] /Parent 1 0 R /Resources 1042 0 R /Type /Page >>
<< /Annots [ 82 0 R 84 0 R 86 0 R 88 0 R 90 0 R 92 0 R 94 0 R 96 0 R 98 0 R 100 0 R 102 0 R 104 0 R 106 0 R 108 0 R 110 0 R 112 0 R 114 0 R 116 0 R 118 0 R 120 0 R 122 0 R 124 0 R 126 0 R 128 0 R 130 0 R 132 0 R 134 0 R 136 0 R 138 0 R 140 0 R 142 0 R 144 0 R 146 0 R 148 0 R 150 0 R 152 0 R 154 0 R 156 0 R 158 0 R ] /Contents [ 1048 0 R ] /Group << /CS /DeviceRGB /S /Transparency >> /MediaBox [ 0 0 1130 799 ] /Parent 1 0 R /Resources 1047 0 R /Type /Page >>
<< /Annots [ 166 0 R 168 0 R 170 0 R 172 0 R 174 0 R 176 0 R 178 0 R 180 0 R 182 0 R ] /Contents [ 1053 0 R ] /Group << /CS /DeviceRGB /S /Transparency >> /MediaBox [ 0 0 1130 799 ] /Parent 1 0 R /Resources 1052 0 R /Type /Page >>
<< /Annots [ 190 0 R 192 0 R 194 0 R 196 0 R ] /Contents [ 1058 0 R ] /Group << /CS /DeviceRGB /S /Transparency >> /MediaBox [ 0 0 1130 799 ] /Parent 1 0 R /Resources 1057 0 R /Type /Page >>
Bookmark 1
Bookmark 2
Bookmark 3

I am not necessarily married to PDFSharp library.

Any pointers?  Thanks!

Body:
I know this is an older question, but I wanted to help out as I recently had the same item happen to me. I was needing to split a document based on the bookmarks. I looked at "/Dest", but was unable to use. Turns out the key is setting child to a PdfOutline type.

This code takes root bookmark and moves said root + children into its own document preserving bookmarks. I know no one uses VB these days, but it should be easy enough to convert to C#.

A note: You will need to open the original document in import mode PdfSharp.Pdf.IO.PdfReader.Open(path, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import).

Dim rgx As New Regex("^[0-9]{16}$")
Dim docs As List(Of PdfDocument) = New List(Of PdfDocument)
Dim i As Integer = 0
Dim p As String = Application.UserAppDataPath + "\part{0}.pdf"
' Root Level Bookmarks
For Each rootb In document.Outlines
    ' Ensure Account Number Type
    If rgx.IsMatch(rootb.Title) Then
        Dim newdoc As PdfSharp.Pdf.PdfDocument = New PdfDocument
        Dim rp As PdfPage = newdoc.AddPage(rootb.DestinationPage)
        Dim outline As PdfOutline = newdoc.Outlines.Add(rootb.Elements.GetString("/Title"), rp, True, PdfOutlineStyle.Bold, XColors.Red)
        Dim child As PdfDictionary = rootb.Elements.GetDictionary("/First")
        While child IsNot Nothing
            Dim item As PdfOutline = child
            Dim cp As PdfPage = newdoc.AddPage(item.DestinationPage)
            outline.Outlines.Add(item.Elements.GetString("/Title"), cp, True)
            child = child.Elements.GetDictionary("/Next")
        End While

        newdoc.Save(String.Format(p, i))
        i += 1
Next


问:
mysql Using INNER JOIN to select multiple tables?
I want to select all fields of several table and fetch result separate but mysql return all rows together:

```<code>SELECT prod_product.*
  ,pub_comment.*
FROM prod_product
INNER JOIN pub_comment ON (prod_product.id = pub_comment.itemId)
WHERE prod_product.id=7744
</code>```

Is there any way that i could fetch each table rows separately?

I try @prod:=prod_product.*, @comment:=pub_comment.* but mysql didn't allow me to store more than 1 row.

答:
```<code>SELECT @prod:= CONCAT_WS(',',prod_product.field1,prod_product.field2,...)
  ,@comment:= CONCAT_WS(' ',pub_comment.field1,pub_comment.field2,....)
FROM prod_product
INNER JOIN pub_comment ON (prod_product.id = pub_comment.itemId)
WHERE prod_product.id = 7744
</code>```

<p>Note that CONCAT_WS will separate your fields and CONCAT will just smash then together. </p>

Body:
I want to select all fields of several table and fetch result separate but mysql return all rows together:

SELECT prod_product.*
  ,pub_comment.*
FROM prod_product
INNER JOIN pub_comment ON (prod_product.id = pub_comment.itemId)
WHERE prod_product.id=7744

Is there any way that i could fetch each table rows separately?

I try @prod:=prod_product.*, @comment:=pub_comment.* but mysql didn't allow me to store more than 1 row.

Body:
SELECT @prod:= CONCAT_WS(',',prod_product.field1,prod_product.field2,...)
  ,@comment:= CONCAT_WS(' ',pub_comment.field1,pub_comment.field2,....)
FROM prod_product
INNER JOIN pub_comment ON (prod_product.id = pub_comment.itemId)
WHERE prod_product.id = 7744

Note that CONCAT_WS will separate your fields and CONCAT will just smash then together.


问:
How to save an Entity with a OneToMany relationship using auto incremented IDs that are related
I am trying to save a "User" object that is related by a OneToMany relationship to a "Volunteer" object.

When I try to save it, it only works when I provide the primary IDs for both these objects. However, what I need is to save the entity and let the database dictate the ID's via autoIncrement. I am not sure how am I suppose to do this or even if it's possible.

Json Mapping that works:

```<code>{
    "id":8,
    "userName": "user8",
    "password": "pass1234",
    "volunteersId": 6,
    "volunteers": [{
            "id":6,
            "committeesId": 2,
            "outreachDate": "2019-12-07",
            "usersId": 8
        }]
}
</code>```

Json Mapping that I need (but will not work):

```<code>{
    "userName": "user8",
    "password": "pass1234",
    "volunteersId": 6,
    "volunteers": [{
            "committeesId": 2,
            "outreachDate": "2019-12-07",
        }]
}
</code>```

So I am thinking maybe there's a way to connect the foreign keys so that I wont have to explicitly add the autoIncrement IDs (usersId, volunteersId).

User controller:

```<code>@Controller
public class UserController {
    @RequestMapping(value = "/v1/users", method = RequestMethod.POST)
    public ResponseEntity<Object> saveUsers( @RequestBody UserEntity request){
        try {
            return ResponseEntity.ok(userService.saveUser(request));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
</code>```

User service:

```<code>@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public Page<UserEntity> saveUser(UserEntity user){
        userRepository.save(user);
        Pageable pageable = PageRequest.of(0, 10, Sort.by("id").descending());
        return userRepository.findAll(pageable);
    }
}
</code>```

User Repository:

```<code>public interface UserRepository extends JpaRepository<UserEntity, Long> {
    public List<UserEntity> findAllByOrderByIdAsc();
    public List<UserEntity> findAllByOrderByIdDesc();
    public Page<UserEntity> findByUserNameContaining(String userName, Pageable pageable);
}
</code>```

User Entity:

```<code>@Entity
@Table(name = "users")
public class UserEntity {

    @Id
    private long id;
    @Column(name = "username")
    private String userName;
    private String password;
    @Column(name = "volunteers_id", nullable = true)
    private Long volunteersId;
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "users_id")
    private List<VolunteerEntity> volunteers = new ArrayList<>();

// omitted getters and setters
}
</code>```

Volunteer Entity:

```<code>@Entity
@Table(name = "volunteers")

public class VolunteerEntity {

     @Id
     private long id;
     @Column(name = "committees_id")
     private long committeesId;
     @Column(name = "outreach_date")
     private Date outreachDate;
     @Column(name = "users_id")
     private Long usersId;

// omitted getters and setters
}
</code>```

Any ideas or suggestions how to save this whole entity? I am wondering if this is really possible to save as in one whole process. Though if not, I am thinking of just saving them independently (User info first, then Volunteer next) but just in case it would be possible, it would really be a great help

答:
This will make the primary id generation auto</p>

```<code>@Entity
@Table(name = "user")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

</code>```

Body:
I am trying to save a "User" object that is related by a OneToMany relationship to a "Volunteer" object.

When I try to save it, it only works when I provide the primary IDs for both these objects. However, what I need is to save the entity and let the database dictate the ID's via autoIncrement. I am not sure how am I suppose to do this or even if it's possible.

Json Mapping that works:

{
    "id":8,
    "userName": "user8",
    "password": "pass1234",
    "volunteersId": 6,
    "volunteers": [{
            "id":6,
            "committeesId": 2,
            "outreachDate": "2019-12-07",
            "usersId": 8
        }]
}

Json Mapping that I need (but will not work):

{
    "userName": "user8",
    "password": "pass1234",
    "volunteersId": 6,
    "volunteers": [{
            "committeesId": 2,
            "outreachDate": "2019-12-07",
        }]
}

So I am thinking maybe there's a way to connect the foreign keys so that I wont have to explicitly add the autoIncrement IDs (usersId, volunteersId).

User controller:

@Controller
public class UserController {
    @RequestMapping(value = "/v1/users", method = RequestMethod.POST)
    public ResponseEntity<Object> saveUsers( @RequestBody UserEntity request){
        try {
            return ResponseEntity.ok(userService.saveUser(request));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}

User service:

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public Page<UserEntity> saveUser(UserEntity user){
        userRepository.save(user);
        Pageable pageable = PageRequest.of(0, 10, Sort.by("id").descending());
        return userRepository.findAll(pageable);
    }
}

User Repository:

public interface UserRepository extends JpaRepository<UserEntity, Long> {
    public List<UserEntity> findAllByOrderByIdAsc();
    public List<UserEntity> findAllByOrderByIdDesc();
    public Page<UserEntity> findByUserNameContaining(String userName, Pageable pageable);
}

User Entity:

@Entity
@Table(name = "users")
public class UserEntity {

    @Id
    private long id;
    @Column(name = "username")
    private String userName;
    private String password;
    @Column(name = "volunteers_id", nullable = true)
    private Long volunteersId;
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "users_id")
    private List<VolunteerEntity> volunteers = new ArrayList<>();

// omitted getters and setters
}

Volunteer Entity:

@Entity
@Table(name = "volunteers")

public class VolunteerEntity {

     @Id
     private long id;
     @Column(name = "committees_id")
     private long committeesId;
     @Column(name = "outreach_date")
     private Date outreachDate;
     @Column(name = "users_id")
     private Long usersId;

// omitted getters and setters
}

Any ideas or suggestions how to save this whole entity? I am wondering if this is really possible to save as in one whole process. Though if not, I am thinking of just saving them independently (User info first, then Volunteer next) but just in case it would be possible, it would really be a great help

Body:
This will make the primary id generation auto

@Entity
@Table(name = "user")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;


问:
Curve fitting algorithm from Klipfolio in python
I am looking for a way to apply such algorithm for curve fitting, that line does not exceed values from which it was fitter

Below there is python code with sample values, if you copy/paste it and run you will see that line on the right side is above points

from scipy import interpolate
from numpy import linspace

y = [5, 0, 4, 4]
x = linspace(0, len(y)-1, num=len(y), endpoint=True)
f2 = interp1d(x, y, kind='cubic')
xnew = linspace(0, len(y)-1, num=100, endpoint=True)

plt.plot(xnew, f2(xnew), '--');
plt.scatter(x=[i for i in range(len(x))],y=y, color='red');
```

答:
Here is an example based on your code comparing linear, quadratic and cubic interpolations. Only the linear interpolation is not above the right side data points. The only general method I know of for that purpose, other than linear interpolation, is clipping - which I personally would consider a bad practice.

```<code>from scipy import interpolate
from numpy import linspace
import matplotlib
import matplotlib.pyplot as plt

y = [5, 0, 4, 4]
x = linspace(0, len(y)-1, num=len(y), endpoint=True)
f1 = interpolate.interp1d(x, y, kind='linear')
f2 = interpolate.interp1d(x, y, kind='quadratic')
f3 = interpolate.interp1d(x, y, kind='cubic')
xnew = linspace(0, len(y)-1, num=100, endpoint=True)

plt.title('Interpolation comparison')
plt.plot(xnew, f1(xnew), linestyle='solid', color='red', label='linear');
plt.plot(xnew, f2(xnew), linestyle='dashed', color='green', label='quadratic');
plt.plot(xnew, f3(xnew), linestyle='dashdot', color='blue', label='cubic');
plt.scatter(x=[i for i in range(len(x))],y=y, color='black');
plt.legend() # turn on the legend
plt.show()
</code>```

Body:
Here is an example based on your code comparing linear, quadratic and cubic interpolations. Only the linear interpolation is not above the right side data points. The only general method I know of for that purpose, other than linear interpolation, is clipping - which I personally would consider a bad practice.

from scipy import interpolate
from numpy import linspace
import matplotlib
import matplotlib.pyplot as plt

y = [5, 0, 4, 4]
x = linspace(0, len(y)-1, num=len(y), endpoint=True)
f1 = interpolate.interp1d(x, y, kind='linear')
f2 = interpolate.interp1d(x, y, kind='quadratic')
f3 = interpolate.interp1d(x, y, kind='cubic')
xnew = linspace(0, len(y)-1, num=100, endpoint=True)

plt.title('Interpolation comparison')
plt.plot(xnew, f1(xnew), linestyle='solid', color='red', label='linear');
plt.plot(xnew, f2(xnew), linestyle='dashed', color='green', label='quadratic');
plt.plot(xnew, f3(xnew), linestyle='dashdot', color='blue', label='cubic');
plt.scatter(x=[i for i in range(len(x))],y=y, color='black');
plt.legend() # turn on the legend
plt.show()


问:
Unity HoloLens App is executed as Windows App instead of AR
I am building a HoloLens Unity App using the following tools

Unity 2018.3.14f1

Visual Studio 2017

Microsoft.MixedReality.Toolkit.Unity.Foundation-v2.0.0-RC1-Refresh.unitypackage (MRToolkit v2)

Unity Project/Scene Configuration

Target Platform: Universal Windows Platform

Target Device: HoloLens

Architecture: x86

Target SDK Version: Latest

Target Platform Version: 10.0.10240.0

Target Platform Settings

Supported Device Family: Holographic

XR Settings: VR Support (unchecked); WSA Holographic Remoting Support (uncheck)

Other Settings:

How I deployed:

Added Open Scene

Build

Open *.sln file

Set 'Universal Windows' project as default project.

Updated [Machine Name/IP] for remote execution

Run/Start the project using 'Remote Device' (HoloLens 1)

deployment package was successful

BUT instead of having a CUBE floating in real world, hololens displayed the App as a Windows App.

Did I miss some incorrect configuration?

Under Target Platform maybe? MRToolkit settings? Platform Settings? UWP Settings?

And also i can't find any documentation on how to do a deployment using the latest MRToolkit v2 TO A HOLOLENS 1 DEVICE. If you can share some links it would be great as well

Thank you in advance.

答:
In addition to HoloLady's answer, to deploy to HoloLens 1 with MRTK v2 you may encounter some additional problems on build.

You need to be using the latest Windows Insider preview on your build PC, with the latest Windows SDK installed (18988 works), although seeing as you managed to build it then maybe you already have this.

You'll likely encounter an error whilst trying to run your app that will involve MixedRealityToolkit.Services.InputSimulation.asmdef. A quick fix for this is to navigate to Assets/MixedRealityToolkit.Services/InputSimulation/ in the Unity project and change the .amsdef file to run on any platform. After this, it should run correctly.


问:
Images are not loading after deploying angular app on github pages
I deployed a test project on github pages using these commands:

```<code>ng build --prod --base-href https://<profile_name>.github.io/<repo_name>/
ngh --dir=dist/scrabble
</code>```

Everything works fine except images (on localhost every image is loading).

outputPath in angular.json:

```<code>"outputPath": "dist/scrabble/",
</code>```

assets in angular.json:

```<code>"assets": [
  "src/favicon.ico",
  "src/assets"
],
</code>```

assets folder with images is located in <project_folder>/src/assets

one example of image tag which works perfectly on localhost but doesn't load on github pages:

```<code>  <img src="../../../assets/scaledlogo.png" routerLink="/menu" />
</code>```

答:
You need to pass --deploy-url option. in your case it should be

ng build --prod --base-href https://<profile_name>.github.io/<repo_name>/ --deploy-url=https://<profile_name>.github.io/<repo_name>/
```

Body:
I deployed a test project on github pages using these commands:

ng build --prod --base-href https://<profile_name>.github.io/<repo_name>/
ngh --dir=dist/scrabble

Everything works fine except images (on localhost every image is loading).

outputPath in angular.json:

"outputPath": "dist/scrabble/",

assets in angular.json:

"assets": [
  "src/favicon.ico",
  "src/assets"
],

assets folder with images is located in <project_folder>/src/assets

one example of image tag which works perfectly on localhost but doesn't load on github pages:


问:
C++: Cloud computing library: is there such a library where I don't need to write much network stuff?
I want my server app to be able to send data to be processed by a bunch of various clients, and then have the processed data returned to the server.

Ideally, I'd have some call like some_process = send_to_client_for_calculating(connection, data)

I just need to be able to send a bunch of data to a client, tell the client what to do (preferably in the same message, which can be done with an array [command, data]), and then return the data...

I'm breaking up pieces of a neural network (tis very large), and then assembling them all later.

If I need to be clearer, let me know how.

答: I'm shocked no one has thrown it out there... how about boost::asio.</p>


问:
Get a tag value in multi line XML using shell script
I have a xml file as follows

```<code><Module dataPath="/abc/def/xyz" handler="DataRegistry" id="id1" path="test.so"/>
<Module id="id2" path="/my/file/path">
  <Config>
    <Source cutoffpackage="1" dailyStart="20060819" dataPath="/abc/def/xyz" />
    <Source cutoffpackage="1" dailyStart="20060819" dataPath="/abc/def/xyz" id="V2"/>
  </Config>
</Module>
</code>```

I just want to extract value of dataPath from every moduleid.

I was using, the command like

```<code>`grep 'id2' file | grep -ioPm1 "(?<=DataPath=)[^ ]+"`
</code>```

which is giving me from the first module id, not for second module id. because second module is in multiple lines.

How can i do this using shell script?

Desired output would be– if i want to get the datapath of id1 module, then is should get

```<code>/my/file/path
</code>```

Of for second module id, say id2, i should get datapath separated by comma

```<code>/my/file/path, /my/file/path
</code>```

Or my second approach to grep the datapath is to replace the newline character between <Module and </Module> only, then i can use grep.

答:
Firstly my answer assumes that you have actual well formed source XML. The example code you've provided doesn't have a root element - but I'll assume there is one anyway.

Bash features by themselves are not very well suited parsing XML.

This renowned Bash FAQ states the following:

Do not attempt [to extract data from an XML file] with sed, awk, grep, and so on (it leads to undesired results)

If you must use a shell script then utilize an XML specific command line tool, such as XMLStarlet or xsltproc. Refer to the download info here for XML Starlet if you don't have it installed already.

Solution:

Given your source XML and your desired output consider utilizing the following xslt template to achieve this.

template.xsl

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="text"/>

  <xsl:template match="node()|@*">
    <xsl:apply-templates select="node()|@*"/>
  </xsl:template>

  <xsl:template match="Module">
    <xsl:choose>

      <xsl:when test="@dataPath and not(descendant::*/@dataPath)">
        <xsl:value-of select="@dataPath"/>
        <xsl:text>
</xsl:text>
      </xsl:when>

      <xsl:when test="not(@dataPath) and descendant::*/@dataPath">
        <xsl:for-each select="descendant::*/@dataPath">
          <xsl:value-of select="."/>
          <xsl:if test="position()!=last()">
            <xsl:text>, </xsl:text>
          </xsl:if>
        </xsl:for-each>
        <xsl:text>
</xsl:text>
      </xsl:when>

      <xsl:when test="@dataPath and descendant::*/@dataPath">
        <xsl:value-of select="@dataPath"/>
        <xsl:text>, </xsl:text>
        <xsl:for-each select="descendant::*/@dataPath">
          <xsl:value-of select="."/>
          <xsl:if test="position()!=last()">
            <xsl:text>, </xsl:text>
          </xsl:if>
        </xsl:for-each>
        <xsl:text>
</xsl:text>
      </xsl:when>

    </xsl:choose>
  </xsl:template>

</xsl:stylesheet>
```</li>
<li><p>Then run either;</p>

<ul>
<li><p>the following XML Starlet command:</p>

<pre class="lang-none prettyprint-override"><code>$ xml tr /path/to/template.xsl /path/to/input.xml
</code>```

Or the following xsltproc command:

$ xsltproc /path/to/template.xsl /path/to/input.xml
```</li>
</ul>

<p><sub><strong>Note:</strong> The pathnames to <code>template.xsl</code> and <code>input.xml</code> in the aforementioned command(s) should be redefined to wherever those files reside.</sub></p>

<p>Either of the commands above essentially transform your <code>input.xml</code> file and print the desired results.</p></li>
</ol>

<hr>

<h2>Demo:</h2>

<ol>
<li><p>Using the following <code>input.xml</code> file:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<root>
  <Module dataPath="/abc/def/1" handler="DataRegistry" id="id1" path="test.so"/>

  <Module id="id2" path="/my/file/path">
    <Config>
      <Source cutoffpackage="1" dailyStart="20060819" dataPath="/abc/def/2" />
      <Source cutoffpackage="1" dailyStart="20060819" dataPath="/abc/def/3" id="V2"/>
    </Config>
  </Module>

  <Module id="id3" path="/my/file/path" dataPath="/abc/def/4">
    <Config>
      <Source cutoffpackage="1" dailyStart="20060819" dataPath="/abc/def/5" />
      <Source cutoffpackage="1" dailyStart="20060819" dataPath="/abc/def/6" id="V2"/>
    </Config>
  </Module>

  <Module id="id4" path="/my/file/path" dataPath="/abc/def/7"/>
  <Module id="id5" path="/my/file/path" dataPath="/abc/def/8"/>

  <!-- The following <Module>'s have no associated `dataPath` attribute -->
  <Module id="id6">
    <Config>
      <Source cutoffpackage="1" dailyStart="20060819" id="V2"/>
    </Config>
  </Module>

  <Module id="id7"/>
</root>
</code>```

Then running either of the aforementioned commands prints the following result:

/abc/def/1
/abc/def/2, /abc/def/3
/abc/def/4, /abc/def/5, /abc/def/6
/abc/def/7
/abc/def/8
```</li>
</ol>

<hr>

<h2>Additional Note:</h2>

<p>If you wanted to avoid the use of a separate <code>.xsl</code> file you could inline the aforementioned XSLT template in your shell script as follows:</p>

<p><strong>script.sh</strong></p>

<pre class="lang-bash prettyprint-override"><code>#!/usr/bin/env bash

xslt() {
cat <<EOX
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="text"/>

  <xsl:template match="node()|@*">
    <xsl:apply-templates select="node()|@*"/>
  </xsl:template>

  <xsl:template match="Module">
    <xsl:choose>

      <xsl:when test="@dataPath and not(descendant::*/@dataPath)">
        <xsl:value-of select="@dataPath"/>
        <xsl:text>
</xsl:text>
      </xsl:when>

      <xsl:when test="not(@dataPath) and descendant::*/@dataPath">
        <xsl:for-each select="descendant::*/@dataPath">
          <xsl:value-of select="."/>
          <xsl:if test="position()!=last()">
            <xsl:text>, </xsl:text>
          </xsl:if>
        </xsl:for-each>
        <xsl:text>
</xsl:text>
      </xsl:when>

      <xsl:when test="@dataPath and descendant::*/@dataPath">
        <xsl:value-of select="@dataPath"/>
        <xsl:text>, </xsl:text>
        <xsl:for-each select="descendant::*/@dataPath">
          <xsl:value-of select="."/>
          <xsl:if test="position()!=last()">
            <xsl:text>, </xsl:text>
          </xsl:if>
        </xsl:for-each>
        <xsl:text>
</xsl:text>
      </xsl:when>

    </xsl:choose>
  </xsl:template>

</xsl:stylesheet>
EOX
}

# 1. Using XML Startlet
xml tr <(xslt) /path/to/input.xml

# 2. Or using xsltproc
xsltproc <(xslt) - </path/to/input.xml
</code>```

Note: The pathname to your input.xml, (i.e. the /path/to/input.xml part in script.sh above), should again be redefined to wherever that file resides.

Body:
I have a xml file as follows

<Module dataPath="/abc/def/xyz" handler="DataRegistry" id="id1" path="test.so"/>
<Module id="id2" path="/my/file/path">
  <Config>
    <Source cutoffpackage="1" dailyStart="20060819" dataPath="/abc/def/xyz" />
    <Source cutoffpackage="1" dailyStart="20060819" dataPath="/abc/def/xyz" id="V2"/>
  </Config>
</Module>

I just want to extract value of dataPath from every moduleid.

I was using, the command like

`grep 'id2' file | grep -ioPm1 "(?<=DataPath=)[^ ]+"`

which is giving me from the first module id, not for second module id. because second module is in multiple lines.

How can i do this using shell script?

Desired output would be– if i want to get the datapath of id1 module, then is should get

/my/file/path

Of for second module id, say id2, i should get datapath separated by comma

/my/file/path, /my/file/path

Or my second approach to grep the datapath is to replace the newline character between <Module and </Module> only, then i can use grep.

Body:
Firstly my answer assumes that you have actual well formed source XML. The example code you've provided doesn't have a root element - but I'll assume there is one anyway.

Bash features by themselves are not very well suited parsing XML.

This renowned Bash FAQ states the following:

Do not attempt [to extract data from an XML file] with sed, awk, grep, and so on (it leads to undesired results)

If you must use a shell script then utilize an XML specific command line tool, such as XMLStarlet or xsltproc. Refer to the download info here for XML Starlet if you don't have it installed already.

Solution:

Given your source XML and your desired output consider utilizing the following xslt template to achieve this.

template.xsl

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="text"/>

  <xsl:template match="node()|@*">
    <xsl:apply-templates select="node()|@*"/>
  </xsl:template>

  <xsl:template match="Module">
    <xsl:choose>

      <xsl:when test="@dataPath and not(descendant::*/@dataPath)">
        <xsl:value-of select="@dataPath"/>
        <xsl:text>&#xa;</xsl:text>
      </xsl:when>

      <xsl:when test="not(@dataPath) and descendant::*/@dataPath">
        <xsl:for-each select="descendant::*/@dataPath">
          <xsl:value-of select="."/>
          <xsl:if test="position()!=last()">
            <xsl:text>, </xsl:text>
          </xsl:if>
        </xsl:for-each>
        <xsl:text>&#xa;</xsl:text>
      </xsl:when>

      <xsl:when test="@dataPath and descendant::*/@dataPath">
        <xsl:value-of select="@dataPath"/>
        <xsl:text>, </xsl:text>
        <xsl:for-each select="descendant::*/@dataPath">
          <xsl:value-of select="."/>
          <xsl:if test="position()!=last()">
            <xsl:text>, </xsl:text>
          </xsl:if>
        </xsl:for-each>
        <xsl:text>&#xa;</xsl:text>
      </xsl:when>

    </xsl:choose>
  </xsl:template>

</xsl:stylesheet>

Then run either;

the following XML Starlet command:

$ xml tr /path/to/template.xsl /path/to/input.xml

Or the following xsltproc command:

$ xsltproc /path/to/template.xsl /path/to/input.xml

Note: The pathnames to template.xsl and input.xml in the aforementioned command(s) should be redefined to wherever those files reside.

Either of the commands above essentially transform your input.xml file and print the desired results.

Demo:

Using the following input.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <Module dataPath="/abc/def/1" handler="DataRegistry" id="id1" path="test.so"/>

  <Module id="id2" path="/my/file/path">
    <Config>
      <Source cutoffpackage="1" dailyStart="20060819" dataPath="/abc/def/2" />
      <Source cutoffpackage="1" dailyStart="20060819" dataPath="/abc/def/3" id="V2"/>
    </Config>
  </Module>

  <Module id="id3" path="/my/file/path" dataPath="/abc/def/4">
    <Config>
      <Source cutoffpackage="1" dailyStart="20060819" dataPath="/abc/def/5" />
      <Source cutoffpackage="1" dailyStart="20060819" dataPath="/abc/def/6" id="V2"/>
    </Config>
  </Module>

  <Module id="id4" path="/my/file/path" dataPath="/abc/def/7"/>
  <Module id="id5" path="/my/file/path" dataPath="/abc/def/8"/>

  <!-- The following <Module>'s have no associated `dataPath` attribute -->
  <Module id="id6">
    <Config>
      <Source cutoffpackage="1" dailyStart="20060819" id="V2"/>
    </Config>
  </Module>

  <Module id="id7"/>
</root>

Then running either of the aforementioned commands prints the following result:

/abc/def/1
/abc/def/2, /abc/def/3
/abc/def/4, /abc/def/5, /abc/def/6
/abc/def/7
/abc/def/8

Additional Note:

If you wanted to avoid the use of a separate .xsl file you could inline the aforementioned XSLT template in your shell script as follows:

script.sh

#!/usr/bin/env bash

xslt() {
cat <<EOX
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="text"/>

  <xsl:template match="node()|@*">
    <xsl:apply-templates select="node()|@*"/>
  </xsl:template>

  <xsl:template match="Module">
    <xsl:choose>

      <xsl:when test="@dataPath and not(descendant::*/@dataPath)">
        <xsl:value-of select="@dataPath"/>
        <xsl:text>&#xa;</xsl:text>
      </xsl:when>

      <xsl:when test="not(@dataPath) and descendant::*/@dataPath">
        <xsl:for-each select="descendant::*/@dataPath">
          <xsl:value-of select="."/>
          <xsl:if test="position()!=last()">
            <xsl:text>, </xsl:text>
          </xsl:if>
        </xsl:for-each>
        <xsl:text>&#xa;</xsl:text>
      </xsl:when>

      <xsl:when test="@dataPath and descendant::*/@dataPath">
        <xsl:value-of select="@dataPath"/>
        <xsl:text>, </xsl:text>
        <xsl:for-each select="descendant::*/@dataPath">
          <xsl:value-of select="."/>
          <xsl:if test="position()!=last()">
            <xsl:text>, </xsl:text>
          </xsl:if>
        </xsl:for-each>
        <xsl:text>&#xa;</xsl:text>
      </xsl:when>

    </xsl:choose>
  </xsl:template>

</xsl:stylesheet>
EOX
}

# 1. Using XML Startlet
xml tr <(xslt) /path/to/input.xml

# 2. Or using xsltproc
xsltproc <(xslt) - </path/to/input.xml

Note: The pathname to your input.xml, (i.e. the /path/to/input.xml part in script.sh above), should again be redefined to wherever that file resides.


问:
Prove that the powerset of a finite set is finite using Coq
While trying to prove some things, I encountered an innocent looking claim that I failed to prove in Coq. The claim is that for a given Finite Ensemble, the powerset is also finite. The statement is given in the Coq code below.

I looked through the Coq documentation on finite sets and facts about finite sets and powersets, but I could not find something that deconstructs the powerset into a union of subsets (such that the Union_is_finite constructor can be used). Another approach may be to show that the cardinal number of the powerset is 2^|S| but here I certainly have no idea how to approach the proof.

```<code>From Coq Require Export Sets.Ensembles.
From Coq Require Export Sets.Powerset.
From Coq Require Export Sets.Finite_sets.

Lemma powerset_finite {T} (S : Ensemble T) :
  Finite T S -> Finite (Ensemble T) (Power_set T S).
Proof.
  (* I don't know how to proceed. *)
Admitted.
</code>```

答:
I did not solve it completely because I myself struggled a lot with this proof. I merely transferred it along your line of thought. Now the crux of problem is, proving the cardinality of power set of a set of n elements is 2^n. </p>

```<code>From Coq Require Export Sets.Ensembles.
From Coq Require Export Sets.Powerset.
From Coq Require Export Sets.Finite_sets.
From Coq Require Export Sets.Finite_sets_facts.

Fixpoint exp (n m : nat) : nat :=
  match m with
    | 0 => 1
    | S m' => n * (exp n m')
  end.

Theorem power_set_empty :
  forall (U : Type), Power_set _ (Empty_set U) = Singleton _ (Empty_set _).
Proof with auto with sets.
  intros U.
  apply Extensionality_Ensembles.
  unfold Same_set. split.
  + unfold Included. intros x Hin.
    inversion Hin; subst.
    apply Singleton_intro.
    symmetry. apply less_than_empty; auto.

  + unfold Included. intros x Hin.
    constructor. inversion Hin; subst.
    unfold Included; intros; assumption.
Qed.

Lemma cardinality_power_set :
  forall (U : Type) (A : Ensemble U) (n : nat),
    cardinal U A n -> cardinal _ (Power_set _ A) (exp 2 n).
Proof.
  intros U A n. revert A.
  induction n; cbn; intros He Hc.
  + inversion Hc; subst. rewrite power_set_empty.
    Search Singleton.
    rewrite <- Empty_set_zero'.
    constructor; repeat auto with sets.
  + inversion Hc; subst; clear Hc.
Admitted.

Lemma powerset_finite {T} (S : Ensemble T) :
  Finite T S -> Finite (Ensemble T) (Power_set T S).
Proof.
  intros Hf.
  destruct (finite_cardinal _ S Hf) as [n Hc].
  eapply cardinal_finite with (n := exp 2 n).
  apply cardinality_power_set; auto.
Qed.
</code>```

Body:
While trying to prove some things, I encountered an innocent looking claim that I failed to prove in Coq. The claim is that for a given Finite Ensemble, the powerset is also finite. The statement is given in the Coq code below.

I looked through the Coq documentation on finite sets and facts about finite sets and powersets, but I could not find something that deconstructs the powerset into a union of subsets (such that the Union_is_finite constructor can be used). Another approach may be to show that the cardinal number of the powerset is 2^|S| but here I certainly have no idea how to approach the proof.

From Coq Require Export Sets.Ensembles.
From Coq Require Export Sets.Powerset.
From Coq Require Export Sets.Finite_sets.

Lemma powerset_finite {T} (S : Ensemble T) :
  Finite T S -> Finite (Ensemble T) (Power_set T S).
Proof.
  (* I don't know how to proceed. *)
Admitted.

Body:
I did not solve it completely because I myself struggled a lot with this proof. I merely transferred it along your line of thought. Now the crux of problem is, proving the cardinality of power set of a set of n elements is 2^n.

From Coq Require Export Sets.Ensembles.
From Coq Require Export Sets.Powerset.
From Coq Require Export Sets.Finite_sets.
From Coq Require Export Sets.Finite_sets_facts.

Fixpoint exp (n m : nat) : nat :=
  match m with
    | 0 => 1
    | S m' => n * (exp n m')
  end.

Theorem power_set_empty :
  forall (U : Type), Power_set _ (Empty_set U) = Singleton _ (Empty_set _).
Proof with auto with sets.
  intros U.
  apply Extensionality_Ensembles.
  unfold Same_set. split.
  + unfold Included. intros x Hin.
    inversion Hin; subst.
    apply Singleton_intro.
    symmetry. apply less_than_empty; auto.

  + unfold Included. intros x Hin.
    constructor. inversion Hin; subst.
    unfold Included; intros; assumption.
Qed.

Lemma cardinality_power_set :
  forall (U : Type) (A : Ensemble U) (n : nat),
    cardinal U A n -> cardinal _ (Power_set _ A) (exp 2 n).
Proof.
  intros U A n. revert A.
  induction n; cbn; intros He Hc.
  + inversion Hc; subst. rewrite power_set_empty.
    Search Singleton.
    rewrite <- Empty_set_zero'.
    constructor; repeat auto with sets.
  + inversion Hc; subst; clear Hc.
Admitted.

Lemma powerset_finite {T} (S : Ensemble T) :
  Finite T S -> Finite (Ensemble T) (Power_set T S).
Proof.
  intros Hf.
  destruct (finite_cardinal _ S Hf) as [n Hc].
  eapply cardinal_finite with (n := exp 2 n).
  apply cardinality_power_set; auto.
Qed.


问:
Eclipse OSGi or RCP application with Maven dependencies instead of TargetPlatform
Using Eclipse as an IDE, is it possible to use the maven dependency management instead of a PDE target platform? Without PDE TargetPlatform the bundles are missing in the launch configuration.

Since it is possible to declare the same update-sites in the pom file, it would be much more convenient adding dependencies through Maven.

```<code><repositories>
    <repository>
        <id>eclipse-neon</id>
        <layout>p2</layout>
        <url>http://download.eclipse.org/releases/neon</url>
    </repository>
    <repository>
        <id>eclipse-2018-12</id>
        <layout>p2</layout>
        <url>http://download.eclipse.org/releases/2018-12</url>
    </repository>
</repositories>
</code>```

Resolving dependencies is also much faster using Maven.

EDIT: I would like to build and launch in Eclipse with the same dependency management. Using tycho and maven without target definition.

答:
I know that you want to get all the dependencies directly from maven repository as a set of jar files or like BOM(Bill of Materials) like spring boot. This can be done but it needs effort. There is another way where you can create your own p2 repository for specific eclipse version. Nexus and Artifactory also supports p2 repostory. First of all setup Nexus or Artifactory in the organization, keep other useful libraries and create p2 repository.The download will be faster and it will be specific to the organisation. For better understanding, the pom.xml will have something  like this.

```<code><repositories>
    <repository>
        <id>custome-rcp-eclipse</id>
        <layout>p2</layout>
        <url>http://nexus.organisation/path/someName</url>
    </repository>
</repositories>
</code>```

Apart from this, I provide some useful links so that you can go through it.
https://www.vogella.com/tutorials/Nexus/article.html
https://www.jfrog.com/confluence/display/RTF/P2+Repositories
https://www.eclipse.org/forums/index.php/t/1095653/

Body:
Using Eclipse as an IDE, is it possible to use the maven dependency management instead of a PDE target platform? Without PDE TargetPlatform the bundles are missing in the launch configuration.

Since it is possible to declare the same update-sites in the pom file, it would be much more convenient adding dependencies through Maven.

<repositories>
    <repository>
        <id>eclipse-neon</id>
        <layout>p2</layout>
        <url>http://download.eclipse.org/releases/neon</url>
    </repository>
    <repository>
        <id>eclipse-2018-12</id>
        <layout>p2</layout>
        <url>http://download.eclipse.org/releases/2018-12</url>
    </repository>
</repositories>

Resolving dependencies is also much faster using Maven.

EDIT: I would like to build and launch in Eclipse with the same dependency management. Using tycho and maven without target definition.

Body:
I know that you want to get all the dependencies directly from maven repository as a set of jar files or like BOM(Bill of Materials) like spring boot. This can be done but it needs effort. There is another way where you can create your own p2 repository for specific eclipse version. Nexus and Artifactory also supports p2 repostory. First of all setup Nexus or Artifactory in the organization, keep other useful libraries and create p2 repository.The download will be faster and it will be specific to the organisation. For better understanding, the pom.xml will have something  like this.

<repositories>
    <repository>
        <id>custome-rcp-eclipse</id>
        <layout>p2</layout>
        <url>http://nexus.organisation/path/someName</url>
    </repository>
</repositories>

Apart from this, I provide some useful links so that you can go through it.
https://www.vogella.com/tutorials/Nexus/article.html
https://www.jfrog.com/confluence/display/RTF/P2+Repositories
https://www.eclipse.org/forums/index.php/t/1095653/


问:
Slide whole
which contain only text with two control arrow
I made a website using Bootstrap. I want to add slider a in my website which slides a
 which contain only text, not the image. Also, that slider contains two arrows for controls. Kindly suggest me a slider.

答:
Here is a slider example that may work for you. It has controls and is text only.

.carousel {
  background-color: #666;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
    <div id="carouselContent" class="carousel slide" data-ride="carousel">
        <div class="carousel-inner" role="listbox">
            <div class="carousel-item active text-center p-4">
                 <p>lorem ipsum (imagine longer text)</p>
            </div>
            <div class="carousel-item text-center p-4">

                <p>lorem ipsum (imagine longer text)</p>
            </div>
        </div>

            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
            <span class="sr-only">Previous</span>

            <span class="carousel-control-next-icon" aria-hidden="true"></span>
            <span class="sr-only">Next</span>

    </div>
</div></code>```

Title: Slide whole <div>which contain only text with two control arrow

Body:
Here is a slider example that may work for you. It has controls and is text only.

.carousel {
  background-color: #666;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
    <div id="carouselContent" class="carousel slide" data-ride="carousel">
        <div class="carousel-inner" role="listbox">
            <div class="carousel-item active text-center p-4">
                 <p>lorem ipsum (imagine longer text)</p>
            </div>
            <div class="carousel-item text-center p-4">

                <p>lorem ipsum (imagine longer text)</p>
            </div>
        </div>
        <a class="carousel-control-prev" href="#carouselContent" role="button" data-slide="prev">
            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
            <span class="sr-only">Previous</span>
        </a>
        <a class="carousel-control-next" href="#carouselContent" role="button" data-slide="next">
            <span class="carousel-control-next-icon" aria-hidden="true"></span>
            <span class="sr-only">Next</span>
        </a>
    </div>
</div>


问:
How to check if multiple subscriptions reached onComplete()?
I have two subscriptions in an Angular 6 component.
Now I want to start a method as soon as these two subscriptions reached onComplete.

How can I do this the easiest way?

答:
forkJoin works when all the obserables have emitted one value. Similar to promise.All.

If the obserables are going to emit more than one value. You can use combineLatest which emits a value each time all the obserables have emitted one value.


问:
How to upload wepb images into wordpress?
I try to upload wepb images into my websites. But it repeatly shows some errors. I already tried many plugins like WebP Express, EWWW Image Optimizer,Short Pixel Image optimizer. It works well but it will affect my slider(slider revolution). So I want to upload webp images manual or some other image upload plugins. Please give me some tips to upload img. thank you..

Have a great day..

答:
Try to use this code in your theme/child theme's functions.php file or create a simple plugin and add the following code:</p>

```<code>function add_webp_to_upload_mimes( $upload_mimes ) {
    $upload_mimes['webp'] = 'image/webp';
    return $upload_mimes;
}
add_filter( 'upload_mimes', 'add_webp_to_upload_mimes', 10, 1 );
</code>```

Body:
Try to use this code in your theme/child theme's functions.php file or create a simple plugin and add the following code:

function add_webp_to_upload_mimes( $upload_mimes ) {
    $upload_mimes['webp'] = 'image/webp';
    return $upload_mimes;
}
add_filter( 'upload_mimes', 'add_webp_to_upload_mimes', 10, 1 );


问:
How To Create Project Group Template Using Visual Studio 2017
The folder does not appear in the template under the solution

I used the method in the link

https://www.c-sharpcorner.com/article/how-to-create-multi-project-template-using-visual-studio-2017/?

```<code>
<VSTemplate Version="2.0.0" Type="ProjectGroup" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
  <TemplateData>
    <Name>Solution Template</Name>
    <Description>An example of a multi-project template</Description>
    <Icon>__TemplateIcon.ico</Icon>
    <ProjectType>CSharp</ProjectType>
    <ProjectSubType>
    </ProjectSubType>
    <SortOrder>1000</SortOrder>
    <CreateNewFolder>true</CreateNewFolder>
    <DefaultName>DomainKod.ModulKod</DefaultName>
    <ProvideDefaultName>true</ProvideDefaultName>
    <LocationField>Enabled</LocationField>
    <EnableLocationBrowseButton>true</EnableLocationBrowseButton>
  </TemplateData>
  <TemplateContent>
    <ProjectCollection>
      <SolutionFolder Name="Src">
        <ProjectTemplateLink ProjectName="$projectname$.Api">
          DomainKod.ModulKod.Api\Api.vstemplate
        </ProjectTemplateLink>
        <ProjectTemplateLink ProjectName="$projectname$.Web">
          DomainKod.ModulKod.Web\Web.vstemplate
        </ProjectTemplateLink>
      </SolutionFolder>
      <SolutionFolder Name="Tests">
        <ProjectTemplateLink ProjectName="$projectname$.Web.Tests">
          DomainKod.ModulKod.Web.Tests\Web.Tests.vstemplate
        </ProjectTemplateLink>
      </SolutionFolder>
      <SolutionFolder Name="SolutionItems">
        <ProjectTemplateLink ProjectName="SolutionItems">
          SolutionItems\Solution.vstemplate
        </ProjectTemplateLink>
      </SolutionFolder>
    </ProjectCollection>
  </TemplateContent>
</VSTemplate>

</code>```

SolutionItems.vstemplate

```<code><VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Project">
  <TemplateData>
    <Name>SolutionItems</Name>
    <Description><No description available></Description>
    <ProjectType>CSharp</ProjectType>
    <ProjectSubType>
    </ProjectSubType>
    <SortOrder>1000</SortOrder>
    <CreateNewFolder>true</CreateNewFolder>
    <CreateInPlace>true</CreateInPlace>
    <DefaultName>SolutionDeneme</DefaultName>
    <ProvideDefaultName>true</ProvideDefaultName>
    <LocationField>Enabled</LocationField>
    <EnableLocationBrowseButton>true</EnableLocationBrowseButton>
    <Icon>__TemplateIcon.ico</Icon>
  </TemplateData>
  <TemplateContent>
      <Folder Name="App-Keys" TargetFolderName="App-Keys">
        <ProjectItem ReplaceParameters="true">key.xml</ProjectItem>
      </Folder>
  </TemplateContent>
</VSTemplate>

</code>```

SolutionItems folder not apper my template create.
How do I enable adding SolutionItems folder templates?

答:
You can create  wizards for multi project template.

https://learn.microsoft.com/en-us/visualstudio/extensibility/how-to-use-wizards-with-project-templates?view=vs-2019

The Dotnet CLI can be helpful for operations that you cannot do in the Wizard.

https://learn.microsoft.com/tr-tr/dotnet/core/tools/?tabs=netcore2x

Body:
The folder does not appear in the template under the solution

I used the method in the link

https://www.c-sharpcorner.com/article/how-to-create-multi-project-template-using-visual-studio-2017/?

<VSTemplate Version="2.0.0" Type="ProjectGroup" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
  <TemplateData>
    <Name>Solution Template</Name>
    <Description>An example of a multi-project template</Description>
    <Icon>__TemplateIcon.ico</Icon>
    <ProjectType>CSharp</ProjectType>
    <ProjectSubType>
    </ProjectSubType>
    <SortOrder>1000</SortOrder>
    <CreateNewFolder>true</CreateNewFolder>
    <DefaultName>DomainKod.ModulKod</DefaultName>
    <ProvideDefaultName>true</ProvideDefaultName>
    <LocationField>Enabled</LocationField>
    <EnableLocationBrowseButton>true</EnableLocationBrowseButton>
  </TemplateData>
  <TemplateContent>
    <ProjectCollection>
      <SolutionFolder Name="Src">
        <ProjectTemplateLink ProjectName="$projectname$.Api">
          DomainKod.ModulKod.Api\Api.vstemplate
        </ProjectTemplateLink>
        <ProjectTemplateLink ProjectName="$projectname$.Web">
          DomainKod.ModulKod.Web\Web.vstemplate
        </ProjectTemplateLink>
      </SolutionFolder>
      <SolutionFolder Name="Tests">
        <ProjectTemplateLink ProjectName="$projectname$.Web.Tests">
          DomainKod.ModulKod.Web.Tests\Web.Tests.vstemplate
        </ProjectTemplateLink>
      </SolutionFolder>
      <SolutionFolder Name="SolutionItems">
        <ProjectTemplateLink ProjectName="SolutionItems">
          SolutionItems\Solution.vstemplate
        </ProjectTemplateLink>
      </SolutionFolder>
    </ProjectCollection>
  </TemplateContent>
</VSTemplate>

SolutionItems.vstemplate

<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Project">
  <TemplateData>
    <Name>SolutionItems</Name>
    <Description><No description available></Description>
    <ProjectType>CSharp</ProjectType>
    <ProjectSubType>
    </ProjectSubType>
    <SortOrder>1000</SortOrder>
    <CreateNewFolder>true</CreateNewFolder>
    <CreateInPlace>true</CreateInPlace>
    <DefaultName>SolutionDeneme</DefaultName>
    <ProvideDefaultName>true</ProvideDefaultName>
    <LocationField>Enabled</LocationField>
    <EnableLocationBrowseButton>true</EnableLocationBrowseButton>
    <Icon>__TemplateIcon.ico</Icon>
  </TemplateData>
  <TemplateContent>
      <Folder Name="App-Keys" TargetFolderName="App-Keys">
        <ProjectItem ReplaceParameters="true">key.xml</ProjectItem>
      </Folder>
  </TemplateContent>
</VSTemplate>

SolutionItems folder not apper my template create.
How do I enable adding SolutionItems folder templates?


问:
Object.fromEntries only available on iOS? (react native - NOT WEB)
The title is pretty self explanatory but still, consider this sample code:

```<code>import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { Constants } from 'expo';

export default class App extends React.Component {
  render() {
    return (
      <Text>
         {Object.fromEntries("test")}
      </Text>
    );
  }
}
</code>```

Check it out on Expo Snacks

By opening it on an Android device, I get the error that the fromEntries function does not exist on Object:

But on iOS, it does exist:

(bad parameter supplied to it, but it exists, nevertheless)

So what's happening here? Aren't JS engines supposed to be identical between the 2 platforms? What other known discrepancies like these exist?

答:
Most likely you have an old or not-fully-supported engine (check the docs). You can make an ES6 polyfill like this:

```<code>Object.fromEntries = Object.fromEntries || arr => arr.reduce((acc, [k, v]) => (acc[k] = v, acc), {});
</code>```

Or an ES5 polyfill like this:

```<code>Object.fromEntries = Object.fromEntries || function(arr) {
    return arr.reduce(function(acc, curr) {
        acc[curr[0]] = curr[1];
        return acc;
    }, {});
};
</code>```

Body:
The title is pretty self explanatory but still, consider this sample code:

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { Constants } from 'expo';

export default class App extends React.Component {
  render() {
    return (
      <Text>
         {Object.fromEntries("test")}
      </Text>
    );
  }
}

Check it out on Expo Snacks

By opening it on an Android device, I get the error that the fromEntries function does not exist on Object:

But on iOS, it does exist:

(bad parameter supplied to it, but it exists, nevertheless)

So what's happening here? Aren't JS engines supposed to be identical between the 2 platforms? What other known discrepancies like these exist?

Body:
Most likely you have an old or not-fully-supported engine (check the docs). You can make an ES6 polyfill like this:

Object.fromEntries = Object.fromEntries || arr => arr.reduce((acc, [k, v]) => (acc[k] = v, acc), {});

Or an ES5 polyfill like this:

Object.fromEntries = Object.fromEntries || function(arr) {
    return arr.reduce(function(acc, curr) {
        acc[curr[0]] = curr[1];
        return acc;
    }, {});
};


问:
Fluentbit: How to have Kubernetes filter working with cpu input
Does Fluentbit Kubernetes FILTER compatible with cpu and mem INPUT?

I fail to configure cpu and mem INPUT with kubernetes filter.
It's okay with tail INPUT

答:
Kubernetes Filter depends on either and only from Tail or Systemd input plugins to process and enrich records with Kubernetes metadata.

This is documented here:
https://github.com/fluent/fluent-bit-docs/blob/master/filter/kubernetes.md#workflow-of-tail--kubernetes-filter


问:
Replicate a data frame by group
I have the following data frame:

```<code>df = structure(list(Group = c(1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3,
3), index = c(1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 1, 2, 3)), row.names = c(NA,
-13L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

I would like to replicate the column index according to the Group column, one time with each number appearing n consecutive times, and a second time all the numbers appear as a group n times, where n is the size of the group (similarly to rep versus rep with each).

So the output would look like this (lets look only at Group 1 because it is too long):

First option:

```<code>df = structure(list(Group = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1), index = c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4,
4, 4, 4)), row.names = c(NA, -16L), class = c("tbl_df", "tbl",
"data.frame"))
</code>```

Second option:

```<code>df = structure(list(Group = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1), index = c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1,
2, 3, 4)), row.names = c(NA, -16L), class = c("tbl_df", "tbl",
"data.frame"))
</code>```

How do I do this with group_by?

答:
We can use uncount

```<code>library(tidyverse)
df %>%
  group_by(Group) %>%
  uncount(n())
# A tibble: 61 x 2
# Groups:   Group [3]
#   Group index
#   <dbl> <dbl>
# 1     1     1
# 2     1     1
# 3     1     1
# 4     1     1
# 5     1     2
# 6     1     2
# 7     1     2
# 8     1     2
# 9     1     3
#10     1     3
# … with 51 more rows
</code>```

Or using data.table

```<code>library(data.table)
setDT(df)[, .SD[rep(seq_len(.N), .N)], Group]
</code>```

Or with base R

```<code>do.call(rbind, lapply(split(df, df$Group),
       function(x) x[rep(seq_len(nrow(x)), nrow(x)),]))
</code>```

Title: Replicate a data frame by group

Body:
I have the following data frame:

df = structure(list(Group = c(1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3,
3), index = c(1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 1, 2, 3)), row.names = c(NA,
-13L), class = c("tbl_df", "tbl", "data.frame"))

I would like to replicate the column index according to the Group column, one time with each number appearing n consecutive times, and a second time all the numbers appear as a group n times, where n is the size of the group (similarly to rep versus rep with each).

So the output would look like this (lets look only at Group 1 because it is too long):

First option:

df = structure(list(Group = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1), index = c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4,
4, 4, 4)), row.names = c(NA, -16L), class = c("tbl_df", "tbl",
"data.frame"))

Second option:

df = structure(list(Group = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1), index = c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1,
2, 3, 4)), row.names = c(NA, -16L), class = c("tbl_df", "tbl",
"data.frame"))

How do I do this with group_by?

Body:
We can use uncount

library(tidyverse)
df %>%
  group_by(Group) %>%
  uncount(n())
# A tibble: 61 x 2
# Groups:   Group [3]
#   Group index
#   <dbl> <dbl>
# 1     1     1
# 2     1     1
# 3     1     1
# 4     1     1
# 5     1     2
# 6     1     2
# 7     1     2
# 8     1     2
# 9     1     3
#10     1     3
# … with 51 more rows

Or using data.table

library(data.table)
setDT(df)[, .SD[rep(seq_len(.N), .N)], Group]

Or with base R

do.call(rbind, lapply(split(df, df$Group),
       function(x) x[rep(seq_len(nrow(x)), nrow(x)),]))


问:
Ansible Failed to set permissions on the temporary
I am using ansible to replace the ssh keys for a user on multiple RHEL6 & RHEL7 servers.  The task I am running is:

```<code>- name: private key
  copy:
    src: /Users/me/Documents/keys/id_rsa
    dest: ~/.ssh/
    owner: unpriv
    group: unpriv
    mode: 0600
    backup: yes
</code>```

Two of the hosts that I'm trying to update are giving the following error:

fatal: [host1]: FAILED! => {"failed": true, "msg": "Failed to set
  permissions on the temporary files Ansible needs to create when
  becoming an unprivileged user (rc: 1, err: chown: changing ownership
  of /tmp/ansible-tmp-19/': Operation not permitted\nchown: changing
  ownership of/tmp/ansible-tmp-19/stat.py': Operation not
  permitted\n). For information on working around this, see
  https://docs.ansible.com/ansible/become.html#becoming-an-unprivileged-user"}

The thing is that these two that are getting the errors are clones of some that are updating just fine.  I've compared the sudoers and sshd settings, as well as permissions and mount options on the /tmp directory.  They are all the same between the problem hosts and the working ones.  Any ideas on what I could check next?

I am running ansible 2.3.1.0 on Mac OS Sierra, if that helps.

Update:

@techraf

I have no idea why this worked on all hosts except for two. Here is the original playbook:

```<code>- name: ssh_keys
  hosts: my_hosts
  remote_user: my_user
  tasks:
    - include: ./roles/common/tasks/keys.yml
      become: yes
      become_method: sudo
</code>```

and original keys.yml:

```<code>- name: public key
  copy:
    src: /Users/me/Documents/keys/id_rsab
    dest: ~/.ssh/
    owner: unpriv
    group: unpriv
    mode: 060
    backup: yes
</code>```

I changed the playbook to:

```<code>- name: ssh_keys
  hosts: my_hosts
  remote_user: my_user
  tasks:
    - include: ./roles/common/tasks/keys.yml
      become: yes
      become_method: sudo
      become_user: root
</code>```

And keys.yml to:

```<code>- name: public key
  copy:
    src: /Users/me/Documents/keys/id_rsab
    dest: /home/unpriv/.ssh/
    owner: unpriv
    group: unpriv
    mode: 0600
    backup: yes
</code>```

And it worked across all hosts.

答:
Try to install ACL on remote host, after that execute ansible script</p>

```<code>sudo apt-get install acl
</code>```

Body:
I am using ansible to replace the ssh keys for a user on multiple RHEL6 & RHEL7 servers.  The task I am running is:

- name: private key
  copy:
    src: /Users/me/Documents/keys/id_rsa
    dest: ~/.ssh/
    owner: unpriv
    group: unpriv
    mode: 0600
    backup: yes

Two of the hosts that I'm trying to update are giving the following error:

fatal: [host1]: FAILED! => {"failed": true, "msg": "Failed to set
  permissions on the temporary files Ansible needs to create when
  becoming an unprivileged user (rc: 1, err: chown: changing ownership
  of /tmp/ansible-tmp-19/': Operation not permitted\nchown: changing
  ownership of/tmp/ansible-tmp-19/stat.py': Operation not
  permitted\n). For information on working around this, see
  https://docs.ansible.com/ansible/become.html#becoming-an-unprivileged-user"}

The thing is that these two that are getting the errors are clones of some that are updating just fine.  I've compared the sudoers and sshd settings, as well as permissions and mount options on the /tmp directory.  They are all the same between the problem hosts and the working ones.  Any ideas on what I could check next?

I am running ansible 2.3.1.0 on Mac OS Sierra, if that helps.

Update:

@techraf

I have no idea why this worked on all hosts except for two. Here is the original playbook:

- name: ssh_keys
  hosts: my_hosts
  remote_user: my_user
  tasks:
    - include: ./roles/common/tasks/keys.yml
      become: yes
      become_method: sudo

and original keys.yml:

- name: public key
  copy:
    src: /Users/me/Documents/keys/id_rsab
    dest: ~/.ssh/
    owner: unpriv
    group: unpriv
    mode: 060
    backup: yes

I changed the playbook to:

- name: ssh_keys
  hosts: my_hosts
  remote_user: my_user
  tasks:
    - include: ./roles/common/tasks/keys.yml
      become: yes
      become_method: sudo
      become_user: root

And keys.yml to:

- name: public key
  copy:
    src: /Users/me/Documents/keys/id_rsab
    dest: /home/unpriv/.ssh/
    owner: unpriv
    group: unpriv
    mode: 0600
    backup: yes

And it worked across all hosts.

Body:
Try to install ACL on remote host, after that execute ansible script

sudo apt-get install acl


问:
javascript Heap out of memory in one module file
my project has only one module file that's why I think this error occurs. but now what should I do

I tried to create every component has a module file

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

答:
This is a very common problem when building and serving Angular applications.

The node process that runs on ng build and ng serve is limited to 512MB RAM on 32bit systems and 1GB RAM on 64bit systems.

Both processes (serve and build) often requires a lot more than that, so you can fix this by executing the build/serve tasks directly from node_modules, and passing a max_old_space_size parameter along that determines how much RAM you will give the process.

So running ng serve and dedicating 4GB of memory to the process becomes

```<code>node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng serve
</code>```

And runnning ng build while dedicating 4GB of memory is

```<code>node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng build
</code>```

You can add these commands as scripts in your package.json:

```<code>{
  ...
  "scripts": {
    "serve": "node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng serve",
    "build": "node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng build",
  }
  ...
}
</code>```

Body:
This is a very common problem when building and serving Angular applications.

The node process that runs on ng build and ng serve is limited to 512MB RAM on 32bit systems and 1GB RAM on 64bit systems.

Both processes (serve and build) often requires a lot more than that, so you can fix this by executing the build/serve tasks directly from node_modules, and passing a max_old_space_size parameter along that determines how much RAM you will give the process.

So running ng serve and dedicating 4GB of memory to the process becomes

node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng serve

And runnning ng build while dedicating 4GB of memory is

node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng build

You can add these commands as scripts in your package.json:

{
  ...
  "scripts": {
    "serve": "node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng serve",
    "build": "node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng build",
  }
  ...
}


问:
Can't upgrade to Angular 8 - running app generates an error from HttpXsrfInterceptor
After upgrading to Angular8 I get this console error when trying to run the app:

Error: Can't resolve all parameters for HttpXsrfInterceptor: (?,
  [object Object]

I am not using HttpXsrfInterceptor, and have even tried to disabled it.

Do anyone know why this might be happening?

答:
The update.angular.io website states that:

If you use the legacy HttpModule and the Http service, switch to HttpClientModule and the HttpClient service. HttpClient simplifies the default ergonomics (You don't need to map to json anymore) and now supports typed return values and interceptors. Read more on angular.io

So you should remove your dependency on the @angular/http package, and move on to the new way of doing HTTP requests - possibly adapting your codebase accordingly.

The official doc for the "new way" is: https://angular.io/guide/http