问:
Unable to convert Firebase JSON to Java Object using FirebaseRecyclerAdapter
I have two activities, one to create an Assessment object, and another to list the Assessment objects in Firebase, however I've encountered an issue: the POJO is able to serialize to JSON just fine, however the FirebaseRecyclerAdapter doesn't seem to be able to return the JSON data to the object type.

Here is my object file:

```<code>@IgnoreExtraProperties
public class Assessment {

private String company;
private String industry;
private String location;
private String product;
private String ownerId;
private String ownerName;
private boolean isDraft;
private boolean isQuickWalk;
private Map<String, Category> categories;

public Assessment() {
    // Default constructor required for calls to DataSnapshot.getValue()
}

public Assessment(String companyName, String industryName, String locationName,
                  String productName, String ownerId, String ownerName, boolean isDraft, boolean isQuickWalk, Map<String, Category> categories) {
    this.company = companyName;
    this.industry = industryName;
    this.location = locationName;
    this.product = productName;
    this.ownerId = ownerId;
    this.ownerName = ownerName;
    this.isDraft = isDraft;
    this.isQuickWalk = isQuickWalk;
    this.categories = categories;
}

public String getCompanyName() {
    return company;
}

public String getIndustryName() {
    return industry;
}

public String getLocationName() {
    return location;
}

public String getProductName() {
    return product;
}

public String getOwnerName() {
    return ownerName;
}

public boolean getIsDraft() {
    return isDraft;
}

public boolean getIsQuickWalk() {
    return isQuickWalk;
}
</code>```

Based on this, I use this code to write to Firebase and it all works fine:

```<code>String key = mDatabaseRef.child(FIREBASE_ASSESSMENTS).push().getKey();
Assessment assessment = new Assessment(editCompanyText, editLocationText,
                        editIndustryText, editProductText, uid,
currentUser.getEmail(), isDraft, isQuickWalk, null);

Map<String, Object> childUpdates = new HashMap<>();
                childUpdates.put("/" + FIREBASE_ASSESSMENTS + "/" + key,
assessment);
mDatabaseRef.updateChildren(childUpdates);
</code>```

However, when I try to read from the database I believe this is where the problem lies:

```<code>FirebaseRecyclerAdapter<Assessment, ViewDraftsViewHolder> adapter;
    mRecyclerView = (RecyclerView) findViewById(R.id.draft_recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    Query query = mEvalRef;
    FirebaseRecyclerOptions<Assessment> options = new FirebaseRecyclerOptions.Builder<Assessment>()
            .setQuery(query, Assessment.class)
            .build();

    adapter = new FirebaseRecyclerAdapter<Assessment, ViewDraftsViewHolder>(options) {
        @Override
        protected void onBindViewHolder(ViewDraftsViewHolder holder, int position, Assessment model) {
            if(model.getIsDraft()) {
                holder.companyName.setText(model.getCompanyName());
                holder.industryName.setText(model.getIndustryName());
                holder.locationName.setText(model.getLocationName());
                holder.productName.setText(model.getProductName());
                holder.ownerName.setText(model.getOwnerName());

                if(model.getIsQuickWalk()) {
                    holder.isQuickWalk.setText("Quick Walkthrough");
                } else {
                    holder.isQuickWalk.setText("Full Questionnaire");
                }
            }

        }

        @Override
        public ViewDraftsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.completed_and_drafts_list_item, parent, false);
            return new ViewDraftsViewHolder(view);
        }
    };

    mRecyclerView.setAdapter(adapter);

    private static class ViewDraftsViewHolder extends RecyclerView.ViewHolder {
    TextView companyName;
    TextView industryName;
    TextView locationName;
    TextView productName;
    TextView ownerName;
    TextView isQuickWalk;

    public ViewDraftsViewHolder(View itemView) {
        super(itemView);

        companyName = (TextView) itemView.findViewById(R.id.companyView);
        industryName = (TextView) itemView.findViewById(R.id.industryView);
        locationName = (TextView) itemView.findViewById(R.id.locationView);
        productName = (TextView) itemView.findViewById(R.id.productView);
        ownerName = (TextView) itemView.findViewById(R.id.ownerName);
        isQuickWalk = (TextView) itemView.findViewById(R.id.isQuickWalkView);
    }
}
</code>```

I'm not exactly sure where I'm going wrong that the FirebaseRecyclerAdapter is unable to convert the data back to an Assessment Object. Did i not set the object up correctly? Did I not set the RecyclerAdapter up correctly? This is how the data looks in Firebase

```<code>"-KzB39l1KH6MyEsgr6Ke" : {
  "companyName" : "testing ",
  "industryName" : "at",
  "isDraft" : true,
  "isQuickWalk" : true,
  "locationName" : "five fifteen",
  "ownerName" : "test@email.com",
  "productName" : "please ignore"
},
</code>```

any help you can give me would be excellent, I have been struggling with wrapping my head around this for a few days. Thanks!!

答:
At this line:

```<code>  Query query = mEvalRef;
</code>```

I assume mEvalRef is a database reference, can you show it because its not clear how you query the data from the database.

just add (mEvalRef), in order to find the problem.

Edit

in your (Assessment) class , I noticed that there is no setter methods for the variable, add setter for each variable in the class and see if this helps.

EDIT 2

in your code where you try to read the values.

remove this

```<code>    FirebaseRecyclerOptions<Assessment> options = new FirebaseRecyclerOptions.Builder<Assessment>()
        .setQuery(query, Assessment.class)
        .build();
</code>```

and in this line or part of the adapter initialization:

```<code>   adapter = new FirebaseRecyclerAdapter<Assessment, ViewDraftsViewHolder>(options)
</code>```

remove the (options) parameter and change the above line of code to this:

```<code>      adapter = new FirebaseRecyclerAdapter<Assessment, ViewDraftsViewHolder>(Assessment.class, R.layout.completed_and_drafts_list_item, ViewDraftsViewHolder.class, query )
</code>```

next remove this code:

```<code>        @Override
    public ViewDraftsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.completed_and_drafts_list_item, parent, false);
        return new ViewDraftsViewHolder(view);
    }
</code>```

and finally change the (private) to (public) in this:

```<code>    private static class ViewDraftsViewHolder extends RecyclerView.ViewHolder {
</code>```

and don't forget to keep the setters for variables in assessment class and make the variables public as I told you.

EDIT 3

now forget about EDIT 2 and retype your code the way you originally did it and just do this after you configured everything:

in the method where you initialize the adapter, add before this:

```<code>   mRecyclerView.setAdapter(adapter);
</code>```

this:

```<code>   adapter.startListening();
</code>```

Body:
I have two activities, one to create an Assessment object, and another to list the Assessment objects in Firebase, however I've encountered an issue: the POJO is able to serialize to JSON just fine, however the FirebaseRecyclerAdapter doesn't seem to be able to return the JSON data to the object type.

Here is my object file:

@IgnoreExtraProperties
public class Assessment {

private String company;
private String industry;
private String location;
private String product;
private String ownerId;
private String ownerName;
private boolean isDraft;
private boolean isQuickWalk;
private Map<String, Category> categories;

public Assessment() {
    // Default constructor required for calls to DataSnapshot.getValue()
}

public Assessment(String companyName, String industryName, String locationName,
                  String productName, String ownerId, String ownerName, boolean isDraft, boolean isQuickWalk, Map<String, Category> categories) {
    this.company = companyName;
    this.industry = industryName;
    this.location = locationName;
    this.product = productName;
    this.ownerId = ownerId;
    this.ownerName = ownerName;
    this.isDraft = isDraft;
    this.isQuickWalk = isQuickWalk;
    this.categories = categories;
}

public String getCompanyName() {
    return company;
}

public String getIndustryName() {
    return industry;
}

public String getLocationName() {
    return location;
}

public String getProductName() {
    return product;
}

public String getOwnerName() {
    return ownerName;
}

public boolean getIsDraft() {
    return isDraft;
}

public boolean getIsQuickWalk() {
    return isQuickWalk;
}

Based on this, I use this code to write to Firebase and it all works fine:

String key = mDatabaseRef.child(FIREBASE_ASSESSMENTS).push().getKey();
Assessment assessment = new Assessment(editCompanyText, editLocationText,
                        editIndustryText, editProductText, uid,
currentUser.getEmail(), isDraft, isQuickWalk, null);

Map<String, Object> childUpdates = new HashMap<>();
                childUpdates.put("/" + FIREBASE_ASSESSMENTS + "/" + key,
assessment);
mDatabaseRef.updateChildren(childUpdates);

However, when I try to read from the database I believe this is where the problem lies:

FirebaseRecyclerAdapter<Assessment, ViewDraftsViewHolder> adapter;
    mRecyclerView = (RecyclerView) findViewById(R.id.draft_recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    Query query = mEvalRef;
    FirebaseRecyclerOptions<Assessment> options = new FirebaseRecyclerOptions.Builder<Assessment>()
            .setQuery(query, Assessment.class)
            .build();

    adapter = new FirebaseRecyclerAdapter<Assessment, ViewDraftsViewHolder>(options) {
        @Override
        protected void onBindViewHolder(ViewDraftsViewHolder holder, int position, Assessment model) {
            if(model.getIsDraft()) {
                holder.companyName.setText(model.getCompanyName());
                holder.industryName.setText(model.getIndustryName());
                holder.locationName.setText(model.getLocationName());
                holder.productName.setText(model.getProductName());
                holder.ownerName.setText(model.getOwnerName());

                if(model.getIsQuickWalk()) {
                    holder.isQuickWalk.setText("Quick Walkthrough");
                } else {
                    holder.isQuickWalk.setText("Full Questionnaire");
                }
            }

        }

        @Override
        public ViewDraftsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.completed_and_drafts_list_item, parent, false);
            return new ViewDraftsViewHolder(view);
        }
    };

    mRecyclerView.setAdapter(adapter);

    private static class ViewDraftsViewHolder extends RecyclerView.ViewHolder {
    TextView companyName;
    TextView industryName;
    TextView locationName;
    TextView productName;
    TextView ownerName;
    TextView isQuickWalk;

    public ViewDraftsViewHolder(View itemView) {
        super(itemView);

        companyName = (TextView) itemView.findViewById(R.id.companyView);
        industryName = (TextView) itemView.findViewById(R.id.industryView);
        locationName = (TextView) itemView.findViewById(R.id.locationView);
        productName = (TextView) itemView.findViewById(R.id.productView);
        ownerName = (TextView) itemView.findViewById(R.id.ownerName);
        isQuickWalk = (TextView) itemView.findViewById(R.id.isQuickWalkView);
    }
}

I'm not exactly sure where I'm going wrong that the FirebaseRecyclerAdapter is unable to convert the data back to an Assessment Object. Did i not set the object up correctly? Did I not set the RecyclerAdapter up correctly? This is how the data looks in Firebase

"-KzB39l1KH6MyEsgr6Ke" : {
  "companyName" : "testing ",
  "industryName" : "at",
  "isDraft" : true,
  "isQuickWalk" : true,
  "locationName" : "five fifteen",
  "ownerName" : "test@email.com",
  "productName" : "please ignore"
},

any help you can give me would be excellent, I have been struggling with wrapping my head around this for a few days. Thanks!!

Body:
At this line:

  Query query = mEvalRef;

I assume mEvalRef is a database reference, can you show it because its not clear how you query the data from the database.

just add (mEvalRef), in order to find the problem.

Edit

in your (Assessment) class , I noticed that there is no setter methods for the variable, add setter for each variable in the class and see if this helps.

EDIT 2

in your code where you try to read the values.

remove this

    FirebaseRecyclerOptions<Assessment> options = new FirebaseRecyclerOptions.Builder<Assessment>()
        .setQuery(query, Assessment.class)
        .build();

and in this line or part of the adapter initialization:

   adapter = new FirebaseRecyclerAdapter<Assessment, ViewDraftsViewHolder>(options)

remove the (options) parameter and change the above line of code to this:

      adapter = new FirebaseRecyclerAdapter<Assessment, ViewDraftsViewHolder>(Assessment.class, R.layout.completed_and_drafts_list_item, ViewDraftsViewHolder.class, query )

next remove this code:

        @Override
    public ViewDraftsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.completed_and_drafts_list_item, parent, false);
        return new ViewDraftsViewHolder(view);
    }

and finally change the (private) to (public) in this:

    private static class ViewDraftsViewHolder extends RecyclerView.ViewHolder {

and don't forget to keep the setters for variables in assessment class and make the variables public as I told you.

EDIT 3

now forget about EDIT 2 and retype your code the way you originally did it and just do this after you configured everything:

in the method where you initialize the adapter, add before this:

   mRecyclerView.setAdapter(adapter);

this:

   adapter.startListening();


来源: stackexchange

问:
IF ELSE IF error , 1st condition working only
I am trying change one column value with a link, like if the column value is published it will changed to unpublished and vice versa. But the problem is that only if condition is working not else if.

Here is the link:

```<code>echo "<td><a href='testi.php?change_status={$testi_id}&status={$testi_status}'>Publish / Unpublish</a></td>";
</code>```

And the php code to change the status:

```<code><?php
if(isset($_GET['change_status'])){
    $the_status =  escape($_GET['status']);
    $the_testi_id = escape($_GET['change_status']);

    if  ($the_status='published'){
    $query = "UPDATE testimonial SET testi_status = 'unpublished' WHERE testi_id = $the_testi_id   ";
    $change_to_sub_query = mysqli_query($connection, $query); }

   else if ($the_status='unpublished'){
        $query = "UPDATE testimonial SET testi_status = 'published' WHERE testi_id = $the_testi_id   ";
        $change_to_sub_query = mysqli_query($connection, $query);

    }

    header("Location: testi.php");

}  ?>
</code>```

答:
Single = sets, double == checks, triple === checks explicitly.

When you do

```<code>if ($value='foo') {}
</code>```

What it is doing is checking if $value was set to 'foo' which will always evaluate to true.

So you want if ($value == 'foo') instead.

In what you have written, it will never evaluate the elseif because if will always be true.

For reference, the difference between == and ===

```<code>//evalates to true
if (1 == true) { ... }

//evaluates to false
if (1 === true) { ... }

//evaluates to true
if (1 === 1) { ... }

//evaluates to true
if (true === true) { ... }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying change one column value with a link, like if the column value is published it will changed to unpublished and vice versa. But the problem is that only if condition is working not else if.

Here is the link:

echo "Publish / Unpublish	";

And the php code to change the status:

<?php
if(isset($_GET['change_status'])){
    $the_status =  escape($_GET['status']);
    $the_testi_id = escape($_GET['change_status']);

    if  ($the_status='published'){
    $query = "UPDATE testimonial SET testi_status = 'unpublished' WHERE testi_id = $the_testi_id   ";
    $change_to_sub_query = mysqli_query($connection, $query); }

   else if ($the_status='unpublished'){
        $query = "UPDATE testimonial SET testi_status = 'published' WHERE testi_id = $the_testi_id   ";
        $change_to_sub_query = mysqli_query($connection, $query);

    }

    header("Location: testi.php");

}  ?>

Body:
Single = sets, double == checks, triple === checks explicitly.

When you do

if ($value='foo') {}

What it is doing is checking if $value was set to 'foo' which will always evaluate to true.

So you want if ($value == 'foo') instead.

In what you have written, it will never evaluate the elseif because if will always be true.

For reference, the difference between == and ===

//evalates to true
if (1 == true) { ... }

//evaluates to false
if (1 === true) { ... }

//evaluates to true
if (1 === 1) { ... }

//evaluates to true
if (true === true) { ... }


问:
Overlay bigger than video under it
I'm trying to put a video under a purple layer but my video doesn't fit the overlay correctly.

Or if I delete this background-size: cover; in home section looks like this:

.videoContainer {}

.videoContainer .overlay { /* ? */
  position: fixed;
  top: 0;
  left: 0;
  z-index: 2;
  opacity: .5;
}

.videoContainer video {
  width: 100%;
  position: absolute;
  z-index: -1;
}

.home-section {
  // background-size: cover;
  background-repeat: no-repeat;
  background-image: url('?');
  z-index: 9999;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="home-section section">
  <div class="videoContainer">
    <video autoplay loop muted>
      <source src="?" type="video/mp4">
    </video>
  </div>
</div></code>```

Edited: added source code link:

Download source code

答:
Based on the source code you linked to, here are CSS changes that I think will do what you are trying to achieve.

The two issues I see with your current approach are that you are not stretching the video to fill .home-section, and neither are you stretching .home-section's background image (the overlay) to fill .home-section.

```<code>.home-section {
    position: relative;
    background-size: cover;
    background-repeat: no-repeat;
    background-image: url(../res/bg_color_home.png);
    /* make sure to remove the z-index declaration */
}
.videoContainer {
    /* make video container fill its parent: */
    position: absolute;
    width: 100%;
    height: 100%;
    /* move it below .home-section: */
    z-index: -1;
}
.videoContainer video {
    /* make the video fill its parent: */
    width: 100%;
    height: 100%;
    /* and retain its aspect ratio: */
    object-fit: cover;
}
</code>```

Please note that the method of stretching the video to fill its container (object-fit) may not work in all browsers, and depending on the level of browser support you wish to provide, you may want to use a different method for scaling the video. I have used it because it is quick and easy.

Title: Overlay bigger than video under it

Body:
I'm trying to put a video under a purple layer but my video doesn't fit the overlay correctly.

Or if I delete this background-size: cover; in home section looks like this:

.videoContainer {}

.videoContainer .overlay { /* ? */
  position: fixed;
  top: 0;
  left: 0;
  z-index: 2;
  opacity: .5;
}

.videoContainer video {
  width: 100%;
  position: absolute;
  z-index: -1;
}

.home-section {
  // background-size: cover;
  background-repeat: no-repeat;
  background-image: url('?');
  z-index: 9999;
}

    <video autoplay loop muted>
      <source src="?" type="video/mp4">
    </video>

Edited: added source code link:

Download source code

Body:
Based on the source code you linked to, here are CSS changes that I think will do what you are trying to achieve.

The two issues I see with your current approach are that you are not stretching the video to fill .home-section, and neither are you stretching .home-section's background image (the overlay) to fill .home-section.

.home-section {
    position: relative;
    background-size: cover;
    background-repeat: no-repeat;
    background-image: url(../res/bg_color_home.png);
    /* make sure to remove the z-index declaration */
}
.videoContainer {
    /* make video container fill its parent: */
    position: absolute;
    width: 100%;
    height: 100%;
    /* move it below .home-section: */
    z-index: -1;
}
.videoContainer video {
    /* make the video fill its parent: */
    width: 100%;
    height: 100%;
    /* and retain its aspect ratio: */
    object-fit: cover;
}

Please note that the method of stretching the video to fill its container (object-fit) may not work in all browsers, and depending on the level of browser support you wish to provide, you may want to use a different method for scaling the video. I have used it because it is quick and easy.


问:
Is there a way to store session information without using cookies?
I'd like to know if it's possible to somehow store session data that does not involve cookies. I tried to look it up but I could only find information involving cookies. I read about storing all data except the session id in the database, and then the id on a cookie, but it still involves cookies.

Is it possible or are cookies always required to some extent with sessions?

答:
Thing called "sessionId" in url -yes, in every request after session is created - is the alternative stuff.

In every request there is transferred stuff like
    sessionId=456um2894myfy6273ynd2

Then it is up to service side how to dig the session data based on this id.


问:
How to merge 2 separate streams, buffer populated data from them and subsrcibe to it after some amout of time
I am trying to test situation like this:

I have 2 classess which just extends from the same Parent.

I am creating and Observables from the list of items for each of the class:

```<code>val listSomeClass1 = ArrayList<SomeClass1>()
val listSomeClass2 = ArrayList<SomeClass2>()

fun populateJust1() {
    listSomeClass1.add(SomeClass1("23", 23))
    listSomeClass1.add(SomeClass1("24", 24))
    listSomeClass1.add(SomeClass1("25", 25))
}

fun populateJust2() {
    listSomeClass2.add(SomeClass2(23.00))
    listSomeClass2.add(SomeClass2(24.00))
    listSomeClass2.add(SomeClass2(25.00))
}

populateItemsSomeClass1()
populateItemsSomeClass2()
</code>```

Now i can create 2 observables:

```<code>  val someClass1Observable = Observable.fromIterable(listSomeClass1)
  val someClass2Observable = Observable.fromIterable(listSomeClass2)
</code>```

And here, i want to merge emission from them, buffer it, and subscribe to it after 10 seconds:

```<code>      Observable.merge(someClass1Observable, someClass2Observable)
            .buffer(10, TimeUnit.SECONDS)
            .doOnSubscribe { Log.v("parentObservable", "STARTED") }
            .subscribe { t: MutableList<Parent> ->
                Log.v("parentObservable", "onNext")
                t.forEach { Log.v("onNext", it.toString()) }
            }
</code>```

However, the observable is not starting after 10 seconds as i expected, and just starts immedietaly with this data ready.
How to simulate something like this, that i will gather 2 separate streams and after 10 seconds i will be able to get the gathered data

I must point that i don't want to use any Subject.

UPDATE

I've done somehitng like this:

```<code>  val list1 = listOf(SomeClass1("1", 1), SomeClass1("2", 2), SomeClass1("3", 3))
    val list2 = listOf(SomeClass2(5.00), SomeClass2(4.00), SomeClass2(6.00))

    val someClass1Observable = Observable
            .fromIterable(list1)
            .zipWith(Observable.interval(2, TimeUnit.SECONDS),
                    BiFunction { item: SomeClass1, _: Long -> item })

    val someClass2Observable = Observable
            .fromIterable(list2)
            .zipWith(Observable.interval(1, TimeUnit.SECONDS),
                    BiFunction { item: SomeClass2, _: Long -> item })

    someClass1Observable.subscribe {
                Log.v("someClass1", it.toString())
            }

    someClass2Observable.subscribe {
                Log.v("someClass2", it.toString())
            }

    Observable.merge(someClass1Observable, someClass2Observable)
            .buffer(10, TimeUnit.SECONDS)
            .delay(10, TimeUnit.SECONDS)
            .doOnSubscribe { Log.v("parentObservable", "STARTED") }
            .subscribe { t: MutableList<Parent> ->
                Log.v("parentObservable", "onNext")
                t.forEach { Log.v("onNext", it.toString()) }
            }

    Thread.sleep(13000)

    someClass1Observable.subscribe {
        Log.v("someClass1", it.toString())
    }

    someClass2Observable.subscribe {
        Log.v("someClass2", it.toString())
    }
</code>```

Here, i want to just simulate 2 infinite streams of someClass1 and someclass2 Observables and same for the merge Observable.

Again, i want to have ability to merge those 2 streams, buffer populated data and do something with it after 10 seconds. If after 10 seconds those 2 streams will again populate some data, the merge Observable should clean previous buffer, and should again buffer new data and emit after 10 seconds and so on, infinite. However, my code is not working as i expected, what changes I need to do to make it as i described?

答:
I think you're looking for the delay operator

http://reactivex.io/documentation/operators/delay.html

Delay
  shift the emissions from an Observable forward in time by a particular amount

So something like:

```<code>.delay(10, TimeUnit.SECONDS)
</code>```

Body:
I am trying to test situation like this:

I have 2 classess which just extends from the same Parent.

I am creating and Observables from the list of items for each of the class:

val listSomeClass1 = ArrayList<SomeClass1>()
val listSomeClass2 = ArrayList<SomeClass2>()

fun populateJust1() {
    listSomeClass1.add(SomeClass1("23", 23))
    listSomeClass1.add(SomeClass1("24", 24))
    listSomeClass1.add(SomeClass1("25", 25))
}

fun populateJust2() {
    listSomeClass2.add(SomeClass2(23.00))
    listSomeClass2.add(SomeClass2(24.00))
    listSomeClass2.add(SomeClass2(25.00))
}

populateItemsSomeClass1()
populateItemsSomeClass2()

Now i can create 2 observables:

  val someClass1Observable = Observable.fromIterable(listSomeClass1)
  val someClass2Observable = Observable.fromIterable(listSomeClass2)

And here, i want to merge emission from them, buffer it, and subscribe to it after 10 seconds:

      Observable.merge(someClass1Observable, someClass2Observable)
            .buffer(10, TimeUnit.SECONDS)
            .doOnSubscribe { Log.v("parentObservable", "STARTED") }
            .subscribe { t: MutableList<Parent> ->
                Log.v("parentObservable", "onNext")
                t.forEach { Log.v("onNext", it.toString()) }
            }

However, the observable is not starting after 10 seconds as i expected, and just starts immedietaly with this data ready.
How to simulate something like this, that i will gather 2 separate streams and after 10 seconds i will be able to get the gathered data

I must point that i don't want to use any Subject.

UPDATE

I've done somehitng like this:

  val list1 = listOf(SomeClass1("1", 1), SomeClass1("2", 2), SomeClass1("3", 3))
    val list2 = listOf(SomeClass2(5.00), SomeClass2(4.00), SomeClass2(6.00))

    val someClass1Observable = Observable
            .fromIterable(list1)
            .zipWith(Observable.interval(2, TimeUnit.SECONDS),
                    BiFunction { item: SomeClass1, _: Long -> item })

    val someClass2Observable = Observable
            .fromIterable(list2)
            .zipWith(Observable.interval(1, TimeUnit.SECONDS),
                    BiFunction { item: SomeClass2, _: Long -> item })

    someClass1Observable.subscribe {
                Log.v("someClass1", it.toString())
            }

    someClass2Observable.subscribe {
                Log.v("someClass2", it.toString())
            }

    Observable.merge(someClass1Observable, someClass2Observable)
            .buffer(10, TimeUnit.SECONDS)
            .delay(10, TimeUnit.SECONDS)
            .doOnSubscribe { Log.v("parentObservable", "STARTED") }
            .subscribe { t: MutableList<Parent> ->
                Log.v("parentObservable", "onNext")
                t.forEach { Log.v("onNext", it.toString()) }
            }

    Thread.sleep(13000)

    someClass1Observable.subscribe {
        Log.v("someClass1", it.toString())
    }

    someClass2Observable.subscribe {
        Log.v("someClass2", it.toString())
    }

Here, i want to just simulate 2 infinite streams of someClass1 and someclass2 Observables and same for the merge Observable.

Again, i want to have ability to merge those 2 streams, buffer populated data and do something with it after 10 seconds. If after 10 seconds those 2 streams will again populate some data, the merge Observable should clean previous buffer, and should again buffer new data and emit after 10 seconds and so on, infinite. However, my code is not working as i expected, what changes I need to do to make it as i described?

Body:
I think you're looking for the delay operator

http://reactivex.io/documentation/operators/delay.html

Delay
  shift the emissions from an Observable forward in time by a particular amount

So something like:

.delay(10, TimeUnit.SECONDS)


问:
jquery: append text and object results in [object Object]
I'm trying to dynamically place a button element next to some text but I'm getting the following in the DOM: Text next to button [object Object].

$btn = $('<button>').text('Button');
$('
').html('Text next to button ' + $btn).appendTo($('#test'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<div id="test"></div></code>```

jsfiddle: https://jsfiddle.net/p43rft4q/1/

What am I doing wrong here and how can I fix this?

答:
You have to append the text and then the element.  You were appending an object to text, which is why you were getting the [Object object].

$btn = $('<button>').text('Button');
$('
').append('Text next to button ').append($btn).appendTo($('#test'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<div id="test"></div></code>```

Body:
I'm trying to dynamically place a button element next to some text but I'm getting the following in the DOM: Text next to button [object Object].

$btn = $('<button>').text('Button');
$('
').html('Text next to button ' + $btn).appendTo($('#test'))

jsfiddle: https://jsfiddle.net/p43rft4q/1/

What am I doing wrong here and how can I fix this?

Body:
You have to append the text and then the element.  You were appending an object to text, which is why you were getting the [Object object].

$btn = $('<button>').text('Button');
$('<div>').append('Text next to button ').append($btn).appendTo($('#test'))

<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<div id="test"></div>


问:
Connection to server is ok, but I'm writing an empty string to the OutputStream
I can't figure out what is up with this code. First of all, as it is here, it works. But I'm afraid I have missed an important concept and I don't want it to come back and bite me later. My code below will write a blank line to a text log that I have created for testing purposes if I don't add the line "connection.getResponseMessage.' It will also work with 'getResponseCode.' Why?

Why does it write an empty buffer to the OutputStream without these codes?

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

    Context mContext;
    private static final String TAG = "AdminActivity";

    EditText mSystemID, mSystemPassword;
    RecyclerView mRecyclerView;
    Button mUpdateButton, mDownloadButton;
    FileItemAdapter mAdapter;

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

        mContext = this;

        mSystemID = findViewById(R.id.et_system_id);
        mSystemPassword = findViewById(R.id.et_system_password);
        mRecyclerView = findViewById(R.id.rv_file_names);
        mUpdateButton = findViewById(R.id.bt_update_files_list);
        mDownloadButton = findViewById(R.id.bt_download_file);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);

        DividerItemDecoration divider = new DividerItemDecoration(mContext, layoutManager.getOrientation());
        divider.setDrawable(ContextCompat.getDrawable(mContext, R.drawable.divider_dark));

        // TESTING TESTING TESTING TESTING TESTING //
        mUpdateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new SendInfoToServer().execute("A new Test");
            }
        });
    }

    private static class SendInfoToServer extends AsyncTask<String, String, String> {

        HttpURLConnection connection = null;  //***** Should eventually change to https instead of http
        OutputStream out = null;

        @Override
        protected String doInBackground(String... params) {

            String parameters = params[0];

            try {
                URL url = new URL("http://www.example.com/login/webhook.php");

                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.connect();

                out = new DataOutputStream(connection.getOutputStream());
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
                writer.write(parameters);
                writer.flush();
                writer.close();

                Log.d(TAG, "response message: " + connection.getResponseMessage());

            } catch (IOException e) {
                Log.d(TAG, "an error occured");
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
            return null;
        }

    }

}
</code>```

I've tried to ask this question multiple different ways and nobody has given me any useful input. This, I guess, is my last attempt to simplify the question. Above is the entire Activity. It has already been suggested to remove 'writer.close()' but that didn't work.

Thanks in advance

答:
HttpURLConnection has a terrible API and is very confusing to use.  I would strongly recommend using OkHttp in its place.  With OkHttp, you would make the request with the following code:

```<code>String parameters = params[0];
Response response;
try {
    MediaType contentType = MediaType.parse("text/plain; charset=utf-8");
    RequestBody body = RequestBody.create(contentType, parameters);
    Request request = new Request.Builder()
        .url("http://www.example.com/login/webhook.php")
        .post(body)
        .build();

    response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        return response.body().string();
    }
} catch (IOException e) {
    Log.d(TAG, "an error occured");
    e.printStackTrace();
} finally {
    if(response != null) {
        response.close();
    }
}
return null;
</code>```

If you want to stick with HttpURLConnection, this answer explains the connection process pretty well.

Body:
I can't figure out what is up with this code. First of all, as it is here, it works. But I'm afraid I have missed an important concept and I don't want it to come back and bite me later. My code below will write a blank line to a text log that I have created for testing purposes if I don't add the line "connection.getResponseMessage.' It will also work with 'getResponseCode.' Why?

Why does it write an empty buffer to the OutputStream without these codes?

public class AdminActivity extends AppCompatActivity {

    Context mContext;
    private static final String TAG = "AdminActivity";

    EditText mSystemID, mSystemPassword;
    RecyclerView mRecyclerView;
    Button mUpdateButton, mDownloadButton;
    FileItemAdapter mAdapter;

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

        mContext = this;

        mSystemID = findViewById(R.id.et_system_id);
        mSystemPassword = findViewById(R.id.et_system_password);
        mRecyclerView = findViewById(R.id.rv_file_names);
        mUpdateButton = findViewById(R.id.bt_update_files_list);
        mDownloadButton = findViewById(R.id.bt_download_file);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);

        DividerItemDecoration divider = new DividerItemDecoration(mContext, layoutManager.getOrientation());
        divider.setDrawable(ContextCompat.getDrawable(mContext, R.drawable.divider_dark));

        // TESTING TESTING TESTING TESTING TESTING //
        mUpdateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new SendInfoToServer().execute("A new Test");
            }
        });
    }

    private static class SendInfoToServer extends AsyncTask<String, String, String> {

        HttpURLConnection connection = null;  //***** Should eventually change to https instead of http
        OutputStream out = null;

        @Override
        protected String doInBackground(String... params) {

            String parameters = params[0];

            try {
                URL url = new URL("http://www.example.com/login/webhook.php");

                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.connect();

                out = new DataOutputStream(connection.getOutputStream());
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
                writer.write(parameters);
                writer.flush();
                writer.close();

                Log.d(TAG, "response message: " + connection.getResponseMessage());

            } catch (IOException e) {
                Log.d(TAG, "an error occured");
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
            return null;
        }

    }

}

I've tried to ask this question multiple different ways and nobody has given me any useful input. This, I guess, is my last attempt to simplify the question. Above is the entire Activity. It has already been suggested to remove 'writer.close()' but that didn't work.

Thanks in advance

Body:
HttpURLConnection has a terrible API and is very confusing to use.  I would strongly recommend using OkHttp in its place.  With OkHttp, you would make the request with the following code:

String parameters = params[0];
Response response;
try {
    MediaType contentType = MediaType.parse("text/plain; charset=utf-8");
    RequestBody body = RequestBody.create(contentType, parameters);
    Request request = new Request.Builder()
        .url("http://www.example.com/login/webhook.php")
        .post(body)
        .build();

    response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        return response.body().string();
    }
} catch (IOException e) {
    Log.d(TAG, "an error occured");
    e.printStackTrace();
} finally {
    if(response != null) {
        response.close();
    }
}
return null;

If you want to stick with HttpURLConnection, this answer explains the connection process pretty well.


问:
Creating a Morse Code translator for my programming class,having troubles with the output
this is my first post on this platform ,im kinda new to this java programing and also not that good at english :p

My teacher asked for a morse code translator that does morse to letters and vice versa

Here's the code i came up with:

```<code>import java.util.Scanner;
public class Morse2 {
    public static void main(String[] args){
 String[] letras = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
                  "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
                  "y", "z"};
 String[] MORSE = {
 ".-" ,"-...","-.-.","-.." ,"." ,
 "..-.","--." ,"....",".." ,".---",
 "-.-" ,".-..","--" ,"-." ,"---" ,
 ".--.","--.-",".-." ,"..." ,"-" ,
 "..-" ,"...-",".--", "-..-","-.--",
 "--.."};
System.out.println("Insira uma frase em codigo morse para uma traducao para texto ou vice-versa");
Scanner in=new Scanner(System.in);
String frase =in.nextLine();
String resp="";

frase=frase.toLowerCase();
String[] paraletras=frase.split("");
String[]paraMorse=frase.split(" ");
for(int i=0;i< paraletras.length;i++){
    for(int j=0;j< letras.length ;j++){
     if (paraletras[i].equals(letras[j])){
    resp=resp+ MORSE[j]+" ";}
    }
}
for(int k=0;k<paraMorse.length;k++){
     for (int l=0;l<MORSE.length;l++){
          if(paraMorse[k].equals(MORSE[l])){
    resp=resp+letras[l]+ " ";}}
    }

System.out.print(resp);}

    }
</code>```

The class compiles fine but im having some issues with my output,more specifically the order of the output:

e.g My input " a b -.- c "
    What i wanted ".- -... k -.-."
    What i got ".- -... -.-. k"
I believe that's because i used 2 for cycles instead of 1 but i cant really tell how to do it.Would apreciate some help
Also when the user writes an impossible character like "*" im suppossed to put an "?" in that position and im also strugling on that i dont know if i should use a if else cycle or what

Please help me and thank you everybody ^^

答:
Yes you are correct. It is because you run your loops sequentially.

You need one loop over your input, then check if one piece of input is a letter - take translation from letters array, if it is a MORSE take from Morse array.

Actaully arrays are not the best approach. It is much easier to use one Map where letter will be a key, MORSE will be a value.

then code may look like:

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

    String[] letras = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
            "s", "t", "u", "v", "w", "x", "y", "z" };
    String[] MORSE = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
            "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };
    System.out.println("Insira uma frase em codigo morse para uma traducao para texto ou vice-versa");

    Map<String, String> decodeMap = new HashMap<String, String>();

    for (int i=0; i< letras.length; i++)
    {
        decodeMap.put(letras[i], MORSE[i]);
    }

    Scanner in=new Scanner(System.in);
    String frase =in.nextLine();
    String resp = "";

    frase = frase.toLowerCase();
    String[] paraletras = frase.split(" ");
    for (int i = 0; i < paraletras.length; i++) {
        boolean gotValue = false;
        for (Entry<String, String> decodeEntry: decodeMap.entrySet()) {
          if (decodeEntry.getKey().equals(paraletras[i]))
          {
            // it is a letter print its MORSE
            resp += decodeEntry.getValue();
            gotValue = true;
            break;
          } else if (decodeEntry.getValue().equals(paraletras[i]))
          {
            // it is a MORSE - print its letter
            resp += decodeEntry.getKey();
            gotValue = true;
            break;
          }
        }
        if (gotValue)
        {
          resp += " ";
        }
    }
    System.out.print(resp);
}
</code>```

Body:
this is my first post on this platform ,im kinda new to this java programing and also not that good at english :p

My teacher asked for a morse code translator that does morse to letters and vice versa

Here's the code i came up with:

import java.util.Scanner;
public class Morse2 {
    public static void main(String[] args){
 String[] letras = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
                  "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
                  "y", "z"};
 String[] MORSE = {
 ".-" ,"-...","-.-.","-.." ,"." ,
 "..-.","--." ,"....",".." ,".---",
 "-.-" ,".-..","--" ,"-." ,"---" ,
 ".--.","--.-",".-." ,"..." ,"-" ,
 "..-" ,"...-",".--", "-..-","-.--",
 "--.."};
System.out.println("Insira uma frase em codigo morse para uma traducao para texto ou vice-versa");
Scanner in=new Scanner(System.in);
String frase =in.nextLine();
String resp="";

frase=frase.toLowerCase();
String[] paraletras=frase.split("");
String[]paraMorse=frase.split(" ");
for(int i=0;i< paraletras.length;i++){
    for(int j=0;j< letras.length ;j++){
     if (paraletras[i].equals(letras[j])){
    resp=resp+ MORSE[j]+" ";}
    }
}
for(int k=0;k<paraMorse.length;k++){
     for (int l=0;l<MORSE.length;l++){
          if(paraMorse[k].equals(MORSE[l])){
    resp=resp+letras[l]+ " ";}}
    }

System.out.print(resp);}

    }

The class compiles fine but im having some issues with my output,more specifically the order of the output:

e.g My input " a b -.- c "
    What i wanted ".- -... k -.-."
    What i got ".- -... -.-. k"
I believe that's because i used 2 for cycles instead of 1 but i cant really tell how to do it.Would apreciate some help
Also when the user writes an impossible character like "*" im suppossed to put an "?" in that position and im also strugling on that i dont know if i should use a if else cycle or what

Please help me and thank you everybody ^^

Body:
Yes you are correct. It is because you run your loops sequentially.

You need one loop over your input, then check if one piece of input is a letter - take translation from letters array, if it is a MORSE take from Morse array.

Actaully arrays are not the best approach. It is much easier to use one Map where letter will be a key, MORSE will be a value.

then code may look like:

 public static void main(String... args) {

    String[] letras = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
            "s", "t", "u", "v", "w", "x", "y", "z" };
    String[] MORSE = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
            "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };
    System.out.println("Insira uma frase em codigo morse para uma traducao para texto ou vice-versa");

    Map<String, String> decodeMap = new HashMap<String, String>();

    for (int i=0; i< letras.length; i++)
    {
        decodeMap.put(letras[i], MORSE[i]);
    }

    Scanner in=new Scanner(System.in);
    String frase =in.nextLine();
    String resp = "";

    frase = frase.toLowerCase();
    String[] paraletras = frase.split(" ");
    for (int i = 0; i < paraletras.length; i++) {
        boolean gotValue = false;
        for (Entry<String, String> decodeEntry: decodeMap.entrySet()) {
          if (decodeEntry.getKey().equals(paraletras[i]))
          {
            // it is a letter print its MORSE
            resp += decodeEntry.getValue();
            gotValue = true;
            break;
          } else if (decodeEntry.getValue().equals(paraletras[i]))
          {
            // it is a MORSE - print its letter
            resp += decodeEntry.getKey();
            gotValue = true;
            break;
          }
        }
        if (gotValue)
        {
          resp += " ";
        }
    }
    System.out.print(resp);
}


问:
Visual Studio IDE will not restore after being minimized
After I minimize My Visual Studio IDE, it is visible on the task bar, but will not restore when selected.  I am forced to close the instance of Visual Studio and restart.  This is an obvious pain.

Other applications on machine do not suffer this problem.

Environment is Visual Studio 2010, Windows 7, 64 bit OS.

Thanks in advance for any ideas.

Jim

答: Do you use multiple monitors?  If so it could be that when clicked on the Visual Studio IDE is opening up outwith the space of the current monitors?  I had this same problem with my Novell mail client.</p>

ContentLicense: CC BY-SA 2.5


问:
Finding a subset of numbers that will give you the max sum
How to find a subset of numbers from 2 to 1000 that will give you the max sum under the condition that any two numbers from the subset don't share common prime factors (e.g., 1000 and 500 share the prime factor 2)?

One (maybe easier) variation to the above question: what is the largest number in the subset? We know that 997 is a prime number, and it is easy to rule out 1000 and 998, thus the question becomes whether is 999 in the subset?

答:
Create a graph with nodes {2, ...,  1000}, and edges when nodes have gcd > 1. Solution to this problem is same as finding maximum-weight independent set problem, which is NP-hard except in some special cases. This graph case doesn't look like a spacial case from list on Wikipedia page or even on this list.

Update

As James suggested it is possible to reduce number of nodes in this graph. Lets say that signature of a number N with prime decomposition p1^k1*...*pn^kn is a tuple (p1, ..., pn).

First reduction is to remove nodes when there is nodes with larger value and same signature. That reduces graph to 607 nodes.

Next reduction is to remove node N with signature (p1, ..., pn) if there are nodes with signatures that is decomposition of (p1, ..., pn) and there sum is >= N. That reduces graph to 277 nodes.

From these nodes 73 are isolated nodes (primes > 500.)


问:
Getting weird popup in IE while using ADAL.js for login to Azure
I am using ADAL.js for log-in to Azure. But getting this weird popup, in which I have to explicitly select Continue to Website. How could I avoid this?

How could I avoid this?

答: This popup typically means the site certificate isn't trusted by your client. Verify that the site's certificate was issued by a trusted issuer. If yes, download and copy the public portion of the cert (.cer) from the site and import into your local machine account's trusted store and that should hopefully resolve your issue.</p>


问:
Python - AttributeError: 'Particle' object has no attribute 'display'
This question is asked a lot, but unfortunately I found no answer fitting my problem. If possible, I prefer a generic answer, since I'm a novice trying to learn Python. Thank you in advance.

This is the code I got by following a tutorial on the basics of python using the pygame library:

```<code>import pygame

background_colour = (255, 255, 255)
(width, height) = (300, 200)

class Particle:
    def __init__(self, x, y, size):
        self.x = x
        self.y = y
        self.size = size
        self.colour = (0, 0, 255)
        self.thickness = 1

screen = pygame.display.set_mode((width, height))

def display(self):
    pygame.draw.circle(screen, self.colour, (self.x, self.y), self.size,  self.thickness)

pygame.display.set_caption('Agar')
screen.fill(background_colour)
pygame.display.flip()

running = True
my_first_particle = Particle(150, 50, 15)
my_first_particle.display()
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
</code>```

It is used to create a window for gaming, with a circle in it. The circle is defined as a class to be used multiple times in a similar way later on.

I got the following error:

```<code>Traceback (most recent call last):
  File "C:/Users/20172542/PycharmProjects/agarTryout/Agar.py", line 29, in <module>
    my_first_particle.display()
AttributeError: 'Particle' object has no attribute 'display'
</code>```

What principle am I not understanding, and what is the specific solution for this error?

Thank you for your time and effort.

答:
The display function defined is not inside Particle, instead at the global (not sure if this name is right) level of your script. Indentation is significant in python, as it does not have brackets. Move the function after your __init__ function, with the same indentation.

Also, I guess you should move screen above your Particle definition.

Body:
This question is asked a lot, but unfortunately I found no answer fitting my problem. If possible, I prefer a generic answer, since I'm a novice trying to learn Python. Thank you in advance.

This is the code I got by following a tutorial on the basics of python using the pygame library:

import pygame

background_colour = (255, 255, 255)
(width, height) = (300, 200)

class Particle:
    def __init__(self, x, y, size):
        self.x = x
        self.y = y
        self.size = size
        self.colour = (0, 0, 255)
        self.thickness = 1

screen = pygame.display.set_mode((width, height))

def display(self):
    pygame.draw.circle(screen, self.colour, (self.x, self.y), self.size,  self.thickness)

pygame.display.set_caption('Agar')
screen.fill(background_colour)
pygame.display.flip()

running = True
my_first_particle = Particle(150, 50, 15)
my_first_particle.display()
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

It is used to create a window for gaming, with a circle in it. The circle is defined as a class to be used multiple times in a similar way later on.

I got the following error:

Traceback (most recent call last):
  File "C:/Users/20172542/PycharmProjects/agarTryout/Agar.py", line 29, in <module>
    my_first_particle.display()
AttributeError: 'Particle' object has no attribute 'display'

What principle am I not understanding, and what is the specific solution for this error?

Thank you for your time and effort.


问:
Symfony2 recursive query builder
I am having a data-table which contains media,docs,pdfs and folders list. Same as Google Drive, I want to show breadcrumb at the top of the data-table. The data-table reflects the changes when clicks on any folders through jQuery. All things are ready except the breadcrumb. I have the id of current opened folder but I don't know how to get the hierarchy from root to current folder.

Currently it gives me the parent id and name not the whole hierarchy.

Note :- There is no relationship between the columns as it was in same table.

Entity Fields :- id, nameDisplay, parentId

Entity Definition :-

```<code>/**
 * driveall
 * @ORM\Table(name="Driveall")
 * @ORM\Entity(repositoryClass="DriveBundle\Repository\DriveallRepository")
 */
class Driveall
{
    /**
     * @var int
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     * @ORM\Column(name="Name_Display", type="string", length=255)
     */
    private $nameDisplay;

    /**
     * @var int
     * @ORM\Column(name="ParentID", type="integer")
     */
    private $parentID;

    /**
     * Get id
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set nameDisplay
     * @param string $nameDisplay
     * @return driveall
     */
    public function setNameDisplay($nameDisplay)
    {
        $this->nameDisplay = $nameDisplay;
        return $this;
    }

    /**
     * Get nameDisplay
     * @return string
     */
    public function getNameDisplay()
    {
        return $this->nameDisplay;
    }

    /**
     * Set parentID
     * @param integer $parentID
     * @return Driveall
     */
    public function setParentID($parentID)
    {
        $this->parentID = $parentID;
        return $this;
    }

    /**
     * Get parentID
     * @return integer
     */
    public function getParentID()
    {
        return $this->parentID;
    }
}
</code>```

Query builder :-

```<code>$qb = $this->_em->createQueryBuilder();
$qb->select("d.parentID,pid.nameDisplay")
   ->from($this->_entityName, 'd')
   ->leftJoin($this->_entityName, 'pid', 'WITH', 'pid.id = d.parentID')
   ->where("d.status=0")
   ->andWhere("d.id=" . $id)
   ->orderBy('d.nameDisplay', 'ASC');
$data = $qb->getQuery()
           ->getResult();
return $data;
</code>```

答:
I assume you have defined an entity class for your table using Doctrine annotations. eg.

```<code>/**
 * @ORM\Entity
 * @ORM\Table(name="folder")
 */
class Folder
{

/**
 * @ORM\Column(type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\Column(name="nameDisplay", type="string", length=100)
 */
private $nameDisplay;

/**
 * parentID
 * @ORM\Column(name="parentID", type="integer", nullable=true)
 */
private $parentId;
}
</code>```

You can use "createNativeQuery()" of your entity manager to achieve what you want:

```<code>use Doctrine\ORM\Query\ResultSetMapping;
...
$rsm = new ResultSetMapping();
$rsm->addEntityResult(\AppBundle\Entity\Folder::class, 'fd');

$rsm->addFieldResult('fd','id','id');
$rsm->addFieldResult('fd','nameDisplay','nameDisplay');

$query = $this->_em->createNativeQuery(
        'SELECT @id :=(SELECT parentID FROM ' . $this->_entityName .' WHERE id = @id) as id,(SELECT nameDisplay FROM ' . $this->_entityName .' WHERE id = @id) as nameDisplay
    FROM (SELECT  @id := ?) vars
    JOIN ' . $this->_entityName .' fd
    WHERE @id IS NOT NULL', $rsm);

$query->setParameter(1, 8);

$folderStructure = $query->getResult();
</code>```

Replace \AppBundle\Entity\Folder with your entity class and you should receive an array with entities ordered to the structure you want.
I could not map also the parentID to the result, but I believe that should be enough.

Original query that was used as reference can be found here

Title: Symfony2 recursive query builder

Body:
I am having a data-table which contains media,docs,pdfs and folders list. Same as Google Drive, I want to show breadcrumb at the top of the data-table. The data-table reflects the changes when clicks on any folders through jQuery. All things are ready except the breadcrumb. I have the id of current opened folder but I don't know how to get the hierarchy from root to current folder.

Currently it gives me the parent id and name not the whole hierarchy.

Note :- There is no relationship between the columns as it was in same table.

Entity Fields :- id, nameDisplay, parentId

Entity Definition :-

/**
 * driveall
 * @ORM\Table(name="Driveall")
 * @ORM\Entity(repositoryClass="DriveBundle\Repository\DriveallRepository")
 */
class Driveall
{
    /**
     * @var int
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     * @ORM\Column(name="Name_Display", type="string", length=255)
     */
    private $nameDisplay;

    /**
     * @var int
     * @ORM\Column(name="ParentID", type="integer")
     */
    private $parentID;

    /**
     * Get id
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set nameDisplay
     * @param string $nameDisplay
     * @return driveall
     */
    public function setNameDisplay($nameDisplay)
    {
        $this->nameDisplay = $nameDisplay;
        return $this;
    }

    /**
     * Get nameDisplay
     * @return string
     */
    public function getNameDisplay()
    {
        return $this->nameDisplay;
    }

    /**
     * Set parentID
     * @param integer $parentID
     * @return Driveall
     */
    public function setParentID($parentID)
    {
        $this->parentID = $parentID;
        return $this;
    }

    /**
     * Get parentID
     * @return integer
     */
    public function getParentID()
    {
        return $this->parentID;
    }
}

Query builder :-

$qb = $this->_em->createQueryBuilder();
$qb->select("d.parentID,pid.nameDisplay")
   ->from($this->_entityName, 'd')
   ->leftJoin($this->_entityName, 'pid', 'WITH', 'pid.id = d.parentID')
   ->where("d.status=0")
   ->andWhere("d.id=" . $id)
   ->orderBy('d.nameDisplay', 'ASC');
$data = $qb->getQuery()
           ->getResult();
return $data;

Body:
I assume you have defined an entity class for your table using Doctrine annotations. eg.

/**
 * @ORM\Entity
 * @ORM\Table(name="folder")
 */
class Folder
{

/**
 * @ORM\Column(type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\Column(name="nameDisplay", type="string", length=100)
 */
private $nameDisplay;

/**
 * parentID
 * @ORM\Column(name="parentID", type="integer", nullable=true)
 */
private $parentId;
}

You can use "createNativeQuery()" of your entity manager to achieve what you want:

use Doctrine\ORM\Query\ResultSetMapping;
...
$rsm = new ResultSetMapping();
$rsm->addEntityResult(\AppBundle\Entity\Folder::class, 'fd');

$rsm->addFieldResult('fd','id','id');
$rsm->addFieldResult('fd','nameDisplay','nameDisplay');

$query = $this->_em->createNativeQuery(
        'SELECT @id :=(SELECT parentID FROM ' . $this->_entityName .' WHERE id = @id) as id,(SELECT nameDisplay FROM ' . $this->_entityName .' WHERE id = @id) as nameDisplay
    FROM (SELECT  @id := ?) vars
    JOIN ' . $this->_entityName .' fd
    WHERE @id IS NOT NULL', $rsm);

$query->setParameter(1, 8);

$folderStructure = $query->getResult();

Replace \AppBundle\Entity\Folder with your entity class and you should receive an array with entities ordered to the structure you want.
I could not map also the parentID to the result, but I believe that should be enough.

Original query that was used as reference can be found here


问:
Why does the OnDownloadStart Method from Downloadlistener never gets called?
maybe you can help me.:)

Im developing an Android app with Xamarin in C#. Before i developed an ASP.NET Page, which should now be implemented in the app. Therefore i used a webview, and everything works fine. But i can't download any files from the server, which i dynamically create in the ASP.NET page.

I tried to implement a downloadlistener, but the OnDownloadStart Method never gets called.

Here are some parts of my code.

OnCreate Method:

```<code>... some Code
// Init Webview
var webViewMain = FindViewById<WebView> (Resource.Id.webViewMain);
webViewMain.Settings.JavaScriptEnabled = true;
webViewMain.SetWebViewClient (new MyCustomWebViewClient ());
webViewMain.SetWebChromeClient (new WebChromeClient ());
webViewMain.LoadUrl (LoadUrl);
</code>```

WebViewClient Class:

```<code>private class MyCustomWebViewClient: WebViewClient, IDownloadListener {

            ... some Code

            public void OnDownloadStart (string url, string userAgent, string contentDisposition, string mimetype, long contentLength)
            {
                Intent i = new Intent(Intent.ActionView);
                i.SetData(Android.Net.Uri.Parse("url"));
            }
}
</code>```

ASP.NET Download Code:

```<code>        ... some Code

        //ByteArray
        var client = new WebClient();
        long length = dataFile.Length;
        byte[] buffer = client.DownloadData(dataFile.FullName);

        File.Delete(dataFile.FullName);

        // Send to User
        page.Response.Clear();
        page.Response.ClearHeaders();
        page.Response.ClearContent();
        page.Response.AddHeader("content-disposition", "attachment; filename=" + dataFile.Name);
        page.Response.AddHeader("Content-Lengt", length.ToString());
        page.Response.ContentType = "application/octet-stream";
        page.Response.BinaryWrite(buffer);

        page.Response.End();
</code>```

Much thanks for your suggestions :)

答:
It's a bit late but your issue was that you needed to add the listener like:</p>

```<code>var c = new MyCustomWebViewClient ();
webViewMain.SetWebViewClient (c);
webViewMain.SetDownloadListener(c);
</code>```

Body:
maybe you can help me.:)

Im developing an Android app with Xamarin in C#. Before i developed an ASP.NET Page, which should now be implemented in the app. Therefore i used a webview, and everything works fine. But i can't download any files from the server, which i dynamically create in the ASP.NET page.

I tried to implement a downloadlistener, but the OnDownloadStart Method never gets called.

Here are some parts of my code.

OnCreate Method:

... some Code
// Init Webview
var webViewMain = FindViewById<WebView> (Resource.Id.webViewMain);
webViewMain.Settings.JavaScriptEnabled = true;
webViewMain.SetWebViewClient (new MyCustomWebViewClient ());
webViewMain.SetWebChromeClient (new WebChromeClient ());
webViewMain.LoadUrl (LoadUrl);

WebViewClient Class:

private class MyCustomWebViewClient: WebViewClient, IDownloadListener {

            ... some Code

            public void OnDownloadStart (string url, string userAgent, string contentDisposition, string mimetype, long contentLength)
            {
                Intent i = new Intent(Intent.ActionView);
                i.SetData(Android.Net.Uri.Parse("url"));
            }
}

ASP.NET Download Code:

        ... some Code

        //ByteArray
        var client = new WebClient();
        long length = dataFile.Length;
        byte[] buffer = client.DownloadData(dataFile.FullName);

        File.Delete(dataFile.FullName);

        // Send to User
        page.Response.Clear();
        page.Response.ClearHeaders();
        page.Response.ClearContent();
        page.Response.AddHeader("content-disposition", "attachment; filename=" + dataFile.Name);
        page.Response.AddHeader("Content-Lengt", length.ToString());
        page.Response.ContentType = "application/octet-stream";
        page.Response.BinaryWrite(buffer);

        page.Response.End();

Much thanks for your suggestions :)

Body:
It's a bit late but your issue was that you needed to add the listener like:

var c = new MyCustomWebViewClient ();
webViewMain.SetWebViewClient (c);
webViewMain.SetDownloadListener(c);


问:
Retrieve graphical representation of an alphabet letter
I spacial representation of characters ( eg 'A' ) in android. Something like an array of Points or a Path object or Vectors. I am going to draw characters on screen myself, instead of using canvas.drawText(). Is this possible?</p>

答:
Here's another way that returns Points:

```<code>private void textStuff() {
    int textSize = 32;
    char letter = 'A';
    getPointsForChar(textSize, letter);
}

@NonNull
private ArrayList<Point> getPointsForChar(int textSize, char letter) {
    Canvas canvas = new Canvas();
    Paint paint = new Paint();
    Bitmap bitmap = Bitmap.createBitmap((int) (float) textSize, (int) (float) textSize, Bitmap.Config.ALPHA_8);
    canvas.drawPaint(paint);
    canvas.setBitmap(bitmap);
    paint.setColor(Color.BLACK);
    paint.setTextSize(textSize);
    canvas.drawText(String.valueOf(letter), 0, (float) textSize, paint);
    Log.d("Font", "bitmap " + bitmap.toString());
    ArrayList<Point> points = new ArrayList<>();
    for (int x = 0; x < bitmap.getWidth(); x++) {
        for (int y = 0; y < bitmap.getHeight(); y++) {
            int pixel = bitmap.getPixel(x, y);
            if (pixel != Color.TRANSPARENT) {
                points.add(new Point(x, y));
            }
        }
    }

    StringBuilder stringBuilder = new StringBuilder("The following points make up '" + letter + "':");
    for (Point point : points) {
        stringBuilder.append("\n\t").append(point.toString()).append(", ");
    }

    Log.d("Font", stringBuilder.toString());
    return points;
}
</code>```

The output of the above method is:

```<code>The following points make up 'A':
    Point(1, 29),
    Point(1, 30),
    Point(1, 31),
    Point(2, 27),
    Point(2, 28),
    Point(2, 29),
    Point(2, 30),
    Point(2, 31),
    Point(3, 24),
    Point(3, 25),
    Point(3, 26),
    Point(3, 27),
    Point(3, 28),
    Point(3, 29),
    Point(3, 30),
    Point(3, 31),
    Point(4, 22),
    Point(4, 23),
    Point(4, 24),
    Point(4, 25),
    Point(4, 26),
    Point(4, 27),
    Point(4, 28),
    Point(5, 19),
    Point(5, 20),
    Point(5, 21),
    Point(5, 22),
    Point(5, 23),
    Point(5, 24),
    Point(5, 25),
    Point(5, 26),
    Point(6, 17),
    Point(6, 18),
    Point(6, 19),
    Point(6, 20),
    Point(6, 21),
    Point(6, 22),
    Point(6, 23),
    Point(6, 24),
    Point(6, 25),
    Point(7, 14),
    Point(7, 15),
    Point(7, 16),
    Point(7, 17),
    Point(7, 18),
    Point(7, 19),
    Point(7, 20),
    Point(7, 21),
    Point(7, 24),
    Point(7, 25),
    Point(8, 12),
    Point(8, 13),
    Point(8, 14),
    Point(8, 15),
    Point(8, 16),
    Point(8, 17),
    Point(8, 18),
    Point(8, 24),
    Point(8, 25),
    Point(9, 10),
    Point(9, 11),
    Point(9, 12),
    Point(9, 13),
    Point(9, 14),
    Point(9, 15),
    Point(9, 24),
    Point(9, 25),
    Point(10, 10),
    Point(10, 11),
    Point(10, 12),
    Point(10, 13),
    Point(10, 24),
    Point(10, 25),
    Point(11, 10),
    Point(11, 11),
    Point(11, 12),
    Point(11, 13),
    Point(11, 14),
    Point(11, 15),
    Point(11, 24),
    Point(11, 25),
    Point(12, 12),
    Point(12, 13),
    Point(12, 14),
    Point(12, 15),
    Point(12, 16),
    Point(12, 17),
    Point(12, 18),
    Point(12, 24),
    Point(12, 25),
    Point(13, 14),
    Point(13, 15),
    Point(13, 16),
    Point(13, 17),
    Point(13, 18),
    Point(13, 19),
    Point(13, 20),
    Point(13, 21),
    Point(13, 24),
    Point(13, 25),
    Point(14, 17),
    Point(14, 18),
    Point(14, 19),
    Point(14, 20),
    Point(14, 21),
    Point(14, 22),
    Point(14, 23),
    Point(14, 24),
    Point(14, 25),
    Point(15, 19),
    Point(15, 20),
    Point(15, 21),
    Point(15, 22),
    Point(15, 23),
    Point(15, 24),
    Point(15, 25),
    Point(15, 26),
    Point(16, 22),
    Point(16, 23),
    Point(16, 24),
    Point(16, 25),
    Point(16, 26),
    Point(16, 27),
    Point(16, 28),
    Point(16, 29),
    Point(17, 24),
    Point(17, 25),
    Point(17, 26),
    Point(17, 27),
    Point(17, 28),
    Point(17, 29),
    Point(17, 30),
    Point(17, 31),
    Point(18, 27),
    Point(18, 28),
    Point(18, 29),
    Point(18, 30),
    Point(18, 31),
    Point(19, 30),
    Point(19, 31),
</code>```

Body:
Here's another way that returns Points:

private void textStuff() {
    int textSize = 32;
    char letter = 'A';
    getPointsForChar(textSize, letter);
}

@NonNull
private ArrayList<Point> getPointsForChar(int textSize, char letter) {
    Canvas canvas = new Canvas();
    Paint paint = new Paint();
    Bitmap bitmap = Bitmap.createBitmap((int) (float) textSize, (int) (float) textSize, Bitmap.Config.ALPHA_8);
    canvas.drawPaint(paint);
    canvas.setBitmap(bitmap);
    paint.setColor(Color.BLACK);
    paint.setTextSize(textSize);
    canvas.drawText(String.valueOf(letter), 0, (float) textSize, paint);
    Log.d("Font", "bitmap " + bitmap.toString());
    ArrayList<Point> points = new ArrayList<>();
    for (int x = 0; x < bitmap.getWidth(); x++) {
        for (int y = 0; y < bitmap.getHeight(); y++) {
            int pixel = bitmap.getPixel(x, y);
            if (pixel != Color.TRANSPARENT) {
                points.add(new Point(x, y));
            }
        }
    }

    StringBuilder stringBuilder = new StringBuilder("The following points make up '" + letter + "':");
    for (Point point : points) {
        stringBuilder.append("\n\t").append(point.toString()).append(", ");
    }

    Log.d("Font", stringBuilder.toString());
    return points;
}

The output of the above method is:

The following points make up 'A':
    Point(1, 29),
    Point(1, 30),
    Point(1, 31),
    Point(2, 27),
    Point(2, 28),
    Point(2, 29),
    Point(2, 30),
    Point(2, 31),
    Point(3, 24),
    Point(3, 25),
    Point(3, 26),
    Point(3, 27),
    Point(3, 28),
    Point(3, 29),
    Point(3, 30),
    Point(3, 31),
    Point(4, 22),
    Point(4, 23),
    Point(4, 24),
    Point(4, 25),
    Point(4, 26),
    Point(4, 27),
    Point(4, 28),
    Point(5, 19),
    Point(5, 20),
    Point(5, 21),
    Point(5, 22),
    Point(5, 23),
    Point(5, 24),
    Point(5, 25),
    Point(5, 26),
    Point(6, 17),
    Point(6, 18),
    Point(6, 19),
    Point(6, 20),
    Point(6, 21),
    Point(6, 22),
    Point(6, 23),
    Point(6, 24),
    Point(6, 25),
    Point(7, 14),
    Point(7, 15),
    Point(7, 16),
    Point(7, 17),
    Point(7, 18),
    Point(7, 19),
    Point(7, 20),
    Point(7, 21),
    Point(7, 24),
    Point(7, 25),
    Point(8, 12),
    Point(8, 13),
    Point(8, 14),
    Point(8, 15),
    Point(8, 16),
    Point(8, 17),
    Point(8, 18),
    Point(8, 24),
    Point(8, 25),
    Point(9, 10),
    Point(9, 11),
    Point(9, 12),
    Point(9, 13),
    Point(9, 14),
    Point(9, 15),
    Point(9, 24),
    Point(9, 25),
    Point(10, 10),
    Point(10, 11),
    Point(10, 12),
    Point(10, 13),
    Point(10, 24),
    Point(10, 25),
    Point(11, 10),
    Point(11, 11),
    Point(11, 12),
    Point(11, 13),
    Point(11, 14),
    Point(11, 15),
    Point(11, 24),
    Point(11, 25),
    Point(12, 12),
    Point(12, 13),
    Point(12, 14),
    Point(12, 15),
    Point(12, 16),
    Point(12, 17),
    Point(12, 18),
    Point(12, 24),
    Point(12, 25),
    Point(13, 14),
    Point(13, 15),
    Point(13, 16),
    Point(13, 17),
    Point(13, 18),
    Point(13, 19),
    Point(13, 20),
    Point(13, 21),
    Point(13, 24),
    Point(13, 25),
    Point(14, 17),
    Point(14, 18),
    Point(14, 19),
    Point(14, 20),
    Point(14, 21),
    Point(14, 22),
    Point(14, 23),
    Point(14, 24),
    Point(14, 25),
    Point(15, 19),
    Point(15, 20),
    Point(15, 21),
    Point(15, 22),
    Point(15, 23),
    Point(15, 24),
    Point(15, 25),
    Point(15, 26),
    Point(16, 22),
    Point(16, 23),
    Point(16, 24),
    Point(16, 25),
    Point(16, 26),
    Point(16, 27),
    Point(16, 28),
    Point(16, 29),
    Point(17, 24),
    Point(17, 25),
    Point(17, 26),
    Point(17, 27),
    Point(17, 28),
    Point(17, 29),
    Point(17, 30),
    Point(17, 31),
    Point(18, 27),
    Point(18, 28),
    Point(18, 29),
    Point(18, 30),
    Point(18, 31),
    Point(19, 30),
    Point(19, 31),


问:
How to rename files in a drectory based on an existing array of names using Python?
I have some video files in a folder (E://Data/Video) with dummy names as

```<code>vid-dummyName.mp4
vid-dummyName (1).mp4
vid-dummyName (2).mp4
vid-dummyName (3).mp4
vid-dummyName (4).mp4
vid-dummyName (5).mp4
</code>```

How can I use Python to rename them based on an exiting array like this:

```<code>import os

path = 'E:/Data/Video'
files = os.listdir(path)
i = 1

names=['Not Dummy Video','Another Not Dummy Video','May be Dummy','Still Thinking','Give it a Name','Tomorrow']

for file in files:
    os.rename(os.path.join(path, file), os.path.join(path, str(i)+'.mp4'))
</code>```

答:
try</p>

```<code>import os
path = "E:/Data/Video"
files = os.listdir(path)
saved_path = os.getcwd()
for file_ in files:
  os.rename(file_, file_+".mp4")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have some video files in a folder (E://Data/Video) with dummy names as

vid-dummyName.mp4
vid-dummyName (1).mp4
vid-dummyName (2).mp4
vid-dummyName (3).mp4
vid-dummyName (4).mp4
vid-dummyName (5).mp4

How can I use Python to rename them based on an exiting array like this:

import os

path = 'E:/Data/Video'
files = os.listdir(path)
i = 1

names=['Not Dummy Video','Another Not Dummy Video','May be Dummy','Still Thinking','Give it a Name','Tomorrow']

for file in files:
    os.rename(os.path.join(path, file), os.path.join(path, str(i)+'.mp4'))

Body:
try

import os
path = "E:/Data/Video"
files = os.listdir(path)
saved_path = os.getcwd()
for file_ in files:
  os.rename(file_, file_+".mp4")


问:
SQL how can I have sql return one row instead of multiple per distinct ID?
According to my coworker, We are using IBM DB2

Having real hard time trying to make my sql return one row per ID.  Asked around at work but no girl here are good with SQL...  I can do some sql but am no SQL expert.

To explain it better, I set up the example below

Here is the TABLE and its data

```<code>ID  DATE        CODE  PERCENT
01  2016-08-21  1111  52
01  2016-09-06  1111  60
01  2016-10-06  1112  38
02  2016-05-01  6666  50
02  2016-10-01  1111  50
</code>```

I want one record returned per each ID with earliest DATE.
so I wrote below SQL

```<code>SELECT ID, MIN(DATE)
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID
</code>```

that worked fine.  I would get

```<code>01 2016-08-21
02 2016-10-01
</code>```

I soon realized that I also need PERCENT column.

```<code>SELECT ID, MIN(DATE), PERCENT
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID, PERCENT
</code>```

but now, I'm getting the multiple rows for ID 01 which is wrong...

```<code>01  2016-08-21  1111  52
01  2016-09-06  1111  60
02  2016-10-01  1111  50
</code>```

Can somebody help me fix this SQL or point me to the right direction so that I can have one row per ID like below?

```<code>01  2016-08-21  1111  52
02  2016-10-01  1111  50
</code>```

答:
```<code>SELECT
    Earliest.ID,
    Earliest.Date,
    TABLE.PERCENT
FROM (
    SELECT
        ID,
        MIN(DATE)
    FROM
        TABLE
    WHERE
        DATE BETWEEN '2016-01-01' AND  '2017-11-01'
        AND CODE = 1111
    GROUP BY ID
) AS Earliest
INNER JOIN TABLE ON Earliest.ID = Table.ID
</code>```

To explain why your adjusted query is returning multiple records: The percent column has different data, and so when you group by it, it will add a new record for every change on that.

In this answer you get the percent from the underlying table by joining to the summarised results.

Body:
According to my coworker, We are using IBM DB2

Having real hard time trying to make my sql return one row per ID.  Asked around at work but no girl here are good with SQL...  I can do some sql but am no SQL expert.

To explain it better, I set up the example below

Here is the TABLE and its data

ID  DATE        CODE  PERCENT
01  2016-08-21  1111  52
01  2016-09-06  1111  60
01  2016-10-06  1112  38
02  2016-05-01  6666  50
02  2016-10-01  1111  50

I want one record returned per each ID with earliest DATE.
so I wrote below SQL

SELECT ID, MIN(DATE)
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID

that worked fine.  I would get

01 2016-08-21
02 2016-10-01

I soon realized that I also need PERCENT column.

SELECT ID, MIN(DATE), PERCENT
FROM TABLE
WHERE DATE >= '2016-01-01' AND  DATE <= '2017-11-01'
AND   CODE = 1111
GROUP BY ID, PERCENT

but now, I'm getting the multiple rows for ID 01 which is wrong...

01  2016-08-21  1111  52
01  2016-09-06  1111  60
02  2016-10-01  1111  50

Can somebody help me fix this SQL or point me to the right direction so that I can have one row per ID like below?

01  2016-08-21  1111  52
02  2016-10-01  1111  50

Body:
SELECT
    Earliest.ID,
    Earliest.Date,
    TABLE.PERCENT
FROM (
    SELECT
        ID,
        MIN(DATE)
    FROM
        TABLE
    WHERE
        DATE BETWEEN '2016-01-01' AND  '2017-11-01'
        AND CODE = 1111
    GROUP BY ID
) AS Earliest
INNER JOIN TABLE ON Earliest.ID = Table.ID

To explain why your adjusted query is returning multiple records: The percent column has different data, and so when you group by it, it will add a new record for every change on that.

In this answer you get the percent from the underlying table by joining to the summarised results.


答:
Use this code</p>

```<code>$btn = $('<button>').text('Button');
$('<div>').html('Text next to button ' + $btn[0].outerHTML).appendTo($('#test'))
</code>```

Title: jquery: append text and object results in [object Object]

Body:
Use this code

$btn = $('<button>').text('Button');
$('<div>').html('Text next to button ' + $btn[0].outerHTML).appendTo($('#test'))


问:
Desktop Bridge UWP Windows.Services.Store;
I have a windows store WPF desktop bridge app compiled to 4.6.1. I am going to give the app away free and allow for in app purchases. To do this I need to use the UWP API for the windows store service.

I am also using the new desktop bridge packaging app template.

I want to keep the UWP API separate from the WPF project, so I have created a serparate dll project for the UWP API. I reference System.Runtime.WindowsRuntime and Windows. Use basic code from the Store Sample.

I add a reference from the WPF app to the UWP dll.

As soon as I reference the UWP dll the desktop bridge packaging app will return 9805 Errors and 1 warning.

One of the errors (which is typical) is

The .winmd file 'Windows.winmd' contains type 'Windows.Gaming.Input.Gamepad'. The use of the Windows namespace is reserved.

The warning is

No implementation file was provided for the .winmd file 'OUTPUT DIRECTORY PATH\Windows.winmd'. To generate registration information in the app manifest, specify the 'Implementation' metadata on the .winmd reference item in the project file.

I get the same errors if I add the two references to the WPF directly (System.Runtime.WindowsRuntime and Windows) and remove the UWP dll.

Updated: Have confirmed this is a problem with Desktop Bridge by:

```<code>Creating a new WPF App project.
Creating a new Windows Application Packaging Project and configure it to include the WPF project.
Build the WPF project.
Create an appx package and perform WACK tests. All Okay.
Add a reference to the C:\Program Files (x86)\Windows Kits\10\UnionMetadata\winmd
Add a reference to the C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
Build the WPF project.
Trying to build the Packaging Project results in 9805 errors.
</code>```

Here is the blog that I was following: https://blogs.windows.com/buildingapps/2017/01/25/calling-windows-10-apis-desktop-application/

Anyone know what is going on?

The error messages come from the WACK tests

```<code><TEST INDEX="54" NAME="Type name correctness" DESCRIPTION="Only system types can be in the Windows namespace and no types can be in the global namespace." EXECUTIONTIME="00h:00m:08s.46ms" OPTIONAL="FALSE">
    <MESSAGES>
      <MESSAGE TEXT="The Windows.ApplicationModel.StartupTaskState type in the Windows.winmd file is in the Windows namespace." />
      <MESSAGE TEXT="The Windows.ApplicationModel.PackageSignatureKind type in the Windows.winmd file is in the Windows namespace." />
      <MESSAGE TEXT="The Windows.ApplicationModel.PackageVersion type in the Windows.winmd file is in the Windows namespace." />
</code>```

Anyone know how to get around it?

答:
Using the Windows.Services.Store namespace in a desktop bridge application is not compatible with the Windows Application Packaging Project. When building the packaging project, it will perform WACK tests which will throw 9805 errors and stop the creation of the appx bundle.

Manually creating the package will still give you to 9805 errors if you perform the WACK tests. But at least you should have an appx you can submit to the store.

Body:
I have a windows store WPF desktop bridge app compiled to 4.6.1. I am going to give the app away free and allow for in app purchases. To do this I need to use the UWP API for the windows store service.

I am also using the new desktop bridge packaging app template.

I want to keep the UWP API separate from the WPF project, so I have created a serparate dll project for the UWP API. I reference System.Runtime.WindowsRuntime and Windows. Use basic code from the Store Sample.

I add a reference from the WPF app to the UWP dll.

As soon as I reference the UWP dll the desktop bridge packaging app will return 9805 Errors and 1 warning.

One of the errors (which is typical) is

The .winmd file 'Windows.winmd' contains type 'Windows.Gaming.Input.Gamepad'. The use of the Windows namespace is reserved.

The warning is

No implementation file was provided for the .winmd file 'OUTPUT DIRECTORY PATH\Windows.winmd'. To generate registration information in the app manifest, specify the 'Implementation' metadata on the .winmd reference item in the project file.

I get the same errors if I add the two references to the WPF directly (System.Runtime.WindowsRuntime and Windows) and remove the UWP dll.

Updated: Have confirmed this is a problem with Desktop Bridge by:

Creating a new WPF App project.
Creating a new Windows Application Packaging Project and configure it to include the WPF project.
Build the WPF project.
Create an appx package and perform WACK tests. All Okay.
Add a reference to the C:\Program Files (x86)\Windows Kits\10\UnionMetadata\winmd
Add a reference to the C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
Build the WPF project.
Trying to build the Packaging Project results in 9805 errors.

Here is the blog that I was following: https://blogs.windows.com/buildingapps/2017/01/25/calling-windows-10-apis-desktop-application/

Anyone know what is going on?

The error messages come from the WACK tests

<TEST INDEX="54" NAME="Type name correctness" DESCRIPTION="Only system types can be in the Windows namespace and no types can be in the global namespace." EXECUTIONTIME="00h:00m:08s.46ms" OPTIONAL="FALSE">
    <MESSAGES>
      <MESSAGE TEXT="The Windows.ApplicationModel.StartupTaskState type in the Windows.winmd file is in the Windows namespace." />
      <MESSAGE TEXT="The Windows.ApplicationModel.PackageSignatureKind type in the Windows.winmd file is in the Windows namespace." />
      <MESSAGE TEXT="The Windows.ApplicationModel.PackageVersion type in the Windows.winmd file is in the Windows namespace." />

Anyone know how to get around it?


问:
What would be Openshift REST API equivalent of a process template command
I am automating some continuous delivery processess that use openshift 3.5. They work fine from a command line, but I can hardly find any documentation of how the oc commands map to the OCP REST API. I've figured out how talk to the API and use what it directly offers. For example, I have a line:

```<code>oc process build-template -p APPLICATION_NAME=worldcontrol -n openshift | oc create -f - -n conspiracyspace
</code>```

That takes a template named "build-template" from "openshift" namespace and processes it, piping the resulting definition to build a few objects like application image, into another namespace. I would appreciate an example of how this could be expressed in http request terms.

edit

Following @Graham's hint, here is what I got. First request is getting the contents of the template:

```<code>curl -k -v -XGET  -H "User-Agent: oc/v3.5.5.15 (linux/amd64) openshift/4b5f317" -H "Authorization: Bearer ...." -H "Accept: application/json, */*" https://example.com/oapi/v1/namespaces/openshift/templates/build-template
</code>```

Then apparently the oc client expands the parameters internally, and feeds the result into the POST:

```<code>curl -k -v -XPOST  -H "Content-Type: application/json" -H "User-Agent: oc/v3.5.5.15 (linux/amd64) openshift/4b5f317" -H "Accept: application/json, */*" -H "Authorization: Bearer ...." https://example.com/oapi/v1/namespaces/openshift/processedtemplates
</code>```

答:
I did this, and at the very end of the output from the CLI, I saw this:

```<code>service "trade4-65869977-9d56-49a5-afa2-4a547df82d5c" created
deploymentconfig "trade4-65869977-9d56-49a5-afa2-4a547df82d5c" created
</code>```

When piping to oc create -f -, then, the CLI must be inspecting the resulting template and creating each object in the objects array. No evidence of those calls were outputted to my command window, other than the two "created" statements.

So to fully automate this through the REST API, we would still need to parse that objects array returned by processtemplates and POST to the appropriate endpoints, correct?

Body:
I am automating some continuous delivery processess that use openshift 3.5. They work fine from a command line, but I can hardly find any documentation of how the oc commands map to the OCP REST API. I've figured out how talk to the API and use what it directly offers. For example, I have a line:

oc process build-template -p APPLICATION_NAME=worldcontrol -n openshift | oc create -f - -n conspiracyspace

That takes a template named "build-template" from "openshift" namespace and processes it, piping the resulting definition to build a few objects like application image, into another namespace. I would appreciate an example of how this could be expressed in http request terms.

edit

Following @Graham's hint, here is what I got. First request is getting the contents of the template:

curl -k -v -XGET  -H "User-Agent: oc/v3.5.5.15 (linux/amd64) openshift/4b5f317" -H "Authorization: Bearer ...." -H "Accept: application/json, */*" https://example.com/oapi/v1/namespaces/openshift/templates/build-template

Then apparently the oc client expands the parameters internally, and feeds the result into the POST:

curl -k -v -XPOST  -H "Content-Type: application/json" -H "User-Agent: oc/v3.5.5.15 (linux/amd64) openshift/4b5f317" -H "Accept: application/json, */*" -H "Authorization: Bearer ...." https://example.com/oapi/v1/namespaces/openshift/processedtemplates

Body:
I did this, and at the very end of the output from the CLI, I saw this:

service "trade4-65869977-9d56-49a5-afa2-4a547df82d5c" created
deploymentconfig "trade4-65869977-9d56-49a5-afa2-4a547df82d5c" created

When piping to oc create -f -, then, the CLI must be inspecting the resulting template and creating each object in the objects array. No evidence of those calls were outputted to my command window, other than the two "created" statements.

So to fully automate this through the REST API, we would still need to parse that objects array returned by processtemplates and POST to the appropriate endpoints, correct?


问:
Converting Spring ParameterizedTypeReference to Jackson TypeReference
I am using spring RestTemplate in a library. Input of the library method accepting a ParameterizedTypeRecerence and passing it to rest template for conversion.

For reasons unrelated, I need to get the response body as byte[] and convert if manually to json using Jackson.
Jackson expects a TypeReference class to do the conversion.

I am looking for a way to convert these to classes.

答:
Can use helper class

```<code>public class CustomTypeReference extends TypeReference<Object>{
    private final Type type;

    public CustomTypeReference(ParameterizedTypeReference pt){
        this.type = pt.getType();
    }

    @Override
    public Type getType() {
        return type;
    }
}
</code>```

And use it like this:

```<code>ParameterizedTypeReference<List<String>> typeRef
        = new ParameterizedTypeReference<List<String>>() {};
TypeReference tr = new CustomTypeReference(typeRef);

ObjectMapper mapper = new ObjectMapper();
String jsonStr = "[\"key\", \"someStr\"]";
List<String> data = mapper.readValue(jsonStr, tr);
</code>```

Or just anonymous TypeReference<Object>

```<code>ParameterizedTypeReference<List<String>> typeRef
        = new ParameterizedTypeReference<List<String>>() {};

TypeReference tr = new TypeReference<Object>(){
    public Type getType() {
        return typeRef.getType();
    }
};
</code>```

Body:
Can use helper class

public class CustomTypeReference extends TypeReference<Object>{
    private final Type type;

    public CustomTypeReference(ParameterizedTypeReference pt){
        this.type = pt.getType();
    }

    @Override
    public Type getType() {
        return type;
    }
}

And use it like this:

ParameterizedTypeReference<List<String>> typeRef
        = new ParameterizedTypeReference<List<String>>() {};
TypeReference tr = new CustomTypeReference(typeRef);

ObjectMapper mapper = new ObjectMapper();
String jsonStr = "[\"key\", \"someStr\"]";
List<String> data = mapper.readValue(jsonStr, tr);

Or just anonymous TypeReference<Object>

ParameterizedTypeReference<List<String>> typeRef
        = new ParameterizedTypeReference<List<String>>() {};

TypeReference tr = new TypeReference<Object>(){
    public Type getType() {
        return typeRef.getType();
    }
};


答:
```<code>$btn = $('<button>').text('Button');
$('<div>').html('Text next to button ' + $btn.clone().wrap('<div>').parent().html()).appendTo($('#test'))
</code>```

<p>Basically what this is doing is creating a "clone" of the element, then wrapping the clone in a div, switching to the div (parent) then grabbing the html contents of that parent div. </p>

Body:
I'm trying to dynamically place a button element next to some text but I'm getting the following in the DOM: Text next to button [object Object].

$btn = $('<button>').text('Button');
$('
').html('Text next to button ' + $btn).appendTo($('#test'))

jsfiddle: https://jsfiddle.net/p43rft4q/1/

What am I doing wrong here and how can I fix this?

Body:
$btn = $('<button>').text('Button');
$('<div>').html('Text next to button ' + $btn.clone().wrap('<div>').parent().html()).appendTo($('#test'))

Basically what this is doing is creating a "clone" of the element, then wrapping the clone in a div, switching to the div (parent) then grabbing the html contents of that parent div.


问:
How use long instead of int can bulletproof the following method - Effective Java
Consider the following code picked from Joshua Bloch - Effective Java, page 263

```<code>// Broken - requires synchronization!
private static volatile int nextSerialNumber = 0;
public static int generateSerialNumber() {
    return nextSerialNumber++;
}
</code>```

One way to fix the
  generateSerialNumber method is to add
  the synchronized modifier to its
  declaration. This ensures that
  multiple invocations won’t be
  interleaved, and that each invocation
  will see the effects of all previous
  invocations. Once you’ve done that,
  you can and should remove the volatile
  modifier from nextSerialNumber. To
  bulletproof the method, use long
  instead of int, or throw an exception
  if nextSerialNumber is about to wrap.

I understand that we can remove volatile after we make generateSerialNumber synchronized, as it is redundant. But, does it make any harm? Any performance penalty if I am having both synchronized and volatile like

```<code>private static volatile int nextSerialNumber = 0;
public static synchronized int generateSerialNumber() {
    return nextSerialNumber++;
}
</code>```

What does, use long instead of int means? I do not understand how this bulletproof the method?

答:
What does, use long instead of int means?

It ensures that serial numbers don't roll over for a long, long time to come. Using an int you might use up all the available values (thus nextSerialNumber will have the maximum possible int value), then at the next increment the value is silently rolled over to the smallest (negative) int value, which is almost certainly not what you would expect from serial numbers :-)

Body:
Consider the following code picked from Joshua Bloch - Effective Java, page 263

// Broken - requires synchronization!
private static volatile int nextSerialNumber = 0;
public static int generateSerialNumber() {
    return nextSerialNumber++;
}

One way to fix the
  generateSerialNumber method is to add
  the synchronized modifier to its
  declaration. This ensures that
  multiple invocations won’t be
  interleaved, and that each invocation
  will see the effects of all previous
  invocations. Once you’ve done that,
  you can and should remove the volatile
  modifier from nextSerialNumber. To
  bulletproof the method, use long
  instead of int, or throw an exception
  if nextSerialNumber is about to wrap.

I understand that we can remove volatile after we make generateSerialNumber synchronized, as it is redundant. But, does it make any harm? Any performance penalty if I am having both synchronized and volatile like

private static volatile int nextSerialNumber = 0;
public static synchronized int generateSerialNumber() {
    return nextSerialNumber++;
}

What does, use long instead of int means? I do not understand how this bulletproof the method?


问:
Javascript accessing inner function from outside
I have the following <s>json</s> object

```<code>{
 ....
 ....
 data: function() {
    var x = 10;
    function isBig() {
        return x>6;
    }
    return x;
 }
}
</code>```

I want the isBig to be a function inside data.

When I call data.isBig I am getting undefined and data.isBig() gives me an error saying isBig is not a function.

答:
obj = {
 data: function(){
        var x = 10;
    return this.isBig(x);
    },
 isBig: function(x){
           return x > 6;
    }
};```
</div>
</div>
</p>

<p>And if you want to reproduce the function but useally your better off with an contructor add that point. </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>f = {
  isSmall: function(){},
  isBig: function(x){
    return x > 6;
  }
};
obj = {
  data: function(){
    var x = 10;
    return this.isBig(x);
  },
  isBig: f.isBig
};
obj.data();
obj.isBig(2);
f.isBig(2);</code>```

Body:
I have the following <s>json</s> object

{
 ....
 ....
 data: function() {
    var x = 10;
    function isBig() {
        return x>6;
    }
    return x;
 }
}

I want the isBig to be a function inside data.

When I call data.isBig I am getting undefined and data.isBig() gives me an error saying isBig is not a function.

Body:
obj = {
 data: function(){
        var x = 10;
    return this.isBig(x);
    },
 isBig: function(x){
           return x > 6;
    }
};

And if you want to reproduce the function but useally your better off with an contructor add that point.

f = {
  isSmall: function(){},
  isBig: function(x){
    return x > 6;
  }
};
obj = {
  data: function(){
    var x = 10;
    return this.isBig(x);
  },
  isBig: f.isBig
};
obj.data();
obj.isBig(2);
f.isBig(2);