问:
How to kill all active and inactive oracle sessions for user
I am trying the below script to kill all active and inactive oracle sessions for user at once but it doesn't work. The script executes successfully but does not kill sessions for user.</p>

```<code>BEGIN
  FOR r IN (select sid,serial# from v$session where username = 'USER')
  LOOP
    EXECUTE IMMEDIATE 'alter system kill session ''' || r.sid
      || ',' || r.serial# || '''';
  END LOOP;
END;
</code>```

答:
```<code>BEGIN
  FOR r IN (select sid,serial# from v$session where username='user')
  LOOP
      EXECUTE IMMEDIATE 'alter system kill session ''' || r.sid  || ','
        || r.serial# || ''' immediate';
  END LOOP;
END;
</code>```

This should work - I just changed your script to add the immediate keyword. As the previous answers pointed out, the kill session only marks the sessions for killing; it does not do so immediately but later when convenient.

From your question, it seemed you are expecting to see the result immediately. So immediate keyword is used to force this.

Body:
I am trying the below script to kill all active and inactive oracle sessions for user at once but it doesn't work. The script executes successfully but does not kill sessions for user.

BEGIN
  FOR r IN (select sid,serial# from v$session where username = 'USER')
  LOOP
    EXECUTE IMMEDIATE 'alter system kill session ''' || r.sid
      || ',' || r.serial# || '''';
  END LOOP;
END;

Body:
BEGIN
  FOR r IN (select sid,serial# from v$session where username='user')
  LOOP
      EXECUTE IMMEDIATE 'alter system kill session ''' || r.sid  || ','
        || r.serial# || ''' immediate';
  END LOOP;
END;

This should work - I just changed your script to add the immediate keyword. As the previous answers pointed out, the kill session only marks the sessions for killing; it does not do so immediately but later when convenient.

From your question, it seemed you are expecting to see the result immediately. So immediate keyword is used to force this.


来源: stackexchange

问:
Something like lambda expressions in Go (merge similar methods)
I have a struct in Go which has more than ten methods. And all of them are almost the same. In fact, the difference is only in one line.

Let's see the simplified example. Here is the first method:

```<code>func (s *service) GetUser(i int, s string) (*SomeObject, error) {
    CommonMethod1()
    CommonMethod2()

    user, err := s.internalLayer.GetUser(i, s)

    if err != nil {
        CommonMethod3()
    }
    return user, err
}
</code>```

And the second one:

```<code>func (s *service) CheckUser(i int) (bool, error) {
    CommonMethod1()
    CommonMethod2()

    exists, err := s.internalLayer.CheckUser(i)

    if err != nil {
        CommonMethod3()
    }
    return exists, err
}
</code>```

And there are almost 10 others with a lot of copy and paste. I'd like to ameliorate this code and the idea is to create some common method that I'll call everywhere.

It should

call CommonMethod1()

call CommonMethod2()

call some method that I pass to it in the parameter

call CommonMethod3() in case of error

return parameters

Can you tell me if it's possible to implement in Go such common method?

```<code>user, err := s.GetUser(i, s)
exists, err := s.CheckUser(i)
</code>```

Has different parameters count and different return types.

答:
If CommonMethod1() and CommonMethod2() calls do not have to precede the calls to the internal layer, basically they can be incorporated into a check function, and you don't even need closures or function values (there's also no need to return the passed error from check()):

```<code>func (s *service) GetUser(i int, s string) (*SomeObject, error) {
    user, err := s.internalLayer.GetUser(i, s)
    check(err)
    return user, err
}

func (s *service) CheckUser(i int) (bool, error) {
    exists, err := s.internalLayer.CheckUser(i)
    check(err)
    return exists, err
}

func check(err error) {
    CommonMethod1()
    CommonMethod2()
    if err != nil {
        CommonMethod3()
    }
}
</code>```

If CommonMethod1() and CommonMethod2() calls must precede the calls to the internal layer, then you may use closures, but using named result parameters simplifies the code, and again, it's unnecessary to return the error from the common function:

```<code>func (s *service) GetUser(i int, s string) (user *SomeObject, err error) {
    do(func() error {
        user, err = s.internalLayer.GetUser(i, s)
        return err
    })
    return
}

func (s *service) CheckUser(i int) (exists bool, err error) {
    do(func() error {
        exists, err = s.internalLayer.CheckUser(i)
        return err
    })
    return
}

func do(f func() error) {
    CommonMethod1()
    CommonMethod2()

    if err := f(); err != nil {
        CommonMethod3()
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a struct in Go which has more than ten methods. And all of them are almost the same. In fact, the difference is only in one line.

Let's see the simplified example. Here is the first method:

func (s *service) GetUser(i int, s string) (*SomeObject, error) {
    CommonMethod1()
    CommonMethod2()

    user, err := s.internalLayer.GetUser(i, s)

    if err != nil {
        CommonMethod3()
    }
    return user, err
}

And the second one:

func (s *service) CheckUser(i int) (bool, error) {
    CommonMethod1()
    CommonMethod2()

    exists, err := s.internalLayer.CheckUser(i)

    if err != nil {
        CommonMethod3()
    }
    return exists, err
}

And there are almost 10 others with a lot of copy and paste. I'd like to ameliorate this code and the idea is to create some common method that I'll call everywhere.

It should

call CommonMethod1()

call CommonMethod2()

call some method that I pass to it in the parameter

call CommonMethod3() in case of error

return parameters

Can you tell me if it's possible to implement in Go such common method?

user, err := s.GetUser(i, s)
exists, err := s.CheckUser(i)

Has different parameters count and different return types.

Body:
If CommonMethod1() and CommonMethod2() calls do not have to precede the calls to the internal layer, basically they can be incorporated into a check function, and you don't even need closures or function values (there's also no need to return the passed error from check()):

func (s *service) GetUser(i int, s string) (*SomeObject, error) {
    user, err := s.internalLayer.GetUser(i, s)
    check(err)
    return user, err
}

func (s *service) CheckUser(i int) (bool, error) {
    exists, err := s.internalLayer.CheckUser(i)
    check(err)
    return exists, err
}

func check(err error) {
    CommonMethod1()
    CommonMethod2()
    if err != nil {
        CommonMethod3()
    }
}

If CommonMethod1() and CommonMethod2() calls must precede the calls to the internal layer, then you may use closures, but using named result parameters simplifies the code, and again, it's unnecessary to return the error from the common function:

func (s *service) GetUser(i int, s string) (user *SomeObject, err error) {
    do(func() error {
        user, err = s.internalLayer.GetUser(i, s)
        return err
    })
    return
}

func (s *service) CheckUser(i int) (exists bool, err error) {
    do(func() error {
        exists, err = s.internalLayer.CheckUser(i)
        return err
    })
    return
}

func do(f func() error) {
    CommonMethod1()
    CommonMethod2()

    if err := f(); err != nil {
        CommonMethod3()
    }
}


问:
How to use time.Parse to parse hh:mm format in Go
I am importing a lot of fields of the format:

09:02 AM

10:02 AM

12:30 PM

04:10 PM

04:50 PM

05:30 PM

I would like to convert the fields into something I can do arithmetic on. For example, do a count down to when the event Occurs.  Thus, saving the field in microseconds... or even seconds.
I have been trying to get the time.Parse to work...   no joy.

```<code>fmt.Println(time.Parse("hh:mm", m.Feed.Entry[i].GsxA100Time.T))
</code>```

returns...

0001-01-01 00:00:00 +0000 UTC parsing time "07:50 PM" as "hh:mm": cannot parse "07:50 PM" as "hh:mm"

any suggestions?

答:
The layout string for time.Parse does not handle the "hh:mm" format. In your case, the layout string would rather be "03:04 PM" as you can see in the documentation.

To get a time.Duration after parsing the string, you can substract your time with a reference time, in your case I would assume "12:00 AM".

Working example:

```<code>package main

import (
    "fmt"
    "time"
)

func main() {
    ref, _ := time.Parse("03:04 PM", "12:00 AM")
    t, err := time.Parse("03:04 PM", "11:22 PM")
    if err != nil {
        panic(err)
    }

    fmt.Println(t.Sub(ref).Seconds())
}
</code>```

Output:

84120

Playground

ContentLicense: CC BY-SA 4.0

Body:
I am importing a lot of fields of the format:

09:02 AM

10:02 AM

12:30 PM

04:10 PM

04:50 PM

05:30 PM

I would like to convert the fields into something I can do arithmetic on. For example, do a count down to when the event Occurs.  Thus, saving the field in microseconds... or even seconds.
I have been trying to get the time.Parse to work...   no joy.

fmt.Println(time.Parse("hh:mm", m.Feed.Entry[i].GsxA100Time.T))

returns...

0001-01-01 00:00:00 +0000 UTC parsing time "07:50 PM" as "hh:mm": cannot parse "07:50 PM" as "hh:mm"

any suggestions?

Body:
The layout string for time.Parse does not handle the "hh:mm" format. In your case, the layout string would rather be "03:04 PM" as you can see in the documentation.

To get a time.Duration after parsing the string, you can substract your time with a reference time, in your case I would assume "12:00 AM".

Working example:

package main

import (
    "fmt"
    "time"
)

func main() {
    ref, _ := time.Parse("03:04 PM", "12:00 AM")
    t, err := time.Parse("03:04 PM", "11:22 PM")
    if err != nil {
        panic(err)
    }

    fmt.Println(t.Sub(ref).Seconds())
}

Output:

84120

Playground


问:
Why won't jQuery call my Ajax error handler?
I have the following jQuery Ajax call (There are no other global settings/handlers):

```<code>$.ajax( {
   url: "http://www.blah.com/url/does/not/exist",
   type: "get",
   data: someData,
   dataType: "json",
   error: function (xhr, msg, ex)
   {
       alert("Failed: " + msg);
   },
   complete: function (xhr, msg)
   {
       alert("Done: " + msg);
   }
</code>```

I would expect my error handler to be called, but instead the complete event fires and the alert displays Done: success. In my Javascript console, I see the following message:

```<code>XMLHttpRequest cannot load http://www.blah.com/url/does/not/exist.
Origin null is not allowed by Access-Control-Allow-Origin.
</code>```

Why won't my error handler get called?

What is the meaning of the Origin message logged to the console?

Thanks!

答:
Looks like the only way is to receive the server response in my success method and store it in a global variable, which I'll check in the handler for complete (which always gets called).  No response means the request failed.

It's a shoddy way of handling errors in this otherwise excellent libary.

ContentLicense: CC BY-SA 2.5

Body:
I have the following jQuery Ajax call (There are no other global settings/handlers):

$.ajax( {
   url: "http://www.blah.com/url/does/not/exist",
   type: "get",
   data: someData,
   dataType: "json",
   error: function (xhr, msg, ex)
   {
       alert("Failed: " + msg);
   },
   complete: function (xhr, msg)
   {
       alert("Done: " + msg);
   }

I would expect my error handler to be called, but instead the complete event fires and the alert displays Done: success. In my Javascript console, I see the following message:

XMLHttpRequest cannot load http://www.blah.com/url/does/not/exist.
Origin null is not allowed by Access-Control-Allow-Origin.

Why won't my error handler get called?

What is the meaning of the Origin message logged to the console?

Thanks!


问:
Local repository upgrade
Some time ago I installed Galaxy application on my server machine. Since there is new release, I wanted to upgrade it and I use command:

```<code>git checkout release_17.05 && git pull --ff-only origin release_17.05
</code>```

but I got error message:

```<code>Already on 'release_17.05'
From https://github.com/galaxyproject/galaxy
 * branch            release_17.05 -> FETCH_HEAD
Updating 5a97b8f..9dca211
error: Your local changes to the following files would be overwritten by merge:
        .ci/first_startup.sh
        .ci/flake8_blacklist.txt
        .ci/py3_sources.txt
        ........
</code>```

If I do git status:

```<code>On branch release_17.05 Changes not staged for commit:   (use "git add/rm <file>..." to update what will be committed)   (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   .ci/check_controller.sh
        modified:   .ci/check_mako.sh
        modified:   .ci/first_startup.sh
        modified:   .ci/flake8_blacklist.txt
        modified:   .ci/py3_sources.txt
        modified:   .coveragerc
        modified:   .gitignore
        modified:   .travis.yml
        ....
        Untracked files:
        (use "git add <file>..." to include in what will be committed)

        FETCH_HEAD
        config/plugins/interactive_environments/jupyter/config/allowed_images.yml
        config/plugins/interactive_environments/rstudio/config/allowed_images.yml
        current_files.summary
        file_list.txt
        static/CDAworkflow.html
        static/CDAworkflow.xml
        static/Capture.PNG
        static/Einladung_Galaxy_03_04_2017.pdf
        static/FTP.pdf
        static/Homo_sapiens.GRCh38.86.gtf
        ......
        no changes added to commit (use "git add" and/or "git commit -a")
</code>```

My question is which step should I perform before upgrade? Should I do git add -A && git commit first and than git pull or maybe better git stash, git pull and git stash pop??? I know only git basics and therefore I am not sure which step should I perform first?

Thanks, Marija

答:
Doing git stash is a good option for this! You can execute these commands:

```<code>git stash           # saving your current working directory to the top of stash
git checkout release_17.05 && git pull --ff-only origin release_17.05
git stash apply     # getting back your changes previously stashed
</code>```

Title: Local repository upgrade

Body:
Some time ago I installed Galaxy application on my server machine. Since there is new release, I wanted to upgrade it and I use command:

git checkout release_17.05 && git pull --ff-only origin release_17.05

but I got error message:

Already on 'release_17.05'
From https://github.com/galaxyproject/galaxy
 * branch            release_17.05 -> FETCH_HEAD
Updating 5a97b8f..9dca211
error: Your local changes to the following files would be overwritten by merge:
        .ci/first_startup.sh
        .ci/flake8_blacklist.txt
        .ci/py3_sources.txt
        ........

If I do git status:

On branch release_17.05 Changes not staged for commit:   (use "git add/rm <file>..." to update what will be committed)   (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   .ci/check_controller.sh
        modified:   .ci/check_mako.sh
        modified:   .ci/first_startup.sh
        modified:   .ci/flake8_blacklist.txt
        modified:   .ci/py3_sources.txt
        modified:   .coveragerc
        modified:   .gitignore
        modified:   .travis.yml
        ....
        Untracked files:
        (use "git add <file>..." to include in what will be committed)

        FETCH_HEAD
        config/plugins/interactive_environments/jupyter/config/allowed_images.yml
        config/plugins/interactive_environments/rstudio/config/allowed_images.yml
        current_files.summary
        file_list.txt
        static/CDAworkflow.html
        static/CDAworkflow.xml
        static/Capture.PNG
        static/Einladung_Galaxy_03_04_2017.pdf
        static/FTP.pdf
        static/Homo_sapiens.GRCh38.86.gtf
        ......
        no changes added to commit (use "git add" and/or "git commit -a")

My question is which step should I perform before upgrade? Should I do git add -A && git commit first and than git pull or maybe better git stash, git pull and git stash pop??? I know only git basics and therefore I am not sure which step should I perform first?

Thanks, Marija

Body:
Doing git stash is a good option for this! You can execute these commands:

git stash           # saving your current working directory to the top of stash
git checkout release_17.05 && git pull --ff-only origin release_17.05
git stash apply     # getting back your changes previously stashed


问:
Conditional @HostBinding depending on @Input()
I'm trying to bind the CSS class foo to my host component, using @HostBinding depending on a test I do on a dynamic variable.
But can't manage to make it work properly.

Here's what I already tried:

```<code>export class MyComponent {
    @Input()
    public input: string;

    @HostBinding('class.foo')
    public isFoo: Boolean = this.inputIsCorrect();

    constructor() {
    }

    private inputIsCorrect(){
        return (this.input != 'not correct');
    }
}
</code>```

How I could make it work ? I was maybe thinking of way to listen to input changes ?

答:
What you did is almost correct : </p>

```<code>export class MyComponent {
    @Input()
    public input: string;

    @HostBinding('class.foo')
    public get isFoo(): Boolean {
        return this.input !== 'not correct';
    }

}
</code>```

Body:
I'm trying to bind the CSS class foo to my host component, using @HostBinding depending on a test I do on a dynamic variable.
But can't manage to make it work properly.

Here's what I already tried:

export class MyComponent {
    @Input()
    public input: string;

    @HostBinding('class.foo')
    public isFoo: Boolean = this.inputIsCorrect();

    constructor() {
    }

    private inputIsCorrect(){
        return (this.input != 'not correct');
    }
}

How I could make it work ? I was maybe thinking of way to listen to input changes ?

Body:
What you did is almost correct :

export class MyComponent {
    @Input()
    public input: string;

    @HostBinding('class.foo')
    public get isFoo(): Boolean {
        return this.input !== 'not correct';
    }

}


问:
Running bazel build with an aspect on test targets does not yield test output jars
running bazel build //... \
--aspects some-aspect.bzl%some_aspect \
--output_groups=some_new_output,default
 does not create test jars outputs.

on the other hand running bazel test does create the test jar outputs:

bazel test //... \
--aspects some-aspect.bzl%some_aspect \
--output_groups=some_new_output,default

How come?

This question was updated to reflect use of aspects:
The original question:

running bazel build //... does not add test code to output jar.

on the other hand bazel test //... builds the test code but also
  runs it.

Is there a way in bazel to build the test code without running the
  tests?

答:
I had a mistake in the values I gave the --output_groups flag.

It should have been --output_groups=+some_new_output,+default

The default can even be omitted:

--output_groups=+some_new_output

This flag is not documented at all. There is an open issue on this in bazel github repo.


问:
Change class property when set
I have the following class:

```<code>class Message {
    var content: [String]?

    init(content: [String]) {
        self.content = content
    }
}
</code>```

I want content to be an array of Strings, that are always uppercase. Even when lowercase text is set to content.
I don't seem to be able to use computed properties for this

答:
You can use a property observer didSet to apply uppercased() to the array when it is set:

```<code>class Message {
    var content: [String]? {
        didSet {
            if let arr = content {
                self.content = arr.map { $0.uppercased() }
            }
        }
    }

    init(content: [String]) {
        self.content = content.map { $0.uppercased() }
    }
}
</code>```

Title: Change class property when set

Body:
I have the following class:

class Message {
    var content: [String]?

    init(content: [String]) {
        self.content = content
    }
}

I want content to be an array of Strings, that are always uppercase. Even when lowercase text is set to content.
I don't seem to be able to use computed properties for this

Body:
You can use a property observer didSet to apply uppercased() to the array when it is set:

class Message {
    var content: [String]? {
        didSet {
            if let arr = content {
                self.content = arr.map { $0.uppercased() }
            }
        }
    }

    init(content: [String]) {
        self.content = content.map { $0.uppercased() }
    }
}


问:
Dynamically creating Buttons and setting onClickListener
I have problem with handling dynamically created Buttons on Android. I'm creating N buttons and I have to do the same method when button is clicked but I have to know which button is clicked.

```<code>for (int i = 0; i < NO_BUTTONS; i++){
        Button btn = new Button(this);
        btn.setId(2000+i);

        ...

        btn.setOnClickListener((OnClickListener) this);
        buttonList.addView(btn);
        list.add(btn);
</code>```

Cucurrently I'm adding ID to every button and I'm using the method below to see which button was clicked. (line btn.setId(2000+i); and btn.setOnClickListener((OnClickListener) this);). This method is also implemented in the activity.

```<code>@Override
public void onClick(View v) {
    switch (v.getId()){
        case 2000: selectButton(0);
        break;

        ...

        case 2007: selectButton(7);
        break;
    }
 }
</code>```

This doesn't look good to me so i'm asking is there some better way to do this? or how to send some information to onclick event? any suggestions?

答: I don't know why you would want to create N buttons, it looks like your value of N is greater than 10 at least, if you are not trying to show them all at once (I mean fit all of them into one single screen, no scrolling) you could try to recycle the invisible buttons just like we do for list view using a list view holder. This would reduce your memory footprint and boost performance, and differentiate the buttons based either on the text you set on them or a tag or you can even hold a reference to those small number of buttons.</p>

Body:
I have problem with handling dynamically created Buttons on Android. I'm creating N buttons and I have to do the same method when button is clicked but I have to know which button is clicked.

for (int i = 0; i < NO_BUTTONS; i++){
        Button btn = new Button(this);
        btn.setId(2000+i);

        ...

        btn.setOnClickListener((OnClickListener) this);
        buttonList.addView(btn);
        list.add(btn);

Cucurrently I'm adding ID to every button and I'm using the method below to see which button was clicked. (line btn.setId(2000+i); and btn.setOnClickListener((OnClickListener) this);). This method is also implemented in the activity.

@Override
public void onClick(View v) {
    switch (v.getId()){
        case 2000: selectButton(0);
        break;

        ...

        case 2007: selectButton(7);
        break;
    }
 }

This doesn't look good to me so i'm asking is there some better way to do this? or how to send some information to onclick event? any suggestions?


问:
K-means Clustering with R
I'm trying to cluster some data using K-means Clustering in R. The data to be clustered is a specific set of features from a sample of tweets. The tweets are labelled as either x or y. An example of the data is shown below, the usernames and IDs are removed, these fields are not used for clustering.

There is a total of 24.6k data items, with roughly 17k labelled y and the rest labelled x. What I would expect after clustering is two clusters, with roughly the corresponding amounts of data in each cluster. However, clustering seems to allocate the biggest majority of all the data to the same cluster, and only a few thousand items to the second cluster. The clustering results are below:

As you can see, almost all of the data is allocated to cluster 2.

I'm not sure what my problem is, it could either be an issue with the structure of my data or with my R implementation.

I have tried various different methods of both clustering and plotting, including ggplot2. This question was of some of use, but my results remained the same.

My R implementation is below. Note that the method of normalisation is taken from this answer. Can anyone point me in the right direction as to why my data is being allocated to the same cluster, even though I have two distinct labels?

Clustering.R

```<code>#Imports
library(jsonlite)
library(tm)
library(fpc)

#Includes
source("./Clustering_Functions.R")

#Program
rawData <- getInput()
clusterData <- filterData(rawData)
clusterData <- scaleData(clusterData)
aCluster <- performClustering(clusterData)
table(rawData$stance, aCluster$cluster)
plotOutput(clusterData, aCluster)
</code>```

Functions.R

```<code>getInput <- function() {
  json_file <- "path/file.json"

  #Set data to dataframe
  frame <- fromJSON(json_file)
  return(frame)
}

#Filter the raw data, remove columns not for clustering
filterData <- function(frame) {
  kcFrame <- frame[c( -3, -4, -9)]
  return (kcFrame)
}

#Scale the columns to uniform data, values 0-100
scaleData <- function(kcFrame) {
  doScale <- function(x) x* 100/max(x, na.rm = TRUE)
  kcFrame <- data.frame(lapply(kcFrame, doScale))
  return (kcFrame)
}

#Apply K-means clustering
performClustering <- function(kcFrame) {
  kc <- kmeans(kcFrame, centers = 2)
  return (kc)
}

#Graph the clusters
plotOutput <- function(kcFrame, kc) {
  plotcluster(kcFrame, kc$cluster)
}
</code>```

EDIT: I suspect that the problem lies with my data; that there isn't enough of a distinction between label x and y in terms of the features.

答:
Your implementations looks fine to me. Please consider, that it may very well be the structure of your data. It is not uncommon to see this kind of behavior. It is often the case that you have a majority and minority class/ cluster - think of it e.g. as one cluster originating from a "Healthy" distribution while the minority originates from the "Unhealthy" distribution (thinking in terms of diseases e.g.).

Also consider, that it is an unsupervised method, thus it just aims at uncovering the biggest difference in terms of the underlying data structure, this does not mean, that it is the relevant difference for your aims. Consider again having patients with a disease and without, if you cluster them with k-means it might very well be, that you will not get clusters according to healthy/ disease but rather male and female.

You could e.g. try to increase the number k or opt for a supervised/ semi-supervised clustering approach (there are quite a few options in R, Google is your friend there).

Title: K-means Clustering with R

Body:
I'm trying to cluster some data using K-means Clustering in R. The data to be clustered is a specific set of features from a sample of tweets. The tweets are labelled as either x or y. An example of the data is shown below, the usernames and IDs are removed, these fields are not used for clustering.

There is a total of 24.6k data items, with roughly 17k labelled y and the rest labelled x. What I would expect after clustering is two clusters, with roughly the corresponding amounts of data in each cluster. However, clustering seems to allocate the biggest majority of all the data to the same cluster, and only a few thousand items to the second cluster. The clustering results are below:

As you can see, almost all of the data is allocated to cluster 2.

I'm not sure what my problem is, it could either be an issue with the structure of my data or with my R implementation.

I have tried various different methods of both clustering and plotting, including ggplot2. This question was of some of use, but my results remained the same.

My R implementation is below. Note that the method of normalisation is taken from this answer. Can anyone point me in the right direction as to why my data is being allocated to the same cluster, even though I have two distinct labels?

Clustering.R

#Imports
library(jsonlite)
library(tm)
library(fpc)

#Includes
source("./Clustering_Functions.R")

#Program
rawData <- getInput()
clusterData <- filterData(rawData)
clusterData <- scaleData(clusterData)
aCluster <- performClustering(clusterData)
table(rawData$stance, aCluster$cluster)
plotOutput(clusterData, aCluster)

Functions.R

getInput <- function() {
  json_file <- "path/file.json"

  #Set data to dataframe
  frame <- fromJSON(json_file)
  return(frame)
}

#Filter the raw data, remove columns not for clustering
filterData <- function(frame) {
  kcFrame <- frame[c( -3, -4, -9)]
  return (kcFrame)
}

#Scale the columns to uniform data, values 0-100
scaleData <- function(kcFrame) {
  doScale <- function(x) x* 100/max(x, na.rm = TRUE)
  kcFrame <- data.frame(lapply(kcFrame, doScale))
  return (kcFrame)
}

#Apply K-means clustering
performClustering <- function(kcFrame) {
  kc <- kmeans(kcFrame, centers = 2)
  return (kc)
}

#Graph the clusters
plotOutput <- function(kcFrame, kc) {
  plotcluster(kcFrame, kc$cluster)
}

EDIT: I suspect that the problem lies with my data; that there isn't enough of a distinction between label x and y in terms of the features.


问:
Macro or Loop to conditional formatting

I need to repeat shown the conditional formatting to all the rows. There are lot of rows. The conditional icon is based on the first value of the cell and others shows according to it. How to achieve all this in one go.
My data ranging from C2:F792.

答:
Or you might even try Conditional Formatting:

[

Title: Macro or Loop to conditional formatting


问:
Beyond item-to-item recommendations
Simple item-to-item recommendation systems are well-known and frequently implemented. An example is the Slope One algorithm. This is fine if the user hasn't rated many items yet, but once they have, I want to offer more finely-grained recommendations. Let's take a music recommendation system as an example, since they are quite popular. If a user is viewing a piece by Mozart, a suggestion for another Mozart piece or Beethoven might be given. But if the user has made many ratings on classical music, we might be able to make a correlation between the items and see that the user dislikes vocals or certain instruments. I'm assuming this would be a two-part process, first part is to find correlations between each users' ratings, the second would be to build the recommendation matrix from these extra data. So the question is, are they any open-source implementations or papers that can be used for each of these steps?</p>

答:
There are two techniques that I can think of:

Train a feed-forward artificial neural net using Backpropagation or one of it's successors (e.g. Resilient Propagation).

Use version space learning. This starts with the most general and the most specific hypotheses about what the user likes and narrows them down when new examples are integrated. You can use a hierarchy of terms to describe concepts.

Common characteristics of these methods are:

You need a different function for
each user. This pretty much rules
out efficient database queries when
searching for recommendations.

The function can be updated on the fly
when the user votes for an item.

The dimensions along which you classify
the input data (e.g. has vocals, beats
per minute, musical scales,
whatever) are very critical to the
quality of the classification.

Please note that these suggestions come from university courses in knowledge based systems and artificial neural nets, not from practical experience.

Title: Beyond item-to-item recommendations


问:
How would I implement this fold function?
Given are the two datatypes Color and Plant.

```<code>data Color = Red | Pink | White | Blue | Purple | Green | Yellow
   deriving (Show, Eq)

data Plant =
     Leaf
   | Blossom Color
   | Stalk Plant Plant
   deriving (Show, Eq)
</code>```

Now I'm supposed to implement a function fold_plant of following type:

```<code>(x -> x -> x) -> (Color -> x) -> x -> Plant -> x
</code>```

The way I understand a fold function is that it takes a list and for each iteration it removes the first element from the list and does something with that element.

Apparently fold_plant Stalk Blossom Leaf is the identity on plants.

Now I know that in Haskell you make functions like this:

```<code>fold_plant :: (x -> x -> x) -> (Color -> x) -> x -> Plant -> x
fold_plant = do something
</code>```

But from here on I don't know how a fold function would work an a plant.

答:
A fold is a function that takes a piece of data in a structure, and collapses it to another piece of data. Usually we do this to "reduce" a collection to a single value. That's why if you look at other languages like Lisp, Smalltalk, Ruby, JavaScript, etc you'll find this operation called reduce, which is the poor cousin of folding in Haskell.

I say it's the poor cousin because your intuition on lists is correct, but in Haskell we're much more abstract and general, so our fold functions can work on any kind of structure whose type we've told haskell what fold means for.

So, we can talk about "using addition with fold to turn a list of numbers into a sum value", or we can talk about "using a function to take a family tree of names and collapse it to a list", and so on and so forth. Any time we have this idea of changing the structure of something to a single value, or maybe to a different structured set of values, that's folding.

The "canonical" way to represent this in Haskell is foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b but it's easier like you've thought to use "a list of a" as the Foldable f => t a type at the beginning coz it's a bit easier to understand. So we have a specialised type of foldr :: (a -> b -> b) -> b -> [a] -> b. But what are a and b ? and what is (a -> b -> b) and what do these three arguments do?

Let's specialise it to Int values for both a and b: foldr :: (Int -> Int -> Int) -> Int -> [Int] -> Int wow... that makes it ... interesting doesn't it? so foldr takes a function of two ints, like, say, the (+) function, and it takes a single Int value (this is the initial value it will use as the target result, and a list of Int values... then it'll produce a single Int from that... that is, it takes that Int -> Int -> Int function and applies it to the single Int and the first of the [Int], then applies that function to that result and the next value of the [Int] and so on and so forth until there are no more [Int] left... then that's what it returns.

It's quite literally folding the function over the data structure.

That's all well and good for lists, which are a single straight line, but what you have is a tree, not a list. So how does it work there? Well, let's see how we might specialise foldr to produce a pair of the highest and lowest numbers from a list of Int instead? foldr :: (Int -> (Int, Int) -> (Int, Int)) -> (Int, Int) -> [Int] -> (Int, Int). So we take a function that takes an Int and a pair, and we put the initial pair into it, along with the first Int from our [Int]. That returns us a new pair, and we then do the same process for the next of the [Int] and then we continue that process untill all we're left with is a pair at the end.

foldToMinMax = foldr (\newNum (minnum,maxnum) -> (min minnum newNum, max maxnum newNum)) (maxBound :: Int, minBound :: Int)

So now things are getting a little bit clearer.

What about this tree of flowers you have, though? Well, you need to write yourself a folding function that will take two values, one of which will be the same value as the initial value and the result value, and the other of which will be the type of your tree, and build a value of the result type. If I were to use pseudo code to write the types in a more descriptive way, I'd probably write something like: foldr :: (contentOfCollectionType -> resultType -> resultType) -> resultType -> (collectionWrapper contentOfCollectionType) -> resultType

But you don't have to use foldr here, in fact you can't use it unless you do some fancy typeclass instantiation stuff anyway. You can totally write your own folding function using plain recursion. That's what they're after.

If you want to learn about recursion and folding and whatnot, and you don't understand these things yet, I recommend the book I helped author. http://happylearnhaskelltutorial.com It explains it in much more detail and with many clear examples. If you understand the basics, it should be pretty quick to get up to speed on the point where you want to know about recursion and folding... but if you don't, well it's going to be very useful for you to understand the basics because you need to know them before getting to the other stuff.

I should mention that your particular fold also has a conversion function in it. It's the thing that converts a Color to an x. The function that you were given to work with as a folding function "crushes x's together" (ie takes two x values and produces another x value, very similar to (+) in our examples above). It can only work on trees because we also give it this function to turn a Color into an x, which effectively takes the meaningful data out of the tree and puts it into a form that the folding function can use.

There's a very beautiful pattern at work here.

Good luck!

Body:
Given are the two datatypes Color and Plant.

data Color = Red | Pink | White | Blue | Purple | Green | Yellow
   deriving (Show, Eq)

data Plant =
     Leaf
   | Blossom Color
   | Stalk Plant Plant
   deriving (Show, Eq)

Now I'm supposed to implement a function fold_plant of following type:

(x -> x -> x) -> (Color -> x) -> x -> Plant -> x

The way I understand a fold function is that it takes a list and for each iteration it removes the first element from the list and does something with that element.

Apparently fold_plant Stalk Blossom Leaf is the identity on plants.

Now I know that in Haskell you make functions like this:

fold_plant :: (x -> x -> x) -> (Color -> x) -> x -> Plant -> x
fold_plant = do something

But from here on I don't know how a fold function would work an a plant.


问:
Ambiguous Authentication in Netsuite Token Based API call
I am trying to make SOAP calls to the Netsuite API using Token Based Authentication. I have a C# client that is generated from WDSL and it is sending the following request (with the secrets replaced).

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:messages_2016_2.platform.webservices.netsuite.com" xmlns:urn1="urn:core_2016_2.platform.webservices.netsuite.com">
   <soapenv:Header>
      <urn:partnerInfo>
         <urn:partnerId>[MyAccountId]</urn:partnerId>
      </urn:partnerInfo>
      <urn:applicationInfo>
         <urn:applicationId>[MyApplicationId]</urn:applicationId>
      </urn:applicationInfo>
      <urn:tokenPassport>
         <urn1:account>[MyAccountId]</urn1:account>
         <urn1:consumerKey>[MyConsumerKey]</urn1:consumerKey>
         <urn1:token>[MyTokenId]</urn1:token>
         <urn1:nonce>1574515852</urn1:nonce>
         <urn1:timestamp>1499135589</urn1:timestamp>
         <urn1:signature algorithm="HMAC-SHA1">Ll8DbLvTWsBh/G7UtenErR03OrM=</urn1:signature>
      </urn:tokenPassport>
   </soapenv:Header>
   <soapenv:Body>
      <urn:getDataCenterUrls>
         <urn:account>[MyAccountId]</urn:account>
      </urn:getDataCenterUrls>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

I am getting the following response

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <soapenv:Fault>
         <faultcode>soapenv:Server.userException</faultcode>
         <faultstring>Ambiguous authentication</faultstring>
         <detail>
            <platformFaults:invalidCredentialsFault xmlns:platformFaults="urn:faults_2016_2.platform.webservices.netsuite.com">
               <platformFaults:code>USER_ERROR</platformFaults:code>
               <platformFaults:message>Ambiguous authentication</platformFaults:message>
            </platformFaults:invalidCredentialsFault>
            <ns1:hostname xmlns:ns1="http://xml.apache.org/axis/">partners-java20004.sea.netledger.com</ns1:hostname>
         </detail>
      </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

I have tried lots of different ways of generating the signature, nonce and timestamp. Currently I have the following:

```<code>private string computeNonce()
{
    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
    byte[] data = new byte[20];
    rng.GetBytes(data);
    int value = Math.Abs(BitConverter.ToInt32(data, 0));
    return value.ToString();
}

private long computeTimestamp()
{
    return ((long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
}

private TokenPassportSignature computeSignature(string accountId, string consumerKey, string consumerSecret, string tokenId, string tokenSecret, string nonce, long timestamp)
{
    string baseString = accountId + "&" + consumerKey + "&" + tokenId + "&" + nonce + "&" + timestamp;
    string key = consumerSecret + "&" + tokenSecret;
    string signature = "";
    var encoding = new System.Text.ASCIIEncoding();
    byte[] keyBytes = encoding.GetBytes(key);
    byte[] baseStringBytes = encoding.GetBytes(baseString);
    using (var hmacSha1 = new HMACSHA1(keyBytes))
    {
        byte[] hashBaseString = hmacSha1.ComputeHash(baseStringBytes);
        signature = Convert.ToBase64String(hashBaseString);
    }
    TokenPassportSignature sign = new TokenPassportSignature();
    sign.algorithm = "HMAC-SHA1";
    sign.Value = signature;
    return sign;
}
</code>```

Does anyone have any ideas? Thanks!

答: Remove the passport.  Sadly, NetSuite fails if you have this in the code when using Token Auth. :/ </p>

Body:
I am trying to make SOAP calls to the Netsuite API using Token Based Authentication. I have a C# client that is generated from WDSL and it is sending the following request (with the secrets replaced).

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:messages_2016_2.platform.webservices.netsuite.com" xmlns:urn1="urn:core_2016_2.platform.webservices.netsuite.com">
   <soapenv:Header>
      <urn:partnerInfo>
         <urn:partnerId>[MyAccountId]</urn:partnerId>
      </urn:partnerInfo>
      <urn:applicationInfo>
         <urn:applicationId>[MyApplicationId]</urn:applicationId>
      </urn:applicationInfo>
      <urn:tokenPassport>
         <urn1:account>[MyAccountId]</urn1:account>
         <urn1:consumerKey>[MyConsumerKey]</urn1:consumerKey>
         <urn1:token>[MyTokenId]</urn1:token>
         <urn1:nonce>1574515852</urn1:nonce>
         <urn1:timestamp>1499135589</urn1:timestamp>
         <urn1:signature algorithm="HMAC-SHA1">Ll8DbLvTWsBh/G7UtenErR03OrM=</urn1:signature>
      </urn:tokenPassport>
   </soapenv:Header>
   <soapenv:Body>
      <urn:getDataCenterUrls>
         <urn:account>[MyAccountId]</urn:account>
      </urn:getDataCenterUrls>
   </soapenv:Body>
</soapenv:Envelope>

I am getting the following response

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <soapenv:Fault>
         <faultcode>soapenv:Server.userException</faultcode>
         <faultstring>Ambiguous authentication</faultstring>
         <detail>
            <platformFaults:invalidCredentialsFault xmlns:platformFaults="urn:faults_2016_2.platform.webservices.netsuite.com">
               <platformFaults:code>USER_ERROR</platformFaults:code>
               <platformFaults:message>Ambiguous authentication</platformFaults:message>
            </platformFaults:invalidCredentialsFault>
            <ns1:hostname xmlns:ns1="http://xml.apache.org/axis/">partners-java20004.sea.netledger.com</ns1:hostname>
         </detail>
      </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>

I have tried lots of different ways of generating the signature, nonce and timestamp. Currently I have the following:

private string computeNonce()
{
    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
    byte[] data = new byte[20];
    rng.GetBytes(data);
    int value = Math.Abs(BitConverter.ToInt32(data, 0));
    return value.ToString();
}

private long computeTimestamp()
{
    return ((long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
}

private TokenPassportSignature computeSignature(string accountId, string consumerKey, string consumerSecret, string tokenId, string tokenSecret, string nonce, long timestamp)
{
    string baseString = accountId + "&" + consumerKey + "&" + tokenId + "&" + nonce + "&" + timestamp;
    string key = consumerSecret + "&" + tokenSecret;
    string signature = "";
    var encoding = new System.Text.ASCIIEncoding();
    byte[] keyBytes = encoding.GetBytes(key);
    byte[] baseStringBytes = encoding.GetBytes(baseString);
    using (var hmacSha1 = new HMACSHA1(keyBytes))
    {
        byte[] hashBaseString = hmacSha1.ComputeHash(baseStringBytes);
        signature = Convert.ToBase64String(hashBaseString);
    }
    TokenPassportSignature sign = new TokenPassportSignature();
    sign.algorithm = "HMAC-SHA1";
    sign.Value = signature;
    return sign;
}

Does anyone have any ideas? Thanks!


问:
JSQMessageData append Json data
I am trying to add json values in JSQMessageData to show the message on JSQMessagesViewController. The view is set up and this the lite chat(can chat only once).We use an api to send and receive messages. The problem is when I fetched data from api as json it returns the value. I want to append that json data to the rest of my JSQMessages objects, I tried the last few days and have failed to accomplish this. Here is the full code and json response.

```<code>    APIHandler.requestGETURL(urlString, success: { (JSON) in
        print(JSON)

        // var messageDictionary : [JSQMessageData] = []
        // this is the message object
        // i want to add the json data to my messageDictionary
        // reload collection view

        /*
         {
         "message_time" : "27-05-2017",
         "user_id" : 1924,
         "user_name" : "Tester name",
         "message" : "hi",
         "user_thumb" : "<image_path>"
         },
         {
         "message_time" : "27-05-2017",
         "user_id" : 1924,
         "user_name" : "Tester name",
         "message" : "how are you?",
         "user_thumb" : "<image_path>"
         }
         */

        // i want to
      let arrayNames =  JSON["data"]
      self.messageDictionary.append(JSQMessageData())
      // I am stuck here
    }) { (Error) in
        print(Error.localizedDescription)
    }
</code>```

答:
@Daniel is saying right, your json is enough simple that you don't need to add any JSQMessageData and maybe you are actually doing some extra effort, i have faced similar kind of problem when i need to pass a NSDictionary object with JSQMessage Objects so i used a tricky way for doing that ( and it works perfectly fine :) )

not sure about your case but this helps me a lot in many situations so follow these steps :

convert your json data into string

now save this json string into the accessebilityHint property of JSQmessage object. like -

(jsqmessageObj).accessibilityHint = jsonString

as according to your need as you want to use this json just extract the JSQmessage Object (like in cellForRowAtIndexPath ! ) , just use (jsqmessageObj).accessibilityHint to get back your json string decode it and use it as your need.

like - strJson = (jsqmessageObj).accessibilityHint

Hope this will help :p

Title: JSQMessageData append Json data

Body:
I am trying to add json values in JSQMessageData to show the message on JSQMessagesViewController. The view is set up and this the lite chat(can chat only once).We use an api to send and receive messages. The problem is when I fetched data from api as json it returns the value. I want to append that json data to the rest of my JSQMessages objects, I tried the last few days and have failed to accomplish this. Here is the full code and json response.

    APIHandler.requestGETURL(urlString, success: { (JSON) in
        print(JSON)

        // var messageDictionary : [JSQMessageData] = []
        // this is the message object
        // i want to add the json data to my messageDictionary
        // reload collection view

        /*
         {
         "message_time" : "27-05-2017",
         "user_id" : 1924,
         "user_name" : "Tester name",
         "message" : "hi",
         "user_thumb" : "<image_path>"
         },
         {
         "message_time" : "27-05-2017",
         "user_id" : 1924,
         "user_name" : "Tester name",
         "message" : "how are you?",
         "user_thumb" : "<image_path>"
         }
         */

        // i want to
      let arrayNames =  JSON["data"]
      self.messageDictionary.append(JSQMessageData())
      // I am stuck here
    }) { (Error) in
        print(Error.localizedDescription)
    }


问:
Python OpenCV open window on top of other applications
When executing an OpenCV python script containing: cv2.imshow(img) the resulting window opens behind my terminal window. This is a mild irritation - is there any way to get it to initially open in front / on top?

A number of people have asked questions (here and here) about forcing persistent behaviour but this is, I think, simpler.

Platform OS X and OpenCV 2.4.11

答:
One way to work around this would be to set all windows from OpenCV "frontmost" using AppleScript.

```<code>subprocess.call(["/usr/bin/osascript", "-e", 'tell app "Finder" to set frontmost of process "Python" to true'])
</code>```

This way, all windows should be brought to the front.

Body:
One way to work around this would be to set all windows from OpenCV "frontmost" using AppleScript.

subprocess.call(["/usr/bin/osascript", "-e", 'tell app "Finder" to set frontmost of process "Python" to true'])

This way, all windows should be brought to the front.


问:
how to check mysql for duplicates with php
I need a way to check a database if a word is in it already if so then it doesn't have to be pushed to the database if the word isn't in it yet then it has to be  pushed into it.

It's a MYSQL database and I have to do it in PHP this is what I got so far.

```<code>$result = array_count_values(explode(" ", $filter));
arsort($result);
foreach ($result as $word => $frequency)
{
    if (!in_array($word, [" ", ""]))
        query("words", "INSERT INTO Woord (woord) VALUE (?)",[$word], false);
}
query("words" "SELECT WHERE")
</code>```

答:
put a unique constraint on the column "woord" in the table.
Then you can let your php script insert as many duplicate words as you want to, it will simply fail.

you could either add a part "ignore duplicate" in your query or just ignore the error you will get.

I thinks that will be easiest to do.

edit:
btw I can think of a lot of words containing serveral of the character you are stripping: "foto's", "zee-eend" etc

--

how to make a unique index:

```<code>ALTER TABLE asciiwoorden
    ADD UNIQUE INDEX somename (Woord);
</code>```

Body:
I need a way to check a database if a word is in it already if so then it doesn't have to be pushed to the database if the word isn't in it yet then it has to be  pushed into it.

It's a MYSQL database and I have to do it in PHP this is what I got so far.

$result = array_count_values(explode(" ", $filter));
arsort($result);
foreach ($result as $word => $frequency)
{
    if (!in_array($word, [" ", ""]))
        query("words", "INSERT INTO Woord (woord) VALUE (?)",[$word], false);
}
query("words" "SELECT WHERE")

Body:
put a unique constraint on the column "woord" in the table.
Then you can let your php script insert as many duplicate words as you want to, it will simply fail.

you could either add a part "ignore duplicate" in your query or just ignore the error you will get.

I thinks that will be easiest to do.

edit:
btw I can think of a lot of words containing serveral of the character you are stripping: "foto's", "zee-eend" etc

--

how to make a unique index:

ALTER TABLE asciiwoorden
    ADD UNIQUE INDEX somename (Woord);


问:
Redux-React: value returned by a dispatch function is not being passed to child component
I am new to react-redux actually so I just need some help trying to understand any syntactical or logical mistake I am making here...

Basically, I want to display the reports fetched from another server. Function 'fetchNames' handles that and function 'fetchdownloadable' creates a returns a link that allows to pass through authentication and download the report in pdf onClick.

So I debugged on console, and I believe that there is something wrong with the order of execution of the code... when i debug.. i noticed that :
fetchnames is executed first to fetch all report data in json array...
then fetchDownloadable is called for each object in the reports array and that returns 'undefined' value on SampleChild...
then SampleChild is executed with undefined value...
and then we come back to execute the fetchDownloadable function that prints link value on the console and dispatches action on the reducer that returns the 'state' instead of 'action.reports_uri' in the reducer...

Thanks in advance!

SampleParent.js

```<code>import React, {Component} from 'react'
import { connect } from 'react-redux'
import { fetchNames, fetchDownloadable } from '../../actions/actions'
import SampleChild from '../ui/SampleChild'
class SampleParent extends Component {
constructor(props) {
    super(props);
    this.fetchDownloadLink = this.fetchDownloadLink.bind(this)
}
componentDidMount() {
    const { dispatch } = this.props
    dispatch(fetchNames())
}
fetchDownloadLink(uri){
    this.props.dispatch(fetchDownloadable(uri))
}
render() {
    return (<div><ul id="myUL">
                {this.props.reports.map((report) => (
                    <li><SampleChild
                            key={report.id}
                            label={report.label}
                            uri={this.fetchDownloadLink("http://localhost:8080/sample"+report.uri+".pdf")}
                        /></li>))}
            </ul></div>
    )}
}
function mapStateToProps(state) {
const { reports } = state
return {
    reports
}}
export default connect(mapStateToProps)(SampleParent)
</code>```

SampleChild.js

```<code>import React, { Component } from 'react'
export default class SampleChild extends Component {
render() {
    const { key, label, uri } = this.props
    return (
    <div className="inside_SampleChild" id={label}>
        {label}
        <a href={uri}><img src="../images/pdf-file_128.png" height="25px" width="25px"></img></a>
    </div>
    )}}
</code>```

Action.js

```<code>import C from '../constants'
import fetch from 'isomorphic-fetch'

export const fetchNames = value => dispatch => {
var obj = { method: 'GET', headers: { 'Authorization': 'Basic ***', 'Accept': 'application/json' },
    'credentials': 'include'};
fetch('http://localhost:8080/samplelink', obj)
    .then(response => {
        if (response.status !== 200) {
            throw Error(response.status);
        }return response;})
    .then((response) => response.json())
    .then(resourceLookup => {
        var arr = [];
        var length = resourceLookup.resourceLookup.length;
        for(var i = 0 ; i< length ; i++){
            arr.push(resourceLookup.resourceLookup[i]);}
        dispatch({
            type: C.FETCH_LIST_REPORTS,
            reports: arr})}).
catch(error => {
    console.log("There was this  error" + error);});}

export const fetchReportDownloadable = (uri) => dispatch => {
var obj = {
    method: 'GET',
    headers: {
        'Authorization': 'Basic ***=',
        'Accept': 'application/json'
    },
    'credentials': 'include'
};
fetch(uri, obj)
    .then(response => {
        if (response.status !== 200) {
            throw Error(response.status);
        }
        return response ;
    })
    .then((response) => response)
    .then(resourceLookup => {
        console.log(`resourceLookup URL: ${resourceLookup.url}`)
        dispatch({
            type: C.FETCH_DOWNLOADABLE,
            report_uri: resourceLookup.url
        })
    }).
catch(error => {
    console.log("There was this  error" + error);
});}
</code>```

Reducers.js

```<code>import C from '../constants'
import { combineReducers } from 'redux'
export const links = (state=null, action) =>
(action.type === C.FETCH_DOWNLOADABLE) ?
    action.report_uri :
    state
export const reports = (state=[], action) => {
switch(action.type) {
    case C.FETCH_LIST_REPORTS :
        return action.reports
    default :
        return state
}}
const rootReducer = combineReducers({
reports,
links
})
export default rootReducer
</code>```

答:
I will try explaining what is happening.

First, the first problem you have is that your passing a wrong value, or either undefined value of uri in:

```<code><li>
  <SampleChild key={report.id} label={report.label}
     uri={this.fetchDownloadLink("http://localhost:8080/sample"+report.uri+".pdf")}
                        />
</li>
</code>```

Here uri is a function, that triggers on the first render, it dispatches the fetchDownloadable(uri) action, it does not return any value however. Hence the uri is undefined.

Secondly, you have C.FETCH_REPORT_DOWNLOADABLE constant used in your reducer. However you never dispatch an action of that type, the action dispatches C.FETCHING_DOWNLOADABLE. Hence the reducer does not do anything really, so the state does not change. My second comment was about C.FETCH_LIST_REPORTS, which is irrelevant for you right now, so I was wrong about that.

What I would do, is create the download link from the server side. Send it back with the report object. This way, you won't need to dispatch two actions to list your reports. Then, I will dispatch my action in componentWillMount(), once it's done fetching the data, the state will be changed - if, again, you have dispatched the correct action - and you will have your reports with the download URL in the same object.

Update

Okay I think that I understand now. What I would do then is to send the uri as string to SampleChild, and then when it mounts I will trigger the fetchDownloadablefunction.

SampleParent

```<code>import React, {Component} from 'react'
import { connect } from 'react-redux'
import { fetchNames, fetchReportDownloadable } from '../../actions/actions'
import SampleChild from '../ui/SampleChild'
class SampleParent extends Component {
constructor(props) {
    super(props);
    this.fetchDownloadLink = this.fetchDownloadLink.bind(this)
}
componentDidMount() {
    const { dispatch } = this.props
    dispatch(fetchNames())
}
fetchDownloadLink(uri){
    this.props.dispatch(fetchReportDownloadable(uri))
}
render() {
    return (<div><ul id="myUL">
                {this.props.reports.map((report) => (
                    <li><SampleChild
                            key={report.id}
                            label={report.label}
                 uri={"http://localhost:8080/sample"+report.uri+".pdf"}
                 download={this.fetchDownloadLink}
                    /></li>))}
            </ul></div>
    )}
}
function mapStateToProps(state) {
const { reports } = state
return {
    reports
}}
export default connect(mapStateToProps)(SampleParent)
</code>```

SampleChild

```<code>import React, { Component } from 'react'
export default class SampleChild extends Component {
componentDidMount() {
    this.props.download(this.props.uri);
}
render() {
    const { key, label, uri } = this.props
    return (
    <div className="inside_SampleChild" id={label}>
        {label}
        <a href={uri}><img src="../images/pdf-file_128.png" height="25px" width="25px"></img></a>
    </div>
    )}}
</code>```

What is supposed to happen now is that you will fetch the reports first in SampleParent then pass the information to SampleChild. Whenever a SampleChild is mounted, it will trigger fetchDownloadable action which in returns download the uri sent to it.

Body:
I am new to react-redux actually so I just need some help trying to understand any syntactical or logical mistake I am making here...

Basically, I want to display the reports fetched from another server. Function 'fetchNames' handles that and function 'fetchdownloadable' creates a returns a link that allows to pass through authentication and download the report in pdf onClick.

So I debugged on console, and I believe that there is something wrong with the order of execution of the code... when i debug.. i noticed that :
fetchnames is executed first to fetch all report data in json array...
then fetchDownloadable is called for each object in the reports array and that returns 'undefined' value on SampleChild...
then SampleChild is executed with undefined value...
and then we come back to execute the fetchDownloadable function that prints link value on the console and dispatches action on the reducer that returns the 'state' instead of 'action.reports_uri' in the reducer...

Thanks in advance!

SampleParent.js

import React, {Component} from 'react'
import { connect } from 'react-redux'
import { fetchNames, fetchDownloadable } from '../../actions/actions'
import SampleChild from '../ui/SampleChild'
class SampleParent extends Component {
constructor(props) {
    super(props);
    this.fetchDownloadLink = this.fetchDownloadLink.bind(this)
}
componentDidMount() {
    const { dispatch } = this.props
    dispatch(fetchNames())
}
fetchDownloadLink(uri){
    this.props.dispatch(fetchDownloadable(uri))
}
render() {
    return (

                {this.props.reports.map((report) => (

<SampleChild
                            key={report.id}
                            label={report.label}
                            uri={this.fetchDownloadLink("http://localhost:8080/sample"+report.uri+".pdf")}
                        />
))}

    )}
}
function mapStateToProps(state) {
const { reports } = state
return {
    reports
}}
export default connect(mapStateToProps)(SampleParent)

SampleChild.js

import React, { Component } from 'react'
export default class SampleChild extends Component {
render() {
    const { key, label, uri } = this.props
    return (

        {label}

    )}}

Action.js

import C from '../constants'
import fetch from 'isomorphic-fetch'

export const fetchNames = value => dispatch => {
var obj = { method: 'GET', headers: { 'Authorization': 'Basic ***', 'Accept': 'application/json' },
    'credentials': 'include'};
fetch('http://localhost:8080/samplelink', obj)
    .then(response => {
        if (response.status !== 200) {
            throw Error(response.status);
        }return response;})
    .then((response) => response.json())
    .then(resourceLookup => {
        var arr = [];
        var length = resourceLookup.resourceLookup.length;
        for(var i = 0 ; i< length ; i++){
            arr.push(resourceLookup.resourceLookup[i]);}
        dispatch({
            type: C.FETCH_LIST_REPORTS,
            reports: arr})}).
catch(error => {
    console.log("There was this  error" + error);});}

export const fetchReportDownloadable = (uri) => dispatch => {
var obj = {
    method: 'GET',
    headers: {
        'Authorization': 'Basic ***=',
        'Accept': 'application/json'
    },
    'credentials': 'include'
};
fetch(uri, obj)
    .then(response => {
        if (response.status !== 200) {
            throw Error(response.status);
        }
        return response ;
    })
    .then((response) => response)
    .then(resourceLookup => {
        console.log(`resourceLookup URL: ${resourceLookup.url}`)
        dispatch({
            type: C.FETCH_DOWNLOADABLE,
            report_uri: resourceLookup.url
        })
    }).
catch(error => {
    console.log("There was this  error" + error);
});}

Reducers.js

import C from '../constants'
import { combineReducers } from 'redux'
export const links = (state=null, action) =>
(action.type === C.FETCH_DOWNLOADABLE) ?
    action.report_uri :
    state
export const reports = (state=[], action) => {
switch(action.type) {
    case C.FETCH_LIST_REPORTS :
        return action.reports
    default :
        return state
}}
const rootReducer = combineReducers({
reports,
links
})
export default rootReducer

Body:
I will try explaining what is happening.

First, the first problem you have is that your passing a wrong value, or either undefined value of uri in:

<li>
  <SampleChild key={report.id} label={report.label}
     uri={this.fetchDownloadLink("http://localhost:8080/sample"+report.uri+".pdf")}
                        />
</li>

Here uri is a function, that triggers on the first render, it dispatches the fetchDownloadable(uri) action, it does not return any value however. Hence the uri is undefined.

Secondly, you have C.FETCH_REPORT_DOWNLOADABLE constant used in your reducer. However you never dispatch an action of that type, the action dispatches C.FETCHING_DOWNLOADABLE. Hence the reducer does not do anything really, so the state does not change. My second comment was about C.FETCH_LIST_REPORTS, which is irrelevant for you right now, so I was wrong about that.

What I would do, is create the download link from the server side. Send it back with the report object. This way, you won't need to dispatch two actions to list your reports. Then, I will dispatch my action in componentWillMount(), once it's done fetching the data, the state will be changed - if, again, you have dispatched the correct action - and you will have your reports with the download URL in the same object.

Update

Okay I think that I understand now. What I would do then is to send the uri as string to SampleChild, and then when it mounts I will trigger the fetchDownloadablefunction.

SampleParent

import React, {Component} from 'react'
import { connect } from 'react-redux'
import { fetchNames, fetchReportDownloadable } from '../../actions/actions'
import SampleChild from '../ui/SampleChild'
class SampleParent extends Component {
constructor(props) {
    super(props);
    this.fetchDownloadLink = this.fetchDownloadLink.bind(this)
}
componentDidMount() {
    const { dispatch } = this.props
    dispatch(fetchNames())
}
fetchDownloadLink(uri){
    this.props.dispatch(fetchReportDownloadable(uri))
}
render() {
    return (<div><ul id="myUL">
                {this.props.reports.map((report) => (
                    <li><SampleChild
                            key={report.id}
                            label={report.label}
                 uri={"http://localhost:8080/sample"+report.uri+".pdf"}
                 download={this.fetchDownloadLink}
                    /></li>))}
            </ul></div>
    )}
}
function mapStateToProps(state) {
const { reports } = state
return {
    reports
}}
export default connect(mapStateToProps)(SampleParent)

SampleChild

import React, { Component } from 'react'
export default class SampleChild extends Component {
componentDidMount() {
    this.props.download(this.props.uri);
}
render() {
    const { key, label, uri } = this.props
    return (
    <div className="inside_SampleChild" id={label}>
        {label}
        <a href={uri}><img src="../images/pdf-file_128.png" height="25px" width="25px"></img></a>
    </div>
    )}}

What is supposed to happen now is that you will fetch the reports first in SampleParent then pass the information to SampleChild. Whenever a SampleChild is mounted, it will trigger fetchDownloadable action which in returns download the uri sent to it.


答:
Did you read the documentation of time.Parse? In the very beginning it says:

The layout defines the format by showing how the reference time,
  defined to be Mon Jan 2 15:04:05 -0700 MST 2006 would be interpreted
  if it were the value

In the beginning of the package documentation there are more details about the layout string. Note that you can omit some of the fields (in your case days, years and timezeone) and those will then always get zero value.

So fmt.Println(time.Parse("3:04 PM", "07:50 PM")) should work.

Title: How to use time.Parse to parse hh:mm format in Go

Body:
I am importing a lot of fields of the format:

09:02 AM

10:02 AM

12:30 PM

04:10 PM

04:50 PM

05:30 PM

I would like to convert the fields into something I can do arithmetic on. For example, do a count down to when the event Occurs.  Thus, saving the field in microseconds... or even seconds.
I have been trying to get the time.Parse to work...   no joy.

fmt.Println(time.Parse("hh:mm", m.Feed.Entry[i].GsxA100Time.T))

returns...

0001-01-01 00:00:00 +0000 UTC parsing time "07:50 PM" as "hh:mm": cannot parse "07:50 PM" as "hh:mm"

any suggestions?


问:
Deploying birt war in karaf
I have karaf 4.1.1 and birt runtime 4.5.0 on my server. I have problems deploying birt.war in karaf. My purpose is using birt report engine api in karaf to generete reports based on birt project files.

I instaled karaf war feature. But I'm unable to install birt. I tried to type in karaf shell:

bundle:install -s "C:\birt-runtime-4_5_0\birt.war?Bundle-SymbolicName=birt&Web-ContextPath=/sample"

I got:
org.osgi.framework.BundleException: Unable to cache bundle

Any suggestions?

答:
Try to install your component using webbundle prefix.

Simply, tap the following command in your running Karaf instance:

```<code>bundle:install webbundle:file:///C:/birt-runtime-4_5_0/birt.war?Bundle-SymbolicName=birt&Web-ContextPath=/sample
</code>```

Title: Deploying birt war in karaf

Body:
Try to install your component using webbundle prefix.

Simply, tap the following command in your running Karaf instance:

bundle:install webbundle:file:///C:/birt-runtime-4_5_0/birt.war?Bundle-SymbolicName=birt&Web-ContextPath=/sample


问:
PHP => $_SESSION Array only keeps last variable
I'm building an interface for an online shop, where every item is a FORM and the BUY button is a submit,it submits the name and price of the clicked form and that data is displayed on a CONFIRM ORDER page. On that confirm order page I've created an array as follows

```<code>if (!isset($input_order_arr)) {
  $input_order_arr = array();
}
</code>```

After that I fetch the posted variables and push them into the array

```<code>if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  if (!empty($_POST['item-title'])  && !empty($_POST['item-price'])) {
    $item_title = test_input($_POST['item-title']);
    $item_price = test_input($_POST['item-price']);
    array_push($input_order_arr,$item_title,$item_price);
  }
}

$_SESSION['chosen_item'] = $input_order_arr;
</code>```

*NOTE : test_input is a function that does striplashes , htmlspecialchars and htmltrim, for security purposes. (someone might edit the value of the item via the Chrome developer console? not sure if that holds any threat though)

And after that the value is displayed in a table like so

```<code>              <?php if (isset($_SESSION['chosen_item'])) {
                foreach ($_SESSION['chosen_item'] as $value) {
                  echo "<td>" . $value . "</td>";
                }
              }  ?>
</code>```

And here comes the problem.

If you order an item its price and name are displayed, but if u go back and you order another item, the previous item and its price are lost, as if its not adding new lines to the array,but replacing the old ones, or the session only saves data from one action, which wouldn't make any sense, since thats what $_SESSION is about, the code is presented with session_start(); in every page that is using the $_SESSION variable.

 Main Question - Why could it be that the $_SESSION Array is losing its older inputs?

答:
you need $_SESSION['chosen_item'][]=$input_order_arr; your overwriting the same index  instead of creating new one

```<code>$_SESSION['chosen_item'][]=$input_order_arr;
</code>```

Note : And also it should be moved inside the if statement .to avoid empty array storing in session

Body:
I'm building an interface for an online shop, where every item is a FORM and the BUY button is a submit,it submits the name and price of the clicked form and that data is displayed on a CONFIRM ORDER page. On that confirm order page I've created an array as follows

if (!isset($input_order_arr)) {
  $input_order_arr = array();
}

After that I fetch the posted variables and push them into the array

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  if (!empty($_POST['item-title'])  && !empty($_POST['item-price'])) {
    $item_title = test_input($_POST['item-title']);
    $item_price = test_input($_POST['item-price']);
    array_push($input_order_arr,$item_title,$item_price);
  }
}

$_SESSION['chosen_item'] = $input_order_arr;

*NOTE : test_input is a function that does striplashes , htmlspecialchars and htmltrim, for security purposes. (someone might edit the value of the item via the Chrome developer console? not sure if that holds any threat though)

And after that the value is displayed in a table like so

              <?php if (isset($_SESSION['chosen_item'])) {
                foreach ($_SESSION['chosen_item'] as $value) {
                  echo "" . $value . "	";
                }
              }  ?>

And here comes the problem.

If you order an item its price and name are displayed, but if u go back and you order another item, the previous item and its price are lost, as if its not adding new lines to the array,but replacing the old ones, or the session only saves data from one action, which wouldn't make any sense, since thats what $_SESSION is about, the code is presented with session_start(); in every page that is using the $_SESSION variable.

 Main Question - Why could it be that the $_SESSION Array is losing its older inputs?

Body:
you need $_SESSION['chosen_item'][]=$input_order_arr; your overwriting the same index  instead of creating new one

$_SESSION['chosen_item'][]=$input_order_arr;

Note : And also it should be moved inside the if statement .to avoid empty array storing in session


问:
How to use time.Parse to parse hh:mm format in Go
I am importing a lot of fields of the format:

09:02 AM

10:02 AM

12:30 PM

04:10 PM

04:50 PM

05:30 PM

I would like to convert the fields into something I can do arithmetic on. For example, do a count down to when the event Occurs.  Thus, saving the field in microseconds... or even seconds.
I have been trying to get the time.Parse to work...   no joy.

```<code>fmt.Println(time.Parse("hh:mm", m.Feed.Entry[i].GsxA100Time.T))
</code>```

returns...

0001-01-01 00:00:00 +0000 UTC parsing time "07:50 PM" as "hh:mm": cannot parse "07:50 PM" as "hh:mm"

any suggestions?

答:
If you'll check again the documentation about time's Parse method you'll find the fact that Go's approach of parsing the time is totally different than the one that you used to work with in other programming languages. To provide the Parse function the layout of the time that you want to parse you need to transform one specific date (which is Mon Jan 2 15:04:05 -0700 MST 2006) into the layout that you're aiming for. In your case that would be "03:04 PM".

The full code: fmt.Println(time.Parse("03:04 PM", m.Feed.Entry[i].GsxA100Time.T))


问:
Are there any good 3rd party GUI products for Python?
In .Net you have companies like DevEpxress, and Infragistics that offer a range of GUI widgets.  Is there any market like that for Python GUI widgets?  I'm thinking specifically about widgets like the DevExpress xtraGrid Suite.

Edit 01-16-09:  For Example:

http://www.devexpress.com/Downloads/NET/OnlineDemos.xml
http://demos.devexpress.com/ASPxGridViewDemos/

http://www.infragistics.com/products/default.aspx

答:
There are a number of GUI Toolkits available for Python. Obviously, the toolkit you choose will determine your selection of 3rd party widgets.

The Contenders

Python comes with Tkinter which is easy to use, but not great looking.

There are some very popular cross platform GUI toolkits borrowed from C/C++ that have a lot of external widgets: wxPython, pyQt, pyFLTK, pyGtk

I also know of, but have not used some of the other toolkits that are out there: PyGUI, Easygui,  PythonCard

My Choice

I'm a fan of wxPython. They have a nice selection of widgets, some great examples that come with the install, good documentation, a book, and an active community.

WxWidgets has additional components offered by the community called wxCode.

Quote about wxPython from the creator of Python:

wxPython is the best and most mature cross-platform GUI toolkit,
  given a number of constraints. The only reason wxPython isn't the
  standard Python GUI toolkit is that Tkinter was there first.

-- Guido van Rossum

OwnerDisplayName: mchean

LastEditorDisplayName: mchean

OwnerDisplayName: John Mulder

LastEditorDisplayName: John Mulder


问:
separating number from date in Pandas columns
I have a column in pandas that include 100 rows like the following:

```<code>timeseries

2000-05-01 10:00:00+00:00   0.9
</code>```

it's only the index and I want to separate datetime with the number, and have two columns like:

```<code>time                                        number

2000-05-01 10:00:00+00:00                    0.9
</code>```

I tried :

```<code>df['start'] = mydata.str.split(' ').str.get(0)
df['end'] =   mydata.str.split(' ').str.get(1)
</code>```

but the answer is like:

```<code>                         timeseries     start  end
2017-05-01 10:00:00+00:00   0.9          0.9    NaN
</code>```

How can I separate the index as date and the number columns?

Body:
I have a column in pandas that include 100 rows like the following:

timeseries

2000-05-01 10:00:00+00:00   0.9

it's only the index and I want to separate datetime with the number, and have two columns like:

time                                        number

2000-05-01 10:00:00+00:00                    0.9

I tried :

df['start'] = mydata.str.split(' ').str.get(0)
df['end'] =   mydata.str.split(' ').str.get(1)

but the answer is like:

                         timeseries     start  end
2017-05-01 10:00:00+00:00   0.9          0.9    NaN

How can I separate the index as date and the number columns?

Body:
If you have a Series containing strings:

ser = pd.Series(['2000-05-01 10:00:00+00:00   0.9 ', '2000-05-01 10:00:00+00:00   1.2 ']) # some example data

then you can do

ser_split = ser.str.split().str
df['time'] = ser_split[0] + ' ' + ser_split[1]
df['number'] = ser_split[-1]

which gives

                        time number
0  2000-05-01 10:00:00+00:00    0.9
1  2000-05-01 10:00:00+00:00    1.2


问:
How to refresh Android listview evry 10 seconds
Im very new on Android. im making this teturial but i have a problem on refresh and can't understand how to refresh my listview </p>

```<code>        // Creating volley request obj
    JsonArrayRequest movieReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hidePDialog();

                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {

                            JSONObject obj = response.getJSONObject(i);
                            Movie movie = new Movie();
                            movie.setTitle(obj.getString("title"));
                            movie.setThumbnailUrl(obj.getString("image"));
                            movie.setRating(((Number) obj.get("rating"))
                                    .doubleValue());
                            movie.setYear(obj.getInt("releaseYear"));

                            // Genre is json array
                            JSONArray genreArry = obj.getJSONArray("genre");
                            ArrayList<String> genre = new ArrayList<String>();
                            for (int j = 0; j < genreArry.length(); j++) {
                                genre.add((String) genreArry.get(j));
                            }
                            movie.setGenre(genre);

                            // adding movie to movies array
                            movieList.add(movie);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hidePDialog();

                }
            });

/** REFRESH HERE /**

 Thread t = new Thread() {

        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(10000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.e(TAG, "EVRY 10 SECOND START NOW ");

                            listView.invalidateViews();
                            listView.refreshDrawableState();
                            adapter.notifyDataSetChanged();

//                                Log.e(TAG, String.valueOf(movieList));

                            // fire the event

                        }
                    });
                }
            } catch (InterruptedException e) {
            }
        }
    };

    t.start();
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(movieReq);
</code>```

<p>i try all methods google... but no luck this notifyDataSetChanged() not working ... </p>

```<code> listView.invalidateViews();
listView.refreshDrawableState();
adapter.notifyDataSetChanged();
</code>```

答:
Use Timer:</p>

```<code> Timer timerAsync;
 TimerTask timerTaskAsync;

timerAsync = new Timer();
        timerTaskAsync = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        doWork();
                    }
                });
            }
        };
        timerAsync.schedule(timerTaskAsync, 1000, 5000);// First Start 1 seconds 5 seconds repeat
</code>```

Body:
Im very new on Android. im making this teturial but i have a problem on refresh and can't understand how to refresh my listview

        // Creating volley request obj
    JsonArrayRequest movieReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hidePDialog();

                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {

                            JSONObject obj = response.getJSONObject(i);
                            Movie movie = new Movie();
                            movie.setTitle(obj.getString("title"));
                            movie.setThumbnailUrl(obj.getString("image"));
                            movie.setRating(((Number) obj.get("rating"))
                                    .doubleValue());
                            movie.setYear(obj.getInt("releaseYear"));

                            // Genre is json array
                            JSONArray genreArry = obj.getJSONArray("genre");
                            ArrayList<String> genre = new ArrayList<String>();
                            for (int j = 0; j < genreArry.length(); j++) {
                                genre.add((String) genreArry.get(j));
                            }
                            movie.setGenre(genre);

                            // adding movie to movies array
                            movieList.add(movie);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hidePDialog();

                }
            });

/** REFRESH HERE /**

 Thread t = new Thread() {

        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(10000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.e(TAG, "EVRY 10 SECOND START NOW ");

                            listView.invalidateViews();
                            listView.refreshDrawableState();
                            adapter.notifyDataSetChanged();

//                                Log.e(TAG, String.valueOf(movieList));

                            // fire the event

                        }
                    });
                }
            } catch (InterruptedException e) {
            }
        }
    };

    t.start();
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(movieReq);

i try all methods google... but no luck this notifyDataSetChanged() not working ...

 listView.invalidateViews();
listView.refreshDrawableState();
adapter.notifyDataSetChanged();

Body:
Use Timer:

 Timer timerAsync;
 TimerTask timerTaskAsync;

timerAsync = new Timer();
        timerTaskAsync = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        doWork();
                    }
                });
            }
        };
        timerAsync.schedule(timerTaskAsync, 1000, 5000);// First Start 1 seconds 5 seconds repeat


问:
MQTT-Broker meets WebServer with Database
I have a question about a combination of a MQTT-Broker and a Webserver.
Please check out the image bellow.

<img src="https://www.allaboutcircuits.com/uploads/articles/Introduction-to-the-MQTT-Protocol-on-NodeMCU-(1).png" alt="MQTT-Broker  <->  WebServer">

Is this a good way to save data from different sensors in a database?
In the picture the WebServer which communicates with the database is an MQTT Client. The WebServer just subscribe too all topics via #.

Is this scalable? I mean if there are 100.000 sensors out there and all send messages to this one WebServer..?

答:
If you want to keep a record of all sensor data then it's about the only option (unless you have different client for different sensor types so split things up a bit). The only other option to a seperate client subscribed to # would be to use a broker like HiveMQ which has a plugin mechanism that can record all messages in a database.

Also # should probably be sensors/# in order to skip any other messages that may be on the system.

100,000 sensors isn't the deciding factor here, the rate at which these sensors deliver messages will be the important point as it will determine the actual load.


问:
Laravel get product id from collection
I want to get all the products by passing array of ids which are from other table

i'm able to get all the product_id as in the dd($main_categorie_ids); but unable to pass it in other query and get the required data

```<code>    public function getHomeData($warehouse_id)
    {
        //get warehouse_table_name by warehouse_id
        $warehouse_table = Warehouse::where('id', $warehouse_id)
                                    ->select('table_name')
                                    ->first();

        //get all products from warehouse_table_name table
        $main_categorie_ids = DB::table($warehouse_table->table_name)
                                ->select('product_id')
                                ->get()
                                ->toArray();

        dd($main_categorie_ids);

        //dd result
        array:2 [
          0 => {#210
            +"product_id": 1
          }
          1 => {#209
            +"product_id": 2
          }
        ]

        //get distinct main_categories by id (line 29)
        $main_categorie = Product::whereIn('id', $main_categorie_ids['product_id'])
                                 ->groupBy('main_category_id')
                                 ->get();

        //get banners of main_categories by id

        //get parent_categories by main_category_id
    }
</code>```

i am getting error

```<code>(1/1) ErrorException
Undefined index: product_id
in HomeController.php (line 29)
</code>```

thank you

答:
Use pluck method to get only ids, like this:

```<code>$productIds = DB::table($warehouse_table->table_name)
                            ->select('product_id')
                            ->distinct()
                            ->pluck('product_id')
                            ->toArray();
$products = Product::whereIn('id', $productIds)->get();
</code>```

Title: Laravel get product id from collection

Body:
I want to get all the products by passing array of ids which are from other table

i'm able to get all the product_id as in the dd($main_categorie_ids); but unable to pass it in other query and get the required data

    public function getHomeData($warehouse_id)
    {
        //get warehouse_table_name by warehouse_id
        $warehouse_table = Warehouse::where('id', $warehouse_id)
                                    ->select('table_name')
                                    ->first();

        //get all products from warehouse_table_name table
        $main_categorie_ids = DB::table($warehouse_table->table_name)
                                ->select('product_id')
                                ->get()
                                ->toArray();

        dd($main_categorie_ids);

        //dd result
        array:2 [
          0 => {#210
            +"product_id": 1
          }
          1 => {#209
            +"product_id": 2
          }
        ]

        //get distinct main_categories by id (line 29)
        $main_categorie = Product::whereIn('id', $main_categorie_ids['product_id'])
                                 ->groupBy('main_category_id')
                                 ->get();

        //get banners of main_categories by id

        //get parent_categories by main_category_id
    }

i am getting error

(1/1) ErrorException
Undefined index: product_id
in HomeController.php (line 29)

thank you

Body:
Use pluck method to get only ids, like this:

$productIds = DB::table($warehouse_table->table_name)
                            ->select('product_id')
                            ->distinct()
                            ->pluck('product_id')
                            ->toArray();
$products = Product::whereIn('id', $productIds)->get();


问:
cant get Model in aspx from System.Web.Mvc.ViewPage<dynamic>
I am trying to get get model in aspx page. How can i get it. is anything i have to do in config file? PLease help  me.</p>

```<code><%@ Page Language="C#" AutoEventWireup="false" CodeBehind="Report.aspx.cs"
 Inherits="IBATechnologies.IBA.Main.Views.Report" %>
 <%@ page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
 <!DOCTYPE html>

 <html xmlns="http://www.w3.org/1999/xhtml">
  <head runat="server">
   <title></title>
   <script runat="server">
    Model // here i cant find Model "the name Model is not in current
   context"
    </script>

</head>
 <body>
<form id="form1" runat="server">
<div>

</div>
</form>
</body>
</html>
</code>```

答:
i'm not sure but you can use DynamicViewPage instead ViewPage.

may be this link will help you.
https://learn.microsoft.com/en-us/aspnet/mvc/overview/views/dynamic-v-strongly-typed-views

Body:
I am trying to get get model in aspx page. How can i get it. is anything i have to do in config file? PLease help  me.

<%@ Page Language="C#" AutoEventWireup="false" CodeBehind="Report.aspx.cs"
 Inherits="IBATechnologies.IBA.Main.Views.Report" %>
 <%@ page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
 <!DOCTYPE html>

   <title></title>

<form id="form1" runat="server">

</form>


问:
Automatically Load Specific Section of Nav Panel
I have the following nav panel and would like to  be able to select which section I display first based on a variable I get from the server. How can I do this? Normally you switch between the content within each nav pane by clicking on the buttons. Edit: See screen shot for an example.

```<code><div class="hr-divider m-y-md">
  <ul class="nav nav-pills hr-divider-content hr-divider-nav" role="tablist">
    <li class="active" role="presentation">
        <a href="#Overview" role="tab" data-toggle="tab" aria-controls="Overview" aria-expanded="false" id="navpanel1">Nav Panel 1</a>
    </li>
    <li role="presentation" class="">
        <a href="#Tasks" role="tab" data-toggle="tab" aria-controls="Tasks" aria-expanded="true" id="navpanel2">Nav Panel 2</a>
    </li>
    <li role="presentation" class="">
        <a href="#IssuesNotes" role="tab" data-toggle="tab" aria-controls="IssuesNotes" aria-expanded="true" id="navpanel3">Nav Panel 3</a>
    </li>
  </ul>
</div>

<div role="tabpanel" class="tab-pane active" id="Nav Panel 1 Content">
  //content
</div>
<div role="tabpanel" class="tab-pane active" id="Nav Panel 2 Content">
  //content
</div>
<div role="tabpanel" class="tab-pane active" id="Nav Panel 3 Content">
  //content
</div>
</code>```

答:
You will need to pass some variable for a conditional operator to your view.

Controller:

```<code>public ActionResult Index(string variable)
{
    switch (variable)
    {
        case "Overview":
        {
            ViewBag.Selected = "Overview";
            break;
        }
        case "Tasks":
        {
            ViewBag.Selected = "Tasks";
            break;
        }
        case "IssueNotes":
        {
            ViewBag.Selected = "IssueNotes";
            break;
        }
        default:
        {
            ViewBag.Selected = "IssueNotes";
            break;
        }
    }

    return View();
}
</code>```

View:

```<code><div class="hr-divider m-y-md">
    <ul class="nav nav-pills hr-divider-content hr-divider-nav" role="tablist">
        <li class="@(ViewBag.Selected == "Overview" ? "active" : "")" role="presentation">
            <a href="#Overview" role="tab" data-toggle="tab" aria-controls="Overview" aria-expanded="false">Overview</a>
        </li>
        <li class="@(ViewBag.Selected == "Tasks" ? "active" : "")" role="presentation">
            <a href="#Tasks" role="tab" data-toggle="tab" aria-controls="Tasks" aria-expanded="true">Tasks</a>
        </li>
        <li class="@(ViewBag.Selected == "IssueNotes" ? "active" : "")" role="presentation">
            <a href="#IssuesNotes" role="tab" data-toggle="tab" aria-controls="IssuesNotes" aria-expanded="true">IssuesNotes</a>
        </li>
    </ul>
</div>

<div class="tab-content clearfix">
    <div role="tabpanel" class="@(ViewBag.Selected == "Overview" ? "tab-pane active" : "tab-pane")" id="Overview">
        //Nav Panel 1 Content
    </div>
    <div role="tabpanel" class="@(ViewBag.Selected == "Tasks" ? "tab-pane active" : "tab-pane")" id="Tasks">
        //Nav Panel 2 Content
    </div>
    <div role="tabpanel" class="@(ViewBag.Selected == "IssueNotes" ? "tab-pane active" : "tab-pane")" id="IssuesNotes">
        //Nav Panel 3 Content
    </div>
</div>
</code>```

Note: I have used ViewBag value for simple example but you could also use model value if it is already being passed to the view (e.g. class="@(Model.Value == "Overview" ? "active" : "")" )

This is an ok solution for a few tabs, but for a more robust solution you could implement a HTML Helper. See accepted answer here for more information: How to add "active" class to Html.ActionLink in ASP.NET MVC

Edit:

Not sure what you want exactly, maybe this helps?

```<code>$(document).ready(function () {
    $("li a").on('click', function() {
        alert($(this).attr('href'));
    });
});
</code>```

Body:
I have the following nav panel and would like to  be able to select which section I display first based on a variable I get from the server. How can I do this? Normally you switch between the content within each nav pane by clicking on the buttons. Edit: See screen shot for an example.

        Nav Panel 1

        Nav Panel 2

        Nav Panel 3

  //content

  //content

  //content

Body:
You will need to pass some variable for a conditional operator to your view.

Controller:

public ActionResult Index(string variable)
{
    switch (variable)
    {
        case "Overview":
        {
            ViewBag.Selected = "Overview";
            break;
        }
        case "Tasks":
        {
            ViewBag.Selected = "Tasks";
            break;
        }
        case "IssueNotes":
        {
            ViewBag.Selected = "IssueNotes";
            break;
        }
        default:
        {
            ViewBag.Selected = "IssueNotes";
            break;
        }
    }

    return View();
}

View:

<div class="hr-divider m-y-md">
    <ul class="nav nav-pills hr-divider-content hr-divider-nav" role="tablist">
        <li class="@(ViewBag.Selected == "Overview" ? "active" : "")" role="presentation">
            <a href="#Overview" role="tab" data-toggle="tab" aria-controls="Overview" aria-expanded="false">Overview</a>
        </li>
        <li class="@(ViewBag.Selected == "Tasks" ? "active" : "")" role="presentation">
            <a href="#Tasks" role="tab" data-toggle="tab" aria-controls="Tasks" aria-expanded="true">Tasks</a>
        </li>
        <li class="@(ViewBag.Selected == "IssueNotes" ? "active" : "")" role="presentation">
            <a href="#IssuesNotes" role="tab" data-toggle="tab" aria-controls="IssuesNotes" aria-expanded="true">IssuesNotes</a>
        </li>
    </ul>
</div>

<div class="tab-content clearfix">
    <div role="tabpanel" class="@(ViewBag.Selected == "Overview" ? "tab-pane active" : "tab-pane")" id="Overview">
        //Nav Panel 1 Content
    </div>
    <div role="tabpanel" class="@(ViewBag.Selected == "Tasks" ? "tab-pane active" : "tab-pane")" id="Tasks">
        //Nav Panel 2 Content
    </div>
    <div role="tabpanel" class="@(ViewBag.Selected == "IssueNotes" ? "tab-pane active" : "tab-pane")" id="IssuesNotes">
        //Nav Panel 3 Content
    </div>
</div>

Note: I have used ViewBag value for simple example but you could also use model value if it is already being passed to the view (e.g. class="@(Model.Value == "Overview" ? "active" : "")" )

This is an ok solution for a few tabs, but for a more robust solution you could implement a HTML Helper. See accepted answer here for more information: How to add "active" class to Html.ActionLink in ASP.NET MVC

Edit:

Not sure what you want exactly, maybe this helps?

$(document).ready(function () {
    $("li a").on('click', function() {
        alert($(this).attr('href'));
    });
});