问:
R - Building a "supported currencies" list from currency pairs
I'm struggling with a loop in R and I don't know how to address my problem. I have a data frame with three columns like this:

```<code>  base_currency quote_currency       api_key
1           USD            AUD      USDAUD13
2           USD            CAD      USDCAD58
3           EUR            CNY      EURCNY99
4           EUR            CZK      EURCZK65
5           USD            EUR      USDEUR45
6           JPY            HKD      JPYHKD33
7           JPY            RUB      JPYRUB83
</code>```

These are all currency pairs for which I have a data source to get exchange rates through an API. As you can see I can convert USD in AUD (and backwards), USD in CAD (and backwards) etc.

I can't directly convert USD in CNY but since I can convert USD in EUR and then EUR in CNY, I can handle the conversion using intermediate currency pairs.

Using this system I can similarily convert AUD in CAD usig the USD/AUD and USD/CAD pairs. Actually, every currency in the first 5 rows can be converted in any currency prensent in those same rows.

My data frame may also contains currency pairs that are isolated from this "system" like JPY/HKD and JPY/RUB. Through those currency pairs I can get HKD/RUB but that's it. The only way that second "system" of currency pairs could be linked to the first one is to share one of it's currency in either the base_currency column or in the quote_currency column.

My objective is to define a "supported currencies" list. This list would contain the currencies that could be converted into any of the other currencies in that list.

I can see that my data frame present two solutions for that problem :

```<code>[1] "USD" "AUD" "CAD" "EUR" "CNY" "CZK"
[2] "JPY" "HKD" "RUB"
</code>```

The solution that I'm interested in is the first one, because it contains "USD".

My real data.frame contains more than 100 currency pairs, some are redundant from different data sources.

To give you a little more info about the context, I'm building a really basic stock portfolio manager using Shiny:

In the settings, the user can specify the "portfolio currency" with a dropdown item list.

When adding a stock to the portfolio, the user must specify the stock's currency from a similar dropdown item list.

I really want to use that "supported currencies" list to build my dropdown menus so they can be dynamically updated when I add a currency pair to the data frame.

For instance if I ever add USD/JPY to the dataframe my dropdown menus will show those choices:

```<code>"USD" "AUD" "CAD" "EUR" "CNY" "CZK" "JPY" "HKD" "RUB"
</code>```

This task seems far too complicated for my modest R skills so I would really appreciate a little help.

Thank you very much !

@Cedric
Thank you so much for your answer. I edited your code to add extra fake currency pairs to check how it reacted and something doesn't work:

```<code>v<-"base_currency;quote_currency;api_key
1;USD;AUD;USDAUD13
2;USD;CAD;USDCAD58
3;EUR;CNY;EURCNY99
4;EUR;CZK;EURCZK65
5;USD;EUR;USDEUR45
6;JPY;HKD;JPYHKD33
7;JPY;RUB;JPYRUB83
8;ALL;AKU;ALLAKU24
9;AKU;RRR;AKURRR96
10;KKL;LOI;KKLLOI46"

d<-read.delim(textConnection(v),header=TRUE,sep=";",strip.white=TRUE,stringsAsFactors =F)

## (1) check for values appearing in both columns
## those will be linked
mm <- d$base_currency%in%d$quote_currency | d$quote_currency%in%d$base_currency
currency_both_sides<-unique(c(d$base_currency[mm],d$quote_currency[mm]))
## (2) find remaining (unlinked) matching pairs for those
d1<-d$base_currency[d$quote_currency%in%currency_both_sides]
d2<-d$quote_currency[d$base_currency%in%currency_both_sides]
(common <- unique(c(d1,d2,currency_both_sides)))
# "EUR" "USD" "ALL" "AKU" "AUD" "CAD" "CNY" "CZK" "RRR"
## (3) the other will only appear on one side
## Here I'm showing all but in the end it will be every single value,
## with all it's matching value in the second column
## they will form separate sets
nn <- !d$base_currency%in%common | !d$quote_currency%in%common
(onesided<-unique(c(d$base_currency[nn],d$quote_currency[nn])))
# "JPY" "KKL" "HKD" "RUB" "LOI"
</code>```

The common vector ("EUR" "USD" "ALL" "AKU" "AUD" "CAD" "CNY" "CZK" "RRR") contains ALL, AKU and RRR. These 3 currencies can be converted into each others but not into any of the other currencies in that vector, thus they should not appear in the list. Do you have any idea ?
Again, Thank you so much for your help.

UPDATE
I tried something that seems to go in the right direction :

```<code>v<-"base_currency;quote_currency;api_key
1;USD;AUD;USDAUD13
2;USD;CAD;USDCAD58
3;EUR;CNY;EURCNY99
4;EUR;CZK;EURCZK65
5;USD;EUR;USDEUR45
6;JPY;HKD;JPYHKD33
7;JPY;RUB;JPYRUB83
8;ALL;AKU;ALLAKU24
9;AKU;RRR;AKURRR96
10;KKL;LOI;KKLLOI46"

d<-read.delim(textConnection(v),header=TRUE,sep=";",strip.white=TRUE,stringsAsFactors =F)
d
#   base_currency quote_currency  api_key
#1            USD            AUD USDAUD13
#2            USD            CAD USDCAD58
#3            EUR            CNY EURCNY99
#4            EUR            CZK EURCZK65
#5            USD            EUR USDEUR45
#6            JPY            HKD JPYHKD33
#7            JPY            RUB JPYRUB83
#8            ALL            AKU ALLAKU24
#9            AKU            RRR AKURRR96
#10           KKL            LOI KKLLOI46

#Select every currency that appears in the dataframe
all_cur <- c(d$base_currency, d$quote_currency)

#all_cur
# [1] "USD" "USD" "EUR" "EUR" "USD" "JPY" "JPY" "ALL" "AKU" "KKL" "AUD" "CAD" "CNY" "CZK" "EUR" "HKD" "RUB" "AKU" "RRR" "LOI"

#Select only unique items
all_cur_unique <- unique(all_cur)

#all_cur_unique
# [1] "USD" "EUR" "JPY" "ALL" "AKU" "KKL" "AUD" "CAD" "CNY" "CZK" "HKD" "RUB" "RRR" "LOI"

 #for each unique currency create a vector containing that currency and
 #each currency associated with it in a currency pair
 A <- lapply (as.list(all_cur_unique) , function (i) c(i,subset(d$base_currency, d$quote_currency == i), subset(d$quote_currency, d$base_currency == i)))

A
#
#[[1]]
#[1] "USD" "AUD" "CAD" "EUR"
#USD group : every currency in this vector can be converted in any other through USD
#
#
#[[2]]
#[1] "EUR" "USD" "CNY" "CZK"
#EUR group : every currency in this vector can be converted in any other through EUR
#
#
#[[3]]
#[1] "JPY" "HKD" "RUB"
#JPY group : every currency in this vector can be converted in any other through JPY
#
#
#[[4]]
#[1] "ALL" "AKU"
#
#[[5]]
#[1] "AKU" "ALL" "RRR"
#
#[[6]]
#[1] "KKL" "LOI"
#
#[[7]]
#[1] "AUD" "USD"
#
#[[8]]
#[1] "CAD" "USD"
#
#[[9]]
#[1] "CNY" "EUR"
#
#[[10]]
#[1] "CZK" "EUR"
#
#[[11]]
#[1] "HKD" "JPY"
#
#[[12]]
#[1] "RUB" "JPY"
#
#[[13]]
#[1] "RRR" "AKU"
#
#[[14]]
#[1] "LOI" "KKL"
</code>```

Now using this list of vectors I need first to select every vector containing "USD" because USD must be in the "supported currencies", therfore i need these items:

```<code>[[1]]
[1] "USD" "AUD" "CAD" "EUR"

[[2]]
[1] "EUR" "USD" "CNY" "CZK"

[[7]]
[1] "AUD" "USD"

[[8]]
[1] "CAD" "USD"
</code>```

Then I need to combine these vectors and select only unique occurences, I managed to do it like that:

```<code>B <- sapply(A, function(x) is.element('USD', x))
usd_convertible_list <- A[B]
usd_convertible_vector <- Reduce(c, usd_convertible_list)
usd_convertible_vector_unique <- unique(usd_convertible_vector)
usd_convertible_vector_unique

#    "USD" "AUD" "CAD" "EUR" "CNY" "CZK"
</code>```

Then, for each currency in that vector, I need to again select each vector of the list containg that currency:

for "USD":

```<code>[[1]]
[1] "USD" "AUD" "CAD" "EUR"

[[2]]
[1] "EUR" "USD" "CNY" "CZK"

[[7]]
[1] "AUD" "USD"

[[8]]
[1] "CAD" "USD"
</code>```

for "AUD":

```<code>[[1]]
[1] "USD" "AUD" "CAD" "EUR"

[[7]]
[1] "AUD" "USD"
</code>```

for "CAD":

```<code>[[1]]
[1] "USD" "AUD" "CAD" "EUR"

[[8]]
[1] "CAD" "USD"
</code>```

etc. for every currency in "USD" "AUD" "CAD" "EUR" "CNY" "CZK" then combine everything in a new vector, compare that vector with the previous one and if new currencies appears, repeat the operation.

When no new currencies are added to that vector that should means the list is complete and the loop should stop. With the currency pairs provided in the df as an example, the list is complete on the first run, but in case it's needed to go through multiple intermediate currency pairs to make a conversion, this process is needed I think.

For instance

```<code>USD    EUR
EUR    CNY
CNY    RUB
RUB    CHF
</code>```

In this case, even that it doesn't seem obvious, every currency can be converted in any other. To get to it the loop needs to run 3 times when the first vector containing USD is selected.

I believe this process should give me the "supported currencies" vector I'm looking for but I struggle to turn this into code...

答:
```<code>v<-"a;b;c
    1;USD;AUD;USDAUD13
    2;USD;CAD;USDCAD58
    3;EUR;CNY;EURCNY99
    4;EUR;CZK;EURCZK65
    5;USD;EUR;USDEUR45
    6;JPY;HKD;JPYHKD33
    7;JPY;RUB;JPYRUB83
    8;ALL;AKU;ALLAKU24
    9;AKU;RRR;AKURRR96
    10;KKL;LOI;KKLLOI46"
d<-read.delim(textConnection(v),header=TRUE,sep=";",strip.white=TRUE,stringsAsFactors=FALSE)
d<-d[,-3] # not needed
e<-d[,c(2,1)]; colnames(e)<-colnames(d)
f<-rbind(d,e) # since you can run both one way or the other, I create a data
# frame mixing to and fro
require(dplyr)
# this function will left join the df with itself using first and last
# column
# at some point some lines will produce NA (no matching values)
# we will not join using those values, so I'm splitting the dataframe
# in two and working only with the one without NA in last column
my_left_join <-function(df){
  aa <- first(colnames(df))
  cc <- last(colnames(df))
  df0 <- df[is.na(df[,ncol(df)]),] # we will not join NA
  df1 <- df[!is.na(df[,ncol(df)]),]
  df1 <- left_join(df1,df1[,c(1,ncol(df1))],by=setNames(aa,cc))
  df0[,last(colnames(df1))]<-rep(NA,nrow(df0))
  df2 <- rbind(df0,df1)
}
(g<-my_left_join(f))
#a   b b.y
#1  USD AUD USD
#2  USD CAD USD
#3  EUR CNY EUR
#4  EUR CZK EUR
#5  USD EUR CNY
#6  USD EUR CZK
#7  USD EUR USD
#8  JPY HKD JPY
#9  JPY RUB JPY
#10 ALL AKU RRR
#11 ALL AKU ALL
# here we see that we might run into loops, so let's remove values already in line
remove_duplicates_inrow <- function(df) {
  df[,ncol(df)]<-apply(df,1,function(X){
        if (X[length(X)]%in%X[1:(length(X)-1)])  X[length(X)]<-NA
        return( X[length(X)])
      })
  return(df[order(df[ncol(df)]),])
}
(h<-ee(g))
#a   b  b.y
#35 RRR AKU  ALL
#17 CAD USD  AUD
#26 EUR USD  AUD
#15 AUD USD  CAD
#27 EUR USD  CAD
#5  USD EUR  CNY
#23 CZK EUR  CNY
#6  USD EUR  CZK
#21 CNY EUR  CZK
#16 AUD USD  EUR
#19 CAD USD  EUR
#31 RUB JPY  HKD
#10 ALL AKU  RRR
#30 HKD JPY  RUB
#22 CNY EUR  USD
#25 CZK EUR  USD
#1  USD AUD <NA>
#2  USD CAD <NA>
# this function will recursive left join untill there is no matching
# due to the way it is built I have to remove the last two columns
recursive_join <-function (df){
  #print(df)
  #browser()
  df <- my_left_join(df)
  df <- remove_duplicates_inrow(df)
  if (all(is.na(df[,ncol(df)]))){
    return(df[order(df[ncol(df)]),-ncol(df)])
  } else {
    recursive_join(df)
  }
}

i<-recursive_join(f)
# everything is a mix, I sort by row and by col to obtain the right order
# order by row
i<-t(apply(i,1,function(X)X[order(X)]))
# order by all columns, note this is a problem as we don't know in advance
# the number of columns, I have asked a question regarding this.
i<-i[order(i[,1],i[,2],i[,3],i[,4]),]
</code>```

the latter assumes that we have only 4 columns, I have posted a question
here asking how to do that if the number of column is unknown.
Below the adapted answer :

```<code>col=""
for (j in 1:ncol(i)){
  col <- paste(col,paste0( 'i[,',j,']' ), sep = "," )
}
## remove first comma
col <- substr(col,2,nchar(col))
i <- eval(parse(text= paste("A[order(",col,",decreasing=TRUE),]")))

# now we have duplicated
i<-i[!duplicated(i),]
# OK these duplicates were the easy ones, but we have vectors of different
length, lets remove vector that are contained in longer vectors

res<-matrix(i[1, ],1,ncol(i))
for (l in 2:nrow(i)){
  # comparing line with last in res but remove NA
  # as we have sorted data this works !
  if (!all(i[l,][!is.na(i[l,])]
  %in%
  res[nrow(res),][!is.na(res[nrow(res),])])){
    res<-rbind(res,i[l,])
  }
}
res
#[,1]  [,2]  [,3]  [,4]
#[1,] "AKU" "ALL" "RRR" NA
#[2,] "AUD" "CAD" "EUR" "USD"
#[3,] "CNY" "CZK" "EUR" "USD"
#[4,] "HKD" "JPY" "RUB" NA
#[5,] "KKL" "LOI" NA    NA
</code>```

Body:
I'm struggling with a loop in R and I don't know how to address my problem. I have a data frame with three columns like this:

  base_currency quote_currency       api_key
1           USD            AUD      USDAUD13
2           USD            CAD      USDCAD58
3           EUR            CNY      EURCNY99
4           EUR            CZK      EURCZK65
5           USD            EUR      USDEUR45
6           JPY            HKD      JPYHKD33
7           JPY            RUB      JPYRUB83

These are all currency pairs for which I have a data source to get exchange rates through an API. As you can see I can convert USD in AUD (and backwards), USD in CAD (and backwards) etc.

I can't directly convert USD in CNY but since I can convert USD in EUR and then EUR in CNY, I can handle the conversion using intermediate currency pairs.

Using this system I can similarily convert AUD in CAD usig the USD/AUD and USD/CAD pairs. Actually, every currency in the first 5 rows can be converted in any currency prensent in those same rows.

My data frame may also contains currency pairs that are isolated from this "system" like JPY/HKD and JPY/RUB. Through those currency pairs I can get HKD/RUB but that's it. The only way that second "system" of currency pairs could be linked to the first one is to share one of it's currency in either the base_currency column or in the quote_currency column.

My objective is to define a "supported currencies" list. This list would contain the currencies that could be converted into any of the other currencies in that list.

I can see that my data frame present two solutions for that problem :

[1] "USD" "AUD" "CAD" "EUR" "CNY" "CZK"
[2] "JPY" "HKD" "RUB"

The solution that I'm interested in is the first one, because it contains "USD".

My real data.frame contains more than 100 currency pairs, some are redundant from different data sources.

To give you a little more info about the context, I'm building a really basic stock portfolio manager using Shiny:

In the settings, the user can specify the "portfolio currency" with a dropdown item list.

When adding a stock to the portfolio, the user must specify the stock's currency from a similar dropdown item list.

I really want to use that "supported currencies" list to build my dropdown menus so they can be dynamically updated when I add a currency pair to the data frame.

For instance if I ever add USD/JPY to the dataframe my dropdown menus will show those choices:

"USD" "AUD" "CAD" "EUR" "CNY" "CZK" "JPY" "HKD" "RUB"

This task seems far too complicated for my modest R skills so I would really appreciate a little help.

Thank you very much !

@Cedric
Thank you so much for your answer. I edited your code to add extra fake currency pairs to check how it reacted and something doesn't work:

v<-"base_currency;quote_currency;api_key
1;USD;AUD;USDAUD13
2;USD;CAD;USDCAD58
3;EUR;CNY;EURCNY99
4;EUR;CZK;EURCZK65
5;USD;EUR;USDEUR45
6;JPY;HKD;JPYHKD33
7;JPY;RUB;JPYRUB83
8;ALL;AKU;ALLAKU24
9;AKU;RRR;AKURRR96
10;KKL;LOI;KKLLOI46"

d<-read.delim(textConnection(v),header=TRUE,sep=";",strip.white=TRUE,stringsAsFactors =F)

## (1) check for values appearing in both columns
## those will be linked
mm <- d$base_currency%in%d$quote_currency | d$quote_currency%in%d$base_currency
currency_both_sides<-unique(c(d$base_currency[mm],d$quote_currency[mm]))
## (2) find remaining (unlinked) matching pairs for those
d1<-d$base_currency[d$quote_currency%in%currency_both_sides]
d2<-d$quote_currency[d$base_currency%in%currency_both_sides]
(common <- unique(c(d1,d2,currency_both_sides)))
# "EUR" "USD" "ALL" "AKU" "AUD" "CAD" "CNY" "CZK" "RRR"
## (3) the other will only appear on one side
## Here I'm showing all but in the end it will be every single value,
## with all it's matching value in the second column
## they will form separate sets
nn <- !d$base_currency%in%common | !d$quote_currency%in%common
(onesided<-unique(c(d$base_currency[nn],d$quote_currency[nn])))
# "JPY" "KKL" "HKD" "RUB" "LOI"

The common vector ("EUR" "USD" "ALL" "AKU" "AUD" "CAD" "CNY" "CZK" "RRR") contains ALL, AKU and RRR. These 3 currencies can be converted into each others but not into any of the other currencies in that vector, thus they should not appear in the list. Do you have any idea ?
Again, Thank you so much for your help.

UPDATE
I tried something that seems to go in the right direction :

v<-"base_currency;quote_currency;api_key
1;USD;AUD;USDAUD13
2;USD;CAD;USDCAD58
3;EUR;CNY;EURCNY99
4;EUR;CZK;EURCZK65
5;USD;EUR;USDEUR45
6;JPY;HKD;JPYHKD33
7;JPY;RUB;JPYRUB83
8;ALL;AKU;ALLAKU24
9;AKU;RRR;AKURRR96
10;KKL;LOI;KKLLOI46"

d<-read.delim(textConnection(v),header=TRUE,sep=";",strip.white=TRUE,stringsAsFactors =F)
d
#   base_currency quote_currency  api_key
#1            USD            AUD USDAUD13
#2            USD            CAD USDCAD58
#3            EUR            CNY EURCNY99
#4            EUR            CZK EURCZK65
#5            USD            EUR USDEUR45
#6            JPY            HKD JPYHKD33
#7            JPY            RUB JPYRUB83
#8            ALL            AKU ALLAKU24
#9            AKU            RRR AKURRR96
#10           KKL            LOI KKLLOI46

#Select every currency that appears in the dataframe
all_cur <- c(d$base_currency, d$quote_currency)

#all_cur
# [1] "USD" "USD" "EUR" "EUR" "USD" "JPY" "JPY" "ALL" "AKU" "KKL" "AUD" "CAD" "CNY" "CZK" "EUR" "HKD" "RUB" "AKU" "RRR" "LOI"

#Select only unique items
all_cur_unique <- unique(all_cur)

#all_cur_unique
# [1] "USD" "EUR" "JPY" "ALL" "AKU" "KKL" "AUD" "CAD" "CNY" "CZK" "HKD" "RUB" "RRR" "LOI"

 #for each unique currency create a vector containing that currency and
 #each currency associated with it in a currency pair
 A <- lapply (as.list(all_cur_unique) , function (i) c(i,subset(d$base_currency, d$quote_currency == i), subset(d$quote_currency, d$base_currency == i)))

A
#
#[[1]]
#[1] "USD" "AUD" "CAD" "EUR"
#USD group : every currency in this vector can be converted in any other through USD
#
#
#[[2]]
#[1] "EUR" "USD" "CNY" "CZK"
#EUR group : every currency in this vector can be converted in any other through EUR
#
#
#[[3]]
#[1] "JPY" "HKD" "RUB"
#JPY group : every currency in this vector can be converted in any other through JPY
#
#
#[[4]]
#[1] "ALL" "AKU"
#
#[[5]]
#[1] "AKU" "ALL" "RRR"
#
#[[6]]
#[1] "KKL" "LOI"
#
#[[7]]
#[1] "AUD" "USD"
#
#[[8]]
#[1] "CAD" "USD"
#
#[[9]]
#[1] "CNY" "EUR"
#
#[[10]]
#[1] "CZK" "EUR"
#
#[[11]]
#[1] "HKD" "JPY"
#
#[[12]]
#[1] "RUB" "JPY"
#
#[[13]]
#[1] "RRR" "AKU"
#
#[[14]]
#[1] "LOI" "KKL"

Now using this list of vectors I need first to select every vector containing "USD" because USD must be in the "supported currencies", therfore i need these items:

[[1]]
[1] "USD" "AUD" "CAD" "EUR"

[[2]]
[1] "EUR" "USD" "CNY" "CZK"

[[7]]
[1] "AUD" "USD"

[[8]]
[1] "CAD" "USD"

Then I need to combine these vectors and select only unique occurences, I managed to do it like that:

B <- sapply(A, function(x) is.element('USD', x))
usd_convertible_list <- A[B]
usd_convertible_vector <- Reduce(c, usd_convertible_list)
usd_convertible_vector_unique <- unique(usd_convertible_vector)
usd_convertible_vector_unique

#    "USD" "AUD" "CAD" "EUR" "CNY" "CZK"

Then, for each currency in that vector, I need to again select each vector of the list containg that currency:

for "USD":

[[1]]
[1] "USD" "AUD" "CAD" "EUR"

[[2]]
[1] "EUR" "USD" "CNY" "CZK"

[[7]]
[1] "AUD" "USD"

[[8]]
[1] "CAD" "USD"

for "AUD":

[[1]]
[1] "USD" "AUD" "CAD" "EUR"

[[7]]
[1] "AUD" "USD"

for "CAD":

[[1]]
[1] "USD" "AUD" "CAD" "EUR"

[[8]]
[1] "CAD" "USD"

etc. for every currency in "USD" "AUD" "CAD" "EUR" "CNY" "CZK" then combine everything in a new vector, compare that vector with the previous one and if new currencies appears, repeat the operation.

When no new currencies are added to that vector that should means the list is complete and the loop should stop. With the currency pairs provided in the df as an example, the list is complete on the first run, but in case it's needed to go through multiple intermediate currency pairs to make a conversion, this process is needed I think.

For instance

USD    EUR
EUR    CNY
CNY    RUB
RUB    CHF

In this case, even that it doesn't seem obvious, every currency can be converted in any other. To get to it the loop needs to run 3 times when the first vector containing USD is selected.

I believe this process should give me the "supported currencies" vector I'm looking for but I struggle to turn this into code...

Body:
v<-"a;b;c
    1;USD;AUD;USDAUD13
    2;USD;CAD;USDCAD58
    3;EUR;CNY;EURCNY99
    4;EUR;CZK;EURCZK65
    5;USD;EUR;USDEUR45
    6;JPY;HKD;JPYHKD33
    7;JPY;RUB;JPYRUB83
    8;ALL;AKU;ALLAKU24
    9;AKU;RRR;AKURRR96
    10;KKL;LOI;KKLLOI46"
d<-read.delim(textConnection(v),header=TRUE,sep=";",strip.white=TRUE,stringsAsFactors=FALSE)
d<-d[,-3] # not needed
e<-d[,c(2,1)]; colnames(e)<-colnames(d)
f<-rbind(d,e) # since you can run both one way or the other, I create a data
# frame mixing to and fro
require(dplyr)
# this function will left join the df with itself using first and last
# column
# at some point some lines will produce NA (no matching values)
# we will not join using those values, so I'm splitting the dataframe
# in two and working only with the one without NA in last column
my_left_join <-function(df){
  aa <- first(colnames(df))
  cc <- last(colnames(df))
  df0 <- df[is.na(df[,ncol(df)]),] # we will not join NA
  df1 <- df[!is.na(df[,ncol(df)]),]
  df1 <- left_join(df1,df1[,c(1,ncol(df1))],by=setNames(aa,cc))
  df0[,last(colnames(df1))]<-rep(NA,nrow(df0))
  df2 <- rbind(df0,df1)
}
(g<-my_left_join(f))
#a   b b.y
#1  USD AUD USD
#2  USD CAD USD
#3  EUR CNY EUR
#4  EUR CZK EUR
#5  USD EUR CNY
#6  USD EUR CZK
#7  USD EUR USD
#8  JPY HKD JPY
#9  JPY RUB JPY
#10 ALL AKU RRR
#11 ALL AKU ALL
# here we see that we might run into loops, so let's remove values already in line
remove_duplicates_inrow <- function(df) {
  df[,ncol(df)]<-apply(df,1,function(X){
        if (X[length(X)]%in%X[1:(length(X)-1)])  X[length(X)]<-NA
        return( X[length(X)])
      })
  return(df[order(df[ncol(df)]),])
}
(h<-ee(g))
#a   b  b.y
#35 RRR AKU  ALL
#17 CAD USD  AUD
#26 EUR USD  AUD
#15 AUD USD  CAD
#27 EUR USD  CAD
#5  USD EUR  CNY
#23 CZK EUR  CNY
#6  USD EUR  CZK
#21 CNY EUR  CZK
#16 AUD USD  EUR
#19 CAD USD  EUR
#31 RUB JPY  HKD
#10 ALL AKU  RRR
#30 HKD JPY  RUB
#22 CNY EUR  USD
#25 CZK EUR  USD
#1  USD AUD <NA>
#2  USD CAD <NA>
# this function will recursive left join untill there is no matching
# due to the way it is built I have to remove the last two columns
recursive_join <-function (df){
  #print(df)
  #browser()
  df <- my_left_join(df)
  df <- remove_duplicates_inrow(df)
  if (all(is.na(df[,ncol(df)]))){
    return(df[order(df[ncol(df)]),-ncol(df)])
  } else {
    recursive_join(df)
  }
}

i<-recursive_join(f)
# everything is a mix, I sort by row and by col to obtain the right order
# order by row
i<-t(apply(i,1,function(X)X[order(X)]))
# order by all columns, note this is a problem as we don't know in advance
# the number of columns, I have asked a question regarding this.
i<-i[order(i[,1],i[,2],i[,3],i[,4]),]

the latter assumes that we have only 4 columns, I have posted a question
here asking how to do that if the number of column is unknown.
Below the adapted answer :

col=""
for (j in 1:ncol(i)){
  col <- paste(col,paste0( 'i[,',j,']' ), sep = "," )
}
## remove first comma
col <- substr(col,2,nchar(col))
i <- eval(parse(text= paste("A[order(",col,",decreasing=TRUE),]")))

# now we have duplicated
i<-i[!duplicated(i),]
# OK these duplicates were the easy ones, but we have vectors of different
length, lets remove vector that are contained in longer vectors

res<-matrix(i[1, ],1,ncol(i))
for (l in 2:nrow(i)){
  # comparing line with last in res but remove NA
  # as we have sorted data this works !
  if (!all(i[l,][!is.na(i[l,])]
  %in%
  res[nrow(res),][!is.na(res[nrow(res),])])){
    res<-rbind(res,i[l,])
  }
}
res
#[,1]  [,2]  [,3]  [,4]
#[1,] "AKU" "ALL" "RRR" NA
#[2,] "AUD" "CAD" "EUR" "USD"
#[3,] "CNY" "CZK" "EUR" "USD"
#[4,] "HKD" "JPY" "RUB" NA
#[5,] "KKL" "LOI" NA    NA


来源: stackexchange

问:
Can I ReadLock a file while I create/modify it using System.IO.File.WriteAllText() method?
I need to create a process that creates/modifies some text files in a folder. I am using below code to do that:

```<code>file = new System.IO.FileInfo(filePath);
file.Directory.Create();
System.IO.File.WriteAllText(file.FullName, "Some text...");
</code>```

I have a Biztalk queue that looks into the text files in the folder every 2 minutes and picks up the files to process them. I want to lock the files when I am creating/modifying so that Biztalk wont try to process those files. How can I achieve this?

I read about Transactional NTFS in windows which will let me create Transaction context but windows documentation says this feature will deprecated and recommends not to use it.

答:
To acquire an exclusive lock you can use the file stream to do so

```<code>        using (FileStream fs = new FileStream("Test.txt", FileMode.Append, FileAccess.Write, FileShare.None))
        {
            using (StreamWriter sw = new StreamWriter(fs))
            {
                sw.WriteLine("test");
            }
        }
</code>```

This way you are locking the file exclusively for the current file stream. Any other application or even a new instance of file stream from another thread within the same application attempts to read or write to the file will be denied by the operating system.

ContentLicense: CC BY-SA 3.0

Body:
I need to create a process that creates/modifies some text files in a folder. I am using below code to do that:

file = new System.IO.FileInfo(filePath);
file.Directory.Create();
System.IO.File.WriteAllText(file.FullName, "Some text...");

I have a Biztalk queue that looks into the text files in the folder every 2 minutes and picks up the files to process them. I want to lock the files when I am creating/modifying so that Biztalk wont try to process those files. How can I achieve this?

I read about Transactional NTFS in windows which will let me create Transaction context but windows documentation says this feature will deprecated and recommends not to use it.

Body:
To acquire an exclusive lock you can use the file stream to do so

        using (FileStream fs = new FileStream("Test.txt", FileMode.Append, FileAccess.Write, FileShare.None))
        {
            using (StreamWriter sw = new StreamWriter(fs))
            {
                sw.WriteLine("test");
            }
        }

This way you are locking the file exclusively for the current file stream. Any other application or even a new instance of file stream from another thread within the same application attempts to read or write to the file will be denied by the operating system.


问:
How to make a Ajax search with Symfony and Jquery
hi guys i'm working in symfony project and i would like to do a realtime search using ajax.
I tried but its not working, for some reason, returns all datas from the database and not the data that i'm searching using keyup.
Can anyone help me please.
here is my code

```<code><div id="div">
    </div>

    <table border="1">
    <tr>
        <td>Id</td><td>Libelle</td><td>pays</td>
    </tr>
    {% for i in voitures %}
            <tr>
            <td>{{ i.id}}</td>
            <td>{{ i.libelle}}</td>
            <td>{{ i.pays}}</td>

           </tr>
     {% endfor %}
    </table>
    {{ form_start(form) }}
    {{ form(form) }}
    {{ form_errors(form) }}
    {{ form_end(form) }}

     <script src="{{ asset('js/jquery.js') }}"></script>
     <script>
     $("#myapp_parcbundle_marque_libelle").keyup(
            function(){
                 var serie=$('#myapp_parcbundle_marque_libelle').val();
                var DATA = 'serie=' + serie;
                $.ajax({
                    type: "POST",
                    url: "{{ path('demo_create')}}",
                    data:DATA,
                    success: function (msg) {
                        $( "#div" ).html( msg );
                    }
                });
            });

</script>
</code>```

Controller

```<code>function testAction(Request $request)
{
    $voiture = new Marque();
    $em = $this->getDoctrine()->getManager();
    $voitures=$em->getRepository('MyAppParcBundle:Marque')->findAll();
    $Form = $this->createForm(RechercheForm::class, $voiture);
    $Form->handleRequest($request);

    if($request->isXmlHttpRequest()&&($Form->isValid())){

        $voitures = $em->getRepository("MyAppParcBundle:Marque")
            ->findBy(array('serie'=>$voiture->getSerie()));
        return new JsonResponse($voitures);

    }
    return $this->render(
        'MyAppParcBundle:Marque:Recherche2.html.twig',
        array("voitures" => $voitures,
            "form" => $Form->createView()));

}
</code>```

答:
so i fixed the probleme my controller whould be : </p>

```<code>function testAction(Request $request)
{
    $voiture = new Marque();
    $em = $this->getDoctrine()->getManager();
    $voitures=$em->getRepository('MyAppParcBundle:Marque')->findAll();
    $Form = $this->createForm(RechercheForm::class, $voiture);
    $Form->handleRequest($request);
    if($request->isXmlHttpRequest()){
        $serializer = new Serializer(array(new ObjectNormalizer()));
        $voitures=$em->getRepository('MyAppParcBundle:Marque')
            ->findBy(array('libelle'=>$request->get('libelle')));
        $data = $serializer->normalize($voitures);
        return new JsonResponse($data);
    }
    return $this->render(
        'MyAppParcBundle:Marque:Recherche2.html.twig',
        array("voitures" => $voitures,
            "form" => $Form->createView()));

}
</code>```

<p>and i changed the view : </p>

```<code><div id="div">
</div>

<div id="affichage">
    <table border="1">
        <tr>
            <td>Id</td><td>Libelle</td><td>pays</td>
        </tr>
        {% for i in voitures %}

            <tr>
                <td>{{ i.id}}</td>
                <td>{{ i.libelle}}</td>
                <td>{{ i.pays}}</td>

            </tr>

        {% endfor %}
    </table>

</div>
{{ form_start(form) }}
{{ form(form) }}
    {{ form_errors(form) }}
{{ form_end(form) }}

<script src="{{ asset('js/jquery.js') }}"></script>
<script>

    $("#myapp_parcbundle_marque_libelle").keyup(
            function(){
                var serie=$('#myapp_parcbundle_marque_libelle').val();
                var DATA =  {'libelle' : serie};
                $.ajax({
                    type: "POST",
                    url: "{{ path('demo_create')}}",
                    data:DATA,
                    success: function (data) {
                        $.each(data,function(k,el) {
                            $("#affichage").hide();
                            $( "#div" ).html("<ul></ul>");
                            $('ul').append(
                                    "<li>"+el.libelle+"</li>"+
                                    "<li>"+el.pays+"</li>"
                            );
                        });
                    },
                    error:function ()
                    {
                        console.log("error "+DATA);
                    }
                });
            });

</script>
</code>```

Body:
hi guys i'm working in symfony project and i would like to do a realtime search using ajax.
I tried but its not working, for some reason, returns all datas from the database and not the data that i'm searching using keyup.
Can anyone help me please.
here is my code

        Id	Libelle	pays

    {% for i in voitures %}

            {{ i.id}}
            {{ i.libelle}}
            {{ i.pays}}

     {% endfor %}

    {{ form_start(form) }}
    {{ form(form) }}
    {{ form_errors(form) }}
    {{ form_end(form) }}

Controller

function testAction(Request $request)
{
    $voiture = new Marque();
    $em = $this->getDoctrine()->getManager();
    $voitures=$em->getRepository('MyAppParcBundle:Marque')->findAll();
    $Form = $this->createForm(RechercheForm::class, $voiture);
    $Form->handleRequest($request);

    if($request->isXmlHttpRequest()&&($Form->isValid())){

        $voitures = $em->getRepository("MyAppParcBundle:Marque")
            ->findBy(array('serie'=>$voiture->getSerie()));
        return new JsonResponse($voitures);

    }
    return $this->render(
        'MyAppParcBundle:Marque:Recherche2.html.twig',
        array("voitures" => $voitures,
            "form" => $Form->createView()));

}

Body:
so i fixed the probleme my controller whould be :

function testAction(Request $request)
{
    $voiture = new Marque();
    $em = $this->getDoctrine()->getManager();
    $voitures=$em->getRepository('MyAppParcBundle:Marque')->findAll();
    $Form = $this->createForm(RechercheForm::class, $voiture);
    $Form->handleRequest($request);
    if($request->isXmlHttpRequest()){
        $serializer = new Serializer(array(new ObjectNormalizer()));
        $voitures=$em->getRepository('MyAppParcBundle:Marque')
            ->findBy(array('libelle'=>$request->get('libelle')));
        $data = $serializer->normalize($voitures);
        return new JsonResponse($data);
    }
    return $this->render(
        'MyAppParcBundle:Marque:Recherche2.html.twig',
        array("voitures" => $voitures,
            "form" => $Form->createView()));

}

and i changed the view :

<div id="div">
</div>

<div id="affichage">
    <table border="1">
        <tr>
            <td>Id</td><td>Libelle</td><td>pays</td>
        </tr>
        {% for i in voitures %}

            <tr>
                <td>{{ i.id}}</td>
                <td>{{ i.libelle}}</td>
                <td>{{ i.pays}}</td>

            </tr>

        {% endfor %}
    </table>

</div>
{{ form_start(form) }}
{{ form(form) }}
    {{ form_errors(form) }}
{{ form_end(form) }}

<script src="{{ asset('js/jquery.js') }}"></script>
<script>

    $("#myapp_parcbundle_marque_libelle").keyup(
            function(){
                var serie=$('#myapp_parcbundle_marque_libelle').val();
                var DATA =  {'libelle' : serie};
                $.ajax({
                    type: "POST",
                    url: "{{ path('demo_create')}}",
                    data:DATA,
                    success: function (data) {
                        $.each(data,function(k,el) {
                            $("#affichage").hide();
                            $( "#div" ).html("<ul></ul>");
                            $('ul').append(
                                    "<li>"+el.libelle+"</li>"+
                                    "<li>"+el.pays+"</li>"
                            );
                        });
                    },
                    error:function ()
                    {
                        console.log("error "+DATA);
                    }
                });
            });

</script>


问:
Why is the address of a variable defined inside a loop unchanged on each iteration?
```<code>for(int i=0; i<10;i++){
    int j = i;
    cout << &j << endl;
}
</code>```

This will output the same address of j in each iteration.  I also noticed the same behavior in C.  Shouldn't it be a different address for different iteration ?

In python different address is printed, couldn't verify it in java

```<code>for i in range(10):
    j = i
    print(hex(id(j)))
</code>```

c++ -v on my system returns this

Using built-in specs.
COLLECT_GCC=c++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 7.2.0-8ubuntu3' --with-bugurl=file:///usr/share/doc/gcc-7/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++ --prefix=/usr --with-gcc-major-version-only --program-suffix=-7 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 7.2.0 (Ubuntu 7.2.0-8ubuntu3)
```

答:
shouldn't it be a different address for different iteration ?

There's no requirement for it to be this way. In fact, on a common implementation where a local variable is located on a functions call frame (on the so called call stack), it's rather easy for the address to be unchanging. It's just reusing the same space, relative to the start of the frame.

In python different address is printed

Because the implementation in Python is different. In each iteration i is reference for a different object in the range. It's not the same storage taking on a different object and value.

Body:
for(int i=0; i<10;i++){
    int j = i;
    cout << &j << endl;
}

This will output the same address of j in each iteration.  I also noticed the same behavior in C.  Shouldn't it be a different address for different iteration ?

In python different address is printed, couldn't verify it in java

for i in range(10):
    j = i
    print(hex(id(j)))

c++ -v on my system returns this

Using built-in specs.
COLLECT_GCC=c++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 7.2.0-8ubuntu3' --with-bugurl=file:///usr/share/doc/gcc-7/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++ --prefix=/usr --with-gcc-major-version-only --program-suffix=-7 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 7.2.0 (Ubuntu 7.2.0-8ubuntu3)


问:
Create a column based on other columns value
I'm looking for a way to create a new column with values based on the value in the first column, with the highest score in the same cluster.

The goal is to move from this:

```<code>WORD     | SCORE | Cluster |
diptyqu  | 19750 |    1    |
daptyqu  | 8830  |    1    |
dyptiqu  | 29    |    1    |
deptiqu  | 2     |    1    |
parfume  | 300   |    2    |
parfum   | 14    |    2    |
</code>```

To this:

```<code>WORD     | SCORE | Cluster | Name    |
diptyqu  | 19750 |    1    | diptyqu |
daptyqu  | 8830  |    1    | diptyqu |
dyptiqu  | 29    |    1    | diptyqu |
deptiqu  | 2     |    1    | diptyqu |
parfume  | 300   |    2    | parfume |
parfum   | 14    |    2    | parfume |
</code>```

I'm litteraly stuck and don't really know how to make it. Do you have any suggestion on a method to do this?

答:
```<code>do.call(rbind,
        lapply(split(dat, dat$Cluster), function(a)
            data.frame(a, Name = a$WORD[which.max(a$SCORE)])))
#       WORD SCORE Cluster    Name
#1.1 diptyqu 19750       1 diptyqu
#1.2 daptyqu  8830       1 diptyqu
#1.3 dyptiqu    29       1 diptyqu
#1.4 deptiqu     2       1 diptyqu
#2.5 parfume   300       2 parfume
#2.6  parfum    14       2 parfume
</code>```

Body:
I'm looking for a way to create a new column with values based on the value in the first column, with the highest score in the same cluster.

The goal is to move from this:

WORD     | SCORE | Cluster |
diptyqu  | 19750 |    1    |
daptyqu  | 8830  |    1    |
dyptiqu  | 29    |    1    |
deptiqu  | 2     |    1    |
parfume  | 300   |    2    |
parfum   | 14    |    2    |

To this:

WORD     | SCORE | Cluster | Name    |
diptyqu  | 19750 |    1    | diptyqu |
daptyqu  | 8830  |    1    | diptyqu |
dyptiqu  | 29    |    1    | diptyqu |
deptiqu  | 2     |    1    | diptyqu |
parfume  | 300   |    2    | parfume |
parfum   | 14    |    2    | parfume |

I'm litteraly stuck and don't really know how to make it. Do you have any suggestion on a method to do this?


问:
Django - allowing specified user to modify certain model fields
I need to allow a certain user, who is specified in the model, to modify a few of the model's fields. I know I need to create a permission class, which will control the whole process, but I have no idea how to do that.
Here's the code sample:

```<code>class Task(models.Model):
   creator = models.ForeignKey('auth.User', related_name='created_tasks', on_delete=models.CASCADE)
   target = models.ForeignKey(User, related_name='assigned_tasks', on_delete=models.CASCADE)
   title = models.CharField(max_length=100)
   description = models.TextField()
   created = models.DateTimeField(auto_now_add=True)
   deadline = models.DateTimeField()
   priority = models.CharField(max_length=50, choices=PRIORITY_CHOICES, default='NORMAL')
   progress = models.CharField(max_length=50, choices=PROGRESS_CHOICES, default='ASSIGNED')
   is_finished = models.BooleanField(default=False)
</code>```

So I want to allow the target, to modify only progress and is_finished fields.

I am using DjangoRestFramework, not sure if that will help.
Should I create a method, which will check if user == target, and ignore all the other changes or is it possible to create a permission which will do that.

答: You can use groups, assign certain permissions on that group and put your target user in your group, just need to go to admin site to setup the groups. Hope this help you.</p>

Body:
I need to allow a certain user, who is specified in the model, to modify a few of the model's fields. I know I need to create a permission class, which will control the whole process, but I have no idea how to do that.
Here's the code sample:

class Task(models.Model):
   creator = models.ForeignKey('auth.User', related_name='created_tasks', on_delete=models.CASCADE)
   target = models.ForeignKey(User, related_name='assigned_tasks', on_delete=models.CASCADE)
   title = models.CharField(max_length=100)
   description = models.TextField()
   created = models.DateTimeField(auto_now_add=True)
   deadline = models.DateTimeField()
   priority = models.CharField(max_length=50, choices=PRIORITY_CHOICES, default='NORMAL')
   progress = models.CharField(max_length=50, choices=PROGRESS_CHOICES, default='ASSIGNED')
   is_finished = models.BooleanField(default=False)

So I want to allow the target, to modify only progress and is_finished fields.

I am using DjangoRestFramework, not sure if that will help.
Should I create a method, which will check if user == target, and ignore all the other changes or is it possible to create a permission which will do that.


问:
Nested range() in range() in Python
Can you nested the range in range? Use variable in range? Because I would like to get some effect. To illustrate the problem I have the following pseudocode:

```<code>for i in range(str(2**i) for i in range(1,2)):
    print (str(i*0.01))
</code>```

At the exit I would like to receive:

```<code>0   0.01
1   0.01
2   0.02
3   0.02
4   0.02
5   0.02
</code>```

Where the number of numbers 0.01 in the column will be 2^1, the number of numbers 0.02 are 2^2, the number of numbers 0.03 are 2^3, and so on ... I will be grateful for any hint as to how to approach this.

答:
For this specific task you'll want to nest them like this:

```<code>for i in range(1,3):
    for j in range(2**i):
        print(i * 0.01)
</code>```

which will print what you want. What this is doing is taking a number i in range(1,3) #[1,2] and then print i * 0.01 2**i number of times which I believe is what you are trying to do.

Title: Nested range() in range() in Python

Body:
Can you nested the range in range? Use variable in range? Because I would like to get some effect. To illustrate the problem I have the following pseudocode:

for i in range(str(2**i) for i in range(1,2)):
    print (str(i*0.01))

At the exit I would like to receive:

0   0.01
1   0.01
2   0.02
3   0.02
4   0.02
5   0.02

Where the number of numbers 0.01 in the column will be 2^1, the number of numbers 0.02 are 2^2, the number of numbers 0.03 are 2^3, and so on ... I will be grateful for any hint as to how to approach this.

Body:
For this specific task you'll want to nest them like this:

for i in range(1,3):
    for j in range(2**i):
        print(i * 0.01)

which will print what you want. What this is doing is taking a number i in range(1,3) #[1,2] and then print i * 0.01 2**i number of times which I believe is what you are trying to do.


问:
Am I doing something wrong, or do Intel graphic cards suck so bad?
I have

VGA compatible controller: Intel Corporation 82G33/G31 Express Integrated Graphics Controller (rev 10) on Ubuntu 10.10 Linux.

I'm rendering statically one VBO per frame. This VBO has 30,000 triangles, with 3 lights and one texture, and I'm getting 15 FPS.

Are intel cards so bad, or am I doing sth wrong?

Drivers are standard, open source drivers from intel.

My code:

```<code>
void init() {
  glGenBuffersARB(4, vbos);
  glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbos[0]);
  glBufferDataARB(GL_ARRAY_BUFFER_ARB, sizeof(GLfloat) * verticesNum * 3, vertXYZ, GL_STATIC_DRAW_ARB);
  glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbos[1]);
  glBufferDataARB(GL_ARRAY_BUFFER_ARB, sizeof(GLfloat) * verticesNum * 4, colorRGBA, GL_STATIC_DRAW_ARB);
  glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbos[2]);
  glBufferDataARB(GL_ARRAY_BUFFER_ARB, sizeof(GLfloat) * verticesNum * 3, normXYZ, GL_STATIC_DRAW_ARB);
  glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbos[3]);
  glBufferDataARB(GL_ARRAY_BUFFER_ARB, sizeof(GLfloat) * verticesNum * 2, texXY, GL_STATIC_DRAW_ARB);
}

void draw() {
  glPushMatrix();

  const Vector3f O = ps.getPosition();

  glScalef(scaleXYZ[0], scaleXYZ[1], scaleXYZ[2]);
  glTranslatef(O.x() - originXYZ[0], O.y() - originXYZ[1], O.z()
          - originXYZ[2]);

  glEnableClientState(GL_VERTEX_ARRAY);
  glEnableClientState(GL_COLOR_ARRAY);
  glEnableClientState(GL_NORMAL_ARRAY);
  glEnableClientState(GL_TEXTURE_COORD_ARRAY);

  glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbos[0]);
  glVertexPointer(3, GL_FLOAT, 0, 0);

  glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbos[1]);
  glColorPointer(4, GL_FLOAT, 0, 0);

  glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbos[2]);
  glNormalPointer(GL_FLOAT, 0, 0);

  glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbos[3]);
  glTexCoordPointer(2, GL_FLOAT, 0, 0);

  texture->bindTexture();
  glDrawArrays(GL_TRIANGLES, 0, verticesNum);

  glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0); //disabling VBO

  glDisableClientState(GL_VERTEX_ARRAY);
  glDisableClientState(GL_COLOR_ARRAY);
  glEnableClientState(GL_NORMAL_ARRAY);
  glEnableClientState(GL_TEXTURE_COORD_ARRAY);

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

EDIT: maybe it's not clear - initialization is in different function, and is only called once.

答:
Make sure your system has OpenGL acceleration enabled:

```<code>$ glxinfo | grep rendering
direct rendering: Yes
</code>```

If you get 'no', then you don't have OpenGL acceleration.

OwnerDisplayName: ajuc

ContentLicense: CC BY-SA 2.5

Body:
I have

VGA compatible controller: Intel Corporation 82G33/G31 Express Integrated Graphics Controller (rev 10) on Ubuntu 10.10 Linux.

I'm rendering statically one VBO per frame. This VBO has 30,000 triangles, with 3 lights and one texture, and I'm getting 15 FPS.

Are intel cards so bad, or am I doing sth wrong?

Drivers are standard, open source drivers from intel.

My code:

void init() {
  glGenBuffersARB(4, vbos);
  glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbos[0]);
  glBufferDataARB(GL_ARRAY_BUFFER_ARB, sizeof(GLfloat) * verticesNum * 3, vertXYZ, GL_STATIC_DRAW_ARB);
  glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbos[1]);
  glBufferDataARB(GL_ARRAY_BUFFER_ARB, sizeof(GLfloat) * verticesNum * 4, colorRGBA, GL_STATIC_DRAW_ARB);
  glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbos[2]);
  glBufferDataARB(GL_ARRAY_BUFFER_ARB, sizeof(GLfloat) * verticesNum * 3, normXYZ, GL_STATIC_DRAW_ARB);
  glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbos[3]);
  glBufferDataARB(GL_ARRAY_BUFFER_ARB, sizeof(GLfloat) * verticesNum * 2, texXY, GL_STATIC_DRAW_ARB);
}

void draw() {
  glPushMatrix();

  const Vector3f O = ps.getPosition();

  glScalef(scaleXYZ[0], scaleXYZ[1], scaleXYZ[2]);
  glTranslatef(O.x() - originXYZ[0], O.y() - originXYZ[1], O.z()
          - originXYZ[2]);

  glEnableClientState(GL_VERTEX_ARRAY);
  glEnableClientState(GL_COLOR_ARRAY);
  glEnableClientState(GL_NORMAL_ARRAY);
  glEnableClientState(GL_TEXTURE_COORD_ARRAY);

  glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbos[0]);
  glVertexPointer(3, GL_FLOAT, 0, 0);

  glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbos[1]);
  glColorPointer(4, GL_FLOAT, 0, 0);

  glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbos[2]);
  glNormalPointer(GL_FLOAT, 0, 0);

  glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbos[3]);
  glTexCoordPointer(2, GL_FLOAT, 0, 0);

  texture->bindTexture();
  glDrawArrays(GL_TRIANGLES, 0, verticesNum);

  glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0); //disabling VBO

  glDisableClientState(GL_VERTEX_ARRAY);
  glDisableClientState(GL_COLOR_ARRAY);
  glEnableClientState(GL_NORMAL_ARRAY);
  glEnableClientState(GL_TEXTURE_COORD_ARRAY);

  glPopMatrix();
}

EDIT: maybe it's not clear - initialization is in different function, and is only called once.

Body:
Make sure your system has OpenGL acceleration enabled:

$ glxinfo | grep rendering
direct rendering: Yes

If you get 'no', then you don't have OpenGL acceleration.

OwnerDisplayName: ewindisch


问:
BigQueryIO.Write in dataflow 2.X
Below code worked for Dataflow 1.9 sdk, migrating to 2.X

```<code>PCollection<TableRow> tableRow = ...

tableRow.apply(BigQueryIO.Write()
                .to(String.format("%1$s:%2$s.%3$s",projectId, bqDataSet, bqTable))
                .withSchema(schema)
                .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND));
</code>```

I get

```<code>The method apply(PTransform<? super PCollection<TableRow>,OutputT>) in the type PCollection<TableRow> is not applicable for the arguments (BigQueryIO.Write<Object>)
</code>```

Release notes are not much of a help here and documentation on 2.X is non existant redirects to beam API page.

答:
Have you tried using BigqueryIO.writeTableRows()?

Apache Beam 2.1.0 BigqueryIO documentation
https://beam.apache.org/documentation/sdks/javadoc/2.1.0/org/apache/beam/sdk/io/gcp/bigquery/BigQueryIO.html

Title: BigQueryIO.Write in dataflow 2.X

Body:
Below code worked for Dataflow 1.9 sdk, migrating to 2.X

PCollection<TableRow> tableRow = ...

tableRow.apply(BigQueryIO.Write()
                .to(String.format("%1$s:%2$s.%3$s",projectId, bqDataSet, bqTable))
                .withSchema(schema)
                .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND));

I get

The method apply(PTransform<? super PCollection<TableRow>,OutputT>) in the type PCollection<TableRow> is not applicable for the arguments (BigQueryIO.Write<Object>)

Release notes are not much of a help here and documentation on 2.X is non existant redirects to beam API page.


问:
error: Error: No resource found that matches the given name: attr 'buttonBarButtonStyle'
I write a theme in styles.xml file like below

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
 <!-- Root styles that vary by API level -->
<style name="FrameworkRoot.Theme" parent="Theme.Sherlock.Light.DarkActionBar">
    <!-- API 11+ (compatibility) -->
    <item name="buttonBarStyle">@style/Compat.ButtonBar</item>
    <item name="buttonBarButtonStyle">@style/Compat.ButtonBarButton</item>
    <item name="indeterminateProgressStyle">@style/Compat.IndeterminateProgress</item>
    <!-- API 14+ (compatibility) -->
    <item name="listPreferredItemPaddingLeft">@dimen/compat_list_preferred_item_padding_left</item>
    <item name="listPreferredItemPaddingRight">@dimen/compat_list_preferred_item_padding_right</item>
    <item name="listPreferredItemHeightSmall">@dimen/compat_list_preferred_item_height_small</item>
</style>
</code>```

but get the error: Error: No resource found that matches the given name: attr 'buttonBarStyle'.

I get the code from the google io2012. Both mine and its'  all base

```<code>    <uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="16" />
</code>```

I can compile the google io2012's source code but not mine. so strange.
is anybody know why? or have the same question?

答:
Had the same problem as yours:

my build.gradlefile:

```<code>android {
compileSdkVersion 25
buildToolsVersion "27.0.1"
defaultConfig {
    applicationId "com.whatever"
    minSdkVersion 15
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}}
</code>```

what I did in my Values folder added a attrs.XML file, with this codes in it:

```<code><declare-styleable name="ButtonBarContainerTheme">
    <attr name="metaButtonBarStyle" format="reference" />
    <attr name="metaButtonBarButtonStyle" format="reference" />
</declare-styleable>
</code>```

now I see no complains!

Body:
I write a theme in styles.xml file like below

<?xml version="1.0" encoding="utf-8"?>
<resources>

but get the error: Error: No resource found that matches the given name: attr 'buttonBarStyle'.

I get the code from the google io2012. Both mine and its'  all base

    <uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="16" />

I can compile the google io2012's source code but not mine. so strange.
is anybody know why? or have the same question?

Body:
Had the same problem as yours:

my build.gradlefile:

android {
compileSdkVersion 25
buildToolsVersion "27.0.1"
defaultConfig {
    applicationId "com.whatever"
    minSdkVersion 15
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}}

what I did in my Values folder added a attrs.XML file, with this codes in it:

<declare-styleable name="ButtonBarContainerTheme">
    <attr name="metaButtonBarStyle" format="reference" />
    <attr name="metaButtonBarButtonStyle" format="reference" />
</declare-styleable>

now I see no complains!


问:
Cronjob Not Running On Root User
I have the following cronjob set for my root user on my VPS. The command itself works if I run it as the root users just fine.

```<code>30 2 * * * service nginx stop && /opt/letsencrypt/letsencrypt-auto renew && service nginx start > /dev/null
</code>```

However it isn't working as I can see that my SSL certificate isn't renewing.

If I run cat /var/log/cron I can see the following

```<code>Nov 13 02:30:01 server CROND[2307]: (root) CMD (service nginx stop && /opt/letsencrypt/letsencrypt-auto renew && service nginx start > /dev/null)
</code>```

Which seems to indicate it ran, but clearly it hasn't done what it's supposed to.

Other cronjobs on my normal user seem to work fine, however I can't use that user for the crons as I need to temporarily stop Nginx for this cron.

Any ideas on how I can further debug this and sort it out?

* Edit: *

I tried running it to log and the following error was shown in the log /bin/sh: service: command not found

答:
The problem was that the service command was not in the crons PATH so I had to use the full path which is /sbin/service.

That meant my final cron command was

```<code>30 2 * * * (/sbin/service nginx stop && /opt/letsencrypt/letsencrypt-auto renew && /sbin/service nginx start) > /dev/null 2>&1
</code>```

Which is now working.

It looks like as a general rule, specifying the full path to any shell commands is best practice.

Title: Cronjob Not Running On Root User

Body:
I have the following cronjob set for my root user on my VPS. The command itself works if I run it as the root users just fine.

30 2 * * * service nginx stop && /opt/letsencrypt/letsencrypt-auto renew && service nginx start > /dev/null

However it isn't working as I can see that my SSL certificate isn't renewing.

If I run cat /var/log/cron I can see the following

Nov 13 02:30:01 server CROND[2307]: (root) CMD (service nginx stop && /opt/letsencrypt/letsencrypt-auto renew && service nginx start > /dev/null)

Which seems to indicate it ran, but clearly it hasn't done what it's supposed to.

Other cronjobs on my normal user seem to work fine, however I can't use that user for the crons as I need to temporarily stop Nginx for this cron.

Any ideas on how I can further debug this and sort it out?

* Edit: *

I tried running it to log and the following error was shown in the log /bin/sh: service: command not found

Body:
The problem was that the service command was not in the crons PATH so I had to use the full path which is /sbin/service.

That meant my final cron command was

30 2 * * * (/sbin/service nginx stop && /opt/letsencrypt/letsencrypt-auto renew && /sbin/service nginx start) > /dev/null 2>&1

Which is now working.

It looks like as a general rule, specifying the full path to any shell commands is best practice.


答:
The address is implementation defined. However, the variable will be created on a stack-like memory structure because of the requirement for objects to deconstruct in reverse order from their constructing.

So it is not allocating random pieces of memory from a heap (or the free store), it is likely re-using the same part of the stack memory structure each time round the loop.

If you think about it, at the beginning of each loop it creates the variable and then destroys it at the end of the loop -freeing up the memory it just occupied. It is not a surprise it then re-creates the object in the same place next time the loop starts.

Title: Why is the address of a variable defined inside a loop unchanged on each iteration?


问:
how to sum two fields
I'm trying to perform Arithmetic Operators and this is my query ,

```<code>SELECT

    GLB.BEGIN_BALANCE_DR_BEQ + GLB.BEGIN_BALANCE_CR_BEQ AS ACTIVITY,
    GLB.PERIOD_NET_DR + GLB.PERIOD_NET_CR AS BEG_BALANCE ,
    ACTIVITY + BEG_BALANCE AS END_BALANCE,
    SUM(ACTIVITY) AS TOTAL_ACT,
    SUM(BEG_BALANCE) AS TOTAL_BEG_BALANCE,
    SUM(END_BALANCE) AS TOTAL_END_BALANCE,
</code>```

But it didn't work , Can anyone guide me how can I fix it ?!

答:
You are mixing two types of operations in this query.  The first three lines are single row operations and the last three are multi row operations. As it's written you are asking for value of GLB.BEGIN_BALANCE_DR_BEQ + GLB.BEGIN_BALANCE_CR_BEQ AS ACTIVITY for each row, and the sum of ACTIVITY across all rows.

If you want the sum of each field across all rows then you have to wrap each call in the sum(...) function.  If you want a mix of single and multi row fields then you have to split them into two queries.

Title: how to sum two fields

Body:
I'm trying to perform Arithmetic Operators and this is my query ,

SELECT

    GLB.BEGIN_BALANCE_DR_BEQ + GLB.BEGIN_BALANCE_CR_BEQ AS ACTIVITY,
    GLB.PERIOD_NET_DR + GLB.PERIOD_NET_CR AS BEG_BALANCE ,
    ACTIVITY + BEG_BALANCE AS END_BALANCE,
    SUM(ACTIVITY) AS TOTAL_ACT,
    SUM(BEG_BALANCE) AS TOTAL_BEG_BALANCE,
    SUM(END_BALANCE) AS TOTAL_END_BALANCE,

But it didn't work , Can anyone guide me how can I fix it ?!


问:
WCF Server get WCF client version automatically
I was created one WCF service some months ago and now I am going to upgrade that WCF service like adding new data member and remove some data member and perform the some extra task in the upgraded service for the only new WCF client not for the old client.

How can I know that the service is called by the new WCF client or the old WCF client ?

Service

```<code>[ServiceContract]
public interface IService1
{
    void Insert(WCFClientInfo wcfClientInfo, Employee employee);
}
</code>```

Implementaion

```<code>public class Service1 : IService1
{
    public void Insert(WCFClientInfo wcfClientInfo, Employee employee)
    {
        // My Task
    }
}
</code>```

Employee

```<code>[DataContract]
public class Employee
{
    [DataMember(Order = 1)]
    public int ID { get; set; }

    [DataMember(Order = 2)]
    public string Name { get; set; }

    [DataMember(Order = 3)]
    public string MobileNo { get; set; }
}
</code>```

WCFClientInfo

```<code>[DataContract]
public class WCFClientInfo
{
    [DataMember]
    public string UserName { get; set; }

    [DataMember]
    public string Password { get; set; }
}
</code>```

Now I am adding the new field in the Employee data contract is EMail.

Employee

```<code>[DataContract]
public class Employee
{
    [DataMember(Order = 1)]
    public int ID { get; set; }

    [DataMember(Order = 2)]
    public string Name { get; set; }

    [DataMember(Order = 3)]
    public string MobileNo { get; set; }

    [DataMember(Order = 4)]
    public string EMail { get; set; }
}
</code>```

So now I want to know the WCF client user is old or new, so for that I add one more field ClientVersion in the WCFClientInfo.

WCFClientInfo

```<code>[DataContract]
public class WCFClientInfo
{
    [DataMember]
    public string UserName { get; set; }

    [DataMember]
    public string Password { get; set; }

    [DataMember]
    public string ClientVersion { get; set; }
    // It must be filled automatically by the WCF client
    // Means no need to provide by the client manually.
}
</code>```

New Implementation:

```<code>public void Insert(WCFClientInfo wcfClientInfo, Employee employee)
{
    if (string.IsNullOrWhiteSpace(wcfClientInfo.ClientVersion) ||
        wcfClientInfo.ClientVersion == "V1.0.0")
    {
        SendSMS(employee.MobileNo);
    }
    else if (wcfClientInfo.ClientVersion == "V2.0.0")
    {
        SendEMail(employee.EMail);
    }
}
</code>```

So previously there is no ClientVersion field in the WCFClientInfo class, but in the upgraded WCF Service there will ve the ClientVersion field.

So now problem is I want the WCF Client Version in the ClientVersion class automatically and there will be need to pass it manually be the client.

Can I made the changes in the WSDL file of the client like add some constant version field and that constant version field will be send automatically when client made the request to the server ?

答:
You are not controlling old clients. They already have old WSDL and will send messages without any new fields.

In general adding new fields to your contract is OK - they will just get null values when you receive the message.

However, removing fields is dangerous, because WCF infrastructure will fail to deserialize incoming messages from old clients.

Typical approach to be used when you want to change contract significantly is to introduce versioning in the endpoint URLs.

E.g. old URL might be http://yourhost.com/YourService/ and the new one will be http://yourhost.com/YourServiceV2/ where new contract can be used.

Body:
I was created one WCF service some months ago and now I am going to upgrade that WCF service like adding new data member and remove some data member and perform the some extra task in the upgraded service for the only new WCF client not for the old client.

How can I know that the service is called by the new WCF client or the old WCF client ?

Service

[ServiceContract]
public interface IService1
{
    void Insert(WCFClientInfo wcfClientInfo, Employee employee);
}

Implementaion

public class Service1 : IService1
{
    public void Insert(WCFClientInfo wcfClientInfo, Employee employee)
    {
        // My Task
    }
}

Employee

[DataContract]
public class Employee
{
    [DataMember(Order = 1)]
    public int ID { get; set; }

    [DataMember(Order = 2)]
    public string Name { get; set; }

    [DataMember(Order = 3)]
    public string MobileNo { get; set; }
}

WCFClientInfo

[DataContract]
public class WCFClientInfo
{
    [DataMember]
    public string UserName { get; set; }

    [DataMember]
    public string Password { get; set; }
}

Now I am adding the new field in the Employee data contract is EMail.

Employee

[DataContract]
public class Employee
{
    [DataMember(Order = 1)]
    public int ID { get; set; }

    [DataMember(Order = 2)]
    public string Name { get; set; }

    [DataMember(Order = 3)]
    public string MobileNo { get; set; }

    [DataMember(Order = 4)]
    public string EMail { get; set; }
}

So now I want to know the WCF client user is old or new, so for that I add one more field ClientVersion in the WCFClientInfo.

WCFClientInfo

[DataContract]
public class WCFClientInfo
{
    [DataMember]
    public string UserName { get; set; }

    [DataMember]
    public string Password { get; set; }

    [DataMember]
    public string ClientVersion { get; set; }
    // It must be filled automatically by the WCF client
    // Means no need to provide by the client manually.
}

New Implementation:

public void Insert(WCFClientInfo wcfClientInfo, Employee employee)
{
    if (string.IsNullOrWhiteSpace(wcfClientInfo.ClientVersion) ||
        wcfClientInfo.ClientVersion == "V1.0.0")
    {
        SendSMS(employee.MobileNo);
    }
    else if (wcfClientInfo.ClientVersion == "V2.0.0")
    {
        SendEMail(employee.EMail);
    }
}

So previously there is no ClientVersion field in the WCFClientInfo class, but in the upgraded WCF Service there will ve the ClientVersion field.

So now problem is I want the WCF Client Version in the ClientVersion class automatically and there will be need to pass it manually be the client.

Can I made the changes in the WSDL file of the client like add some constant version field and that constant version field will be send automatically when client made the request to the server ?


答:
Thanks fo answers.

Yeah, I have direct rendering on, according to glxinfo. In glxgears I get sth like 150 FPS, and games like Warzone or glest works fast enough. So probably problem is in my code.

I'll buy some real graphic card eventually anyway, but I wanted my game to work on integrated graphic cards too, that's why I posted this question.

Title: Am I doing something wrong, or do Intel graphic cards suck so bad?


问:
How Does C# Handle Locking On A Dictionary Item?
I was working on some pathfinding code for a game in C# (.NET 3.5) and I added parallelism of the pathfinding to the game to make it faster. The AI agents must "register" with the pathfinding system and are provided a id in return. A dictionary agentMap stores information for a AI agent to do with it's pathfinding calls (the last start point, end point and path calculated for the last pathfinding call).

When I start a parallel pathfinding search the first thing the thread does is call lock(agentMap[id]). The thing is that the game loop also accesses agentMap[id] when updating where the agent wants to go. Somehow, the game hasn't frozen up (as far as I can tell).

As I understand it, agentMap[id] locks on the item referred to by the key id so when the game loop tries to access that item the game loop should be blocked. Is there some special behaviour of locking on a dictionary item (or am I just lucky not to have problems)?

Code for parallel pathfinding thread:

```<code>/*
    C# will nicely this function in a parallel thread for me
*/
void getBasicPathParallelized (object id)
{
    lock (agentMap [id]) {
        try {
            /* get path */
        } catch (Exception e) {
            /* error handling */
        }
    }
}
</code>```

Starting the pathfinding thread:

```<code>agentMap [caller].pathfindingThread = new Thread (this.getBasicPathParallelized);
agentMap [caller].pathfindingThread.Start (caller);
</code>```

The game loop code that manipulates the agentMap [id] items is too long to share in full but here is a section to show how the game loop uses the items of the dictionary:

```<code>agentMap [id].openList = new NodeList<PathNode> ();
agentMap [id].destination = destination;
agentMap [id].start = start;
agentMap [id].flags = flags;
++agentMap [id].pathSearchID;
agentMap [id].startTriangle = startTriangle;
agentMap [id].destinationTriangle = destinationTriangle;
</code>```

答:
so when the game loop tries to access that item the game loop should be blocked

No.  If the game loop tries to lock on the item, it'll be blocked.  If it tries to access the item then it will just access the item.  If you want it to block, it needs to lock around access to it.  Because you're accessing a shared object without proper synchronization, all sorts of bad things can happen.

Note that mutating an object from multiple places like this, and having a widely accessible object being synchronized on, are both bad ideas.  This object should almost certainly be immutable, and changes to the dictionary holding it should be properly synchronized through a single type responsible for ensuring properly synchronized access, possibly by using a ConcurrentDictionary instead of a Dictionary.

Body:
I was working on some pathfinding code for a game in C# (.NET 3.5) and I added parallelism of the pathfinding to the game to make it faster. The AI agents must "register" with the pathfinding system and are provided a id in return. A dictionary agentMap stores information for a AI agent to do with it's pathfinding calls (the last start point, end point and path calculated for the last pathfinding call).

When I start a parallel pathfinding search the first thing the thread does is call lock(agentMap[id]). The thing is that the game loop also accesses agentMap[id] when updating where the agent wants to go. Somehow, the game hasn't frozen up (as far as I can tell).

As I understand it, agentMap[id] locks on the item referred to by the key id so when the game loop tries to access that item the game loop should be blocked. Is there some special behaviour of locking on a dictionary item (or am I just lucky not to have problems)?

Code for parallel pathfinding thread:

/*
    C# will nicely this function in a parallel thread for me
*/
void getBasicPathParallelized (object id)
{
    lock (agentMap [id]) {
        try {
            /* get path */
        } catch (Exception e) {
            /* error handling */
        }
    }
}

Starting the pathfinding thread:

agentMap [caller].pathfindingThread = new Thread (this.getBasicPathParallelized);
agentMap [caller].pathfindingThread.Start (caller);

The game loop code that manipulates the agentMap [id] items is too long to share in full but here is a section to show how the game loop uses the items of the dictionary:

agentMap [id].openList = new NodeList<PathNode> ();
agentMap [id].destination = destination;
agentMap [id].start = start;
agentMap [id].flags = flags;
++agentMap [id].pathSearchID;
agentMap [id].startTriangle = startTriangle;
agentMap [id].destinationTriangle = destinationTriangle;


问:
iPhone X - Face ID - Unwanted "Enter your Password" text
Since I got my iPhone X, I've been updating my app to work with Face ID. When Face ID fails too many times I get the text "Face Not Recognized" "Enter your Password". The problem I have is that for this prompt I don't want a fallback action so asking to enter a password doesn't make sense. Any help would be appreciated.

This is the code I'm using:

```<code>let context = LAContext()
context.localizedFallbackTitle = ""
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics,
                       localizedReason: "Reason for bio auth",
                       reply: { (isSuccess, error) in

})
</code>```

This is the result:

答: This appears to be fixed in the upcoming iOS 11.2 release. </p>

Body:
Since I got my iPhone X, I've been updating my app to work with Face ID. When Face ID fails too many times I get the text "Face Not Recognized" "Enter your Password". The problem I have is that for this prompt I don't want a fallback action so asking to enter a password doesn't make sense. Any help would be appreciated.

This is the code I'm using:

let context = LAContext()
context.localizedFallbackTitle = ""
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics,
                       localizedReason: "Reason for bio auth",
                       reply: { (isSuccess, error) in

})

This is the result:


问:
Replacing values of a diagonal matrix with specific values in R
I'm new to programming and coding as a whole and am currently learning R here at school as part of my statistics certification.

We have been asked to create a 10 x 10 matrix called ‘mat’ that contains the numbers 1 on the diagonal and 0 on the off-diagonal.

I have done this using the following:

```<code>mat<-diag(10)
mat
   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
   [1,]    1    0    0    0    0    0    0    0    0     0
   [2,]    0    1    0    0    0    0    0    0    0     0
   [3,]    0    0    1    0    0    0    0    0    0     0
   [4,]    0    0    0    1    0    0    0    0    0     0
   [5,]    0    0    0    0    1    0    0    0    0     0
   [6,]    0    0    0    0    0    1    0    0    0     0
   [7,]    0    0    0    0    0    0    1    0    0     0
   [8,]    0    0    0    0    0    0    0    1    0     0
   [9,]    0    0    0    0    0    0    0    0    1     0
  [10,]    0    0    0    0    0    0    0    0    0     1
</code>```

then I am asked to partition off a k x k block of the matrix where k=3 and also has this identity structure and describe how many ways are there to do this.

I only figured out how to do this doing the following:

```<code> mat2<-mat[c(1,2,3),c(1,2,3)]
 mat2
          [,1] [,2] [,3]
    [1,]    1    0    0
    [2,]    0    1    0
    [3,]    0    0    1
</code>```

So far so good I guess? However, now I'm really stuck, I have no idea how to go about the following, with mat2 I am now asked to replace the block diagonal portion of mat (mat2) with a matrix like this:

```<code>          [,1] [,2] [,3]
    [1,]    1   .5   .25
    [2,]   .5    1    .5
    [3,]  .25   .5     1
</code>```

My professor has also hinted, that using the outer function will make this easier, I really have no idea how I can do this, I tried using upper.tri and lower.tri functions, but I wasn't too successful with that either.

I would greatly appreciate any help. Thank you in advance!

Body:
I'm new to programming and coding as a whole and am currently learning R here at school as part of my statistics certification.

We have been asked to create a 10 x 10 matrix called ‘mat’ that contains the numbers 1 on the diagonal and 0 on the off-diagonal.

I have done this using the following:

mat<-diag(10)
mat
   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
   [1,]    1    0    0    0    0    0    0    0    0     0
   [2,]    0    1    0    0    0    0    0    0    0     0
   [3,]    0    0    1    0    0    0    0    0    0     0
   [4,]    0    0    0    1    0    0    0    0    0     0
   [5,]    0    0    0    0    1    0    0    0    0     0
   [6,]    0    0    0    0    0    1    0    0    0     0
   [7,]    0    0    0    0    0    0    1    0    0     0
   [8,]    0    0    0    0    0    0    0    1    0     0
   [9,]    0    0    0    0    0    0    0    0    1     0
  [10,]    0    0    0    0    0    0    0    0    0     1

then I am asked to partition off a k x k block of the matrix where k=3 and also has this identity structure and describe how many ways are there to do this.

I only figured out how to do this doing the following:

 mat2<-mat[c(1,2,3),c(1,2,3)]
 mat2
          [,1] [,2] [,3]
    [1,]    1    0    0
    [2,]    0    1    0
    [3,]    0    0    1

So far so good I guess? However, now I'm really stuck, I have no idea how to go about the following, with mat2 I am now asked to replace the block diagonal portion of mat (mat2) with a matrix like this:

          [,1] [,2] [,3]
    [1,]    1   .5   .25
    [2,]   .5    1    .5
    [3,]  .25   .5     1

My professor has also hinted, that using the outer function will make this easier, I really have no idea how I can do this, I tried using upper.tri and lower.tri functions, but I wasn't too successful with that either.

I would greatly appreciate any help. Thank you in advance!

Body:
If you have the replacement matrix ready:

mat<-diag(10)
replacement <- matrix(c(1,.5,.25,.5,1,.5,.25,.5,1), nrow=3, byrow=T)
mat[c(1,2,3),c(1,2,3)] <- replacement

the put it in for loop to make across the whole diagonal

for(idx in 1:8){
    mat[c(idx,idx+1,idx+2),c(idx,idx+1,idx+2)] <- replacement
}
mat
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,] 1.00 0.50 0.25 0.00 0.00 0.00 0.00 0.00 0.00  0.00
 [2,] 0.50 1.00 0.50 0.25 0.00 0.00 0.00 0.00 0.00  0.00
 [3,] 0.25 0.50 1.00 0.50 0.25 0.00 0.00 0.00 0.00  0.00
 [4,] 0.00 0.25 0.50 1.00 0.50 0.25 0.00 0.00 0.00  0.00
 [5,] 0.00 0.00 0.25 0.50 1.00 0.50 0.25 0.00 0.00  0.00
 [6,] 0.00 0.00 0.00 0.25 0.50 1.00 0.50 0.25 0.00  0.00
 [7,] 0.00 0.00 0.00 0.00 0.25 0.50 1.00 0.50 0.25  0.00
 [8,] 0.00 0.00 0.00 0.00 0.00 0.25 0.50 1.00 0.50  0.25
 [9,] 0.00 0.00 0.00 0.00 0.00 0.00 0.25 0.50 1.00  0.50
[10,] 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.25 0.50  1.00


问:
Bootstrap 4 makes outline not work
How does Bootstrap disable the HTML outline property?
When I add the form control class to my input, "outline: none;" no longer works.

```<code><input class="form-control" style="outline:none;">
</code>```

codepen: https://codepen.io/Eli92/pen/WXXbRa

I can just use my own css class for this input, but I want to know what's happening here, and I'm too much of a beginner to submit a bug report.

The reason I want to remove the outline is to add my own to an outer element, like Youtube and most popular sites do for their search bar.

答:
You issue is that bootstrap defines .form-control, and that some extra attributes are assigned by this class to bootstrap inputs.

```<code>.form-control {
    display: block;
    width: 100%;
    padding: .375rem .75rem;
    font-size: 1rem;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-image: none;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
}
</code>```

What you'd want to add to your class to change the border is an override so that there is something else that replaces the default. If you truly want no border on an element, then you'd want to set the border to 0px thick

```<code>border: 0px;
</code>```

codepen: https://codepen.io/anon/pen/eeeNZB

Title: Bootstrap 4 makes outline not work

Body:
How does Bootstrap disable the HTML outline property?
When I add the form control class to my input, "outline: none;" no longer works.

<input class="form-control" style="outline:none;">

codepen: https://codepen.io/Eli92/pen/WXXbRa

I can just use my own css class for this input, but I want to know what's happening here, and I'm too much of a beginner to submit a bug report.

The reason I want to remove the outline is to add my own to an outer element, like Youtube and most popular sites do for their search bar.

Body:
You issue is that bootstrap defines .form-control, and that some extra attributes are assigned by this class to bootstrap inputs.

.form-control {
    display: block;
    width: 100%;
    padding: .375rem .75rem;
    font-size: 1rem;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-image: none;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
}

What you'd want to add to your class to change the border is an override so that there is something else that replaces the default. If you truly want no border on an element, then you'd want to set the border to 0px thick

border: 0px;

codepen: https://codepen.io/anon/pen/eeeNZB


问:
How to use Grails Spring Security Plugin to require logging in before access an action?
I know that I can use annotation or Request mapping to restrict access to an ACTION by some specific ROLES. But now I have a different circumstance.

My scenario is: every user of my site can create posts, and they can make their own post public, private, or only share to some other users. I implement sharing post by a database table PERMISSION, which specify if a user have the right to view a post or not.

The problem arises here is that when a customer access a post through a direct link, how can I determine he/she have the privilege to view it? There's 3 circumstances:

The post is public, so it can be viewed by anyone (include not-login
  user)

The post is private, so only the login-owner can view it

The post is sharing, it means only the login-user that is shared and the
  owner can view it.

I want to process like this:

If the requested post is public: ok.

If the requested post is private/sharing: I want to redirect
  the customer to the login page; after
  logging in, the user will be re-direct
  to the page he wants to see.

The problem here is that I can redirect the user to login controller/ auth action, but after that I don't know how to redirect it back. The link to every post is different by post_id, so I can't use SpringSecurityUtils.securityConfig.successHandler.defaultTargetUrl

Could anyone know a way to do this?

答:
I have found a quick workaround for this problem:

If the user is logged in: check the user's privilege, and return the appropriate result.

If the user is not logged in: At view action, set the post_id by:

session.post_id = 8

Redirect the user to the Login Controller/ Auth action.

At checkrole action(which is my grails.plugins.springsecurity.successHandler.defaultTargetUrl in Config.groovy), if session.post_id exists, use it to build the link for re-directing to the view action. Before redirecting, clear the session.post_id.


问:
USQL Activity in ADF V2 - 2705 User is not able to access to datalake store
I'm facing an issue when running a U-SQL Script with Azure Data Factory V2.

This U-SQL Script work fine in the portal or vs :

```<code> @a  =
  SELECT * FROM
    (VALUES
       ("Contoso",   1500.0, "2017-03-39"),
       ("Woodgrove", 2700.0, "2017-04-10")
    ) AS D( customer, amount );

@results =
  SELECT
    customer,
    amount
  FROM @a;

OUTPUT @results
  TO "test"
  USING Outputters.Text();
</code>```

But don't work when started in Azure Data Factory V2 Activity, bellow my ADF scripts.

```<code>Creating or updating linked service ADLA [adla] ...
{
  "properties": {
    "type": "AzureDataLakeAnalytics",
    "typeProperties": {
      "accountName": "adla",
      "servicePrincipalId": "ea4823f2-3b7a-4c-78d29cffa68b",
      "servicePrincipalKey": {
        "type": "SecureString",
        "value": "jKhyspEwMScDAGU0MO39FcAP9qQ="
      },
      "tenant": "41f06-8ca09e840041",
      "subscriptionId": "9cf053128b749",
      "resourceGroupName": "test"
    }
  }
}

Creating or updating linked service BLOB [BLOB] ...
{
  "properties": {
    "type": "AzureStorage",
    "typeProperties": {
      "connectionString": {
        "type": "SecureString",
        "value": "DefaultEndpointsProtocol=https;AccountName=totoblob;AccountKey=qZqpKyGtWMRXZO2CNLa0qTyvLTMko4lzfgsg07pjloIPGZtJel4qvRBkoVOA==;EndpointSuffix=core.windows.net"
      }
    }
  }
}

Creating or updating pipeline ADLAPipeline...
{
  "properties": {
    "activities": [
      {
        "type": "DataLakeAnalyticsU-SQL",
        "typeProperties": {
          "scriptPath": "src/test.usql",
          "scriptLinkedService": {
            "referenceName": "blob",
            "type": "LinkedServiceReference"
          },
          "degreeOfParallelism": 1
        },
        "linkedServiceName": {
          "referenceName": "adla",
          "type": "LinkedServiceReference"
        },
        "name": "Usql-toto"
      }
    ]
  }
}
</code>```

1 - I checked the connection to the blob storage, the u-sql script is successfully found (if i rename it, it throw a not found error)

2 - I checked the connection to azure data lake analytics, it seems to connect, if i set a wrong credential it throw an other error

3 - When running the pipeline I Have the following error : "Activity Usql-toto failed: User is not able to access to datalake store" and actually I don't provide Data Lake Store Credential but there is a default datalake store account attached ADLAnalytics.

Any hint?

答:
Finally found help in this post: U-SQL Job Failing in Data Factory

Folders system and catalog doesn't inherit from parent permissions ... So I had to reassign permission on this two folders.

Body:
I'm facing an issue when running a U-SQL Script with Azure Data Factory V2.

This U-SQL Script work fine in the portal or vs :

 @a  =
  SELECT * FROM
    (VALUES
       ("Contoso",   1500.0, "2017-03-39"),
       ("Woodgrove", 2700.0, "2017-04-10")
    ) AS D( customer, amount );

@results =
  SELECT
    customer,
    amount
  FROM @a;

OUTPUT @results
  TO "test"
  USING Outputters.Text();

But don't work when started in Azure Data Factory V2 Activity, bellow my ADF scripts.

Creating or updating linked service ADLA [adla] ...
{
  "properties": {
    "type": "AzureDataLakeAnalytics",
    "typeProperties": {
      "accountName": "adla",
      "servicePrincipalId": "ea4823f2-3b7a-4c-78d29cffa68b",
      "servicePrincipalKey": {
        "type": "SecureString",
        "value": "jKhyspEwMScDAGU0MO39FcAP9qQ="
      },
      "tenant": "41f06-8ca09e840041",
      "subscriptionId": "9cf053128b749",
      "resourceGroupName": "test"
    }
  }
}

Creating or updating linked service BLOB [BLOB] ...
{
  "properties": {
    "type": "AzureStorage",
    "typeProperties": {
      "connectionString": {
        "type": "SecureString",
        "value": "DefaultEndpointsProtocol=https;AccountName=totoblob;AccountKey=qZqpKyGtWMRXZO2CNLa0qTyvLTMko4lzfgsg07pjloIPGZtJel4qvRBkoVOA==;EndpointSuffix=core.windows.net"
      }
    }
  }
}

Creating or updating pipeline ADLAPipeline...
{
  "properties": {
    "activities": [
      {
        "type": "DataLakeAnalyticsU-SQL",
        "typeProperties": {
          "scriptPath": "src/test.usql",
          "scriptLinkedService": {
            "referenceName": "blob",
            "type": "LinkedServiceReference"
          },
          "degreeOfParallelism": 1
        },
        "linkedServiceName": {
          "referenceName": "adla",
          "type": "LinkedServiceReference"
        },
        "name": "Usql-toto"
      }
    ]
  }
}

1 - I checked the connection to the blob storage, the u-sql script is successfully found (if i rename it, it throw a not found error)

2 - I checked the connection to azure data lake analytics, it seems to connect, if i set a wrong credential it throw an other error

3 - When running the pipeline I Have the following error : "Activity Usql-toto failed: User is not able to access to datalake store" and actually I don't provide Data Lake Store Credential but there is a default datalake store account attached ADLAnalytics.

Any hint?


问:
Provision certficate to LAMP EC2, which are autoscaled on AWS
I need to design a solution, where the AWS EC2 has LAMP installed . The EC2s are autoscalled . The EC2 should have HTTPS for LAMP . The certificate can be self signed , but the private key should be protected. That is the private key should not be hardcoded on EC2 instance ( which is not best practice) . Also the HTTPS  should originate from EC2 and not from ELB,CloudFront,ACM etc. </p>

<p>Can someone help me in suggesting best practices ? </p>

答:
I would question why you feel you need to terminate SSL on your EC2 instances rather than on the load balancer.

If you require end-to-end encryption of data in flight, you can communicate between ELB and EC2 by using self-signed certs on EC2.

This means you don't have to deploy your private keys to EC2.

Body:
I need to design a solution, where the AWS EC2 has LAMP installed . The EC2s are autoscalled . The EC2 should have HTTPS for LAMP . The certificate can be self signed , but the private key should be protected. That is the private key should not be hardcoded on EC2 instance ( which is not best practice) . Also the HTTPS  should originate from EC2 and not from ELB,CloudFront,ACM etc.

Can someone help me in suggesting best practices ?


问:
Openstack release name
I am not able to determine the Openstack release running on my machine. I tried to match the output of nova package version with release naming site. But my nova version does not have a match.

```<code>stack@Selm:~$  nova-manage  --version

12.0.0
</code>```

This package is not listed on following release site:
https://wiki.openstack.org/wiki/Releases

Could someone please tell me how can I determine the release name running on my machine?

Thanks,
Manish

答: The resource provided in the previous responses is not updated. OpenStack releases are now available at https://releases.openstack.org/</p>

Title: Openstack release name

Body:
I am not able to determine the Openstack release running on my machine. I tried to match the output of nova package version with release naming site. But my nova version does not have a match.

stack@Selm:~$  nova-manage  --version

12.0.0

This package is not listed on following release site:
https://wiki.openstack.org/wiki/Releases

Could someone please tell me how can I determine the release name running on my machine?

Thanks,
Manish


问:
Chisel -- clock gating
Clock gating is important for power reduction.  How do we specify clock gating in Chisel?

Clock gating is where a logic signal determines whether or not the clock to a particular register is toggled.  When the logic signal is inactive, then the clock remains steady, unchanging.  Only when the enable is active does the clock signal toggle, which in turn latches inputs into the flip flop.

The backend tools handle inserting the implementation of this, but they need the RTL to indicate the enable signal.

答:
Using Chisel3 MultiClock test as an example.  I think this is pretty close to what you are looking for.

```<code>import chisel3._
import chisel3.experimental.withClock

class GatedCounter extends Module {
  val io = IO(new Bundle {
    val count = Output(UInt(32.W))
  })

  val counter = RegInit(0.U(32.W))

  counter := counter + 1.U

  io.count := counter
}

class HasGatedCounter extends Module {
  val io = IO(new Bundle {
    val enable = Input(Bool())
    val count  = Output(UInt(32.W))
  })

  val clock2 = (clock.asUInt()(0) & io.enable).asClock()

  withClock(clock2) {
    val counterModule = Module(new GatedCounter)

    io.count := counterModule.io.count
  }
}
</code>```

Note: This does not seem to work with the firrtl-interpreter backend, so you must use the verilator backend or something else to test it properly.

Title: Chisel -- clock gating

Body:
Using Chisel3 MultiClock test as an example.  I think this is pretty close to what you are looking for.

import chisel3._
import chisel3.experimental.withClock

class GatedCounter extends Module {
  val io = IO(new Bundle {
    val count = Output(UInt(32.W))
  })

  val counter = RegInit(0.U(32.W))

  counter := counter + 1.U

  io.count := counter
}

class HasGatedCounter extends Module {
  val io = IO(new Bundle {
    val enable = Input(Bool())
    val count  = Output(UInt(32.W))
  })

  val clock2 = (clock.asUInt()(0) & io.enable).asClock()

  withClock(clock2) {
    val counterModule = Module(new GatedCounter)

    io.count := counterModule.io.count
  }
}

Note: This does not seem to work with the firrtl-interpreter backend, so you must use the verilator backend or something else to test it properly.


问:
Incorporating 7z in macrodef in ANT
I have been using a macro definition to copy a set of files to different locations and FTP servers. But copying seems quite slow so I want to compress the bundle using 7z and copy all into FTP as one single file. Can it be done using 7z? My amcrodef is below which works:</p>

```<code><macrodef name="copyimages">
  <attribute name="todir"/>
  <sequential>
    <copy todir="@{todir}" overwrite="true" failonerror="false">
      <fileset dir="${build.output.dir}">
                  <include name="logs/*${build.id}*armv5*scan2.html"/>
                  <include name="logs/*${build.id}*main.ant.log"/>
        <include name="logs/*${build.id}*bom.xml"/>
        <include name="logs/compile/*${build.id}*.*"/>
        <include name="logs/cone/*${build.id}*.*"/>
        <include name="logs/post/*${build.id}*.*"/>
        <include name="logs/roms/*${build.id}*.*"/>
        <include name="**/*${build.id}_codescanner/**"/>
      </fileset>
    </copy>
  </sequential>
</macrodef>

<copyimages todir="${publish.ssdoci.dir}/${env.version}.${build.number}"/>
</code>```

答:
If you are not particular about 7z, then you can use the Zip Task.

You could try something like this instead of <copy></copy...

```<code><zip destfile ="@{destfile}">
  <fileset dir="${build.output.dir}">
    <include name="logs/*${build.id}*armv5*scan2.html"/>
    <include name="logs/*${build.id}*main.ant.log"/>
    <include name="logs/*${build.id}*bom.xml"/>
    <include name="logs/compile/*${build.id}*.*"/>
    <include name="logs/cone/*${build.id}*.*"/>
    <include name="logs/post/*${build.id}*.*"/>
    <include name="logs/roms/*${build.id}*.*"/>
    <include name="**/*${build.id}_codescanner/**"/>
  </fileset>
</zip>

<copyimages destfile="${publish.ssdoci.file}-${env.version}.${build.number}"/>
</code>```

Title: Incorporating 7z in macrodef in ANT

Body:
I have been using a macro definition to copy a set of files to different locations and FTP servers. But copying seems quite slow so I want to compress the bundle using 7z and copy all into FTP as one single file. Can it be done using 7z? My amcrodef is below which works:

<macrodef name="copyimages">
  <attribute name="todir"/>
  <sequential>
    <copy todir="@{todir}" overwrite="true" failonerror="false">
      <fileset dir="${build.output.dir}">
                  <include name="logs/*${build.id}*armv5*scan2.html"/>
                  <include name="logs/*${build.id}*main.ant.log"/>
        <include name="logs/*${build.id}*bom.xml"/>
        <include name="logs/compile/*${build.id}*.*"/>
        <include name="logs/cone/*${build.id}*.*"/>
        <include name="logs/post/*${build.id}*.*"/>
        <include name="logs/roms/*${build.id}*.*"/>
        <include name="**/*${build.id}_codescanner/**"/>
      </fileset>
    </copy>
  </sequential>
</macrodef>

<copyimages todir="${publish.ssdoci.dir}/${env.version}.${build.number}"/>

Body:
If you are not particular about 7z, then you can use the Zip Task.

You could try something like this instead of <copy></copy...

<zip destfile ="@{destfile}">
  <fileset dir="${build.output.dir}">
    <include name="logs/*${build.id}*armv5*scan2.html"/>
    <include name="logs/*${build.id}*main.ant.log"/>
    <include name="logs/*${build.id}*bom.xml"/>
    <include name="logs/compile/*${build.id}*.*"/>
    <include name="logs/cone/*${build.id}*.*"/>
    <include name="logs/post/*${build.id}*.*"/>
    <include name="logs/roms/*${build.id}*.*"/>
    <include name="**/*${build.id}_codescanner/**"/>
  </fileset>
</zip>

<copyimages destfile="${publish.ssdoci.file}-${env.version}.${build.number}"/>


问:
How do I loop through or enumerate a JavaScript object?
I have a JavaScript object like the following:

```<code>var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};
</code>```

How do I loop through all of p's elements (p1, p2, p3...) and get their keys and values?

答:
The Object.keys() method returns an array of a given object's own enumerable properties. Read more about it here

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

Object.keys(p).map((key)=> console.log(key + "->" + p[key]))```

OwnerDisplayName: Tanmoy Rajguru

ContentLicense: CC BY-SA 4.0

Body:
I have a JavaScript object like the following:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

How do I loop through all of p's elements (p1, p2, p3...) and get their keys and values?


答:
.form-control applies a box-shadow (not an outline) on :focus.  Removing it is as simple as overriding the .form-control:focus declaration in Bootstrap:

```<code>.form-control:focus {
    box-shadow: none;
}
</code>```

Title: Bootstrap 4 makes outline not work

Body:
.form-control applies a box-shadow (not an outline) on :focus.  Removing it is as simple as overriding the .form-control:focus declaration in Bootstrap:

.form-control:focus {
    box-shadow: none;
}


问:
MongoDB - $gt date returns day and month correctly but shows previous years
I save date in the database 09/29/2017 format using

```<code>import DatePicker from "react-datepicker";
</code>```

The issue is that when I run

```<code>return Appointments.find({date: { $gt : todayDate }});
</code>```

where todayDate is 09/29/2017 it returns days and months correctly but includes previous years, so the result of above may be: 09/30/2017, 10/01/2017, 09/30/2016

How can I fix the year issue? Changing everything to save in the format like this 2017-09-29T20:17:05.856Z is not a preferable solution for me because I'll need to make lots of changes.

答: Switched to 2017-09-30 format and it started working correctly.</p>

Body:
I save date in the database 09/29/2017 format using

import DatePicker from "react-datepicker";

The issue is that when I run

return Appointments.find({date: { $gt : todayDate }});

where todayDate is 09/29/2017 it returns days and months correctly but includes previous years, so the result of above may be: 09/30/2017, 10/01/2017, 09/30/2016

How can I fix the year issue? Changing everything to save in the format like this 2017-09-29T20:17:05.856Z is not a preferable solution for me because I'll need to make lots of changes.