问:
group_concat is displaying same records multiple times in SQL Query
Note: Using DISTINCT will not solve the problem. (I will explain why)

Here is my code

```
DROP TABLE tmdb_movies;
CREATE TABLE tmdb_movies (
  tmdb_id INTEGER NOT NULL PRIMARY KEY,
  movie_title TEXT NOT NULL
);

INSERT INTO tmdb_movies (tmdb_id, movie_title) VALUES
(1, 'The Dark Knight');

DROP TABLE recommendations;
CREATE TABLE recommendations (
  recommendations_tmdb_id INTEGER NOT NULL,
  recommendations_title TEXT NOT NULL,
  recommendations_vote_average TEXT NOT NULL
);

INSERT INTO recommendations (recommendations_tmdb_id, recommendations_title, recommendations_vote_average) VALUES
(1, 'The Dark Knight Rises', '7.5'),
(1, 'Batman Begins', '7.5'),
(1, 'Iron Man', '7.3'),
(1, 'The Lord of the Rings: The Return of the King', '8.1'),
(1, 'The Lord of the Rings: The The Fellowship of the Ring', '8'),
(1, 'The Lord of the Rings: The Two Towers', '7.9'),
(1, 'The Matrix', '7.9'),
(1, 'Inception', '8'),
(1, 'Iron Man 2', '6.6'),
(1, 'Captain America: The First Avenger', '6.6');

DROP TABLE cast;
CREATE TABLE cast (
  cast_tmdb_id INTEGER NOT NULL,
  cast_name TEXT NOT NULL,
  cast_character TEXT NOT NULL
);

INSERT INTO cast (cast_tmdb_id, cast_name, cast_character) VALUES
(1, 'Christian Bale', 'Bruce Wayne / Batman'),
(1, 'Michael Caine', 'Alfred Pennyworth'),
(1, 'Heath Ledger', 'The Joker'),
(1, 'Aaron Eckhart', 'Harvey Dent / Two-Face'),
(1, 'Gary Oldman', 'Lt. James Gordon'),
(1, 'Maggie Gyllenhaal', 'Rachel Dawes'),
(1, 'Morgan Freeman', 'Lucius Fox'),
(1, 'Chin Han', 'Lau'),
(1, 'Eric Roberts', 'Salvatore Maroni'),
(1, 'Monique Gabriela Curnen', 'Ramirez');

SELECT tmdb_movies.movie_title
,GROUP_CONCAT(recommendations.recommendations_title) as recommendations_title
,GROUP_CONCAT(recommendations.recommendations_vote_average) as recommendations_vote_average

FROM tmdb_movies

LEFT JOIN cast ON cast.cast_tmdb_id=tmdb_movies.tmdb_id
LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id

Where tmdb_movies.tmdb_id= 1

GROUP BY tmdb_movies.movie_title
```

Complete SQL Fiddle

As you can see, the records from recommendations table are displaying multiple times. But If i remove this line LEFT JOIN cast ON cast.cast_tmdb_id=tmdb_movies.tmdb_id
then, they do not display multiple times. So this line is the main problem.

I did not use cast table in my SQL Query, just for the sake of simplicity. But I need it.

And yes, I need group_concat to display the records together in my PHP code

Why DISTINCT will not solve the problem? Well, some movies have the same rating, for example: 7.5. So, not all movie's rating will get displayed. That's why, you can try it yourself, try to use in the fiddle

QL

答:
Are you looking like for this result?</p>

```<code>SELECT tmdb_movies.movie_title
,GROUP_CONCAT(DISTINCT(recommendations.recommendations_title)) as recommendations_title
,GROUP_CONCAT(DISTINCT(recommendations.recommendations_vote_average)) as recommendations_vote_average

FROM tmdb_movies

LEFT JOIN cast ON cast.cast_tmdb_id=tmdb_movies.tmdb_id
LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id

Where tmdb_movies.tmdb_id= 1

GROUP BY tmdb_movies.movie_title
</code>```

Body:
Note: Using DISTINCT will not solve the problem. (I will explain why)

Here is my code

DROP TABLE tmdb_movies;
CREATE TABLE tmdb_movies (
  tmdb_id INTEGER NOT NULL PRIMARY KEY,
  movie_title TEXT NOT NULL
);

INSERT INTO tmdb_movies (tmdb_id, movie_title) VALUES
(1, 'The Dark Knight');

DROP TABLE recommendations;
CREATE TABLE recommendations (
  recommendations_tmdb_id INTEGER NOT NULL,
  recommendations_title TEXT NOT NULL,
  recommendations_vote_average TEXT NOT NULL
);

INSERT INTO recommendations (recommendations_tmdb_id, recommendations_title, recommendations_vote_average) VALUES
(1, 'The Dark Knight Rises', '7.5'),
(1, 'Batman Begins', '7.5'),
(1, 'Iron Man', '7.3'),
(1, 'The Lord of the Rings: The Return of the King', '8.1'),
(1, 'The Lord of the Rings: The The Fellowship of the Ring', '8'),
(1, 'The Lord of the Rings: The Two Towers', '7.9'),
(1, 'The Matrix', '7.9'),
(1, 'Inception', '8'),
(1, 'Iron Man 2', '6.6'),
(1, 'Captain America: The First Avenger', '6.6');

DROP TABLE cast;
CREATE TABLE cast (
  cast_tmdb_id INTEGER NOT NULL,
  cast_name TEXT NOT NULL,
  cast_character TEXT NOT NULL
);

INSERT INTO cast (cast_tmdb_id, cast_name, cast_character) VALUES
(1, 'Christian Bale', 'Bruce Wayne / Batman'),
(1, 'Michael Caine', 'Alfred Pennyworth'),
(1, 'Heath Ledger', 'The Joker'),
(1, 'Aaron Eckhart', 'Harvey Dent / Two-Face'),
(1, 'Gary Oldman', 'Lt. James Gordon'),
(1, 'Maggie Gyllenhaal', 'Rachel Dawes'),
(1, 'Morgan Freeman', 'Lucius Fox'),
(1, 'Chin Han', 'Lau'),
(1, 'Eric Roberts', 'Salvatore Maroni'),
(1, 'Monique Gabriela Curnen', 'Ramirez');

SELECT tmdb_movies.movie_title
,GROUP_CONCAT(recommendations.recommendations_title) as recommendations_title
,GROUP_CONCAT(recommendations.recommendations_vote_average) as recommendations_vote_average

FROM tmdb_movies

LEFT JOIN cast ON cast.cast_tmdb_id=tmdb_movies.tmdb_id
LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id

Where tmdb_movies.tmdb_id= 1

GROUP BY tmdb_movies.movie_title

Complete SQL Fiddle

As you can see, the records from recommendations table are displaying multiple times. But If i remove this line LEFT JOIN cast ON cast.cast_tmdb_id=tmdb_movies.tmdb_id
then, they do not display multiple times. So this line is the main problem.

I did not use cast table in my SQL Query, just for the sake of simplicity. But I need it.

And yes, I need group_concat to display the records together in my PHP code

Why DISTINCT will not solve the problem? Well, some movies have the same rating, for example: 7.5. So, not all movie's rating will get displayed. That's why, you can try it yourself, try to use in the fiddle

QL

Body:
Are you looking like for this result?

SELECT tmdb_movies.movie_title
,GROUP_CONCAT(DISTINCT(recommendations.recommendations_title)) as recommendations_title
,GROUP_CONCAT(DISTINCT(recommendations.recommendations_vote_average)) as recommendations_vote_average

FROM tmdb_movies

LEFT JOIN cast ON cast.cast_tmdb_id=tmdb_movies.tmdb_id
LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id

Where tmdb_movies.tmdb_id= 1

GROUP BY tmdb_movies.movie_title


来源: stackexchange

问:
Is there a python implementation of a Face shape detector?
Is there an OpenCV-python, dlib or any python 3 implementation of a face shape detector (diamond, oblong, square)?</p>

答:
If you just want an implementation, maybe you can check out the demo by Face++. They also present the keypoints in the form of a JSON.

https://www.faceplusplus.com/landmarks/

Also, check this out for additional links:
http://www.learnopencv.com/facial-landmark-detection/

ContentLicense: CC BY-SA 3.0


问:
method argument is not accessible by name inside method
Is it a bug in android studio or java, don't know. I was working on an astronomy application. I have created a method to get phase of moon. It takes two argument but only one argument is accessible by name. In debugger it says argument not found but when I assign to some other variable, it gets assigned. No runtime error in execution.

Argument that is not accessible is moon_degrees but when I assign it's value to variable moon_degree it works.

Don't know what's happening

Android studio Version 2.0

windows 7 X86

答: Your method argument is accessing inside method, but if you want to see inside method variable value in Debugger, please declare this inside variable Global. </p>


问:
Exposing properties of an object contained by a control
I have a simple object, could be a struct even, with three properties that I want to expose to the designer. Basically, I want my property to look like the Size or Padding properties of your average control, with an arrow to collapse or expand the properties as a sub-list of the control's properties. However, I cannot find any reference as to how this can be done. Since there are several types of properties with this collapse/extend look and feel I imagine there's something built-in I can use. If I have to implement my own Designer or Editor, forget it; it's not worth it. I doubt that that's the case; there's gotta be some simple attribute I can stick on the property or class that tells the designer to expose the browsable sub-properties.</p>

答:
What you're looking for is called Attributes.
Or more specifically Design-Time Attributes</p>

```<code>[Category("Hello World")]
[Description("Indicates if Button is Enabled or not")]
[Browsable(true)]
public int Blah { get; set; }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
What you're looking for is called Attributes.
Or more specifically Design-Time Attributes

[Category("Hello World")]
[Description("Indicates if Button is Enabled or not")]
[Browsable(true)]
public int Blah { get; set; }


问:
Smooth scroll to top not working
I am using the to top arrow in website to move to the top section with smooth scroll.. Now its moving to top but not moving in smooth..

The js that i used to get smooth scroll was

```<code>$(function() {
  $('a.page-scroll').bind('click', function(event) {
    console.log("scroll");
    var $anchor = $(this);
  $('html, body').stop().animate({
      scrollTop: $($anchor.attr('href')).offset().top
  }, 1500, 'easeInOutExpo');
  event.preventDefault();
  });
});
</code>```

BUt its not working..
The jsfiddle was https://jsfiddle.net/36m5kp00/

The jquery's that i have used was,

```<code><script src="scripts/controllers/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</code>```

答:
Use this</p>

```<code>$(function() {
  $('a.page-scroll').bind('click', function(event) {
    $("html, body").animate({ scrollTop: 0 }, 1500);
    event.preventDefault();
  });
});
</code>```

Title: Smooth scroll to top not working

Body:
I am using the to top arrow in website to move to the top section with smooth scroll.. Now its moving to top but not moving in smooth..

The js that i used to get smooth scroll was

$(function() {
  $('a.page-scroll').bind('click', function(event) {
    console.log("scroll");
    var $anchor = $(this);
  $('html, body').stop().animate({
      scrollTop: $($anchor.attr('href')).offset().top
  }, 1500, 'easeInOutExpo');
  event.preventDefault();
  });
});

BUt its not working..
The jsfiddle was https://jsfiddle.net/36m5kp00/

The jquery's that i have used was,

Body:
Use this

$(function() {
  $('a.page-scroll').bind('click', function(event) {
    $("html, body").animate({ scrollTop: 0 }, 1500);
    event.preventDefault();
  });
});


问:
Predicate inside a Where<> query not hit?
I need to call the method for each item in the list. So, I have used Where<> query as follows,

```<code>List<string> list = new List<string>();
list.Add("Name1");
list.Add("Name2");
list.Add("Name3");

var name = list.Where(n =>
{
    return CheckName(n);
});
</code>```

But in the above case, CheckName() is not hit. The same method is triggered if I use FirstOrDefault<>. I don't know whether it is a framework break or I am going in a wrong way.

As additional info, I am using.NET Framework 4.5.

Has anyone experienced this error? If so, is there any solution to overcome this issue?

答:
LINQ has a Deferred Execution principal which means the query will not be executed until and unless you access name variable. If you want to execute it immediately, (just for example) add .ToList() in the end, which is exactly what FirstOrDefault does. It does immediate execution instead of deferred execution.

```<code>var name = list.Where(n =>
{
    return CheckName(n);
}).ToList() != null;
</code>```

Also where condition result will never be null. Even if there is no object in list satisfying your condition(s) in CheckName, where will return an empty collection.

Body:
I need to call the method for each item in the list. So, I have used Where<> query as follows,

List<string> list = new List<string>();
list.Add("Name1");
list.Add("Name2");
list.Add("Name3");

var name = list.Where(n =>
{
    return CheckName(n);
});

But in the above case, CheckName() is not hit. The same method is triggered if I use FirstOrDefault<>. I don't know whether it is a framework break or I am going in a wrong way.

As additional info, I am using.NET Framework 4.5.

Has anyone experienced this error? If so, is there any solution to overcome this issue?

Body:
LINQ has a Deferred Execution principal which means the query will not be executed until and unless you access name variable. If you want to execute it immediately, (just for example) add .ToList() in the end, which is exactly what FirstOrDefault does. It does immediate execution instead of deferred execution.

var name = list.Where(n =>
{
    return CheckName(n);
}).ToList() != null;

Also where condition result will never be null. Even if there is no object in list satisfying your condition(s) in CheckName, where will return an empty collection.


问:
Couchbase lite ios retrieve documents
How can I retrieve all documents with key containing a certain string? I know how to retrieve one document if I have it key using:

```<code>let doc = database.documentWithID(myDocID)
</code>```

but if I want all documents where the key contains the string "key" for example is there an easy way to do it or do I have to create view and queries?

Thanks.

答:
This is how I did it (with views and queries); I have added a field type and add in it the specification:</p>

```<code>    let view = db?.viewNamed("list")
    if view?.mapBlock == nil {
        view?.setMapBlock({ (doc, emit) in
            if let type: String = doc["type"] as? String, let name = doc["name"], let overview = doc["overview"], type == "task" {
                emit(name, nil)
            }
        }, version: "1.0")
    }
    liveQuery = view?.createQuery().asLive()
</code>```

Title: Couchbase lite ios retrieve documents

Body:
How can I retrieve all documents with key containing a certain string? I know how to retrieve one document if I have it key using:

let doc = database.documentWithID(myDocID)

but if I want all documents where the key contains the string "key" for example is there an easy way to do it or do I have to create view and queries?

Thanks.

Body:
This is how I did it (with views and queries); I have added a field type and add in it the specification:

    let view = db?.viewNamed("list")
    if view?.mapBlock == nil {
        view?.setMapBlock({ (doc, emit) in
            if let type: String = doc["type"] as? String, let name = doc["name"], let overview = doc["overview"], type == "task" {
                emit(name, nil)
            }
        }, version: "1.0")
    }
    liveQuery = view?.createQuery().asLive()


问:
Can't use CKEDITOR in django template
I am using a form without a model class.

```<code>class ClubWallForm(forms.Form):

    title = forms.CharField(label='Post title', max_length=100)
    description = RichTextField()
    imgURL = forms.CharField(label='Post image url', max_length=100)
    filefield = forms.FileField( label='Select a file',validators=[validate_file_extension] )
</code>```

In my template I used

```<code>`        {% for field in form %}
            <div class="fieldWrapper">
                {{ field.errors }}
                {{ field.label_tag }}: {{ field }}
            </div>
        {% endfor %}`
</code>```

CKEDITOR is not geting displayed in my template.
This is what I am getting.

Inside my views it tried to use ipdb and found that the form has only fields title imgurl and filefield .

答:
You have two issues:

RichTextField is a model field. RichTextFormField is the corresponding form field.

You're not handling the form media in the template. This is outlined in the documentation.

Title: Can't use CKEDITOR in django template

Body:
I am using a form without a model class.

class ClubWallForm(forms.Form):

    title = forms.CharField(label='Post title', max_length=100)
    description = RichTextField()
    imgURL = forms.CharField(label='Post image url', max_length=100)
    filefield = forms.FileField( label='Select a file',validators=[validate_file_extension] )

In my template I used

`        {% for field in form %}

                {{ field.errors }}
                {{ field.label_tag }}: {{ field }}

        {% endfor %}`

CKEDITOR is not geting displayed in my template.
This is what I am getting.

Inside my views it tried to use ipdb and found that the form has only fields title imgurl and filefield .


问:
EF Code first Multi level inheritence issues
I have a multi level inheriance heriarchy consisting of the following classes:

```<code>public abstract class BasePoco
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
}

public class Activity : BasePoco
{
    public ActivityType ActivityType { get; set; }

    [MaxLength(1000)]
    public string Description { get; set; }
}
</code>```

Now there is a special type of Activity which is called a data capture activity.
Which is of two types: DataCaptureActivity and MasterDataCaptureActivity

```<code>public class DataCaptureActivityBase : Activity
{

    [MaxLength(100)]
    public string Title { get; set; }
}
</code>```

Derived Classes :

```<code>[Table("DataCaptureActivities")]
public class DataCaptureActivity : DataCaptureActivityBase
{
    public virtual DataCaptureActivityType DataCaptureActivityType { get; set; }
}

[Table("MasterDataCaptureActivities")]
public class MasterDataCaptureActivity : DataCaptureActivityBase
{
    public virtual string SomeOtherField{ get; set; }
}
</code>```

The problem is upon creating a migration, The column Title which should be a part of DataCaptureActivity is actually coming up as a part of the Activity table.
Please note that DataCaptureActivityBase should not be a table in my schema. It is just for holding the common parameters DataCaptureActivities table and its inherited types.

The Schema I am targeting is :

```<code>Activity
-------------------------------
Id  | ActivityType  | Description

DataCaptureActivity
--------------------------------
Id | Title

MasterDataCaptureActivity
--------------------------------
Id | Title | SomeOtherField
</code>```

答:
Try doing the below steps.

Mark Activity class with a Table Attribute

Mark DataCaptureActivityBase as abstract

In OnModelCreating Map Derived Entities with MapInheritedProperties();

Hope this helps

Body:
I have a multi level inheriance heriarchy consisting of the following classes:

public abstract class BasePoco
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
}

public class Activity : BasePoco
{
    public ActivityType ActivityType { get; set; }

    [MaxLength(1000)]
    public string Description { get; set; }
}

Now there is a special type of Activity which is called a data capture activity.
Which is of two types: DataCaptureActivity and MasterDataCaptureActivity

public class DataCaptureActivityBase : Activity
{

    [MaxLength(100)]
    public string Title { get; set; }
}

Derived Classes :

[Table("DataCaptureActivities")]
public class DataCaptureActivity : DataCaptureActivityBase
{
    public virtual DataCaptureActivityType DataCaptureActivityType { get; set; }
}

[Table("MasterDataCaptureActivities")]
public class MasterDataCaptureActivity : DataCaptureActivityBase
{
    public virtual string SomeOtherField{ get; set; }
}

The problem is upon creating a migration, The column Title which should be a part of DataCaptureActivity is actually coming up as a part of the Activity table.
Please note that DataCaptureActivityBase should not be a table in my schema. It is just for holding the common parameters DataCaptureActivities table and its inherited types.

The Schema I am targeting is :

Activity
-------------------------------
Id  | ActivityType  | Description

DataCaptureActivity
--------------------------------
Id | Title

MasterDataCaptureActivity
--------------------------------
Id | Title | SomeOtherField


问:
Sieve of Eratosthenes in Erlang
I'm in the process of learning Erlang. As an exercise I picked up the Sieve of Eratosthenes algorithm of generating prime numbers. Here is my code:

```<code>-module(seed2).
-export([get/1]).

get(N) -> WorkList = lists:duplicate(N, empty),
          get(2, N, WorkList, []).

get(thats_the_end, _N, _WorkList, ResultList) -> lists:reverse(ResultList);
get(CurrentPrime, N, WorkList, ResultList) -> ModWorkList = markAsPrime(CurrentPrime, N, WorkList),
                                              NextPrime = findNextPrime(CurrentPrime + 1, N, WorkList),
                                              get(NextPrime, N, ModWorkList, [CurrentPrime|ResultList]).

markAsPrime(CurrentPrime, N, WorkList) when CurrentPrime =< N -> WorkListMod = replace(CurrentPrime, WorkList, prime),
                                                                 markAllMultiples(CurrentPrime, N, 2*CurrentPrime, WorkListMod).

markAllMultiples(_ThePrime, N, TheCurentMark, WorkList) when TheCurentMark > N -> WorkList;
markAllMultiples(ThePrime, N, TheCurrentMark, WorkList) -> WorkListMod = replace(TheCurrentMark, WorkList, marked),
                                                           markAllMultiples(ThePrime, N, TheCurrentMark + ThePrime, WorkListMod).

findNextPrime(Iterator, N, _WorkList) when Iterator > N -> thats_the_end;
findNextPrime(Iterator, N, WorkList) -> I = lists:nth(Iterator, WorkList),
                                        if
                                          I =:= empty -> Iterator;
                                          true -> findNextPrime(Iterator + 1, N, WorkList)
                                        end.

replace(N, L, New)-> {L1, [_H|L2]} = lists:split(N - 1, L),
                     lists:append(L1, [New|L2]).
</code>```

This code actually works :) . The problem is that I have this feeling that it is not the best possible implementation.

My question is what would be the "erlangish" way of implementing the "Sieve of Eratosthenes"

EDIT: OK, Andreas solution is very good but it is slow. Any ideas how to improve that?

答:
Have a look here to find 4 different implementations for finding prime numbers in Erlang (two of which are "real" sieves) and for performance measurement results:

http://caylespandon.blogspot.com/2009/01/in-euler-problem-10-we-are-asked-to.html

OwnerDisplayName: Roskoto

Title: Sieve of Eratosthenes in Erlang

Body:
I'm in the process of learning Erlang. As an exercise I picked up the Sieve of Eratosthenes algorithm of generating prime numbers. Here is my code:

-module(seed2).
-export([get/1]).

get(N) -> WorkList = lists:duplicate(N, empty),
          get(2, N, WorkList, []).

get(thats_the_end, _N, _WorkList, ResultList) -> lists:reverse(ResultList);
get(CurrentPrime, N, WorkList, ResultList) -> ModWorkList = markAsPrime(CurrentPrime, N, WorkList),
                                              NextPrime = findNextPrime(CurrentPrime + 1, N, WorkList),
                                              get(NextPrime, N, ModWorkList, [CurrentPrime|ResultList]).

markAsPrime(CurrentPrime, N, WorkList) when CurrentPrime =< N -> WorkListMod = replace(CurrentPrime, WorkList, prime),
                                                                 markAllMultiples(CurrentPrime, N, 2*CurrentPrime, WorkListMod).

markAllMultiples(_ThePrime, N, TheCurentMark, WorkList) when TheCurentMark > N -> WorkList;
markAllMultiples(ThePrime, N, TheCurrentMark, WorkList) -> WorkListMod = replace(TheCurrentMark, WorkList, marked),
                                                           markAllMultiples(ThePrime, N, TheCurrentMark + ThePrime, WorkListMod).

findNextPrime(Iterator, N, _WorkList) when Iterator > N -> thats_the_end;
findNextPrime(Iterator, N, WorkList) -> I = lists:nth(Iterator, WorkList),
                                        if
                                          I =:= empty -> Iterator;
                                          true -> findNextPrime(Iterator + 1, N, WorkList)
                                        end.

replace(N, L, New)-> {L1, [_H|L2]} = lists:split(N - 1, L),
                     lists:append(L1, [New|L2]).

This code actually works :) . The problem is that I have this feeling that it is not the best possible implementation.

My question is what would be the "erlangish" way of implementing the "Sieve of Eratosthenes"

EDIT: OK, Andreas solution is very good but it is slow. Any ideas how to improve that?

LastEditorDisplayName: Roskoto

OwnerDisplayName: Cayle Spandon


问:
pytest execution order of tests in a class
I 'm writing test cases in the following manner.

```<code># content of test_class.py
class TestClass(object):
    def test_one(self):
        x = "this"
        assert 'h' in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')
</code>```

test_two depends on test_one, so ordering of the execution is important, What's the convention to enforce test execution order when you group tests in a class?

答: You can use pytest_collection_modifyitems hook to change the order as you wish.

Body:
I 'm writing test cases in the following manner.

# content of test_class.py
class TestClass(object):
    def test_one(self):
        x = "this"
        assert 'h' in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')

test_two depends on test_one, so ordering of the execution is important, What's the convention to enforce test execution order when you group tests in a class?


问:
You have to be inside an angular-cli project in order to use the serve command
I am trying to run a drag and drop sample from dragula.but when i run ng serve it complains with :

```<code>You have to be inside an angular-cli project in order to use the serve command.
</code>```

when i run ng -v in my machine, I have:

```<code>angular-cli: 1.0.0-beta.16
node: 4.6.0
os: win32 x64
</code>```

I have tried to add:

```<code>"angular-cli": "1.0.0-beta.16",
</code>```

in the dependencies of project and then npm install, but my node fails to install the package.

How can i run the dragula?

答:
ng serve Will not work if you don't have angular cli,

but you can start your project by npm start command.

You should install angular cli globally by following command.

npm install -g @angular/cli@latest

Body:
I am trying to run a drag and drop sample from dragula.but when i run ng serve it complains with :

You have to be inside an angular-cli project in order to use the serve command.

when i run ng -v in my machine, I have:

angular-cli: 1.0.0-beta.16
node: 4.6.0
os: win32 x64

I have tried to add:

"angular-cli": "1.0.0-beta.16",

in the dependencies of project and then npm install, but my node fails to install the package.

How can i run the dragula?


问:
How to Bind list box ItemsSource with array from external resource dictionary
I am currently using List box ItemsSource to bind the values
from x:array like this:

```<code>     <x:Array x:Key="SampleImages" Type="{x:Type BitmapImage}">
                        <BitmapImage UriSource="www.google.com/a.png" />
                        <BitmapImage UriSource="www.google.com/b.jpg" />
                        <BitmapImage UriSource="www.google.com/c.jpg" />
                        <BitmapImage UriSource="www.google.com/d.jpg" />
     </x:Array>
</code>```

Then using it in the same xaml page as

```<code>    <ListBox ItemsSource="{StaticResource SampleImages}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Image Source="{Binding}"></Image>
                    </DataTemplate>
                </ListBox.ItemTemplate>
    </ListBox>
</code>```

Instead of defining the images in the array,
I would like to use the array to get the images from another resource dictionary (SampleImages.xaml; so it is easier to change the images later if need arises) defined as -

```<code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <BitmapImage UriSource="www.google.com/a.png" />
    <BitmapImage UriSource="www.google.com/b.jpg" />
    <BitmapImage UriSource="www.google.com/c.jpg" />
    <BitmapImage UriSource="www.google.com/d.jpg" />
</ResourceDictionary>
</code>```

How would you refer the SampleImages.xaml in x:Array ?
Thanks in Advance.

答:
Move the whole Array to your resource file.
Reference it in your app.xaml to be available in the whole application.

SampleImages.xaml:

```<code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <x:Array x:Key="SampleImages" Type="{x:Type BitmapImage}">
         <BitmapImage UriSource="www.google.com/a.png" />
         <BitmapImage UriSource="www.google.com/b.jpg" />
         <BitmapImage UriSource="www.google.com/c.jpg" />
         <BitmapImage UriSource="www.google.com/d.jpg" />
  </x:Array>
</ResourceDictionary>
</code>```

App.xaml:

```<code><Application x:Class="Project.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="MainWindow.xaml" >
   <Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/YourResourceFolderIfAny/SampleImages.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
  </Application.Resources>
</Application>
</code>```

Any other view:

```<code><ListBox ItemsSource="{StaticResource SampleImages}">
     <ListBox.ItemTemplate>
         <DataTemplate>
              <Image Source="{Binding}"></Image>
          </DataTemplate>
     </ListBox.ItemTemplate>
</ListBox>
</code>```

Body:
I am currently using List box ItemsSource to bind the values
from x:array like this:

     <x:Array x:Key="SampleImages" Type="{x:Type BitmapImage}">
                        <BitmapImage UriSource="www.google.com/a.png" />
                        <BitmapImage UriSource="www.google.com/b.jpg" />
                        <BitmapImage UriSource="www.google.com/c.jpg" />
                        <BitmapImage UriSource="www.google.com/d.jpg" />
     </x:Array>

Then using it in the same xaml page as

    <ListBox ItemsSource="{StaticResource SampleImages}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Image Source="{Binding}"></Image>
                    </DataTemplate>
                </ListBox.ItemTemplate>
    </ListBox>

Instead of defining the images in the array,
I would like to use the array to get the images from another resource dictionary (SampleImages.xaml; so it is easier to change the images later if need arises) defined as -

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <BitmapImage UriSource="www.google.com/a.png" />
    <BitmapImage UriSource="www.google.com/b.jpg" />
    <BitmapImage UriSource="www.google.com/c.jpg" />
    <BitmapImage UriSource="www.google.com/d.jpg" />
</ResourceDictionary>

How would you refer the SampleImages.xaml in x:Array ?
Thanks in Advance.

Body:
Move the whole Array to your resource file.
Reference it in your app.xaml to be available in the whole application.

SampleImages.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <x:Array x:Key="SampleImages" Type="{x:Type BitmapImage}">
         <BitmapImage UriSource="www.google.com/a.png" />
         <BitmapImage UriSource="www.google.com/b.jpg" />
         <BitmapImage UriSource="www.google.com/c.jpg" />
         <BitmapImage UriSource="www.google.com/d.jpg" />
  </x:Array>
</ResourceDictionary>

App.xaml:

<Application x:Class="Project.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="MainWindow.xaml" >
   <Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/YourResourceFolderIfAny/SampleImages.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
  </Application.Resources>
</Application>

Any other view:

<ListBox ItemsSource="{StaticResource SampleImages}">
     <ListBox.ItemTemplate>
         <DataTemplate>
              <Image Source="{Binding}"></Image>
          </DataTemplate>
     </ListBox.ItemTemplate>
</ListBox>


问:
python numpy: iterate for different conditions without using a loop
I am trying to iterate over numpy arrays and generate an output, which has conditions similar to that described below:

```<code>min1 = 3
max1 = 1
a1 = np.array([1, 2, 5, 3, 4])
a2 = np.array([5, 2, 6, 2, 1])
output = np.zeros(5)
for i in range(0, 5):
  if((a1[i] - a2[i]) > min1):
    output[i] = 3 * (a1[i] - a2[i])

  if((a1[i] - a2[i]) < max1):
    output = 5 * (a1[i] - a2[i])
</code>```

I need to optimize the above code, so that I utilize the numpy functionalities as the best and also avoid using a loop. How should I do it?

答:
Your question is a bit vague. Here's a possible solution depending on what you really want.

This solution will return 2 arrays of that contains values that belong to the min and max that you indicated. What this does is that it does the - operation to your two arrays then instead of doing if, numpy has the function called where that does this for you without iterating through the whole array.

```<code>import numpy as np
min1=3
max1=1
a1=np.array([1,2,5,3,4])
a2=np.array([5,2,6,2,1])
array_op = a1-a2
min_output = 3*(array_op[np.where((array_op)>min1)])
max_output = 5*(array_op[np.where((array_op)<max1)])
</code>```

Body:
I am trying to iterate over numpy arrays and generate an output, which has conditions similar to that described below:

min1 = 3
max1 = 1
a1 = np.array([1, 2, 5, 3, 4])
a2 = np.array([5, 2, 6, 2, 1])
output = np.zeros(5)
for i in range(0, 5):
  if((a1[i] - a2[i]) > min1):
    output[i] = 3 * (a1[i] - a2[i])

  if((a1[i] - a2[i]) < max1):
    output = 5 * (a1[i] - a2[i])

I need to optimize the above code, so that I utilize the numpy functionalities as the best and also avoid using a loop. How should I do it?

Body:
Your question is a bit vague. Here's a possible solution depending on what you really want.

This solution will return 2 arrays of that contains values that belong to the min and max that you indicated. What this does is that it does the - operation to your two arrays then instead of doing if, numpy has the function called where that does this for you without iterating through the whole array.

import numpy as np
min1=3
max1=1
a1=np.array([1,2,5,3,4])
a2=np.array([5,2,6,2,1])
array_op = a1-a2
min_output = 3*(array_op[np.where((array_op)>min1)])
max_output = 5*(array_op[np.where((array_op)<max1)])


问:
Multidimensional array can't foreach
i have this array :

```<code>array:2 [▼
  0 => array:6 [▼
    "id" => 1
    "name" => "Longline T-Shirt In Fake Linen With All Over Floral Print"
    "price" => 18.11
    "quantity" => 1
    "attributes" => []
    "conditions" => []
  ]
  1 => array:6 [▼
    "id" => 3
    "name" => "Longline T-Shirt With All Over Aztec Print"
    "price" => 16.99
    "quantity" => 1
    "attributes" => []
    "conditions" => []
  ]
]
</code>```

(dd from laravel)

but when i run foreach on array ($all_order) it returns me only first detail.

tried to flat the array with :

```<code>$result = [];
        array_walk_recursive($all_order, function($v) use (&$result) {
            $result[] = $v;
        });
        dd( $result);
</code>```

result :

```<code> 0 => 1
  1 => "Longline T-Shirt In Fake Linen With All Over Floral Print"
  2 => 18.11
  3 => 1
  4 => 3
  5 => "Longline T-Shirt With All Over Aztec Print"
  6 => 16.99
  7 => 1
</code>```

The problem is, i need only id + quantity to down the value of stock from product table.... i'm stack for about 4 hours -_-"

答:
I'm guessing you have an error in your original foreach code. This is how you'd normally do it: </p>

```<code>foreach ($all_order as $value) {
  $id = $value['id'];
  $quantity = $value['quantity'];
  // then do something with your values...
}
</code>```

Title: Multidimensional array can't foreach

Body:
i have this array :

array:2 [▼
  0 => array:6 [▼
    "id" => 1
    "name" => "Longline T-Shirt In Fake Linen With All Over Floral Print"
    "price" => 18.11
    "quantity" => 1
    "attributes" => []
    "conditions" => []
  ]
  1 => array:6 [▼
    "id" => 3
    "name" => "Longline T-Shirt With All Over Aztec Print"
    "price" => 16.99
    "quantity" => 1
    "attributes" => []
    "conditions" => []
  ]
]

(dd from laravel)

but when i run foreach on array ($all_order) it returns me only first detail.

tried to flat the array with :

$result = [];
        array_walk_recursive($all_order, function($v) use (&$result) {
            $result[] = $v;
        });
        dd( $result);

result :

 0 => 1
  1 => "Longline T-Shirt In Fake Linen With All Over Floral Print"
  2 => 18.11
  3 => 1
  4 => 3
  5 => "Longline T-Shirt With All Over Aztec Print"
  6 => 16.99
  7 => 1

The problem is, i need only id + quantity to down the value of stock from product table.... i'm stack for about 4 hours -_-"

Body:
I'm guessing you have an error in your original foreach code. This is how you'd normally do it:

foreach ($all_order as $value) {
  $id = $value['id'];
  $quantity = $value['quantity'];
  // then do something with your values...
}


问:
How can I show the button only in parent element?
I have a little question. I have a nested table. The first item in this table should be removed. Everything is okay so far. But how can I show the 'Remove User' button only on the first elements?

class UserList extends Component {

  constructor(props) {
    super(props);
    this.state = {
      openDetail: false
    }
  }

  parentUserToggle (item, index) {
    this.setState({
      openDetail: !this.state.openDetail
    })
  }

  render() {
    const { userProfile, index } = this.props;
    let parentUserItem = null;
    if (userProfile.children instanceof Object) {
      parentUserItem = userProfile.children.map((children, index) => {
        return <UserList key={children.ID} index={index} userProfile={children} />
      });
    }
    return (

          {
            userProfile.children ?
            <button
              className="btn btn-primary"
              onClick={this.parentUserToggle.bind(this, userProfile.children)}
            >
              { !this.state.openDetail ? 'OPEN' : 'CLOSE' }
            </button>
            : null
          }

{userProfile.Name}

{userProfile.City}

{userProfile.Phone}

          {
            userProfile || !parentUserItem ?
            <button
              className="btn btn-danger"
              onClick={this.props.removeUser}
            > Remove User </button>
            : null
          }

          {
            parentUserItem
          }

    );
  }
}```

Thanks for support.

答:
I'm sorry I answered a little late. But the problem I solved that day. The correct answer was to check with props. Thank you for your support!

{
  this.props.removeUser ?
  <button
    className="btn btn-danger"
    onClick={this.props.removeUser}
  > Remove User </button>
  : null
}```

Body:
I have a little question. I have a nested table. The first item in this table should be removed. Everything is okay so far. But how can I show the 'Remove User' button only on the first elements?

class UserList extends Component {

  constructor(props) {
    super(props);
    this.state = {
      openDetail: false
    }
  }

  parentUserToggle (item, index) {
    this.setState({
      openDetail: !this.state.openDetail
    })
  }

  render() {
    const { userProfile, index } = this.props;
    let parentUserItem = null;
    if (userProfile.children instanceof Object) {
      parentUserItem = userProfile.children.map((children, index) => {
        return <UserList key={children.ID} index={index} userProfile={children} />
      });
    }
    return (

          {
            userProfile.children ?
            <button
              className="btn btn-primary"
              onClick={this.parentUserToggle.bind(this, userProfile.children)}
            >
              { !this.state.openDetail ? 'OPEN' : 'CLOSE' }
            </button>
            : null
          }

{userProfile.Name}

{userProfile.City}

{userProfile.Phone}

          {
            userProfile || !parentUserItem ?
            <button
              className="btn btn-danger"
              onClick={this.props.removeUser}
            > Remove User </button>
            : null
          }

          {
            parentUserItem
          }

    );
  }
}

Thanks for support.


问:
Invalid Auth Token with Rails, Graphql, Apollo Client
I am trying to get a basic Rails, Graphql, Apollo-Client setup working but having trouble with 422 errors 'invalid auth token' on the rails side.

Does my use of apollo look wrong?

It is a Rails 5 app with graphql gem and apollo client.

```<code>const csrfToken = document.getElementsByName('csrf-token')[0].content
const client = new ApolloClient({
  networkInterface: createNetworkInterface({
    uri: '/graphql',
    credentials: 'same-origin',
    headers: {
      'X-CSRF-Token': csrfToken
    }
  }),
});
client.query({
query: gql`
    query Camillo2 {
      user {
        id
        email
        created_at
      }
    }
  `,
})
.then(data => console.log(data))
.catch(error => console.error(error));
</code>```

Rails log:

```<code>Started POST "/graphql" for ::1 at 2017-03-10 08:51:58 -0800
Processing by GraphqlController#create as */*
Parameters: {"query"=>"query Camillo2 {\n  user {\n    id\n    email\n    created_at\n    __typename\n  }\n}\n", "operationName"=>"Camillo2", "graphql"=>{"query"=>"query Camillo2 {\n  user {\n    id\n    email\n    created_at\n    __typename\n  }\n}\n", "operationName"=>"Camillo2"}}
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 2ms (ActiveRecord: 0.0ms)
</code>```

答:
To clarify some of the above answers, since one of the users noted that passing in the uri as a first argument to createNetworkInterface works but logs a deprecation message in the console: you have to pass in options like "credentials" and "headers" in as properties of an options object like so:

```<code>const networkInterface = createNetworkInterface({
  uri: '/graphql',
  opts: {
    credentials: 'same-origin',
    headers: {
      'X-CSRF-TOKEN': $('meta[name=csrf-token]').attr('content'),
    },
  },
});
</code>```

See the second example under Fetch in the docs: http://dev.apollodata.com/core/network.html

Body:
I am trying to get a basic Rails, Graphql, Apollo-Client setup working but having trouble with 422 errors 'invalid auth token' on the rails side.

Does my use of apollo look wrong?

It is a Rails 5 app with graphql gem and apollo client.

const csrfToken = document.getElementsByName('csrf-token')[0].content
const client = new ApolloClient({
  networkInterface: createNetworkInterface({
    uri: '/graphql',
    credentials: 'same-origin',
    headers: {
      'X-CSRF-Token': csrfToken
    }
  }),
});
client.query({
query: gql`
    query Camillo2 {
      user {
        id
        email
        created_at
      }
    }
  `,
})
.then(data => console.log(data))
.catch(error => console.error(error));

Rails log:

Started POST "/graphql" for ::1 at 2017-03-10 08:51:58 -0800
Processing by GraphqlController#create as */*
Parameters: {"query"=>"query Camillo2 {\n  user {\n    id\n    email\n    created_at\n    __typename\n  }\n}\n", "operationName"=>"Camillo2", "graphql"=>{"query"=>"query Camillo2 {\n  user {\n    id\n    email\n    created_at\n    __typename\n  }\n}\n", "operationName"=>"Camillo2"}}
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 2ms (ActiveRecord: 0.0ms)

Body:
To clarify some of the above answers, since one of the users noted that passing in the uri as a first argument to createNetworkInterface works but logs a deprecation message in the console: you have to pass in options like "credentials" and "headers" in as properties of an options object like so:

const networkInterface = createNetworkInterface({
  uri: '/graphql',
  opts: {
    credentials: 'same-origin',
    headers: {
      'X-CSRF-TOKEN': $('meta[name=csrf-token]').attr('content'),
    },
  },
});

See the second example under Fetch in the docs: http://dev.apollodata.com/core/network.html


问:
How to accept an out parameter in Ajax?
I have a static function in the aspx page with this signature:

```<code>   public static bool UserNeedsToBeAlertedPwdReset(out DateTime dtExpires)
   {
        DateTime dt = DateTime.MivValue;

        return true;
   }
</code>```

So I want to call this function from the client side, using the jQuery Ajax. How do I get a hold of the out value?

Edit
Alternatevly I could check for nulls if this is possible with Ajax + jQuery like that:

```<code>   public static DateTime? UserNeedsToBeAlertedPwdReset()
   {
        if(blah)
           return null;
        return DateTime.Now;
   }
</code>```

答:
I don't believe it's possible.

You would be better written a class that contains the response data and returning that instead.

Title: How to accept an out parameter in Ajax?

Body:
I have a static function in the aspx page with this signature:

   public static bool UserNeedsToBeAlertedPwdReset(out DateTime dtExpires)
   {
        DateTime dt = DateTime.MivValue;

        return true;
   }

So I want to call this function from the client side, using the jQuery Ajax. How do I get a hold of the out value?

Edit
Alternatevly I could check for nulls if this is possible with Ajax + jQuery like that:

   public static DateTime? UserNeedsToBeAlertedPwdReset()
   {
        if(blah)
           return null;
        return DateTime.Now;
   }


问:
GSON - JsonSyntaxException - Expected name at line 7 column 4
I have the following result class whose object is to be returned as JSON.

```<code>public class Result {
    public String objectid;
    public String dtype;
    public String type;
    public String name;
    public String description;

    public Result() {
        this.objectid = "";
        this.dtype= "";
        this.type="";
        this.name= "";
        this.description = "";
    }

    public String getObjectid() {
        return objectid;
    }

    public void setObjectid(String s) {
        this.objectid = s;
    }

    public String getDtype() {
        return dtype;
    }

    public void setDtype(String s) {
        this.dtype= s;
    }

    public String getType() {
        return type;
    }

    public void setType(String s) {
        this.type = s;
    }

    public String getName() {
        return name;
    }

    public void setName(String s) {
        this.name = s;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String s) {
        this.description = s;
    }

}
</code>```

I have a configuration json which is read my the main .java and returned as json as HTTP RESPONSE. It is as below:

```<code>{
        "objectid" : "test",
        "dtype" : "test",
        "type" : "test",
        "name" : "test",
        "description" : "test" // removed
},
{
        "objectid" : "test",
        "dtype" : "test",
        "type" : "test",
        "name" : "test",
        "description" : "test"
}
</code>```

Main .java

Using Gson, it reads the configuration.json file and has to return a json.

My code:

```<code>Gson g = new Gson();
Result r = g.fromJson(res.toString(), Result.class);
</code>```

where res.toString() gets me the configuration.json file content as string.

My problem:

I am experiencing the following exception:

Exception com.google.gson.JsonSyntaxException:   com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 7 column 3

  com.google.gson.JsonSyntaxException:   com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 7 column 3

Any pointers?

答:
You have two objects but getting one object from GSON. either you should use below format of JSON string to get Result object from this JSON string.

```<code>{
    "objectid" : "test",
    "dtype" : "test",
    "type" : "test",
    "name" : "test",
    "description" : "test"
</code>```

}

Second option :-

You will have to change JSON string format. you will have to change it in JSON array and get ArrayList of this object, After that, we can get Result object using array list index.new JSON string would be like this.

```<code>    {"resultArray":[{
    "objectid" : "test",
    "dtype" : "test",
    "type" : "test",
    "name" : "test",
    "description" : "test"
           },
      {
    "objectid" : "test",
    "dtype" : "test",
    "type" : "test",
    "name" : "test",
    "description" : "test"
        }]}
</code>```

And java code to fetch Result Object.

```<code>Gson g = new Gson();
ResultList r = g.fromJson(res.toString(), ResultList.class);
ArrayList<Result> resultList = r.getResultList();
       for(int x=0 ;x<resultList.size();x++){
              Result result = resultList.get(x);
              }
</code>```

ResultList Model is:-

```<code>public class ResultList {
@SerializedName("resultArray")
public ArrayList<Result> resultList;
public getResultList(){
          return resultList;
           }
       }
</code>```

@Note: - Result.java would be used same as given above.

Body:
I have the following result class whose object is to be returned as JSON.

public class Result {
    public String objectid;
    public String dtype;
    public String type;
    public String name;
    public String description;

    public Result() {
        this.objectid = "";
        this.dtype= "";
        this.type="";
        this.name= "";
        this.description = "";
    }

    public String getObjectid() {
        return objectid;
    }

    public void setObjectid(String s) {
        this.objectid = s;
    }

    public String getDtype() {
        return dtype;
    }

    public void setDtype(String s) {
        this.dtype= s;
    }

    public String getType() {
        return type;
    }

    public void setType(String s) {
        this.type = s;
    }

    public String getName() {
        return name;
    }

    public void setName(String s) {
        this.name = s;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String s) {
        this.description = s;
    }

}

I have a configuration json which is read my the main .java and returned as json as HTTP RESPONSE. It is as below:

{
        "objectid" : "test",
        "dtype" : "test",
        "type" : "test",
        "name" : "test",
        "description" : "test" // removed
},
{
        "objectid" : "test",
        "dtype" : "test",
        "type" : "test",
        "name" : "test",
        "description" : "test"
}

Main .java

Using Gson, it reads the configuration.json file and has to return a json.

My code:

Gson g = new Gson();
Result r = g.fromJson(res.toString(), Result.class);

where res.toString() gets me the configuration.json file content as string.

My problem:

I am experiencing the following exception:

Exception com.google.gson.JsonSyntaxException:   com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 7 column 3

  com.google.gson.JsonSyntaxException:   com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 7 column 3

Any pointers?

Body:
You have two objects but getting one object from GSON. either you should use below format of JSON string to get Result object from this JSON string.

{
    "objectid" : "test",
    "dtype" : "test",
    "type" : "test",
    "name" : "test",
    "description" : "test"

}

Second option :-

You will have to change JSON string format. you will have to change it in JSON array and get ArrayList of this object, After that, we can get Result object using array list index.new JSON string would be like this.

    {"resultArray":[{
    "objectid" : "test",
    "dtype" : "test",
    "type" : "test",
    "name" : "test",
    "description" : "test"
           },
      {
    "objectid" : "test",
    "dtype" : "test",
    "type" : "test",
    "name" : "test",
    "description" : "test"
        }]}

And java code to fetch Result Object.

Gson g = new Gson();
ResultList r = g.fromJson(res.toString(), ResultList.class);
ArrayList<Result> resultList = r.getResultList();
       for(int x=0 ;x<resultList.size();x++){
              Result result = resultList.get(x);
              }

ResultList Model is:-

public class ResultList {
@SerializedName("resultArray")
public ArrayList<Result> resultList;
public getResultList(){
          return resultList;
           }
       }

@Note: - Result.java would be used same as given above.


问:
Split or extract a Value from a vector SCALA
I am working with the following list in a text file:

```<code>10,44,22
10,47,12
15,38,3
15,41,30
16,44,15
16,47,18
22,38,21
22,41,42
34,44,40
34,47,36
40,38,39
40,41,42
45,38,27
45,41,30
46,44,45
46,47,48
</code>```

I am creating some indexes to analysis the table, then if each column is (s,p,o) and I create a map that is P -> SO I create it of the form

```<code>val dicP_SO: scala.collection.mutable.Map[Int, Vector[Vector[Int]]] = collection.mutable.Map[Int, Vector[Vector[Int]]]()
</code>```

I read the file, and create the mapping with

```<code>if (dicP_SO.contains(p)) {
   P_SO = dicP_SO.apply(p) :+ Vector(s, o) //To add to the same key the diff
   dicP_SO += (p -> P_SO)                  //(s,o)
}else dicP_SO += (p -> Vector(Vector(s,o)))
</code>```

in this way if I put as key the 38, and I run the following code:

```<code>dicP_SO.getOrElse(38,Vector(0))
</code>```

I get the following:

```<code>Vector(Vector(15, 3), Vector(22, 21), Vector(40, 39), Vector(45, 27))
</code>```

My quetion is the following: I need each vector[Int] that are inside, I try to declare a variable

```<code>val a:Vector[Int] = dicP_SO.getOrElse(yi,Vector(0))
</code>```

I am getting the error that a Vector[Any] does not conform to Vector[Int] and I don't know why is this error and how fix it

答:
The reason you have compile error is that the value in the map is in the type of Vector[Vector[Int]]. So when you do getOrElse(yi, Vector(0)), the Vector(0) value will have type Vector[Int], and hence the compiler will try to refer the returned type of the two types ( Vector[Vector[Int]] and Vector[Int]) as Vector[Any].

Given the data that you have, I'd recommend using these data structure and code:

```<code>val dicP_SO: mutable.Map[Int, List[(Int, Int)]] = mutable.Map[Int, List[(Int, Int)]]()
</code>```

Then for inserting new info:

```<code>val currentValues = if (dicP_SO.contains(p)) {
    dicP_SO.remove(p)
} else {
    List.empty[(Int, Int)]
}

dicP_SO += p -> currentValues :+ (s, o)
</code>```

To retrieve info for a key yi:

```<code>val a: List[(Int, Int)] = dicP_SO.getOrElse(yi, List.empty[(Int, Int)] // return empty list if the key doesn't exists
</code>```

Then you can process the information however you want, e.g.:

```<code>a.map { case (s, o) => /* do something with s and o */ }
</code>```

Body:
I am working with the following list in a text file:

10,44,22
10,47,12
15,38,3
15,41,30
16,44,15
16,47,18
22,38,21
22,41,42
34,44,40
34,47,36
40,38,39
40,41,42
45,38,27
45,41,30
46,44,45
46,47,48

I am creating some indexes to analysis the table, then if each column is (s,p,o) and I create a map that is P -> SO I create it of the form

val dicP_SO: scala.collection.mutable.Map[Int, Vector[Vector[Int]]] = collection.mutable.Map[Int, Vector[Vector[Int]]]()

I read the file, and create the mapping with

if (dicP_SO.contains(p)) {
   P_SO = dicP_SO.apply(p) :+ Vector(s, o) //To add to the same key the diff
   dicP_SO += (p -> P_SO)                  //(s,o)
}else dicP_SO += (p -> Vector(Vector(s,o)))

in this way if I put as key the 38, and I run the following code:

dicP_SO.getOrElse(38,Vector(0))

I get the following:

Vector(Vector(15, 3), Vector(22, 21), Vector(40, 39), Vector(45, 27))

My quetion is the following: I need each vector[Int] that are inside, I try to declare a variable

val a:Vector[Int] = dicP_SO.getOrElse(yi,Vector(0))

I am getting the error that a Vector[Any] does not conform to Vector[Int] and I don't know why is this error and how fix it

Body:
The reason you have compile error is that the value in the map is in the type of Vector[Vector[Int]]. So when you do getOrElse(yi, Vector(0)), the Vector(0) value will have type Vector[Int], and hence the compiler will try to refer the returned type of the two types ( Vector[Vector[Int]] and Vector[Int]) as Vector[Any].

Given the data that you have, I'd recommend using these data structure and code:

val dicP_SO: mutable.Map[Int, List[(Int, Int)]] = mutable.Map[Int, List[(Int, Int)]]()

Then for inserting new info:

val currentValues = if (dicP_SO.contains(p)) {
    dicP_SO.remove(p)
} else {
    List.empty[(Int, Int)]
}

dicP_SO += p -> currentValues :+ (s, o)

To retrieve info for a key yi:

val a: List[(Int, Int)] = dicP_SO.getOrElse(yi, List.empty[(Int, Int)] // return empty list if the key doesn't exists

Then you can process the information however you want, e.g.:

a.map { case (s, o) => /* do something with s and o */ }


问:
TSQL - how to find if a column has a space char(32)?
TSQL - how to find if a column has a space char(32)?

```<code>select *
from [sometable]
where CHARINDEX(' ', [somecolumn]) > 0
</code>```

doesn't work?  Any ideas?

答:
The following worked for me:</p>

```<code>PrdPicture LIKE '%'+char(160)+'%'
</code>```

OwnerDisplayName: NCR

Body:
TSQL - how to find if a column has a space char(32)?

select *
from [sometable]
where CHARINDEX(' ', [somecolumn]) > 0

doesn't work?  Any ideas?

Body:
The following worked for me:

PrdPicture LIKE '%'+char(160)+'%'


问:
How to display javascript alert without reset form
I have a form to be filled in and a popup javascript alert will be displayed if the Password and Re-Confirm Password does not match. However, once I click "OK"on the popup alert, the whole form is reset. But I just want the password to be blank again, not the whole form.

I tried this way:

```<code>if($pwd != $pwd2) {
    echo("<script type='text/javascript'>alert('Password does not match!')</script>");
}
</code>```

I also tried the one below but still the same thing happened:

```<code>if($pwd != $pwd2) {
    ?>
    <script type="text/javascript">
        alert("Password does not match!");
    </script>
    <?php
}
</code>```

答:
if you really need using php</p>

```<code><?php
$pwd = isset($_REQUEST['pwd']) ? $_REQUEST['pwd'] : "";
$pwd2 = isset($_REQUEST['pwd2']) ? $_REQUEST['pwd2'] : "";

if($pwd != $pwd2) {
    echo("<script type='text/javascript'>alert('Password does not match!')</script>");
}
>
<input name"pwd" value="<?php echo $pwd; ?>">
<input name"pwd2" value="<?php echo $pwd2; ?>">
</code>```

Body:
I have a form to be filled in and a popup javascript alert will be displayed if the Password and Re-Confirm Password does not match. However, once I click "OK"on the popup alert, the whole form is reset. But I just want the password to be blank again, not the whole form.

I tried this way:

if($pwd != $pwd2) {
    echo("");
}

I also tried the one below but still the same thing happened:

if($pwd != $pwd2) {
    ?>

    <?php
}

Body:
if you really need using php

<?php
$pwd = isset($_REQUEST['pwd']) ? $_REQUEST['pwd'] : "";
$pwd2 = isset($_REQUEST['pwd2']) ? $_REQUEST['pwd2'] : "";

if($pwd != $pwd2) {
    echo("<script type='text/javascript'>alert('Password does not match!')</script>");
}
>
<input name"pwd" value="<?php echo $pwd; ?>">
<input name"pwd2" value="<?php echo $pwd2; ?>">


问:
Another question on negative regex
I have a python script that checks code for coding convention errors.  It does this by matching a regex that represents a violation of the coding standard.

One of our standards is that 'if', 'while' and 'do-while' conditionals must contain a conditional operator.

So no

```<code>if (var1)
{
    // blah
}
</code>```

Instead I need

```<code>if (var1 == TRUE)
{
    // blah
}
</code>```

For example, what I need for if statements is to match "if" at the beginning of the line, and find the situation when it doesn't contain "==", "<=", ">=", "||" or "&&" anywhere after it.  I've been pounding my head against the wall for a few hours and I'm hoping someone here can alleviate some of the pain!

答:
Here is what I ended up doing, it works fairly well for the most part, not ideal though and we are looking into a third party parser.</p>

```<code>^\s*\bif\s*\(\s*\w+\s*\)\s*$
</code>```

Title: Another question on negative regex

Body:
I have a python script that checks code for coding convention errors.  It does this by matching a regex that represents a violation of the coding standard.

One of our standards is that 'if', 'while' and 'do-while' conditionals must contain a conditional operator.

So no

if (var1)
{
    // blah
}

Instead I need

if (var1 == TRUE)
{
    // blah
}

For example, what I need for if statements is to match "if" at the beginning of the line, and find the situation when it doesn't contain "==", "<=", ">=", "||" or "&&" anywhere after it.  I've been pounding my head against the wall for a few hours and I'm hoping someone here can alleviate some of the pain!

Body:
Here is what I ended up doing, it works fairly well for the most part, not ideal though and we are looking into a third party parser.

^\s*\bif\s*\(\s*\w+\s*\)\s*$


问:
How to remove key from an array in php
I need to remove keys from my arrays, and array be like

```<code>Array ( [0] => 23/2 [1] => KG Halli [2] => D' Souza Layout [3] => Sampangi Rama Nagar [4] => Bengaluru [5] => Bangalore Urban [6] => Karnataka [7] => India [8] => 560001 )
</code>```

and i need it as

23/2, KG Halli, D' Souza Layout, Sampangi Rama Nagar, Bengaluru, Banglore Urban

答:
```<code>$required_str = implode(',',$array);
</code>```

Title: How to remove key from an array in php

Body:
I need to remove keys from my arrays, and array be like

Array ( [0] => 23/2 [1] => KG Halli [2] => D' Souza Layout [3] => Sampangi Rama Nagar [4] => Bengaluru [5] => Bangalore Urban [6] => Karnataka [7] => India [8] => 560001 )

and i need it as

23/2, KG Halli, D' Souza Layout, Sampangi Rama Nagar, Bengaluru, Banglore Urban

Body: $required_str = implode(',',$array);


问:
json file does not contain valid JSON
I have issue with my auth.json file in magento 2.1.6

Basically i am using auth.json file to connect with repo.magento.com

While i m trying to install module via composer than it is giving me error like this

auth.json does not contain valid JSON Parse error on line 1

Here is my auth.json file

```<code>"http-basic": {
    "repo.magento.com": {
        "username":"<public key>",
        "password":"<private key>"
    }
}
</code>```

Here is the actual error

Error: Parse error on line 1:

"http-basic": {    "repo.magento.c

------------^

Expecting 'EOF', '}', ',', ']', got ':'

Any help will be appreciated.

答:
I got answer while i was testing this code in jsonlint.com.

The json code should be wrapped by {}

It will goes like this.

```<code>{
    "http-basic": {
       "repo.magento.com": {
           "username":"<public key>",
           "password":"<private key>"
       }
    }
}
</code>```

Title: json file does not contain valid JSON

Body:
I have issue with my auth.json file in magento 2.1.6

Basically i am using auth.json file to connect with repo.magento.com

While i m trying to install module via composer than it is giving me error like this

auth.json does not contain valid JSON Parse error on line 1

Here is my auth.json file

"http-basic": {
    "repo.magento.com": {
        "username":"<public key>",
        "password":"<private key>"
    }
}

Here is the actual error

Error: Parse error on line 1:

"http-basic": {    "repo.magento.c

------------^

Expecting 'EOF', '}', ',', ']', got ':'

Any help will be appreciated.

Body:
I got answer while i was testing this code in jsonlint.com.

The json code should be wrapped by {}

It will goes like this.

{
    "http-basic": {
       "repo.magento.com": {
           "username":"<public key>",
           "password":"<private key>"
       }
    }
}


问:
Can Perl 6 sort or compare based on collations?
The cmp operator works on code numbers, or at least that's what I think it does because the docs aren't explicit on that and don't mention any localization stuff.

Can I make it sort by other collations? I know I tell sort how to compare, but I figure it must be in there already (somewhere).

答:
Collation is available as an experimental feature:

```<code>my @list = <a ö ä Ä o ø>;
say @list.sort;                     # (a o Ä ä ö ø)

use experimental :collation;
say @list.collate;                  # (a ä Ä o ö ø)
$*COLLATION.set(:tertiary(False));
say @list.collate;                  # (a Ä ä o ö ø)
</code>```

Please give feedback on this feature to help it move out of the "experimental" state and be included in v6.d.

Body:
Collation is available as an experimental feature:

my @list = <a ö ä Ä o ø>;
say @list.sort;                     # (a o Ä ä ö ø)

use experimental :collation;
say @list.collate;                  # (a ä Ä o ö ø)
$*COLLATION.set(:tertiary(False));
say @list.collate;                  # (a Ä ä o ö ø)

Please give feedback on this feature to help it move out of the "experimental" state and be included in v6.d.


答:
Try this:</p>

```<code>$yourString = implode(", ", $yourArray);
</code>```

Title: How to remove key from an array in php

Body:
Try this:

$yourString = implode(", ", $yourArray);


问:
jaxws-maven-plugin or jaxb2-maven-plugin to create java classes from WSDL
I am developing a web service contract-first. I have seen a lot of developers use the plugin jaxws-maven-pluginin the pom.xml to create java classes from the wsdl file (or the xsd file), while other developers use some pluggin variation of jaxb2-maven-plugin to do it.

Does someone know advantage of using one or the other?. Is any of them obsolete?

答:
jaxb2 - maven - plugin is a maven plugin that replaces XJC and schemagen to complete the transformation of Java classes and schema files.
When using jaxb2: schemagen generates a schema file, it cannot be generated if the Java bean property name is different from the specified name

Jaxws-maven-plugin generates the Web Service client Java code.

Most of the time Jaxws-maven -plugin is more recommended for use


问:
How instance variable are related to class variable in python
```<code>class myclass(object):
    i=0
    def increase(self):
        self.i+=1
        print('increased value:', self.i)

if __name__=='__main__':
    m=myclass()
    m.increase()
</code>```

Here is a class variable and self.i is instance variable , on executing i get o/P as 1.

But if  comment class variable i I get an error

```<code>self.i+=1
AttributeError: 'myclass' object has no attribute 'i'
</code>```

what is the relation between class variable i and instance variable self.i here.

答:
A class variable is a variable which can be changed by all instances of your class. You call it by [class_name].[variable_name]

For Example:

```<code>class myclass(object):
    i=0
    def increase(self):
        myclass.i+=1
        print('incresed value:',self.i)

if __name__=='__main__':
    m=myclass()
    k = myclass()

    k.increase()
    m.increase()
    m.increase()
    m.increase()
    m.increase()
    k.increase()
</code>```

results in

```<code>incresed value: 1
incresed value: 2
incresed value: 3
incresed value: 4
incresed value: 5
incresed value: 6
</code>```

An instance variable on the other hand (like you have it) can only be accessed by the instance which created it (with self.[variable_name]).
To access a variable, the variable first needs to be instantiated. Like

```<code>a+=5
</code>```

would create an error while

```<code>a = 0
a+= 5
</code>```

would not

In your example the instance variable is not specificly instantiated. But because of the class variable (i=0) python automatically instantiates the instance variable (i) with the value of the class variable. (because class and instance variable have the same name)

In other words:

When in your example the class variable
    i=0
is removed python does not know what value your instance variable
    self.i
should have in the beginning.

Body:
class myclass(object):
    i=0
    def increase(self):
        self.i+=1
        print('increased value:', self.i)

if __name__=='__main__':
    m=myclass()
    m.increase()

Here is a class variable and self.i is instance variable , on executing i get o/P as 1.

But if  comment class variable i I get an error

self.i+=1
AttributeError: 'myclass' object has no attribute 'i'

what is the relation between class variable i and instance variable self.i here.

Body:
A class variable is a variable which can be changed by all instances of your class. You call it by [class_name].[variable_name]

For Example:

class myclass(object):
    i=0
    def increase(self):
        myclass.i+=1
        print('incresed value:',self.i)

if __name__=='__main__':
    m=myclass()
    k = myclass()

    k.increase()
    m.increase()
    m.increase()
    m.increase()
    m.increase()
    k.increase()

results in

incresed value: 1
incresed value: 2
incresed value: 3
incresed value: 4
incresed value: 5
incresed value: 6

An instance variable on the other hand (like you have it) can only be accessed by the instance which created it (with self.[variable_name]).
To access a variable, the variable first needs to be instantiated. Like

a+=5

would create an error while

a = 0
a+= 5

would not

In your example the instance variable is not specificly instantiated. But because of the class variable (i=0) python automatically instantiates the instance variable (i) with the value of the class variable. (because class and instance variable have the same name)

In other words:

When in your example the class variable
    i=0
is removed python does not know what value your instance variable
    self.i
should have in the beginning.


问:
Making a list of neighbor polygons touching same border of each polygon in R
I have a shape file that has a geospacial map of different territories. I have already loaded it into R. The CRS it has is NAD83 and the ellipse is GRS80.

I am trying to make a list of all the territories touching the border for each territory in the map.

When I type head(shapefile), it shows something like this:

```<code>        Territory  Year
    0   ACE        1803
    1   FAS        1814
    2   CAT        1865
    3   TAT        1834
    4   GAL        1833
    5   UBE        1877
</code>```

I have already tried:

```<code>    gTouches(shapefile, byid = TRUE)
</code>```

and it worked, but it is not the format I want. I have also tried

```<code>    shapefile.knn <- knearneigh(coordinates(shapefile), k=7)
    plot(knn2nb(shapefile.knn), coordinates(shapefile), col="red", add=TRUE)
</code>```

and it worked as well, but I want to find the neighboring territories that TOUCH the border for each territory and this seems to just take the nearest neighbors not dependent on if they touch the border or not. I also want to make a list of these neighboring territory names for each territory name.

I came across this link: http://grokbase.com/t/r/r-sig-geo/072fxj7bhr/how-to-find-neighbor-polygons-and-analysis-of-their-attributes

In this link, a person was asking for something similar to what I want, so I tried the code that was shared to her to see if it will work for me, but I only got this far:

```<code>   nbs <- poly2nb(as(shapefile, "SpatialPolygons"))
   wts <- nb2listw(nbs, style = "W")
</code>```

I am not sure how/what to do after this, and I'm not really even sure if it will lead me to what I want. On the website they use a lag function. I tried:

```<code>   shapefile$W_var <-lag(wts, shapefile$var)
</code>```

but it didnt work and says, "Error: n must be a nonnegative integer scalar, not NULL of length 0". I suspect it is because I do not have a column called "var" in my shapefile, but I am not sure what type of column they are trying to refer to.

Any help is much appreciated, thank you!

答:
To get the list of polygons numbers being neighbors, you need to use:

```<code>list.nb <- gTouches(shapefile, byid = TRUE, returnDense = FALSE)
</code>```

Numbers are the positions of polygons in your shapefile. You can thus get names with a simple vector extraction: shapefile$Territory[number]. In your case, you need to apply this on the complete list:

```<code>list.Territories <- lapply(list.nb, function(x) shapefile$Territory[x])
</code>```

Body:
I have a shape file that has a geospacial map of different territories. I have already loaded it into R. The CRS it has is NAD83 and the ellipse is GRS80.

I am trying to make a list of all the territories touching the border for each territory in the map.

When I type head(shapefile), it shows something like this:

        Territory  Year
    0   ACE        1803
    1   FAS        1814
    2   CAT        1865
    3   TAT        1834
    4   GAL        1833
    5   UBE        1877

I have already tried:

    gTouches(shapefile, byid = TRUE)

and it worked, but it is not the format I want. I have also tried

    shapefile.knn <- knearneigh(coordinates(shapefile), k=7)
    plot(knn2nb(shapefile.knn), coordinates(shapefile), col="red", add=TRUE)

and it worked as well, but I want to find the neighboring territories that TOUCH the border for each territory and this seems to just take the nearest neighbors not dependent on if they touch the border or not. I also want to make a list of these neighboring territory names for each territory name.

I came across this link: http://grokbase.com/t/r/r-sig-geo/072fxj7bhr/how-to-find-neighbor-polygons-and-analysis-of-their-attributes

In this link, a person was asking for something similar to what I want, so I tried the code that was shared to her to see if it will work for me, but I only got this far:

   nbs <- poly2nb(as(shapefile, "SpatialPolygons"))
   wts <- nb2listw(nbs, style = "W")

I am not sure how/what to do after this, and I'm not really even sure if it will lead me to what I want. On the website they use a lag function. I tried:

   shapefile$W_var <-lag(wts, shapefile$var)

but it didnt work and says, "Error: n must be a nonnegative integer scalar, not NULL of length 0". I suspect it is because I do not have a column called "var" in my shapefile, but I am not sure what type of column they are trying to refer to.

Any help is much appreciated, thank you!

Body:
To get the list of polygons numbers being neighbors, you need to use:

list.nb <- gTouches(shapefile, byid = TRUE, returnDense = FALSE)

Numbers are the positions of polygons in your shapefile. You can thus get names with a simple vector extraction: shapefile$Territory[number]. In your case, you need to apply this on the complete list:

list.Territories <- lapply(list.nb, function(x) shapefile$Territory[x])


问:
Country selection in android using API
I need spinner item should be flag image which is from service but it is showing country name in spinner item or i can use custom list view instead of spinner which one is easy.

MainActivity.java

```<code>public class MainActivity extends Activity {
    JSONObject jsonobject;
    JSONArray jsonarray;
    ProgressDialog mProgressDialog;
    ArrayList<String> worldlist;
    ArrayList<WorldPopulation> world;

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

    // Download JSON file AsyncTask
    new DownloadJSON().execute();

}

// Download JSON file AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        // Locate the WorldPopulation Class
        world = new ArrayList<WorldPopulation>();
        // Create an array to populate the spinner
        worldlist = new ArrayList<String>();
        // JSON file URL address
        jsonobject = JSONfunctions
                .getJSONfromURL("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");

        try {
            // Locate the NodeList name
            jsonarray = jsonobject.getJSONArray("worldpopulation");
            for (int i = 0; i < jsonarray.length(); i++) {
                jsonobject = jsonarray.getJSONObject(i);

                WorldPopulation worldpop = new WorldPopulation();

                worldpop.setRank(jsonobject.optString("rank"));
                worldpop.setCountry(jsonobject.optString("country"));
                worldpop.setPopulation(jsonobject.optString("population"));
                worldpop.setFlag(jsonobject.optString("flag"));
                world.add(worldpop);

                // Populate spinner with country names
                worldlist.add(jsonobject.optString("country"));

            }
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {
        // Locate the spinner in activity_main.xml
        Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);

        // Spinner adapter
        mySpinner
                .setAdapter(new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_spinner_dropdown_item,
                        worldlist));

        // Spinner on item click listener
        mySpinner
                .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> arg0,
                            View arg1, int position, long arg3) {
                        // TODO Auto-generated method stub
                        // Locate the textviews in activity_main.xml
                        TextView txtrank = (TextView) findViewById(R.id.rank);
                        TextView txtcountry = (TextView) findViewById(R.id.country);
                        TextView txtpopulation = (TextView) findViewById(R.id.population);

                        // Set the text followed by the position
                        txtrank.setText("Rank : "
                                + world.get(position).getRank());
                        txtcountry.setText("Country : "
                                + world.get(position).getCountry());
                        txtpopulation.setText("Population : "
                                + world.get(position).getPopulation());
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> arg0) {
                        // TODO Auto-generated method stub
                    }
                });
    }
}
}
</code>```

JSONfunctions.java

```<code>public class JSONfunctions {

public static JSONObject getJSONfromURL(String url) {
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    // Download JSON data from URL
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // Convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    try {

        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }

    return jArray;
}
}
</code>```

activity_main.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Spinner
    android:id="@+id/my_spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/rank"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/my_spinner" />

<TextView
    android:id="@+id/country"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/rank" />

<TextView
    android:id="@+id/population"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/country" />

</RelativeLayout>
</code>```

答: Try using https://developers.google.com/places/android-api/autocomplete which is better. Please check the image you can use the default interface provided by Google

Title: Country selection in android using API

Body:
I need spinner item should be flag image which is from service but it is showing country name in spinner item or i can use custom list view instead of spinner which one is easy.

MainActivity.java

public class MainActivity extends Activity {
    JSONObject jsonobject;
    JSONArray jsonarray;
    ProgressDialog mProgressDialog;
    ArrayList<String> worldlist;
    ArrayList<WorldPopulation> world;

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

    // Download JSON file AsyncTask
    new DownloadJSON().execute();

}

// Download JSON file AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        // Locate the WorldPopulation Class
        world = new ArrayList<WorldPopulation>();
        // Create an array to populate the spinner
        worldlist = new ArrayList<String>();
        // JSON file URL address
        jsonobject = JSONfunctions
                .getJSONfromURL("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");

        try {
            // Locate the NodeList name
            jsonarray = jsonobject.getJSONArray("worldpopulation");
            for (int i = 0; i < jsonarray.length(); i++) {
                jsonobject = jsonarray.getJSONObject(i);

                WorldPopulation worldpop = new WorldPopulation();

                worldpop.setRank(jsonobject.optString("rank"));
                worldpop.setCountry(jsonobject.optString("country"));
                worldpop.setPopulation(jsonobject.optString("population"));
                worldpop.setFlag(jsonobject.optString("flag"));
                world.add(worldpop);

                // Populate spinner with country names
                worldlist.add(jsonobject.optString("country"));

            }
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {
        // Locate the spinner in activity_main.xml
        Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);

        // Spinner adapter
        mySpinner
                .setAdapter(new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_spinner_dropdown_item,
                        worldlist));

        // Spinner on item click listener
        mySpinner
                .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> arg0,
                            View arg1, int position, long arg3) {
                        // TODO Auto-generated method stub
                        // Locate the textviews in activity_main.xml
                        TextView txtrank = (TextView) findViewById(R.id.rank);
                        TextView txtcountry = (TextView) findViewById(R.id.country);
                        TextView txtpopulation = (TextView) findViewById(R.id.population);

                        // Set the text followed by the position
                        txtrank.setText("Rank : "
                                + world.get(position).getRank());
                        txtcountry.setText("Country : "
                                + world.get(position).getCountry());
                        txtpopulation.setText("Population : "
                                + world.get(position).getPopulation());
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> arg0) {
                        // TODO Auto-generated method stub
                    }
                });
    }
}
}

JSONfunctions.java

public class JSONfunctions {

public static JSONObject getJSONfromURL(String url) {
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    // Download JSON data from URL
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // Convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    try {

        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }

    return jArray;
}
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Spinner
    android:id="@+id/my_spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/rank"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/my_spinner" />

<TextView
    android:id="@+id/country"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/rank" />

<TextView
    android:id="@+id/population"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/country" />

</RelativeLayout>


问:
Bean instance is not getting loaded
I need a help regarding dependency injection.

I hava a bean class which is having a object reference of JdbcTemplate and I am using @Autowired to
create instance of that object. But that object is not getting loaded and as a result NullPointerException is thrown
from setCustName() method.

Please help

Bean Class :

```<code>class CustomerBean {

    private String custName;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void setCustName(String custName) {
    this.custName = custName;
    jdbcTemplate.update(query);
    }
}
</code>```

XML :

```<code><bean id="myjdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
 </bean>

 <bean id="custBean" class="com.test.CustomerBean">
        <property name="custName" value="John" />
 </bean>
</code>```

Stacktrace:

```<code>PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'custName' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:334)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1419)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1160)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
</code>```

答:
you get NullPointerException  as jdbcTemplate is null / not injected.

if you describe bean custBean by xml , as you did, you should add :
< property name="jdbcTemplate" value="myjdbcTemplate" /> for inject jdbcTemplate into your bean.

you have mixed configuration - xml and annotation. in your xml should be :

```<code><context:component-scan base-package="package....." />
</code>```

to support @Autowired and CustomerBean should be @service or @component.

vaiant1 :

add  into xml and

```<code>@Component
class CustomerBean {

    private String custName;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void setCustName(String custName) {
        this.custName = custName;
        jdbcTemplate.update(query);
    }
}
</code>```

variant2 :

class CustomerBean {

```<code>private String custName;
private JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
     this.jdbcTemplate = jdbcTemplate;
}

public void setCustName(String custName) {
   this.custName = custName;
   jdbcTemplate.update(query);
}
</code>```

}

and xml

```<code> <bean id="custBean" class="com.test.CustomerBean">
        <property name="custName" value="John" />
        <property name="jdbcTemplate" ref="myjdbcTemplate" />
 </bean>
</code>```

Title: Bean instance is not getting loaded

Body:
I need a help regarding dependency injection.

I hava a bean class which is having a object reference of JdbcTemplate and I am using @Autowired to
create instance of that object. But that object is not getting loaded and as a result NullPointerException is thrown
from setCustName() method.

Please help

Bean Class :

class CustomerBean {

    private String custName;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void setCustName(String custName) {
    this.custName = custName;
    jdbcTemplate.update(query);
    }
}

XML :

<bean id="myjdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
 </bean>

 <bean id="custBean" class="com.test.CustomerBean">
        <property name="custName" value="John" />
 </bean>

Stacktrace:

PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'custName' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:334)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1419)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1160)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)

Body:
you get NullPointerException  as jdbcTemplate is null / not injected.

if you describe bean custBean by xml , as you did, you should add :
< property name="jdbcTemplate" value="myjdbcTemplate" /> for inject jdbcTemplate into your bean.

you have mixed configuration - xml and annotation. in your xml should be :

<context:component-scan base-package="package....." />

to support @Autowired and CustomerBean should be @service or @component.

vaiant1 :

add  into xml and

@Component
class CustomerBean {

    private String custName;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void setCustName(String custName) {
        this.custName = custName;
        jdbcTemplate.update(query);
    }
}

variant2 :

class CustomerBean {

private String custName;
private JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
     this.jdbcTemplate = jdbcTemplate;
}

public void setCustName(String custName) {
   this.custName = custName;
   jdbcTemplate.update(query);
}

}

and xml

 <bean id="custBean" class="com.test.CustomerBean">
        <property name="custName" value="John" />
        <property name="jdbcTemplate" ref="myjdbcTemplate" />
 </bean>