问:
Python array access notation
I have a very quick question about the notation on accessing an array in python.

Is this line:

```<code>trainPredictPlot[look_back:len(trainPredict) + look_back, :] = trainPredict
</code>```

I've seen arrays are being accessed like this x[a:b] but never like this x[a:b,:]

Can someone explain me with detail what this line of code is doing? What does it mean to put colon before the closing bracket? What about the comma?

答:
When you use x[a:b], it means that you are taking the elements from position "a" (x[a]) to position "b" (x[b]) of a one dimensional array.
For the second case x[a:b,:], it is a two dimensional "a" to position "b" of the first dimension of the array, and all the elements of the second dimension of the array, in other words, from  x[a][first element] to x[b][last element].</p>

Title: Python array access notation

Body:
I have a very quick question about the notation on accessing an array in python.

Is this line:

trainPredictPlot[look_back:len(trainPredict) + look_back, :] = trainPredict

I've seen arrays are being accessed like this x[a:b] but never like this x[a:b,:]

Can someone explain me with detail what this line of code is doing? What does it mean to put colon before the closing bracket? What about the comma?


来源: stackexchange

问:
Updating an HTML list using Js
So I have a js game like scrabble. Now when the user makes a new word, I would like the word to be added to a list that is displayed in a div on my page.
The issue is I quite don't understand, how I could keep my old word created and insert a new word with new formatting and everything in a list form.

I know there is a list tag --

```<code><ul>
     <li>apple</li>
     <li>ball</li>
</ul>
</code>```

but what I can't really figure out is how do I use java script to enter the word as a new list entry.

I have used js to display the word created by the following syntax

```<code>document.getElementById('currentword').innerHTML = word;
</code>```

where word is the variable that holds the current word created and currentword is the div id. but how do I use this kind of syntax for a list?
Please help!

Thanks

EDIT: I would also like the last entry to the list as the first item on my list. Seems like the list populates itself but the latest entry gets hidden and the list doesn't really auto scroll down as the items are added.
PS: Also incase someone knows how I could replace the tacky scroll bar option generated by CSS to a custom scroll bar. It would be great if you could point me in the correct direction!

答:
```<code><ul>
 <li>apple</li>
 <li>ball</li>
</ul>
</code>```

<p>then, </p>

```<code>var newListItem = $('<li></li>').html("myNewWord");

$("ul").append(newListItem);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Updating an HTML list using Js

Body:
So I have a js game like scrabble. Now when the user makes a new word, I would like the word to be added to a list that is displayed in a div on my page.
The issue is I quite don't understand, how I could keep my old word created and insert a new word with new formatting and everything in a list form.

I know there is a list tag --

apple

ball

but what I can't really figure out is how do I use java script to enter the word as a new list entry.

I have used js to display the word created by the following syntax

document.getElementById('currentword').innerHTML = word;

where word is the variable that holds the current word created and currentword is the div id. but how do I use this kind of syntax for a list?
Please help!

Thanks

EDIT: I would also like the last entry to the list as the first item on my list. Seems like the list populates itself but the latest entry gets hidden and the list doesn't really auto scroll down as the items are added.
PS: Also incase someone knows how I could replace the tacky scroll bar option generated by CSS to a custom scroll bar. It would be great if you could point me in the correct direction!

Body:
<ul>
 <li>apple</li>
 <li>ball</li>
</ul>

then,

var newListItem = $('<li></li>').html("myNewWord");

$("ul").append(newListItem);


问:
Using Makefile with Terraform and split project layout
I have a Terraform project layout that's similar to

```<code>stage
  └ Makefile
  └ terraform.tfvars
  └ vpc
  └ services
      └ frontend-app
      └ backend-app
          └ vars.tf
          └ outputs.tf
          └ main.tf
  └ data-storage
      └ mysql
      └ redis
</code>```

Where the contents of Makefile are similar to

```<code>.PHONY: all plan apply destroy

all: plan

plan:
    terraform plan -var-file terraform.tfvars -out terraform.tfplan

apply:
    terraform apply -var-file terraform.tfvars

destroy:
    terraform plan -destroy -var-file terraform.tfvars -out terraform.tfplan
    terraform apply terraform.tfplan
</code>```

As far as I understand it, Terraform will only run on templates in the current directory.  So I would need to cd stage/services/backend-app and run terraform apply there.

However I would like to be able to manage the whole stack from the Makefile.  I have not seen a good clean way to pass arguments to make.

My goal is to have targets such as

```<code>make s3 plan # verify syntax
make s3 apply # apply plan
</code>```

Unless there's a better way to run terraform from a parent directory?  Is there something similar to:

```<code>make all plan  # create stage plan
make all apply # apply stage plan
</code>```

答:
Another solution could be to create a tmp folder on each run and use terraform init ... and terraform get..., like this (the example also shows the remote state management using partial configuration):

```<code>readonly orig_path=$(pwd) && \
mkdir tmp && \
cd tmp && \
terraform init -backend=true -backend-config="$tf_backend_config" -backend-config="key=${account}/${envir}/${project}.json" $project_path && \
terraform get $project_path && \
terraform apply && \
cd $orig_path && \
rm -fR tmp
</code>```

Or maybe wrap the above into a shell script, and call it from make file under "apply" etc.

-- adding this section to address a comment/question from Sam Hammamy --

In general, with the way how the current versions of terraform processes projects, we do want to think ahead of time to how to structure our projects, and how to break them down into manageable still functional pieces. Which is why usually we break them into "foundational" projects like VPC, VPN, SecurityGroups, IAM-Policies, Bastions etc. vs. 'functional" like "db", "web-cluster" etc. We usually run/deploy/modify the "fundamental" pieces once or occasionally, while the "functional" pieces we might re-deploy several times a day.

Which means that with the fragmenting of our IaC code like that, we also will end up of fragmenting of our remote state accordingly, and the execution of our project deployment as well.

For a project structure, which reflects that "philosophy" we usually end up with a project structure similar to this (common modules are not shown):

```<code>├── projects
│   └── application-name
│       ├── dev
│       │   ├── bastion
│       │   ├── db
│       │   ├── vpc
│       │   └── web-cluster
│       ├── prod
│       │   ├── bastion
│       │   ├── db
│       │   ├── vpc
│       │   └── web-cluster
│       └── backend.config
└── run-tf.sh
</code>```

Where each project is a subfolder, and for each application_name/env/component = folder (i.e. dev/vpc) we added a placeholder backend configuration file: backend.tf:

```<code>terraform {
    backend "s3" {
    }
}
</code>```

Where the folder content for each component will contain files similar to:

```<code>│       ├── prod
│       │   ├── vpc
│       │   │   ├── backend.tf
│       │   │   ├── main.tf
│       │   │   ├── outputs.tf
│       │   │   └── variables.tf
</code>```

At "application_name/" or "application_name/env" level we added a backend.config file, with a content:

```<code>bucket     = "BUCKET_NAME"
region     = "region_name"
lock       = true
lock_table = "lock_table_name"
encrypt    = true
</code>```

Our wrapper shell script expects parameters application-name, environment, component, and the actual terraform cmd to run.

The content of run-tf.sh script (simplified):

```<code>#!/bin/bash

application=$1
envir=$2
component=$3
cmd=$4

tf_backend_config="root_path/$application/$envir/$component/backend.config"

terraform init -backend=true -backend-config="$tf_backend_config" -backend-config="key=tfstate/${application}/${envir}/${component}.json"

terraform get

terraform $cmd
</code>```

Here is how a typical run-tf.sh invocation looks like (to be executed from Makefile):

```<code>$ run-tf.sh application_name dev vpc plan

$ run-tf.sh application_name prod bastion apply
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a Terraform project layout that's similar to

stage
  └ Makefile
  └ terraform.tfvars
  └ vpc
  └ services
      └ frontend-app
      └ backend-app
          └ vars.tf
          └ outputs.tf
          └ main.tf
  └ data-storage
      └ mysql
      └ redis

Where the contents of Makefile are similar to

.PHONY: all plan apply destroy

all: plan

plan:
    terraform plan -var-file terraform.tfvars -out terraform.tfplan

apply:
    terraform apply -var-file terraform.tfvars

destroy:
    terraform plan -destroy -var-file terraform.tfvars -out terraform.tfplan
    terraform apply terraform.tfplan

As far as I understand it, Terraform will only run on templates in the current directory.  So I would need to cd stage/services/backend-app and run terraform apply there.

However I would like to be able to manage the whole stack from the Makefile.  I have not seen a good clean way to pass arguments to make.

My goal is to have targets such as

make s3 plan # verify syntax
make s3 apply # apply plan

Unless there's a better way to run terraform from a parent directory?  Is there something similar to:

make all plan  # create stage plan
make all apply # apply stage plan

Body:
Another solution could be to create a tmp folder on each run and use terraform init ... and terraform get..., like this (the example also shows the remote state management using partial configuration):

readonly orig_path=$(pwd) && \
mkdir tmp && \
cd tmp && \
terraform init -backend=true -backend-config="$tf_backend_config" -backend-config="key=${account}/${envir}/${project}.json" $project_path && \
terraform get $project_path && \
terraform apply && \
cd $orig_path && \
rm -fR tmp

Or maybe wrap the above into a shell script, and call it from make file under "apply" etc.

-- adding this section to address a comment/question from Sam Hammamy --

In general, with the way how the current versions of terraform processes projects, we do want to think ahead of time to how to structure our projects, and how to break them down into manageable still functional pieces. Which is why usually we break them into "foundational" projects like VPC, VPN, SecurityGroups, IAM-Policies, Bastions etc. vs. 'functional" like "db", "web-cluster" etc. We usually run/deploy/modify the "fundamental" pieces once or occasionally, while the "functional" pieces we might re-deploy several times a day.

Which means that with the fragmenting of our IaC code like that, we also will end up of fragmenting of our remote state accordingly, and the execution of our project deployment as well.

For a project structure, which reflects that "philosophy" we usually end up with a project structure similar to this (common modules are not shown):

├── projects
│   └── application-name
│       ├── dev
│       │   ├── bastion
│       │   ├── db
│       │   ├── vpc
│       │   └── web-cluster
│       ├── prod
│       │   ├── bastion
│       │   ├── db
│       │   ├── vpc
│       │   └── web-cluster
│       └── backend.config
└── run-tf.sh

Where each project is a subfolder, and for each application_name/env/component = folder (i.e. dev/vpc) we added a placeholder backend configuration file: backend.tf:

terraform {
    backend "s3" {
    }
}

Where the folder content for each component will contain files similar to:

│       ├── prod
│       │   ├── vpc
│       │   │   ├── backend.tf
│       │   │   ├── main.tf
│       │   │   ├── outputs.tf
│       │   │   └── variables.tf

At "application_name/" or "application_name/env" level we added a backend.config file, with a content:

bucket     = "BUCKET_NAME"
region     = "region_name"
lock       = true
lock_table = "lock_table_name"
encrypt    = true

Our wrapper shell script expects parameters application-name, environment, component, and the actual terraform cmd to run.

The content of run-tf.sh script (simplified):

#!/bin/bash

application=$1
envir=$2
component=$3
cmd=$4

tf_backend_config="root_path/$application/$envir/$component/backend.config"

terraform init -backend=true -backend-config="$tf_backend_config" -backend-config="key=tfstate/${application}/${envir}/${component}.json"

terraform get

terraform $cmd

Here is how a typical run-tf.sh invocation looks like (to be executed from Makefile):

$ run-tf.sh application_name dev vpc plan

$ run-tf.sh application_name prod bastion apply


问:
Searching a Data.Table in R
I'm having a bit of an issue searching a data table in R (I'm relatively new to the data.table package and R in general so my issue may be trivial, but I can't seem to find anything online).

Anyway, I have a column of time values and a column of millisecond values for their respective time in a data table, and I have a second set of information in a different data table (specifically another time value and another millisecond value) and I want to able to use this second set of information to find the closest time and millisecond values in the data table such that it is less than or equal to the time and millisecond values I have.

For example, let's say I have the following code:

```<code># DATA TABLE of time and millisecond values

Timevec <- c("10:00:05", "10:00:45", "10:01:03", "10:01:27", "10:01:52", "10:02:07", "10:02:13", "10:02:29", "10:02:33", "10:02:40", "10:02:44")
MilliSecond <- c(5, 321, 786, 79, 930, 680, 753, 214, 964, 832, 135)
tdf <- data.frame(Timevec, MilliSecond,(stringsAsFactors=FALSE))
setDT(tdf)

# Individual time and millisecond values

timesingle <- c("10:02:07")
millisecondsingle <- c(656)
sdf <- data.frame(timesingle ,millisecondsingle,(stringsAsFactors=FALSE))
setDT(sdf)
</code>```

In this case, since the time is 10:02:07 and milliseconds is 656, the closest time in the first data table (which is also less than or equal to the time I have) would be at 10:01:52 with its milliseconds at 930

I'm trying to find a way to perform this operation but I'm not sure how. I originally had the following code to try and do this for me:

```<code>max(which(tdf$Timevec<=sdf[1,time1] & tdf$MilliSecond <= sdf[1,milli1]))
</code>```

I originally hoped this would give me the index of the relevent time and millisecond columns I was after, but this failed since it only seemed to look at either one or the other condition. Does anyone know a better function or method to implement this? I don't mind if it's some sort of weird loop or anything, I'm just really not sure what to do for this so I'd appreciate any help I can get

答:
Kind of a strange way to store times, and a strange way to construct the data table. You should avoid labeling a column as a vector also

```<code>Timevec <- c("10:00:05", "10:00:45", "10:01:03", "10:01:27", "10:01:52", "10:02:07", "10:02:13", "10:02:29", "10:02:33", "10:02:40", "10:02:44")
MilliSecond <- c(5, 321, 786, 79, 930, 680, 753, 214, 964, 832, 135)
tdf <- data.table("time" = Timevec, "ms" = MilliSecond)
</code>```

let just use lubridate and add milliseconds

```<code> library(lubridate)
    > print(betterTime <- (hms(tdf$Timevec) + tdf$MilliSecond / 1000))
 [1] "10H 0M 5.005S"  "10H 0M 45.321S" "10H 1M 3.786S"  "10H 1M 27.079S" "10H 1M 52.93S"  "10H 2M 7.68S"   "10H 2M 13.753S" "10H 2M 29.214S" "10H 2M 33.964S" "10H 2M 40.832S" "10H 2M 44.135S"
</code>```

Thats just to see how it works. But you can actually do the conversion in-table!

```<code>otherrandomtime <- "10:02:13"
otherrandomms <- 751 # note that this demonstrates that milliseconds can break the tie.
print(otherConverted <- hms(otherrandomtime) + otherrandomms / 1000)
[1] "10H 2M 13.751S"

tail(tdf[(hms(time) + ms/1000) < hms(otherrandomtime) + otherrandomms / 1000],1)
       time  ms
1: 10:02:07 680
</code>```

Title: Searching a Data.Table in R

Body:
I'm having a bit of an issue searching a data table in R (I'm relatively new to the data.table package and R in general so my issue may be trivial, but I can't seem to find anything online).

Anyway, I have a column of time values and a column of millisecond values for their respective time in a data table, and I have a second set of information in a different data table (specifically another time value and another millisecond value) and I want to able to use this second set of information to find the closest time and millisecond values in the data table such that it is less than or equal to the time and millisecond values I have.

For example, let's say I have the following code:

# DATA TABLE of time and millisecond values

Timevec <- c("10:00:05", "10:00:45", "10:01:03", "10:01:27", "10:01:52", "10:02:07", "10:02:13", "10:02:29", "10:02:33", "10:02:40", "10:02:44")
MilliSecond <- c(5, 321, 786, 79, 930, 680, 753, 214, 964, 832, 135)
tdf <- data.frame(Timevec, MilliSecond,(stringsAsFactors=FALSE))
setDT(tdf)

# Individual time and millisecond values

timesingle <- c("10:02:07")
millisecondsingle <- c(656)
sdf <- data.frame(timesingle ,millisecondsingle,(stringsAsFactors=FALSE))
setDT(sdf)

In this case, since the time is 10:02:07 and milliseconds is 656, the closest time in the first data table (which is also less than or equal to the time I have) would be at 10:01:52 with its milliseconds at 930

I'm trying to find a way to perform this operation but I'm not sure how. I originally had the following code to try and do this for me:

max(which(tdf$Timevec<=sdf[1,time1] & tdf$MilliSecond <= sdf[1,milli1]))

I originally hoped this would give me the index of the relevent time and millisecond columns I was after, but this failed since it only seemed to look at either one or the other condition. Does anyone know a better function or method to implement this? I don't mind if it's some sort of weird loop or anything, I'm just really not sure what to do for this so I'd appreciate any help I can get

Body:
Kind of a strange way to store times, and a strange way to construct the data table. You should avoid labeling a column as a vector also

Timevec <- c("10:00:05", "10:00:45", "10:01:03", "10:01:27", "10:01:52", "10:02:07", "10:02:13", "10:02:29", "10:02:33", "10:02:40", "10:02:44")
MilliSecond <- c(5, 321, 786, 79, 930, 680, 753, 214, 964, 832, 135)
tdf <- data.table("time" = Timevec, "ms" = MilliSecond)

let just use lubridate and add milliseconds

 library(lubridate)
    > print(betterTime <- (hms(tdf$Timevec) + tdf$MilliSecond / 1000))
 [1] "10H 0M 5.005S"  "10H 0M 45.321S" "10H 1M 3.786S"  "10H 1M 27.079S" "10H 1M 52.93S"  "10H 2M 7.68S"   "10H 2M 13.753S" "10H 2M 29.214S" "10H 2M 33.964S" "10H 2M 40.832S" "10H 2M 44.135S"

Thats just to see how it works. But you can actually do the conversion in-table!

otherrandomtime <- "10:02:13"
otherrandomms <- 751 # note that this demonstrates that milliseconds can break the tie.
print(otherConverted <- hms(otherrandomtime) + otherrandomms / 1000)
[1] "10H 2M 13.751S"

tail(tdf[(hms(time) + ms/1000) < hms(otherrandomtime) + otherrandomms / 1000],1)
       time  ms
1: 10:02:07 680


问:
How to remove the two lowest numbers from a listbox in Visual Basic 2015?
Ok so I'm supposed to have the user input up to 13 grades, then have them averaged after removing the two lowest grades. I can't figure out what to use to remove the two lowest grades, whether it be from the listbox or during the calculation. Here's my code so far:</p>

```<code>    Dim strGrades As String
    Dim decGrades As Decimal = 0
    Dim decAverage As Decimal = 0
    Dim decTotal As Decimal = 0

    Dim strInputMessage As String = "Enter grade #"
    Dim strInputHeading As String = "Grade"
    Dim strNormalMessage As String = "Enter grade #"
    Dim strNonNumericError As String = "Error - Please enter a grade"
    Dim strNegativeError As String = "Error - Please enter a positive number"

    Dim strCancelClicked As String = ""
    Dim intMaxNumberOfEntries As Decimal = 13
    Dim intNumberOfEntries As Decimal = 1

    strGrades = InputBox(strInputMessage & intNumberOfEntries, strInputHeading, " ")

    Do Until intNumberOfEntries > intMaxNumberOfEntries Or strGrades = strCancelClicked
        If IsNumeric(strGrades) Then
            decGrades = Convert.ToDecimal(strGrades)
            If decGrades >= 0 Then
                lstGrades.Items.Add(decGrades)
                decTotal += decGrades
                intNumberOfEntries += 1
                strInputMessage = strNormalMessage
            Else
                strInputMessage = strNegativeError
            End If
        Else
            strInputMessage = strNonNumericError
        End If

        If intNumberOfEntries <= intMaxNumberOfEntries Then
            strGrades = InputBox(strInputMessage & intNumberOfEntries, strInputHeading, " ")
        End If

    Loop
    lstGrades.Sorted = True
</code>```

答:
Assuming that you have an enumerable list of numeric values, e.g. an array of Decimal, then the most succinct way to get the average of all but the two lowest values would be:

```<code>Dim average = myList.OrderBy(Function(n) n).Skip(2).Avg()
</code>```

I'm not sure how much of that would be acceptable for an assignment - if that's what this is - but the part that you're asking about specifically can still be done by calling Skip(2) if you start with a list that is sorted in ascending order.

Body:
Ok so I'm supposed to have the user input up to 13 grades, then have them averaged after removing the two lowest grades. I can't figure out what to use to remove the two lowest grades, whether it be from the listbox or during the calculation. Here's my code so far:

    Dim strGrades As String
    Dim decGrades As Decimal = 0
    Dim decAverage As Decimal = 0
    Dim decTotal As Decimal = 0

    Dim strInputMessage As String = "Enter grade #"
    Dim strInputHeading As String = "Grade"
    Dim strNormalMessage As String = "Enter grade #"
    Dim strNonNumericError As String = "Error - Please enter a grade"
    Dim strNegativeError As String = "Error - Please enter a positive number"

    Dim strCancelClicked As String = ""
    Dim intMaxNumberOfEntries As Decimal = 13
    Dim intNumberOfEntries As Decimal = 1

    strGrades = InputBox(strInputMessage & intNumberOfEntries, strInputHeading, " ")

    Do Until intNumberOfEntries > intMaxNumberOfEntries Or strGrades = strCancelClicked
        If IsNumeric(strGrades) Then
            decGrades = Convert.ToDecimal(strGrades)
            If decGrades >= 0 Then
                lstGrades.Items.Add(decGrades)
                decTotal += decGrades
                intNumberOfEntries += 1
                strInputMessage = strNormalMessage
            Else
                strInputMessage = strNegativeError
            End If
        Else
            strInputMessage = strNonNumericError
        End If

        If intNumberOfEntries <= intMaxNumberOfEntries Then
            strGrades = InputBox(strInputMessage & intNumberOfEntries, strInputHeading, " ")
        End If

    Loop
    lstGrades.Sorted = True

Body:
Assuming that you have an enumerable list of numeric values, e.g. an array of Decimal, then the most succinct way to get the average of all but the two lowest values would be:

Dim average = myList.OrderBy(Function(n) n).Skip(2).Avg()

I'm not sure how much of that would be acceptable for an assignment - if that's what this is - but the part that you're asking about specifically can still be done by calling Skip(2) if you start with a list that is sorted in ascending order.


问:
vue-awesome-swiper and callback functions
I'm using Vue.js 2 and vue-awesome-swiper.

I would like to do at least one of these two things on the callback of the swiper onSlideChangeEnd(swiper)

Be able to trigger the function onSwipe()

Access to this.private.privateData

I think the underlying problem is that I don't know how to access the this which represents not the swiper nor the object touchEventsTarget but my App.vue.

When I tries to do this.private.privateData I get Uncaught TypeError: Cannot read property 'orderFilter' of undefined which makes sense.

What should I do ? Thank you.

App.vue

```<code>  <template>
  <swiper :options="swiperOption" ref="mySwiper">
    <!-- slides -->
    <swiper-slide>I'm Slide 1</swiper-slide>
    <swiper-slide>I'm Slide 2</swiper-slide>
  </swiper>
</template>

<script>
  export default {
    name: 'carrousel',
    data() {
      return {
        private: {
            privateData : 'private'
        },
        swiperOption: {

          notNextTick: true,
          setWrapperSize :true,
          autoHeight: true,
          onSlideChangeEnd(swiper) {

               ***** DO SOMETHING HERE *****
          },
        }
      }
    },

   methods : {
     onSwipe() {console.log('Swiped')};
   },
    computed: {
      swiper() {
        return this.$refs.mySwiper.swiper
      }
    },
    mounted() {
      console.log('this is current swiper instance object',this.swiper)

    }
  }
</script>
</code>```

答:
Use a closure.</p>

```<code>  data(){
    const vue = this;
    return {
      private: {
        privateData : 'private'
      },
      swiperOption: {
        notNextTick: true,
        setWrapperSize :true,
        autoHeight: true,
        onSlideChangeEnd:function(){
          console.log(vue.private.privateData);
          vue.onSwipe()
        }
      }
    }
  },
</code>```

Body:
I'm using Vue.js 2 and vue-awesome-swiper.

I would like to do at least one of these two things on the callback of the swiper onSlideChangeEnd(swiper)

Be able to trigger the function onSwipe()

Access to this.private.privateData

I think the underlying problem is that I don't know how to access the this which represents not the swiper nor the object touchEventsTarget but my App.vue.

When I tries to do this.private.privateData I get Uncaught TypeError: Cannot read property 'orderFilter' of undefined which makes sense.

What should I do ? Thank you.

App.vue

  <template>
  <swiper :options="swiperOption" ref="mySwiper">

    <swiper-slide>I'm Slide 1</swiper-slide>
    <swiper-slide>I'm Slide 2</swiper-slide>
  </swiper>
</template>

Body:
Use a closure.

  data(){
    const vue = this;
    return {
      private: {
        privateData : 'private'
      },
      swiperOption: {
        notNextTick: true,
        setWrapperSize :true,
        autoHeight: true,
        onSlideChangeEnd:function(){
          console.log(vue.private.privateData);
          vue.onSwipe()
        }
      }
    }
  },


问:
Confusion in an Python program related to topic of Namespace and Scope
I just stepped in python recently and now I reached to the topic of Namespace and Scope. With the intention of further understanding of this subject,  I found this which contains a program resulting in my confusion.

And, here's the program:

```<code>1  def outer_function():
2      a = 20
3      def inner_function():
4          a = 30
5          print('a =',a)
6
7      inner_function()
8      print('a =',a)
10
11 a = 10
12 outer_function()
13 print('a =',a)
</code>```

And here's the result which you must be quite sure but I am not

```<code>a = 30
a = 20
a = 10
</code>```

but the output in my mind should be

```<code>a = 30
a = 30
a = 20
a = 10
</code>```

Even I modified the original code to be like this in order to make it clearer:

```<code>def outer_function():
    a = 20
    def inner_function():
        a = 30
        print('a1 =',a)

    inner_function()
    print('a2 =',a)

a = 10
outer_function()
print('a3 =',a)
</code>```

But it still like this:

```<code>a1 = 30
a2 = 20
a3 = 10
</code>```

So, the reason why I thought that there's supposed to a double a1 = 30 is because I believed that line5 in the code was executed twice as,

firstly, it runs when the outer_function() is called at line12 which goes from line1 to line8 and line5 is called with the a1 = 30 output

secondly, the line7 is called which triggered the line5 again with the same output as above,

finally the function outer_function() ends when line8 is done, that's when a2 = 20 show up.

Then go back to "main thread" (I just call it as this not actually mean it, or it is?) line13 and print a3 = 10

So, as what I got is not what I thought, what's wrong with my understanding of this program?

Thanks for spending time on reading my problem, it will be of great help to me if you can give me a hand on this :) Thanks in advance

Edit:

I just found out where my confusion was! Great appreciation to those who give me a hand.
Turns out the main problem of my confusion is my unstable foundation of the programming knowledge. So, I incorrectly thought the line5 will run when the inner_function() was declared. Hahaha, how could this happen?? This so basic mistakes just happened -- the declaration of the function will never run until it is called in the program! That's why there's only one a = 30!

Anyway, I will keep in mind that do not make the same mistakes again. I'm appreciated to those who give a hand on this minor basic syntactic mistake!

Cheers!

答:
The inner_function was declared on line 3, but it is only ever called once, and that's on line 7.

If you took out line 7, a1 would never print.

Body:
I just stepped in python recently and now I reached to the topic of Namespace and Scope. With the intention of further understanding of this subject,  I found this which contains a program resulting in my confusion.

And, here's the program:

1  def outer_function():
2      a = 20
3      def inner_function():
4          a = 30
5          print('a =',a)
6
7      inner_function()
8      print('a =',a)
10
11 a = 10
12 outer_function()
13 print('a =',a)

And here's the result which you must be quite sure but I am not

a = 30
a = 20
a = 10

but the output in my mind should be

a = 30
a = 30
a = 20
a = 10

Even I modified the original code to be like this in order to make it clearer:

def outer_function():
    a = 20
    def inner_function():
        a = 30
        print('a1 =',a)

    inner_function()
    print('a2 =',a)

a = 10
outer_function()
print('a3 =',a)

But it still like this:

a1 = 30
a2 = 20
a3 = 10

So, the reason why I thought that there's supposed to a double a1 = 30 is because I believed that line5 in the code was executed twice as,

firstly, it runs when the outer_function() is called at line12 which goes from line1 to line8 and line5 is called with the a1 = 30 output

secondly, the line7 is called which triggered the line5 again with the same output as above,

finally the function outer_function() ends when line8 is done, that's when a2 = 20 show up.

Then go back to "main thread" (I just call it as this not actually mean it, or it is?) line13 and print a3 = 10

So, as what I got is not what I thought, what's wrong with my understanding of this program?

Thanks for spending time on reading my problem, it will be of great help to me if you can give me a hand on this :) Thanks in advance

Edit:

I just found out where my confusion was! Great appreciation to those who give me a hand.
Turns out the main problem of my confusion is my unstable foundation of the programming knowledge. So, I incorrectly thought the line5 will run when the inner_function() was declared. Hahaha, how could this happen?? This so basic mistakes just happened -- the declaration of the function will never run until it is called in the program! That's why there's only one a = 30!

Anyway, I will keep in mind that do not make the same mistakes again. I'm appreciated to those who give a hand on this minor basic syntactic mistake!

Cheers!


问:
How to run node.js app forever when console is closed?
I connect to my remote server via ssh. Then I start my node.js app with Forever. Everything works fine until I close my console window. How to run node.js app FOREVER on my remote server even when I close my connection via ssh? I just want to start an app and shut down my copmputer. My app should be working in the background on my remote server.</p>

答:
If you're running node.js in a production environment, you should consider using PM2, forever.js, or Nodemon. </p>

<p>There is no shortage of articles online comparing the different packages. </p>

Body:
If you're running node.js in a production environment, you should consider using PM2, forever.js, or Nodemon.

There is no shortage of articles online comparing the different packages.


问:
How do curly braces affect MySQL syntax?
I accidentally put a PHP statement into MySQL:

```<code>select * from info where id={${intval(17a)}}
</code>```

MySQL gave me the error message:

ERROR 1054 (42S22): Unknown column '17a' in 'where clause'

Why does MySQL not issue a syntax error, empty result, or show {${intval(17a)}} in the error message? The column in the id value is {${intval(17a)}} but mysql says column '17a'? Are the curly braces and dollar sign special characters in MySQL?

Demo

答:
That $ sign is PHP Specific Syntax.

I think you are just looking for this

```<code>select * from info where id='17a';
</code>```

Body:
I accidentally put a PHP statement into MySQL:

select * from info where id={${intval(17a)}}

MySQL gave me the error message:

ERROR 1054 (42S22): Unknown column '17a' in 'where clause'

Why does MySQL not issue a syntax error, empty result, or show {${intval(17a)}} in the error message? The column in the id value is {${intval(17a)}} but mysql says column '17a'? Are the curly braces and dollar sign special characters in MySQL?

Demo

Body:
That $ sign is PHP Specific Syntax.

I think you are just looking for this

select * from info where id='17a';


问:
URL to fill input fields
There is a website that I use regularly that has quite a few log in fields. I'm trying to formulate a link to pre-populate most of them.
The fields in question are formatted like this:

```<code><input id="frm:User" type="text" name="frm:User" autocomplete="off" style="width:80%" />
</code>```

I've tried using "http://website?frm:User=User&frmGroup=Group" to no avail. Any suggestions?

Thanks!

答:
If you are using Google Chrome, this can be done pretty easily with Autofill extension. All you need to do is:

Install Autofill extension.

Open the website page that you want to auto fill input fields. Activate the Autofill extension.

Fill the input fields manually and then save it to a profile.

Click "Generate Autofill Rules". Next time, when you visit this page, the input fields will be filled automatically.

Title: URL to fill input fields

Body:
There is a website that I use regularly that has quite a few log in fields. I'm trying to formulate a link to pre-populate most of them.
The fields in question are formatted like this:

<input id="frm:User" type="text" name="frm:User" autocomplete="off" style="width:80%" />

I've tried using "http://website?frm:User=User&frmGroup=Group" to no avail. Any suggestions?

Thanks!


问:
use data from multiple tables in SQL
need some quick help.. i think i'm supposed to use INNER JOIN, but i'm not really sure.

```<code>List  the employee ID and the full name of the employee who sold or packaged the
transactions placed by customer Benjamin Jones. Each employee should only show up
once in your results
</code>```

employeeID, first and last are in the EMPLOYEES table

benjamin jones' memberID is 101 and in the MEMBERS table

memberID and transactionID and soldorpackagedby are in the TRANSACTIONS table

this is what I have to start it off but don't know how to finish it.

```<code> SELECT EmployeeID, First, Last
 FROM Employees
 WHERE MemberID = '101'
</code>```

thanks!

答:
Try -

```<code>SELECT employees.EmployeeID,
       employees.First,
       employees.Last
FROM employees
JOIN transactions ON employees.EmployeeID = transactions.SoldOrPackagedBy
WHERE transactions.memberID = 101
GROUP BY employees.EmployeeID;
</code>```

Because you are using data from more than one table in this SQL statement you will need to specify which table a repeated field name such as EmployeeID will come from, hence employees.EmployeeID.  employee. is probably not called for in front of First and Last but I tend to put it in anyway since the habit can help avoid bugs occurring when I am writing more complex statements.

JOIN without INNER, LEFT, RIGHT or FULL in front is the same as INNER JOIN (see https://www.w3schools.com/sql/sql_join.asp).

Since the Member's ID is already known and used in the Transactions table, and we are not being asked to refer to any other detail about the member here, then there is no need to link in the Members table.

Without GROUP BY the SELECT statement will return a record for every time an Employee packaged a Transaction for a Member.  These details would be the same every time.  Using GROUP BY would reduce this to just one instance of those details.

If you have any questions or comments, then please feel free to post a Comment accordingly.

Title: use data from multiple tables in SQL

Body:
need some quick help.. i think i'm supposed to use INNER JOIN, but i'm not really sure.

List  the employee ID and the full name of the employee who sold or packaged the
transactions placed by customer Benjamin Jones. Each employee should only show up
once in your results

employeeID, first and last are in the EMPLOYEES table

benjamin jones' memberID is 101 and in the MEMBERS table

memberID and transactionID and soldorpackagedby are in the TRANSACTIONS table

this is what I have to start it off but don't know how to finish it.

 SELECT EmployeeID, First, Last
 FROM Employees
 WHERE MemberID = '101'

thanks!

Body:
Try -

SELECT employees.EmployeeID,
       employees.First,
       employees.Last
FROM employees
JOIN transactions ON employees.EmployeeID = transactions.SoldOrPackagedBy
WHERE transactions.memberID = 101
GROUP BY employees.EmployeeID;

Because you are using data from more than one table in this SQL statement you will need to specify which table a repeated field name such as EmployeeID will come from, hence employees.EmployeeID.  employee. is probably not called for in front of First and Last but I tend to put it in anyway since the habit can help avoid bugs occurring when I am writing more complex statements.

JOIN without INNER, LEFT, RIGHT or FULL in front is the same as INNER JOIN (see https://www.w3schools.com/sql/sql_join.asp).

Since the Member's ID is already known and used in the Transactions table, and we are not being asked to refer to any other detail about the member here, then there is no need to link in the Members table.

Without GROUP BY the SELECT statement will return a record for every time an Employee packaged a Transaction for a Member.  These details would be the same every time.  Using GROUP BY would reduce this to just one instance of those details.

If you have any questions or comments, then please feel free to post a Comment accordingly.


问:
PHP - How to get the value of json api using Php?
I have a question regarding on json.. I tried to get an api from other site and downloaded it as json file..I've already decoded this file using this code below..

```<code>$str = file_get_contents('../trelloApi.json');
$json = json_decode($str, true);
echo '```' . print_r($json, true) . '```';
</code>```

From this image attached, how do I get or print the value of the [list] => Array, [board] => Array and [card] => Array?

Please help me :(

答:
You get access for only 173 locaions array:

```<code>$list = $json[173]['data']['list'];
$board = $json[173]['data']['board'];
$card = $json[173]['data']['card'];

print_r($list);
print_r($board);
print_r($card);
</code>```

you can get all of the array like

```<code>foreach ($json as $key => $value) {
    $list[] = $value['data']['list'];
    $board[] = $value['data']['board'];
    $card[] = $value['data']['card'];
}

print_r($list);
print_r($board);
print_r($card);
</code>```

Body:
I have a question regarding on json.. I tried to get an api from other site and downloaded it as json file..I've already decoded this file using this code below..

$str = file_get_contents('../trelloApi.json');
$json = json_decode($str, true);
echo '
' . print_r($json, true) . '
';

From this image attached, how do I get or print the value of the [list] => Array, [board] => Array and [card] => Array?

Please help me :(

Body:
You get access for only 173 locaions array:

$list = $json[173]['data']['list'];
$board = $json[173]['data']['board'];
$card = $json[173]['data']['card'];

print_r($list);
print_r($board);
print_r($card);

you can get all of the array like

foreach ($json as $key => $value) {
    $list[] = $value['data']['list'];
    $board[] = $value['data']['board'];
    $card[] = $value['data']['card'];
}

print_r($list);
print_r($board);
print_r($card);


问:
Execute multiple functions at once
I need to make a simple calculator for a school project using only functions.

One of the functions is:

```<code>double addition(double a, double b)
{
    return a + b;
}
</code>```

And I call it and show the results doing this:

```<code>printf( "Addition: %.2lf\n", addition(x,y));
</code>```

I have other functions for substraction, multiplication, and division.

I need to perform each one of those separately, and then, perform them all at once.

How can I integrate all of these functions in just one function, like this:

```<code>printf( "All of the results %.2lf\n", allfunctions(x,y));
</code>```

Is it possible?

I'm trying to avoid doing something like this:

```<code>printf( "Addition: %.2lf\n", addition(x,y));
printf( "Substraction: %.2lf\n", substraction(x,y));
</code>```

Thanks.

答:
You can do that by create an allfunctions(x,y) and inside the allfunctions(x,y) you call another functions that you want to execute. Example:

Function 1: add(double x, double y) { printf( "Addition: %.2lf\n", x + y ); }

Function 2: divide(double x, double y) { printf( "Division: %.2lf\n", x / y ); }

All functions: allfunctions(double x, double y) { add(x,y); divide(x,y); }

Then all you need is calling allfunctions(x,y).

Title: Execute multiple functions at once

Body:
I need to make a simple calculator for a school project using only functions.

One of the functions is:

double addition(double a, double b)
{
    return a + b;
}

And I call it and show the results doing this:

printf( "Addition: %.2lf\n", addition(x,y));

I have other functions for substraction, multiplication, and division.

I need to perform each one of those separately, and then, perform them all at once.

How can I integrate all of these functions in just one function, like this:

printf( "All of the results %.2lf\n", allfunctions(x,y));

Is it possible?

I'm trying to avoid doing something like this:

printf( "Addition: %.2lf\n", addition(x,y));
printf( "Substraction: %.2lf\n", substraction(x,y));

Thanks.


问:
Getting route params on initial page load
I'm trying to get route parameters for the first time, and I can't seem to figure out how to use ActivatedRoute properly.

Based on the API and docs, I'm trying this to get my route params on page load.

```<code>ngOnInit() {
    const orgSlug: Observable<string> = this.route.params.map(params => {console.log(params); return params.org});
}
</code>```

On page load, nothing gets logged. My assumption would have been on the page load, I would get the initial state of the params object. I tried it both in the ngOnInit and the constructor with no results in either. I know I can check snapshot, but then I'd have to have duplicate code for the initial state and any changed state, which feels wrong.

Am I misunderstanding how observables or the ActivatedRoute works?

答:
You should use in the constructor and you should subscribe to the params, which  will be executed before the page is rendered and your params will be available , since these are async calls putting it in the onInit is not advisable</p>

```<code>constructor(private route:ActivatedRoute) {
    this.route.params.subscribe(params => {

         console.log(params);

    }).map(params => {
           console.log(params);
           return params.org}
    );
});
</code>```

Body:
I'm trying to get route parameters for the first time, and I can't seem to figure out how to use ActivatedRoute properly.

Based on the API and docs, I'm trying this to get my route params on page load.

ngOnInit() {
    const orgSlug: Observable<string> = this.route.params.map(params => {console.log(params); return params.org});
}

On page load, nothing gets logged. My assumption would have been on the page load, I would get the initial state of the params object. I tried it both in the ngOnInit and the constructor with no results in either. I know I can check snapshot, but then I'd have to have duplicate code for the initial state and any changed state, which feels wrong.

Am I misunderstanding how observables or the ActivatedRoute works?

Body:
You should use in the constructor and you should subscribe to the params, which  will be executed before the page is rendered and your params will be available , since these are async calls putting it in the onInit is not advisable

constructor(private route:ActivatedRoute) {
    this.route.params.subscribe(params => {

         console.log(params);

    }).map(params => {
           console.log(params);
           return params.org}
    );
});


问:
GitBash cmd line branch delete
what does it mean that I see (feature/StoreTextVariable_134) (I assume branch I created earlier in and switched to in VS, and I deleted the local code earlier)?

how can I get rid of it?

I'm a GitBash newbie.

答:
Thanks @Tai I had to use -f with my checkout so that I could discard pending changes I didn't need

git checkout -f branchName

then to delete it I used

git branch -d -f branchName

now I am back on my default branch

Title: GitBash cmd line branch delete


问:
Datalist is not showing complete name after space in dropdown
Datalist is not printing complete name after space. It is just giving first word of name i.e ignoring complete name after space. The names are fetched from database. Suppose the bank name is "XYZ Global Bank" then it is showing only "XYZ" in drop down and rest name is not shown.
Please help me here.</p>

```<code>$query = "SELECT name FROM issuer";
$result = $conn->query($query);
if(!$result) die($conn->error);
$rows=$result->num_rows;
echo "<datalist id='bankNames'>";
for($i=0; $i<$rows; $i++)
{
$result->data_seek($i);
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "<option value='".$row['name']."'>";
 }
 echo "</datalist>";
</code>```

答:
```<code>$name = htmlentities($row['name']);
echo "<option value='$name'>";
</code>```

Body:
Datalist is not printing complete name after space. It is just giving first word of name i.e ignoring complete name after space. The names are fetched from database. Suppose the bank name is "XYZ Global Bank" then it is showing only "XYZ" in drop down and rest name is not shown.
Please help me here.

$query = "SELECT name FROM issuer";
$result = $conn->query($query);
if(!$result) die($conn->error);
$rows=$result->num_rows;
echo "<datalist id='bankNames'>";
for($i=0; $i<$rows; $i++)
{
$result->data_seek($i);
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "<option value='".$row['name']."'>";
 }
 echo "</datalist>";


答:
Looks like that the api return a array of arrays, then use foreach to iterate through the json_decode.

```<code>foreach ($json as $ticket) {
    // if your $ticket['data'] is a StdClass, force to be array
    $ticket['data'] = (array)$ticket['data'];

    // now you can access your indexes
    $list = $ticket['data']['list'];
    $board = $ticket['data']['board'];
    $card = $ticket['data']['card'];
}
</code>```

If you don't like your $ticket['data'] as array, use as object instead $ticket['data']->list, $ticket['data']->board...

Title: PHP - How to get the value of json api using Php?

Body:
Looks like that the api return a array of arrays, then use foreach to iterate through the json_decode.

foreach ($json as $ticket) {
    // if your $ticket['data'] is a StdClass, force to be array
    $ticket['data'] = (array)$ticket['data'];

    // now you can access your indexes
    $list = $ticket['data']['list'];
    $board = $ticket['data']['board'];
    $card = $ticket['data']['card'];
}

If you don't like your $ticket['data'] as array, use as object instead $ticket['data']->list, $ticket['data']->board...


问:
Filestream and receive the data from the read
Reading an JSON document "source.json" thru filestream but how do you get the data from the json file?  After that I am trying to append the newly edited json data back on the same file. </p>

```<code>Dim pathSource As String = "Server.MapPath('~/source.json')"
Try
    Using fs As FileStream = New FileStream(pathSource, _
        FileMode.Open, FileAccess.Read)
            Dim bytes() As Byte = New Byte((fsSource.Length) - 1) {}
            Dim numBytesToRead As Integer = CType(fsSource.Length,Integer)
            Dim numBytesRead As Integer = 0

            While (numBytesToRead > 0)
                Dim n As Integer = fsSource.Read(bytes, numBytesRead, _
                    numBytesToRead)
                If (n = 0) Then
                    Exit While
                End If
                numBytesRead = (numBytesRead + n)
                numBytesToRead = (numBytesToRead - n)

            End While
        numBytesToRead = bytes.Length
        Dim xmlBuilder = New StringBuilder()
        fs.Seek(0, SeekOrigin.Begin)
        Dim ms As New MemoryStream()
        fs.CopyTo(ms)
        xmlBuilder.Append(Encoding.UTF8.GetString(ms.ToArray()))
        ms.Flush()
        ms.Close()
        '???How to access the data from the file "source.json" you just read in???

       'Edit the file "source.json" data

        ?? How to put it into "bytesout" the edited data???

        Using fsAppend As FileStream = New FileStream(pathSource, _
            FileMode.Append, FileAccess.Write)
            fsAppend.Write(bytesout, 0, numBytesToRead)
        End Using
    End Using
Catch ioEx As FileNotFoundException
    Console.WriteLine(ioEx.Message)
End Try
</code>```

答: I've been down that path. Try to figure out what you did wrong with newtonsoft. The serializer and deserializer methods are fairly easy to use. You only have to create an object per the Json format and deserializer will populate the object automatically. You just have to have the variables in the class be declared as public property nameofjsonobject as  </p>

Body:
Reading an JSON document "source.json" thru filestream but how do you get the data from the json file?  After that I am trying to append the newly edited json data back on the same file.

Dim pathSource As String = "Server.MapPath('~/source.json')"
Try
    Using fs As FileStream = New FileStream(pathSource, _
        FileMode.Open, FileAccess.Read)
            Dim bytes() As Byte = New Byte((fsSource.Length) - 1) {}
            Dim numBytesToRead As Integer = CType(fsSource.Length,Integer)
            Dim numBytesRead As Integer = 0

            While (numBytesToRead > 0)
                Dim n As Integer = fsSource.Read(bytes, numBytesRead, _
                    numBytesToRead)
                If (n = 0) Then
                    Exit While
                End If
                numBytesRead = (numBytesRead + n)
                numBytesToRead = (numBytesToRead - n)

            End While
        numBytesToRead = bytes.Length
        Dim xmlBuilder = New StringBuilder()
        fs.Seek(0, SeekOrigin.Begin)
        Dim ms As New MemoryStream()
        fs.CopyTo(ms)
        xmlBuilder.Append(Encoding.UTF8.GetString(ms.ToArray()))
        ms.Flush()
        ms.Close()
        '???How to access the data from the file "source.json" you just read in???

       'Edit the file "source.json" data

        ?? How to put it into "bytesout" the edited data???

        Using fsAppend As FileStream = New FileStream(pathSource, _
            FileMode.Append, FileAccess.Write)
            fsAppend.Write(bytesout, 0, numBytesToRead)
        End Using
    End Using
Catch ioEx As FileNotFoundException
    Console.WriteLine(ioEx.Message)
End Try


问:
redirect output from stdout to a string?
in C
i want to redirect the output of a process from stdout to write to a "shared memory segment" which can be thought of as a char array or a string with a pointer

i know that there is dup2 but it takes file discriptors as argument not a pointer to an array.  is there any way to redirect it to a string?

答:
In order to do a simple redirection of stdout to a memory string, just do this:</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PATH_MAX 1000

int main()
{
    FILE *fp;
    int status;
    char path[PATH_MAX];

    fp = popen("ls ", "r");

    if (fp == NULL)  return 0;

    while (fgets(path, PATH_MAX, fp) != NULL)
        printf("\nTest=> %s", path);

    status = pclose(fp);
}
</code>```

Body:
In order to do a simple redirection of stdout to a memory string, just do this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PATH_MAX 1000

int main()
{
    FILE *fp;
    int status;
    char path[PATH_MAX];

    fp = popen("ls ", "r");

    if (fp == NULL)  return 0;

    while (fgets(path, PATH_MAX, fp) != NULL)
        printf("\nTest=> %s", path);

    status = pclose(fp);
}


问:
TimePicker reset bug. Any workaround?
I found some problem for TimePicker widget. After user change time in widget setHour and setMinute methods not works.

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

    private Button mButton;
    private TimePicker mTimePicker;

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mButton = (Button) findViewById(R.id.reset);
        mTimePicker = (TimePicker) findViewById(R.id.timePicker);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar cal = Calendar.getInstance();
                int hour = cal.get(Calendar.HOUR_OF_DAY);
                int minute = cal.get(Calendar.MINUTE);

                mTimePicker.setHour(hour);
                mTimePicker.setMinute(minute);

                Log.v(TAG, "onClick: " + hour + "=>" + mTimePicker.getHour());
                Log.v(TAG, "onClick: " + minute + "=>" + mTimePicker.getMinute());
            }
        });
    }
}
</code>```

Step for reproduce:

Run app (my time: 13:21)

Change time on the Widget (21:21)

Tap on the Reset button

Result:time not reset to 13:21

Log:

03-30 13:18:05.765 30923-30923/ru.neverdark.timepickerproblem
  V/MainActivity: onClick: 13=>21 03-30 13:18:05.765
  30923-30923/ru.neverdark.timepickerproblem V/MainActivity: onClick:
  18=>18

Any workaround for this problem?

Same bug I found in Issue Tracker: https://code.google.com/p/android/issues/detail?id=208180 but in SDK25 not fixed...

Demo project on the github: https://github.com/yankovskiy/TimePickerProblem

答:
```<code> protected Dialog onCreateDialog(int id) {
    checkMark = (Button) findViewById(R.id.button13)                            ;
    checkMark.setVisibility(View.VISIBLE)                                       ;
    switch (id) {
        case TIME_DIALOG_ID:
        // set time picker as current time
        return new TimePickerDialog(this,
            timePickerListener, hour, minute,false);

        case TIME_DIALOG_ID_ON:
        // set time picker as current time
        return new TimePickerDialog(this,
            timePickerListenerOn, hour, minute,false);
    }
    return null;
    }
</code>```

How about this?

```<code>picker.setCurrentHour(date.getHours())
picker.setCurrentMinute(date.getMinutes())
</code>```

Title: TimePicker reset bug. Any workaround?

Body:
I found some problem for TimePicker widget. After user change time in widget setHour and setMinute methods not works.

public class MainActivity extends AppCompatActivity {

    private Button mButton;
    private TimePicker mTimePicker;

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mButton = (Button) findViewById(R.id.reset);
        mTimePicker = (TimePicker) findViewById(R.id.timePicker);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar cal = Calendar.getInstance();
                int hour = cal.get(Calendar.HOUR_OF_DAY);
                int minute = cal.get(Calendar.MINUTE);

                mTimePicker.setHour(hour);
                mTimePicker.setMinute(minute);

                Log.v(TAG, "onClick: " + hour + "=>" + mTimePicker.getHour());
                Log.v(TAG, "onClick: " + minute + "=>" + mTimePicker.getMinute());
            }
        });
    }
}

Step for reproduce:

Run app (my time: 13:21)

Change time on the Widget (21:21)

Tap on the Reset button

Result:time not reset to 13:21

Log:

03-30 13:18:05.765 30923-30923/ru.neverdark.timepickerproblem
  V/MainActivity: onClick: 13=>21 03-30 13:18:05.765
  30923-30923/ru.neverdark.timepickerproblem V/MainActivity: onClick:
  18=>18

Any workaround for this problem?

Same bug I found in Issue Tracker: https://code.google.com/p/android/issues/detail?id=208180 but in SDK25 not fixed...

Demo project on the github: https://github.com/yankovskiy/TimePickerProblem

Body:
 protected Dialog onCreateDialog(int id) {
    checkMark = (Button) findViewById(R.id.button13)                            ;
    checkMark.setVisibility(View.VISIBLE)                                       ;
    switch (id) {
        case TIME_DIALOG_ID:
        // set time picker as current time
        return new TimePickerDialog(this,
            timePickerListener, hour, minute,false);

        case TIME_DIALOG_ID_ON:
        // set time picker as current time
        return new TimePickerDialog(this,
            timePickerListenerOn, hour, minute,false);
    }
    return null;
    }

How about this?

picker.setCurrentHour(date.getHours())
picker.setCurrentMinute(date.getMinutes())


问:
Can Spring Boot and Vert.x be mixed into one artifact / deployment?
Suppose I have a Spring Boot application: can I use both, a @RestController and Vert.x Router to define APIs in the same application?

答:
Yes, you can! Assuming you are using Vert.x 3.3.x, have a look here.

Basically you need a Spring component with your route definition(s), and be able to inject it into Vertx.vertx().deployVerticle when the application starts. I'm not sure if you can mix end-point definition(s) with the same "root context(s)" though.

In any case, Spring Boot and Vert.x plays well together (so far). There are some more examples also here.


问:
com.google.api.config.ServiceConfigSupplier - Failed to fetch default config version for service (only on localhost)
I'm using Cloud Endpoints Frameworks (2.0.1) for Java as part of my final year project and have been relatively successful with it so far.
I don't have any problems when deploying to my appspot.com domain, however, I am running into some problems when deploying locally.

(Any references to my-project-id in the following code blocks are aliases for my actual google cloud project id)

I have a valid openapi descriptor (openapi.json) of an annotated @API class which I am deploying to cloud endpoints using "gcloud service-management deploy openapi.json".
The command returns successfully:

```<code>Service Configuration [2017-02-23r0] uploaded for service [api.endpoints.<my-project-id>.cloud.goog]
</code>```

I then map the returned config_id to the correct endpoints_api_service in my app.yaml

```<code>endpoints_api_service:
  name: api.endpoints.<my-project-id>.cloud.goog
  config_id: 2017-02-23r0
</code>```

This service is listed by the gcloud cli tool using "gcloud service-management list"

```<code>    NAME                                                           TITLE
    storage-component.googleapis.com                 Google Cloud Storage
    api.endpoints.<my-project-id>.cloud.goog         api.endpoints.<my-project-id>.cloud.goog
    etc...
</code>```

and "gcloud service-management configs list --service api.endpoints.my-project-id.cloud.goog"

```<code>CONFIG_ID        SERVICE_NAME
2017-02-23r0     api.endpoints.<my-project-id>.cloud.goog
... other version configs
</code>```

and is accessible on my appspot.com domain (I can call the endpoint and receive the correct response)

I am trying to deploy my project on localhost using the maven appengine plugin for java (mvn appengine:devserver), but upon jetty startup I'm hit with the following Exception:

```<code> WARNING: Failed startup of context com.google.appengine.tools.development.DevAppEngineWebAppContext...

com.google.api.config.ServiceConfigException: Failed to fetch default config version for service 'api.endpoints.<my-project-id>.cloud.goog'. No versions exist!
at com.google.api.config.ServiceConfigSupplier.fetchLatestServiceVersion(ServiceConfigSupplier.java:155)
....
</code>```

The deployment then gets stuck in an endless cycle of trying to start jetty, and being hit with that error message, and restarting etc. Any attempts to access localhost:8080 result in a "503: Service not found" error

I assumed that the local deployment of my app would be able to access the service config that was deployed using "gcloud service-management deploy", in the same way that the appspot.com deployment can, but is this not the case?
Looking at the source for ServiceConfigSupplier.getchLatestServiceVersion() I gather that serviceManagement.services().configs().list(my-service-name).execute().getServiceConfigs() is returning an empty list, but why is this only occurring locally?

Extra Information

my ENDPOINTS_SERVICE_NAME environment variable matches 'api.endpoints.my-project-id.cloud.goog'

I noticed that there was an update (1.0.2) to com.google.api.config a few days ago, and it has a dependency on an older version of com.google.api.services.servicemanagement (dependent on v1-rev14-1.22.0 with the newest version being v1-rev340-1.22.0)
I doubt this is the problem, but I thought I would mention it, as it contains classes relevant to the exception (ServiceManagement is used by ServiceConfigSupplier, which is throwing the exception). Perhaps there is an inconsistency in where they are looking for the service configs?

I'm quite stumped tbh, it's a bit over my head. I would dislike having to remove Endpoints, as I'm starting to like it, but we also can't really lose usage of our devserver either. I hope someone can shed a little bit of light on this issue.

答:
This may be related to a permission issue if you have pulled all recent updates. git pull Also, check that your Cloud SDK is up-to-date by using: gcloud components update.

Assuming you followed the instructions listed at https://cloud.google.com/endpoints/docs/frameworks/java/quickstart-frameworks-java. To get around this issue you can create a service account with necessary permissions or use the command gcloud auth application-default login.

You can setup a service account using the Cloud SDK gcloud at https://cloud.google.com/sdk/docs/authorizing

Please let me know if you have anymore questions.

As for the command gcloud auth application-default login. According to the help description:

Obtains user access credentials via a web flow and puts them in the
  well-known location for Application Default Credentials to use them as
  a proxy for a service account.

When you used this command it obtains credentials for gcloud your Gmail Account. something@gmail.com and then stores the credentials in a location known to contain application credentials.

Body:
I'm using Cloud Endpoints Frameworks (2.0.1) for Java as part of my final year project and have been relatively successful with it so far.
I don't have any problems when deploying to my appspot.com domain, however, I am running into some problems when deploying locally.

(Any references to my-project-id in the following code blocks are aliases for my actual google cloud project id)

I have a valid openapi descriptor (openapi.json) of an annotated @API class which I am deploying to cloud endpoints using "gcloud service-management deploy openapi.json".
The command returns successfully:

Service Configuration [2017-02-23r0] uploaded for service [api.endpoints.<my-project-id>.cloud.goog]

I then map the returned config_id to the correct endpoints_api_service in my app.yaml

endpoints_api_service:
  name: api.endpoints.<my-project-id>.cloud.goog
  config_id: 2017-02-23r0

This service is listed by the gcloud cli tool using "gcloud service-management list"

    NAME                                                           TITLE
    storage-component.googleapis.com                 Google Cloud Storage
    api.endpoints.<my-project-id>.cloud.goog         api.endpoints.<my-project-id>.cloud.goog
    etc...

and "gcloud service-management configs list --service api.endpoints.my-project-id.cloud.goog"

CONFIG_ID        SERVICE_NAME
2017-02-23r0     api.endpoints.<my-project-id>.cloud.goog
... other version configs

and is accessible on my appspot.com domain (I can call the endpoint and receive the correct response)

I am trying to deploy my project on localhost using the maven appengine plugin for java (mvn appengine:devserver), but upon jetty startup I'm hit with the following Exception:

 WARNING: Failed startup of context com.google.appengine.tools.development.DevAppEngineWebAppContext...

com.google.api.config.ServiceConfigException: Failed to fetch default config version for service 'api.endpoints.<my-project-id>.cloud.goog'. No versions exist!
at com.google.api.config.ServiceConfigSupplier.fetchLatestServiceVersion(ServiceConfigSupplier.java:155)
....

The deployment then gets stuck in an endless cycle of trying to start jetty, and being hit with that error message, and restarting etc. Any attempts to access localhost:8080 result in a "503: Service not found" error

I assumed that the local deployment of my app would be able to access the service config that was deployed using "gcloud service-management deploy", in the same way that the appspot.com deployment can, but is this not the case?
Looking at the source for ServiceConfigSupplier.getchLatestServiceVersion() I gather that serviceManagement.services().configs().list(my-service-name).execute().getServiceConfigs() is returning an empty list, but why is this only occurring locally?

Extra Information

my ENDPOINTS_SERVICE_NAME environment variable matches 'api.endpoints.my-project-id.cloud.goog'

I noticed that there was an update (1.0.2) to com.google.api.config a few days ago, and it has a dependency on an older version of com.google.api.services.servicemanagement (dependent on v1-rev14-1.22.0 with the newest version being v1-rev340-1.22.0)
I doubt this is the problem, but I thought I would mention it, as it contains classes relevant to the exception (ServiceManagement is used by ServiceConfigSupplier, which is throwing the exception). Perhaps there is an inconsistency in where they are looking for the service configs?

I'm quite stumped tbh, it's a bit over my head. I would dislike having to remove Endpoints, as I'm starting to like it, but we also can't really lose usage of our devserver either. I hope someone can shed a little bit of light on this issue.


问:
Java Thread Count doesn't work
Why is count 0? </p>

<p>I start the thread 1 then I start thread 2. Count should be 2000. But it shows count to be 0. Someone please explain in simple terms.     </p>

```<code>public class App {
    private int count = 0;

    public static void main(String[] args) {
        App app = new App();
        app.doWork();
    }

    public void doWork(){
        Thread t1 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0;i < 10000;i++){
                    count++;
                }
            }
        });

        Thread t2 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0;i < 10000;i++){
                    count++;
                }
            }
        });
        t1.start();
        t2.start();

        System.out.println("Count is: " + count);
    }
}
</code>```

答:
Integer's increment is not safe to multithreading. You should use AtmoicInteger like this:</p>

```<code>public class App {

    private AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        App app = new App();
        app.doWork();
    }

    public void doWork() throws InterruptedException {
        Thread t1 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0;i < 10000;i++){
                    count.getAndIncrement();
                }
            }
        });

        Thread t2 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0;i < 10000;i++){
                    count.getAndIncrement();
                }
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Count is: " + count);
    }
}
</code>```

Title: Java Thread Count doesn't work

Body:
Why is count 0?

I start the thread 1 then I start thread 2. Count should be 2000. But it shows count to be 0. Someone please explain in simple terms.

public class App {
    private int count = 0;

    public static void main(String[] args) {
        App app = new App();
        app.doWork();
    }

    public void doWork(){
        Thread t1 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0;i < 10000;i++){
                    count++;
                }
            }
        });

        Thread t2 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0;i < 10000;i++){
                    count++;
                }
            }
        });
        t1.start();
        t2.start();

        System.out.println("Count is: " + count);
    }
}

Body:
Integer's increment is not safe to multithreading. You should use AtmoicInteger like this:

public class App {

    private AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        App app = new App();
        app.doWork();
    }

    public void doWork() throws InterruptedException {
        Thread t1 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0;i < 10000;i++){
                    count.getAndIncrement();
                }
            }
        });

        Thread t2 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0;i < 10000;i++){
                    count.getAndIncrement();
                }
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Count is: " + count);
    }
}


问:
d3.js change path target or increase lines
using the bl.ocks collapsable tree example: how do I increase the length of the lines between the circles (or move the circles further out, to the right)? I know I can style the lines easily using CSS and I can update the circle sizes easily in the script... but my text is longer and it is overlaid when the children are exposed. Better still would be either:
* calculate the max length of text in that set of children and set the new children out past the current set of children.
or
* when exposing children, move the current set of children apart so the child that is now also a parent, has room at top/bottom to accommodate it's children.

答: You can use the tree.nodeSize() function to set the height and width of the spacing. The thing to note is that if you are following the code posted above, it is using the tree.size() function and the both of these can't be used at the same time. Here is the documentation for the tree.nodeSize() function: https://github.com/d3/d3-3.x-api-reference/blob/master/Tree-Layout.md#nodeSize.


问:
Best way add a new column with sequential numbering in an existing data table
I have a non empty datatable . What is the best way to add another column to it that has sequential numbering starting from 1.

I tried the following code. But did not work.

```<code>DataColumn dc = new DataColumn("Col1");
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
dc.DataType = typeof(Int32);
dt.Columns.Add(dc);
</code>```

Will setting any expression help in this scenario ?

Thanks in Advance

答: You'll have to build a whole new datatable for this and manually deep-copy each row one by one from the old table to the new.  Sorry.</p>

Body:
I have a non empty datatable . What is the best way to add another column to it that has sequential numbering starting from 1.

I tried the following code. But did not work.

DataColumn dc = new DataColumn("Col1");
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
dc.DataType = typeof(Int32);
dt.Columns.Add(dc);

Will setting any expression help in this scenario ?

Thanks in Advance


问:
Set current time field for MySQL
I am trying to set the value of a field via a hidden form field to the current date and time using either PHP or Javascript that would conform to MySQL's datetime field.</p>

答: $current = date_timestamp_set(date_create(), time());</p>

Title: Set current time field for MySQL


问:
Is WSO2 / Mulesoft Identity Server Free for commercial purposes?
I am looking out for Authentication Broker products for integrating with multiple IDPs which has SAML2P, Ws-Fed based endpoints, ADFS/STS, Facebook, Google etc.

I am a .NET Developer and developing applications on .NET platform. Initially I thought to create a Auth. Broker by my own using Kentor AuthServices OR ComponentOne and WIF etc. But some of the folks mentioned about countertop products. Could you please help with best one , open source and good for .NET / MSFT platform Product integrations etc.

Note : I heard WSO2, Mulesoft is based on APACHE,JAVA etc. Seems like its hard for us to maintain those on our technology stack. Please comment....

答: I'm not aware of the Mulesoft. But WSO2 products are licensed under apache license and you are free to use it for any commercial purposes.</p>


问:
How to create a Form dynamically?
I want to create, dynamically, forms depending a type of user. For example:
I want, if it is an administrator, to create the form or the buttons, for this user specifically.
 In the code of my login there is a validation that identifies the type of user.
But I only did that when it identifies the user to send it to the corresponding screen with its buttons already set, but what I want is that when identifying the user type, generate the buttons that the user should have access to;
The user has a type of user and that type of user has 1 or more permissions, then, depending on how many permissions that user has, create the buttons. Each permission is a button.
Example:
The user Alfonso is type of sales and has permissions to invoice and sell, then when it initiates session the "invoice" and "sell" buttons will be generated.</p>

答:
Below is just an example to show how to open different Form based on user type. You can optimize it further when you redesign it as per your requirement.
In below code assumption is FUser1 and FUser2 are 2 forms to be opened as per the userType variable.

```<code>private FUser1 fUser1;
private FUser2 fUser2;
private FUser2 fUserAdmin;

private void OpenForm(int userType)
{
    switch (userType)
    {
        case 1:
            if (fUser1 == null)
            {
                fUser1 = new FUser1();
                //do initialization specific to FUser1
                fUser1.txtLogin.Text = "Robinhood";
            }
            fUser1.Show();
            break;
        case 2:
            if (fUser2 == null)
            {
                fUser2 = new FUser2();
                //do initialization specific to FUser2
                fUser2.btnProcess.Enable = false;
                fUser2.btnPermit.Visible = false;
            }
            fUser2.Show();
            break;
        case 3: //Admin
            if (fUserAdmin == null)
            {
                fUserAdmin = new FUser2();
                //do initialization specific to FUser2
                fUserAdmin.btnProcess.Enable = true;
                fUserAdmin.btnPermit.Visible = true;
                fUserAdmin.ProcessSales(); //Public function in FUser2
            }
            fUserAdmin.Show();
            break;
    }
}
</code>```

Title: How to create a Form dynamically?

Body:
Below is just an example to show how to open different Form based on user type. You can optimize it further when you redesign it as per your requirement.
In below code assumption is FUser1 and FUser2 are 2 forms to be opened as per the userType variable.

private FUser1 fUser1;
private FUser2 fUser2;
private FUser2 fUserAdmin;

private void OpenForm(int userType)
{
    switch (userType)
    {
        case 1:
            if (fUser1 == null)
            {
                fUser1 = new FUser1();
                //do initialization specific to FUser1
                fUser1.txtLogin.Text = "Robinhood";
            }
            fUser1.Show();
            break;
        case 2:
            if (fUser2 == null)
            {
                fUser2 = new FUser2();
                //do initialization specific to FUser2
                fUser2.btnProcess.Enable = false;
                fUser2.btnPermit.Visible = false;
            }
            fUser2.Show();
            break;
        case 3: //Admin
            if (fUserAdmin == null)
            {
                fUserAdmin = new FUser2();
                //do initialization specific to FUser2
                fUserAdmin.btnProcess.Enable = true;
                fUserAdmin.btnPermit.Visible = true;
                fUserAdmin.ProcessSales(); //Public function in FUser2
            }
            fUserAdmin.Show();
            break;
    }
}


问:
Is there a way to save the Visual Studio workspace manually?
I've given up trying to stop VS from crashing (usually 2 to 3 times a day). Now I'm moving on to finding a way limit the amount of work that needs to be redone when I re-open my project after a crash.

When VS crashes, any changes you have made to the workspace such as which files are open, pinned etc are gone. Any breakpoints, bookmarks etc are also gone. If VS is shutdown normally without crashing then all these workspace changes are saved, but if it crashes they're lost. I am now at the point where I deliberately shutdown VS every so often just so that any changes will be saved when it inevitably crashes.

Is there a way to manually save the workspace?

答: File - Save all should save most of the current workspace configuration.


问:
Downloading 'Yum groupinstall "development tools"'?
I've looked all over and build essentials are all I see that was replaced by Development tools. When I type the command I receive "no such command".

What is the alternative to this?

答: Ubuntu doesn't use yum. You still want to use the apt instructions.</p>


问:
Why objectMapper fails if I put a method different to set and get property in Java?
I have a class named Car that represents an entity, it has a property that let me knows if the car has the doors opened or not.

```<code>private int doorsOpened;
public void setDoorsOpened( val ) { this.doorsOpened = val; }
public int getDoorsOpened() { return this.doorsOpened; }
</code>```

When I need to know that, I simply call:

```<code>if (car.getDoorsOpened() != 0) {
    car.startAlarm();
}
else {
    car.allIsFine();
}
</code>```

But, I don't want to use getDoorsOpened() != 0 comparison, for that reason I created a new method named doorsOpened() that brings to me the boolean value:

```<code>public boolean doorsOpened() { return this.doorsOpened != 0; }
</code>```

But with this new method when I want to do this:

```<code>String carData = objectMapper.writeValueAsString( car );
</code>```

I get this exception:

```<code>Unhandled server exception: (was java.lang.NullPointerException) (through reference chain: com.desafioguerreros.artifacts.car.entities.Car["volunteer"])
com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.desafioguerreros.artifacts.car.entities.Car["volunteer"])
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:232)
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:197)
    at com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:187)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:647)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:114)
    at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:2866)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2323)
</code>```

Why?

答:
First of all, seeing the stacktrace, it looks like one of the attributes in the entity is null and it is causing the exception. If my understanding is correct, if you have a non-conventional getter, Jackson will just ignore the field and not throw any exception. If you want to have a custom getter and include that field in serialization, you can use @JsonProperty as shown below.

```<code>public class car{
    private int doorsOpened;

    @JsonProperty(value="doorsOpened")
    public boolean doorsOpened(){
        return this.doorsOpened != 0;
    }

}
</code>```

Body:
I have a class named Car that represents an entity, it has a property that let me knows if the car has the doors opened or not.

private int doorsOpened;
public void setDoorsOpened( val ) { this.doorsOpened = val; }
public int getDoorsOpened() { return this.doorsOpened; }

When I need to know that, I simply call:

if (car.getDoorsOpened() != 0) {
    car.startAlarm();
}
else {
    car.allIsFine();
}

But, I don't want to use getDoorsOpened() != 0 comparison, for that reason I created a new method named doorsOpened() that brings to me the boolean value:

public boolean doorsOpened() { return this.doorsOpened != 0; }

But with this new method when I want to do this:

String carData = objectMapper.writeValueAsString( car );

I get this exception:

Unhandled server exception: (was java.lang.NullPointerException) (through reference chain: com.desafioguerreros.artifacts.car.entities.Car["volunteer"])
com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.desafioguerreros.artifacts.car.entities.Car["volunteer"])
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:232)
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:197)
    at com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:187)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:647)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:114)
    at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:2866)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2323)

Why?

Body:
First of all, seeing the stacktrace, it looks like one of the attributes in the entity is null and it is causing the exception. If my understanding is correct, if you have a non-conventional getter, Jackson will just ignore the field and not throw any exception. If you want to have a custom getter and include that field in serialization, you can use @JsonProperty as shown below.

public class car{
    private int doorsOpened;

    @JsonProperty(value="doorsOpened")
    public boolean doorsOpened(){
        return this.doorsOpened != 0;
    }

}


问:
Merge conflict when multiple core data inserts are dispatched to NSPersistentContainer using performBackgroundTask
I was experimenting with the new core data API NSPersistentContainer and was under the impression that an internal queueing mechanism would prevent write transactions from evaluating concurrently, as detailed in this stack overflow answer  NSPersistentContainer concurrency for saving to core data

The way that a lot of pros have been dealing with the problem for a long time (even before NSPersistentContainer did it) was to have an operation queue to queue the writes so there is only one write going on at a time, and have another context on the main thread only for reads. This way you never get any merge conflicts. (see https://vimeo.com/89370886 for a great explanation on this setup which is now what NSPersistentContainer does internally).
  When you call performBackgroundTask the persistentContainer enqueues that block into an internal serial queue. This ensure that there are no mergeConflicts.

However if I insert multiple entities which share a relationship destination in a tight loop using performBackgroundTask for each iteration, I get a NSMergeConflict error when I save the context:

```<code>            let bundlePath = Bundle.main.resourceURL!

        let directoryEnumerator = FileManager.default.enumerator(at: bundlePath, includingPropertiesForKeys: [URLResourceKey.isDirectoryKey, URLResourceKey.nameKey])
        while let url = directoryEnumerator?.nextObject() as? URL {

            if url.pathExtension == "jpeg" {
                let imageData = try! Data(contentsOf: url)

                DataManager.persistentContainer.performBackgroundTask { (context) in

                    //          context.mergePolicy = NSMergePolicy.overwrite

                    let new = Photo(context: context)
                    new.name = url.lastPathComponent
                    new.data = imageData as NSData

                    let corresponding = try! context.existingObject(with: DataManager.rootFolder.objectID) as! Folder
                    new.parent = corresponding

                    try! context.save()
                }
            }
</code>```

I posted a sample project on github to demonstrate the problem:
https://github.com/MaximeBoulat/NSPersistentContainer_Merge_Conflict

The crash seems to be happening because multiple entities are setting their "parent" relationship concurrently, for the same parent, which causes the parent's "children" relationship to be desynchronized across concurrent updates.

This happens even if I set the .automaticallyMergesChangesFromParent property of the incoming context to true. I can prevent the crash by defining the incoming context's merge policy, but that's not an acceptable solution.

Is there any way to configure NSPersistentContainer to properly serialize updates dispatched using the performBackgroundTask API. Or is there something I am missing which is causing these updates to conflict with each other? Or did Apple provide the NSPersistentContainer stack with the expectations that any conflicts encountered when evaluating logic passed into performBackgroundTask should either be fatal, or be disregarded?

答:
From the documentation on performBackgroundTask(:):

Each time this method is invoked, the persistent container creates a new NSManagedObjectContext with the concurrencyType set to privateQueueConcurrencyType. The persistent container then executes the passed in block against that newly created context on the context’s private queue

So, I don't think that's doing what you want it to do. I think you want to call newBackgroundContext(), store it in a property somewhere, and use performBlock(:) on it whenever you want that serialization.

Body:
I was experimenting with the new core data API NSPersistentContainer and was under the impression that an internal queueing mechanism would prevent write transactions from evaluating concurrently, as detailed in this stack overflow answer  NSPersistentContainer concurrency for saving to core data

The way that a lot of pros have been dealing with the problem for a long time (even before NSPersistentContainer did it) was to have an operation queue to queue the writes so there is only one write going on at a time, and have another context on the main thread only for reads. This way you never get any merge conflicts. (see https://vimeo.com/89370886 for a great explanation on this setup which is now what NSPersistentContainer does internally).
  When you call performBackgroundTask the persistentContainer enqueues that block into an internal serial queue. This ensure that there are no mergeConflicts.

However if I insert multiple entities which share a relationship destination in a tight loop using performBackgroundTask for each iteration, I get a NSMergeConflict error when I save the context:

            let bundlePath = Bundle.main.resourceURL!

        let directoryEnumerator = FileManager.default.enumerator(at: bundlePath, includingPropertiesForKeys: [URLResourceKey.isDirectoryKey, URLResourceKey.nameKey])
        while let url = directoryEnumerator?.nextObject() as? URL {

            if url.pathExtension == "jpeg" {
                let imageData = try! Data(contentsOf: url)

                DataManager.persistentContainer.performBackgroundTask { (context) in

                    //          context.mergePolicy = NSMergePolicy.overwrite

                    let new = Photo(context: context)
                    new.name = url.lastPathComponent
                    new.data = imageData as NSData

                    let corresponding = try! context.existingObject(with: DataManager.rootFolder.objectID) as! Folder
                    new.parent = corresponding

                    try! context.save()
                }
            }

I posted a sample project on github to demonstrate the problem:
https://github.com/MaximeBoulat/NSPersistentContainer_Merge_Conflict

The crash seems to be happening because multiple entities are setting their "parent" relationship concurrently, for the same parent, which causes the parent's "children" relationship to be desynchronized across concurrent updates.

This happens even if I set the .automaticallyMergesChangesFromParent property of the incoming context to true. I can prevent the crash by defining the incoming context's merge policy, but that's not an acceptable solution.

Is there any way to configure NSPersistentContainer to properly serialize updates dispatched using the performBackgroundTask API. Or is there something I am missing which is causing these updates to conflict with each other? Or did Apple provide the NSPersistentContainer stack with the expectations that any conflicts encountered when evaluating logic passed into performBackgroundTask should either be fatal, or be disregarded?


问:
Silverstripe custom display rules—how to use the value of a select?

I'm trying to have a select field, and when I select an option, I want a second select box to appear.

The problem is that select fields don't have a value like text fields do. So, any comparison SS provides will fail—always thinking the select field is ''.

Is there any way to compare the value of a select field?

答:
Use display-logic

Disclaimer: I'm the author


问:
Is there a template engine that updates the DOM when data is changed?
All of the template engines I've tried so far (Handlebars, Underscore, Embedded) require you to input data and render the template to HTML. However, my data updates fairly frequently and this causes the page to flicker as the layout is rebuilt.

Is there a template engine that supports updating the DOM instead of recreating it every time?

答:
As @Josh Beam said, React is a sort of "view framework". But it's not a template engine. Maybe Vdt is the one is wanted. It is based on virtual-dom, so it can be updated without recreating the entire DOM every time.

A snippet like bellow:

Hello {name}!

```

<pre class="lang-js prettyprint-override"><code>var vdt = Vdt(template);
vdt.render({name: 'World'});

// then update
vdt.data.name = 'Vdt';
vdt.update();
</code>```

Body:
As @Josh Beam said, React is a sort of "view framework". But it's not a template engine. Maybe Vdt is the one is wanted. It is based on virtual-dom, so it can be updated without recreating the entire DOM every time.

A snippet like bellow:

<div>Hello {name}!</div>

var vdt = Vdt(template);
vdt.render({name: 'World'});

// then update
vdt.data.name = 'Vdt';
vdt.update();


问:
Setting property value of object in a deep javascript Array
I was wondering if anyone could help figure out how i can set the value of a property in an object which can be found in a deep Array.

Below is an example of the Tree array

I would like to know how i can insert

```<code>var newObjectToInsert = {id: 999, name: 'new name'};
</code>```

in the 'nodes' array of the object whose id === 3901

var tree = [
  {
    id: 1,
    name: 'Level 1 - A',
    nodes: [
      {
        id: 33,
        name: 'Level 2 = A',
        nodes: []
      },

      {
        id: 21,
        name: 'Level 2 = B',
        nodes: []
      }
    ]
  },

  {
    id: 2,
    name: 'Level 1 - B',
    nodes: []
  },

  {
    id: 3,
    name: 'Level 1 - B',
    nodes: [
      {
        id: 65,
        name: 'Level 2 = A',
        nodes: []
      },

      {
        id: 124,
        name: 'Level 2 = A',
        nodes: [
          {
            id: 3901,
            name: 'Level 3 - A'
          },

          {
            id: 29182,
            name: 'Level 3 - B',
            nodes: [
              {
                id: 32423413,
                name: 'Level 4 - A'
              }
            ]
          }
        ]
      },

      {
        id: 534,
        name: 'Level 2 = A',
        nodes: []
      }
    ]
  },
];```

答:
You have a recursive structure. So you visit all items you need a visitor.

Pseudo code:

```<code>function visit(visitor, tree) {
  visitor(tree);
  items.nodes.forEach(subTree => visit(visitor, subTree));
}
</code>```

And use

```<code>visit(node => {
  if (node.id === 'whatever'){
    node.push({yournode});
  }
}, tree);
</code>```

Body:
I was wondering if anyone could help figure out how i can set the value of a property in an object which can be found in a deep Array.

Below is an example of the Tree array

I would like to know how i can insert

var newObjectToInsert = {id: 999, name: 'new name'};

in the 'nodes' array of the object whose id === 3901

var tree = [
  {
    id: 1,
    name: 'Level 1 - A',
    nodes: [
      {
        id: 33,
        name: 'Level 2 = A',
        nodes: []
      },

      {
        id: 21,
        name: 'Level 2 = B',
        nodes: []
      }
    ]
  },

  {
    id: 2,
    name: 'Level 1 - B',
    nodes: []
  },

  {
    id: 3,
    name: 'Level 1 - B',
    nodes: [
      {
        id: 65,
        name: 'Level 2 = A',
        nodes: []
      },

      {
        id: 124,
        name: 'Level 2 = A',
        nodes: [
          {
            id: 3901,
            name: 'Level 3 - A'
          },

          {
            id: 29182,
            name: 'Level 3 - B',
            nodes: [
              {
                id: 32423413,
                name: 'Level 4 - A'
              }
            ]
          }
        ]
      },

      {
        id: 534,
        name: 'Level 2 = A',
        nodes: []
      }
    ]
  },
];

Body:
You have a recursive structure. So you visit all items you need a visitor.

Pseudo code:

function visit(visitor, tree) {
  visitor(tree);
  items.nodes.forEach(subTree => visit(visitor, subTree));
}

And use

visit(node => {
  if (node.id === 'whatever'){
    node.push({yournode});
  }
}, tree);