问:
How can I sum strings in one column into one row in Microsoft SQL? Group by does not work since it is MSSQL
for example we have table with three columns

```<code>Column A |  Column B | Column C
-------------------------------
P1       |    10     |    A
P1       |    20     |    B
P1       |    30     |    C
P2       |    30     |    D
P2       |    40     |    E
</code>```

How do I have to write SELECT query in Microsoft SQL to have this kind of result

```<code>Column A |     Column B      |   Column C
------------------------------------------
P1       |    10, 20, 30     |    A, B, C
P2       |    30, 40         |    D, E
</code>```

答:
If you are running SQL Server 2017, T-SQL enhancements introduced to SQL developers include the STRING_AGG string concatenation function

You can simply use following SELECT statement for aggregating string values from different rows into a single column value

```<code>select
    ColumnA,
    string_agg(ColumnB,',') ColumnB,
    string_agg(ColumnC,',') ColumnC
from TestTable1
group by ColumnA
</code>```

Body:
for example we have table with three columns

Column A |  Column B | Column C
-------------------------------
P1       |    10     |    A
P1       |    20     |    B
P1       |    30     |    C
P2       |    30     |    D
P2       |    40     |    E

How do I have to write SELECT query in Microsoft SQL to have this kind of result

Column A |     Column B      |   Column C
------------------------------------------
P1       |    10, 20, 30     |    A, B, C
P2       |    30, 40         |    D, E

Body:
If you are running SQL Server 2017, T-SQL enhancements introduced to SQL developers include the STRING_AGG string concatenation function

You can simply use following SELECT statement for aggregating string values from different rows into a single column value

select
    ColumnA,
    string_agg(ColumnB,',') ColumnB,
    string_agg(ColumnC,',') ColumnC
from TestTable1
group by ColumnA


来源: stackexchange

问:
ngram text to be as separate column in R

I got list of several text got from ngram, and want to add to original datatable as columns.

```<code>> prep_test
                                                                                prep_test
 1:                      Women Athletic,Athletic Apparel,Apparel Pants,Pants Tights,Tights Leggings
 2:                                                                       Beauty Makeup,Makeup Face
 3:                                                                       Beauty Makeup,Makeup Face
 4:     Electronics Cell,Cell Phones,Phones Accessories,Accessories Cases,Cases Covers,Covers Skins
 5:                                                                         Women Shoes,Shoes Boots
 6:                                                   Men Men,Men s,s Accessories,Accessories Belts
 7: Electronics Cell,Cell Phones,Phones Accessories,Accessories Cell,Cell Phones,Phones Smartphones
 8:                                                           Women Tops,Tops Blouses,Blouses Other
 9:                      Women Athletic,Athletic Apparel,Apparel Pants,Pants Tights,Tights Leggings
10:                                                Home Home,Home DÃ,DÃ cor,cor Home,Home Fragrance

str(prep_test)
Classes ‘data.table’ and 'data.frame':  10 obs. of  1 variable:
 $ prep_test:List of 10
  ..$ : chr  "Women Athletic" "Athletic Apparel" "Apparel Pants" "Pants Tights" ...
  ..$ : chr  "Beauty Makeup" "Makeup Face"
  ..$ : chr  "Beauty Makeup" "Makeup Face"
  ..$ : chr  "Electronics Cell" "Cell Phones" "Phones Accessories" "Accessories Cases" ...
  ..$ : chr  "Women Shoes" "Shoes Boots"
  ..$ : chr  "Men Men" "Men s" "s Accessories" "Accessories Belts"
  ..$ : chr  "Electronics Cell" "Cell Phones" "Phones Accessories" "Accessories Cell" ...
  ..$ : chr  "Women Tops" "Tops Blouses" "Blouses Other"
  ..$ : chr  "Women Athletic" "Athletic Apparel" "Apparel Pants" "Pants Tights" ...
  ..$ : chr  "Home Home" "Home DÃ" "DÃ cor" "cor Home" ...
 - attr(*, ".internal.selfref")=<externalptr>
</code>```

current code to generate n-gram for a column

```<code>bigram_fun <- function(y){
  y <- gsub("[[:punct:][:blank:]]+", " ", y)
  y <- ngram_asweka(y, min=2, max=2)
  #y <- str_split_fixed(y, ",", n=Inf)
  #y <- unlist(y)
  return(y)
}

prep_test <- all[1:10, 9]
prep_test <- apply(prep_test, 1, bigram_fun)
prep_test <- data.table(prep_test)
prep_test
</code>```

dput here

```<code>> dput(prep_test)
list(c("Women Athletic", "Athletic Apparel", "Apparel Pants",
"Pants Tights", "Tights Leggings"), c("Beauty Makeup", "Makeup Face"
), c("Beauty Makeup", "Makeup Face"), c("Electronics Cell", "Cell Phones",
"Phones Accessories", "Accessories Cases", "Cases Covers", "Covers Skins"
), c("Women Shoes", "Shoes Boots"), c("Men Men", "Men s", "s Accessories",
"Accessories Belts"), c("Electronics Cell", "Cell Phones", "Phones Accessories",
"Accessories Cell", "Cell Phones", "Phones Smartphones"), c("Women Tops",
"Tops Blouses", "Blouses Other"), c("Women Athletic", "Athletic Apparel",
"Apparel Pants", "Pants Tights", "Tights Leggings"), c("Home Home",
"Home DÃ", "DÃ cor", "cor Home", "Home Fragrance"))
</code>```

desired outcome

```<code>Bigram 1           Bigram 2           Bigram 3              Bigram 4     ...
"Women Athletic"   "Athletic Apparel" "Apparel Pants"      "Pants Tights"...
"Beauty Makeup"    "Makeup Face"      NA                    NA           ...
"Beauty Makeup"    "Makeup Face"      NA                    NA           ...
"Electronics Cell" "Cell Phones"      "Phones Accessories" "Accessories Cases"
"Women Shoes"      "Shoes Boots"      NA                    NA
</code>```

Appreciate any answers, and sorry for poor questions here as a newbie here

答:
We can convert the bigrams to data frames, bind into a molten data frame, then cast to a wide format tidy data file as follows.

```<code>theBigrams <- list(c("Women Athletic", "Athletic Apparel", "Apparel Pants",
"Pants Tights", "Tights Leggings"), c("Beauty Makeup", "Makeup Face"),
 c("Beauty Makeup", "Makeup Face"), c("Electronics Cell", "Cell Phones",
"Phones Accessories", "Accessories Cases", "Cases Covers", "Covers Skins"
), c("Women Shoes", "Shoes Boots"), c("Men Men", "Men s", "s Accessories",
"Accessories Belts"), c("Electronics Cell", "Cell Phones", "Phones Accessories",
"Accessories Cell", "Cell Phones", "Phones Smartphones"), c("Women Tops",
"Tops Blouses", "Blouses Other"), c("Women Athletic", "Athletic Apparel",
"Apparel Pants", "Pants Tights", "Tights Leggings"), c("Home Home",
"Home DÃ", "DÃ cor", "cor Home", "Home Fragrance"))

meltedBigrams <- do.call(rbind,lapply(seq_along(theBigrams),function(i) {
     x <- theBigrams[[i]]
     bigram <- 1:length(x)
     id <- rep(i,length(x))
     data.frame(id,bigram,value=x,stringsAsFactors=FALSE)
}))
library(reshape2)
castData <- dcast(meltedBigrams,id ~ bigram )
castData
</code>```

...and the output:

```<code>> castData
   id                1                2                  3                 4               5                  6
1   1   Women Athletic Athletic Apparel      Apparel Pants      Pants Tights Tights Leggings               <NA>
2   2    Beauty Makeup      Makeup Face               <NA>              <NA>            <NA>               <NA>
3   3    Beauty Makeup      Makeup Face               <NA>              <NA>            <NA>               <NA>
4   4 Electronics Cell      Cell Phones Phones Accessories Accessories Cases    Cases Covers       Covers Skins
5   5      Women Shoes      Shoes Boots               <NA>              <NA>            <NA>               <NA>
6   6          Men Men            Men s      s Accessories Accessories Belts            <NA>               <NA>
7   7 Electronics Cell      Cell Phones Phones Accessories  Accessories Cell     Cell Phones Phones Smartphones
8   8       Women Tops     Tops Blouses      Blouses Other              <NA>            <NA>               <NA>
9   9   Women Athletic Athletic Apparel      Apparel Pants      Pants Tights Tights Leggings               <NA>
10 10        Home Home          Home DÃ             DÃ cor          cor Home  Home Fragrance               <NA>
>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I got list of several text got from ngram, and want to add to original datatable as columns.

> prep_test
                                                                                prep_test
 1:                      Women Athletic,Athletic Apparel,Apparel Pants,Pants Tights,Tights Leggings
 2:                                                                       Beauty Makeup,Makeup Face
 3:                                                                       Beauty Makeup,Makeup Face
 4:     Electronics Cell,Cell Phones,Phones Accessories,Accessories Cases,Cases Covers,Covers Skins
 5:                                                                         Women Shoes,Shoes Boots
 6:                                                   Men Men,Men s,s Accessories,Accessories Belts
 7: Electronics Cell,Cell Phones,Phones Accessories,Accessories Cell,Cell Phones,Phones Smartphones
 8:                                                           Women Tops,Tops Blouses,Blouses Other
 9:                      Women Athletic,Athletic Apparel,Apparel Pants,Pants Tights,Tights Leggings
10:                                                Home Home,Home DÃ,DÃ cor,cor Home,Home Fragrance

str(prep_test)
Classes ‘data.table’ and 'data.frame':  10 obs. of  1 variable:
 $ prep_test:List of 10
  ..$ : chr  "Women Athletic" "Athletic Apparel" "Apparel Pants" "Pants Tights" ...
  ..$ : chr  "Beauty Makeup" "Makeup Face"
  ..$ : chr  "Beauty Makeup" "Makeup Face"
  ..$ : chr  "Electronics Cell" "Cell Phones" "Phones Accessories" "Accessories Cases" ...
  ..$ : chr  "Women Shoes" "Shoes Boots"
  ..$ : chr  "Men Men" "Men s" "s Accessories" "Accessories Belts"
  ..$ : chr  "Electronics Cell" "Cell Phones" "Phones Accessories" "Accessories Cell" ...
  ..$ : chr  "Women Tops" "Tops Blouses" "Blouses Other"
  ..$ : chr  "Women Athletic" "Athletic Apparel" "Apparel Pants" "Pants Tights" ...
  ..$ : chr  "Home Home" "Home DÃ" "DÃ cor" "cor Home" ...
 - attr(*, ".internal.selfref")=<externalptr>

current code to generate n-gram for a column

bigram_fun <- function(y){
  y <- gsub("[[:punct:][:blank:]]+", " ", y)
  y <- ngram_asweka(y, min=2, max=2)
  #y <- str_split_fixed(y, ",", n=Inf)
  #y <- unlist(y)
  return(y)
}

prep_test <- all[1:10, 9]
prep_test <- apply(prep_test, 1, bigram_fun)
prep_test <- data.table(prep_test)
prep_test

dput here

> dput(prep_test)
list(c("Women Athletic", "Athletic Apparel", "Apparel Pants",
"Pants Tights", "Tights Leggings"), c("Beauty Makeup", "Makeup Face"
), c("Beauty Makeup", "Makeup Face"), c("Electronics Cell", "Cell Phones",
"Phones Accessories", "Accessories Cases", "Cases Covers", "Covers Skins"
), c("Women Shoes", "Shoes Boots"), c("Men Men", "Men s", "s Accessories",
"Accessories Belts"), c("Electronics Cell", "Cell Phones", "Phones Accessories",
"Accessories Cell", "Cell Phones", "Phones Smartphones"), c("Women Tops",
"Tops Blouses", "Blouses Other"), c("Women Athletic", "Athletic Apparel",
"Apparel Pants", "Pants Tights", "Tights Leggings"), c("Home Home",
"Home DÃ", "DÃ cor", "cor Home", "Home Fragrance"))

desired outcome

Bigram 1           Bigram 2           Bigram 3              Bigram 4     ...
"Women Athletic"   "Athletic Apparel" "Apparel Pants"      "Pants Tights"...
"Beauty Makeup"    "Makeup Face"      NA                    NA           ...
"Beauty Makeup"    "Makeup Face"      NA                    NA           ...
"Electronics Cell" "Cell Phones"      "Phones Accessories" "Accessories Cases"
"Women Shoes"      "Shoes Boots"      NA                    NA

Appreciate any answers, and sorry for poor questions here as a newbie here

Body:
We can convert the bigrams to data frames, bind into a molten data frame, then cast to a wide format tidy data file as follows.

theBigrams <- list(c("Women Athletic", "Athletic Apparel", "Apparel Pants",
"Pants Tights", "Tights Leggings"), c("Beauty Makeup", "Makeup Face"),
 c("Beauty Makeup", "Makeup Face"), c("Electronics Cell", "Cell Phones",
"Phones Accessories", "Accessories Cases", "Cases Covers", "Covers Skins"
), c("Women Shoes", "Shoes Boots"), c("Men Men", "Men s", "s Accessories",
"Accessories Belts"), c("Electronics Cell", "Cell Phones", "Phones Accessories",
"Accessories Cell", "Cell Phones", "Phones Smartphones"), c("Women Tops",
"Tops Blouses", "Blouses Other"), c("Women Athletic", "Athletic Apparel",
"Apparel Pants", "Pants Tights", "Tights Leggings"), c("Home Home",
"Home DÃ", "DÃ cor", "cor Home", "Home Fragrance"))

meltedBigrams <- do.call(rbind,lapply(seq_along(theBigrams),function(i) {
     x <- theBigrams[[i]]
     bigram <- 1:length(x)
     id <- rep(i,length(x))
     data.frame(id,bigram,value=x,stringsAsFactors=FALSE)
}))
library(reshape2)
castData <- dcast(meltedBigrams,id ~ bigram )
castData

...and the output:

> castData
   id                1                2                  3                 4               5                  6
1   1   Women Athletic Athletic Apparel      Apparel Pants      Pants Tights Tights Leggings               <NA>
2   2    Beauty Makeup      Makeup Face               <NA>              <NA>            <NA>               <NA>
3   3    Beauty Makeup      Makeup Face               <NA>              <NA>            <NA>               <NA>
4   4 Electronics Cell      Cell Phones Phones Accessories Accessories Cases    Cases Covers       Covers Skins
5   5      Women Shoes      Shoes Boots               <NA>              <NA>            <NA>               <NA>
6   6          Men Men            Men s      s Accessories Accessories Belts            <NA>               <NA>
7   7 Electronics Cell      Cell Phones Phones Accessories  Accessories Cell     Cell Phones Phones Smartphones
8   8       Women Tops     Tops Blouses      Blouses Other              <NA>            <NA>               <NA>
9   9   Women Athletic Athletic Apparel      Apparel Pants      Pants Tights Tights Leggings               <NA>
10 10        Home Home          Home DÃ             DÃ cor          cor Home  Home Fragrance               <NA>
>


问:
How to emulate the same behaviour in kotlin
How to emulate the same behaviour using lambdas kotlin.

Java Code:

```<code>   public interface OnClickListener{
    public void onClick();
    }

    public class Sample {

            OnclickListener mOnclickListener;

            public void setOnclickListener(OnclickListener l){

                if(l!=null)
                mOnclickListener =l;
            }

            public void performClick()
            {
                mOnclickListener.onClick(5);
            }

        }

  public class SampleImpl{

     Sample sample=new Sample();
      sample.setOnClickListener(new OnClickListner(){ onClick{}});

     sample.performClick();

}
</code>```

As per kotlin, function receives parameter of interface with single method can represent in lambda, i am trying...

Kotlin code :

```<code>var sample= Sample();

    sample.setOnClickListener({Int ->  println("action performed") })
    sample.performClick(); //will call this method whenever needed.

    class Sample {

         var click=null;

        fun setOnClickListener(onClick : (Int)->Unit){

           click= onClick // trying to assign and want to use it in another
                              funciton. I know it is wrong, how to achieve
                             this.
        }

      fun performClick()
       {
           click(5)
       }
    }
</code>```

Is there any alternative to achieve this?

答:
I know it already answered, but if you want to stick with null declaration of click variable, you can write it like:

```<code>class Sample {
    var click: ((Int)->Unit)? = null

    fun setOnClickListener(onClick : (Int)->Unit) {
        click = onClick
    }

    fun performClick() {
        click?.invoke(5)
    }
}
</code>```

Hope it can help anyone

Body:
How to emulate the same behaviour using lambdas kotlin.

Java Code:

   public interface OnClickListener{
    public void onClick();
    }

    public class Sample {

            OnclickListener mOnclickListener;

            public void setOnclickListener(OnclickListener l){

                if(l!=null)
                mOnclickListener =l;
            }

            public void performClick()
            {
                mOnclickListener.onClick(5);
            }

        }

  public class SampleImpl{

     Sample sample=new Sample();
      sample.setOnClickListener(new OnClickListner(){ onClick{}});

     sample.performClick();

}

As per kotlin, function receives parameter of interface with single method can represent in lambda, i am trying...

Kotlin code :

var sample= Sample();

    sample.setOnClickListener({Int ->  println("action performed") })
    sample.performClick(); //will call this method whenever needed.

    class Sample {

         var click=null;

        fun setOnClickListener(onClick : (Int)->Unit){

           click= onClick // trying to assign and want to use it in another
                              funciton. I know it is wrong, how to achieve
                             this.
        }

      fun performClick()
       {
           click(5)
       }
    }

Is there any alternative to achieve this?

Body:
I know it already answered, but if you want to stick with null declaration of click variable, you can write it like:

class Sample {
    var click: ((Int)->Unit)? = null

    fun setOnClickListener(onClick : (Int)->Unit) {
        click = onClick
    }

    fun performClick() {
        click?.invoke(5)
    }
}

Hope it can help anyone


问:
Connect consul agent to consul
I'm trying to setup the consul server and connect an agent to it for 2 or 3 days already. I'm using docker-compose.

But after performing a join operation, agent gets a message "Agent not live or unreachable".

Here are the logs:

```<code>root@e33a6127103f:/app# consul agent -join 10.1.30.91 -data-dir=/tmp/consul
==> Starting Consul agent...
==> Joining cluster...
Join completed. Synced with 1 initial agents
==> Consul agent running!
Version: 'v1.0.1'
Node ID: '0e1adf74-462d-45a4-1927-95ed123f1526'
Node name: 'e33a6127103f'
Datacenter: 'dc1' (Segment: '')
Server: false (Bootstrap: false)
Client Addr: [127.0.0.1] (HTTP: 8500, HTTPS: -1, DNS: 8600)
Cluster Addr: 172.17.0.2 (LAN: 8301, WAN: 8302)
Encrypt: Gossip: false, TLS-Outgoing: false, TLS-Incoming: false
==> Log data will now stream in as it occurs:
2017/12/06 10:44:43 [INFO] serf: EventMemberJoin: e33a6127103f 172.17.0.2
2017/12/06 10:44:43 [INFO] agent: Started DNS server 127.0.0.1:8600 (udp)
2017/12/06 10:44:43 [INFO] agent: Started DNS server 127.0.0.1:8600 (tcp)
2017/12/06 10:44:43 [INFO] agent: Started HTTP server on 127.0.0.1:8500 (tcp)
2017/12/06 10:44:43 [INFO] agent: (LAN) joining: [10.1.30.91]
2017/12/06 10:44:43 [INFO] serf: EventMemberJoin: consul1 172.19.0.2 2017/12/06 10:44:43 [INFO] consul: adding server consul1 (Addr: tcp/172.19.0.2:8300) (DC: dc1)
2017/12/06 10:44:43 [INFO] agent: (LAN) joined: 1 Err: <nil>
2017/12/06 10:44:43 [INFO] agent: started state syncer
2017/12/06 10:44:43 [WARN] manager: No servers available
2017/12/06 10:44:43 [ERR] agent: failed to sync remote state: No known Consul servers
2017/12/06 10:44:54 [INFO] memberlist: Suspect consul1 has failed, no acks received
2017/12/06 10:44:55 [ERR] consul: "Catalog.NodeServices" RPC failed to server 172.19.0.2:8300: rpc error getting client: failed to get conn: dial tcp <nil>->172.19.0.2:8300: i/o timeout
2017/12/06 10:44:55 [ERR] agent: failed to sync remote state: rpc error getting client: failed to get conn: dial tcp <nil>->172.19.0.2:8300: i/o timeout
2017/12/06 10:44:58 [INFO] memberlist: Marking consul1 as failed, suspect timeout reached (0 peer confirmations)
2017/12/06 10:44:58 [INFO] serf: EventMemberFailed: consul1 172.19.0.2
2017/12/06 10:44:58 [INFO] consul: removing server consul1 (Addr: tcp/172.19.0.2:8300) (DC: dc1)
2017/12/06 10:45:05 [INFO] memberlist: Suspect consul1 has failed, no acks received
2017/12/06 10:45:06 [WARN] manager: No servers available
2017/12/06 10:45:06 [ERR] agent: Coordinate update error: No known Consul servers
2017/12/06 10:45:12 [WARN] manager: No servers available
2017/12/06 10:45:12 [ERR] agent: failed to sync remote state: No known Consul servers
2017/12/06 10:45:13 [INFO] serf: attempting reconnect to consul1 172.19.0.2:8301
2017/12/06 10:45:28 [WARN] manager: No servers available
2017/12/06 10:45:28 [ERR] agent: failed to sync remote state: No known Consul servers
2017/12/06 10:45:32 [WARN] manager: No servers available . `
</code>```

My settings are:
docker-compose SERVER:

```<code>consul1:
image: "consul.1.0.1"
container_name: "consul1"
hostname: "consul1"
volumes:
- ./consul/config:/config/
ports:
- "8400:8400"
- "8500:8500"
- "8600:53"
- "8300:8300"
- "8301:8301"
command: "agent -config-dir=/config -ui -server -bootstrap-expect 1"
</code>```

Help please solve the problem.

答:
I think you using wrong ip-address of consul-server

"consul agent -join 10.1.30.91 -data-dir=/tmp/consul"

10.1.30.91 this is not docker container ip it might be your host address/virtualbox.

Get consul-container ip and use that to join in consul-agent command.

For more info about how consul and agent works follow the link

https://dzone.com/articles/service-discovery-with-docker-and-consul-part-1

Title: Connect consul agent to consul

Body:
I'm trying to setup the consul server and connect an agent to it for 2 or 3 days already. I'm using docker-compose.

But after performing a join operation, agent gets a message "Agent not live or unreachable".

Here are the logs:

root@e33a6127103f:/app# consul agent -join 10.1.30.91 -data-dir=/tmp/consul
==> Starting Consul agent...
==> Joining cluster...
Join completed. Synced with 1 initial agents
==> Consul agent running!
Version: 'v1.0.1'
Node ID: '0e1adf74-462d-45a4-1927-95ed123f1526'
Node name: 'e33a6127103f'
Datacenter: 'dc1' (Segment: '')
Server: false (Bootstrap: false)
Client Addr: [127.0.0.1] (HTTP: 8500, HTTPS: -1, DNS: 8600)
Cluster Addr: 172.17.0.2 (LAN: 8301, WAN: 8302)
Encrypt: Gossip: false, TLS-Outgoing: false, TLS-Incoming: false
==> Log data will now stream in as it occurs:
2017/12/06 10:44:43 [INFO] serf: EventMemberJoin: e33a6127103f 172.17.0.2
2017/12/06 10:44:43 [INFO] agent: Started DNS server 127.0.0.1:8600 (udp)
2017/12/06 10:44:43 [INFO] agent: Started DNS server 127.0.0.1:8600 (tcp)
2017/12/06 10:44:43 [INFO] agent: Started HTTP server on 127.0.0.1:8500 (tcp)
2017/12/06 10:44:43 [INFO] agent: (LAN) joining: [10.1.30.91]
2017/12/06 10:44:43 [INFO] serf: EventMemberJoin: consul1 172.19.0.2 2017/12/06 10:44:43 [INFO] consul: adding server consul1 (Addr: tcp/172.19.0.2:8300) (DC: dc1)
2017/12/06 10:44:43 [INFO] agent: (LAN) joined: 1 Err: <nil>
2017/12/06 10:44:43 [INFO] agent: started state syncer
2017/12/06 10:44:43 [WARN] manager: No servers available
2017/12/06 10:44:43 [ERR] agent: failed to sync remote state: No known Consul servers
2017/12/06 10:44:54 [INFO] memberlist: Suspect consul1 has failed, no acks received
2017/12/06 10:44:55 [ERR] consul: "Catalog.NodeServices" RPC failed to server 172.19.0.2:8300: rpc error getting client: failed to get conn: dial tcp <nil>->172.19.0.2:8300: i/o timeout
2017/12/06 10:44:55 [ERR] agent: failed to sync remote state: rpc error getting client: failed to get conn: dial tcp <nil>->172.19.0.2:8300: i/o timeout
2017/12/06 10:44:58 [INFO] memberlist: Marking consul1 as failed, suspect timeout reached (0 peer confirmations)
2017/12/06 10:44:58 [INFO] serf: EventMemberFailed: consul1 172.19.0.2
2017/12/06 10:44:58 [INFO] consul: removing server consul1 (Addr: tcp/172.19.0.2:8300) (DC: dc1)
2017/12/06 10:45:05 [INFO] memberlist: Suspect consul1 has failed, no acks received
2017/12/06 10:45:06 [WARN] manager: No servers available
2017/12/06 10:45:06 [ERR] agent: Coordinate update error: No known Consul servers
2017/12/06 10:45:12 [WARN] manager: No servers available
2017/12/06 10:45:12 [ERR] agent: failed to sync remote state: No known Consul servers
2017/12/06 10:45:13 [INFO] serf: attempting reconnect to consul1 172.19.0.2:8301
2017/12/06 10:45:28 [WARN] manager: No servers available
2017/12/06 10:45:28 [ERR] agent: failed to sync remote state: No known Consul servers
2017/12/06 10:45:32 [WARN] manager: No servers available . `

My settings are:
docker-compose SERVER:

consul1:
image: "consul.1.0.1"
container_name: "consul1"
hostname: "consul1"
volumes:
- ./consul/config:/config/
ports:
- "8400:8400"
- "8500:8500"
- "8600:53"
- "8300:8300"
- "8301:8301"
command: "agent -config-dir=/config -ui -server -bootstrap-expect 1"

Help please solve the problem.


问:
create and open record in inherited tree view is not working in odoo
I am new to odoo. I have inherited res.partner tree view for my custom module but the create and open operations does not work on inherited view.Here is my code plz help.

in my view.xml file.

```<code><record id="my_contacts" model="ir.actions.act_window">
    <field name="name">my contacts</field>
    <field name="type">ir.actions.act_window</field>
    <field name="res_model">res.partner</field>
    <field name="view_mode">tree</field>
    <field name="view_id" ref="base.view_partner_tree"/>
    <field name="search_view_id" ref="base.view_res_partner_filter"/>
    <field name="help" type="html">
      <p class="oe_view_nocontent_create">
        Click to add a new contact.
      </p>
    </field>
</record>

 <record id="my_res_partner_tree" model="ir.ui.view">
<field name="name">res.partner.extended</field>
<field name="model">res.partner</field>
<field name="inherit_id" ref="base.view_partner_tree"/>
<field name="arch" type="xml">
    <xpath expr="//field[@name='email']" position="after">
        <field name="create_date"/>
        </xpath>
</field>
</code>```

in my model.py file

```<code>class my_contact_template(models.Model):
_inherit = 'res.partner'
_name = 'res.partner'
    _order = "create_date desc"
res_partner()
</code>```

答:
That is because the Tree view don't support that by default
you need to add attribute editable="top" but pay attention
to this because it affect the tree view in all action and
when you click on the record next time it will not open it
in the form view, but instead it will start editing the record
in the tree view so you have two option:

1- open the record in two view Tree,Form so you can open the record in
      The form and edit them.

  <field name="view_mode">tree,form</field>
```

<p>2- make your tree view editable:</p>

<pre class="lang-xml prettyprint-override"><code>    <field name="arch" type="xml">
        <xpath expr="/tree" position="attributes">
            <attribute name="editable">top</attribute>
        </xpath>

        <xpath expr="//field[@name='email']" position="after">
            <field name="create_date"/>
        </xpath>
    </field>
</code>```

Body:
I am new to odoo. I have inherited res.partner tree view for my custom module but the create and open operations does not work on inherited view.Here is my code plz help.

in my view.xml file.

<record id="my_contacts" model="ir.actions.act_window">
    <field name="name">my contacts</field>
    <field name="type">ir.actions.act_window</field>
    <field name="res_model">res.partner</field>
    <field name="view_mode">tree</field>
    <field name="view_id" ref="base.view_partner_tree"/>
    <field name="search_view_id" ref="base.view_res_partner_filter"/>
    <field name="help" type="html">

        Click to add a new contact.

    </field>
</record>

 <record id="my_res_partner_tree" model="ir.ui.view">
<field name="name">res.partner.extended</field>
<field name="model">res.partner</field>
<field name="inherit_id" ref="base.view_partner_tree"/>
<field name="arch" type="xml">
    <xpath expr="//field[@name='email']" position="after">
        <field name="create_date"/>
        </xpath>
</field>

in my model.py file

class my_contact_template(models.Model):
_inherit = 'res.partner'
_name = 'res.partner'
    _order = "create_date desc"
res_partner()

Body:
That is because the Tree view don't support that by default
you need to add attribute editable="top" but pay attention
to this because it affect the tree view in all action and
when you click on the record next time it will not open it
in the form view, but instead it will start editing the record
in the tree view so you have two option:

1- open the record in two view Tree,Form so you can open the record in
      The form and edit them.

  <field name="view_mode">tree,form</field>

2- make your tree view editable:

    <field name="arch" type="xml">
        <xpath expr="/tree" position="attributes">
            <attribute name="editable">top</attribute>
        </xpath>

        <xpath expr="//field[@name='email']" position="after">
            <field name="create_date"/>
        </xpath>
    </field>


问:
C++ Iterator declare from typedef std::map as template argument
How can I declare an iterator for template argument map?

I know I could pass it as argument from main function as another template argument, but if I don't, how can I declare it?

```<code>template< typename container >
int print_data( container map )
{
    map::iterator iter; // this is wrong
    return 0;
}

int main()
{
    typedef std::map< int, double > Map;
    Map new_map;

    print_data< Map >( new_map );
}
</code>```

答:
If you are able to use a C++11 (or later) compiler, you have couple of more ways to declare iter.

If you can declare and initialize it in one statement, you can use:

```<code>auto iter = map.begin();
</code>```

You can also use decltype to deduce the type.

```<code>using iterator_type = decltype(map.begin());
iterator_type iter;
</code>```

I would recommend using the first method. It is less code to deal with. It's also a better programming habit to declare and initialize a variable in one statement.

Body:
How can I declare an iterator for template argument map?

I know I could pass it as argument from main function as another template argument, but if I don't, how can I declare it?

template< typename container >
int print_data( container map )
{
    map::iterator iter; // this is wrong
    return 0;
}

int main()
{
    typedef std::map< int, double > Map;
    Map new_map;

    print_data< Map >( new_map );
}

Body:
If you are able to use a C++11 (or later) compiler, you have couple of more ways to declare iter.

If you can declare and initialize it in one statement, you can use:

auto iter = map.begin();

You can also use decltype to deduce the type.

using iterator_type = decltype(map.begin());
iterator_type iter;

I would recommend using the first method. It is less code to deal with. It's also a better programming habit to declare and initialize a variable in one statement.


问:
Print into console terminal not into cell output of IPython Notebook
I would like to print into the terminal window that runs IPython Notebook and not into the cell output. Printing into cell output consumes more memory and slows down my system when I issue a substantial number of print calls. In essence, I would like this behaviour by design.

I have tried the following:

I tried a different permutations of print and sys.stdout.write calls

I looked at the IPython Notebook documentation here, here and here without help

I have tried using this as a workaround but it seems to be only working on Python 2.7

答:
On Windows, this can work:</p>

```<code>import sys
sys.stdout = open(1, 'w')
</code>```

Body:
On Windows, this can work:

import sys
sys.stdout = open(1, 'w')


问:
How can i repeat active class only once?

My v-for works properly but thing is i want my bootstrap 4 css .active class also repeat.i want to bootstrap 4 active class repeat only once.
please suggest me how can i get rid of this.

var app = new Vue ({
  el: '#app',
  data:{
   subjects: ['CSE','EEE','BBA']
  }
 })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
  font-family: 'Trykker','Spectral SC', serif;
 }
 h1,h2,h3,h4,h5,h6{
  font-family: 'Spectral SC', serif;
 }
 p{
  font-family: 'Trykker', serif;
 }</code>```

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

{{ subject }}

 ```

答:
Are you asking for only active the selected subject?
You can check for the class and style binding on vuejs official website. I have included the example.

var app = new Vue ({
        el: '#app',
        data:{
            activeSubject: 'CSE',
            subjects: ['CSE','EEE','BBA']
        }
    })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
        font-family: 'Trykker','Spectral SC', serif;
    }
    h1,h2,h3,h4,h5,h6{
        font-family: 'Spectral SC', serif;
    }
    p{
        font-family: 'Trykker', serif;
    }</code>```

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

{{ subject }}

    ```

Body:
My v-for works properly but thing is i want my bootstrap 4 css .active class also repeat.i want to bootstrap 4 active class repeat only once.
please suggest me how can i get rid of this.

var app = new Vue ({
  el: '#app',
  data:{
   subjects: ['CSE','EEE','BBA']
  }
 })

body{
  font-family: 'Trykker','Spectral SC', serif;
 }
 h1,h2,h3,h4,h5,h6{
  font-family: 'Spectral SC', serif;
 }
 p{
  font-family: 'Trykker', serif;
 }

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

{{ subject }}

Body:
Are you asking for only active the selected subject?
You can check for the class and style binding on vuejs official website. I have included the example.

var app = new Vue ({
        el: '#app',
        data:{
            activeSubject: 'CSE',
            subjects: ['CSE','EEE','BBA']
        }
    })

body{
        font-family: 'Trykker','Spectral SC', serif;
    }
    h1,h2,h3,h4,h5,h6{
        font-family: 'Spectral SC', serif;
    }
    p{
        font-family: 'Trykker', serif;
    }

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
  <script src="https://unpkg.com/vue/dist/vue.js"></script>

    <div class="container">
        <div class="row">
            <div id="app">

            <ul class="list-group">
                <li v-for="subject in subjects" class="list-group-item" :class="{active:subject==activeSubject}">{{ subject }}</li>
            </ul>

            </div>
        </div>
    </div>

ContentLicense: CC BY-SA 4.0


问:
Can I get ido-mode-style completion for searching tags in Emacs?
Is it possible to use ido-mode completion to find definitions in a TAGS file?  I suspect that ido-completing-read is part of the answer.  Here's my non-working code, which shows an unpopulated ido-mode minibuffer:</p>

```<code>(defun ido-choose-from-tags ()
  "Use ido to select tags "
  (interactive)
    (etags-tags-apropos
     (ido-completing-read "Tags: "  nil t)))
</code>```

答:
Of course it's possible, this is EMACS.  What does the non-working code do that tells you it isn't working?

My first suspicion is that it might work better if you used tags-apropos (see about line 1885 in etags.el), seeing as etags-tags-apropos isn't defined and all.

OwnerDisplayName: James Sulak

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to use ido-mode completion to find definitions in a TAGS file?  I suspect that ido-completing-read is part of the answer.  Here's my non-working code, which shows an unpopulated ido-mode minibuffer:

(defun ido-choose-from-tags ()
  "Use ido to select tags "
  (interactive)
    (etags-tags-apropos
     (ido-completing-read "Tags: "  nil t)))

LastEditorDisplayName: James Sulak

OwnerDisplayName: Charlie Martin


问:
Disable COD when exceeded specific amount

I need to disable Woocommerce COD option and make it unchecked when total price exceeded certain amount.

I tried this code, but does nothing!

```<code>add_filter('woocommerce_available_payment_gateways', 'unsetting_payment_gateway', 10, 1);
function unsetting_payment_gateway( $available_gateways ) {
    global $woocommerce;
    $shipping_cost = WC()->cart->get_cart_shipping_total();
    $amount = $woocommerce->cart->cart_contents_total + $woocommerce->cart->tax_total + $shipping_cost;

  $max = 999.9 * WCPBC()->customer->exchange_rate;

    if($amount >= $max){   ?>
    <script type="text/javascript">
        jQuery(document).ready(function ($) {
          $("#payment_method_cod").disabled = true;
          $("#payment_method_cod").checked = false;
        });
    </script>
    <?php
    add_action( 'woocommerce_review_order_before_payment', 'COD_exceed_amount_before_paying_notice' );
  }
    return $available_gateways;
}

function COD_exceed_amount_before_paying_notice() {
  wc_print_notice( __( 'COD amount exceeded!', 'woocommerce' ), 'notice' );
}
</code>```

答:
First you need to deregister the woocommerce/assets/js/frontend/checkout.js

Then include checkout.js in your theme assets folder and register it again after theme script files

then your code will work as you expect.

for deregister use below code,

wp_deregister_script( $handle );

again register by,

wp_enqueue_script(parameters);

Body:
I need to disable Woocommerce COD option and make it unchecked when total price exceeded certain amount.

I tried this code, but does nothing!

add_filter('woocommerce_available_payment_gateways', 'unsetting_payment_gateway', 10, 1);
function unsetting_payment_gateway( $available_gateways ) {
    global $woocommerce;
    $shipping_cost = WC()->cart->get_cart_shipping_total();
    $amount = $woocommerce->cart->cart_contents_total + $woocommerce->cart->tax_total + $shipping_cost;

  $max = 999.9 * WCPBC()->customer->exchange_rate;

    if($amount >= $max){   ?>

    <?php
    add_action( 'woocommerce_review_order_before_payment', 'COD_exceed_amount_before_paying_notice' );
  }
    return $available_gateways;
}

function COD_exceed_amount_before_paying_notice() {
  wc_print_notice( __( 'COD amount exceeded!', 'woocommerce' ), 'notice' );
}


问:
Angular 5 - Can't bind to 'ngFormOptions' since it isn't a known property of 'form'
We just recently updated our application Angular version to v5 and as part of new update Forms support ngFormOptions to configure the validations for form elements on certain events. Below is what we have done:

```<code><form class="example-form" autocomplete="off" [ngFormOptions]="{updateOn:'submit'}" [formGroup]="testform">

</form>
</code>```

But it's throwing below error

Can't bind to 'ngFormOptions' since it isn't a known property of
  'form'

Below the dependencies for the application after update.

package.json

```<code>"dependencies": {
    "@angular/animations": "5.0.0-rc.5",
    "@angular/common": "5.0.0-rc.5",
    "@angular/compiler": "5.0.0-rc.5",
    "@angular/core": "5.0.0-rc.5",
    "@angular/forms": "5.0.0-rc.5",
    "@angular/http": "5.0.0-rc.5",
    "@angular/platform-browser": "5.0.0-rc.5",
    "@angular/platform-browser-dynamic": "5.0.0-rc.5",
    "@angular/router": "5.0.0-rc.5",
    "core-js": "^2.4.1",
    "ng2-accordion": "0.0.15",
    "ngx-bootstrap": "^1.9.3",
    "ngx-popover": "0.0.16",
    "rxjs": "^5.5.2",
    "typescript": "2.4.2",
    "zone.js": "^0.8.14"
},
"devDependencies": {
    "@angular/cli": "^1.5.4",
    "@angular/compiler-cli": "5.0.0",
    "@angular/language-service": "5.0.0",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.1.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.3.2"
}
</code>```

What else are we missing here? Why we still get this error even after the proper update?

答:
As @Andriy mentioned in his comments

ngForms selector is selector: 'form:not([ngNoForm]):not([formGroup]),ngForm,[ngForm]'  - source . Thus, using formGroup directive on form will make this form as NOT ngForm and ngFormOptions will have no affect in this case.

Alternatively, we can use the said options in `component file as below:

```<code>this.testform = new FormGroup({
      testcontrol: new FormControl('', Validators.required)
}, {updateOn: 'submit'});
</code>```

Body:
We just recently updated our application Angular version to v5 and as part of new update Forms support ngFormOptions to configure the validations for form elements on certain events. Below is what we have done:

<form class="example-form" autocomplete="off" [ngFormOptions]="{updateOn:'submit'}" [formGroup]="testform">

</form>

But it's throwing below error

Can't bind to 'ngFormOptions' since it isn't a known property of
  'form'

Below the dependencies for the application after update.

package.json

"dependencies": {
    "@angular/animations": "5.0.0-rc.5",
    "@angular/common": "5.0.0-rc.5",
    "@angular/compiler": "5.0.0-rc.5",
    "@angular/core": "5.0.0-rc.5",
    "@angular/forms": "5.0.0-rc.5",
    "@angular/http": "5.0.0-rc.5",
    "@angular/platform-browser": "5.0.0-rc.5",
    "@angular/platform-browser-dynamic": "5.0.0-rc.5",
    "@angular/router": "5.0.0-rc.5",
    "core-js": "^2.4.1",
    "ng2-accordion": "0.0.15",
    "ngx-bootstrap": "^1.9.3",
    "ngx-popover": "0.0.16",
    "rxjs": "^5.5.2",
    "typescript": "2.4.2",
    "zone.js": "^0.8.14"
},
"devDependencies": {
    "@angular/cli": "^1.5.4",
    "@angular/compiler-cli": "5.0.0",
    "@angular/language-service": "5.0.0",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.1.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.3.2"
}

What else are we missing here? Why we still get this error even after the proper update?

Body:
As @Andriy mentioned in his comments

ngForms selector is selector: 'form:not([ngNoForm]):not([formGroup]),ngForm,[ngForm]'  - source . Thus, using formGroup directive on form will make this form as NOT ngForm and ngFormOptions will have no affect in this case.

Alternatively, we can use the said options in `component file as below:

this.testform = new FormGroup({
      testcontrol: new FormControl('', Validators.required)
}, {updateOn: 'submit'});


问:
Unrecognized keyword. in PHP
hi my name is milind and trying to mysql UPDATE query fire with CASE and WHEN statement and i getting this error below:

```<code>24 errors were found during analysis.

Unrecognized keyword. (near "CASE" at position 27)
Unrecognized keyword. (near "WHEN" at position 32)
Unexpected token. (near "id" at position 37)
Unexpected token. (near "=" at position 39)
Unexpected token. (near "'2'" at position 40)
Unrecognized keyword. (near "THEN" at position 44)
Unexpected token. (near "'Y'" at position 49)
Unrecognized keyword. (near "ELSE" at position 53)
Unrecognized keyword. (near "status" at position 58)
Unrecognized keyword. (near "END" at position 65)
Unexpected token. (near "," at position 68)
Unrecognized keyword. (near "status" at position 71)
Unexpected token. (near "!=" at position 78)
Unrecognized keyword. (near "CASE" at position 81)
Unrecognized keyword. (near "WHEN" at position 86)
Unrecognized keyword. (near "status" at position 91)
Unexpected token. (near "=" at position 98)
Unexpected token. (near "'2'" at position 99)
Unrecognized keyword. (near "THEN" at position 103)
Unexpected token. (near "'N'" at position 108)
Unrecognized keyword. (near "ELSE" at position 112)
Unrecognized keyword. (near "status" at position 117)
Unrecognized keyword. (near "END" at position 124)
Unexpected token. (near "," at position 127)
</code>```

and my UPDETE query is below:

```<code>UPDATE quotes SET status = CASE WHEN id='2' THEN 'Y' ELSE status END,
status = CASE WHEN id !='2' THEN 'N' ELSE status END,
WHERE id='2';
</code>```

i want update where status=Y insted of status=N and where stutus=N insted of status=Y.

答:
You seem to have misunderstood how to use the CASE statement. See the example below from this MySQL tutorial</p>

```<code>DELIMITER $$

CREATE PROCEDURE GetCustomerShipping(
 in  p_customerNumber int(11),
 out p_shiping        varchar(50))
BEGIN
    DECLARE customerCountry varchar(50);

    SELECT country INTO customerCountry
 FROM customers
 WHERE customerNumber = p_customerNumber;

    CASE customerCountry
 WHEN  'USA' THEN
    SET p_shiping = '2-day Shipping';
 WHEN 'Canada' THEN
    SET p_shiping = '3-day Shipping';
 ELSE
    SET p_shiping = '5-day Shipping';
 END CASE;

END$$
</code>```

Title: Unrecognized keyword. in PHP

Body:
hi my name is milind and trying to mysql UPDATE query fire with CASE and WHEN statement and i getting this error below:

24 errors were found during analysis.

Unrecognized keyword. (near "CASE" at position 27)
Unrecognized keyword. (near "WHEN" at position 32)
Unexpected token. (near "id" at position 37)
Unexpected token. (near "=" at position 39)
Unexpected token. (near "'2'" at position 40)
Unrecognized keyword. (near "THEN" at position 44)
Unexpected token. (near "'Y'" at position 49)
Unrecognized keyword. (near "ELSE" at position 53)
Unrecognized keyword. (near "status" at position 58)
Unrecognized keyword. (near "END" at position 65)
Unexpected token. (near "," at position 68)
Unrecognized keyword. (near "status" at position 71)
Unexpected token. (near "!=" at position 78)
Unrecognized keyword. (near "CASE" at position 81)
Unrecognized keyword. (near "WHEN" at position 86)
Unrecognized keyword. (near "status" at position 91)
Unexpected token. (near "=" at position 98)
Unexpected token. (near "'2'" at position 99)
Unrecognized keyword. (near "THEN" at position 103)
Unexpected token. (near "'N'" at position 108)
Unrecognized keyword. (near "ELSE" at position 112)
Unrecognized keyword. (near "status" at position 117)
Unrecognized keyword. (near "END" at position 124)
Unexpected token. (near "," at position 127)

and my UPDETE query is below:

UPDATE quotes SET status = CASE WHEN id='2' THEN 'Y' ELSE status END,
status = CASE WHEN id !='2' THEN 'N' ELSE status END,
WHERE id='2';

i want update where status=Y insted of status=N and where stutus=N insted of status=Y.

Body:
You seem to have misunderstood how to use the CASE statement. See the example below from this MySQL tutorial

DELIMITER $$

CREATE PROCEDURE GetCustomerShipping(
 in  p_customerNumber int(11),
 out p_shiping        varchar(50))
BEGIN
    DECLARE customerCountry varchar(50);

    SELECT country INTO customerCountry
 FROM customers
 WHERE customerNumber = p_customerNumber;

    CASE customerCountry
 WHEN  'USA' THEN
    SET p_shiping = '2-day Shipping';
 WHEN 'Canada' THEN
    SET p_shiping = '3-day Shipping';
 ELSE
    SET p_shiping = '5-day Shipping';
 END CASE;

END$$


问:
how the event bubbling and phases occurred in html
How are events and phases triggered according to the events?

like every objects created in tree with their handles and if you click on one button all events linked in that div are triggered.

I have made program which have different sub div and having one paragraph and button.

I have came across different theories for event bubbling like event bubbling explained

答:
Basic Example
in HTML, elements are nested inside other elements like so

```<code><div id="outer">
   <h1 id="inner">Inner<h1>
</div>
</code>```

when an event on an inner element is triggered it affects every outer element as you might have read in the post you linked. This is bubbling. Event flow can be controlled by

```<code>var element = document.getElementById('inner');
element.addEventListener("event",yourFunction, false);
</code>```

here, false means event flow is from the inner element (on which event is fired) to the outer elements. this is the default in all browsers.

to stop bubbling you could use stopPropagation()

Body:
Basic Example
in HTML, elements are nested inside other elements like so

<div id="outer">
   <h1 id="inner">Inner<h1>
</div>

when an event on an inner element is triggered it affects every outer element as you might have read in the post you linked. This is bubbling. Event flow can be controlled by

var element = document.getElementById('inner');
element.addEventListener("event",yourFunction, false);

here, false means event flow is from the inner element (on which event is fired) to the outer elements. this is the default in all browsers.

to stop bubbling you could use stopPropagation()


问:
How to disable Shift Ctrl?
I would like to disable Shift Ctrl without disabling other shorcuts like Shift Ctrl A, or Ctrl A, or Shift A.

I have tried multiple combinaison of ^+:: return with and without :

```<code>- Up : ^+ Up:: return
- ~ : ~^+ Up:: return
- & : ~^ & ~+ Up:: return
</code>```

Nothing work. Even when I start my script as admin it doesn work.

I want to rename Shift Ctrl because I have two keyboard languages and pressing Shift Ctrl change it. I already have the shorcut Windows Space so I don't need Shift Ctrl.

I have tried with ahk but I am open to any other way to solve this.

答:
"^" is the modifier symbol for the Control key and "+" for the Shift key.

Modifier symbols are used only in key-combinations for modifying other keys.

Try also

```<code>+Ctrl Up:: return
</code>```

or

```<code>Shift & Ctrl Up:: return
</code>```

EDIT:

You can change or remove the combination  that changes the keyboard language on Control panel --> Language, as shown in the comments below.

Title: How to disable Shift Ctrl?

Body:
I would like to disable Shift Ctrl without disabling other shorcuts like Shift Ctrl A, or Ctrl A, or Shift A.

I have tried multiple combinaison of ^+:: return with and without :

- Up : ^+ Up:: return
- ~ : ~^+ Up:: return
- & : ~^ & ~+ Up:: return

Nothing work. Even when I start my script as admin it doesn work.

I want to rename Shift Ctrl because I have two keyboard languages and pressing Shift Ctrl change it. I already have the shorcut Windows Space so I don't need Shift Ctrl.

I have tried with ahk but I am open to any other way to solve this.

Body:
"^" is the modifier symbol for the Control key and "+" for the Shift key.

Modifier symbols are used only in key-combinations for modifying other keys.

Try also

+Ctrl Up:: return

or

Shift & Ctrl Up:: return

EDIT:

You can change or remove the combination  that changes the keyboard language on Control panel --> Language, as shown in the comments below.


问:
How is it possible to do UI operations outside the UI thread?
I tried to set a text inside a normal thread outside of the UI thread and it worked fine.

```<code>    private TextView mTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.my_text);
        Log.d("**** ONCREATE****", Thread.currentThread().getId()+"");
        new BackgroundTestThread().start();
    }

    class BackgroundTestThread extends Thread{
    @Override
    public void run() {
         Log.d("**** THREAD****", Thread.currentThread().getId()+"");
         mTextView.setText("Text was set successfully", TextView.BufferType.EDITABLE);
         }
    }
</code>```

I was pretty much surprised to see this happen. I thought a worker thread can never update main thread because only main thread can render the UI elements (TextView, EditText etc.) and if we try to update, for sure we are going to get an exception.

Why did this happen?

答: It won't work sometimes as it is not thread safe. Thus, it is recommended to use handler or runonuithead.</p>

Body:
I tried to set a text inside a normal thread outside of the UI thread and it worked fine.

    private TextView mTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.my_text);
        Log.d("**** ONCREATE****", Thread.currentThread().getId()+"");
        new BackgroundTestThread().start();
    }

    class BackgroundTestThread extends Thread{
    @Override
    public void run() {
         Log.d("**** THREAD****", Thread.currentThread().getId()+"");
         mTextView.setText("Text was set successfully", TextView.BufferType.EDITABLE);
         }
    }

I was pretty much surprised to see this happen. I thought a worker thread can never update main thread because only main thread can render the UI elements (TextView, EditText etc.) and if we try to update, for sure we are going to get an exception.

Why did this happen?


问:
Replacing information in fixed length records in Python
Interestingly enough I found this exact question on this website - for the exact same homework problem no less- but a conclusion was never reached due to insufficient information about the problem. Hopefully, I will have better luck.

I am working on my Python 3 homework and I've come to a problem that I am really struggling with.

The exact prompt given is:

"You will be passed the filename 'P', firstname 'F', lastname 'L',
  and a new  birthday 'B'.    Load the fixed length record file in P,
  search for F,L in the first  and change birthday to B.    Then save
  the file."

The idea here being that we create a program to change a person's birthday from one unknown to another, using the variables given. Being the impatient person that I am I print()ed P - the file- and know that it is:

Adam            Smith           11111985Theodore        Anderson

  03201990Monty           Biscuit-Barrel  10181980Adam

  Smithers        10101960Ruthy           Anderson        06062010

The spacing gets lost upon pasting, but the first and last names have a fixed length of 16 each, and the birthdays have a fixed length of 8.

The name of the individual who's birthday I am trying to change is:

Adam Smithers

And that I am trying to change his birthday to:

00000000

I've tried replacing the birthday using slice (as, per our instruction, opening a text file in python turns the file into a string, and therefore immutabel). However, when I try the script:

```<code>with open(P) as p:
  new_file = p[0:141] + B + p[161:]
</code>```

I receive the error message " '_io.TextIOWrapper' object is not subscriptable"

I've been trying to finagle this for a couple hours now, but haven't gotten any closer. Any suggestions would be appreciated at this point. Thank you

答:
From the homework's description I understand that you need to update the existing file. For that you can use a memory map: mmap.
Here's a partial code you can take and extend:

```<code>import mmap
import os

def memory_map(filename):
    size = os.path.getsize(filename)
    fd = os.open(filename, os.O_RDWR)
    return mmap.mmap(fd, size, access=mmap.ACCESS_WRITE)

def update_file(P, F, L, B):
    with memory_map(P) as p:
        # Find the offset of the right record with F and L
        p[141:157] = B
</code>```

Body:
Interestingly enough I found this exact question on this website - for the exact same homework problem no less- but a conclusion was never reached due to insufficient information about the problem. Hopefully, I will have better luck.

I am working on my Python 3 homework and I've come to a problem that I am really struggling with.

The exact prompt given is:

"You will be passed the filename 'P', firstname 'F', lastname 'L',
  and a new  birthday 'B'.    Load the fixed length record file in P,
  search for F,L in the first  and change birthday to B.    Then save
  the file."

The idea here being that we create a program to change a person's birthday from one unknown to another, using the variables given. Being the impatient person that I am I print()ed P - the file- and know that it is:

Adam            Smith           11111985Theodore        Anderson

  03201990Monty           Biscuit-Barrel  10181980Adam

  Smithers        10101960Ruthy           Anderson        06062010

The spacing gets lost upon pasting, but the first and last names have a fixed length of 16 each, and the birthdays have a fixed length of 8.

The name of the individual who's birthday I am trying to change is:

Adam Smithers

And that I am trying to change his birthday to:

00000000

I've tried replacing the birthday using slice (as, per our instruction, opening a text file in python turns the file into a string, and therefore immutabel). However, when I try the script:

with open(P) as p:
  new_file = p[0:141] + B + p[161:]

I receive the error message " '_io.TextIOWrapper' object is not subscriptable"

I've been trying to finagle this for a couple hours now, but haven't gotten any closer. Any suggestions would be appreciated at this point. Thank you

Body:
From the homework's description I understand that you need to update the existing file. For that you can use a memory map: mmap.
Here's a partial code you can take and extend:

import mmap
import os

def memory_map(filename):
    size = os.path.getsize(filename)
    fd = os.open(filename, os.O_RDWR)
    return mmap.mmap(fd, size, access=mmap.ACCESS_WRITE)

def update_file(P, F, L, B):
    with memory_map(P) as p:
        # Find the offset of the right record with F and L
        p[141:157] = B


问:
ISO dateTime formatting in Java 7
I have date format like this 2016-11-25T12:29:10.588+01:00

I want to convert this to milliseconds and later while printing I have to again convert milliseconds to "yyyy-MM-dd HH:mm:ss.SSS" this format.

I have tried this its working fine but it give wrong value when time between 12 to 13, It sets hours to 00 insted of 12 or 13

(yyyy-mm-ddThh:mm:ss+-ZONE), for example: 2006-06-13T15:58:00.123+01:00.

```<code>SimpleDateFormat ISODateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSXXX");
Date result = ISODateFormat.parse(matcher.group(0));
syslogTimeStampInMillis = result.getTime();
</code>```

答:
hh = 12hours format, in combination with AM/PM

HH = 24hours format

(And to consider is - for other cases, like month names - the Locale.getDefault() that is used under the hood. One could specify the Locale too.)

Title: ISO dateTime formatting in Java 7

Body:
I have date format like this 2016-11-25T12:29:10.588+01:00

I want to convert this to milliseconds and later while printing I have to again convert milliseconds to "yyyy-MM-dd HH:mm:ss.SSS" this format.

I have tried this its working fine but it give wrong value when time between 12 to 13, It sets hours to 00 insted of 12 or 13

(yyyy-mm-ddThh:mm:ss+-ZONE), for example: 2006-06-13T15:58:00.123+01:00.

SimpleDateFormat ISODateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSXXX");
Date result = ISODateFormat.parse(matcher.group(0));
syslogTimeStampInMillis = result.getTime();


问:
Recycler View custom divider for rows
I want to add custom grid divider to RecyclerView , I have no idea please suggest some idea. For first row divider should start from beginning and for others it should be centered.

答:
For your solution we need to access middle column sequence 1,4,7,10... to get that

```<code>if (i % 3 == 1) {
  System.out.print(i);
}
</code>```

from this you'll get position and by that change/ add padding to line

Title: Recycler View custom divider for rows

Body:
For your solution we need to access middle column sequence 1,4,7,10... to get that

if (i % 3 == 1) {
  System.out.print(i);
}

from this you'll get position and by that change/ add padding to line


问:
trying to select data in mysql table in between two dates but code showing error
This is my php code which i am using for my requirment guide me the right one pls. Hope this is enough for understand .</p>

```<code><?php
$t1 = $_POST['t1'];
$t2 = $_POST['t2'];
$con=mysqli_connect("localhost","root","agni","gyaninfra");
$s=mysqli_query($con,"select * from shahabad where 'date' between '$t1' and
'$t2';");
echo "<br>";
echo "<table border='2'><tr class='autostyle'><td colspan='4'>SHAHABAD
RESORT ACCOUNT BOOK</td></tr>
  <tr><td>SR.NO.</td><td>Date</td>
  <td>Particulars</td><td>Debit/Credit</td>
  <td>Amount</td><td>Note</td><td>Recipt Image</td></tr>";
while($k=mysqli_fetch_array($s))
{
$a= $k['tr_img'];
echo "<tr><td>".$k['sr_no']."</td><td>".$k['date'].
   "</td><td>".$k['particulars']."</td><td>".$k['transaction'].
   "</td><td>".$k['amount']."</td><td>".$k['note'].
   "</td><td>"."<img height=100 widht=100 src ='$a'>"."</td></tr>";
}
echo "</table>";
?>
</code>```

答:
```<code><?php
$t1 = $_POST['t1'];
$t2 = $_POST['t2'];
$con=mysqli_connect("localhost","root","agni","gyaninfra");
$s=mysqli_query($con,"select * from shahabad where `date` between '".$t1."' and
'".$t2."';");
echo "<br>";
echo "<table border='2'><tr class='autostyle'><td colspan='4'>SHAHABAD
RESORT ACCOUNT BOOK</td></tr>
  <tr><td>SR.NO.</td><td>Date</td>
  <td>Particulars</td><td>Debit/Credit</td>
  <td>Amount</td><td>Note</td><td>Recipt Image</td></tr>";
while($k=mysqli_fetch_array($s))
{
$a= $k['tr_img'];
echo "<tr><td>".$k['sr_no']."</td><td>".$k['date'].
   "</td><td>".$k['particulars']."</td><td>".$k['transaction'].
   "</td><td>".$k['amount']."</td><td>".$k['note'].
   "</td><td>"."<img height=100 widht=100 src ='$a'>"."</td></tr>";
}
echo "</table>";
?>
</code>```

TRY this code :D

Body:
This is my php code which i am using for my requirment guide me the right one pls. Hope this is enough for understand .

<?php
$t1 = $_POST['t1'];
$t2 = $_POST['t2'];
$con=mysqli_connect("localhost","root","agni","gyaninfra");
$s=mysqli_query($con,"select * from shahabad where 'date' between '$t1' and
'$t2';");
echo "
";
echo "

SHAHABAD
RESORT ACCOUNT BOOK

SR.NO.	Date
  Particulars	Debit/Credit
  Amount	Note	Recipt Image
";
while($k=mysqli_fetch_array($s))
{
$a= $k['tr_img'];
echo "
".$k['sr_no']."	".$k['date'].
   "	".$k['particulars']."	".$k['transaction'].
   "	".$k['amount']."	".$k['note'].
   "	".""."
";
}
echo "
";
?>

Body:
<?php
$t1 = $_POST['t1'];
$t2 = $_POST['t2'];
$con=mysqli_connect("localhost","root","agni","gyaninfra");
$s=mysqli_query($con,"select * from shahabad where `date` between '".$t1."' and
'".$t2."';");
echo "<br>";
echo "<table border='2'><tr class='autostyle'><td colspan='4'>SHAHABAD
RESORT ACCOUNT BOOK</td></tr>
  <tr><td>SR.NO.</td><td>Date</td>
  <td>Particulars</td><td>Debit/Credit</td>
  <td>Amount</td><td>Note</td><td>Recipt Image</td></tr>";
while($k=mysqli_fetch_array($s))
{
$a= $k['tr_img'];
echo "<tr><td>".$k['sr_no']."</td><td>".$k['date'].
   "</td><td>".$k['particulars']."</td><td>".$k['transaction'].
   "</td><td>".$k['amount']."</td><td>".$k['note'].
   "</td><td>"."<img height=100 widht=100 src ='$a'>"."</td></tr>";
}
echo "</table>";
?>

TRY this code :D


问:
I need someone who explain me these lines of code
I need someone who explain me this code, line by line. I specially don't understand this line:

```<code>operator std::map<T, U>()
</code>```

Thank you very much.

```<code>template <typename T, typename U>
class create_map
{
    std::map<T, U> m_map;
public:
    create_map(const T& key, const U& val)
    {
        m_map[key] = val;
    }
    create_map<T, U>& operator()(const T& key, const U& val)
    {
        m_map[key] = val;
        return *this;
    }
    operator std::map<T, U>()
    {
        return m_map;
    }
};
</code>```

答:
The line

```<code>operator std::map<T, U>()
</code>```

defines a function that will be called when your create_map object is used like an std::map somewhere in the code.

An easier example would be:

```<code>class A
{
public:
  operator int()
  {
    return 3;
  }
};

int main()
{
  A a;
  cout << a << endl;
}
</code>```

Now the computer finds out that it doesn't know how to print variable a, but it knows how to convert it to an int and then print it. So "3" gets printed.

Body:
I need someone who explain me this code, line by line. I specially don't understand this line:

operator std::map<T, U>()

Thank you very much.

template <typename T, typename U>
class create_map
{
    std::map<T, U> m_map;
public:
    create_map(const T& key, const U& val)
    {
        m_map[key] = val;
    }
    create_map<T, U>& operator()(const T& key, const U& val)
    {
        m_map[key] = val;
        return *this;
    }
    operator std::map<T, U>()
    {
        return m_map;
    }
};

Body:
The line

operator std::map<T, U>()

defines a function that will be called when your create_map object is used like an std::map somewhere in the code.

An easier example would be:

class A
{
public:
  operator int()
  {
    return 3;
  }
};

int main()
{
  A a;
  cout << a << endl;
}

Now the computer finds out that it doesn't know how to print variable a, but it knows how to convert it to an int and then print it. So "3" gets printed.


问:
How to show differences between rows based on a 'version' column in Oracle data set?
I have written a variety of SQL queries for a university's large oracle database. The output is a list of available degrees and associated information.

I now need to find a way to show what has changed between versions (based on a column called 'version'. New versions are created when data is changed)

How might I highlight differences based on the output of my selects in the queries?

This is the smallest query I can show as an example:

```

    SELECT
      -- DETAILS
    b.programmeid,
    b.programmecode AS course_udc,
    b.programmeversion AS version,
    b.externalversion AS external_version,
    b.programme AS full_title,
      -- OUTCOMES
    b.programmeoutcomeid AS outcome_number,
    b.outcomedesc AS outcome_description,
    b.programmeoutcometypeid AS graduate_attribute_link
    FROM
    (
    SELECT
              -- DETAILS
    a.programmeid,
    a.programmecode,
    a.programmeversion,
    a.externalversion,
    a.programme,
              -- OUTCOMES
    a.programmeoutcomeid,
    a.outcomedesc,
    a.programmeoutcometypeid
    FROM
    document_application.dmn_domains d,
    (
    SELECT
                      -- DETAILS
    ed.dmn_cuid,
    p.programmeid,
    p.programmecode,
    p.programmeversion,
    p.externalversion,
    p.programme,
                      -- OUTCOMES
    plo.programmeoutcomeid,
    ( dbms_lob.substr(pso.suboutcomedesc,4000,1) ) AS outcomedesc,
    plo.programmeoutcometypeid
    FROM
    document_application.programmes p
    INNER JOIN document_application.edm_entitydomains ed ON p.cuid = ed.entitycuid -- Join with EDM_ENTITYDOMAINS
    INNER JOIN document_application.programmeoutcomes plo ON p.programmeid = plo.programmeid -- Join with PROGRAMMEOUTCOMES
    INNER JOIN document_application.programmesuboutcomes pso ON plo.programmeoutcomeid = pso.suboutcomeid -- Join with PROMGRAMMESUBOUTCOMES
    WHERE
    p.programmecode IN (
    SELECT
    p.programmecode
    FROM
    document_application.programmes p
    GROUP BY
    p.programmecode
    HAVING
    COUNT(*) > 1
    )
    AND   ed.ett_code = 'P'
    ) a
    WHERE
    a.dmn_cuid = d.cuid
    ) b
    ORDER BY
    course_udc,
    version

```

As you can see, I'll be using a variety of tables.
The b.programmeversion is the version column from which I need to show changes between.

This is an example of the output
output

答:
To show what changed between one version and the other, you can use the MINUS clause. Say you want to see what changed at the level of columns c1, c2, c3 between v1 and v2:

was in version v1, but not any more in v2

```<code>      select c1, c2, c3 from result_set where VERSION='v1'
minus select c1, c2, c3 from result_set where VERSION='v2'
</code>```

new in version v2, was not in v1

```<code>      select c1, c2, c3 from result_set where VERSION='v2'
minus select c1, c2, c3 from result_set where VERSION='v1'
</code>```

hope this helps

Body:
I have written a variety of SQL queries for a university's large oracle database. The output is a list of available degrees and associated information.

I now need to find a way to show what has changed between versions (based on a column called 'version'. New versions are created when data is changed)

How might I highlight differences based on the output of my selects in the queries?

This is the smallest query I can show as an example:

    SELECT
      -- DETAILS
    b.programmeid,
    b.programmecode AS course_udc,
    b.programmeversion AS version,
    b.externalversion AS external_version,
    b.programme AS full_title,
      -- OUTCOMES
    b.programmeoutcomeid AS outcome_number,
    b.outcomedesc AS outcome_description,
    b.programmeoutcometypeid AS graduate_attribute_link
    FROM
    (
    SELECT
              -- DETAILS
    a.programmeid,
    a.programmecode,
    a.programmeversion,
    a.externalversion,
    a.programme,
              -- OUTCOMES
    a.programmeoutcomeid,
    a.outcomedesc,
    a.programmeoutcometypeid
    FROM
    document_application.dmn_domains d,
    (
    SELECT
                      -- DETAILS
    ed.dmn_cuid,
    p.programmeid,
    p.programmecode,
    p.programmeversion,
    p.externalversion,
    p.programme,
                      -- OUTCOMES
    plo.programmeoutcomeid,
    ( dbms_lob.substr(pso.suboutcomedesc,4000,1) ) AS outcomedesc,
    plo.programmeoutcometypeid
    FROM
    document_application.programmes p
    INNER JOIN document_application.edm_entitydomains ed ON p.cuid = ed.entitycuid -- Join with EDM_ENTITYDOMAINS
    INNER JOIN document_application.programmeoutcomes plo ON p.programmeid = plo.programmeid -- Join with PROGRAMMEOUTCOMES
    INNER JOIN document_application.programmesuboutcomes pso ON plo.programmeoutcomeid = pso.suboutcomeid -- Join with PROMGRAMMESUBOUTCOMES
    WHERE
    p.programmecode IN (
    SELECT
    p.programmecode
    FROM
    document_application.programmes p
    GROUP BY
    p.programmecode
    HAVING
    COUNT(*) > 1
    )
    AND   ed.ett_code = 'P'
    ) a
    WHERE
    a.dmn_cuid = d.cuid
    ) b
    ORDER BY
    course_udc,
    version

As you can see, I'll be using a variety of tables.
The b.programmeversion is the version column from which I need to show changes between.

This is an example of the output
output

Body:
To show what changed between one version and the other, you can use the MINUS clause. Say you want to see what changed at the level of columns c1, c2, c3 between v1 and v2:

was in version v1, but not any more in v2

      select c1, c2, c3 from result_set where VERSION='v1'
minus select c1, c2, c3 from result_set where VERSION='v2'

new in version v2, was not in v1

      select c1, c2, c3 from result_set where VERSION='v2'
minus select c1, c2, c3 from result_set where VERSION='v1'

hope this helps


问:
How to trim string from right in PHP?
I have a string example

```<code>this-is-the-example/exa
</code>```

I want to trim /exa from the above line

```<code>$string1 = "this-is-the-example/exa";
$string2 = "/exa";
</code>```

I am using rtrim($string1, $sting2)

But the output is this-is-the-exampl

I want to this-is-the-example as output.

Both string are dynamic and may have multiple occurrences within the string. But I only want to remove the last part. Also its not compulsory that the string2 has / in it. this may be normal string too. like a, abc too..

答:
Hope this helps. :)

Simply try this code:

```<code><?php
$this_example = substr("this-is-the-example/exa", 0, -4);
echo "<br/>".$this_example; // returns "this-is-the-example"
?>
</code>```

Title: How to trim string from right in PHP?

Body:
I have a string example

this-is-the-example/exa

I want to trim /exa from the above line

$string1 = "this-is-the-example/exa";
$string2 = "/exa";

I am using rtrim($string1, $sting2)

But the output is this-is-the-exampl

I want to this-is-the-example as output.

Both string are dynamic and may have multiple occurrences within the string. But I only want to remove the last part. Also its not compulsory that the string2 has / in it. this may be normal string too. like a, abc too..

Body:
Hope this helps. :)

Simply try this code:

<?php
$this_example = substr("this-is-the-example/exa", 0, -4);
echo "<br/>".$this_example; // returns "this-is-the-example"
?>


问:
Executing a function in backgroud/seperate thread in angular 2 application
I am developing an application and I have below requirement. from my angular application I am making REST call to server which will trigger some job on the server and return status as "Job Started". After that I want to keep checking status of job every 10 seconds, for which server provides API that return status of job.

Now my requirement is I need to call this job status API every 10 seconds, but in background, that means user should able to perform other tasks on application.

How would I achieve this?

Any help with some example would be really helpful.

答:
You can resolve this by 2 way.

Simplest way - setInterval().

Since it's only check if job is done via http request it won't kill UI and user will be able to perform other actions.

```<code>setInterval(() => {
   this.http.post(...).subscribe(
      (res) => handleResponse(res);
   );
}, 10000);
</code>```

Web Worker

With web workers there is a lot of trouble, depends how your project is build etc. However it will do the trick with background thread but there is a question. Is it only to make a http request to check some data is necessary for web worker?. If yes, then look at this link it's well explained how it works. You will have to create XHR request since Angular and jQuery(I'm not 100% sure, but maybe there is ajax for web workers) won't work there. The biggest trouble would be loading source code of web worker. You can stringify source code of web worker (how to) or just build it as file and link it. It's depends how your project is gonna be build in production.

```<code>// source code for worker.
let code = function() {
    setInterval(function() {
        makeRequest()
        .then(function(res) {
            // process request. if you want to send message to main thread just use fn below
            // message can be almost everything, but it can not pass any methods.
            // self is simply worker. you don't have to declar self, it's already declared like window in main thread.
            self.postMessage(message)
        })
        .catch(function(err) {
            // process request failure.
        })
    }, 10000)
};

// stringify source code and make it blob as described in link

let worker = new Worker(code);

worker.addEventListener('message', function(workerReponse) {
    // workerReponse is simply `message` which was passed in self.postMessage(message).
})
</code>```

Source code to blob file

makeRequest method can look like this answer

Body:
You can resolve this by 2 way.

Simplest way - setInterval().

Since it's only check if job is done via http request it won't kill UI and user will be able to perform other actions.

setInterval(() => {
   this.http.post(...).subscribe(
      (res) => handleResponse(res);
   );
}, 10000);

Web Worker

With web workers there is a lot of trouble, depends how your project is build etc. However it will do the trick with background thread but there is a question. Is it only to make a http request to check some data is necessary for web worker?. If yes, then look at this link it's well explained how it works. You will have to create XHR request since Angular and jQuery(I'm not 100% sure, but maybe there is ajax for web workers) won't work there. The biggest trouble would be loading source code of web worker. You can stringify source code of web worker (how to) or just build it as file and link it. It's depends how your project is gonna be build in production.

// source code for worker.
let code = function() {
    setInterval(function() {
        makeRequest()
        .then(function(res) {
            // process request. if you want to send message to main thread just use fn below
            // message can be almost everything, but it can not pass any methods.
            // self is simply worker. you don't have to declar self, it's already declared like window in main thread.
            self.postMessage(message)
        })
        .catch(function(err) {
            // process request failure.
        })
    }, 10000)
};

// stringify source code and make it blob as described in link

let worker = new Worker(code);

worker.addEventListener('message', function(workerReponse) {
    // workerReponse is simply `message` which was passed in self.postMessage(message).
})

Source code to blob file

makeRequest method can look like this answer


问:
Duplicates in an array invalid input
I tried making a simple code for checking in an array for duplicate numbers/numbers that are smaller than the size of the array and numbers that are bigger than the size of the array.
(for example for an array by the size of 7, the number in the array should be between 1-7 with no duplicates, if not the system will print invalid error)
when I enter an array by the size of 1 and enter the number 2 for example I get the following error message:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
      at sumn.main(sumn.java:24)

Here is the code itself, any thoughts on how to fix this?

```<code>public class sumn {
    public static boolean Duplicates(int arr[]) {
        int a, b;
        boolean flag = true;
        for (a=0;a<arr.length-1;a++) {
            for (b=a+1;b<arr.length;b++) {
                if (arr[b]==arr[a]) {
                    return false;
                }
            }
        }
        return flag;
    }

    public static void main(String[] args) {
        int N = MyConsole.readInt("Enter the size of the array:");
        int arr[] = new int [N];
        int i, j;
        boolean flag = true;
        for (i=0;i<arr.length;i++) {
            arr[i]= MyConsole.readInt("Enter a number between 1 to ");
        }
        for (j=0;j<arr.length;j++) {
            if (Duplicates(arr)==false || N<arr[i] || arr[i]<=0)
                flag = false;
            if (flag == false)  {
                System.out.println("Invalid input");
            }
        }
    }

}
</code>```

答:
Problem is in this line

```<code>if (Duplicates(arr)==false || N<arr[i] || arr[i]<=0)
</code>```

make it

```<code>if (Duplicates(arr)==false || N<arr[j] || arr[j]<=0)
</code>```

replace i with j

Title: Duplicates in an array invalid input

Body:
I tried making a simple code for checking in an array for duplicate numbers/numbers that are smaller than the size of the array and numbers that are bigger than the size of the array.
(for example for an array by the size of 7, the number in the array should be between 1-7 with no duplicates, if not the system will print invalid error)
when I enter an array by the size of 1 and enter the number 2 for example I get the following error message:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
      at sumn.main(sumn.java:24)

Here is the code itself, any thoughts on how to fix this?

public class sumn {
    public static boolean Duplicates(int arr[]) {
        int a, b;
        boolean flag = true;
        for (a=0;a<arr.length-1;a++) {
            for (b=a+1;b<arr.length;b++) {
                if (arr[b]==arr[a]) {
                    return false;
                }
            }
        }
        return flag;
    }

    public static void main(String[] args) {
        int N = MyConsole.readInt("Enter the size of the array:");
        int arr[] = new int [N];
        int i, j;
        boolean flag = true;
        for (i=0;i<arr.length;i++) {
            arr[i]= MyConsole.readInt("Enter a number between 1 to ");
        }
        for (j=0;j<arr.length;j++) {
            if (Duplicates(arr)==false || N<arr[i] || arr[i]<=0)
                flag = false;
            if (flag == false)  {
                System.out.println("Invalid input");
            }
        }
    }

}

Body:
Problem is in this line

if (Duplicates(arr)==false || N<arr[i] || arr[i]<=0)

make it

if (Duplicates(arr)==false || N<arr[j] || arr[j]<=0)

replace i with j


问:
Redirection not working when inserting value?
view:

```<code><script>
        $(document).ready(function(){
            $("#verify").click(function(event){
                event.preventDefault()
                mobile = $("#mobile").val();
                uid = $("#uid").val();
                $.ajax({
                    type:"POST",
                    data:{"mobile":mobile, "uid":uid},
                    url:"<?php echo base_url(); ?>quiz/mobile_verification",
                    success:function(data){
                        alert(data);
                    }
                });
            });
        });
    </script>
    <li><a href="javascript:void(0)" data-toggle="modal" data-target="#mobiles">Result</a></li>
    <div id="mobiles" class="modal fade" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-body">
            <button type="button" class="close" data-dismiss="modal">×</button>
            <p style="text-align:center;color:red;">Your mobile number is not verify</p>
            <p style="text-align:center;color:red;">Please enter your mobile number for verification to see result.</p>
            <input type="hidden" name="uid" id="uid" value="<?php echo $uid; ?>">
            <center>Enter Your Valid Number :<input type="text" name="mobile" id="mobile" onkeyup="check(); return false;"/>
            <p id="message" style="margin-bottom: 0px;"></p>
            <input type="submit" name="verify" id="verify" class="btn btn-success" value="Verify" style="margin-top:10px;"/></center>
          </div>
        </div>
      </div>
    </div>
</code>```

controller:

```<code>public function mobile_verification()
{
    $data['logg'] = $this->session->userdata('logged_in');
    $mobile = $this->input->post('mobile');
    $uid = $this->input->post('uid');
    $password = rand(10,10000);

    $data = array(
                "uid"=>$uid,
                "mobile"=>$mobile,
                "password"=>$password,
                );
    $sql = $this->db->insert('mobile_verify',$data);
    if($sql = true)
    {
        redirect("quiz/verify");
    }
    else
    {
        echo "error";
    }
}
</code>```

In my view I have create a model over result for mobile verification. Now , when I put mobile number inside text box value will store into database but it not redirect. Inside redirect I am using bulk sms process through which I am sending message to client. So, How can I do this ?Please help me.

Thank You

答:
You are using ajax for mobile varification thats why you can not redirect it from there</p>

```<code>$.ajax({
        type:"POST",
        data:{"mobile":mobile, "uid":uid},
        url:"<?php echo base_url(); ?>quiz/mobile_verification",
        success:function(data){
                        window.location.href= '<?php echo base_url(); ?>quiz/verify';//redirect from here or use $.reload() function
                    }
     });
</code>```

Body:
view:

Result

            <button type="button" class="close" data-dismiss="modal">×</button>

Your mobile number is not verify

Please enter your mobile number for verification to see result.

            <input type="hidden" name="uid" id="uid" value="<?php echo $uid; ?>">
            Enter Your Valid Number :<input type="text" name="mobile" id="mobile" onkeyup="check(); return false;"/>

            <input type="submit" name="verify" id="verify" class="btn btn-success" value="Verify" style="margin-top:10px;"/>

controller:

public function mobile_verification()
{
    $data['logg'] = $this->session->userdata('logged_in');
    $mobile = $this->input->post('mobile');
    $uid = $this->input->post('uid');
    $password = rand(10,10000);

    $data = array(
                "uid"=>$uid,
                "mobile"=>$mobile,
                "password"=>$password,
                );
    $sql = $this->db->insert('mobile_verify',$data);
    if($sql = true)
    {
        redirect("quiz/verify");
    }
    else
    {
        echo "error";
    }
}

In my view I have create a model over result for mobile verification. Now , when I put mobile number inside text box value will store into database but it not redirect. Inside redirect I am using bulk sms process through which I am sending message to client. So, How can I do this ?Please help me.

Thank You

Body:
You are using ajax for mobile varification thats why you can not redirect it from there

$.ajax({
        type:"POST",
        data:{"mobile":mobile, "uid":uid},
        url:"<?php echo base_url(); ?>quiz/mobile_verification",
        success:function(data){
                        window.location.href= '<?php echo base_url(); ?>quiz/verify';//redirect from here or use $.reload() function
                    }
     });


问:
SQL - Can this relation have a primary key?
The relationship between bands and members, 'MemberOf', includes a member id (Mid), band id (Bid), 'StartYear', 'EndYear' and 'Instrument' played. Mid and Bid are both foreign keys to Member and Band relations respectively but I am struggling to identify the primary key in this situation for the 'MemberOf' relation.

Note: start year can be null if a member was in a band from the start and end year can also be null if a member is still in the band.

In this situation, start and end year cannot be used as PK's as they may contain null values, but the member id and band id is not enough information to be unique - e.g. the same member returns to the same band at a later date.

Does this mean no primary key exists? Thanks.

答:
Everything in human history happened at some point in time, so StartYear can not be NULL -- really.

If you introduce IsCurrent instead the EndYear then there are no NULLs at all. If you do choose to keep the EndYear, it is common practice to load it with some date in far future, like 3000-01-01. And finally, if you do keep and leave EndYear NULL -- it is not tragic, the only problem being that it may be hard to distinguish between missing data and the current membership.

Note: StartDate may be more appropriate than the StartYear.


问:
Setting up Protractor with Microsoft Edge
I use CucumberJs and Gulp to run my e2e tests; However, I need to run them against Microsoft Edge. When I do gulp protractor, it successfully opens up both Chrome and Firefox, since neither of them require any drivers like IEDriver.exe or EdgeDriver.exe.

Could anyone point me to an article or show the steps below if it's simple on how to set up Protractor with Microsoft Edge?

I'm trying to achieve parallelism by executing my tests on multiple browsers; this is what my config looks like:

```<code> exports.config = {
  framework: 'cucumber',
  shardTestFiles: true,
  maxInstances: 2,
  multiCapabilities: [
    {
       'browserName': 'MicrosoftEdge',
       'platform': 'windows',
      }
    },
    {
      'browserName': 'firefox',
      loggingPrefs: {
        driver: 'DEBUG',
        server: 'INFO',
        browser: 'ALL'
      }
    }],
    //more configs here
}
</code>```

I achieved the config right above, to run protractor e2e tests in parallel, using this article: http://blog.yodersolutions.com/run-protractor-tests-in-parallel/

Also one for IE driver would be just as helpful if you don't know how to set up Edge.

UPDATES:

From this link: https://msdn.microsoft.com/en-us/library/mt188085(v=vs.85).aspx; under the

Enabling WebDriver with Microsoft Edge:

Download a WebDriver language binding of your choice. Currently C# and
  Java Selenium language bindings are supported.

I'm not using Java or C#, I am only using Javascript (Protractor); does that mean that the language binding for Javascript currenlty does NOT work for Edge browser?

In other words, we currently cannot automate the Edge browser using Protractor (Javascript)?

Any help much appreciated and I'll update this post if I find anything pertaining to setting up Protractor with Edge, been looking around the web for hours now.

答:
After some struggle, I got Protractor to work on Microsoft Edge on my Windows 10 system.

Note: I'm using the Jasmine2 framework instead of Cucumber, but I believe the steps below should work for Cucumber as well. I'll try with Cucumber later and update here.

Here are the steps:

Get the Microsoft EdgeHTML version number in use in your system. In my case it is 15.15063. Take a note of the release number here. In this case it is 15063.

(Q.: How to get the Microsoft EdgeHTML version number?

A.: Edge browser > ... > Settings > About this app)

download the correct Release of MicrosoftWebDriver.exe from https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/

In my case I downloaded Release 15063. If you get the wrong release, then you are likely to run into an error like this error:

"This version of MicrosoftWebDriver.exe is not compatible with the installed version of Windows 10."

place the MicrosoftWebDriver.exe in the folder where the other drivers are like:

```<code>C:\Users\yourname\AppData\Roaming\npm\node_modules\protractor\node_modules\webdriver-manager\selenium\
</code>```

Adjust your conf.js file. Essentially, this is what conf.js should have:

```<code>seleniumAddress: 'http://localhost:4444/wd/hub',
capabilities: // or multiCapabilities:
{
    'browserName': "MicrosoftEdge"
}
</code>```

start the webdriver-manager like this:

```<code>C:\your\path>webdriver-manager start --edge C:\Users\yourname\AppData\Roaming\npm\node_modules\protractor\node_modules\webdriver-manager\selenium\MicrosoftWebDriver.exe
</code>```

You are all set to run your Protractor tests on the Edge browser.

Good Luck!

Body:
I use CucumberJs and Gulp to run my e2e tests; However, I need to run them against Microsoft Edge. When I do gulp protractor, it successfully opens up both Chrome and Firefox, since neither of them require any drivers like IEDriver.exe or EdgeDriver.exe.

Could anyone point me to an article or show the steps below if it's simple on how to set up Protractor with Microsoft Edge?

I'm trying to achieve parallelism by executing my tests on multiple browsers; this is what my config looks like:

 exports.config = {
  framework: 'cucumber',
  shardTestFiles: true,
  maxInstances: 2,
  multiCapabilities: [
    {
       'browserName': 'MicrosoftEdge',
       'platform': 'windows',
      }
    },
    {
      'browserName': 'firefox',
      loggingPrefs: {
        driver: 'DEBUG',
        server: 'INFO',
        browser: 'ALL'
      }
    }],
    //more configs here
}

I achieved the config right above, to run protractor e2e tests in parallel, using this article: http://blog.yodersolutions.com/run-protractor-tests-in-parallel/

Also one for IE driver would be just as helpful if you don't know how to set up Edge.

UPDATES:

From this link: https://msdn.microsoft.com/en-us/library/mt188085(v=vs.85).aspx; under the

Enabling WebDriver with Microsoft Edge:

Download a WebDriver language binding of your choice. Currently C# and
  Java Selenium language bindings are supported.

I'm not using Java or C#, I am only using Javascript (Protractor); does that mean that the language binding for Javascript currenlty does NOT work for Edge browser?

In other words, we currently cannot automate the Edge browser using Protractor (Javascript)?

Any help much appreciated and I'll update this post if I find anything pertaining to setting up Protractor with Edge, been looking around the web for hours now.

Body:
After some struggle, I got Protractor to work on Microsoft Edge on my Windows 10 system.

Note: I'm using the Jasmine2 framework instead of Cucumber, but I believe the steps below should work for Cucumber as well. I'll try with Cucumber later and update here.

Here are the steps:

Get the Microsoft EdgeHTML version number in use in your system. In my case it is 15.15063. Take a note of the release number here. In this case it is 15063.

(Q.: How to get the Microsoft EdgeHTML version number?

A.: Edge browser > ... > Settings > About this app)

download the correct Release of MicrosoftWebDriver.exe from https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/

In my case I downloaded Release 15063. If you get the wrong release, then you are likely to run into an error like this error:

"This version of MicrosoftWebDriver.exe is not compatible with the installed version of Windows 10."

place the MicrosoftWebDriver.exe in the folder where the other drivers are like:

C:\Users\yourname\AppData\Roaming\npm\node_modules\protractor\node_modules\webdriver-manager\selenium\

Adjust your conf.js file. Essentially, this is what conf.js should have:

seleniumAddress: 'http://localhost:4444/wd/hub',
capabilities: // or multiCapabilities:
{
    'browserName': "MicrosoftEdge"
}

start the webdriver-manager like this:

C:\your\path>webdriver-manager start --edge C:\Users\yourname\AppData\Roaming\npm\node_modules\protractor\node_modules\webdriver-manager\selenium\MicrosoftWebDriver.exe

You are all set to run your Protractor tests on the Edge browser.

Good Luck!


问:
dual for loops to find missing number from the entered sequence
Need help to complete this learner with for loops

Program:

```<code>import java.util.Scanner;

public class Main1 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int id[] = new int[n];
        for(int i=0; i<=n; i++) {
            id[i] = scan.nextInt();
        }
    }
}
</code>```

Input Format:

The first input consists of an integer n corresponding to the number of IDs.
Next n inputs corresponds to the Ids.

Output Format:

Output should display the missing Id.

答:
Try this, you can get the missing in between number according to the sequence you entered.

```<code>public static void main(String[] args){

        Scanner scan = new Scanner(System.in);
        int num = 0;
        int missingTrack = 0;
        System.out.println("Enter number of sequence:");
        int n = scan.nextInt();
        int id[] = new int[n];
        int missing[] = new int[10];

        for(int i=0; i<n; i++) {
            System.out.printf("Enter number %d:",i+1);
            id[i] = scan.nextInt();
        }

        for(int i=0; i<n; i++) {

            //Stop to check when the loop reach the last number in the sequence.
            if(i==n-1)
            {
                break;
            }
            //Assign the different between the next number to identify the missing number
            num = id[i+1]-id[i];

            //Loop based on the difference we get from "num"
            for(int y = 1;y<num;y++)
            {
                //Evaluate and store the missing number into the array
                missing[missingTrack] = id[i]+y;
                missingTrack = missingTrack+1;
            }

        }
        System.out.println("Missing input: ");
        for(int i=0; i < missingTrack; i++) {
            System.out.print(missing[i]+" ");
        }

}
</code>```

With the dual For loop to check and keep track of the missing number, hope you can get an idea on how to implement it to your scenario.

PS: Assume the sequence entered is in ascending order. Extra checking or sorting need to be done first if the input is entered not in sequential manner.

Body:
Need help to complete this learner with for loops

Program:

import java.util.Scanner;

public class Main1 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int id[] = new int[n];
        for(int i=0; i<=n; i++) {
            id[i] = scan.nextInt();
        }
    }
}

Input Format:

The first input consists of an integer n corresponding to the number of IDs.
Next n inputs corresponds to the Ids.

Output Format:

Output should display the missing Id.

Body:
Try this, you can get the missing in between number according to the sequence you entered.

public static void main(String[] args){

        Scanner scan = new Scanner(System.in);
        int num = 0;
        int missingTrack = 0;
        System.out.println("Enter number of sequence:");
        int n = scan.nextInt();
        int id[] = new int[n];
        int missing[] = new int[10];

        for(int i=0; i<n; i++) {
            System.out.printf("Enter number %d:",i+1);
            id[i] = scan.nextInt();
        }

        for(int i=0; i<n; i++) {

            //Stop to check when the loop reach the last number in the sequence.
            if(i==n-1)
            {
                break;
            }
            //Assign the different between the next number to identify the missing number
            num = id[i+1]-id[i];

            //Loop based on the difference we get from "num"
            for(int y = 1;y<num;y++)
            {
                //Evaluate and store the missing number into the array
                missing[missingTrack] = id[i]+y;
                missingTrack = missingTrack+1;
            }

        }
        System.out.println("Missing input: ");
        for(int i=0; i < missingTrack; i++) {
            System.out.print(missing[i]+" ");
        }

}

With the dual For loop to check and keep track of the missing number, hope you can get an idea on how to implement it to your scenario.

PS: Assume the sequence entered is in ascending order. Extra checking or sorting need to be done first if the input is entered not in sequential manner.