问:
Changing the commit message while grafting a large number of changesets using Mercurial
I need to graft a large number (thousands) of small changesets from branch A to branch B - but need to alter the commit message in the process.

The message change needs to look roughly like this:

```<code>"Ref XXX: Fixed foo and bar" -> "GRAFT: Ref YYY: Fixed foo and bar".
</code>```

In other words, I need to prepend "GRAFT:" and change a reference number. If I can't make these replacements directly with Mercurial, I could create the new commit messages all in advance then make a script to apply each new message during its respective graft. Happily, Mercurial allows editing commit messages during grafting, with the -e argument:

https://www.mercurial-scm.org/repo/hg/help/graft

The problem is that this pops up a text editor for each changeset for me to make the change manually. There doesn't seem to be a way to amend the message in a programmatic way, or just to provide an entirely new message, at the comment line. Given the size of operation, using the editor each time isn't plausible.

My last option would be to use the text editor with some sort of AutoIt/Macro script to enter the right things in the places at the right times - but the thought of needing to resort to this is frankly making me feel a bit ill.

Save me from this ugly fate.

Thanks in advance.

答:
A possible workaround is to specify the use of a shell script in lieu of an editor. For example:

```<code>#!/bin/sh
sed -e '1,1s/^/GRAFT: /' -i "$1"
</code>```

We're making use of the fact that with -i, sed will do an in-place edit. Don't forget to make the shell script executable. Then you can run

```<code>hg graft --config ui.editor=/path/to/prepend-graft.sh -e -r <revision>
</code>```

where /path/to/prepend-graft.sh is the path of the aforementioned shell script.

Changing a number may require code that's more complex than a sed script, but would follow the same approach.

Body:
I need to graft a large number (thousands) of small changesets from branch A to branch B - but need to alter the commit message in the process.

The message change needs to look roughly like this:

"Ref XXX: Fixed foo and bar" -> "GRAFT: Ref YYY: Fixed foo and bar".

In other words, I need to prepend "GRAFT:" and change a reference number. If I can't make these replacements directly with Mercurial, I could create the new commit messages all in advance then make a script to apply each new message during its respective graft. Happily, Mercurial allows editing commit messages during grafting, with the -e argument:

https://www.mercurial-scm.org/repo/hg/help/graft

The problem is that this pops up a text editor for each changeset for me to make the change manually. There doesn't seem to be a way to amend the message in a programmatic way, or just to provide an entirely new message, at the comment line. Given the size of operation, using the editor each time isn't plausible.

My last option would be to use the text editor with some sort of AutoIt/Macro script to enter the right things in the places at the right times - but the thought of needing to resort to this is frankly making me feel a bit ill.

Save me from this ugly fate.

Thanks in advance.

Body:
A possible workaround is to specify the use of a shell script in lieu of an editor. For example:

#!/bin/sh
sed -e '1,1s/^/GRAFT: /' -i "$1"

We're making use of the fact that with -i, sed will do an in-place edit. Don't forget to make the shell script executable. Then you can run

hg graft --config ui.editor=/path/to/prepend-graft.sh -e -r <revision>

where /path/to/prepend-graft.sh is the path of the aforementioned shell script.

Changing a number may require code that's more complex than a sed script, but would follow the same approach.


来源: stackexchange

问:
Removing body margin in CSS
I'm new to web development, and met a problem when removing margin of body.

There's space between the very top of the browser and "logo" text. And my code is here on jsbin.

Is body { margin: 0;} wrong if I'd like to remove the space?

答:
Just Remove The Browser Default Margin and Padding Apply Top Of Your Css.

```<code><style>

* {
  margin: 0;
  padding: 0;
}

</style>
</code>```

NOTE:

Try to Reset all the html elements before writing your css.

OR [ Use This In Your Case ]

```<code><style>

  *{
        margin: 0px;
        padding: 0px;
    }

h1 {
        margin-top: 0px;
    }

</style>
</code>```

DEMO:

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
 <head>
 </head>
 <body>
  <h1>logo</h1>
 </body>
</html></code>```

ContentLicense: CC BY-SA 3.0

Title: Removing body margin in CSS

Body:
Just Remove The Browser Default Margin and Padding Apply Top Of Your Css.

<style>

* {
  margin: 0;
  padding: 0;
}

</style>

NOTE:

Try to Reset all the html elements before writing your css.

OR [ Use This In Your Case ]

<style>

  *{
        margin: 0px;
        padding: 0px;
    }

h1 {
        margin-top: 0px;
    }

</style>

DEMO:

<style>

  *{
        margin: 0px;
        padding: 0px;
    }

h1 {
        margin-top: 0px;
    }

</style>

<html>
 <head>
 </head>
 <body>
  <h1>logo</h1>
 </body>
</html>


问:
Check if an instance has overridden a superclass method or not in Python
I'm writing a UI library that is designed for keyboard-navigable interfaces. It has a feature where it can automatically "autocomplete" the links that determine which button the highlight moves to from any given button when the end-user presses an arrow key. Obviously this system needs to know if the library user has already specified where the link should go, or if new behavior has been specified to happen when an arrow key is pressed.

I was thinking I could just have On{Up/Down/Left/Right}ArrowKeyPressed methods, whose default is to switch highlight to self.{Up/Down/Left/Right}Link, and so if self.___Link == None and On____ArrowKeyPressed has not been overridden, the library can safely assume that it is in charge of setting that link for that button.

Is there a reliable way of detecting if an object is using its default superclass method or not? Would thebutton.OnUpArrowKeyPressed is Button.OnUpArrowKeyPressed work in all cases?

答:
You can check if a class has overridden a function by comparing the functions.

```<code>class A:
    def ping(self):
        print("pong")

class B(A):
    def ping(self):
        print("overridden")

class C(A):
    pass
    # Not Overridden

A.ping == B.ping  # False
A.ping == C.ping  # True
</code>```

When I tested this it did not work when comparing the methods in the objects

```<code>a = A()
b = B()
c = C()

a.ping == b.ping  # False
a.ping == c.ping  # False
</code>```

If you need to compare methods in objects you can use

```<code>a.__class__.ping == c.__class__.ping  # True
</code>```

Body:
You can check if a class has overridden a function by comparing the functions.

class A:
    def ping(self):
        print("pong")

class B(A):
    def ping(self):
        print("overridden")

class C(A):
    pass
    # Not Overridden

A.ping == B.ping  # False
A.ping == C.ping  # True

When I tested this it did not work when comparing the methods in the objects

a = A()
b = B()
c = C()

a.ping == b.ping  # False
a.ping == c.ping  # False

If you need to compare methods in objects you can use

a.__class__.ping == c.__class__.ping  # True


问:
javascript - check a radiobutton from a radiobutton group by it's value from code
i'm working on a project, and i need to check a radiobutton from a radiobutton group by it's value.

i have this radiobutton group.

```<code><label class="radio-inline">
    <input type="radio" name="slect" id="optradio"  value="oriente" checked>=Orienté
</label>
<label class="radio-inline">
    <input type="radio" name="slect" id="optradio" value="Nonoriente">Non orienté
</label>
</code>```

in my code i have a variable, i manage to affect it to  one of two values

```<code>var x="Nonoriente"       or     var x="oriente"
</code>```

My goal is to automatiquly check the équivalent value of x in the radiobuttons when an event is triggered.

答:
Easy with jQuery. Here are the docs for the .prop() method.

```<code>if (x === Oriente) {
    $( input:first-of-type ).prop( "checked" );
} else {
    $( input:first-of-type ).prop( "checked" );
}
</code>```

It might make it easier to assign unique ID's to each radio button and use those to access the .prop() method on the DOM element. (Semantically they should be unique anyways. If for some reason you want to apply anything to multiple DOM nodes you should be using a class.)

Native Javascript:

```<code>if (x === Oriente) {
    document.getElementById('uniqueId1').checked = true;
} else {
   document.getElementById('uniqueId2').checked = true;
}
</code>```

Body:
i'm working on a project, and i need to check a radiobutton from a radiobutton group by it's value.

i have this radiobutton group.

    <input type="radio" name="slect" id="optradio"  value="oriente" checked>=Orienté

    <input type="radio" name="slect" id="optradio" value="Nonoriente">Non orienté

in my code i have a variable, i manage to affect it to  one of two values

var x="Nonoriente"       or     var x="oriente"

My goal is to automatiquly check the équivalent value of x in the radiobuttons when an event is triggered.

Body:
Easy with jQuery. Here are the docs for the .prop() method.

if (x === Oriente) {
    $( input:first-of-type ).prop( "checked" );
} else {
    $( input:first-of-type ).prop( "checked" );
}

It might make it easier to assign unique ID's to each radio button and use those to access the .prop() method on the DOM element. (Semantically they should be unique anyways. If for some reason you want to apply anything to multiple DOM nodes you should be using a class.)

Native Javascript:

if (x === Oriente) {
    document.getElementById('uniqueId1').checked = true;
} else {
   document.getElementById('uniqueId2').checked = true;
}


问:
Chef: gem dependency on provider
We're creating a provider for a resource. It stands for creating a mongo user into given database.

```<code>class LivingMongoCookbook::UserProvider < Chef::Provider::LWRPBase
  provides :living_mongo_user
  def whyrun_supported?
   true
  end
  def action_create
   db = Mongo::Connection.new(new_resource.host, new_resource.port).db(new_resource.database)
   users = db.getUsers
   db.createUser({ user: new_resource.user, pwd: new_resource.passwd, roles: [ new_resource.roles ]})
   new_resource.updated_by_last_action(true)
 end
end
</code>```

We're lokking to use mongo ruby driver in order to be able to create user on db. Nevertheless, we're getting this message:

```<code>================================================================================
  Recipe Compile Error in /tmp/kitchen/cache/cookbooks/living_mongo/libraries/provider_user.rb
   ================================================================================       LoadError
  ---------
  cannot load such file -- mongo       Cookbook Trace:
  ---------------
    /tmp/kitchen/cache/cookbooks/living_mongo/libraries/provider_user.rb:1:in `<top (required)>'       Relevant File Content:
  ----------------------
  /tmp/kitchen/cache/cookbooks/living_mongo/libraries/provider_user.rb:         1>> require 'mongo'
    2:
    3:  # Chef Provider for creating a user and group for Elasticsearch
    4:  class LivingMongoCookbook::UserProvider < Chef::Provider::LWRPBase
    5:
    6:    provides :living_mongo_user
    7:
    8:    def whyrun_supported?
    9:      true
   10:    end
</code>```

It seems like mongo driver is not available.

Any ideas?

答: Assuming you have a recent-ish Chef version and the gem doesn't require a C compiler, add gem 'mongo' to the metadata.rb and Chef will take care of installing it for you.

Title: Chef: gem dependency on provider

Body:
We're creating a provider for a resource. It stands for creating a mongo user into given database.

class LivingMongoCookbook::UserProvider < Chef::Provider::LWRPBase
  provides :living_mongo_user
  def whyrun_supported?
   true
  end
  def action_create
   db = Mongo::Connection.new(new_resource.host, new_resource.port).db(new_resource.database)
   users = db.getUsers
   db.createUser({ user: new_resource.user, pwd: new_resource.passwd, roles: [ new_resource.roles ]})
   new_resource.updated_by_last_action(true)
 end
end

We're lokking to use mongo ruby driver in order to be able to create user on db. Nevertheless, we're getting this message:

================================================================================
  Recipe Compile Error in /tmp/kitchen/cache/cookbooks/living_mongo/libraries/provider_user.rb
   ================================================================================       LoadError
  ---------
  cannot load such file -- mongo       Cookbook Trace:
  ---------------
    /tmp/kitchen/cache/cookbooks/living_mongo/libraries/provider_user.rb:1:in `<top (required)>'       Relevant File Content:
  ----------------------
  /tmp/kitchen/cache/cookbooks/living_mongo/libraries/provider_user.rb:         1>> require 'mongo'
    2:
    3:  # Chef Provider for creating a user and group for Elasticsearch
    4:  class LivingMongoCookbook::UserProvider < Chef::Provider::LWRPBase
    5:
    6:    provides :living_mongo_user
    7:
    8:    def whyrun_supported?
    9:      true
   10:    end

It seems like mongo driver is not available.

Any ideas?


问:
How to modify view controller after pressing a button?
Let's say that if you press the button from the bottom of the screen after typing something in the account text field, you would be required to also enter the password like in the second image.

How should I do this? I don't think that creating a new view controller would be good. So, should I somehow modify the same view controller?

How could I add the new password text field under the account text field?

Keep in mind that they are still centered. Hiding and unhiding wouldn't work in this case and I also need to modify more things than only adding that text field.

答:
another option is you can make tableView at Center, you need to create tableview height constraint outlet,

then you can maintain a counter how many time you want to add View, the counter should be return in tableView numberOfRowsInSection,
and you can make this view in Prototype Cell or using NIB, then just adjust header label text, textField placeholder and text on specific cell index,

when you increase or decrease counter update tableView Constraint, example you have a cell height as 50, in first case when you have on cell in tableView, you can set your tableView height constraint's constant as 50, when cells are two the 100 and so on.....

I think it's a simple logic


问:
Use scrapy to get list of urls, and then scrape content inside those urls
I need a Scrapy spider to scrape the following page (https://www.phidgets.com/?tier=1&catid=64&pcid=57) for each URL (30 products, so 30 urls) and then go into each product via that url and scrape the data inside.

I have the second part working exactly as I want:

```<code>import scrapy

class ProductsSpider(scrapy.Spider):
    name = "products"
    start_urls = [
        'https://www.phidgets.com/?tier=1&catid=64&pcid=57',
    ]

    def parse(self, response):
        for info in response.css('div.ph-product-container'):
            yield {
                'product_name': info.css('h2.ph-product-name::text').extract_first(),
                'product_image': info.css('div.ph-product-img-ctn a').xpath('@href').extract(),
                'sku': info.css('span.ph-pid').xpath('@prod-sku').extract_first(),
                'short_description': info.css('div.ph-product-summary::text').extract_first(),
                'price': info.css('h2.ph-product-price > span.price::text').extract_first(),
                'long_description': info.css('div#product_tab_1').extract_first(),
                'specs': info.css('div#product_tab_2').extract_first(),
            }

        # next_page = response.css('div.ph-summary-entry-ctn a::attr("href")').extract_first()
        # if next_page is not None:
        #     yield response.follow(next_page, self.parse)
</code>```

But I don't know how to do the first part. As you will see I have the main page (https://www.phidgets.com/?tier=1&catid=64&pcid=57) set as the start_url. But how do I get it to populate the start_urls list with all 30 urls I need crawled?

答:
I am not able to test at this moment, so please let me know if this works for you so I can edit it should there be any bugs.

The idea here is that we find every link in the first page and yield new scrapy requests passing your product parsing method as a callback

```<code>import scrapy
from urllib.parse import urljoin

class ProductsSpider(scrapy.Spider):
    name = "products"
    start_urls = [
        'https://www.phidgets.com/?tier=1&catid=64&pcid=57',
    ]

    def parse(self, response):
        products = response.xpath("//*[contains(@class, 'ph-summary-entry-ctn')]/a/@href").extract()
        for p in products:
            url = urljoin(response.url, p)
            yield scrapy.Request(url, callback=self.parse_product)

    def parse_product(self, response):
        for info in response.css('div.ph-product-container'):
            yield {
                'product_name': info.css('h2.ph-product-name::text').extract_first(),
                'product_image': info.css('div.ph-product-img-ctn a').xpath('@href').extract(),
                'sku': info.css('span.ph-pid').xpath('@prod-sku').extract_first(),
                'short_description': info.css('div.ph-product-summary::text').extract_first(),
                'price': info.css('h2.ph-product-price > span.price::text').extract_first(),
                'long_description': info.css('div#product_tab_1').extract_first(),
                'specs': info.css('div#product_tab_2').extract_first(),
            }
</code>```

Body:
I need a Scrapy spider to scrape the following page (https://www.phidgets.com/?tier=1&catid=64&pcid=57) for each URL (30 products, so 30 urls) and then go into each product via that url and scrape the data inside.

I have the second part working exactly as I want:

import scrapy

class ProductsSpider(scrapy.Spider):
    name = "products"
    start_urls = [
        'https://www.phidgets.com/?tier=1&catid=64&pcid=57',
    ]

    def parse(self, response):
        for info in response.css('div.ph-product-container'):
            yield {
                'product_name': info.css('h2.ph-product-name::text').extract_first(),
                'product_image': info.css('div.ph-product-img-ctn a').xpath('@href').extract(),
                'sku': info.css('span.ph-pid').xpath('@prod-sku').extract_first(),
                'short_description': info.css('div.ph-product-summary::text').extract_first(),
                'price': info.css('h2.ph-product-price > span.price::text').extract_first(),
                'long_description': info.css('div#product_tab_1').extract_first(),
                'specs': info.css('div#product_tab_2').extract_first(),
            }

        # next_page = response.css('div.ph-summary-entry-ctn a::attr("href")').extract_first()
        # if next_page is not None:
        #     yield response.follow(next_page, self.parse)

But I don't know how to do the first part. As you will see I have the main page (https://www.phidgets.com/?tier=1&catid=64&pcid=57) set as the start_url. But how do I get it to populate the start_urls list with all 30 urls I need crawled?

Body:
I am not able to test at this moment, so please let me know if this works for you so I can edit it should there be any bugs.

The idea here is that we find every link in the first page and yield new scrapy requests passing your product parsing method as a callback

import scrapy
from urllib.parse import urljoin

class ProductsSpider(scrapy.Spider):
    name = "products"
    start_urls = [
        'https://www.phidgets.com/?tier=1&catid=64&pcid=57',
    ]

    def parse(self, response):
        products = response.xpath("//*[contains(@class, 'ph-summary-entry-ctn')]/a/@href").extract()
        for p in products:
            url = urljoin(response.url, p)
            yield scrapy.Request(url, callback=self.parse_product)

    def parse_product(self, response):
        for info in response.css('div.ph-product-container'):
            yield {
                'product_name': info.css('h2.ph-product-name::text').extract_first(),
                'product_image': info.css('div.ph-product-img-ctn a').xpath('@href').extract(),
                'sku': info.css('span.ph-pid').xpath('@prod-sku').extract_first(),
                'short_description': info.css('div.ph-product-summary::text').extract_first(),
                'price': info.css('h2.ph-product-price > span.price::text').extract_first(),
                'long_description': info.css('div#product_tab_1').extract_first(),
                'specs': info.css('div#product_tab_2').extract_first(),
            }


问:
Java: custom toString to fit any class
I want to create a toString() method that works for any class, printing all its attributes as if it worked like this:

```<code>String toString(){
    String s = "";
    for(Attribute att: this.Attributes){
        s += (att.name + ": " + att.toString() + "\n");
    }
    return s;
}
</code>```

But this would work supposing all attributes have toString() method, so let's keep this supposition.

I guess this question includes concepts of reflection, and I don't know much about this concept nor how to apply this in Java.

答:
I think easiest way to do this - It is lombok's annotation @ToString which by default will generate toString() method with all fields, but of course you will able to exclude couple of them, or describe only required fields.

https://projectlombok.org/features/ToString

It will be look like

```<code>package test;

import lombok.AllArgsConstructor;
import lombok.ToString;
import java.util.Currency;

@AllArgsConstructor
@ToString
public class Example {
    private String name;
    private double amount;
    private Currency currency;

    public static void main(String[] args) {
        Example example = new Example("visa", 1000, Currency.getInstance("USD"));
        System.out.println(example.toString());
    }
}
</code>```

and output

```<code>Example(name=visa, amount=1000.0, currency=USD)
</code>```

Title: Java: custom toString to fit any class

Body:
I want to create a toString() method that works for any class, printing all its attributes as if it worked like this:

String toString(){
    String s = "";
    for(Attribute att: this.Attributes){
        s += (att.name + ": " + att.toString() + "\n");
    }
    return s;
}

But this would work supposing all attributes have toString() method, so let's keep this supposition.

I guess this question includes concepts of reflection, and I don't know much about this concept nor how to apply this in Java.

Body:
I think easiest way to do this - It is lombok's annotation @ToString which by default will generate toString() method with all fields, but of course you will able to exclude couple of them, or describe only required fields.

https://projectlombok.org/features/ToString

It will be look like

package test;

import lombok.AllArgsConstructor;
import lombok.ToString;
import java.util.Currency;

@AllArgsConstructor
@ToString
public class Example {
    private String name;
    private double amount;
    private Currency currency;

    public static void main(String[] args) {
        Example example = new Example("visa", 1000, Currency.getInstance("USD"));
        System.out.println(example.toString());
    }
}

and output

Example(name=visa, amount=1000.0, currency=USD)


问:
Jackson - Can't deserialize datetime with timezone offset 'unparsed text found at index 23'
My datetime has to come from frontend with timezone offset: 2017-07-04T06:00:00.000+01:00

I cannot deserialize it with Jackson.
The error is:

Text '2017-07-04T06:00:00.000+01:00' could not be parsed, unparsed
  text found at index 23;

I was trying to Google the solution by all are about DateTime with Z at the end.

```<code>    @NotNull
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS aZ")
    private LocalDateTime time;
</code>```

Is there any solution for that?

答:
The pattern a is used to parse AM/PM, which is not in the input String, that's why you get a parse error.

The input format matches an OffsetDateTime, which can be parsed with the respective built-in formatter DateTimeFormatter.ISO_OFFSET_DATE_TIME, so you can use this formatter in a deserializer object and register it in the module. You must also remove the JsonFormat annotation from the field.

```<code>ObjectMapper om = new ObjectMapper();
JavaTimeModule module = new JavaTimeModule();
LocalDateTimeDeserializer deserializer = new LocalDateTimeDeserializer(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
module.addDeserializer(LocalDateTime.class, deserializer);
om.registerModule(module);
</code>```

This will parse the input and convert it to a LocalDateTime. In the test I've made, the value of LocalDateTime was set to 2017-07-04T06:00.

To control the output, you can either do:

```<code>om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
</code>```

Which will output the LocalDateTime as 2017-07-04T06:00:00, or you can use a custom formatter:

```<code>LocalDateTimeSerializer serializer = new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS a"));
module.addSerializer(LocalDateTime.class, serializer);
</code>```

The serializer above will output the field as 2017-07-04T06:00:00.000 AM. Please note that the Z pattern will not work because a LocalDateTime has no timezone information and it can't resolve its offset - because when you deserialized to a LocalDateTime, the offset information in the input (+01:00) was lost.

Another alternative (without the need to configure the object mapper) is to use the correct pattern in the annotation:

```<code>@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS[xxx]")
private LocalDateTime time;
</code>```

Note that I used the pattern [xxx] because the offset (+01:00) can be optional: when deserializing, this information is lost becase a LocalDateTime has no information about timezones and offsets, so when serializing this field won't be found - making the field optional (using [] delimiters) make it work for both deserialization and serialization.

This will deserialize the input 2017-07-04T06:00:00.000+01:00 and serialize to  2017-07-04T06:00:00.000 (note that the optional offset is not used in serialization, as the LocalDateTime has no such information).

If you want different formats for deserialization and serialization, you can also create custom classes and anotate them in the field:

```<code>public class CustomDeserializer extends LocalDateTimeDeserializer {
    public CustomDeserializer() {
        super(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    }
}

public class CustomSerializer extends LocalDateTimeSerializer {
    public CustomSerializer() {
        super(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS a"));
    }
}

// in this case, don't use @JsonFormat
@JsonSerialize(using = CustomSerializer.class)
@JsonDeserialize(using = CustomDeserializer.class)
private LocalDateTime time;
</code>```

This will use the format 2017-07-04T06:00:00.000+01:00 for deserialize and the format 2017-07-04T06:00:00.000 AM to serialize.

Body:
My datetime has to come from frontend with timezone offset: 2017-07-04T06:00:00.000+01:00

I cannot deserialize it with Jackson.
The error is:

Text '2017-07-04T06:00:00.000+01:00' could not be parsed, unparsed
  text found at index 23;

I was trying to Google the solution by all are about DateTime with Z at the end.

    @NotNull
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS aZ")
    private LocalDateTime time;

Is there any solution for that?

Body:
The pattern a is used to parse AM/PM, which is not in the input String, that's why you get a parse error.

The input format matches an OffsetDateTime, which can be parsed with the respective built-in formatter DateTimeFormatter.ISO_OFFSET_DATE_TIME, so you can use this formatter in a deserializer object and register it in the module. You must also remove the JsonFormat annotation from the field.

ObjectMapper om = new ObjectMapper();
JavaTimeModule module = new JavaTimeModule();
LocalDateTimeDeserializer deserializer = new LocalDateTimeDeserializer(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
module.addDeserializer(LocalDateTime.class, deserializer);
om.registerModule(module);

This will parse the input and convert it to a LocalDateTime. In the test I've made, the value of LocalDateTime was set to 2017-07-04T06:00.

To control the output, you can either do:

om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

Which will output the LocalDateTime as 2017-07-04T06:00:00, or you can use a custom formatter:

LocalDateTimeSerializer serializer = new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS a"));
module.addSerializer(LocalDateTime.class, serializer);

The serializer above will output the field as 2017-07-04T06:00:00.000 AM. Please note that the Z pattern will not work because a LocalDateTime has no timezone information and it can't resolve its offset - because when you deserialized to a LocalDateTime, the offset information in the input (+01:00) was lost.

Another alternative (without the need to configure the object mapper) is to use the correct pattern in the annotation:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS[xxx]")
private LocalDateTime time;

Note that I used the pattern [xxx] because the offset (+01:00) can be optional: when deserializing, this information is lost becase a LocalDateTime has no information about timezones and offsets, so when serializing this field won't be found - making the field optional (using [] delimiters) make it work for both deserialization and serialization.

This will deserialize the input 2017-07-04T06:00:00.000+01:00 and serialize to  2017-07-04T06:00:00.000 (note that the optional offset is not used in serialization, as the LocalDateTime has no such information).

If you want different formats for deserialization and serialization, you can also create custom classes and anotate them in the field:

public class CustomDeserializer extends LocalDateTimeDeserializer {
    public CustomDeserializer() {
        super(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    }
}

public class CustomSerializer extends LocalDateTimeSerializer {
    public CustomSerializer() {
        super(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS a"));
    }
}

// in this case, don't use @JsonFormat
@JsonSerialize(using = CustomSerializer.class)
@JsonDeserialize(using = CustomDeserializer.class)
private LocalDateTime time;

This will use the format 2017-07-04T06:00:00.000+01:00 for deserialize and the format 2017-07-04T06:00:00.000 AM to serialize.


问:
jQuery $.when, then, multiple AJAX requests, and promises
Well after extensively web searches and several years of failing to understand documentation and finding alternative solutions, I've come to you to ask how I should go about my problem.

Note: Each AJAX request has a unique success function.

One of the suggested similar questions was -
 How to loop through Ajax Requests inside a JQuery When - Then statment? - is this similar to what I need, albeit the incompatibility with my unique success callbacks?

```<code>$.when(

  $.ajax({
    url: '/-.json',
    method: 'get',
    dataType: "jsonp",
    complete: function(r) {

      //my stuff

    }
  }),

  $.ajax({
    url: '/-.json',
    method: 'get',
    dataType: "jsonp",
    complete: function(r) {

      //my stuff

    }
  })

).then(function() {

  console.log('leggo');

});
</code>```

I based my solution on CSS-Tricks article but console.log is never fired, though the AJAX requests are.

Thanks

答: The answer was the dataType, as @charlietfl suggested. I have no heckin' idea why, but changing from jsonp to json was the answer. They're obviously more different than just the obvious situational usage.

Body:
Well after extensively web searches and several years of failing to understand documentation and finding alternative solutions, I've come to you to ask how I should go about my problem.

Note: Each AJAX request has a unique success function.

One of the suggested similar questions was -
 How to loop through Ajax Requests inside a JQuery When - Then statment? - is this similar to what I need, albeit the incompatibility with my unique success callbacks?

$.when(

  $.ajax({
    url: '/-.json',
    method: 'get',
    dataType: "jsonp",
    complete: function(r) {

      //my stuff

    }
  }),

  $.ajax({
    url: '/-.json',
    method: 'get',
    dataType: "jsonp",
    complete: function(r) {

      //my stuff

    }
  })

).then(function() {

  console.log('leggo');

});

I based my solution on CSS-Tricks article but console.log is never fired, though the AJAX requests are.

Thanks


问:
MLPClassifier on time series data
How do I use an MLPClassifier in scikit-learn on timeseries data?

I have data currently in a list called a[]

How do I use a training mechanism to train the data in this list? It is a list that lists daily closing price of a certain equity over a period of several years.

Thanks for your help, I am still a novice in data science programming.

Can anyone please explain to me how this classifier works, whether I should use MLPClassification or MLPRegression in scikit-learn to predict the price of an equity. What exactly does the classifier do and what the different activation functions represent?

My data looks like this:

[25.45, 25.68, 25.69, 26.00, 25.70, ... etc]

These are the daily stock prices over a period of years for a stock. How could I use this data to predict the future of where the stock price will be? For example if I have 17 years worth of past data, how can I determine the next 6 months?

答:
This is a general question.
You can use a lot of methods for this goal.
A simple Linear Regression could provide nice predictions (maybe, it needs to be tested).

A very good model that you can also use is: Random Forest Classifiers.

More details here link.

Nice example here link.

If you want particularly to use MLPRegressor, here is an example:

CODE

```<code>from sklearn.neural_network import MLPRegressor
import random
import numpy as np

#create the model.
regressor=MLPRegressor(hidden_layer_sizes=(100, ), activation='relu', solver='adam', alpha=0.0001,random_state=0)

#random data. let's say you have 365 values, one per day for a year
y=random.sample(range(50),365)

#make y a column vector
y=y.reshape(1,365)

#create 365 random years from 1600 to 1965
X=np.arange(1600,1965,1)
X=X.reshape(365,1)

#fit the model
regressor.fit(X,y)

#X_new is the future years. You want to predict the values for these years.
X_new = np.array([[2030,2050,2080]])
X_new=X_new.reshape(3,1)

#predict
pred = regressor.predict(X_new)

#print the predictions for year 2030, 2050, 2080
print(pred)
</code>```

Result

```<code>array([ 265.3367414,  267.9489602,  271.8672884])
</code>```

The first value corresponds to 2030 year etc.
For the model MLPRegressor, here link you can see all the available parameters.
Hope this helps.

Title: MLPClassifier on time series data

Body:
This is a general question.
You can use a lot of methods for this goal.
A simple Linear Regression could provide nice predictions (maybe, it needs to be tested).

A very good model that you can also use is: Random Forest Classifiers.

More details here link.

Nice example here link.

If you want particularly to use MLPRegressor, here is an example:

CODE

from sklearn.neural_network import MLPRegressor
import random
import numpy as np

#create the model.
regressor=MLPRegressor(hidden_layer_sizes=(100, ), activation='relu', solver='adam', alpha=0.0001,random_state=0)

#random data. let's say you have 365 values, one per day for a year
y=random.sample(range(50),365)

#make y a column vector
y=y.reshape(1,365)

#create 365 random years from 1600 to 1965
X=np.arange(1600,1965,1)
X=X.reshape(365,1)

#fit the model
regressor.fit(X,y)

#X_new is the future years. You want to predict the values for these years.
X_new = np.array([[2030,2050,2080]])
X_new=X_new.reshape(3,1)

#predict
pred = regressor.predict(X_new)

#print the predictions for year 2030, 2050, 2080
print(pred)

Result

array([ 265.3367414,  267.9489602,  271.8672884])

The first value corresponds to 2030 year etc.
For the model MLPRegressor, here link you can see all the available parameters.
Hope this helps.


问:
How to show javascript alertbox on button click event in asp.net webpage if textbox1.text=""?
How to show javascript alertbox on button click event in asp.net webpage if textbox1.text="" ?</p>

答:
If you meant button click on client side you can use OnClientClick event of the asp.net Button Control. Check the link.

And if you simply want it for Validation purpose only then you can use RequiredFieldValidator and ValidationSummary Controls.

ContentLicense: CC BY-SA 2.5


问:
How to better understand a programme or languages documentation
I am trying to be more independent when learning code by referring to the language documentation a lot more. However whilst I might understand the extract of code that I am supposed to be learning, I often have difficulty understanding where in my project files it would go.

For example, recently I've been trying to implement the Firebase Realtime Database feature into my project, and have been consulting the official documentation to learn how to read and write data on iOS using the database. This is the segment I have been going through: https://firebase.google.com/docs/database/ios/read-and-write .

This is where I have the issue, as the first section asks me to create an instance of FIRDatabaseReference, but I have no idea which of my project files or even where in it I am supposed to add this reference to.

I am not looking for an answer to that specific question - although it would be helpful - I'm more looking at what knowledge I am missing which would have helped me understand where that reference is supposed to go. I have attached a photo of my project files for convenience.

!Project Files]1

答:
My approach is to look at the code in the documentation to see what commands I don't understand. From your example, I did not understand "FIRDatabase", so I went on Google and found the following link, which provides detail on creating an instance:

https://firebase.google.com/docs/reference/ios/firebasedatabase/api/reference/Classes/FIRDatabase

Generally speaking, decomposing things to the lowest common denominator is a good start. From there, you can get into the more complex components, in your example, permissions, and so forth.


问:
How to draw image over preexisting layout Android Studio
I've got a space game, but now I need to spawn enemy spaceships over the top of my preexisting content_layout.xml (which has things like a star background). I don't know where to start because I'm not using ImageViews like I did for my spaceship because I want to spawn them continuously.</p>

答:
Check this:
 https://android--code.blogspot.co.il/2015/08/android-imageview-programmatically.html

Or this:
Problems drawing a bitmap on a layout


问:
How to subtract from list of numbers individually?
What I want to do is subtract from list on numbers just one number.
For example I have in a table following numbers and I want to subtract 4000:

```<code><table>
<thead>
   <tr>
      <td>result</td>
      <td>start</td>
   <tr>
</thead>
<tbody>
   <tr>
      <td>0</td>
      <td>3000</td>
   </tr>
   <tr>
      <td>0</td>
      <td>3500</td>
   </tr>
   <tr>
      <td>0</td>
      <td>4000</td>
   </tr>
</tbody>
</table>
</code>```

A perfect result would look like this:

```<code><table>
<thead>
   <tr>
      <td>result</td>
      <td>start</td>
   <tr>
</thead>
   <tbody>
   <tr>
      <td>0</td>
      <td>3000</td>
   </tr>
   <tr>
      <td>2500</td>
      <td>3500</td>
   </tr>
   <tr>
      <td>4000</td>
      <td>4000</td>
   </tr>
   </tbody>
</table>
</code>```

Here's a link what I've tried already:

http://jsfiddle.net/tiitremmel/LBjVJ/9/

答:
If you want to remove a row that has the first cell as your target number then try:</p>

```<code>var targetNumber = 4000;

// Note, better to use the ID of the table instead of 'table' here
$('table tr').each(function() {
  var tCell = $(this).find('td:first');
  if (parseInt(tCell.text()) == targetNumber) {
    $(this).remove();
  }
});
</code>```

Body:
What I want to do is subtract from list on numbers just one number.
For example I have in a table following numbers and I want to subtract 4000:

      result
      start

      0
      3000

      0
      3500

      0
      4000

A perfect result would look like this:

      result
      start

      0
      3000

      2500
      3500

      4000
      4000

Here's a link what I've tried already:

http://jsfiddle.net/tiitremmel/LBjVJ/9/

Body:
If you want to remove a row that has the first cell as your target number then try:

var targetNumber = 4000;

// Note, better to use the ID of the table instead of 'table' here
$('table tr').each(function() {
  var tCell = $(this).find('td:first');
  if (parseInt(tCell.text()) == targetNumber) {
    $(this).remove();
  }
});


问:
Laravel 5.4 Eloquent Relationship Issue
I need to clear my doubt about Eloquent Relationships. I have 2 models User (which comes with Laravel) and Other is Role which I created.
in migration, I added role_id as an additional column as I want every user must have a role now I want to retrieve a user role based on user's id so, I created a public function named roles inside the User Model.

```<code>    public function roles(){
        return $this->belongsTo(Role::class);
    }
</code>```

now when i try to run the query like this.

```<code>  App\User::find(1)->roles;
</code>```

it won't return any result, just empty screen but when I change it to

```<code>    public function role(){
        return $this->belongsTo(Role::class);
    }
</code>```

after that i run code

```<code>  App\User::find(1)->role;
</code>```

now it returns the exact row where the user with id 1 has a proper role. it's confusing why with the roles() function it's not working but with the role() function it's working.

Sorry, If this question is already posted you can redirect me to that question.

Thank You!

答:
You have to specify the foreign key

```<code>public function roles()
{
    return $this->belongsTo(Role::class, 'role_id');
}
</code>```

However, calling it role() is more accurate, since your are assuming that a User can only have one role.

Title: Laravel 5.4 Eloquent Relationship Issue

Body:
I need to clear my doubt about Eloquent Relationships. I have 2 models User (which comes with Laravel) and Other is Role which I created.
in migration, I added role_id as an additional column as I want every user must have a role now I want to retrieve a user role based on user's id so, I created a public function named roles inside the User Model.

    public function roles(){
        return $this->belongsTo(Role::class);
    }

now when i try to run the query like this.

  App\User::find(1)->roles;

it won't return any result, just empty screen but when I change it to

    public function role(){
        return $this->belongsTo(Role::class);
    }

after that i run code

  App\User::find(1)->role;

now it returns the exact row where the user with id 1 has a proper role. it's confusing why with the roles() function it's not working but with the role() function it's working.

Sorry, If this question is already posted you can redirect me to that question.

Thank You!

Body:
You have to specify the foreign key

public function roles()
{
    return $this->belongsTo(Role::class, 'role_id');
}

However, calling it role() is more accurate, since your are assuming that a User can only have one role.


问:
Emacs24 , org-mode, can't find `latex'(needed to convert LaTeX fragments fo images)
I want to use the command C-c C-x C-l to preview latex code in org-mode.  Since the emacs-nox cannot do this, I tried apt-get install emacs24.  However, after I have installed the emacs24 with GUI, I get an error like

```<code>can't find \`latex'(needed to convert LaTeX fragments to images)
</code>```

I have installed texlive2016, and I can latex *.tex in shell command.

I added the /paht/to/latex to .emacs, but it don't work well.

答:
Adding the following to my init.el makes it work:

```<code>;; Making emacs find latex (so that C-c C-x C-l works on orgmode)
(setenv "PATH" (concat ":/Library/TeX/texbin/" (getenv "PATH")))
(add-to-list 'exec-path "/Library/TeX/texbin/")
</code>```

It is not a very pretty solution, but it does the job and is very easy to modify and understand.

This solution worked on a Mac running macOS Sierra and Emacs v25.1.

Body:
I want to use the command C-c C-x C-l to preview latex code in org-mode.  Since the emacs-nox cannot do this, I tried apt-get install emacs24.  However, after I have installed the emacs24 with GUI, I get an error like

can't find \`latex'(needed to convert LaTeX fragments to images)

I have installed texlive2016, and I can latex *.tex in shell command.

I added the /paht/to/latex to .emacs, but it don't work well.

Body:
Adding the following to my init.el makes it work:

;; Making emacs find latex (so that C-c C-x C-l works on orgmode)
(setenv "PATH" (concat ":/Library/TeX/texbin/" (getenv "PATH")))
(add-to-list 'exec-path "/Library/TeX/texbin/")

It is not a very pretty solution, but it does the job and is very easy to modify and understand.

This solution worked on a Mac running macOS Sierra and Emacs v25.1.


问:
Exploding array and adding execution timestamp for each bit of data in the array?
Using curl_multi, I have loaded up 3 url's and then printed the array.

1) How can I also set a timestamp on output to let me know when each url was run?

2) How can I explode the array to only display the data and timestamp, excluding the text "Array ( [0] =>", "[1] =>", "[2] =>" and " )"?

Code

```<code><?php

function multiRequest($data, $options = array()) {

  // array of curl handles
  $curly = array();
  // data to be returned
  $result = array();

  // multi handle
  $mh = curl_multi_init();

  // loop through $data and create curl handles
  // then add them to the multi-handle
  foreach ($data as $id => $d) {

    $curly[$id] = curl_init();

    $url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d;
    curl_setopt($curly[$id], CURLOPT_URL,            $url);
    curl_setopt($curly[$id], CURLOPT_HEADER,         0);
    curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1);

    // post?
    if (is_array($d)) {
      if (!empty($d['post'])) {
        curl_setopt($curly[$id], CURLOPT_POST,       1);
        curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']);
      }
    }

    // extra options?
    if (!empty($options)) {
      curl_setopt_array($curly[$id], $options);
    }

    curl_multi_add_handle($mh, $curly[$id]);
  }

  // execute the handles
  $running = null;
  do {
    curl_multi_exec($mh, $running);
  } while($running > 0);

  // get content and remove handles
  foreach($curly as $id => $c) {
    $result[$id] = curl_multi_getcontent($c);
    curl_multi_remove_handle($mh, $c);
  }

  // all done
  curl_multi_close($mh);

  return $result;
}

$data = array(array(),array());

$data[0]['url']  = 'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Pearl+Jam&output=json';
$data[1]['url']  = 'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Black+Eyed+Peas&output=json';
$data[2]['url']  = 'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Nirvana&output=json';

$r = multiRequest($data);

print_r($r);

?>
</code>```

Output

```<code>Array ( [0] => Pearl Jam <br>
        [1] => Black Eyed Peas<br>
        [2] => Nirvana )
</code>```

Preferred Output

```<code>01:00:01 Pearl Jam <br>
01:00:02 Black Eyed Peas<br>
01:00:03 Nirvana
</code>```

答:
I'd say keep it simple...just do a loop where you set the timestamp and do a single curl call, then explode the resultarray and filter out all key or values you don't need.

For the curl call:

```<code>$r= array();

foreach($urls as $url) {
 $r[]["timestamp"]= time();
 $output= curl_exec($url);
 $r[]["bandname"]= $output;
}
</code>```

Your final loop would be something like

```<code>foreach($r as $key=>$value){
 print $value["timestamp"];
 print $value["bandname"];
 print "<br>";
}
</code>```

Body:
Using curl_multi, I have loaded up 3 url's and then printed the array.

1) How can I also set a timestamp on output to let me know when each url was run?

2) How can I explode the array to only display the data and timestamp, excluding the text "Array ( [0] =>", "[1] =>", "[2] =>" and " )"?

Code

<?php

function multiRequest($data, $options = array()) {

  // array of curl handles
  $curly = array();
  // data to be returned
  $result = array();

  // multi handle
  $mh = curl_multi_init();

  // loop through $data and create curl handles
  // then add them to the multi-handle
  foreach ($data as $id => $d) {

    $curly[$id] = curl_init();

    $url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d;
    curl_setopt($curly[$id], CURLOPT_URL,            $url);
    curl_setopt($curly[$id], CURLOPT_HEADER,         0);
    curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1);

    // post?
    if (is_array($d)) {
      if (!empty($d['post'])) {
        curl_setopt($curly[$id], CURLOPT_POST,       1);
        curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']);
      }
    }

    // extra options?
    if (!empty($options)) {
      curl_setopt_array($curly[$id], $options);
    }

    curl_multi_add_handle($mh, $curly[$id]);
  }

  // execute the handles
  $running = null;
  do {
    curl_multi_exec($mh, $running);
  } while($running > 0);

  // get content and remove handles
  foreach($curly as $id => $c) {
    $result[$id] = curl_multi_getcontent($c);
    curl_multi_remove_handle($mh, $c);
  }

  // all done
  curl_multi_close($mh);

  return $result;
}

$data = array(array(),array());

$data[0]['url']  = 'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Pearl+Jam&output=json';
$data[1]['url']  = 'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Black+Eyed+Peas&output=json';
$data[2]['url']  = 'http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=Nirvana&output=json';

$r = multiRequest($data);

print_r($r);

?>

Output

Array ( [0] => Pearl Jam

        [1] => Black Eyed Peas

        [2] => Nirvana )

Preferred Output

01:00:01 Pearl Jam

01:00:02 Black Eyed Peas

01:00:03 Nirvana

Body:
I'd say keep it simple...just do a loop where you set the timestamp and do a single curl call, then explode the resultarray and filter out all key or values you don't need.

For the curl call:

$r= array();

foreach($urls as $url) {
 $r[]["timestamp"]= time();
 $output= curl_exec($url);
 $r[]["bandname"]= $output;
}

Your final loop would be something like

foreach($r as $key=>$value){
 print $value["timestamp"];
 print $value["bandname"];
 print "<br>";
}


问:
Excel VBA Concatenate Function With COUNTIF Like Condition
The duplicate that this references is asking for a formula. The person explicitly said no VBA.

I'm looking for a function that performs concatenation like the built-in CONCATENATE() function, but with conditions like COUNTIF().

I'm looking for a simple VBA function. Other answers are complicated formulas.

Does something like this exist?

This question was created and worded to be found easily in a search. The idea was to help others from having to read many other questions and answers and not finding the answer they needed.

答:
This is a VBA function called ConcatenateIF() It works similar to how COUNTIF() works.

```<code>Function ConcatenateIf(CriteriaRange As Range, Condition As Variant, _
        ConcatenateRange As Range, Optional Separator As String = ",") As Variant
    Dim i As Long
    Dim strResult As String
    On Error GoTo ErrHandler
    If CriteriaRange.Count <> ConcatenateRange.Count Then
        ConcatenateIf = CVErr(xlErrRef)
        Exit Function
    End If
    For i = 1 To CriteriaRange.Count
        If CriteriaRange.Cells(i).Value = Condition Then
            strResult = strResult & Separator & ConcatenateRange.Cells(i).Value
        End If
    Next i
    If strResult <> "" Then
        strResult = Mid(strResult, Len(Separator) + 1)
    End If
    ConcatenateIf = strResult
    Exit Function
ErrHandler:
    ConcatenateIf = CVErr(xlErrValue)
End Function
</code>```

http://www.eileenslounge.com/viewtopic.php?f=27&t=12298

Body:
This is a VBA function called ConcatenateIF() It works similar to how COUNTIF() works.

Function ConcatenateIf(CriteriaRange As Range, Condition As Variant, _
        ConcatenateRange As Range, Optional Separator As String = ",") As Variant
    Dim i As Long
    Dim strResult As String
    On Error GoTo ErrHandler
    If CriteriaRange.Count <> ConcatenateRange.Count Then
        ConcatenateIf = CVErr(xlErrRef)
        Exit Function
    End If
    For i = 1 To CriteriaRange.Count
        If CriteriaRange.Cells(i).Value = Condition Then
            strResult = strResult & Separator & ConcatenateRange.Cells(i).Value
        End If
    Next i
    If strResult <> "" Then
        strResult = Mid(strResult, Len(Separator) + 1)
    End If
    ConcatenateIf = strResult
    Exit Function
ErrHandler:
    ConcatenateIf = CVErr(xlErrValue)
End Function

http://www.eileenslounge.com/viewtopic.php?f=27&t=12298


问:
AngularJS UI Rendering issue in custom plugin of vSphere web client
We are developing user custom for vmware's vSphere web client with the help of vSphere client SDK 6.0.

We have use html-bridge (AngularJS) to develop a UI for plugin and we are facing rendering issue of UI for one specific scenario.

Image 1: This window belongs to vCenter. If I select any drop down it will not impacting the remaining part of the screen.

Image 2: This window we have created in AngularJS with the help of html-bridge.

Image 3: If I am working on our custom window and selecting any drop own which is not a part of our custom window (They belongs to component of vCenter and I have highlighted with arrow). Then all content of our window will get disappeared.

Can we avoid this issue?

Please advice.

答:
This is an inherent problem of how Flash player shows HTML content. The HTML content you are showing in your plugin's view is nested in an IFrame which is essentially a native OS window in which your content is drawn. The Flash content of the web client is drawn in a separate native window that has a lower z-index than the IFrame window.
Since Flash popups (the menu in your screenshot, for example) is not drawn in its dedicate window but in the Flash player's one, it cannot float on top of the IFrame window (your content). Thus if the IFrame is not hidden, you'll "see" the pull-down menu going behind your plugin's view.

There is no proper workaround to this limitation.


问:
extension method overload Queryable.contains
This is the Error im getting.
This is for a search method.

Error CS1929  'SiteLocation' does not contain a definition for
  'Contains' and the best extension method overload
  'Queryable.Contains(IQueryable, string)' requires a
  receiver of type 'IQueryable'

```<code>public ActionResult Index(string projectname)
    {
        var projects = db.Projects.Include(p => p.Engineer).Include(p =>
p.SiteLocation);

        var a = from p in db.Projects.Include(p => p.Engineer).Include(p =>
p.SiteLocation)
                select p;
        if (!String.IsNullOrEmpty(projectname))
        {
            //NumberMCP = c.NumberMCP,
            //Engineer = c.Engineer,
            //Plink = c.Plink,
            a = a.Where(c => c.SiteLocation.Contains(projectname));
            a = a.Where(c => c.NumberMCP.Contains(projectname));
            a = a.Where(c => c.nameProject.Contains(projectname));
            //Ptype = c.Ptype,
              //       Pyear = c.Pyear,
                //     SiteLocationID = c.SiteLocationID
                 }

        return View(a.ToList());

    }
</code>```

I think my problem might be this: iqueryable convert int to string

答:
Problem: Were calling INT instead of String

Resolve: Converting type ToString if needed

```<code>  a = a.Where(c => c.NumberMCP.Contains(projectname)
                     || c.nameProject.Contains(projectname)
                    || c.Engineer.ToString().Contains(projectname)
                    || c.Plink.Contains(projectname)
                    || c.Pyear.ToString().Contains(projectname)
                    || c.SiteLocation.ToString().Contains(projectname)
                    || c.Ptype.Contains(projectname)
</code>```

Body:
This is the Error im getting.
This is for a search method.

Error CS1929  'SiteLocation' does not contain a definition for
  'Contains' and the best extension method overload
  'Queryable.Contains(IQueryable, string)' requires a
  receiver of type 'IQueryable'

public ActionResult Index(string projectname)
    {
        var projects = db.Projects.Include(p => p.Engineer).Include(p =>
p.SiteLocation);

        var a = from p in db.Projects.Include(p => p.Engineer).Include(p =>
p.SiteLocation)
                select p;
        if (!String.IsNullOrEmpty(projectname))
        {
            //NumberMCP = c.NumberMCP,
            //Engineer = c.Engineer,
            //Plink = c.Plink,
            a = a.Where(c => c.SiteLocation.Contains(projectname));
            a = a.Where(c => c.NumberMCP.Contains(projectname));
            a = a.Where(c => c.nameProject.Contains(projectname));
            //Ptype = c.Ptype,
              //       Pyear = c.Pyear,
                //     SiteLocationID = c.SiteLocationID
                 }

        return View(a.ToList());

    }

I think my problem might be this: iqueryable convert int to string

Body:
Problem: Were calling INT instead of String

Resolve: Converting type ToString if needed

  a = a.Where(c => c.NumberMCP.Contains(projectname)
                     || c.nameProject.Contains(projectname)
                    || c.Engineer.ToString().Contains(projectname)
                    || c.Plink.Contains(projectname)
                    || c.Pyear.ToString().Contains(projectname)
                    || c.SiteLocation.ToString().Contains(projectname)
                    || c.Ptype.Contains(projectname)


问:
Can't set title of toolbar that is inside an AppBarLayout
I have a toolbar inside of an AppBarLayout like this:

```<code><android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="right"
                android:orientation="horizontal">

                <ImageButton
                    android:id="@+id/editButton"
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center_vertical"
                    android:layout_marginRight="16dp"
                    android:scaleType="fitCenter"
                    android:background=
                        "?attr/selectableItemBackgroundBorderless"
                    android:contentDescription="Post"
                    android:src="@drawable/ic_mode_edit_24dp"
                    />

            </LinearLayout>

        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>
</code>```

In my Activity.OnCreate() I try to set the title like this:

```<code>Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Edit");
</code>```

(Not sure if this matters but..) After that I inflate a fragment:

```<code>MyFragment fragment = new MyFragment();
fragment.setArguments(savedInstanceState);

// Add fragment with tag
getSupportFragmentManager().beginTransaction()
    .add(R.id.content_frame, fragment, "my_frag")
    .commit();
</code>```

However, this has no effect. In fact, there is no title at all. Is this because I have a LinearLayout inside of the Toolbar or something? Or because of the AppBarLayout?

答: Use getSupportActionBar().setTitle(getString(R.string.title)); within the  activity. This can be done in onCreate should be done whenever the locale is changed

Body:
I have a toolbar inside of an AppBarLayout like this:

<android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="right"
                android:orientation="horizontal">

                <ImageButton
                    android:id="@+id/editButton"
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center_vertical"
                    android:layout_marginRight="16dp"
                    android:scaleType="fitCenter"
                    android:background=
                        "?attr/selectableItemBackgroundBorderless"
                    android:contentDescription="Post"
                    android:src="@drawable/ic_mode_edit_24dp"
                    />

            </LinearLayout>

        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>

In my Activity.OnCreate() I try to set the title like this:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Edit");

(Not sure if this matters but..) After that I inflate a fragment:

MyFragment fragment = new MyFragment();
fragment.setArguments(savedInstanceState);

// Add fragment with tag
getSupportFragmentManager().beginTransaction()
    .add(R.id.content_frame, fragment, "my_frag")
    .commit();

However, this has no effect. In fact, there is no title at all. Is this because I have a LinearLayout inside of the Toolbar or something? Or because of the AppBarLayout?


问:
Why did python choose commas over parenthesis in tuple design?
From python wiki

Multiple Element Tuples

In Python, multiple-element tuples look like:

1,2,3

...

but again, it is the commas, not the parentheses, that define the tuple.

Oh, really?!

Then why:

```<code>>>> tuple((((((1, 2, 3)))))) # creates a valid tuple
# (1, 2, 3)
>>> tuple(1, 2, 3, ) # But not here
# TypeError: tuple() takes at most 1 argument (3 given)
</code>```

More seriously, I don't get why the parenthesis was not chosen over the commas?

Because I think it would create a paradox when:

```<code>>>> 1, # is a valid tuple
# (1,)
>>> tuple([1]) # Or this
# (1,)
>>> tuple(1) # But not this one
# TypeError: 'int' object is not iterable
</code>```

However, if you consider that parenthesis were always in charge of instantiating  a tuple, all of the problems with instantiating  tuple with multiple items are gone.

e.g. in my imaginary world:

```<code>>>> (1, 2, 3) # stay valid
# (1, 2, 3)
>>> (1) # is newly valid
# (1)
>>> () # stay valid
# ()
>>> 1,
# TypeError: int() takes exactly 1 argument (2 given)
</code>```

I know this is a well-known feature and I'm already sorry if it a duplicate. I have found lots of similar topics about how tuple worked, but none explaining in details why this feature was created like that.

I am also aware that this topic could be closed as opinion-based, but I am mostly interested in technical reasons (if any), or at least historical reasons.

Thank you

答:
This is an artifact of the grammar.

The terms separated by commas are a building block for tuples, lists, and sets depending on whether they are wrapped by square brackets, curly braces, or nothing at all.

The chief challenge when specifying a grammar is balancing multiple competing uses of the same characters.  Commas separate parts of lists, tuples, dicts, and sets.  Commas also separate arguments in function calls.  Trailing commas are allowed for both uses (and are required for tuples of length one). Likewise, parentheses have multiple uses including function calls and grouping for arithmetic expressions.  The period serves as a decimal point and for the getattribute operator.

Body:
From python wiki

Multiple Element Tuples

In Python, multiple-element tuples look like:

1,2,3

...

but again, it is the commas, not the parentheses, that define the tuple.

Oh, really?!

Then why:

>>> tuple((((((1, 2, 3)))))) # creates a valid tuple
# (1, 2, 3)
>>> tuple(1, 2, 3, ) # But not here
# TypeError: tuple() takes at most 1 argument (3 given)

More seriously, I don't get why the parenthesis was not chosen over the commas?

Because I think it would create a paradox when:

>>> 1, # is a valid tuple
# (1,)
>>> tuple([1]) # Or this
# (1,)
>>> tuple(1) # But not this one
# TypeError: 'int' object is not iterable

However, if you consider that parenthesis were always in charge of instantiating  a tuple, all of the problems with instantiating  tuple with multiple items are gone.

e.g. in my imaginary world:

>>> (1, 2, 3) # stay valid
# (1, 2, 3)
>>> (1) # is newly valid
# (1)
>>> () # stay valid
# ()
>>> 1,
# TypeError: int() takes exactly 1 argument (2 given)

I know this is a well-known feature and I'm already sorry if it a duplicate. I have found lots of similar topics about how tuple worked, but none explaining in details why this feature was created like that.

I am also aware that this topic could be closed as opinion-based, but I am mostly interested in technical reasons (if any), or at least historical reasons.

Thank you


问:
Background Worker with Flask
I have a webapp that's built on python/Flask and it has a corresponding background job that runs continuously, periodically polling for data for each registered user.

I would like this background job to start when the system starts and keep running til it shuts down. Instead of setting up /etc/rc.d scripts, I just had the flask app spawn a new process (using the multiprocessing  module) when the app starts up.

So with this setup, I only have to deploy the Flask app and that will get the background worker running as well.

What are the downsides of this? Is this a complete and utter hack that is fragile in some way or a nice way to set up a webapp with corresponding background task?

答:
The downside of your approach is that there are many ways it could fail especially around stopping and restarting your flask application.

You will have to deal with graceful shutdown to give your worker a chance to finish its current task.

Sometime your worker won't stop on time and might linger while you start another one when you reboot your flask application.

Here are some approches I would suggest depending on your constraints:

script + crontab

You only have to write a script that does whatever task you want and cron will take care of running it for you every few minutes. Advantages: cron will run it for you periodically and will start when the system starts. Disadvantages: if the task takes too long, you might have multiple instances of your script running at the same time. You can find some solutions for this problem here.

supervisord

supervisord is a neat way to deal with different daemons. You can set it to run your app, your background script or both and have them start with the server. Only downside is that you have to install supervisord and make sure its daemon is running when the server starts.

uwsgi

uwsgi is a very common way for deploying flask applications. It has few features that might come in handy for managing background workers.

Celery

Celery is an asynchronous task queue/job queue based on distributed message passing. It is focused on real-time operation, but supports scheduling as well. I think this is the best solution for scheduling background tasks for a flask application or any other python based application. But using it comes with some extra bulk. You will be introducing at least the following processes:
- a broker (rabbitmq or redis)
- a worker
- a scheduler

You can also get supervisord to manage all of the processes above and get them to start when the server starts.

Conclusion

In your quest of reducing the number of processes, I would highly suggest the crontab based solution as it can get you a long way. But please make sure your background script leaves an execution trace or logs of some sort.

Title: Background Worker with Flask


问:
PHP files and folder structure showing, need to hide it
I have the following folder structure:

```<code>+users
   -adduser.php
   -viewuser.php
</code>```

When a visitor navigates to example.com/users it's showing the folder structure. I need to restrict visitors ability to see the file listing, either by hiding it or removing it. How can I do that in php?

答:
You can create a .htaccess file on root folder with following;

```<code>RewriteEngine on
Redirect 301 /users http://www.example.com/404.html
</code>```

Then you just need to create 404.html in your website and change example.com with your domain.

Now your /users path will redirect to 404.html.

Body:
I have the following folder structure:

+users
   -adduser.php
   -viewuser.php

When a visitor navigates to example.com/users it's showing the folder structure. I need to restrict visitors ability to see the file listing, either by hiding it or removing it. How can I do that in php?

Body:
You can create a .htaccess file on root folder with following;

RewriteEngine on
Redirect 301 /users http://www.example.com/404.html

Then you just need to create 404.html in your website and change example.com with your domain.

Now your /users path will redirect to 404.html.


答:
The reason why tuple(..) does not take multiple arguments, is because there can be confusion between (1) a single element with an iterable that should be converted to a tuple, and (2) multiple arguments.

Say you call tuple with a single iterable element, then there can be confusion whether Python should construct a tuple with one element: the iterable; or a tuple that is constructed based on the given iterable. The designers of Python chose the latter. As is specified in the documentation:

tuple(iterable)

This is reasonable since then one can write:

```<code>tuple(x*x for x in somelist if x%2)
</code>```

For instance to construct a tuple with squares of odd elements of the somelist.

In your first example:

```<code>tuple((((((1, 2, 3))))))
</code>```

You have constructed a tuple (1, 2, 3). Now you pass that tuple to the tuple constructor as the only parameter. Since a tuple is an iterable, you thus construct a tuple based on the only iterable you pass.

Your expression:

```<code>tuple(1, 2, 3, )
</code>```

However raises an error, since you provide more elements than the only one that you can and should pass.

Next you have the tuple literal. A literal is a comma separated list of expressions. It constructs a tuple with the given elements. In case you would however call a method without additional parenthesis, there is confusion between (1) a tuple literal; and (2) multiple arguments you pass to the method.

There are other such "grammar" aspects in Python. For instance if you pass a generator to a function with multiple arguments, the generator needs to be enclosed by parenthesis as well.

Title: Why did python choose commas over parenthesis in tuple design?

Body:
The reason why tuple(..) does not take multiple arguments, is because there can be confusion between (1) a single element with an iterable that should be converted to a tuple, and (2) multiple arguments.

Say you call tuple with a single iterable element, then there can be confusion whether Python should construct a tuple with one element: the iterable; or a tuple that is constructed based on the given iterable. The designers of Python chose the latter. As is specified in the documentation:

tuple(iterable)

This is reasonable since then one can write:

tuple(x*x for x in somelist if x%2)

For instance to construct a tuple with squares of odd elements of the somelist.

In your first example:

tuple((((((1, 2, 3))))))

You have constructed a tuple (1, 2, 3). Now you pass that tuple to the tuple constructor as the only parameter. Since a tuple is an iterable, you thus construct a tuple based on the only iterable you pass.

Your expression:

tuple(1, 2, 3, )

However raises an error, since you provide more elements than the only one that you can and should pass.

Next you have the tuple literal. A literal is a comma separated list of expressions. It constructs a tuple with the given elements. In case you would however call a method without additional parenthesis, there is confusion between (1) a tuple literal; and (2) multiple arguments you pass to the method.

There are other such "grammar" aspects in Python. For instance if you pass a generator to a function with multiple arguments, the generator needs to be enclosed by parenthesis as well.


问:
build maven project with propriatery libraries included
How to create maven pom, which will make project buildable, can I include propriatery jars with my project directly without having to take them from repository? anyone did this before ?

EDIT :

I don't want to make it runnable by building assembly with dependencies jar, I want it to be buildable. So anyone having this project is able to build it, even if jars are nowhere to be found at any repository.

答:
Why not run something like Nexus, your own maven repo that you can upload 3rd party proprietary jar files, and also proxy other public repositories, to save on bandwith?

This also has some good reasons to run your own maven repository manager.


答:
Usually, parens do not serve anything more than grouping, but when they appear after a callable, they have a different connotation than just grouping expressions; Python unlike, say Haskell, requires those parens to make the call.

In the following example, the outer pair of parens are bound to the function call (language construct), while the nested ones group the inner expression (the function arguments(s)) as a tuple:

```<code>>>> tuple((1, 2, 3))
(1, 2, 3)
</code>```

Essentially, the tuple is created by the comma(s).

Body:
Usually, parens do not serve anything more than grouping, but when they appear after a callable, they have a different connotation than just grouping expressions; Python unlike, say Haskell, requires those parens to make the call.

In the following example, the outer pair of parens are bound to the function call (language construct), while the nested ones group the inner expression (the function arguments(s)) as a tuple:

>>> tuple((1, 2, 3))
(1, 2, 3)

Essentially, the tuple is created by the comma(s).


问:
how do I change id for Single File Components in vue
I want to use single file component code style as following code in vue

item.vue

```<code><template>
    <item v-if="value">
</template>
<script>
   export default {
      name: 'item',...</script>
...
</script>
<style>...</style>
</code>```

its OK but as you see I have used item component Recursively but there is problem with recursive components and they say I have to use different name and id as following code to fix this problem

```<code>Vue.component('id', {
    name: 'internal-name',
    ...
})
</code>```

so how do I set different name and id in item.vue with its code style?

答:
The id is only set when you make the component globaly available in the parent by using the Vue.component('id', {...}) command. The name is an optional part of a component.
The given solution in the issue with Vue.component('id', Vue.extend({...})) seems to be worth a try.

ContentLicense: CC BY-SA 4.0

Body:
I want to use single file component code style as following code in vue

item.vue

<template>
    <item v-if="value">
</template>

...
</script>

its OK but as you see I have used item component Recursively but there is problem with recursive components and they say I have to use different name and id as following code to fix this problem

Vue.component('id', {
    name: 'internal-name',
    ...
})

so how do I set different name and id in item.vue with its code style?


问:
How to set a created event's `isTrusted` property in javascript using Greasemonkey
I would like to create and fire a KeyPress Event through a userscript in Greasemonkey but I observed that the createEvent's isTrusted is set to false all the time.

isTrusted is read-only property but I read that it can be set to True by extensions like Greasemonkey but it's not working for me.

Is there a way to set isTrusted to true?.

答:
No.  You cannot currently do this with Greasemonkey.  For the most part, Greasemonkey just runs javascript, and javascript can't set isTrusted.  It would defy the spec and defeat the whole purpose of trusted events.

That said, theoretically, a Firefox add-on should be able to spoof isTrusted, but Greasemonkey has not extended that capability to its users.

There is a feature request to add isTrusted capability to Greasemonkey.  You can go there and add your voice to the discussion, or you can fork the Greasemonkey code and add the capability yourself.

There is a related question for Google Chrome, but spoofing isTrusted may not be possible in that browser, even for extensions.


问:
Amazon Cognito: Enforcing password expiration policy
Is there a way to enforce password expiration policy on users in Amazon Cognito user pools?</p>

答: It doesn't look like expiration is built into the password policy. You could track password expiration by adding a passwordUpdatedAt field and manually updating that attribute on user sign up and on changePassword. Then you could schedule something that queries users with expired passwords and call AdminResetUserPassword for those users. It would be somewhat more reliable if AWS published Cognito Userpoool User events like changePassword or just baked it into the service.


问:
Java: custom toString to fit any class
I want to create a toString() method that works for any class, printing all its attributes as if it worked like this:

```<code>String toString(){
    String s = "";
    for(Attribute att: this.Attributes){
        s += (att.name + ": " + att.toString() + "\n");
    }
    return s;
}
</code>```

But this would work supposing all attributes have toString() method, so let's keep this supposition.

I guess this question includes concepts of reflection, and I don't know much about this concept nor how to apply this in Java.

答:
This is a rather complicated affair, because one of the things you need to take care of is circular references, which, if you are not careful, will cause infinite recursion resulting in a StackOverflow exception.

These are a set of methods for accomplishing what you want:

```<code>public static String reflectionToString( Object obj )
{
    StringBuilder stringBuilder = new StringBuilder();
    reflectionToString( stringBuilder, obj );
    return stringBuilder.toString();
}

public static void reflectionToString( StringBuilder stringBuilder, Object obj )
{
    reflectionToString( new ArrayList<>(), stringBuilder, obj );
}

private static void reflectionToString( ArrayList<Object> visited,
    StringBuilder stringBuilder, Object obj )
{
    if( obj == null )
    {
        stringBuilder.append( "null" );
        return;
    }

    Class<?> objectClass = obj.getClass();

    if( objectClass == String.class )
    {
        StaticStringHelpers.appendEscapedForJava( stringBuilder, String.valueOf( obj ), '"' );
        return;
    }

    if( objectClass.isPrimitive() )
    {
        stringBuilder.append( obj );
        return;
    }

    if( Collection.class.isAssignableFrom( objectClass ) && ((Collection<?>)obj).isEmpty() )
    {
        stringBuilder.append( "{}" );
        return;
    }

    if( objectClass.isEnum() )
    {
        stringBuilder.append( obj );
        return;
    }

    if( objectClass.isArray() )
    {
        stringBuilder.append( objectClass.getComponentType().getName() ).append( "[]" );
    }
    else
    {
        stringBuilder.append( objectClass.getName() );
    }
    stringBuilder.append( "@" ).append( Integer.toHexString( System.identityHashCode( obj ) ) );

    if( visited.contains( obj ) )
        return;
    visited.add( obj );

    stringBuilder.append( "={" );
    if( objectClass.isArray() )
    {
        for( int i = 0; i < Array.getLength( obj ); i++ )
        {
            if( i > 0 )
                stringBuilder.append( "," );
            Object val = Array.get( obj, i );
            reflectionToString( visited, stringBuilder, val );
        }
    }
    else
    {
        boolean[] first = { true };
        reflectionToString( visited, stringBuilder, first, objectClass, obj );
    }
    stringBuilder.append( "}" );
}

private static void reflectionToString( ArrayList<Object> visited,
    StringBuilder stringBuilder, boolean[] first,
    Class<?> objectClass, Object obj )
{
    Class<?> superClass = objectClass.getSuperclass();
    if( superClass != null )
        reflectionToString( visited, stringBuilder, first, superClass, obj );
    Field[] fields = objectClass.getDeclaredFields();
    AccessibleObject.setAccessible( fields, true );
    for( Field field : fields )
    {
        if( Modifier.isStatic( field.getModifiers() ) )
            continue;
        appendNonFirst( stringBuilder, first, "," );
        stringBuilder.append( field.getName() ).append( "=" );
        try
        {
            Object fieldValue = field.get( obj );
            reflectionToString( visited, stringBuilder, fieldValue );
        }
        catch( Exception e )
        {
            assert false : e;
        }
    }
}

private static StringBuilder appendNonFirst( StringBuilder stringBuilder,
    boolean[] first, String text )
{
    if( first[0] )
        first[0] = false;
    else
        stringBuilder.append( text );
    return stringBuilder;
}
</code>```

The ArrayList<Object> visited collects all visited objects so as to avoid re-visiting them.  I do not remember why it is an ArrayList and not a Set.

The StringBuilder is where the string is collected.  The toString() method which invokes reflectionToString() ends with a return stringBuilder.toString();.

boolean[] first is just a single-element array containing a boolean, which is a hacky way to pass a single boolean by reference.  It is simply used for figuring out whether a comma should be emitted.

Class<?> objectClass is the class of the object being emitted.

Object obj is the object being emitted.

Title: Java: custom toString to fit any class

Body:
I want to create a toString() method that works for any class, printing all its attributes as if it worked like this:

String toString(){
    String s = "";
    for(Attribute att: this.Attributes){
        s += (att.name + ": " + att.toString() + "\n");
    }
    return s;
}

But this would work supposing all attributes have toString() method, so let's keep this supposition.

I guess this question includes concepts of reflection, and I don't know much about this concept nor how to apply this in Java.

Body:
This is a rather complicated affair, because one of the things you need to take care of is circular references, which, if you are not careful, will cause infinite recursion resulting in a StackOverflow exception.

These are a set of methods for accomplishing what you want:

public static String reflectionToString( Object obj )
{
    StringBuilder stringBuilder = new StringBuilder();
    reflectionToString( stringBuilder, obj );
    return stringBuilder.toString();
}

public static void reflectionToString( StringBuilder stringBuilder, Object obj )
{
    reflectionToString( new ArrayList<>(), stringBuilder, obj );
}

private static void reflectionToString( ArrayList<Object> visited,
    StringBuilder stringBuilder, Object obj )
{
    if( obj == null )
    {
        stringBuilder.append( "null" );
        return;
    }

    Class<?> objectClass = obj.getClass();

    if( objectClass == String.class )
    {
        StaticStringHelpers.appendEscapedForJava( stringBuilder, String.valueOf( obj ), '"' );
        return;
    }

    if( objectClass.isPrimitive() )
    {
        stringBuilder.append( obj );
        return;
    }

    if( Collection.class.isAssignableFrom( objectClass ) && ((Collection<?>)obj).isEmpty() )
    {
        stringBuilder.append( "{}" );
        return;
    }

    if( objectClass.isEnum() )
    {
        stringBuilder.append( obj );
        return;
    }

    if( objectClass.isArray() )
    {
        stringBuilder.append( objectClass.getComponentType().getName() ).append( "[]" );
    }
    else
    {
        stringBuilder.append( objectClass.getName() );
    }
    stringBuilder.append( "@" ).append( Integer.toHexString( System.identityHashCode( obj ) ) );

    if( visited.contains( obj ) )
        return;
    visited.add( obj );

    stringBuilder.append( "={" );
    if( objectClass.isArray() )
    {
        for( int i = 0; i < Array.getLength( obj ); i++ )
        {
            if( i > 0 )
                stringBuilder.append( "," );
            Object val = Array.get( obj, i );
            reflectionToString( visited, stringBuilder, val );
        }
    }
    else
    {
        boolean[] first = { true };
        reflectionToString( visited, stringBuilder, first, objectClass, obj );
    }
    stringBuilder.append( "}" );
}

private static void reflectionToString( ArrayList<Object> visited,
    StringBuilder stringBuilder, boolean[] first,
    Class<?> objectClass, Object obj )
{
    Class<?> superClass = objectClass.getSuperclass();
    if( superClass != null )
        reflectionToString( visited, stringBuilder, first, superClass, obj );
    Field[] fields = objectClass.getDeclaredFields();
    AccessibleObject.setAccessible( fields, true );
    for( Field field : fields )
    {
        if( Modifier.isStatic( field.getModifiers() ) )
            continue;
        appendNonFirst( stringBuilder, first, "," );
        stringBuilder.append( field.getName() ).append( "=" );
        try
        {
            Object fieldValue = field.get( obj );
            reflectionToString( visited, stringBuilder, fieldValue );
        }
        catch( Exception e )
        {
            assert false : e;
        }
    }
}

private static StringBuilder appendNonFirst( StringBuilder stringBuilder,
    boolean[] first, String text )
{
    if( first[0] )
        first[0] = false;
    else
        stringBuilder.append( text );
    return stringBuilder;
}

The ArrayList<Object> visited collects all visited objects so as to avoid re-visiting them.  I do not remember why it is an ArrayList and not a Set.

The StringBuilder is where the string is collected.  The toString() method which invokes reflectionToString() ends with a return stringBuilder.toString();.

boolean[] first is just a single-element array containing a boolean, which is a hacky way to pass a single boolean by reference.  It is simply used for figuring out whether a comma should be emitted.

Class<?> objectClass is the class of the object being emitted.

Object obj is the object being emitted.


问:
Pause/resume mediaPlayer on notification sound
It's easy to detect when phone calls come in (via phoneStateListener), but what about other notification sounds, such as email or sms?

On some devices, these notification sounds mute but don't pause any currently running mediaPlayer instances, which is annoying for the user.  Ideally, I'd like to listen for notifications that play sound, pause playback for the duration, and then resume playback afterwards.

答: You can get notified when another app wants to play audio by registering a callback on AudioManager.OnAudioFocusChangeListener (this would also handle the case of an incoming call).  Specifically, you can look for AUDIOFOCUS_GAIN, AUDIOFOCUS_LOSS, and AUDIOFOCUS_TRANSIENT_LOSS.  The Android music player source has a good example of this.


答:
You could do this by reflection or you could use libraries like snakeyaml or gson or jackson.

You could in fact serialize several simple objects, but there are object which could not be serialized to a string, and also objects with circular references could prove difficult to stringify.

You could do this with a couple of clicks in a java IDE, for example in eclipse there is a very simple wizard that does this for any object.

Last but not least it would not play well with java polymorphism, it would not be advisable to make many classes inherit from a common ancestor just to override the toString().

I personally stick with the IDE simple solution which is practical and uses neither libraries nor imposes any constraint on classes with a minimum fuss.

For example in eclipse you could achieve this on the source context menu by selecting Source > Generate toString ... :

```<code>public class Foo {
    private String name;
    private Integer age;
    private Date birthday;

    @Override
    public String toString() {
        return "Foo [name=" + name + ", age=" + age + ", birthday=" + birthday + "]";
    }
}
</code>```

Title: Java: custom toString to fit any class

Body:
You could do this by reflection or you could use libraries like snakeyaml or gson or jackson.

You could in fact serialize several simple objects, but there are object which could not be serialized to a string, and also objects with circular references could prove difficult to stringify.

You could do this with a couple of clicks in a java IDE, for example in eclipse there is a very simple wizard that does this for any object.

Last but not least it would not play well with java polymorphism, it would not be advisable to make many classes inherit from a common ancestor just to override the toString().

I personally stick with the IDE simple solution which is practical and uses neither libraries nor imposes any constraint on classes with a minimum fuss.

For example in eclipse you could achieve this on the source context menu by selecting Source > Generate toString ... :

public class Foo {
    private String name;
    private Integer age;
    private Date birthday;

    @Override
    public String toString() {
        return "Foo [name=" + name + ", age=" + age + ", birthday=" + birthday + "]";
    }
}


问:
How to add a trendline to a boxplot of counts(y axis) and ids(x axis) when x axis is ordered
```<code>df1 <- data.frame(a=c(1,4,7),
              b=c(3, 5, 6),
              c=c(1, 1, 4),
              d=c(2 ,6 ,3))
df2<-data.frame(id=c("a","f","f","b","b","c","c","c","d","d"),
            var=c(12,20,15,18,10,30,5,8,5,5))

mediorder <- with(df2, reorder(id, -var, median))
boxplot(var~mediorder, data = df2)

fc = levels(as.factor(mediorder))
ndf1= df1[,intersect(fc, colnames(df1))]

ln<-lm( #confused here

boxplot(ndf1)
abline(ln)
</code>```

I have the above boxplot (ndf1) with an x-axis ordered according to medians from another data frame, and I would like to add a trendline to it.

I am confused since it doesn't have an x and y variable to refer to, just columns with counts. Also the ordering is causing me problems.

EDITED for clarification...
I am building on the question here: How to match an ordered list (e.g., levels(as.factor(x)) ) to another dataframe in which only some columns match?

All I would like to do is fit a trend line to ndf1

答:
Something like this should do. It's fairly easy using ggplot2. However, your data/question are a bit confusing e.g. Some factors (a,d) have one data point only. Is this what you want?

```<code>df2$id <- factor(df2$id , levels = levels(mediorder))
library(ggplot2)
ggplot(data = df2, aes(x = id, y = var)) +  geom_boxplot() +
  geom_smooth(method = "lm", aes(group = 1), se = F)
</code>```

Body:
df1 <- data.frame(a=c(1,4,7),
              b=c(3, 5, 6),
              c=c(1, 1, 4),
              d=c(2 ,6 ,3))
df2<-data.frame(id=c("a","f","f","b","b","c","c","c","d","d"),
            var=c(12,20,15,18,10,30,5,8,5,5))

mediorder <- with(df2, reorder(id, -var, median))
boxplot(var~mediorder, data = df2)

fc = levels(as.factor(mediorder))
ndf1= df1[,intersect(fc, colnames(df1))]

ln<-lm( #confused here

boxplot(ndf1)
abline(ln)

I have the above boxplot (ndf1) with an x-axis ordered according to medians from another data frame, and I would like to add a trendline to it.

I am confused since it doesn't have an x and y variable to refer to, just columns with counts. Also the ordering is causing me problems.

EDITED for clarification...
I am building on the question here: How to match an ordered list (e.g., levels(as.factor(x)) ) to another dataframe in which only some columns match?

All I would like to do is fit a trend line to ndf1

Body:
Something like this should do. It's fairly easy using ggplot2. However, your data/question are a bit confusing e.g. Some factors (a,d) have one data point only. Is this what you want?

df2$id <- factor(df2$id , levels = levels(mediorder))
library(ggplot2)
ggplot(data = df2, aes(x = id, y = var)) +  geom_boxplot() +
  geom_smooth(method = "lm", aes(group = 1), se = F)


问:
Exclude one class file in gradle Android Studio
In my projects, I need to import third party jar file and Facebook SDK.

```<code>compile files('libs/SkinSDK.jar')
compile 'com.facebook.android:facebook-android-sdk:4.14.0'
</code>```

Both include same BundleJSONConverter class. So, I cannot do generate signed APK. It always shows duplicate entry com/facebook/internal/BundleJSONConverter.

So, I want to exclude in Facebook or SkinSDK.jar. I tried like

```<code>compile ('com.facebook.android:facebook-android-sdk:4.14.0') {
    exclude group: 'com.facebook.internal', module: 'BundleJSONConverter'
}
</code>```

It's not working and showing same error.

答:
The exclude method of the configuration closure for a dependency excludes transitive dependencies. So, if your module dependency depends on other modules, you can exclude them from your build. You can check out the transitive dependencies of the 'com.facebook.android:facebook-android-sdk:4.14.0' module on its Maven repository info page.

If the BundleJSONConverter class exists in a transitive dependency, you can exclude the specific module in the same way you are trying now. Just specify the group, the module and the version, like you do for dependencies.

If you just want to exclude one class for a dependency jar, take a look at the jar jar links tool and its Gradle plugin. It allows you to alter included jars, e.g. to change packages or remove classes.

The following (shortened) example shows the usage of the plugin and some methods to alter the dependency jar:

```<code>compile jarjar.repackage {
    from 'org.apache.hive:hive-exec:0.13.0.2.1.5.0-695'

    archiveBypass "commons*.jar"
    archiveExclude "slf4j*.jar"

    classDelete "org.apache.thrift.**"
    classRename 'org.json.**', 'org.anarres.hive.json.@1'
}
</code>```

Body:
In my projects, I need to import third party jar file and Facebook SDK.

compile files('libs/SkinSDK.jar')
compile 'com.facebook.android:facebook-android-sdk:4.14.0'

Both include same BundleJSONConverter class. So, I cannot do generate signed APK. It always shows duplicate entry com/facebook/internal/BundleJSONConverter.

So, I want to exclude in Facebook or SkinSDK.jar. I tried like

compile ('com.facebook.android:facebook-android-sdk:4.14.0') {
    exclude group: 'com.facebook.internal', module: 'BundleJSONConverter'
}

It's not working and showing same error.

Body:
The exclude method of the configuration closure for a dependency excludes transitive dependencies. So, if your module dependency depends on other modules, you can exclude them from your build. You can check out the transitive dependencies of the 'com.facebook.android:facebook-android-sdk:4.14.0' module on its Maven repository info page.

If the BundleJSONConverter class exists in a transitive dependency, you can exclude the specific module in the same way you are trying now. Just specify the group, the module and the version, like you do for dependencies.

If you just want to exclude one class for a dependency jar, take a look at the jar jar links tool and its Gradle plugin. It allows you to alter included jars, e.g. to change packages or remove classes.

The following (shortened) example shows the usage of the plugin and some methods to alter the dependency jar:

compile jarjar.repackage {
    from 'org.apache.hive:hive-exec:0.13.0.2.1.5.0-695'

    archiveBypass "commons*.jar"
    archiveExclude "slf4j*.jar"

    classDelete "org.apache.thrift.**"
    classRename 'org.json.**', 'org.anarres.hive.json.@1'
}