问:
Appcelerator - iOS : Use launch screen storyboard only for iPhone?
It's possible to use the launch screen storyboard only for iPhone?

```<code><enable-launch-screen-storyboard>true</enable-launch-screen-storyboard>
</code>```

I started using this feature with iPhone X, and for all the iPhone's models it's ok. But i don't want to support iPad Pro (for now).

Before the activation of the enable-launch-screen-storyboard functionality it was enough to not put the iPad Pro splash-screen to disable the iPad Pro support.

答: No. You can only differ now between iPhone and iPad</p>

Body:
It's possible to use the launch screen storyboard only for iPhone?

<enable-launch-screen-storyboard>true</enable-launch-screen-storyboard>

I started using this feature with iPhone X, and for all the iPhone's models it's ok. But i don't want to support iPad Pro (for now).

Before the activation of the enable-launch-screen-storyboard functionality it was enough to not put the iPad Pro splash-screen to disable the iPad Pro support.


来源: stackexchange

问:
Difference between %hash and \%hash as a parameter?
I'm currently trying to learn Perl and I noticed that sometimes people "escape" variables when passing them as parameters. I first noticed this using SQL::Abstract:

```<code>my %hash = (
  'foo' => 'bar'
);
$db->insert('table', \%hash);
```

And now, searching for a "print_r" (PHP) equivalent in Perl and seeing people recommend Data::Dumper, I couldn't understand why people would think they're equivalent until I saw an example using print Dumper(\%hash); instead of print Dumper(%hash);.

This:

```<code>my %hash = (
  key1 => 'value1',
  key2 => 'value2'
);
print Dumper(%hash);</code>```

Outputs this:

```<code>$VAR1 = 'key2';
$VAR2 = 'value2';
$VAR3 = 'key1';
$VAR4 = 'value1';
</code>```

But print Dumper(\%hash); outputs this:
```
$VAR1 = {
          'key2' => 'value2',
          'key1' => 'value1'
        };```

Can someone explain exactly what is this and what's happening? I can't find this on my Perl book and don't even know what to search for on Google. Thanks.

答:
Borrowing from Ether's comment - look at the Perl References Tutorial, and later at Perl References Manual in the language specification.  Or use perldoc perlreftut and perldoc perlref at the command line.

When you pass %hash, Perl passes a possibly large number of elements to the called function, which correspond to the key/value pairs.

When you pass \%hash, Perl passes a reference to a hash - essentially the address of the hash.

For example:

```<code>my %hash = ( Key1 => "Value1", Key2 => "Value2" );
sub counter
{
    printf "Count: %d\n", scalar(@_);
}
counter(%hash);
counter(\%hash);
</code>```

which generates:

```<code>Count: 4
Count: 1
</code>```

There are multiple ways you can get at the data:

```<code>sub hashref
{
    my($ref) = @_;
    foreach my $key (keys %{$ref})
    {
         print "$key: $ref->{$key}\n";
    }
}

sub hashnonref
{
    my(%hash) = @_;
    foreach my $key (keys %hash)
    {
        print "$key: $hash{$key}\n";
    }
}

sub hashasarray
{
    my(@array) = @_;
    foreach my $value (@array)
    {
         print "Value: $value\n";
    }
}

hashref(\%hash);   # Same data as before
print "\n";
hashnonref(%hash);
hashasarray(%hash);
</code>```

Extra output:

```<code>Key2: Value2
Key1: Value1

Key1: Value1
Key2: Value2
Value: Key2
Value: Value2
Value: Key1
Value: Value1
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm currently trying to learn Perl and I noticed that sometimes people "escape" variables when passing them as parameters. I first noticed this using SQL::Abstract:

my %hash = (
  'foo' => 'bar'
);
$db->insert('table', \%hash);

And now, searching for a "print_r" (PHP) equivalent in Perl and seeing people recommend Data::Dumper, I couldn't understand why people would think they're equivalent until I saw an example using print Dumper(\%hash); instead of print Dumper(%hash);.

This:

my %hash = (
  key1 => 'value1',
  key2 => 'value2'
);
print Dumper(%hash);

Outputs this:

$VAR1 = 'key2';
$VAR2 = 'value2';
$VAR3 = 'key1';
$VAR4 = 'value1';

But print Dumper(\%hash); outputs this:

$VAR1 = {
          'key2' => 'value2',
          'key1' => 'value1'
        };

Can someone explain exactly what is this and what's happening? I can't find this on my Perl book and don't even know what to search for on Google. Thanks.

Body:
Borrowing from Ether's comment - look at the Perl References Tutorial, and later at Perl References Manual in the language specification.  Or use perldoc perlreftut and perldoc perlref at the command line.

When you pass %hash, Perl passes a possibly large number of elements to the called function, which correspond to the key/value pairs.

When you pass \%hash, Perl passes a reference to a hash - essentially the address of the hash.

For example:

my %hash = ( Key1 => "Value1", Key2 => "Value2" );
sub counter
{
    printf "Count: %d\n", scalar(@_);
}
counter(%hash);
counter(\%hash);

which generates:

Count: 4
Count: 1

There are multiple ways you can get at the data:

sub hashref
{
    my($ref) = @_;
    foreach my $key (keys %{$ref})
    {
         print "$key: $ref->{$key}\n";
    }
}

sub hashnonref
{
    my(%hash) = @_;
    foreach my $key (keys %hash)
    {
        print "$key: $hash{$key}\n";
    }
}

sub hashasarray
{
    my(@array) = @_;
    foreach my $value (@array)
    {
         print "Value: $value\n";
    }
}

hashref(\%hash);   # Same data as before
print "\n";
hashnonref(%hash);
hashasarray(%hash);

Extra output:

Key2: Value2
Key1: Value1

Key1: Value1
Key2: Value2
Value: Key2
Value: Value2
Value: Key1
Value: Value1


问:
Encoding in a in-memory stream or how does TextIOBase work?
I am currently reading the documentation for the io module: https://docs.python.org/3.5/library/io.html?highlight=stringio#io.TextIOBase

Maybe it is because I don't know Python well enough, but in most cases I just don't understand their documentation.

I need to save the data in addresses_list to a csv file and serve it to the user via https. So all of this must happen in-memory. This is the code for it and currently it is working fine.

```<code>addresses = Abonnent.objects.filter(exemplare__gt=0)
addresses_list = list(addresses.values_list(*fieldnames))

csvfile = io.StringIO()
csvwriter_unicode = csv.writer(csvfile)
csvwriter_unicode.writerow(fieldnames)

for a in addresses_list:
    csvwriter_unicode.writerow(a)
csvfile.seek(0)

export_data = io.BytesIO()
myzip = zipfile.ZipFile(export_data, "w", zipfile.ZIP_DEFLATED)
myzip.writestr("output.csv", csvfile.read())
myzip.close()
csvfile.close()
export_data.close()

# serve the file via https
</code>```

Now the problem is that I need the content of the csv file to be encoded in cp1252 and not in utf-8. Traditionally I would just write f = open("output.csv", "w", encoding="cp1252") and then dump all the data into it. But with in-memory streams it doesn't work that way. Both, io.StringIO() and io.BytesIO() don't take a parameter encoding=.

This is where I have truoble understanding the documentation:

The text stream API is described in detail in the documentation of TextIOBase.

And the documentation of TextIOBase says this:

encoding=

The name of the encoding used to decode the stream’s bytes into strings, and to encode strings into bytes.

But io.StringIO(encoding="cp1252") just throws: TypeError: 'encoding' is an invalid keyword argument for this function.

So how can I use TextIOBase's enconding parameter with StringIO? Or how does this work in general? I am so confused.

答:
StringIO deals only with strings/text. It doesn't know anything about encodings or bytes. The easiest way to do what you want is probably something like:</p>

```<code>f = StringIO()
f.write("Some text")

# Old-ish way:
f.seek(0)
my_bytes = f.read().encode("cp1252")

# Alternatively
my_bytes = f.getvalue().encode("cp1252")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am currently reading the documentation for the io module: https://docs.python.org/3.5/library/io.html?highlight=stringio#io.TextIOBase

Maybe it is because I don't know Python well enough, but in most cases I just don't understand their documentation.

I need to save the data in addresses_list to a csv file and serve it to the user via https. So all of this must happen in-memory. This is the code for it and currently it is working fine.

addresses = Abonnent.objects.filter(exemplare__gt=0)
addresses_list = list(addresses.values_list(*fieldnames))

csvfile = io.StringIO()
csvwriter_unicode = csv.writer(csvfile)
csvwriter_unicode.writerow(fieldnames)

for a in addresses_list:
    csvwriter_unicode.writerow(a)
csvfile.seek(0)

export_data = io.BytesIO()
myzip = zipfile.ZipFile(export_data, "w", zipfile.ZIP_DEFLATED)
myzip.writestr("output.csv", csvfile.read())
myzip.close()
csvfile.close()
export_data.close()

# serve the file via https

Now the problem is that I need the content of the csv file to be encoded in cp1252 and not in utf-8. Traditionally I would just write f = open("output.csv", "w", encoding="cp1252") and then dump all the data into it. But with in-memory streams it doesn't work that way. Both, io.StringIO() and io.BytesIO() don't take a parameter encoding=.

This is where I have truoble understanding the documentation:

The text stream API is described in detail in the documentation of TextIOBase.

And the documentation of TextIOBase says this:

encoding=

The name of the encoding used to decode the stream’s bytes into strings, and to encode strings into bytes.

But io.StringIO(encoding="cp1252") just throws: TypeError: 'encoding' is an invalid keyword argument for this function.

So how can I use TextIOBase's enconding parameter with StringIO? Or how does this work in general? I am so confused.

Body:
StringIO deals only with strings/text. It doesn't know anything about encodings or bytes. The easiest way to do what you want is probably something like:

f = StringIO()
f.write("Some text")

# Old-ish way:
f.seek(0)
my_bytes = f.read().encode("cp1252")

# Alternatively
my_bytes = f.getvalue().encode("cp1252")


问:
Media query not working when styling ninja form in Wordpress
newbie on here so apologies if I get anything wrong on here.

I'm building a wordpress website for a client and trying to style the contact form (currently using the Ninja form plugin). With the basic version, it is easy to have two fields in one row, but what I want to do is for mobile view, make the right hand field file neatly underneath into one column.

The relevant CSS in the plug-in is below:

```<code>.nf-form-cont {
.five-sixths,
.four-sixths,
.one-fourth,
.one-half,
.one-sixth,
.one-third,
.three-fourths,
.three-sixths,
.two-fourths,
.two-sixths,
.two-thirds {
    clear: initial;
    float: left;
    margin-left: 2.564102564102564%;
    .inside {
        padding: 20px;
    }
    &::after {
        clear: both;
        content: "";
        display: block;
    }
}

.one-half,
.three-sixths,
.two-fourths {
    width: 48.717948717948715%;
}
</code>```

I've written the CSS below which makes the second field drop below the first and removes the margin:

```<code>.one-half {
    margin-left:0;
    width: 100%;
}
</code>```

This works fine, until I place in a media query like so:

```<code>@media only screen and (max-width: 719px) {

.one-half {
    margin-left:0;
    width: 100%;
    }
}
</code>```

From reading other questions on here, I believe the issue might be something to do with needing an ID in the media query also, but I've tried numerous IDs without success. When I use Inspect on Google to check the code, the media query doesn't even seem to exist.

Hope someone can shed some light on this! Thanks.

答:
Add the following code to the bottom of your appearance->Additional Css</p>

```<code>    @media screen and (max-width : 680px){
     .one-fourth {
           min-width: 100%;
           display:block;
        }
    }
</code>```

Body:
newbie on here so apologies if I get anything wrong on here.

I'm building a wordpress website for a client and trying to style the contact form (currently using the Ninja form plugin). With the basic version, it is easy to have two fields in one row, but what I want to do is for mobile view, make the right hand field file neatly underneath into one column.

The relevant CSS in the plug-in is below:

.nf-form-cont {
.five-sixths,
.four-sixths,
.one-fourth,
.one-half,
.one-sixth,
.one-third,
.three-fourths,
.three-sixths,
.two-fourths,
.two-sixths,
.two-thirds {
    clear: initial;
    float: left;
    margin-left: 2.564102564102564%;
    .inside {
        padding: 20px;
    }
    &::after {
        clear: both;
        content: "";
        display: block;
    }
}

.one-half,
.three-sixths,
.two-fourths {
    width: 48.717948717948715%;
}

I've written the CSS below which makes the second field drop below the first and removes the margin:

.one-half {
    margin-left:0;
    width: 100%;
}

This works fine, until I place in a media query like so:

@media only screen and (max-width: 719px) {

.one-half {
    margin-left:0;
    width: 100%;
    }
}

From reading other questions on here, I believe the issue might be something to do with needing an ID in the media query also, but I've tried numerous IDs without success. When I use Inspect on Google to check the code, the media query doesn't even seem to exist.

Hope someone can shed some light on this! Thanks.

Body:
Add the following code to the bottom of your appearance->Additional Css

    @media screen and (max-width : 680px){
     .one-fourth {
           min-width: 100%;
           display:block;
        }
    }


问:
Should you use a function for only one line of code?
I'm relatively new to python and I was wondering if it's always better to never write something twice. I'm currently making a program where at two points in the program the same sentence may need to be saved to a file (consisting only of that sentence). </p>

<p>Is it worth it to make a function for that? I was wondering since it now takes up 2 lines of code, but making a function would make it 4 (2 to define the function and 2 to call it). </p>

答:
When to create a function depends a lot on the specifics of the situation. It isn't just about saving lines of code - often, more lines of code is better because it makes it easier to maintain or easier to understand.

One reason to make a function is that it means if you need to change your code, there is just one place you have to change it.

It's unclear to me from your situation if you should create a function or not. It depends on the line of code. If the line of code is just calling another function, then wrapping that in another function doesn't make sense. If it's some complicated line that has lots of parts subject to change, then it might make sense.

Body:
I'm relatively new to python and I was wondering if it's always better to never write something twice. I'm currently making a program where at two points in the program the same sentence may need to be saved to a file (consisting only of that sentence).

Is it worth it to make a function for that? I was wondering since it now takes up 2 lines of code, but making a function would make it 4 (2 to define the function and 2 to call it).


问:
How to count distinct values that all satisfy a condition in MySQL?
I'm trying to write a query to find distinct values in a particular field, count the number of occurrences of that value where for all instances of that particular value another column value is satisfied, and then display the results as follows (more explanation to follow):

Example db:

```<code>RowId    Status       MemberIdentifier
-----    ------       ----------------
1       In Progress   111111111
2       Complete      123456789
3       Not Started   146782452
4       Complete      111111111
5       Complete      123456789
6       Not Started   146782452
7       Complete      111111111
</code>```

Desired Result:

```<code>Status         MemberIdentifierCount
------         ----------------------
Not Started    1
In Progress    1
Complete       1
</code>```

In the above query, the number of distinct MemberIdentifiers with a given Status are counted and displayed. If a MemberIdentifier has two rows with Status 'Complete' but one with Status 'In Progress,' it is grouped and counted as in progress (i.e., MemberIdentifier= 111111111). For a MemberIdentifier to be grouped and counted as complete, all of its rows must have a Status of 'Complete' (i.e., MemberIdentifier= 123456789). Any insight would be appreciated (MySQL newbie).

答:
Another way using a specific table to configure the order (map to Power of two integer).

This mapping allow bit_or aggregate to simply transpose data.

http://rextester.com/edit/ZSG98543

```<code>-- Table bit_progression to determine priority

CREATE TABLE bit_progression (bit_status int PRIMARY KEY, Status VARCHAR(255));
INSERT INTO bit_progression (bit_status, Status)
VALUES
(1,       'Not Started'),
(2,       'Complete'   ),
(4,       'In Progress');

select
    Status,
    count(*)
from
    (
    select
         MemberIdentifier,max(bit_status) bit_status
    from
        tbl natural join bit_progression
    group by
        MemberIdentifier
    ) Maxi natural join bit_progression
group by
    Status
;
</code>```

produce

```<code>Status  count(*)

1   Complete    1
2   In Progress 1
3   Not Started 1
</code>```

Extra :

```<code>select
    MemberIdentifier,
    bit_or(bit_status) bits_status,
    case when bit_or(bit_status) & 4 = 4 then true end as withStatusInProgress,
    case when bit_or(bit_status) & 2 = 2 then true end as withStatusComplete,
    case when bit_or(bit_status) & 1 = 1 then true end as withStatusNotStarted
from
    tbl natural join bit_progression
group by
    MemberIdentifier
;
</code>```

produce it :

```<code>MemberIdentifier bits_status    withStatusInProgress    withStatusComplete  withStatusNotStarted

111111111   6   1       1       NULL
123456789   2   NULL    1       NULL
146782452   1   NULL    NULL    1
</code>```

Body:
I'm trying to write a query to find distinct values in a particular field, count the number of occurrences of that value where for all instances of that particular value another column value is satisfied, and then display the results as follows (more explanation to follow):

Example db:

RowId    Status       MemberIdentifier
-----    ------       ----------------
1       In Progress   111111111
2       Complete      123456789
3       Not Started   146782452
4       Complete      111111111
5       Complete      123456789
6       Not Started   146782452
7       Complete      111111111

Desired Result:

Status         MemberIdentifierCount
------         ----------------------
Not Started    1
In Progress    1
Complete       1

In the above query, the number of distinct MemberIdentifiers with a given Status are counted and displayed. If a MemberIdentifier has two rows with Status 'Complete' but one with Status 'In Progress,' it is grouped and counted as in progress (i.e., MemberIdentifier= 111111111). For a MemberIdentifier to be grouped and counted as complete, all of its rows must have a Status of 'Complete' (i.e., MemberIdentifier= 123456789). Any insight would be appreciated (MySQL newbie).

Body:
Another way using a specific table to configure the order (map to Power of two integer).

This mapping allow bit_or aggregate to simply transpose data.

http://rextester.com/edit/ZSG98543

-- Table bit_progression to determine priority

CREATE TABLE bit_progression (bit_status int PRIMARY KEY, Status VARCHAR(255));
INSERT INTO bit_progression (bit_status, Status)
VALUES
(1,       'Not Started'),
(2,       'Complete'   ),
(4,       'In Progress');

select
    Status,
    count(*)
from
    (
    select
         MemberIdentifier,max(bit_status) bit_status
    from
        tbl natural join bit_progression
    group by
        MemberIdentifier
    ) Maxi natural join bit_progression
group by
    Status
;

produce

Status  count(*)

1   Complete    1
2   In Progress 1
3   Not Started 1

Extra :

select
    MemberIdentifier,
    bit_or(bit_status) bits_status,
    case when bit_or(bit_status) & 4 = 4 then true end as withStatusInProgress,
    case when bit_or(bit_status) & 2 = 2 then true end as withStatusComplete,
    case when bit_or(bit_status) & 1 = 1 then true end as withStatusNotStarted
from
    tbl natural join bit_progression
group by
    MemberIdentifier
;

produce it :

MemberIdentifier bits_status    withStatusInProgress    withStatusComplete  withStatusNotStarted

111111111   6   1       1       NULL
123456789   2   NULL    1       NULL
146782452   1   NULL    NULL    1


问:
unit testing for observer pattern
I am rather new for software testing. I wonder what is the right way to make a unit testing for observer pattern? e.g. if we have the following 4 classes implemented: Subject class(attach/detach/notify), Observer interface class (update virtual method), ConcreteSubject class, and ConcreteObserver (concrete update method).
how to write test tracks for each of these classes? Is there any good example to take a reference?

Thanks for any inputs.

答:
For the Subject, you can test:
if the observer is well attach(count the number of observers and check if the one attach is the good one),
and after if the observer is well detach.

You can also check by adding more than one observer just to be sure your collection of Observers is well implemented.

You can check the notification by creating a mock observer that contains a boolean set to true if he is updated.

Title: unit testing for observer pattern

ContentLicense: CC BY-SA 4.0


问:
Date range in SSRS report header
I am using Date range in where clause of the SQL query which is being used in Data Set of SSRS report. Basically I am showing current week's data which is running perfect. I would like to display both dates (Moday) and (Friday) in report's Title so users can have idea which dates this report is based on.

Could you please help me how to display these 2 dates in SSRS report title ?

This is where clause of my query

WHERE TRANS_DATE BETWEEN dateadd(wk, datediff(wk, 0, GETDATE()), 0) AND dateadd(wk, datediff(wk, 0, GETDATE()), 0) + 4

dateadd(wk, datediff(wk, 0, GETDATE()), 0)  -- Returns Monday of current week
dateadd(wk, datediff(wk, 0, GETDATE()), 0) + 4 -- Return Friday of current week

Thanks,
Nadeem

答: If you declare fromDate and toDate parameters in your report then you can reference them in both your query (as @FromDate) and in the page header as Parameters!fromDate</p>

Title: Date range in SSRS report header


问:
Looping through worksheets and check cell value
I am trying to loop through all sheets and check them one by one and do the following: If in the checked cell the value of E18 = N/A then on the first sheet (named Summary) I'd change the value of G23 to N/A as well (and then do that for each cell, and on Summary change G23 then G24 then G25 and so forth) I wrote the following loop, it runs but it doesn't do anything whatsoever

```<code>Sub MyTestSub()

Dim ws As Worksheet

LastRow = Cells(Rows.Count, "G").End(xlUp).Row
For X = 22 To LastRow
    For Each ws In Worksheets
        If ws.Range("E18").Value="N/A" then ThisWorkbook.Sheets("Summary").Range("G"&x).Value="N/A"
    Next ws
Next x

End Sub
</code>```

Any help would be appreciated!

答:
Try to reverse the nested loops. Something like this should be working:

```<code>Sub MyTestSub()
    Dim ws As Worksheet
    For Each ws In Worksheets
        LastRow = ws.Cells(ws.Rows.Count, "G").End(xlUp).Row
        If IsError(ws.Range("E18")) then
            For X = 22 To LastRow
                Sheets("Summary").Range("G" & LastRow) = ws.Range("E18")
            next x
        end if
    Next ws
End Sub
</code>```

Furthermore, I assume that the LastRow is different per worksheet, thus you have to reset it quite often - every time there is a new worksheet.
Last but not least - make sure that you refer the worksheet, when you are refering to Cells, like this:

```<code>LastRow = ws.Cells(ws.Rows.Count, "G").End(xlUp).Row
</code>```

If you do not do it you will be taking into account the ActiveSheet.

Here is more about the errors in Excel and returning them - http://www.cpearson.com/excel/ReturningErrors.aspx

The solution will work with any error, not only with #N/A

Body:
I am trying to loop through all sheets and check them one by one and do the following: If in the checked cell the value of E18 = N/A then on the first sheet (named Summary) I'd change the value of G23 to N/A as well (and then do that for each cell, and on Summary change G23 then G24 then G25 and so forth) I wrote the following loop, it runs but it doesn't do anything whatsoever

Sub MyTestSub()

Dim ws As Worksheet

LastRow = Cells(Rows.Count, "G").End(xlUp).Row
For X = 22 To LastRow
    For Each ws In Worksheets
        If ws.Range("E18").Value="N/A" then ThisWorkbook.Sheets("Summary").Range("G"&x).Value="N/A"
    Next ws
Next x

End Sub

Any help would be appreciated!

Body:
Try to reverse the nested loops. Something like this should be working:

Sub MyTestSub()
    Dim ws As Worksheet
    For Each ws In Worksheets
        LastRow = ws.Cells(ws.Rows.Count, "G").End(xlUp).Row
        If IsError(ws.Range("E18")) then
            For X = 22 To LastRow
                Sheets("Summary").Range("G" & LastRow) = ws.Range("E18")
            next x
        end if
    Next ws
End Sub

Furthermore, I assume that the LastRow is different per worksheet, thus you have to reset it quite often - every time there is a new worksheet.
Last but not least - make sure that you refer the worksheet, when you are refering to Cells, like this:

LastRow = ws.Cells(ws.Rows.Count, "G").End(xlUp).Row

If you do not do it you will be taking into account the ActiveSheet.

Here is more about the errors in Excel and returning them - http://www.cpearson.com/excel/ReturningErrors.aspx

The solution will work with any error, not only with #N/A


问:
Login-AzureRMAccount returns "Unknown User Type"
As the title implies, I'm trying to automate the login process to AzureRMAccount in Powershell.

I've scoured every forum on every website I can find trying every different combination of solutions (well, except for the solution that works).

Every time I try to automate the login process of my Azure account, I get an error :

Unknown User Type

Yes, I have full access to this account, and Yes it does work fine if I omit all of the parameters and allow for the interactive username/password dialog.

I have even tried to simply call the Get-Credentials and push those into a variable and then call Login-AzureRMAccount using those creds....no luck.

Add-AzureRMAccount fails too.

Any help would be appreciated.

答:
I did find one solution, although it's not the most secure solution as it generates a disk file putting your information at risk if someone were to gain access to the machine on which the Powershell code is executing.

You can login interactively and immediately export the context to a json file, Then at a later time, import that json file as the current context to bypass login

```<code>PS C:\> Save-AzureRmContext -Profile (Add-AzureRmAccount) -Path C:\test.json
</code>```

then in a later session, Import the context

```<code>PS C:\> Import-AzureRmContext -Path C:\test.json
</code>```

Again, this is not the most secure option but it did achieve the results. I would love to have a more secure option.

Body:
I did find one solution, although it's not the most secure solution as it generates a disk file putting your information at risk if someone were to gain access to the machine on which the Powershell code is executing.

You can login interactively and immediately export the context to a json file, Then at a later time, import that json file as the current context to bypass login

PS C:\> Save-AzureRmContext -Profile (Add-AzureRmAccount) -Path C:\test.json

then in a later session, Import the context

PS C:\> Import-AzureRmContext -Path C:\test.json

Again, this is not the most secure option but it did achieve the results. I would love to have a more secure option.


问:
ORA-01722 invalid number on using the expression in select and while joining
```<code>CASE WHEN (r.code_value4 = 0 AND LENGTH(ltrim(rtrim(xx.AFFILIATE_CODE))) > 0) AND
          r_intercompany.code_value1 is not null AND
          ltrim(rtrim(xx.AFFILIATE_CODE)) <> (CASE WHEN xx.COMPANY_CODE_JE_EXCEPTION_FLAG = 1
                                                   THEN r.code_value3 ELSE r.code_value1 END)
     THEN r_intercompany.code_value1
     ELSE NVL(r_mga_acct.code_value2, xx.ACCOUNT_NUMBER) END
</code>```

I have view in which the above part of the sql is being used in select statement and as well as to compare with a field while joining. When I run the view after making this change, it is throwing the error ORA-01722 invalid number.

Please let me know on how to correct this.

Thanks

答:
My Suspicion is either r.code_value4 field  or xx.COMPANY_CODE_JE_EXCEPTION_FLAG field is String type hence try the below </p>

```<code>CASE WHEN (r.code_value4 = '0' AND LENGTH(ltrim(rtrim(xx.AFFILIATE_CODE))) > 0) AND
      r_intercompany.code_value1 is not null AND
      ltrim(rtrim(xx.AFFILIATE_CODE)) <> (CASE WHEN xx.COMPANY_CODE_JE_EXCEPTION_FLAG = '1'
                                               THEN r.code_value3 ELSE r.code_value1 END)
 THEN r_intercompany.code_value1
 ELSE NVL(r_mga_acct.code_value2, xx.ACCOUNT_NUMBER) END
</code>```

Body:
CASE WHEN (r.code_value4 = 0 AND LENGTH(ltrim(rtrim(xx.AFFILIATE_CODE))) > 0) AND
          r_intercompany.code_value1 is not null AND
          ltrim(rtrim(xx.AFFILIATE_CODE)) <> (CASE WHEN xx.COMPANY_CODE_JE_EXCEPTION_FLAG = 1
                                                   THEN r.code_value3 ELSE r.code_value1 END)
     THEN r_intercompany.code_value1
     ELSE NVL(r_mga_acct.code_value2, xx.ACCOUNT_NUMBER) END

I have view in which the above part of the sql is being used in select statement and as well as to compare with a field while joining. When I run the view after making this change, it is throwing the error ORA-01722 invalid number.

Please let me know on how to correct this.

Thanks

Body:
My Suspicion is either r.code_value4 field  or xx.COMPANY_CODE_JE_EXCEPTION_FLAG field is String type hence try the below

CASE WHEN (r.code_value4 = '0' AND LENGTH(ltrim(rtrim(xx.AFFILIATE_CODE))) > 0) AND
      r_intercompany.code_value1 is not null AND
      ltrim(rtrim(xx.AFFILIATE_CODE)) <> (CASE WHEN xx.COMPANY_CODE_JE_EXCEPTION_FLAG = '1'
                                               THEN r.code_value3 ELSE r.code_value1 END)
 THEN r_intercompany.code_value1
 ELSE NVL(r_mga_acct.code_value2, xx.ACCOUNT_NUMBER) END


问:
how to put a jQuery $ (..).click (function () { inside a javascript object?
I'm trying to put a  $(..).click(function () {...  inside a javascript object, but I feel like I'm asking for the impossible.

Inside this object there can be several Dom elements, so I think that making a jQuery extension is excluded too?
But I admit, I can not understand how to make an jQuery extension, there are still concepts that escape me in this respect.

Anyway, here's an example of what I'm looking to do, even if it's not functional:

$(document).ready(function() {
  class bt_Fab {
    constructor($elem_ID, $messageBox_ID, message) {
      this.$_ID = $elem_ID;
      this.$_ID_MsgBox = $messageBox_ID;
      this._msg = message;

      this.$_ID.click(function() {
        this.$_ID_MsgBox.text(this._msg); // does nothing...
      });
    }
  };

  var
    myOneButton = new bt_Fab($('#btn_one'), $('#messageBox'), 'message from button one!'),
    myTwoButton = new bt_Fab($('#btn_two'), $('#messageBox'), 'message from button two!');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='btn_one'>button One</button>
<button id='btn_two'>button Two</button>
<!-- lot of html here -->
<div id="messageBox">... </div></code>```

[ Update Edit ] ( for @Sam Hanley & @meagar )
This question is different from How to access the correct `this` inside a callback?
because this question is about the use of jQuery function inside a Javascript Object; and they are not about the corect usage of a this in Javascript object model.

答:
In jQuery, within a event handler such as $.click(), the this keyword is overriden with the reference to the sender object, in this case $_ID. In this.$_ID.click, this is actually the instance of the class. Inside of the click handler, i.e. function() { this.msgBox... }, this refers to the element that was clicked.

When I create a class in javascript, I usually create a class variable called my that I set to this in the constructor of the class. Instead of using this use the my variable when you're using jQuery to avoid confusion.

Sometimes it's actually nice that this is overridden, but when you're defining a class it's just horrible.

Body:
I'm trying to put a  $(..).click(function () {...  inside a javascript object, but I feel like I'm asking for the impossible.

Inside this object there can be several Dom elements, so I think that making a jQuery extension is excluded too?
But I admit, I can not understand how to make an jQuery extension, there are still concepts that escape me in this respect.

Anyway, here's an example of what I'm looking to do, even if it's not functional:

$(document).ready(function() {
  class bt_Fab {
    constructor($elem_ID, $messageBox_ID, message) {
      this.$_ID = $elem_ID;
      this.$_ID_MsgBox = $messageBox_ID;
      this._msg = message;

      this.$_ID.click(function() {
        this.$_ID_MsgBox.text(this._msg); // does nothing...
      });
    }
  };

  var
    myOneButton = new bt_Fab($('#btn_one'), $('#messageBox'), 'message from button one!'),
    myTwoButton = new bt_Fab($('#btn_two'), $('#messageBox'), 'message from button two!');
});

<button id='btn_one'>button One</button>
<button id='btn_two'>button Two</button>

...

[ Update Edit ] ( for @Sam Hanley & @meagar )
This question is different from How to access the correct `this` inside a callback?
because this question is about the use of jQuery function inside a Javascript Object; and they are not about the corect usage of a this in Javascript object model.


问:
Contact form 7 file attachment
I use contact form 7.
[file file-123 limit:25m filetypes:png|jpg|jpeg|pdf]
This is the shortcode. When i upload the file and send it is just says the name of the file but not the file it self.</p>

答:
You need to include [file-123] on the second TAB - "Mail" in the last section "file attachments"

Also, limit needs to be like limit:25mb you are missing b, but I do not suggest to use that big attachments because most of emails have limit to 25mb

Title: Contact form 7 file attachment


问:
Order of JAX-RS filter and interceptor
I have two request filters and one request interceptor as follows:

```<code>@Provider
@RequestLogger
@Priority(100)
public class LogRequestFilter implements ContainerRequestFilter {
    ...
}

@Provider
@OracleSessionChecker
@Priority(300)
public class CheckOracleSessionFilter implements ContainerRequestFilter {
    ...
}

@Provider
@RequestChecker
@Priority(200)
public class CheckRequestInterceptor implements ReaderInterceptor {
    ...
}
</code>```

I have JAX-RS web services that use these filters and interceptor. The following is one example web service method.

```<code>@POST
@RequestLogger
@RequestChecker
@OracleSessionChecker
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("Logout")
public Response logout(@Context HttpServletRequest request, Parameters inputs) {
    ...
}
</code>```

From the priorities given, I would think that the order that the filters/interceptor are called would be:
LogRequestFilter, CheckRequestInterceptor, CheckOracleSessionFilter.

But the actual order that they are called is:
LogRequestFilter, CheckOracleSessionFilter, CheckRequestInterceptor.

Why is the CheckRequestInterceptor called last even though its priority, 200, is in the middle?

How can I make them called in the order that I want (that is, LogRequestFilter, CheckRequestInterceptor, CheckOracleSessionFilter)?

Thanks in advance.

答:
All RequestFilters are executed based on their priorities before any RequestInterceptors (which are then executed based on their priorities).

The simplest explanation I can think of is if you had the following files in a folder:

```<code>F-100
F-300
I-200
</code>```

I-200 doesn't come before F-300 (even though 200 is before 300) because 'F's are sorted before 'I's.

Title: Order of JAX-RS filter and interceptor

Body:
I have two request filters and one request interceptor as follows:

@Provider
@RequestLogger
@Priority(100)
public class LogRequestFilter implements ContainerRequestFilter {
    ...
}

@Provider
@OracleSessionChecker
@Priority(300)
public class CheckOracleSessionFilter implements ContainerRequestFilter {
    ...
}

@Provider
@RequestChecker
@Priority(200)
public class CheckRequestInterceptor implements ReaderInterceptor {
    ...
}

I have JAX-RS web services that use these filters and interceptor. The following is one example web service method.

@POST
@RequestLogger
@RequestChecker
@OracleSessionChecker
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("Logout")
public Response logout(@Context HttpServletRequest request, Parameters inputs) {
    ...
}

From the priorities given, I would think that the order that the filters/interceptor are called would be:
LogRequestFilter, CheckRequestInterceptor, CheckOracleSessionFilter.

But the actual order that they are called is:
LogRequestFilter, CheckOracleSessionFilter, CheckRequestInterceptor.

Why is the CheckRequestInterceptor called last even though its priority, 200, is in the middle?

How can I make them called in the order that I want (that is, LogRequestFilter, CheckRequestInterceptor, CheckOracleSessionFilter)?

Thanks in advance.

Body:
All RequestFilters are executed based on their priorities before any RequestInterceptors (which are then executed based on their priorities).

The simplest explanation I can think of is if you had the following files in a folder:

F-100
F-300
I-200

I-200 doesn't come before F-300 (even though 200 is before 300) because 'F's are sorted before 'I's.


答:
Do you mean assign a variable (by that I mean x = 7, or rate = getSamplingRate(sound)/2) or write a function?  I try to assign variables when I use them several times or if it makes the code easier to read.

if you mean define a new function like this:

```<code>    def newSentence():
</code>```

then I would write a new function if I am doing the same thing several times.  It wouldn't hurt to define a function if you are performing the same action more than once.

I think a good rule of thumb when you're starting out is to first get your code to work, then make sure it is easy to read (for yourself, or for another person reading your program), then focus on efficiency.

I'm sort of new to Python as well. I hope that helps.

Title: Should you use a function for only one line of code?

Body:
Do you mean assign a variable (by that I mean x = 7, or rate = getSamplingRate(sound)/2) or write a function?  I try to assign variables when I use them several times or if it makes the code easier to read.

if you mean define a new function like this:

    def newSentence():

then I would write a new function if I am doing the same thing several times.  It wouldn't hurt to define a function if you are performing the same action more than once.

I think a good rule of thumb when you're starting out is to first get your code to work, then make sure it is easy to read (for yourself, or for another person reading your program), then focus on efficiency.

I'm sort of new to Python as well. I hope that helps.


问:
Django-Rest-Framework APIView returning a model object and an image
suppose that I want to return in a APIView.get a (non model) object conatining 2 properties, one of them is a model object, and the other is a binary Image

I've tried several ways and had problems with serializer.

thanks!

Serializer:

```<code>class MyCustomSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyCustom
        fields = '__all__'
</code>```

View:

```<code>class MyCustomGet(APIView):
    def get(self, request, format=None):
        serializer = MyCustomSerializer
        obj = s.get_custom()
        return Response({"obj": serializer(obj.obj).data, "image": obj.image})
</code>```

get_custom:

```<code>class CustomClass:
    obj = None
    image = None

def get_custom():
    r = CustomClass()
    r.obj = MyCustom.objects.all().first()
    r.image = PIL.Image.open('file/path.png')
    return r
</code>```

答:
I'm not sure if this would be helpful, but this is what I did for a similar situation. I had one primary model object, and a semi-related object I wanted to tag in.

Basically, if your CustomClass model is somehow related to the image you need to include, just fetch it directly in the serializer instance.

This is sort of how I would try to do it:

```<code>class MyCustomSerializer(serializers.ModelSerializer):
    image_binary = serializers.SerializerMethodField()

    class Meta:
        model = MyCustom
        fields = '__all__'

    def get_image_binary(self, obj):
        return WhateverModel.objects.get(relation=obj).attribute
</code>```

This simply adds some extra data to your model serializer, calculated on the fly by the serializer. You could even have a second serializer for the image_binary and in the get_image_binary() simply return the .data for the serializer, just like you did in your view.

This of course relies on the fact that the MyCustom object is somehow implicitly related to your image binary.

Body:
suppose that I want to return in a APIView.get a (non model) object conatining 2 properties, one of them is a model object, and the other is a binary Image

I've tried several ways and had problems with serializer.

thanks!

Serializer:

class MyCustomSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyCustom
        fields = '__all__'

View:

class MyCustomGet(APIView):
    def get(self, request, format=None):
        serializer = MyCustomSerializer
        obj = s.get_custom()
        return Response({"obj": serializer(obj.obj).data, "image": obj.image})

get_custom:

class CustomClass:
    obj = None
    image = None

def get_custom():
    r = CustomClass()
    r.obj = MyCustom.objects.all().first()
    r.image = PIL.Image.open('file/path.png')
    return r

Body:
I'm not sure if this would be helpful, but this is what I did for a similar situation. I had one primary model object, and a semi-related object I wanted to tag in.

Basically, if your CustomClass model is somehow related to the image you need to include, just fetch it directly in the serializer instance.

This is sort of how I would try to do it:

class MyCustomSerializer(serializers.ModelSerializer):
    image_binary = serializers.SerializerMethodField()

    class Meta:
        model = MyCustom
        fields = '__all__'

    def get_image_binary(self, obj):
        return WhateverModel.objects.get(relation=obj).attribute

This simply adds some extra data to your model serializer, calculated on the fly by the serializer. You could even have a second serializer for the image_binary and in the get_image_binary() simply return the .data for the serializer, just like you did in your view.

This of course relies on the fact that the MyCustom object is somehow implicitly related to your image binary.


问:
Intermittent timeouts between AWS Lambda and RDS
We are currently experiencing what I can only describe as random intermittent timeouts between AWS Lambda and RDS. After deploying our functions and running them successfully, they can randomly switch to a state of timing out with no configuration changes. Important to note, we are also monitoring the DB connections and can confirm that we aren't running into a max connection issue.

Here are the details on our setup:

Code being executed (using Node.JS v. 6.10):

```<code>const mysql = require('mysql');

exports.dbWrite = (events, context, callback) => {

   const db = mysql.createConnection({
       host: <redacted>,
       user: <redacted>,
       password: <redacted>,
       database: <redacted>
   });

   db.connect(function (err) {
       if (err) {
           console.error('error connecting: ' + err.stack);
           return;
       }

       console.log('connected !');
   });

   db.end();

};
</code>```

We are using the Node.JS mysql library, v. 2.14.1.

From a networking perspective:

The Lambda function is in the same VPC as our RDS instance

The Lambda function has subnets assigned, which are associated with a routing table that does not have internet access (not associated with an internet gateway)

The RDS database is not publicly accessible.

A security group has been created and associated with the Lambda function that has wide open access on all ports (for now - once DB connectivity is reliable, that will change).

The above security group has been whitelisted on port 3306 within a security group associated with the RDS instance.

CloudWatch error:

```<code>{
  "errorMessage": "connect ETIMEDOUT",
  "errorType": "Error",
  "stackTrace": [
    "Connection._handleConnectTimeout
     (/var/task/node_modules/mysql/lib/Connection.js:419:13)",
     "Socket.g (events.js:292:16)",
     "emitNone (events.js:86:13)",
     "Socket.emit (events.js:185:7)",
     "Socket._onTimeout (net.js:338:8)",
     "ontimeout (timers.js:386:14)",
     "tryOnTimeout (timers.js:250:5)",
     "Timer.listOnTimeout (timers.js:214:5)",
     "    --------------------",
     "Protocol._enqueue
      (/var/task/node_modules/mysql/lib/protocol/Protocol.js:145:48)",
     "Protocol.handshake
      (/var/task/node_modules/mysql/lib/protocol/Protocol.js:52:23)",
     "Connection.connect
      (/var/task/node_modules/mysql/lib/Connection.js:130:18)",
     "Connection._implyConnect
      (/var/task/node_modules/mysql/lib/Connection.js:461:10)",
     "Connection.query
      (/var/task/node_modules/mysql/lib/Connection.js:206:8)",
     "/var/task/db-write-lambda.js:52:12",
     "getOrCreateEventTypeId (/var/task/db-write-lambda.js:51:12)",
     "exports.dbWrite (/var/task/db-write-lambda.js:26:9)"
   ]
 }
</code>```

Amongst the references already reviewed:

https://forums.aws.amazon.com/thread.jspa?threadID=221928
(the invocation ID in CloudWatch is different on all timeout cases)

pretty much every post in this list: https://stackoverflow.com/search?q=aws+lambda+timeouts+to+RDS

In summary, the fact that these timeouts are intermittent makes this an issue that is totally confusing. AWS support has stated that NodeJS-mysql is a third-party tool, and is technically not supported, but I know folks are using this technique.

Any help is greatly appreciated!

答:
Updating this issue: It turns out that the issue was related to the fact that the database connection was being made within the handler! Due to the asynchronous nature of Lambda and Node, this was the culprit for the intermittent timeouts.

Here's the revised code:

```<code>const mysql = require('mysql');
const database = getConnection();

exports.dbWrite = (events, context, callback) => {

   database.connect(function (err) {
     if (err) {
          console.error('error connecting: ' + err.stack);
          return;
     }

     console.log('connected !');
});

db.end();

function getConnection() {
   let db = mysql.createConnection({
       host: process.env.DB_HOST,
       user: process.env.DB_USER,
       password: process.env.DB_PASS,
       database: process.env.DB_NAME
   });

   console.log('Host: ' + process.env.DB_HOST);
   console.log('User: ' + process.env.DB_USER);
   console.log('Database: ' + process.env.DB_NAME);

   console.log('Connecting to ' + process.env.DB_HOST + '...');

   return db;
}
</code>```

Body:
We are currently experiencing what I can only describe as random intermittent timeouts between AWS Lambda and RDS. After deploying our functions and running them successfully, they can randomly switch to a state of timing out with no configuration changes. Important to note, we are also monitoring the DB connections and can confirm that we aren't running into a max connection issue.

Here are the details on our setup:

Code being executed (using Node.JS v. 6.10):

const mysql = require('mysql');

exports.dbWrite = (events, context, callback) => {

   const db = mysql.createConnection({
       host: <redacted>,
       user: <redacted>,
       password: <redacted>,
       database: <redacted>
   });

   db.connect(function (err) {
       if (err) {
           console.error('error connecting: ' + err.stack);
           return;
       }

       console.log('connected !');
   });

   db.end();

};

We are using the Node.JS mysql library, v. 2.14.1.

From a networking perspective:

The Lambda function is in the same VPC as our RDS instance

The Lambda function has subnets assigned, which are associated with a routing table that does not have internet access (not associated with an internet gateway)

The RDS database is not publicly accessible.

A security group has been created and associated with the Lambda function that has wide open access on all ports (for now - once DB connectivity is reliable, that will change).

The above security group has been whitelisted on port 3306 within a security group associated with the RDS instance.

CloudWatch error:

{
  "errorMessage": "connect ETIMEDOUT",
  "errorType": "Error",
  "stackTrace": [
    "Connection._handleConnectTimeout
     (/var/task/node_modules/mysql/lib/Connection.js:419:13)",
     "Socket.g (events.js:292:16)",
     "emitNone (events.js:86:13)",
     "Socket.emit (events.js:185:7)",
     "Socket._onTimeout (net.js:338:8)",
     "ontimeout (timers.js:386:14)",
     "tryOnTimeout (timers.js:250:5)",
     "Timer.listOnTimeout (timers.js:214:5)",
     "    --------------------",
     "Protocol._enqueue
      (/var/task/node_modules/mysql/lib/protocol/Protocol.js:145:48)",
     "Protocol.handshake
      (/var/task/node_modules/mysql/lib/protocol/Protocol.js:52:23)",
     "Connection.connect
      (/var/task/node_modules/mysql/lib/Connection.js:130:18)",
     "Connection._implyConnect
      (/var/task/node_modules/mysql/lib/Connection.js:461:10)",
     "Connection.query
      (/var/task/node_modules/mysql/lib/Connection.js:206:8)",
     "/var/task/db-write-lambda.js:52:12",
     "getOrCreateEventTypeId (/var/task/db-write-lambda.js:51:12)",
     "exports.dbWrite (/var/task/db-write-lambda.js:26:9)"
   ]
 }

Amongst the references already reviewed:

https://forums.aws.amazon.com/thread.jspa?threadID=221928
(the invocation ID in CloudWatch is different on all timeout cases)

pretty much every post in this list: https://stackoverflow.com/search?q=aws+lambda+timeouts+to+RDS

In summary, the fact that these timeouts are intermittent makes this an issue that is totally confusing. AWS support has stated that NodeJS-mysql is a third-party tool, and is technically not supported, but I know folks are using this technique.

Any help is greatly appreciated!

Body:
Updating this issue: It turns out that the issue was related to the fact that the database connection was being made within the handler! Due to the asynchronous nature of Lambda and Node, this was the culprit for the intermittent timeouts.

Here's the revised code:

const mysql = require('mysql');
const database = getConnection();

exports.dbWrite = (events, context, callback) => {

   database.connect(function (err) {
     if (err) {
          console.error('error connecting: ' + err.stack);
          return;
     }

     console.log('connected !');
});

db.end();

function getConnection() {
   let db = mysql.createConnection({
       host: process.env.DB_HOST,
       user: process.env.DB_USER,
       password: process.env.DB_PASS,
       database: process.env.DB_NAME
   });

   console.log('Host: ' + process.env.DB_HOST);
   console.log('User: ' + process.env.DB_USER);
   console.log('Database: ' + process.env.DB_NAME);

   console.log('Connecting to ' + process.env.DB_HOST + '...');

   return db;
}


问:
Get line number from preg_match_all()
I'm using PHP's preg_match_all() to search a string imported using file_get_contents(). The regex returns matches but I would like to know at which line number those matches are found. What's the best technique to achieve this?

I could read the file as an array and perform the regex for each line, but the problem is that my regex matches results across carriage returns (new lines).

答:
i think first of all, you need to read the $String into an array, each element stand for each line, and do look like this :</p>

```<code>$List=file($String);
for($i=0;$i<count($List),$i++){
if(preg_match_all()){;//your work here
echo $i;//echo the line number where the preg_match_all() works
}
}
</code>```

Title: Get line number from preg_match_all()

Body:
i think first of all, you need to read the $String into an array, each element stand for each line, and do look like this :

$List=file($String);
for($i=0;$i<count($List),$i++){
if(preg_match_all()){;//your work here
echo $i;//echo the line number where the preg_match_all() works
}
}


问:
Does GWT have richtextbox which show RTF type data?
I'm using GWT Richtextbox, But this widget shows values which are simple text or HTML formatted.
Is there any way to show RTF data in a GWT-Richtext or GWT-htmlEditor widget? Or is there a widget in other GWT libraries which will do this?</p>

答:
You could use RTFEditorKit in combination with HTMLEditorKit to convert between the two server-side or in an applet.  This way you can use GWT's rich text editor and output or input RTF.</p>

```<code>public static String getHtmlFromRtf(InputStream fi){
    Writer sOut = new StringWriter();
    DefaultStyledDocument doc = new DefaultStyledDocument();
    HTMLEditorKit htmlKit = new HTMLEditorKit();
    RTFEditorKit rtf = new RTFEditorKit();

    try
    {
        rtf.read( fi, doc, 0 );
        htmlKit.write(sOut, doc, 0, doc.getLength());
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    catch (BadLocationException e)
    {
        e.printStackTrace();
    }
    return sOut.toString();
}
</code>```

Body:
You could use RTFEditorKit in combination with HTMLEditorKit to convert between the two server-side or in an applet.  This way you can use GWT's rich text editor and output or input RTF.

public static String getHtmlFromRtf(InputStream fi){
    Writer sOut = new StringWriter();
    DefaultStyledDocument doc = new DefaultStyledDocument();
    HTMLEditorKit htmlKit = new HTMLEditorKit();
    RTFEditorKit rtf = new RTFEditorKit();

    try
    {
        rtf.read( fi, doc, 0 );
        htmlKit.write(sOut, doc, 0, doc.getLength());
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    catch (BadLocationException e)
    {
        e.printStackTrace();
    }
    return sOut.toString();
}


问:
rmarkdown: recursive chunk evaluation?
I would like to have a string produced by an R chunk in an rmarkdown document to be re-evaluated - is that possible? For demonstration purposes consider the following document:

```<code>---
params:
  B: 'test'
---

```{r simple, results='asis', echo=FALSE}
write(params[['B']], file = "")
```

```{r recursive-evaluation-questionmark, results='asis', echo=FALSE}
write(
  "How to get \"params[['B']]\" evaluated here? This \"`r params[['B']]`\" is
    expected to be \"test\" ...",
  file = "")
```
</code>```

Currently this produces the following when knitted:

```<code>test

How to get “params[[‘B’]]” evaluated here? This “r params[['B']]” is expected to be “test” …
</code>```

but I want:

```<code>test

How to get “params[[‘B’]]” evaluated here? This “test” is expected to be “test” …
</code>```

答:
You can't get knitr to treat R code as text, but you can solve the problem using pure R code.  I'd also recommend using cat() instead of write().  For your example,

```<code>write(
  paste0("How to get \"params[['B']]\" evaluated here? This \"", params[['B']], "\" is
  expected to be \"test\" ..."),
 file = "")
</code>```

or the simpler

```<code>cat("How to get \"params[['B']]\" evaluated here? This \"", params[['B']], "\" is
  expected to be \"test\" ...", sep = "")
</code>```

For more complicated macro-like substitutions, you may want to use the sub() or gsub() functions, e.g.

```<code>msg <- "How to get \"params[['B']]\" evaluated here? This \"%param%\" is
  expected to be \"test\" ..."
cat(sub("%param%", params[['B']], msg))
</code>```

Title: rmarkdown: recursive chunk evaluation?

Body:
I would like to have a string produced by an R chunk in an rmarkdown document to be re-evaluated - is that possible? For demonstration purposes consider the following document:

---
params:
  B: 'test'
---

```{r simple, results='asis', echo=FALSE}
write(params[['B']], file = "")
```

```{r recursive-evaluation-questionmark, results='asis', echo=FALSE}
write(
  "How to get \"params[['B']]\" evaluated here? This \"`r params[['B']]`\" is
    expected to be \"test\" ...",
  file = "")
```

Currently this produces the following when knitted:

test

How to get “params[[‘B’]]” evaluated here? This “r params[['B']]” is expected to be “test” …

but I want:

test

How to get “params[[‘B’]]” evaluated here? This “test” is expected to be “test” …

Body:
You can't get knitr to treat R code as text, but you can solve the problem using pure R code.  I'd also recommend using cat() instead of write().  For your example,

write(
  paste0("How to get \"params[['B']]\" evaluated here? This \"", params[['B']], "\" is
  expected to be \"test\" ..."),
 file = "")

or the simpler

cat("How to get \"params[['B']]\" evaluated here? This \"", params[['B']], "\" is
  expected to be \"test\" ...", sep = "")

For more complicated macro-like substitutions, you may want to use the sub() or gsub() functions, e.g.

msg <- "How to get \"params[['B']]\" evaluated here? This \"%param%\" is
  expected to be \"test\" ..."
cat(sub("%param%", params[['B']], msg))


问:
Completely disable ng-pick-datetime calendar input in an Angular form
I'm working on an Angular project which has a calendar picker in a form. I chose 'ng-pick-datetime' (npmjs.com/package/ng-pick-datetime) to get cross-browser calendar compatibility.

I've succesfully implemented the calendar. The issue is how to completely disable/block it (I need this when certain user is in the form). What happens right now is that the input field correctly gets disabled when [disabled] is true in the template tag, so no Date can be written in there.

BUT, there is a cross at the right part of the field that never gets disabled, so the user is always able to click that cross and erase the Date, setting the input at null, whenever the calendar is disabled or not.

My html template code is as follows:

```<code><div class="input-control col-sm-6" [class.has-error]="endDate.invalid && endDate.dirty">
   <label class="control-label" for="endDate">End date *</label>
   <owl-date-time
      [(ngModel)]="data.endDate"
      [dateFormat]="'DD-MM-YYYY'"
      [inputId]="'endDate'"
      [placeHolder]="'dd-mm-aaaa'"
      [type]="'calendar'"
      [autoClose]="'true'"
      id="endDate"
      name="endDate"
      #endDate="ngModel"
      [disabled]="!paramsService.isSolicitante()"
      required="required">
    </owl-date-time >
</div>
</code>```

If any other code / info is needed I'll provide it quickly, but I think it's mainly a template problem.

Screenshot ng-pick-datetime cross

答:
Looks like there is [hideClearButton] property, can be set using boolean in the docs:

When specified to true, the picker's input clear icon would be hidden.

Body:
I'm working on an Angular project which has a calendar picker in a form. I chose 'ng-pick-datetime' (npmjs.com/package/ng-pick-datetime) to get cross-browser calendar compatibility.

I've succesfully implemented the calendar. The issue is how to completely disable/block it (I need this when certain user is in the form). What happens right now is that the input field correctly gets disabled when [disabled] is true in the template tag, so no Date can be written in there.

BUT, there is a cross at the right part of the field that never gets disabled, so the user is always able to click that cross and erase the Date, setting the input at null, whenever the calendar is disabled or not.

My html template code is as follows:

   End date *
   <owl-date-time
      [(ngModel)]="data.endDate"
      [dateFormat]="'DD-MM-YYYY'"
      [inputId]="'endDate'"
      [placeHolder]="'dd-mm-aaaa'"
      [type]="'calendar'"
      [autoClose]="'true'"
      id="endDate"
      name="endDate"
      #endDate="ngModel"
      [disabled]="!paramsService.isSolicitante()"
      required="required">
    </owl-date-time >

If any other code / info is needed I'll provide it quickly, but I think it's mainly a template problem.

Screenshot ng-pick-datetime cross


问:
Efficient way of creating recursive paths Python
I need a simple function to create a path in Python where the parent may or may not exist.

From python documentation os.makedirs will fail if one of the parents exists.

I have written the below method as which works by makes as many sub directories as necessary.

Does this look efficient?

```<code>def create_path(path):
    import os.path as os_path
    paths_to_create = []
    while not os_path.lexists(path):
        paths_to_create.insert(0, path)
        head,tail = os_path.split(path)
        if len(tail.strip())==0: # Just incase path ends with a / or \
            path = head
            head,tail = os_path.split(path)
        path = head

    for path in paths_to_create:
        os.mkdir(path)
</code>```

答:
This is an old thread, but I was not satisfied with the solutions provided since they were mostly too complicated for a simple task.

From the available functions in the library I believe the cleanest we can do is:

```<code>os.path.isdir("mydir") or os.makedirs("mydir")
</code>```

Body:
I need a simple function to create a path in Python where the parent may or may not exist.

From python documentation os.makedirs will fail if one of the parents exists.

I have written the below method as which works by makes as many sub directories as necessary.

Does this look efficient?

def create_path(path):
    import os.path as os_path
    paths_to_create = []
    while not os_path.lexists(path):
        paths_to_create.insert(0, path)
        head,tail = os_path.split(path)
        if len(tail.strip())==0: # Just incase path ends with a / or \
            path = head
            head,tail = os_path.split(path)
        path = head

    for path in paths_to_create:
        os.mkdir(path)

Body:
This is an old thread, but I was not satisfied with the solutions provided since they were mostly too complicated for a simple task.

From the available functions in the library I believe the cleanest we can do is:

os.path.isdir("mydir") or os.makedirs("mydir")


问:
Auto find and replace Google Sheet every time I run the script
I find this code but it doesn't work like expected.

```<code>    function onOpen() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getRange("'Feuille 1'!1:1137");//This line is most likely the culprit
  var to_replace = ".";
  var replace_with = ",";
  replaceInSheet(sheet,range, to_replace, replace_with);
}

function replaceInSheet(sheet, range, to_replace, replace_with) {
  //Confirm
  var ui = SpreadsheetApp.getUi();
  var spread = SpreadsheetApp.getActiveSpreadsheet();

  var result = ui.alert(
     "Will update " + to_replace + " to " + replace_with + " ",
     'Are you sure you want to continue?',
      ui.ButtonSet.YES_NO);

  // Process the user's response.
  if (result == ui.Button.YES) {

    // User clicked "Yes".
    spread.toast("Will update " + to_replace + " to " + replace_with + " ", "ALERT");

    var data  = range.getValues();//I think error is occurring here

    var oldValue="";
    var newValue="";
    var cellsChanged = 0;

    for (var row=0; row<data.length; row++) {
      for (var item=0; item<data[row].length; item++) {
        oldValue = data[row][item];
        newValue = data[row][item].replace(to_replace, replace_with);
        if (oldValue!=newValue)
        {
          cellsChanged++;
          data[row][item] = newValue;
        }
      }
    }
    range.setValues(data);
    spread.toast(cellsChanged + " cells changed", "STATUS");
  }
  else {
    // User clicked "No" or X in the title bar.
    spread.toast("No action taken", "ABANDONED");
  }
}
</code>```

I got this error :
TypeError: Impossible d'appeler la méthode "getValues" de undefined. (ligne 25, fichier "Code")

Could you help me I'm a noob
Regards

答:
So apparently this line has a problem:

```<code>var range = sheet.getRange("'Feuille 1'!1:1137");
</code>```

The range is the problem it should be something like 'Sheet1!A1:A1137'.

So may be this will work: var range = sheet.getRange("'Feuille 1'!A1:A1137");

Since I can't see your sheet you will have to determine the appropriate range.

Body:
I find this code but it doesn't work like expected.

    function onOpen() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getRange("'Feuille 1'!1:1137");//This line is most likely the culprit
  var to_replace = ".";
  var replace_with = ",";
  replaceInSheet(sheet,range, to_replace, replace_with);
}

function replaceInSheet(sheet, range, to_replace, replace_with) {
  //Confirm
  var ui = SpreadsheetApp.getUi();
  var spread = SpreadsheetApp.getActiveSpreadsheet();

  var result = ui.alert(
     "Will update " + to_replace + " to " + replace_with + " ",
     'Are you sure you want to continue?',
      ui.ButtonSet.YES_NO);

  // Process the user's response.
  if (result == ui.Button.YES) {

    // User clicked "Yes".
    spread.toast("Will update " + to_replace + " to " + replace_with + " ", "ALERT");

    var data  = range.getValues();//I think error is occurring here

    var oldValue="";
    var newValue="";
    var cellsChanged = 0;

    for (var row=0; row<data.length; row++) {
      for (var item=0; item<data[row].length; item++) {
        oldValue = data[row][item];
        newValue = data[row][item].replace(to_replace, replace_with);
        if (oldValue!=newValue)
        {
          cellsChanged++;
          data[row][item] = newValue;
        }
      }
    }
    range.setValues(data);
    spread.toast(cellsChanged + " cells changed", "STATUS");
  }
  else {
    // User clicked "No" or X in the title bar.
    spread.toast("No action taken", "ABANDONED");
  }
}

I got this error :
TypeError: Impossible d'appeler la méthode "getValues" de undefined. (ligne 25, fichier "Code")

Could you help me I'm a noob
Regards

Body:
So apparently this line has a problem:

var range = sheet.getRange("'Feuille 1'!1:1137");

The range is the problem it should be something like 'Sheet1!A1:A1137'.

So may be this will work: var range = sheet.getRange("'Feuille 1'!A1:A1137");

Since I can't see your sheet you will have to determine the appropriate range.


问:
Removing an item for a list without reducing the total number
Here we go again. So what I am trying to do is, let's say I have a list like this:

```<code>List = ['one','two','three']
</code>```

And they are all assigned to numbers 0,1,2 for example:

```<code>'one': 0, 'two': 1, 'three': 2
</code>```

What I want to do now is I want to remove an item from my list... let's say two

```<code>List.remove('two')
</code>```

But if I do this, 'three' goes into the place of two and the total amount decreases by one. Is there a way I can remove two, but still keep the total amount of objects in a list, with the ones being removed just being replaced with 'None' or something similar?

答:
You can replace it with None or with an empty string '' using:

```<code>List[List.index('two')] = None
# List = ['one', None, 'three']
</code>```

or

```<code>List[List.index('two')] = ''
# List = ['one', '', 'three']
</code>```

Body:
Here we go again. So what I am trying to do is, let's say I have a list like this:

List = ['one','two','three']

And they are all assigned to numbers 0,1,2 for example:

'one': 0, 'two': 1, 'three': 2

What I want to do now is I want to remove an item from my list... let's say two

List.remove('two')

But if I do this, 'three' goes into the place of two and the total amount decreases by one. Is there a way I can remove two, but still keep the total amount of objects in a list, with the ones being removed just being replaced with 'None' or something similar?

Body:
You can replace it with None or with an empty string '' using:

List[List.index('two')] = None
# List = ['one', None, 'three']

or

List[List.index('two')] = ''
# List = ['one', '', 'three']


问:
How do I remove all events of a type from an element
I want to remove ALL click events from a certain DOM element. How? There is removeEventListener, but that requires the attached function.

Is there a way to remove ALL attached events of one type (or just ALL, that's fine too)?

答:
Unfortunately, there is no method in the DOM specification that can list or remove event listeners without already knowing the listener function.

The best you can do is to create a new element of the same type, copy all properties and move children from the original element to the new one.


问:
Count of primes in integer factorization
I wonder if there are any algorithms that can count or predict the number of primes in integer factorization. Not to find them, just compute their quantity. For example, for integer 198, the output is 4, because 198 contains 4 primes (2, 3, 3, 11). Is this possible in some efficient way? Some ideas?</p>

答: The function that computes the number of distinct prime factors of an integer is known to number theorists as the ω (omega) function, so ω(198) = 3 for the primes 2, 3 and 11 (multiplicities of primes are ignored in computing ω). It can be computed by an inverse Möbius transform. A good place to start reading is MathWorld. Be prepared for some hairy greek-letter math.</p>


问:
how to launch sonarqube?
for my studies I need to install sonarqube on an ubuntu server.

I installed it following this tutorial : http://www.naturalborncoder.com/methodology/2015/05/27/sonarqube-on-ubuntu-14-04/ (I stopped before the proxying part) but I can't access to 127.0.0.1:9000. From the logs it look like there is a problem with elasticsearch when i launch sonarcube.

/opt/sonar/log/sonar.log :

--> Wrapper Started as Daemon
Launching a JVM...
Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
  Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.

2017.11.14 18:21:11 INFO  app[][o.s.a.AppFileSystem] Cleaning or creating temp directory /opt/sonar/temp
2017.11.14 18:21:11 INFO  app[][o.s.a.es.EsSettings] Elasticsearch listening on /127.0.0.1:9001
2017.11.14 18:21:11 INFO  app[][o.s.a.p.ProcessLauncherImpl] Launch process[[key='es', ipcIndex=1, logFilenamePrefix=es]] from [/opt/sonar/elasticsearch]: /opt/sonar/elasticsearch/bin/elasticsearch -Epath.conf=/opt/sonar/temp/conf/es
2017.11.14 18:21:11 INFO  app[][o.s.a.SchedulerImpl] Waiting for Elasticsearch to be up and running
2017.11.14 18:21:13 INFO  app[][o.e.p.PluginsService] no modules loaded
2017.11.14 18:21:13 INFO  app[][o.e.p.PluginsService] loaded plugin [org.elasticsearch.transport.Netty4Plugin]
java.security.policy: error adding Entry:
        java.net.MalformedURLException: no protocol: ${codebase.elasticsearch-rest-client}
java.security.policy: error adding Entry:
        java.net.MalformedURLException: no protocol: ${codebase.httpasyncclient-4.1.2.jar}
java.security.policy: error adding Entry:
        java.net.MalformedURLException: no protocol: ${codebase.netty-common-4.1.13.Final.jar}
java.security.policy: error adding Entry:
        java.net.MalformedURLException: no protocol: ${codebase.netty-transport-4.1.13.Final.jar}
java.security.policy: error adding Entry:
        java.net.MalformedURLException: no protocol: ${codebase.securesm-1.1.jar}
java.security.policy: error adding Entry:
        java.net.MalformedURLException: no protocol: ${codebase.lucene-core-6.6.1.jar}
java.security.policy: error adding Entry:
        java.net.MalformedURLException: no protocol: ${codebase.lucene-misc-6.6.1.jar}
2017.11.14 18:21:27 WARN  app[][o.s.a.p.AbstractProcessMonitor] Process exited with exit value [es]: 1
2017.11.14 18:21:27 INFO  app[][o.s.a.SchedulerImpl] Process [es] is stopped
2017.11.14 18:21:27 INFO  app[][o.s.a.SchedulerImpl] SonarQube is stopped
<-- Wrapper Stopped```
</div>
</div>
</p>

<p>/opt/sonar/logs/es.log :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>2017.11.14 18:21:24 INFO  es[][o.e.n.Node] initializing ...
2017.11.14 18:21:24 INFO  es[][o.e.e.NodeEnvironment] using [1] data paths, mounts [[/ (/dev/vda1)]], net usable_space [5.7gb], net total_space [9.6gb], spins? [possibly], types [ext4]
2017.11.14 18:21:24 INFO  es[][o.e.e.NodeEnvironment] heap size [503.6mb], compressed ordinary object pointers [true]
2017.11.14 18:21:24 INFO  es[][o.e.n.Node] node name [sonarqube], node ID [3PxDbRbDQ4-M_YDsv25FHg]
2017.11.14 18:21:24 INFO  es[][o.e.n.Node] version[5.6.3], pid[8661], build[1a2f265/2017-10-06T20:33:39.012Z], OS[Linux/4.4.0-22-generic/amd64], JVM[Oracle Corporation/OpenJDK 64-Bit Server VM/9-internal/9-internal+0-2016-04-14-195246.b$
2017.11.14 18:21:24 INFO  es[][o.e.n.Node] JVM arguments [-XX:+UseConcMarkSweepGC, -XX:CMSInitiatingOccupancyFraction=75, -XX:+UseCMSInitiatingOccupancyOnly, -XX:+AlwaysPreTouch, -Xss1m, -Djava.awt.headless=true, -Dfile.encoding=UTF-8, $
2017.11.14 18:21:26 INFO  es[][o.e.p.PluginsService] loaded module [aggs-matrix-stats]
2017.11.14 18:21:26 INFO  es[][o.e.p.PluginsService] loaded module [ingest-common]
2017.11.14 18:21:26 INFO  es[][o.e.p.PluginsService] loaded module [parent-join]
2017.11.14 18:21:26 INFO  es[][o.e.p.PluginsService] loaded module [percolator]
2017.11.14 18:21:26 INFO  es[][o.e.p.PluginsService] loaded module [reindex]
2017.11.14 18:21:26 INFO  es[][o.e.p.PluginsService] loaded module [transport-netty4]
2017.11.14 18:21:26 INFO  es[][o.e.p.PluginsService] no plugins loaded
2017.11.14 18:21:27 ERROR es[][o.e.b.ElasticsearchUncaughtExceptionHandler] fatal error in thread [main], exiting
java.lang.ExceptionInInitializerError: null
        at org.apache.lucene.analysis.miscellaneous.StemmerOverrideFilter$Builder.build(StemmerOverrideFilter.java:205) ~[lucene-analyzers-common-6.6.1.jar:6.6.1 9aa465a89b64ff2dabe7b4d50c472de32c298683 - varunthacker - 2017-08-29 21:55$
        at org.apache.lucene.analysis.nl.DutchAnalyzer.<init>(DutchAnalyzer.java:133) ~[lucene-analyzers-common-6.6.1.jar:6.6.1 9aa465a89b64ff2dabe7b4d50c472de32c298683 - varunthacker - 2017-08-29 21:55:17]
        at org.apache.lucene.analysis.nl.DutchAnalyzer.<init>(DutchAnalyzer.java:106) ~[lucene-analyzers-common-6.6.1.jar:6.6.1 9aa465a89b64ff2dabe7b4d50c472de32c298683 - varunthacker - 2017-08-29 21:55:17]
        at org.elasticsearch.indices.analysis.PreBuiltAnalyzers$20.create(PreBuiltAnalyzers.java:246) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.indices.analysis.PreBuiltAnalyzers.getAnalyzer(PreBuiltAnalyzers.java:487) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.index.analysis.AnalysisRegistry$PrebuiltAnalysis.<init>(AnalysisRegistry.java:407) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.index.analysis.AnalysisRegistry$PrebuiltAnalysis.<init>(AnalysisRegistry.java:392) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.index.analysis.AnalysisRegistry.<init>(AnalysisRegistry.java:62) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.indices.analysis.AnalysisModule.<init>(AnalysisModule.java:177) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.node.Node.<init>(Node.java:340) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.node.Node.<init>(Node.java:245) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.bootstrap.Bootstrap$5.<init>(Bootstrap.java:233) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:233) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:342) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:132) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:123) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.cli.EnvironmentAwareCommand.execute(EnvironmentAwareCommand.java:70) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:134) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.cli.Command.main(Command.java:90) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:91) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:84) ~[elasticsearch-5.6.3.jar:5.6.3]
Caused by: java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:468) ~[?:?]
        at java.security.AccessController.checkPermission(AccessController.java:894) ~[?:?]
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:541) ~[?:?]
        at java.lang.Class.checkMemberAccess(Class.java:2584) ~[?:?]
        at java.lang.Class.getDeclaredFields(Class.java:2092) ~[?:?]
        at org.apache.lucene.util.RamUsageEstimator$1.run(RamUsageEstimator.java:339) ~[lucene-core-6.6.1.jar:6.6.1 9aa465a89b64ff2dabe7b4d50c472de32c298683 - varunthacker - 2017-08-29 21:54:39]
        at org.apache.lucene.util.RamUsageEstimator$1.run(RamUsageEstimator.java:336) ~[lucene-core-6.6.1.jar:6.6.1 9aa465a89b64ff2dabe7b4d50c472de32c298683 - varunthacker - 2017-08-29 21:54:39]
        at java.security.AccessController.doPrivileged(Native Method) ~[?:?]
        at org.apache.lucene.util.RamUsageEstimator.shallowSizeOfInstance(RamUsageEstimator.java:336) ~[lucene-core-6.6.1.jar:6.6.1 9aa465a89b64ff2dabe7b4d50c472de32c298683 - varunthacker - 2017-08-29 21:54:39]
        at org.apache.lucene.util.RamUsageEstimator.shallowSizeOf(RamUsageEstimator.java:313) ~[lucene-core-6.6.1.jar:6.6.1 9aa465a89b64ff2dabe7b4d50c472de32c298683 - varunthacker - 2017-08-29 21:54:39]
        at org.apache.lucene.util.fst.ByteSequenceOutputs.<clinit>(ByteSequenceOutputs.java:154) ~[lucene-core-6.6.1.jar:6.6.1 9aa465a89b64ff2dabe7b4d50c472de32c298683 - varunthacker - 2017-08-29 21:54:39]
        ... 21 more</code>```

java -version :

```<code>OpenJDK Runtime Environment (build 1.8.0_151-8u151-b12-0ubuntu0.16.04.2-b12)
OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)
</code>```

sonarqube version : 6.7

I launch sonarqube as root so there should not have problem coming from access right.

All the post that i find about this error where related with openjdk9 but this is not my case.

Do you have an idea of what is happening ?

答:
SonarQube 6.7 includes an upgraded version of Elasticsearch which cannot be run as root. Thus, SonarQube can no longer be run as root.

The blog post you followed seems to recommend / assume that you're running as root. To not start SonarQube as root, simply end your su session, or log back in as yourself to start the process. Note that you'll need to make sure the user you are starting SonarQube as has 7 (read, write, execute) on the SonarQube directory, recursively, and 6 (read, write) on the log files if they already exist.

Title: how to launch sonarqube?

Body:
for my studies I need to install sonarqube on an ubuntu server.

I installed it following this tutorial : http://www.naturalborncoder.com/methodology/2015/05/27/sonarqube-on-ubuntu-14-04/ (I stopped before the proxying part) but I can't access to 127.0.0.1:9000. From the logs it look like there is a problem with elasticsearch when i launch sonarcube.

/opt/sonar/log/sonar.log :

--> Wrapper Started as Daemon
Launching a JVM...
Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
  Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.

2017.11.14 18:21:11 INFO  app[][o.s.a.AppFileSystem] Cleaning or creating temp directory /opt/sonar/temp
2017.11.14 18:21:11 INFO  app[][o.s.a.es.EsSettings] Elasticsearch listening on /127.0.0.1:9001
2017.11.14 18:21:11 INFO  app[][o.s.a.p.ProcessLauncherImpl] Launch process[[key='es', ipcIndex=1, logFilenamePrefix=es]] from [/opt/sonar/elasticsearch]: /opt/sonar/elasticsearch/bin/elasticsearch -Epath.conf=/opt/sonar/temp/conf/es
2017.11.14 18:21:11 INFO  app[][o.s.a.SchedulerImpl] Waiting for Elasticsearch to be up and running
2017.11.14 18:21:13 INFO  app[][o.e.p.PluginsService] no modules loaded
2017.11.14 18:21:13 INFO  app[][o.e.p.PluginsService] loaded plugin [org.elasticsearch.transport.Netty4Plugin]
java.security.policy: error adding Entry:
        java.net.MalformedURLException: no protocol: ${codebase.elasticsearch-rest-client}
java.security.policy: error adding Entry:
        java.net.MalformedURLException: no protocol: ${codebase.httpasyncclient-4.1.2.jar}
java.security.policy: error adding Entry:
        java.net.MalformedURLException: no protocol: ${codebase.netty-common-4.1.13.Final.jar}
java.security.policy: error adding Entry:
        java.net.MalformedURLException: no protocol: ${codebase.netty-transport-4.1.13.Final.jar}
java.security.policy: error adding Entry:
        java.net.MalformedURLException: no protocol: ${codebase.securesm-1.1.jar}
java.security.policy: error adding Entry:
        java.net.MalformedURLException: no protocol: ${codebase.lucene-core-6.6.1.jar}
java.security.policy: error adding Entry:
        java.net.MalformedURLException: no protocol: ${codebase.lucene-misc-6.6.1.jar}
2017.11.14 18:21:27 WARN  app[][o.s.a.p.AbstractProcessMonitor] Process exited with exit value [es]: 1
2017.11.14 18:21:27 INFO  app[][o.s.a.SchedulerImpl] Process [es] is stopped
2017.11.14 18:21:27 INFO  app[][o.s.a.SchedulerImpl] SonarQube is stopped
<-- Wrapper Stopped

/opt/sonar/logs/es.log :

2017.11.14 18:21:24 INFO  es[][o.e.n.Node] initializing ...
2017.11.14 18:21:24 INFO  es[][o.e.e.NodeEnvironment] using [1] data paths, mounts [[/ (/dev/vda1)]], net usable_space [5.7gb], net total_space [9.6gb], spins? [possibly], types [ext4]
2017.11.14 18:21:24 INFO  es[][o.e.e.NodeEnvironment] heap size [503.6mb], compressed ordinary object pointers [true]
2017.11.14 18:21:24 INFO  es[][o.e.n.Node] node name [sonarqube], node ID [3PxDbRbDQ4-M_YDsv25FHg]
2017.11.14 18:21:24 INFO  es[][o.e.n.Node] version[5.6.3], pid[8661], build[1a2f265/2017-10-06T20:33:39.012Z], OS[Linux/4.4.0-22-generic/amd64], JVM[Oracle Corporation/OpenJDK 64-Bit Server VM/9-internal/9-internal+0-2016-04-14-195246.b$
2017.11.14 18:21:24 INFO  es[][o.e.n.Node] JVM arguments [-XX:+UseConcMarkSweepGC, -XX:CMSInitiatingOccupancyFraction=75, -XX:+UseCMSInitiatingOccupancyOnly, -XX:+AlwaysPreTouch, -Xss1m, -Djava.awt.headless=true, -Dfile.encoding=UTF-8, $
2017.11.14 18:21:26 INFO  es[][o.e.p.PluginsService] loaded module [aggs-matrix-stats]
2017.11.14 18:21:26 INFO  es[][o.e.p.PluginsService] loaded module [ingest-common]
2017.11.14 18:21:26 INFO  es[][o.e.p.PluginsService] loaded module [parent-join]
2017.11.14 18:21:26 INFO  es[][o.e.p.PluginsService] loaded module [percolator]
2017.11.14 18:21:26 INFO  es[][o.e.p.PluginsService] loaded module [reindex]
2017.11.14 18:21:26 INFO  es[][o.e.p.PluginsService] loaded module [transport-netty4]
2017.11.14 18:21:26 INFO  es[][o.e.p.PluginsService] no plugins loaded
2017.11.14 18:21:27 ERROR es[][o.e.b.ElasticsearchUncaughtExceptionHandler] fatal error in thread [main], exiting
java.lang.ExceptionInInitializerError: null
        at org.apache.lucene.analysis.miscellaneous.StemmerOverrideFilter$Builder.build(StemmerOverrideFilter.java:205) ~[lucene-analyzers-common-6.6.1.jar:6.6.1 9aa465a89b64ff2dabe7b4d50c472de32c298683 - varunthacker - 2017-08-29 21:55$
        at org.apache.lucene.analysis.nl.DutchAnalyzer.<init>(DutchAnalyzer.java:133) ~[lucene-analyzers-common-6.6.1.jar:6.6.1 9aa465a89b64ff2dabe7b4d50c472de32c298683 - varunthacker - 2017-08-29 21:55:17]
        at org.apache.lucene.analysis.nl.DutchAnalyzer.<init>(DutchAnalyzer.java:106) ~[lucene-analyzers-common-6.6.1.jar:6.6.1 9aa465a89b64ff2dabe7b4d50c472de32c298683 - varunthacker - 2017-08-29 21:55:17]
        at org.elasticsearch.indices.analysis.PreBuiltAnalyzers$20.create(PreBuiltAnalyzers.java:246) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.indices.analysis.PreBuiltAnalyzers.getAnalyzer(PreBuiltAnalyzers.java:487) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.index.analysis.AnalysisRegistry$PrebuiltAnalysis.<init>(AnalysisRegistry.java:407) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.index.analysis.AnalysisRegistry$PrebuiltAnalysis.<init>(AnalysisRegistry.java:392) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.index.analysis.AnalysisRegistry.<init>(AnalysisRegistry.java:62) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.indices.analysis.AnalysisModule.<init>(AnalysisModule.java:177) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.node.Node.<init>(Node.java:340) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.node.Node.<init>(Node.java:245) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.bootstrap.Bootstrap$5.<init>(Bootstrap.java:233) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:233) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:342) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:132) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:123) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.cli.EnvironmentAwareCommand.execute(EnvironmentAwareCommand.java:70) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:134) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.cli.Command.main(Command.java:90) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:91) ~[elasticsearch-5.6.3.jar:5.6.3]
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:84) ~[elasticsearch-5.6.3.jar:5.6.3]
Caused by: java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:468) ~[?:?]
        at java.security.AccessController.checkPermission(AccessController.java:894) ~[?:?]
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:541) ~[?:?]
        at java.lang.Class.checkMemberAccess(Class.java:2584) ~[?:?]
        at java.lang.Class.getDeclaredFields(Class.java:2092) ~[?:?]
        at org.apache.lucene.util.RamUsageEstimator$1.run(RamUsageEstimator.java:339) ~[lucene-core-6.6.1.jar:6.6.1 9aa465a89b64ff2dabe7b4d50c472de32c298683 - varunthacker - 2017-08-29 21:54:39]
        at org.apache.lucene.util.RamUsageEstimator$1.run(RamUsageEstimator.java:336) ~[lucene-core-6.6.1.jar:6.6.1 9aa465a89b64ff2dabe7b4d50c472de32c298683 - varunthacker - 2017-08-29 21:54:39]
        at java.security.AccessController.doPrivileged(Native Method) ~[?:?]
        at org.apache.lucene.util.RamUsageEstimator.shallowSizeOfInstance(RamUsageEstimator.java:336) ~[lucene-core-6.6.1.jar:6.6.1 9aa465a89b64ff2dabe7b4d50c472de32c298683 - varunthacker - 2017-08-29 21:54:39]
        at org.apache.lucene.util.RamUsageEstimator.shallowSizeOf(RamUsageEstimator.java:313) ~[lucene-core-6.6.1.jar:6.6.1 9aa465a89b64ff2dabe7b4d50c472de32c298683 - varunthacker - 2017-08-29 21:54:39]
        at org.apache.lucene.util.fst.ByteSequenceOutputs.<clinit>(ByteSequenceOutputs.java:154) ~[lucene-core-6.6.1.jar:6.6.1 9aa465a89b64ff2dabe7b4d50c472de32c298683 - varunthacker - 2017-08-29 21:54:39]
        ... 21 more

java -version :

OpenJDK Runtime Environment (build 1.8.0_151-8u151-b12-0ubuntu0.16.04.2-b12)
OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)

sonarqube version : 6.7

I launch sonarqube as root so there should not have problem coming from access right.

All the post that i find about this error where related with openjdk9 but this is not my case.

Do you have an idea of what is happening ?


问:
How to replace relective method access by Java 1.8 functions?
Problem: We need to get a (String) key for different classes of objects.
For expendability we want to configure the Method to use to get the key String – instead of implementing many if-else with intanceOf…

Naive solution (with example data) is:

```<code>public static String getKey(Object object, Map<Class<?>, Method> keySources) {
    Method source = keySources.get(object.getClass());

    if (source == null) {
        return null;
    }

    try {
        return (String) source.invoke(object);
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        throw new RuntimeException("Error at 'invoke': " + e.getMessage(), e);
    }
}

public static void main(String[] args) {
    Map<Class<?>, Method> keySources = new HashMap<>();

    try {
        keySources.put(String.class, String.class.getMethod("toString"));
        keySources.put(Thread.class, Thread.class.getMethod("getName"));
    } catch (NoSuchMethodException | SecurityException e) {
        throw new RuntimeException("Error at 'getMethod': " + e.getMessage(), e);
    }

    System.out.println(getKey("test", keySources));
    System.out.println(getKey(new Thread("name"), keySources));
}
</code>```

Desired solution would be like:

```<code>public static String getKey(Object object, Map<Class<?>, Function<Object, String>> keySources) {
    Function<Object, String> source = keySources.get(object.getClass());

    if (source == null) {
        return null;
    }

    return source.apply(object);
}

public static void main(String[] args) {
    Map<Class<?>, Function<Object, String>> keySources = new HashMap<>();

    keySources.put(String.class, String::toString);
    keySources.put(Thread.class, Thread::getName);

    System.out.println(getKey("test", keySources));
    System.out.println(getKey(new Thread("name"), keySources));
}
</code>```

But String::toString is giving compilation error: The type String does not define toString(Object) that is applicable here

Constraints: We cannot modify the classes since they were generated.

答:
I managed to get your code to pass compilation and run. I'm not sure why it works with lambda expressions but not with method references.

Perhaps there are better ways to do this.

```<code>public static <T> String getKey(T object, Map<Class<?>, Function<? extends Object, String>> keySources)
{
    Function<T, String> source = (Function<T, String>) keySources.get(object.getClass());

    if (source == null) {
        return null;
    }

    return source.apply(object);
}

public static void main (java.lang.String[] args) throws Exception
{
    Map<Class<?>, Function<? extends Object, String>> keySources = new HashMap<>();

    keySources.put(String.class, s -> s.toString());
    keySources.put(Thread.class, (Thread t) -> t.getName());

    System.out.println(getKey("test", keySources));
    System.out.println(getKey(new Thread("name"), keySources));
}
</code>```

Body:
Problem: We need to get a (String) key for different classes of objects.
For expendability we want to configure the Method to use to get the key String – instead of implementing many if-else with intanceOf…

Naive solution (with example data) is:

public static String getKey(Object object, Map<Class<?>, Method> keySources) {
    Method source = keySources.get(object.getClass());

    if (source == null) {
        return null;
    }

    try {
        return (String) source.invoke(object);
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        throw new RuntimeException("Error at 'invoke': " + e.getMessage(), e);
    }
}

public static void main(String[] args) {
    Map<Class<?>, Method> keySources = new HashMap<>();

    try {
        keySources.put(String.class, String.class.getMethod("toString"));
        keySources.put(Thread.class, Thread.class.getMethod("getName"));
    } catch (NoSuchMethodException | SecurityException e) {
        throw new RuntimeException("Error at 'getMethod': " + e.getMessage(), e);
    }

    System.out.println(getKey("test", keySources));
    System.out.println(getKey(new Thread("name"), keySources));
}

Desired solution would be like:

public static String getKey(Object object, Map<Class<?>, Function<Object, String>> keySources) {
    Function<Object, String> source = keySources.get(object.getClass());

    if (source == null) {
        return null;
    }

    return source.apply(object);
}

public static void main(String[] args) {
    Map<Class<?>, Function<Object, String>> keySources = new HashMap<>();

    keySources.put(String.class, String::toString);
    keySources.put(Thread.class, Thread::getName);

    System.out.println(getKey("test", keySources));
    System.out.println(getKey(new Thread("name"), keySources));
}

But String::toString is giving compilation error: The type String does not define toString(Object) that is applicable here

Constraints: We cannot modify the classes since they were generated.

Body:
I managed to get your code to pass compilation and run. I'm not sure why it works with lambda expressions but not with method references.

Perhaps there are better ways to do this.

public static <T> String getKey(T object, Map<Class<?>, Function<? extends Object, String>> keySources)
{
    Function<T, String> source = (Function<T, String>) keySources.get(object.getClass());

    if (source == null) {
        return null;
    }

    return source.apply(object);
}

public static void main (java.lang.String[] args) throws Exception
{
    Map<Class<?>, Function<? extends Object, String>> keySources = new HashMap<>();

    keySources.put(String.class, s -> s.toString());
    keySources.put(Thread.class, (Thread t) -> t.getName());

    System.out.println(getKey("test", keySources));
    System.out.println(getKey(new Thread("name"), keySources));
}