问:
Django Inline for ManyToMany generate duplicate queries
I'm experiencing some major performing issue with my django admin. Lots of duplicate queries based on how many inlines that I have.

models.py

```<code>class Setting(models.Model):
    name = models.CharField(max_length=50, unique=True)

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name

class DisplayedGroup(models.Model):
    name = models.CharField(max_length=30, unique=True)
    position = models.PositiveSmallIntegerField(default=100)

    class Meta:
        ordering = ('priority',)

    def __str__(self):
        return self.name

class Machine(models.Model):
    name = models.CharField(max_length=20, unique=True)
    settings = models.ManyToManyField(
        Setting, through='Arrangement', blank=True
    )

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name

class Arrangement(models.Model):
    machine = models.ForeignKey(Machine, on_delete=models.CASCADE)
    setting = models.ForeignKey(Setting, on_delete=models.CASCADE)
    displayed_group = models.ForeignKey(
        DisplayedGroup, on_delete=models.PROTECT,
        default=1)
    priority = models.PositiveSmallIntegerField(
        default=100,
        help_text='Smallest number will be displayed first'
    )

    class Meta:
        ordering = ('priority',)
        unique_together = (("machine", "setting"),)
</code>```

admin.py

```<code>class ArrangementInline(admin.TabularInline):
    model = Arrangement
    extra = 1

class MachineAdmin(admin.ModelAdmin):
    inlines = (ArrangementInline,)
</code>```

If I have 3 settings added on inline form and 1 extra, I have about 10 duplicate queries

```<code>SELECT "corps_setting"."id", "corps_setting"."name", "corps_setting"."user_id", "corps_setting"."tagged", "corps_setting"."created", "corps_setting"."modified" FROM "corps_setting" ORDER BY "corps_setting"."name" ASC
- Duplicated 5 times

SELECT "corps_displayedgroup"."id", "corps_displayedgroup"."name", "corps_displayedgroup"."color", "corps_displayedgroup"."priority", "corps_displayedgroup"."created", "corps_displayedgroup"."modified" FROM "corps_displayedgroup" ORDER BY "corps_displayedgroup"."priority" ASC
- Duplicated 5 times.
</code>```

Could someone please tell me what I'm doing wrong right here? I've spent 3 days trying to figure the problem out myself without luck.

The issue gets worse when I have about 50 settings inlines of a Machine, I will have ~100 queries.

Here is the screenshot

答:
Nowadays, (kudos to that question), BaseFormset receives a form_kwargs attribute.

The ChoicesFormSet code in the accepted answer could be slightly modified as such:

```<code>class ChoicesFormSet(forms.BaseInlineFormSet):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        setting_choices = list(Setting.objects.values_list('id', 'name'))
        displayed_group_choices = list(DisplayedGroup.objects.values_list('id', 'name'))
        self.form_kwargs['setting_choices'] = self.setting_choices
        self.form_kwargs['displayed_group_choices'] = self.displayed_group_choices
</code>```

The rest of the code stays intact, as desscribed in the accepted answer:

```<code>class ArrangementInlineForm(forms.ModelForm):
    class Meta:
        model = Arrangement
        exclude = ()

    def __init__(self, *args, **kwargs):
        setting_choices = kwargs.pop('setting_choices', [((), ())])
        displayed_group_choices = kwargs.pop('displayed_group_choices', [((), ())])

        super().__init__(*args, **kwargs)

        # This ensures that you can still save the form without setting all 50 (see extra value) inline values.
        # When you save, the field value is checked against the "initial" value
        # of a field and you only get a validation error if you've changed any of the initial values.
        self.fields['setting'].choices = [('-', '---')] + setting_choices
        self.fields['setting'].initial = self.fields['setting'].choices[0][0]
        self.fields['setting'].empty_values = (self.fields['setting'].choices[0][0],)

        self.fields['displayed_group'].choices = displayed_group_choices
        self.fields['displayed_group'].initial = self.fields['displayed_group'].choices[0][0]

class ArrangementInline(admin.TabularInline):
    model = Arrangement
    extra = 50
    form = ArrangementInlineForm
    formset = ChoicesFormSet

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('setting')

class MachineAdmin(admin.ModelAdmin):
    inlines = (ArrangementInline,)

admin.site.register(Machine, MachineAdmin)
</code>```

Body:
I'm experiencing some major performing issue with my django admin. Lots of duplicate queries based on how many inlines that I have.

models.py

class Setting(models.Model):
    name = models.CharField(max_length=50, unique=True)

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name

class DisplayedGroup(models.Model):
    name = models.CharField(max_length=30, unique=True)
    position = models.PositiveSmallIntegerField(default=100)

    class Meta:
        ordering = ('priority',)

    def __str__(self):
        return self.name

class Machine(models.Model):
    name = models.CharField(max_length=20, unique=True)
    settings = models.ManyToManyField(
        Setting, through='Arrangement', blank=True
    )

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name

class Arrangement(models.Model):
    machine = models.ForeignKey(Machine, on_delete=models.CASCADE)
    setting = models.ForeignKey(Setting, on_delete=models.CASCADE)
    displayed_group = models.ForeignKey(
        DisplayedGroup, on_delete=models.PROTECT,
        default=1)
    priority = models.PositiveSmallIntegerField(
        default=100,
        help_text='Smallest number will be displayed first'
    )

    class Meta:
        ordering = ('priority',)
        unique_together = (("machine", "setting"),)

admin.py

class ArrangementInline(admin.TabularInline):
    model = Arrangement
    extra = 1

class MachineAdmin(admin.ModelAdmin):
    inlines = (ArrangementInline,)

If I have 3 settings added on inline form and 1 extra, I have about 10 duplicate queries

SELECT "corps_setting"."id", "corps_setting"."name", "corps_setting"."user_id", "corps_setting"."tagged", "corps_setting"."created", "corps_setting"."modified" FROM "corps_setting" ORDER BY "corps_setting"."name" ASC
- Duplicated 5 times

SELECT "corps_displayedgroup"."id", "corps_displayedgroup"."name", "corps_displayedgroup"."color", "corps_displayedgroup"."priority", "corps_displayedgroup"."created", "corps_displayedgroup"."modified" FROM "corps_displayedgroup" ORDER BY "corps_displayedgroup"."priority" ASC
- Duplicated 5 times.

Could someone please tell me what I'm doing wrong right here? I've spent 3 days trying to figure the problem out myself without luck.

The issue gets worse when I have about 50 settings inlines of a Machine, I will have ~100 queries.

Here is the screenshot

Body:
Nowadays, (kudos to that question), BaseFormset receives a form_kwargs attribute.

The ChoicesFormSet code in the accepted answer could be slightly modified as such:

class ChoicesFormSet(forms.BaseInlineFormSet):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        setting_choices = list(Setting.objects.values_list('id', 'name'))
        displayed_group_choices = list(DisplayedGroup.objects.values_list('id', 'name'))
        self.form_kwargs['setting_choices'] = self.setting_choices
        self.form_kwargs['displayed_group_choices'] = self.displayed_group_choices

The rest of the code stays intact, as desscribed in the accepted answer:

class ArrangementInlineForm(forms.ModelForm):
    class Meta:
        model = Arrangement
        exclude = ()

    def __init__(self, *args, **kwargs):
        setting_choices = kwargs.pop('setting_choices', [((), ())])
        displayed_group_choices = kwargs.pop('displayed_group_choices', [((), ())])

        super().__init__(*args, **kwargs)

        # This ensures that you can still save the form without setting all 50 (see extra value) inline values.
        # When you save, the field value is checked against the "initial" value
        # of a field and you only get a validation error if you've changed any of the initial values.
        self.fields['setting'].choices = [('-', '---')] + setting_choices
        self.fields['setting'].initial = self.fields['setting'].choices[0][0]
        self.fields['setting'].empty_values = (self.fields['setting'].choices[0][0],)

        self.fields['displayed_group'].choices = displayed_group_choices
        self.fields['displayed_group'].initial = self.fields['displayed_group'].choices[0][0]

class ArrangementInline(admin.TabularInline):
    model = Arrangement
    extra = 50
    form = ArrangementInlineForm
    formset = ChoicesFormSet

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('setting')

class MachineAdmin(admin.ModelAdmin):
    inlines = (ArrangementInline,)

admin.site.register(Machine, MachineAdmin)


来源: stackexchange

问:
BeautifulSoup .text method error: ResultSet object has no attribute 'text'
I created a simple scraper but I have a problem with changing ResultSet to text. I want to get the only text without a href etc. When I use find method it works good, but when I add find_all as a second method it shows error:

```<code>numberone = soup.find("span", itemprop="house").text                      <---- this works good
print(numberone)

numbertwo = soup.find("div", class_="interesting").find_all('a').text     <---- this does not work
print(numbertwo)
</code>```

Output for 'numberone' is good, but for 'numbertwo' it shows an error:

"ResultSet object has no attribute '%s'. You're probably treating a
  list of elements like a single element. Did you call find_all() when
  you meant to call find()?" % key AttributeError: ResultSet object has
  no attribute 'text'. You're probably treating a list of elements like
  a single element. Did you call find_all() when you meant to call
  find()?

Maybe someone knows the solution?

答:
it is because it returns a set of results, in order to print all the results you can use a for-loop like this:</p>

```<code>results = numbertwo = soup.find("div", class_="interesting").find_all('a')
for result in results:
    print(result.text)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I created a simple scraper but I have a problem with changing ResultSet to text. I want to get the only text without a href etc. When I use find method it works good, but when I add find_all as a second method it shows error:

numberone = soup.find("span", itemprop="house").text                      <---- this works good
print(numberone)

numbertwo = soup.find("div", class_="interesting").find_all('a').text     <---- this does not work
print(numbertwo)

Output for 'numberone' is good, but for 'numbertwo' it shows an error:

"ResultSet object has no attribute '%s'. You're probably treating a
  list of elements like a single element. Did you call find_all() when
  you meant to call find()?" % key AttributeError: ResultSet object has
  no attribute 'text'. You're probably treating a list of elements like
  a single element. Did you call find_all() when you meant to call
  find()?

Maybe someone knows the solution?

Body:
it is because it returns a set of results, in order to print all the results you can use a for-loop like this:

results = numbertwo = soup.find("div", class_="interesting").find_all('a')
for result in results:
    print(result.text)


问:
Passing function from another class to this class
I know, title is hard to understand.

So, i have this class:

```<code>class ConfigDict(dict):

    def __init__(self, dic):
        super(ConfigDict, self).__init__(dic)

    def required(self, keys_array, function):
        print 'required'

    def valid(self, function = None):
        print 'valid'
</code>```

And what i want - i create instance of this class with dict as parameter:

```<code>ConfigDict({'a' : 'b'})
</code>```

It's working, thats good. But i want pass function as argument in dict from ConfigDict class without importing methods from ConfigDict.

For example, i want do this:

```<code> ConfigDict({'a' : ('b', required(['test'], valid))})
</code>```

I know that required in ConfigDict do nothing now. Expected result is:

```<code>>> ConfigDict({'a' : ('b', required(['test'], valid()))})
required called with ['test'], valid for {a : b}
valid called from required with None for {a : b}
</code>```

So, after creating instance of ConfigDict with {'a' : ('b', required['test'], valid())} dict, i want that this instance in __init__ method make loop in all dict elements, and if founds tuple in value, execute founded nested function in itselfs.

Is here any way to do this without importing all methods from ConfigDict?

EDIT:

As i expected i must better explain what i need.

Ok, we take this fragment:

```<code>ConfigDict({'a' : ('b', required(['test'], valid))})
</code>```

This made us new instance of ConfigDict. These functions in touple is used to validate value, in this case it is 'b'. I made few changes waiting for response, so calling this class is now look that:

```<code>cd = ConfigDict()
cd.feed({'a' : 'b'})
</code>```

I can call functions like that:

```<code>cd.feed({'a' : ('b', cg.required(['test']))})
</code>```

What is work's very well, but there's one thing - it not pass to required function the value. ConfigDicts.required should get an array and value, in this case 'b'. I don't expect to find way to do this myself, except using everywhere lambda's what i like to avoid.

So, my question been bit changed - is there a any way to get 'b' value from inside required function? I can pass 'b' as argument directly into required, but i expect to have many functions call in tuple, passing value for each make a little mess in code.

Also, anyone please, edit title of my post, i lack of words to describe this problem :)

答:
Use a lambda function:

```<code>ConfigDict({'a' : ('b', lambda self: self.required(['test'], valid))})
</code>```

This would require you to explicitly pass self as a parameter (From the __init__ method, it would look like dict['a'][1](self)).

You can find out if something is a tuple like this:

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

And if you need to, you can find out if something is a function like so:

```<code>>>> import inspect
>>> def f():
    print "I'm a function"
>>> inspect.isfunction(f)
True
>>> inspect.isfunction(5)
False
>>> inspect.isfunction(lambda d: d)
True
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know, title is hard to understand.

So, i have this class:

class ConfigDict(dict):

    def __init__(self, dic):
        super(ConfigDict, self).__init__(dic)

    def required(self, keys_array, function):
        print 'required'

    def valid(self, function = None):
        print 'valid'

And what i want - i create instance of this class with dict as parameter:

ConfigDict({'a' : 'b'})

It's working, thats good. But i want pass function as argument in dict from ConfigDict class without importing methods from ConfigDict.

For example, i want do this:

 ConfigDict({'a' : ('b', required(['test'], valid))})

I know that required in ConfigDict do nothing now. Expected result is:

>> ConfigDict({'a' : ('b', required(['test'], valid()))})
required called with ['test'], valid for {a : b}
valid called from required with None for {a : b}

So, after creating instance of ConfigDict with {'a' : ('b', required['test'], valid())} dict, i want that this instance in __init__ method make loop in all dict elements, and if founds tuple in value, execute founded nested function in itselfs.

Is here any way to do this without importing all methods from ConfigDict?

EDIT:

As i expected i must better explain what i need.

Ok, we take this fragment:

ConfigDict({'a' : ('b', required(['test'], valid))})

This made us new instance of ConfigDict. These functions in touple is used to validate value, in this case it is 'b'. I made few changes waiting for response, so calling this class is now look that:

cd = ConfigDict()
cd.feed({'a' : 'b'})

I can call functions like that:

cd.feed({'a' : ('b', cg.required(['test']))})

What is work's very well, but there's one thing - it not pass to required function the value. ConfigDicts.required should get an array and value, in this case 'b'. I don't expect to find way to do this myself, except using everywhere lambda's what i like to avoid.

So, my question been bit changed - is there a any way to get 'b' value from inside required function? I can pass 'b' as argument directly into required, but i expect to have many functions call in tuple, passing value for each make a little mess in code.

Also, anyone please, edit title of my post, i lack of words to describe this problem :)

Body:
Use a lambda function:

ConfigDict({'a' : ('b', lambda self: self.required(['test'], valid))})

This would require you to explicitly pass self as a parameter (From the __init__ method, it would look like dict['a'][1](self)).

You can find out if something is a tuple like this:

>>> isinstance((1, 2, 3), tuple)
True
>>> isinstance(1, tuple)
False

And if you need to, you can find out if something is a function like so:

>>> import inspect
>>> def f():
    print "I'm a function"
>>> inspect.isfunction(f)
True
>>> inspect.isfunction(5)
False
>>> inspect.isfunction(lambda d: d)
True


问:
sharepoint email workflow not sending mails
i am not able to initiate mails from one of my workflow . i have created one workflow with 2 stages, first one detects the recurrence and second one creates the new task if the first task has been completed.
And another workflow which sent out mails "3" days before start date. This sending mails 3 days before start date is not working, however if i will create the workflow just to sent mails on the start date then that would work fine.

答:
I don't see anything in these steps that would send an email 3 days before the start date.  This workflow calculates a reminder date 3 days before the start date, but then the next step only sends the email if the Start Date is before the Reminder Date -- since the Reminder date is always 3 days before Start Date, Start Date will Never be before Reminder Date, thus the email will not be send.

I think you need to add a step before the Send Emails step that says if Reminder Date is greater than Today, then use a Pause until Date to pause until the Reminder Date.  Then you can remove the second conditional in the Email step so that all you are checking is the Status before sending the email.


问:
What is the "right" JSON date format?
I've seen so many different standards for the JSON date format:

```<code>"\"\\/Date(1335205592410)\\/\""         .NET JavaScriptSerializer
"\"\\/Date(1335205592410-0500)\\/\""    .NET DataContractJsonSerializer
"2012-04-23T18:25:43.511Z"              JavaScript built-in JSON object
"2012-04-21T18:25:43-05:00"             ISO 8601
</code>```

Which one is the right one? Or best? Is there any sort of standard on this?

答:
"2014-01-01T23:28:56.782Z"

The date is represented in a standard and sortable format that represents a UTC time (indicated by the Z). ISO 8601 also supports time zones by replacing the Z with + or – value for the timezone offset:

"2014-02-01T09:28:56.321-10:00"

There are other variations of the timezone encoding in the ISO 8601 spec, but the –10:00 format is the only TZ format that current JSON parsers support. In general it’s best to use the UTC based format (Z) unless you have a specific need for figuring out the time zone in which the date was produced (possible only in server side generation).

NB:

```<code>    var date = new Date();
    console.log(date); // Wed Jan 01 2014 13:28:56 GMT-
    1000 (Hawaiian Standard Time)

    var json = JSON.stringify(date);
    console.log(json);  // "2014-01-01T23:28:56.782Z"
</code>```

To tell you that's the preferred way even though JavaScript doesn't have a standard format for it

```<code>// JSON encoded date
var json = "\"2014-01-01T23:28:56.782Z\"";

var dateStr = JSON.parse(json);
console.log(dateStr); // 2014-01-01T23:28:56.782Z
</code>```

Title: What is the "right" JSON date format?

Body:
I've seen so many different standards for the JSON date format:

"\"\\/Date(1335205592410)\\/\""         .NET JavaScriptSerializer
"\"\\/Date(1335205592410-0500)\\/\""    .NET DataContractJsonSerializer
"2012-04-23T18:25:43.511Z"              JavaScript built-in JSON object
"2012-04-21T18:25:43-05:00"             ISO 8601

Which one is the right one? Or best? Is there any sort of standard on this?

Body:
"2014-01-01T23:28:56.782Z"

The date is represented in a standard and sortable format that represents a UTC time (indicated by the Z). ISO 8601 also supports time zones by replacing the Z with + or – value for the timezone offset:

"2014-02-01T09:28:56.321-10:00"

There are other variations of the timezone encoding in the ISO 8601 spec, but the –10:00 format is the only TZ format that current JSON parsers support. In general it’s best to use the UTC based format (Z) unless you have a specific need for figuring out the time zone in which the date was produced (possible only in server side generation).

NB:

    var date = new Date();
    console.log(date); // Wed Jan 01 2014 13:28:56 GMT-
    1000 (Hawaiian Standard Time)

    var json = JSON.stringify(date);
    console.log(json);  // "2014-01-01T23:28:56.782Z"

To tell you that's the preferred way even though JavaScript doesn't have a standard format for it

// JSON encoded date
var json = "\"2014-01-01T23:28:56.782Z\"";

var dateStr = JSON.parse(json);
console.log(dateStr); // 2014-01-01T23:28:56.782Z


问:
Conversion to Dalvik format failed: Unable to execute dex: Java heap space
I have added a 2.45mb jar file to my Android eclipse project and now I continue to get "Conversion to Dalvik format failed: Unable to execute dex: Java heap space" no matter what I do.

I have researched online, and was informed to update my eclipse.ini to increase my Java VM heapsizes. I have done this for all the values in eclipse.ini and I continue to get the build error.

Any ideas?

答:
Modify the -XmsAm and -XmxBm paremeters in eclipse.ini so that they are large enough. The default is -Xms40m -Xmx384m. Try changing them both to -Xms512m -Xmx512m and restart eclipse to see if that helps. If not, continue to increase the values and restart eclipse until either one of two things happens:

Your build completes.

Eclipse won't restart because you don't have enough memory.

eclipse.ini is located at /etc/eclipse.ini in Ubuntu (assuming you installed Eclipse from the Ubuntu repositories).

For MAC please see:

Finding eclipse.ini is a wee bit tricky. To locate it, right-click on the Eclipse Application icon and select "Show Package Contents", then double-click on the "Contents" folder and then double-click on the "MacOS" folder, the home of eclipse.ini

https://confluence.sakaiproject.org/pages/viewpage.action?pageId=61341742


问:
What is wrong with how I'm dynamically allocating space for this 2d array?
I'm trying to create a 2D array that will store be able to store each character of a .txt file as an element in the 2D array.

How do I dynamically allocate space for it?

This what I've done so far to malloc it. (this was copied of GeeksForGeeks)

```<code>char *arr[rownum2];

for (i = 0; i < rownum2; i++) {
    arr[i] = (char *)malloc(colnum * sizeof(char));
</code>```

However, I think this is the source of serious memory related issues later on in my program, and I've also been told some parts of this are unnecessary.

Can I please get the most suitable way to dynamically allocate memory for the 2D array in this specific scenario?

答:
Technically, it's not a 2D array, but an array of arrays. The difference is, you can't make 2D array with lines of different size, but you can do it with your array of arrays.

If you don't need it, you can allocate rownum2*colnum elements and access each element as arr[x+colnum*y] (it's used often because all data are kept in one place, decreasing CPU cache load and some system inner needs for storing each pointer of each allocated chunk).

Also, even array of lines of different sizes can be placed into 1D array and accessed like 2D (at least, if they do not change size or even RO). You can allocate char body[total_size], read the whole array, allocate char* arr[rownum2] and set each arr[i]=body+line_beginning_offset.

BTW don't forget there are not actual C strings because they are not null-terminated. You'll need an additional column for null-term. If you store ASCII art, 2D array is a very good solution.

Body:
I'm trying to create a 2D array that will store be able to store each character of a .txt file as an element in the 2D array.

How do I dynamically allocate space for it?

This what I've done so far to malloc it. (this was copied of GeeksForGeeks)

char *arr[rownum2];

for (i = 0; i < rownum2; i++) {
    arr[i] = (char *)malloc(colnum * sizeof(char));

However, I think this is the source of serious memory related issues later on in my program, and I've also been told some parts of this are unnecessary.

Can I please get the most suitable way to dynamically allocate memory for the 2D array in this specific scenario?


问:
Unable to find a suitable main class, please add a 'mainClass' property, Spring boot
Hi friends i am developing a spring boot maven based project and and i have created a maven submodules but when i try to run my project it gives an error

```<code>[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.2.5.RELEASE:run (default-cli) on project demo-jhipster: Unable to find a suitable main class, please add a 'mainClass' property -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.2.5.RELEASE:run (default-cli) on project demo-jhipster: Unable to find a suitable main class, please add a 'mainClass' property
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:216)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
        at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:120)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:355)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:155)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:584)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:216)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:160)
</code>```

my parent pom and child pom is

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>1.2.5.RELEASE</version>
        <relativePath />
    </parent>

    <groupId>com.aquevix.demo</groupId>
    <artifactId>demo-jhipster</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>

    <name>demo_jhipster</name>

    <prerequisites>
        <maven>3.0.0</maven>
    </prerequisites>
    <modules>
        <module>JhipsterSubmodule</module>
    </modules>

    <properties>
        <assertj-core.version>3.1.0</assertj-core.version>
        <awaitility.version>1.4.0</awaitility.version>
        <commons-io.version>2.4</commons-io.version>
        <commons-lang.version>2.6</commons-lang.version>
        <gatling-maven-plugin.version>2.1.6</gatling-maven-plugin.version>
        <gatling.version>2.1.6</gatling.version>
        <hibernate.version>4.3.10.Final</hibernate.version>
        <hikaricp.version>2.4.0</hikaricp.version>
        <jacoco-maven-plugin.version>0.7.4.201502262128</jacoco-maven-plugin.version>
        <java.version>1.8</java.version>
        <javax.inject.version>1</javax.inject.version>
        <joda-time-hibernate.version>1.4</joda-time-hibernate.version>
        <liquibase-hibernate4.version>3.5</liquibase-hibernate4.version>
        <liquibase-slf4j.version>1.2.1</liquibase-slf4j.version>
        <liquibase.version>3.4.1</liquibase.version>
        <mapstruct.version>1.0.0.CR1</mapstruct.version>
        <maven-enforcer-plugin.version>1.3.1</maven-enforcer-plugin.version>
        <maven-sortpom-plugin.version>2.3.0</maven-sortpom-plugin.version>
        <maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>
        <metrics-spark-reporter.version>1.2</metrics-spark-reporter.version>
        <metrics-spring.version>3.1.2</metrics-spring.version>
        <!-- Sonar properties -->
        <project.testresult.directory>${project.build.directory}/test-results</project.testresult.directory>
        <run.addResources>false</run.addResources>
        <sonar-maven-plugin.version>2.6</sonar-maven-plugin.version>
        <sonar.exclusions>src/main/webapp/assets/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/dist/**/*.*</sonar.exclusions>
        <sonar.jacoco.itReportPath>${project.testresult.directory}/coverage/jacoco/jacoco-it.exec</sonar.jacoco.itReportPath>
        <sonar.jacoco.reportPath>${project.testresult.directory}/coverage/jacoco/jacoco.exec</sonar.jacoco.reportPath>
        <sonar.java.codeCoveragePlugin>jacoco</sonar.java.codeCoveragePlugin>

        <sonar.javascript.jstestdriver.reportsPath>${project.testresult.directory}/karma</sonar.javascript.jstestdriver.reportsPath>
        <sonar.javascript.lcov.reportPath>${project.testresult.directory}/coverage/report-lcov/lcov.info</sonar.javascript.lcov.reportPath>

        <sonar.sources>${project.basedir}/src/main/</sonar.sources>
        <sonar.surefire.reportsPath>${project.testresult.directory}/surefire-reports</sonar.surefire.reportsPath>
        <sonar.tests>${project.basedir}/src/test/</sonar.tests>
        <spring-security.version>4.0.2.RELEASE</spring-security.version>
        <springfox.version>2.0.3</springfox.version>
        <usertype-core.version>4.0.0.GA</usertype-core.version>

    </properties>

    <dependencies>
        // dependencies..
    </dependencies>
    <build>
        <resources>
            <resource>
                <filtering>true</filtering>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <filtering>false</filtering>
                <directory>src/main/resources</directory>
                <excludes>
                    <exclude>**/*.xml</exclude>
                </excludes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>com.google.code.sortpom</groupId>
                <artifactId>maven-sortpom-plugin</artifactId>
                <version>${maven-sortpom-plugin.version}</version>
                <executions>
                    <execution>
                        <phase>verify</phase>
                        <goals>
                            <goal>sort</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <sortProperties>true</sortProperties>
                    <nrOfIndentSpace>4</nrOfIndentSpace>
                    <sortDependencies>groupId,artifactId</sortDependencies>
                    <sortPlugins>groupId,artifactId</sortPlugins>
                    <keepBlankLines>true</keepBlankLines>
                    <expandEmptyElements>false</expandEmptyElements>
                </configuration>
            </plugin>
            <plugin>
                <groupId>io.gatling</groupId>
                <artifactId>gatling-maven-plugin</artifactId>
                <version>${gatling-maven-plugin.version}</version>
                <configuration>
                    <configFolder>src/test/gatling/conf</configFolder>
                    <dataFolder>src/test/gatling/data</dataFolder>
                    <resultsFolder>target/gatling/results</resultsFolder>
                    <bodiesFolder>src/test/gatling/bodies</bodiesFolder>
                    <simulationsFolder>src/test/gatling/simulations</simulationsFolder>
                    <!-- This will force Gatling to ask which simulation to run
                      This is useful when you have multiple simulations -->
                    <simulationClass>*</simulationClass>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <configuration>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-enforcer-plugin</artifactId>
                <version>${maven-enforcer-plugin.version}</version>
                <executions>
                    <execution>
                        <id>enforce-versions</id>
                        <goals>
                            <goal>enforce</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <rules>
                        <requireMavenVersion>
                            <message>You are running an older version of Maven. JHipster requires at least Maven 3.0</message>
                            <version>[3.0.0,)</version>
                        </requireMavenVersion>
                        <requireJavaVersion>
                            <message>You are running an older version of Java. JHipster requires at least JDK ${java.version}</message>
                            <version>[${java.version}.0,)</version>
                        </requireJavaVersion>
                    </rules>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <argLine>-Xmx256m ${surefireArgLine}</argLine>
                    <!-- Force alphabetical order to have a reproducible build -->
                    <runOrder>alphabetical</runOrder>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <packagingExcludes>WEB-INF/lib/tomcat-*.jar</packagingExcludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.bsc.maven</groupId>
                <artifactId>maven-processor-plugin</artifactId>
                <version>2.2.4</version>
                <executions>
                    <execution>
                        <id>process</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>process</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>org.mapstruct</groupId>
                        <artifactId>mapstruct-processor</artifactId>
                        <version>${mapstruct.version}</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <defaultOutputDirectory>${project.build.directory}/generated-sources</defaultOutputDirectory>
                    <processors>
                        <processor>org.mapstruct.ap.MappingProcessor</processor>
                    </processors>
                    <options>
                        <mapstruct.suppressGeneratorTimestamp>true</mapstruct.suppressGeneratorTimestamp>
                        <mapstruct.defaultComponentModel>spring</mapstruct.defaultComponentModel>
                    </options>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>sonar-maven-plugin</artifactId>
                <version>${sonar-maven-plugin.version}</version>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>${jacoco-maven-plugin.version}</version>
                <executions>
                    <execution>
                        <id>pre-unit-tests</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <!-- Sets the path to the file which contains the execution data. -->
                            <destFile>${project.testresult.directory}/coverage/jacoco/jacoco.exec</destFile>
                            <!-- Sets the name of the property containing the settings for JaCoCo runtime agent. -->
                            <propertyName>surefireArgLine</propertyName>
                        </configuration>
                    </execution>
                    <!-- Ensures that the code coverage report for unit tests is created after unit tests have been run -->
                    <execution>
                        <id>post-unit-test</id>
                        <phase>test</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                        <configuration>
                            <dataFile>${project.testresult.directory}/coverage/jacoco/jacoco.exec</dataFile>
                            <outputDirectory>${project.testresult.directory}/coverage/jacoco</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.liquibase</groupId>
                <artifactId>liquibase-maven-plugin</artifactId>
                <version>${liquibase.version}</version>
                <dependencies>
                    <dependency>
                        <groupId>org.javassist</groupId>
                        <artifactId>javassist</artifactId>
                        <version>3.18.2-GA</version>
                    </dependency>
                    <dependency>
                        <groupId>org.liquibase.ext</groupId>
                        <artifactId>liquibase-hibernate4</artifactId>
                        <version>${liquibase-hibernate4.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-data-jpa</artifactId>
                        <version>${project.parent.version}</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <changeLogFile>src/main/resources/config/liquibase/master.xml</changeLogFile>
                    <diffChangeLogFile>src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml</diffChangeLogFile>
                    <driver />
                    <url />
                    <defaultSchemaName />
                    <username />
                    <password />
                    <referenceUrl>hibernate:spring:com.aquevix.demo.domain?dialect=</referenceUrl>
                    <verbose>true</verbose>
                    <logging>debug</logging>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <jvmArguments>-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005</jvmArguments>
                    <arguments>
                        <argument>--spring.profiles.active=dev</argument>
                    </arguments>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>dev</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <!-- log configuration -->
                <logback.loglevel>DEBUG</logback.loglevel>
            </properties>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </dependency>
            </dependencies>
        </profile>
        <profile>
            <id>fast</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-maven-plugin</artifactId>
                        <configuration>
                            <arguments>
                                <argument>--spring.profiles.active=dev,fast</argument>
                            </arguments>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
            <properties>
                <!-- log configuration -->
                <logback.loglevel>DEBUG</logback.loglevel>
            </properties>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-undertow</artifactId>
                </dependency>
            </dependencies>
        </profile>
        <profile>
            <id>prod</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>com.github.trecloux</groupId>
                        <artifactId>yeoman-maven-plugin</artifactId>
                        <version>0.4</version>
                        <executions>
                            <execution>
                                <id>run-frontend-build</id>
                                <phase>generate-resources</phase>
                                <goals>
                                    <goal>build</goal>
                                </goals>
                                <configuration>
                                    <buildTool>grunt</buildTool>
                                    <buildArgs>build --force --no-color</buildArgs>
                                </configuration>
                            </execution>
                        </executions>
                        <configuration>
                            <yeomanProjectDirectory>${project.basedir}</yeomanProjectDirectory>
                        </configuration>
                    </plugin>
                    <plugin>
                        <artifactId>maven-clean-plugin</artifactId>
                        <version>2.5</version>
                        <configuration>
                            <filesets>
                                <fileset>                                       <directory>src/main/webapp/dist</directory>
                                </fileset>
                                <fileset>
                                    <directory>.tmp</directory>
                                </fileset>
                                <fileset>
                                    <directory>node_modules</directory>
                                </fileset>
                            </filesets>
                        </configuration>
                    </plugin>
                    <plugin>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-maven-plugin</artifactId>
                        <configuration>
                            <arguments>
                                <argument>--spring.profiles.active=prod</argument>
                            </arguments>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
            <properties>
                <!-- log configuration -->
                <logback.loglevel>INFO</logback.loglevel>
            </properties>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </dependency>
            </dependencies>
        </profile>
    </profiles>
</project>
</code>```

and chile pom is

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>demo-jhipster</artifactId>
        <groupId>com.aquevix.demo</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>JhipsterSubmodule1</artifactId>
</project>
</code>```

I have googled but not found any solution please help in this regard!

答:
If you don't want to create a fat jar, you can add follow lines in your pom.xml:</p>

```<code><properties>
    <spring-boot.repackage.skip>true</spring-boot.repackage.skip>
</properties>
</code>```

Body:
Hi friends i am developing a spring boot maven based project and and i have created a maven submodules but when i try to run my project it gives an error

[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.2.5.RELEASE:run (default-cli) on project demo-jhipster: Unable to find a suitable main class, please add a 'mainClass' property -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.2.5.RELEASE:run (default-cli) on project demo-jhipster: Unable to find a suitable main class, please add a 'mainClass' property
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:216)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
        at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:120)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:355)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:155)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:584)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:216)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:160)

my parent pom and child pom is

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>1.2.5.RELEASE</version>
        <relativePath />
    </parent>

    <groupId>com.aquevix.demo</groupId>
    <artifactId>demo-jhipster</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>

    <name>demo_jhipster</name>

    <prerequisites>
        <maven>3.0.0</maven>
    </prerequisites>
    <modules>
        <module>JhipsterSubmodule</module>
    </modules>

    <properties>
        <assertj-core.version>3.1.0</assertj-core.version>
        <awaitility.version>1.4.0</awaitility.version>
        <commons-io.version>2.4</commons-io.version>
        <commons-lang.version>2.6</commons-lang.version>
        <gatling-maven-plugin.version>2.1.6</gatling-maven-plugin.version>
        <gatling.version>2.1.6</gatling.version>
        <hibernate.version>4.3.10.Final</hibernate.version>
        <hikaricp.version>2.4.0</hikaricp.version>
        <jacoco-maven-plugin.version>0.7.4.201502262128</jacoco-maven-plugin.version>
        <java.version>1.8</java.version>
        <javax.inject.version>1</javax.inject.version>
        <joda-time-hibernate.version>1.4</joda-time-hibernate.version>
        <liquibase-hibernate4.version>3.5</liquibase-hibernate4.version>
        <liquibase-slf4j.version>1.2.1</liquibase-slf4j.version>
        <liquibase.version>3.4.1</liquibase.version>
        <mapstruct.version>1.0.0.CR1</mapstruct.version>
        <maven-enforcer-plugin.version>1.3.1</maven-enforcer-plugin.version>
        <maven-sortpom-plugin.version>2.3.0</maven-sortpom-plugin.version>
        <maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>
        <metrics-spark-reporter.version>1.2</metrics-spark-reporter.version>
        <metrics-spring.version>3.1.2</metrics-spring.version>

        <project.testresult.directory>${project.build.directory}/test-results</project.testresult.directory>
        <run.addResources>false</run.addResources>
        <sonar-maven-plugin.version>2.6</sonar-maven-plugin.version>
        <sonar.exclusions>src/main/webapp/assets/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/dist/**/*.*</sonar.exclusions>
        <sonar.jacoco.itReportPath>${project.testresult.directory}/coverage/jacoco/jacoco-it.exec</sonar.jacoco.itReportPath>
        <sonar.jacoco.reportPath>${project.testresult.directory}/coverage/jacoco/jacoco.exec</sonar.jacoco.reportPath>
        <sonar.java.codeCoveragePlugin>jacoco</sonar.java.codeCoveragePlugin>

        <sonar.javascript.jstestdriver.reportsPath>${project.testresult.directory}/karma</sonar.javascript.jstestdriver.reportsPath>
        <sonar.javascript.lcov.reportPath>${project.testresult.directory}/coverage/report-lcov/lcov.info</sonar.javascript.lcov.reportPath>

        <sonar.sources>${project.basedir}/src/main/</sonar.sources>
        <sonar.surefire.reportsPath>${project.testresult.directory}/surefire-reports</sonar.surefire.reportsPath>
        <sonar.tests>${project.basedir}/src/test/</sonar.tests>
        <spring-security.version>4.0.2.RELEASE</spring-security.version>
        <springfox.version>2.0.3</springfox.version>
        <usertype-core.version>4.0.0.GA</usertype-core.version>

    </properties>

    <dependencies>
        // dependencies..
    </dependencies>
    <build>
        <resources>
            <resource>
                <filtering>true</filtering>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <filtering>false</filtering>
                <directory>src/main/resources</directory>
                <excludes>
                    <exclude>**/*.xml</exclude>
                </excludes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>com.google.code.sortpom</groupId>
                <artifactId>maven-sortpom-plugin</artifactId>
                <version>${maven-sortpom-plugin.version}</version>
                <executions>
                    <execution>
                        <phase>verify</phase>
                        <goals>
                            <goal>sort</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <sortProperties>true</sortProperties>
                    <nrOfIndentSpace>4</nrOfIndentSpace>
                    <sortDependencies>groupId,artifactId</sortDependencies>
                    <sortPlugins>groupId,artifactId</sortPlugins>
                    <keepBlankLines>true</keepBlankLines>
                    <expandEmptyElements>false</expandEmptyElements>
                </configuration>
            </plugin>
            <plugin>
                <groupId>io.gatling</groupId>
                <artifactId>gatling-maven-plugin</artifactId>
                <version>${gatling-maven-plugin.version}</version>
                <configuration>
                    <configFolder>src/test/gatling/conf</configFolder>
                    <dataFolder>src/test/gatling/data</dataFolder>
                    <resultsFolder>target/gatling/results</resultsFolder>
                    <bodiesFolder>src/test/gatling/bodies</bodiesFolder>
                    <simulationsFolder>src/test/gatling/simulations</simulationsFolder>

                    <simulationClass>*</simulationClass>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <configuration>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-enforcer-plugin</artifactId>
                <version>${maven-enforcer-plugin.version}</version>
                <executions>
                    <execution>
                        <id>enforce-versions</id>
                        <goals>
                            <goal>enforce</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <rules>
                        <requireMavenVersion>
                            <message>You are running an older version of Maven. JHipster requires at least Maven 3.0</message>
                            <version>[3.0.0,)</version>
                        </requireMavenVersion>
                        <requireJavaVersion>
                            <message>You are running an older version of Java. JHipster requires at least JDK ${java.version}</message>
                            <version>[${java.version}.0,)</version>
                        </requireJavaVersion>
                    </rules>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <argLine>-Xmx256m ${surefireArgLine}</argLine>

                    <runOrder>alphabetical</runOrder>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <packagingExcludes>WEB-INF/lib/tomcat-*.jar</packagingExcludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.bsc.maven</groupId>
                <artifactId>maven-processor-plugin</artifactId>
                <version>2.2.4</version>
                <executions>
                    <execution>
                        <id>process</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>process</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>org.mapstruct</groupId>
                        <artifactId>mapstruct-processor</artifactId>
                        <version>${mapstruct.version}</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <defaultOutputDirectory>${project.build.directory}/generated-sources</defaultOutputDirectory>
                    <processors>
                        <processor>org.mapstruct.ap.MappingProcessor</processor>
                    </processors>
                    <options>
                        <mapstruct.suppressGeneratorTimestamp>true</mapstruct.suppressGeneratorTimestamp>
                        <mapstruct.defaultComponentModel>spring</mapstruct.defaultComponentModel>
                    </options>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>sonar-maven-plugin</artifactId>
                <version>${sonar-maven-plugin.version}</version>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>${jacoco-maven-plugin.version}</version>
                <executions>
                    <execution>
                        <id>pre-unit-tests</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>

                            <destFile>${project.testresult.directory}/coverage/jacoco/jacoco.exec</destFile>

                            <propertyName>surefireArgLine</propertyName>
                        </configuration>
                    </execution>

                    <execution>
                        <id>post-unit-test</id>
                        <phase>test</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                        <configuration>
                            <dataFile>${project.testresult.directory}/coverage/jacoco/jacoco.exec</dataFile>
                            <outputDirectory>${project.testresult.directory}/coverage/jacoco</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.liquibase</groupId>
                <artifactId>liquibase-maven-plugin</artifactId>
                <version>${liquibase.version}</version>
                <dependencies>
                    <dependency>
                        <groupId>org.javassist</groupId>
                        <artifactId>javassist</artifactId>
                        <version>3.18.2-GA</version>
                    </dependency>
                    <dependency>
                        <groupId>org.liquibase.ext</groupId>
                        <artifactId>liquibase-hibernate4</artifactId>
                        <version>${liquibase-hibernate4.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-data-jpa</artifactId>
                        <version>${project.parent.version}</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <changeLogFile>src/main/resources/config/liquibase/master.xml</changeLogFile>
                    <diffChangeLogFile>src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml</diffChangeLogFile>
                    <driver />
                    <url />
                    <defaultSchemaName />
                    <username />
                    <password />
                    <referenceUrl>hibernate:spring:com.aquevix.demo.domain?dialect=</referenceUrl>
                    <verbose>true</verbose>
                    <logging>debug</logging>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <jvmArguments>-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005</jvmArguments>
                    <arguments>
                        <argument>--spring.profiles.active=dev</argument>
                    </arguments>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>dev</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>

                <logback.loglevel>DEBUG</logback.loglevel>
            </properties>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </dependency>
            </dependencies>
        </profile>
        <profile>
            <id>fast</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-maven-plugin</artifactId>
                        <configuration>
                            <arguments>
                                <argument>--spring.profiles.active=dev,fast</argument>
                            </arguments>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
            <properties>

                <logback.loglevel>DEBUG</logback.loglevel>
            </properties>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-undertow</artifactId>
                </dependency>
            </dependencies>
        </profile>
        <profile>
            <id>prod</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>com.github.trecloux</groupId>
                        <artifactId>yeoman-maven-plugin</artifactId>
                        <version>0.4</version>
                        <executions>
                            <execution>
                                <id>run-frontend-build</id>
                                <phase>generate-resources</phase>
                                <goals>
                                    <goal>build</goal>
                                </goals>
                                <configuration>
                                    <buildTool>grunt</buildTool>
                                    <buildArgs>build --force --no-color</buildArgs>
                                </configuration>
                            </execution>
                        </executions>
                        <configuration>
                            <yeomanProjectDirectory>${project.basedir}</yeomanProjectDirectory>
                        </configuration>
                    </plugin>
                    <plugin>
                        <artifactId>maven-clean-plugin</artifactId>
                        <version>2.5</version>
                        <configuration>
                            <filesets>
                                <fileset>                                       <directory>src/main/webapp/dist</directory>
                                </fileset>
                                <fileset>
                                    <directory>.tmp</directory>
                                </fileset>
                                <fileset>
                                    <directory>node_modules</directory>
                                </fileset>
                            </filesets>
                        </configuration>
                    </plugin>
                    <plugin>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-maven-plugin</artifactId>
                        <configuration>
                            <arguments>
                                <argument>--spring.profiles.active=prod</argument>
                            </arguments>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
            <properties>

                <logback.loglevel>INFO</logback.loglevel>
            </properties>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </dependency>
            </dependencies>
        </profile>
    </profiles>
</project>

and chile pom is

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>demo-jhipster</artifactId>
        <groupId>com.aquevix.demo</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>JhipsterSubmodule1</artifactId>
</project>

I have googled but not found any solution please help in this regard!

Body:
If you don't want to create a fat jar, you can add follow lines in your pom.xml:

<properties>
    <spring-boot.repackage.skip>true</spring-boot.repackage.skip>
</properties>


问:
messaging.onMessage (web use case) never gets invoked
I am able to consume web notifications fine for the setBackgroundMessageHandler use case without issue.

However when I try to consume notifications when my chrome browser tab is selected/active, the messaging.onMessage is never called.

The server is always sending the message:

```<code>{"multicast_id":*********,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:*********"}]}
</code>```

Chrome version: Version 79.0.3945.130 (Official Build) (64-bit)

Here is how I am configuring firebase in my page:

```<code>var messaging;

var config = {
    apiKey: "*************",
    authDomain: "*************",
    databaseURL: "*************",
    projectId: "*************",
    storageBucket: "*************",
    messagingSenderId: "*************",
    appId: "*************"
};
firebase.initializeApp(config);
messaging = firebase.messaging();
if (firebase.messaging.isSupported()) {
    console.log('Messaging supported!!!!');//excutes, so messenging supported
    messaging.onMessage(function (payload) {
        console.log('Message received. ', payload);//never invoked :(
    });
}
</code>```

And for completeness, firebase-messeging-sw.js which is working well:

```<code>self.addEventListener('notificationclick', function(event) {
    ...
    ...
}
importScripts('https://www.gstatic.com/firebasejs/7.8.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.8.2/firebase-messaging.js');

firebase.initializeApp({
  'messagingSenderId': "*************",
  'apiKey': "*************",
  'projectId': "*************",
  'appId': "*************",
  'authDomain': "*************",
  'storageBucket' :"*************"
  });

const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function(payload) {
    //gets called :)
});
</code>```

Any ideas or debugging hints?

答: Figured it out, my firebase library versions were different between client and firebase-messenging-sw.js </p>

Body:
I am able to consume web notifications fine for the setBackgroundMessageHandler use case without issue.

However when I try to consume notifications when my chrome browser tab is selected/active, the messaging.onMessage is never called.

The server is always sending the message:

{"multicast_id":*********,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:*********"}]}

Chrome version: Version 79.0.3945.130 (Official Build) (64-bit)

Here is how I am configuring firebase in my page:

var messaging;

var config = {
    apiKey: "*************",
    authDomain: "*************",
    databaseURL: "*************",
    projectId: "*************",
    storageBucket: "*************",
    messagingSenderId: "*************",
    appId: "*************"
};
firebase.initializeApp(config);
messaging = firebase.messaging();
if (firebase.messaging.isSupported()) {
    console.log('Messaging supported!!!!');//excutes, so messenging supported
    messaging.onMessage(function (payload) {
        console.log('Message received. ', payload);//never invoked :(
    });
}

And for completeness, firebase-messeging-sw.js which is working well:

self.addEventListener('notificationclick', function(event) {
    ...
    ...
}
importScripts('https://www.gstatic.com/firebasejs/7.8.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.8.2/firebase-messaging.js');

firebase.initializeApp({
  'messagingSenderId': "*************",
  'apiKey': "*************",
  'projectId': "*************",
  'appId': "*************",
  'authDomain': "*************",
  'storageBucket' :"*************"
  });

const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function(payload) {
    //gets called :)
});

Any ideas or debugging hints?


问:
Creating a file stream for a HTTP file
I need to create a file stream directly at a server location using an URL. Something like

```<code>fs = new FileStream("http://SiteName.in/abc/xyz/pqr.pdf", FileMode.Create);
</code>```

but its giving me this exception:

URI formats are not supported

I tried it with many other options but not providing satisfactory result.

答:
You can simply download your file into Stream

```<code>public static Stream DownloadFile(string TargetFile)
{
    WebClient MyWebClient = new WebClient();
    byte[] BytesFile = MyWebClient.DownloadData(TargetFile);

    MemoryStream iStream = new MemoryStream(BytesFile);

    return iStream;
}
</code>```

Title: Creating a file stream for a HTTP file

Body:
I need to create a file stream directly at a server location using an URL. Something like

fs = new FileStream("http://SiteName.in/abc/xyz/pqr.pdf", FileMode.Create);

but its giving me this exception:

URI formats are not supported

I tried it with many other options but not providing satisfactory result.

Body:
You can simply download your file into Stream

public static Stream DownloadFile(string TargetFile)
{
    WebClient MyWebClient = new WebClient();
    byte[] BytesFile = MyWebClient.DownloadData(TargetFile);

    MemoryStream iStream = new MemoryStream(BytesFile);

    return iStream;
}


问:
Two identical queries returning two different values. C# .Net Core EF Core
Scenario

This is for a discord bot using the DSharp library. Now in this instance, when I chat a command on discord as !status testmenu the context's content will be !status testmenu. So in order to isolate the command and prefix from the message body I am creating a new string message which holds only the message body(testmenu) as shown in this line.

```<code> string message = context.Message.Content.Replace(context.Message.Content.Substring(0, (context.Command.Name.Length + 1)), string.Empty);
</code>```

However simultaneously, the parameter content also returns just the message body alone. So right before the if condition both content and message are equal, including case sensitivity wise as well.

So both message and content both have a string value of testmenu.

Reason for duplicates: Controlled testing.

Problem

When I query the database with the first string, message I get a null return.
However when I query the database with the second string content (from the parameter) I get the appropriate record returned. However bear in mind, again, both message and content are identical strings, case sensitivity included.

I tried swapping the query statements between each other just to ensure it wasn't a sequential error and it was not. It's the same result each time. The query with the parameter string always returns a value while the query with the message string returns null. And yes I have indeed put a break point right before the "if" statement just to ensure the message string isn't null and it was not. It had the same value as context.

```<code>    [Command("status")]
    public async Task Status(CommandContext context, string content)
    {
        string message = context.Message.Content.Replace(context.Message.Content.Substring(0, (context.Command.Name.Length + 1)), string.Empty);
        Models.Menu SelectedMenu;

        if (!String.IsNullOrEmpty(message))
        {
           //returns null
            SelectedMenu = await _context.Menus.FirstOrDefaultAsync(m => m.Menu_Name.ToLower().Contains(message)).ConfigureAwait(false);

        }

        //returns appropriate record
        var menu = await _context.Menus.FirstOrDefaultAsync(m => m.Menu_Name.ToLower().Contains(context.Message.Content)).ConfigureAwait(false);
        await context.Channel.SendMessageAsync(menu.Status.ToString()).ConfigureAwait(false);
    }
</code>```

答:
This was a silly mistake however at first glance, not so noticeable.

string message = context.Message.Content.Replace(context.Message.Content.Substring(0, (context.Command.Name.Length + 1)), string.Empty);

context.Message.Content, of which "Content" has a value "!status testmenu"

context.Command.Name has a value of "status" and I am adding + 1 to the substring to remove the initial "!" as well. So now the string has a value " testmenu"

As you can see here, I am not trimming this string, so there are still white spaces left at the beginning.

To the human eye in visual studio, when you hover your mouse while debugging, over the variables they may seem identical but it's not the case since there was indeed a white space at the beginning, hence why I was receiving a null value when I tried to query the data.

Once I trimmed the string and ran the query everything worked as it should.

Body:
Scenario

This is for a discord bot using the DSharp library. Now in this instance, when I chat a command on discord as !status testmenu the context's content will be !status testmenu. So in order to isolate the command and prefix from the message body I am creating a new string message which holds only the message body(testmenu) as shown in this line.

 string message = context.Message.Content.Replace(context.Message.Content.Substring(0, (context.Command.Name.Length + 1)), string.Empty);

However simultaneously, the parameter content also returns just the message body alone. So right before the if condition both content and message are equal, including case sensitivity wise as well.

So both message and content both have a string value of testmenu.

Reason for duplicates: Controlled testing.

Problem

When I query the database with the first string, message I get a null return.
However when I query the database with the second string content (from the parameter) I get the appropriate record returned. However bear in mind, again, both message and content are identical strings, case sensitivity included.

I tried swapping the query statements between each other just to ensure it wasn't a sequential error and it was not. It's the same result each time. The query with the parameter string always returns a value while the query with the message string returns null. And yes I have indeed put a break point right before the "if" statement just to ensure the message string isn't null and it was not. It had the same value as context.

    [Command("status")]
    public async Task Status(CommandContext context, string content)
    {
        string message = context.Message.Content.Replace(context.Message.Content.Substring(0, (context.Command.Name.Length + 1)), string.Empty);
        Models.Menu SelectedMenu;

        if (!String.IsNullOrEmpty(message))
        {
           //returns null
            SelectedMenu = await _context.Menus.FirstOrDefaultAsync(m => m.Menu_Name.ToLower().Contains(message)).ConfigureAwait(false);

        }

        //returns appropriate record
        var menu = await _context.Menus.FirstOrDefaultAsync(m => m.Menu_Name.ToLower().Contains(context.Message.Content)).ConfigureAwait(false);
        await context.Channel.SendMessageAsync(menu.Status.ToString()).ConfigureAwait(false);
    }


问:
How does one get Browser (IE) toolbars in an HTA App?
I'm working on a web app that's embedded within an HTA.  Is it possible to enable browser toolbars so i can enable utilities like Development Toolbar, or IE8's built in Developer Tools?

I'm trying to do some firebug type things without using firebug or firebug lite and based on my googling it seems like it might not be possible!

Thank you!

答:
In short, no.  HTA is a wrapper for the core trident engine.

It does not have browser support (like dev tools).


问:
How to resolve KeyError: 'val_mean_absolute_error' Keras 2.3.1 and TensorFlow 2.0 From Chollet Deep Learning with Python
I am on section 3.7 of Chollet's book Deep Learning with Python.
The project is to find the median price of homes in a given Boston suburbs in the 1970's.

https://github.com/fchollet/deep-learning-with-python-notebooks/blob/master/3.7-predicting-house-prices.ipynb

At section "Validating our approach using K-fold validation" I try to run this block of code:

```<code>num_epochs = 500
all_mae_histories = []
for i in range(k):
    print('processing fold #', i)
    # Prepare the validation data: data from partition # k
    val_data = train_data[i * num_val_samples: (i + 1) * num_val_samples]
    val_targets = train_targets[i * num_val_samples: (i + 1) * num_val_samples]

    # Prepare the training data: data from all other partitions
    partial_train_data = np.concatenate(
        [train_data[:i * num_val_samples],
         train_data[(i + 1) * num_val_samples:]],
        axis=0)
    partial_train_targets = np.concatenate(
        [train_targets[:i * num_val_samples],
         train_targets[(i + 1) * num_val_samples:]],
        axis=0)

    # Build the Keras model (already compiled)
    model = build_model()
    # Train the model (in silent mode, verbose=0)
    history = model.fit(partial_train_data, partial_train_targets,
                        validation_data=(val_data, val_targets),
                        epochs=num_epochs, batch_size=1, verbose=0)
    mae_history = history.history['val_mean_absolute_error']
    all_mae_histories.append(mae_history)

</code>```

I get an error KeyError: 'val_mean_absolute_error'

```<code>mae_history = history.history['val_mean_absolute_error']
</code>```

I am guessing the solution is figure out the correct parameter to replace val_mean_absolute_error. I've tried looking into some Keras documentation for what would be the correct key value. Anyone know the correct key value?

答: I replaced 'val_mean_absolute_error' with 'val_mae' and it worked for me

Body:
I am on section 3.7 of Chollet's book Deep Learning with Python.
The project is to find the median price of homes in a given Boston suburbs in the 1970's.

https://github.com/fchollet/deep-learning-with-python-notebooks/blob/master/3.7-predicting-house-prices.ipynb

At section "Validating our approach using K-fold validation" I try to run this block of code:

num_epochs = 500
all_mae_histories = []
for i in range(k):
    print('processing fold #', i)
    # Prepare the validation data: data from partition # k
    val_data = train_data[i * num_val_samples: (i + 1) * num_val_samples]
    val_targets = train_targets[i * num_val_samples: (i + 1) * num_val_samples]

    # Prepare the training data: data from all other partitions
    partial_train_data = np.concatenate(
        [train_data[:i * num_val_samples],
         train_data[(i + 1) * num_val_samples:]],
        axis=0)
    partial_train_targets = np.concatenate(
        [train_targets[:i * num_val_samples],
         train_targets[(i + 1) * num_val_samples:]],
        axis=0)

    # Build the Keras model (already compiled)
    model = build_model()
    # Train the model (in silent mode, verbose=0)
    history = model.fit(partial_train_data, partial_train_targets,
                        validation_data=(val_data, val_targets),
                        epochs=num_epochs, batch_size=1, verbose=0)
    mae_history = history.history['val_mean_absolute_error']
    all_mae_histories.append(mae_history)

I get an error KeyError: 'val_mean_absolute_error'

mae_history = history.history['val_mean_absolute_error']

I am guessing the solution is figure out the correct parameter to replace val_mean_absolute_error. I've tried looking into some Keras documentation for what would be the correct key value. Anyone know the correct key value?


问:
java.net.UnknownHostException when attempting to connect to database
I am attempting to connect to an Oracle database through Java with the Oracle JDBC driver with the following code (obscuring the host, service, user, and password):

```<code>import java.sql.*;

public class Main {
    public Main () {
        try {
            String host = "HOST_NAME";
            String port = "1521";
            String service = "SERVICE_NAME";
            String user = "SCHEMA_USER";
            String password = "SCHEMA_PASSWORD";

            Class.forName("oracle.jdbc.driver.OracleDriver");

            Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=" +
                        host +
                        ")(PORT=" +
                        port +
                        ")))(CONNECT_DATA=(SERVICE_NAME=" +
                        service +
                        ")))",
                        user,
                        password);

            connection.close ();

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

    public static void main (String args) {
        new Main ();
    }
}
</code>```

However, I receive the following error:

java.sql.SQLException: IO Error: The Network Adapter could not establish the connection
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:458)
    at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:546)
    at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:236)
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:521)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at com.acxiom.axle.reporting.database.DatabaseConnection.connect(DatabaseConnection.java:23)
    at com.acxiom.axle.reporting.Reporting.establishDatabaseConnection(Reporting.java:53)
    at com.acxiom.axle.reporting.Reporting.beginReporting(Reporting.java:20)
    at com.acxiom.axle.reporting.Entry.<init>(Entry.java:28)
    at com.acxiom.axle.reporting.Entry.main(Entry.java:118)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
    at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:392)
    at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:434)
    at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:687)
    at oracle.net.ns.NSProtocol.connect(NSProtocol.java:247)
    at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1102)
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:320)
    ... 11 more
Caused by: java.net.UnknownHostException: null
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
    at java.net.InetAddress$2.lookupAllHostAddr(Unknown Source)
    at java.net.InetAddress.getAddressesFromNameService(Unknown Source)
    at java.net.InetAddress.getAllByName0(Unknown Source)
    at java.net.InetAddress.getAllByName(Unknown Source)
    at java.net.InetAddress.getAllByName(Unknown Source)
    at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:117)
    at oracle.net.nt.ConnOption.connect(ConnOption.java:133)
    at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:370)
    ... 16 more
```

The strange thing is, I can connect to the database from PL/SQL Developer, I can ping the remote host, and I can telnet to the remote host on port 1521.

Why would only Java appear to give an UnknownHostException, but I can connect and ping the host with other applications?

EDIT: I removed "hr/hr" from the connection string above. I have tried the connection as-is with it removed and still receive the same error. I've also tried changing the connection string to match the version morgano listed in his answer, with the same result. Finally, I tried to change the port number to a port I know it's not listening on, and it still receives the same error.

答:
The connection string is of the correct format.  The problem is that the host isn't set.  It's null, or perhaps the string "null".  There's simply no other way to generate the error message java.net.UnknownHostException: null

In your sample code, you write String host = "HOST_NAME";.  This makes it look like in your real code you are assigning a constant string to the variable host.  However, I'm going to stick my neck out and say that in your real code you are not doing this.  You are looking up the host name from somewhere, this lookup fails for some reason, you don't check this, and hence you pass a null value into the connection string.

Body:
I am attempting to connect to an Oracle database through Java with the Oracle JDBC driver with the following code (obscuring the host, service, user, and password):

import java.sql.*;

public class Main {
    public Main () {
        try {
            String host = "HOST_NAME";
            String port = "1521";
            String service = "SERVICE_NAME";
            String user = "SCHEMA_USER";
            String password = "SCHEMA_PASSWORD";

            Class.forName("oracle.jdbc.driver.OracleDriver");

            Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=" +
                        host +
                        ")(PORT=" +
                        port +
                        ")))(CONNECT_DATA=(SERVICE_NAME=" +
                        service +
                        ")))",
                        user,
                        password);

            connection.close ();

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

    public static void main (String args) {
        new Main ();
    }
}

However, I receive the following error:

java.sql.SQLException: IO Error: The Network Adapter could not establish the connection
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:458)
    at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:546)
    at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:236)
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:521)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at com.acxiom.axle.reporting.database.DatabaseConnection.connect(DatabaseConnection.java:23)
    at com.acxiom.axle.reporting.Reporting.establishDatabaseConnection(Reporting.java:53)
    at com.acxiom.axle.reporting.Reporting.beginReporting(Reporting.java:20)
    at com.acxiom.axle.reporting.Entry.<init>(Entry.java:28)
    at com.acxiom.axle.reporting.Entry.main(Entry.java:118)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
    at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:392)
    at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:434)
    at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:687)
    at oracle.net.ns.NSProtocol.connect(NSProtocol.java:247)
    at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1102)
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:320)
    ... 11 more
Caused by: java.net.UnknownHostException: null
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
    at java.net.InetAddress$2.lookupAllHostAddr(Unknown Source)
    at java.net.InetAddress.getAddressesFromNameService(Unknown Source)
    at java.net.InetAddress.getAllByName0(Unknown Source)
    at java.net.InetAddress.getAllByName(Unknown Source)
    at java.net.InetAddress.getAllByName(Unknown Source)
    at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:117)
    at oracle.net.nt.ConnOption.connect(ConnOption.java:133)
    at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:370)
    ... 16 more

The strange thing is, I can connect to the database from PL/SQL Developer, I can ping the remote host, and I can telnet to the remote host on port 1521.

Why would only Java appear to give an UnknownHostException, but I can connect and ping the host with other applications?

EDIT: I removed "hr/hr" from the connection string above. I have tried the connection as-is with it removed and still receive the same error. I've also tried changing the connection string to match the version morgano listed in his answer, with the same result. Finally, I tried to change the port number to a port I know it's not listening on, and it still receives the same error.


问:
PhpStorm isn't doing code completion with large file
I've just installed this library. PhpStorm does its usual code completion, except for the \XeroAPI\XeroPHP\Api\AccountingApi class. The \XeroAPI\XeroPHP\Api\IdentityApi class in the same folder works just fine.

The file is quite big - 2,560KB. If I delete roughly half of the 65,000 lines from the class (and it works whether it's the first half or the second half) then I get my code completion back. In fact, I can delete just the last 3,000 or so lines (getting the file down to 2,499KB) and it works.

I've also tried a quick regex find/replace to remove all the @throws PHPDoc comments. This got the file down to 2,491KB and hey presto, code completion works fine.

If I had to make a guess I'd say it's not doing code completion with source files over 2.5MB or something, but I can't find any setting for this.

Any way to get code completion going with this file short of deleting stuff from it (which will be restored next time I do a Composer update anyway)?

答:
Based on your info (especially the mentioned file size and the fact that it starts to work after reducing it) you have hit a limit of max file size that IDE is willing to parse and index.

Solution: configure idea.max.intellisense.filesize option using Help | Edit Custom Properties command. By default it has a value of 2500 (size in KB). Set it to 3000 or so (to cover your file size) and restart IDE (it reads and applies settings from idea.properties file on start only).

```<code>idea.max.intellisense.filesize=3000
</code>```

P.S. Do not put that value too big as it may cause other performance issues.

Body:
Based on your info (especially the mentioned file size and the fact that it starts to work after reducing it) you have hit a limit of max file size that IDE is willing to parse and index.

Solution: configure idea.max.intellisense.filesize option using Help | Edit Custom Properties command. By default it has a value of 2500 (size in KB). Set it to 3000 or so (to cover your file size) and restart IDE (it reads and applies settings from idea.properties file on start only).

idea.max.intellisense.filesize=3000

P.S. Do not put that value too big as it may cause other performance issues.


问:
Finding the limit of a sequence in python, jupyter notebook
I’ve got a sequence a(n)=(5-77sin(n)+8n^2)/(1-4n^2) and I’m trying to find a candidate for the limit of this sequence. How do I do this? I’ve tried using a code below but that didn’t work so any ideas?enter image description here</p>

答:
As discussed here, for sympy you need to use ** for raising to a power and not ^.

This will work:

from sympy import limit, sin, Symbol, oo
from sympy.abc import x ,n
r = limit((5-77*sin(n)+8*n**2)/(1-4*n**2),n , oo)
r
```

Adaptation of OP code based on:

https://docs.sympy.org/latest/modules/abc.html

https://docs.sympy.org/latest/modules/series/series.html

Body:
As discussed here, for sympy you need to use ** for raising to a power and not ^.

This will work:

from sympy import limit, sin, Symbol, oo
from sympy.abc import x ,n
r = limit((5-77*sin(n)+8*n**2)/(1-4*n**2),n , oo)
r

Adaptation of OP code based on:

https://docs.sympy.org/latest/modules/abc.html

https://docs.sympy.org/latest/modules/series/series.html


问:
Spring: Configuring the location of message files containing internationalization keys
I know that by default a Spring application will look for message files containing internationalization keys and values in the src/main/resources folder.  What is the best way to specify an alternate location for these message files (i.e. other than src/main/resources)?

答:
The more simple way to achieve this is to use in your properties file: spring.messages.basename,

There is another more complicated way is to define your own Bean of type: MessageSource.
Of course, the first way should be the one to use.


问:
How to count IMG tags within DIV using Xpath
I want to count how many IMG tags there are under the surface div tag and echo the amount.

```<code><div id="surface" style="width: 4567px; height: 4137px; left: -1850px; top: -1152px; cursor: default;">

<img src="https://media.memories.png" data-seat="L:106|EE:5" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2221px; top: 1561px; display: block;">

<img src="https://media.memories.png" data-seat="L:106|EE:6" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2237px; top: 1561px; display: block;">

<img src="https://media.memories.png" data-seat="L:106|EE:7" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2253px; top: 1561px; display: block;">

<img src="https://media.memories.png" data-seat="L:106|EE:8" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2269px; top: 1561px; display: block;">

</div>
</code>```

Here is my non working attempt to get the count however its not returning the count to run my test in selenium IDE.

```<code>"//div[@surface='data-seat']/img"
</code>```

答:
Option 1:
You can simply use the below xpath and then get the count.

xpath to Image - "//div[@id='surface']/img"

```<code>System.out.println(driver.findElements(By.xpath("//div[@id='surface']/img")).size());
</code>```

Option 2:
If you want to make it more complex, use the js to run the query and return the count.

```<code>JavascriptExecutor js = (JavascriptExecutor) driver;
Long number_of_imgs = (Long) js.executeScript("return document.querySelectorAll(\"div[id='surface'] img\").length");
System.out.println(number_of_imgs);
</code>```

I would prefer the option 1.

Body:
I want to count how many IMG tags there are under the surface div tag and echo the amount.

Here is my non working attempt to get the count however its not returning the count to run my test in selenium IDE.

"//div[@surface='data-seat']/img"

Body:
Option 1:
You can simply use the below xpath and then get the count.

xpath to Image - "//div[@id='surface']/img"

System.out.println(driver.findElements(By.xpath("//div[@id='surface']/img")).size());

Option 2:
If you want to make it more complex, use the js to run the query and return the count.

JavascriptExecutor js = (JavascriptExecutor) driver;
Long number_of_imgs = (Long) js.executeScript("return document.querySelectorAll(\"div[id='surface'] img\").length");
System.out.println(number_of_imgs);

I would prefer the option 1.