问:
Reading text file using fscanf in octave / matlab into cell array
I have a comma delimited single text file with strings and integers that I'm trying to import into a cell array.  I then want to export it to several files based on the same Resonance Freq. and add text to the filename row

This is a sample of the text file to import: (please note the file will be much larger then this)

```<code>Resonance Freq,number,Filename,time,fs,Split-3675,Session Num
277.912902832031250,1,p000001,00:00:01,44100,3675,0
123.912902832031250,2,p000002,00:00:02,44100,3675,2
277.912902832031250,3,p000003,00:00:03,44100,3675,0
277.912902832031250,4,p000001,00:00:01,44100,3675,1
343.912902832031250,5,p000002,00:00:02,44100,3675,0
277.912902832031250,6,p000003,00:00:03,44100,3675,4
</code>```

And this is the exported text files I want created (text file1)

```<code>277.912902832031250,1,/tmp/p000001.wav,00:00:01,44100,3675,0
277.912902832031250,3,/tmp/p000003.wav,00:00:03,44100,3675,0
277.912902832031250,4,/tmp/p000001.wav,00:00:01,44100,3675,1
</code>```

And this is the exported text files I want created (text file2)

```<code>123.912902832031250,2,/tmp/p000002.wav,00:00:02,44100,3675,2
</code>```

And this is the exported text files I want created (text file3)

```<code>343.912902832031250,5,/tmp/p000002.wavadded ,00:00:02,44100,3675,0
</code>```

I'm having a problem with fscanf and using comma delimited data

```<code>fid = fopen('/tmp/freq_range_color_coded.txt');
m_s = fscanf(fid,'%f %f %s %s %f %f %f');
fclose(fid);
</code>```

when I access a cell like m_s(1,2) I get back a single letter instead of a field.  How can I get it so when I type m_s(1,2) I get back the whole field example

m_s(2,1) should give me
  277.912902832031250

thanks

PS I'm using  octave and textscan is not compatible with it.

答: it looks like octave textscan is not fully compatible with matlab. strread and textscan in Octave 3.4.0 are not fully compatible with their implementations in Matlab 2009b (and probably later versions as well). For instance, the N=-1 option (repeat reading format until end of string) is not implemented in Octave 3.4.0 . Using a value of N=a positive integer (read format N times) does work the same as in Matlab. I'll have to use fscanf but can it use delimiters</p>

Body:
I have a comma delimited single text file with strings and integers that I'm trying to import into a cell array.  I then want to export it to several files based on the same Resonance Freq. and add text to the filename row

This is a sample of the text file to import: (please note the file will be much larger then this)

Resonance Freq,number,Filename,time,fs,Split-3675,Session Num
277.912902832031250,1,p000001,00:00:01,44100,3675,0
123.912902832031250,2,p000002,00:00:02,44100,3675,2
277.912902832031250,3,p000003,00:00:03,44100,3675,0
277.912902832031250,4,p000001,00:00:01,44100,3675,1
343.912902832031250,5,p000002,00:00:02,44100,3675,0
277.912902832031250,6,p000003,00:00:03,44100,3675,4

And this is the exported text files I want created (text file1)

277.912902832031250,1,/tmp/p000001.wav,00:00:01,44100,3675,0
277.912902832031250,3,/tmp/p000003.wav,00:00:03,44100,3675,0
277.912902832031250,4,/tmp/p000001.wav,00:00:01,44100,3675,1

And this is the exported text files I want created (text file2)

123.912902832031250,2,/tmp/p000002.wav,00:00:02,44100,3675,2

And this is the exported text files I want created (text file3)

343.912902832031250,5,/tmp/p000002.wavadded ,00:00:02,44100,3675,0

I'm having a problem with fscanf and using comma delimited data

fid = fopen('/tmp/freq_range_color_coded.txt');
m_s = fscanf(fid,'%f %f %s %s %f %f %f');
fclose(fid);

when I access a cell like m_s(1,2) I get back a single letter instead of a field.  How can I get it so when I type m_s(1,2) I get back the whole field example

m_s(2,1) should give me
  277.912902832031250

thanks

PS I'm using  octave and textscan is not compatible with it.


来源: stackexchange

问:
Why do comma separated placeholder rules not get applied in css?
If I apply the following rule to an input element with id #one then the placeholder color will change,

```<code>#one::-webkit-input-placeholder {
  color: red;
}
</code>```

But if I use comma separater to combine placeholder rules of different browsers then the color doesn't apply, e.g.

```<code>#two::-webkit-input-placeholder,
#two::-moz-placeholder{
  color: red;
}
</code>```

Working example:

#one::-webkit-input-placeholder {
  color: red;
}

#two::-webkit-input-placeholder,
#two::-moz-placeholder{
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="one" type="text" placeholder="one">
<input id="two" type="text" placeholder="two"></code>```

Why does the #two placeholder not change its color to red?

答:
This is because a browser will only apply a rule form a selector it can fully interpret.

For a webkit type browser -webkit-input-placeholder is valid but -moz-placeholder is not, so it trashes the entire selector, and vise-versa for a geeko based browser.

The solution is to separate browser specific selectors.

```<code>#two::-webkit-input-placeholder{
  color: red;
}
#two::-moz-placeholder{
  color: red;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If I apply the following rule to an input element with id #one then the placeholder color will change,

#one::-webkit-input-placeholder {
  color: red;
}

But if I use comma separater to combine placeholder rules of different browsers then the color doesn't apply, e.g.

#two::-webkit-input-placeholder,
#two::-moz-placeholder{
  color: red;
}

Working example:

#one::-webkit-input-placeholder {
  color: red;
}

#two::-webkit-input-placeholder,
#two::-moz-placeholder{
  color: red;
}

<input id="one" type="text" placeholder="one">
<input id="two" type="text" placeholder="two">

Why does the #two placeholder not change its color to red?

Body:
This is because a browser will only apply a rule form a selector it can fully interpret.

For a webkit type browser -webkit-input-placeholder is valid but -moz-placeholder is not, so it trashes the entire selector, and vise-versa for a geeko based browser.

The solution is to separate browser specific selectors.

#two::-webkit-input-placeholder{
  color: red;
}
#two::-moz-placeholder{
  color: red;
}


问:
How do I stop the getting blank plots when trying to use Matplotlib's subplot feature?
I am currently working on some Vidhya articles. As part of following along, I'm running the following code:

```<code>import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8,4))
ax1 = fig.add_subplot(121)
ax1.set_xlabel('Credit_History')
ax1.set_ylabel('Count of Applicants')
ax1.set_title("Applicants by Credit_History")
temp1.plot(kind='bar')

ax2 = fig.add_subplot(122)
temp2.plot(kind = 'bar')
ax2.set_xlabel('Credit_History')
ax2.set_ylabel('Probability of getting loan')
ax2.set_title("Probability of getting loan by credit history")
</code>```

This is supposed to produce the following:

Correct answer from Vidhya

This seems straightforward enough. I understand the

However, when I attempt this, I have been getting this no matter how much I jiggle around with things.

What I'm getting

Obviously, this isn't right. My understanding of what is supposed to happen is:

I create a figure.

I specify that the figure will have two subplots, with the '121' and '122' specifying they will be horizontally adjacent to each other.

As I use the 'plot' command, the subplots should be utilized in the order they were generated.

Unfortunately, it seems like the code I am using is only utilizing ONE of the subplots, and then producing the other plot on a new line. I can not for the life of me figure out why this is the case.

While writing this I read some of 'Python for Data Analysis' and tried some new code to no avail. I've also attempted to print it this way with similar results:

```<code>fig, axes = plt.subplots(1, 2, figsize=(10, 8))
temp1.plot(kind='bar')
temp2.plot(kind='bar')
</code>```

The code for temp1 and temp2 are as follows:

```<code>temp1 = df['Credit_History'].value_counts(ascending=True)
temp2 = df.pivot_table(values='Loan_Status',index['Credit_History'],aggfunc=lambda x: x.map({'Y':1,'N':0}).mean())
</code>```

It seems that even if I print temp1 twice, the first subplot is blank for some reason. I'm really pretty stumped. The latter attempt to make it work is almost an exact copy of the code from 'Python for Data Analysis'.

答:
You're not plotting in the axis that you want to. You need to tell Pandas which axis you want.

Try this:

```<code>import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8, 4))
ax1 = fig.add_subplot(121)
ax1.set_xlabel('Credit_History')
ax1.set_ylabel('Count of Applicants')
ax1.set_title("Applicants by Credit_History")
temp1.plot(kind='bar', ax=ax1)

ax2 = fig.add_subplot(122)
ax2.plot(kind='bar')
ax2.set_xlabel('Credit_History')
ax2.set_ylabel('Probability of getting loan')
ax2.set_title("Probability of getting loan by credit history")
temp2.plot(kind='bar', ax=ax2)
</code>```

Notice the ax kwarg in the plot methods.

Body:
I am currently working on some Vidhya articles. As part of following along, I'm running the following code:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8,4))
ax1 = fig.add_subplot(121)
ax1.set_xlabel('Credit_History')
ax1.set_ylabel('Count of Applicants')
ax1.set_title("Applicants by Credit_History")
temp1.plot(kind='bar')

ax2 = fig.add_subplot(122)
temp2.plot(kind = 'bar')
ax2.set_xlabel('Credit_History')
ax2.set_ylabel('Probability of getting loan')
ax2.set_title("Probability of getting loan by credit history")

This is supposed to produce the following:

Correct answer from Vidhya

This seems straightforward enough. I understand the

However, when I attempt this, I have been getting this no matter how much I jiggle around with things.

What I'm getting

Obviously, this isn't right. My understanding of what is supposed to happen is:

I create a figure.

I specify that the figure will have two subplots, with the '121' and '122' specifying they will be horizontally adjacent to each other.

As I use the 'plot' command, the subplots should be utilized in the order they were generated.

Unfortunately, it seems like the code I am using is only utilizing ONE of the subplots, and then producing the other plot on a new line. I can not for the life of me figure out why this is the case.

While writing this I read some of 'Python for Data Analysis' and tried some new code to no avail. I've also attempted to print it this way with similar results:

fig, axes = plt.subplots(1, 2, figsize=(10, 8))
temp1.plot(kind='bar')
temp2.plot(kind='bar')

The code for temp1 and temp2 are as follows:

temp1 = df['Credit_History'].value_counts(ascending=True)
temp2 = df.pivot_table(values='Loan_Status',index['Credit_History'],aggfunc=lambda x: x.map({'Y':1,'N':0}).mean())

It seems that even if I print temp1 twice, the first subplot is blank for some reason. I'm really pretty stumped. The latter attempt to make it work is almost an exact copy of the code from 'Python for Data Analysis'.

Body:
You're not plotting in the axis that you want to. You need to tell Pandas which axis you want.

Try this:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8, 4))
ax1 = fig.add_subplot(121)
ax1.set_xlabel('Credit_History')
ax1.set_ylabel('Count of Applicants')
ax1.set_title("Applicants by Credit_History")
temp1.plot(kind='bar', ax=ax1)

ax2 = fig.add_subplot(122)
ax2.plot(kind='bar')
ax2.set_xlabel('Credit_History')
ax2.set_ylabel('Probability of getting loan')
ax2.set_title("Probability of getting loan by credit history")
temp2.plot(kind='bar', ax=ax2)

Notice the ax kwarg in the plot methods.


问:
shiny app with module as a package
I'm trying to create a package of a shiny app organized with module. I can't find any help, every example which i can find doesn't use module. Someone can give me an example ?</p>

答:
Gregor de Cillia gives you a good example of how the UI and server function can be constructed and should be exported. A few other things to take into account before the package is completely functional:

As Gregor said, exporting these functions will make them available for the end user.

Make sure you add the shiny package to the Depends list in the description file ( see also Package Dependencies in the R manual ). It makes a lot more sense to add it to the depends list compared to importing the shiny package, as all shiny functions should also be available to the end user and not solely your module functions. The standard is now to use import rather than depends, but in this case Depends makes a lot more sense.

For making your package top-notch, add a small example that illustrates your module. Take the example of Gregor, then you add a folder inst/examples/moduleExample/ to your package, and in there you have a file app.R as follows:

```<code>shinyApp(
  fluidPage(myModuleUI("someId")),
  function(input,output,session){
    callModule(myModuleServer, "someId")
  }
)
</code>```

Now you add eg a moduleDemo function that illustrates the use of the module.

```<code>#' @export
moduleDemo <- function(){
  loc <- system.file("examples","moduleExample",
                     package = "myPackage")
  shinyAppDir(loc)
}
</code>```

Title: shiny app with module as a package

Body:
Gregor de Cillia gives you a good example of how the UI and server function can be constructed and should be exported. A few other things to take into account before the package is completely functional:

As Gregor said, exporting these functions will make them available for the end user.

Make sure you add the shiny package to the Depends list in the description file ( see also Package Dependencies in the R manual ). It makes a lot more sense to add it to the depends list compared to importing the shiny package, as all shiny functions should also be available to the end user and not solely your module functions. The standard is now to use import rather than depends, but in this case Depends makes a lot more sense.

For making your package top-notch, add a small example that illustrates your module. Take the example of Gregor, then you add a folder inst/examples/moduleExample/ to your package, and in there you have a file app.R as follows:

shinyApp(
  fluidPage(myModuleUI("someId")),
  function(input,output,session){
    callModule(myModuleServer, "someId")
  }
)

Now you add eg a moduleDemo function that illustrates the use of the module.

#' @export
moduleDemo <- function(){
  loc <- system.file("examples","moduleExample",
                     package = "myPackage")
  shinyAppDir(loc)
}


问:
Why concatenated email addresses aren't printing correctly?
I have a Perl script that loads names and email addresses from a file, and then tries to concatenate them into a single string to use to send an email. The email address line needs to be a comma separated list of addresses in the form Name <email address>, ....

I expect it to produce a final output of

```<code>To: John and Julie <john@example.com>, John and Julie <julie@example.com>, Bobby and Liz <bobby@example.net>, Kevin and Jayme <kevin3248@example.com>, Kevin and Jayme <jayme8396@example.com>, Ellen and Mike <mike397987@example.com>, Ellen and Mike <ellen397286@example.com>,
</code>```

but instead it is producing only

```<code>>,
</code>```

The following is the full output from the program on my Mac running the latest version of Sierra and Perl 5.18.2.

```<code>on master* perl example.pl
EmailConfig initialized: John and Julie = john@example.com,julie@example.com
EmailConfig initialized: Bobby and Liz = bobby@example.net
EmailConfig initialized: Kevin and Jayme = kevin3248@example.com,jayme8396@example.com
EmailConfig initialized: Ellen and Mike = mike397987@example.com,ellen397286@example.com
john@example.com
julie@example.com
bobby@example.net
kevin3248@example.com
jayme8396@example.com
mike397987@example.com
ellen397286@example.com
>, on master* <ellen397286@example.com
</code>```

I seem to be reading in all the emails correctly since I can print each one individually, but I'm not sure if the problem in the script is the concatenation or the printing of the final concatenated value.

Main Perl program

```<code>#!/usr/bin/perl

use strict;
use warnings FATAL => 'all';

use EmailConfig;
use File::Slurp;

# Turn off output buffering
$| = 1;

my @emailConfig = ();

sub main() {
    loadConfig();
    processDataAndSendEmail();
}

main();

sub loadConfig() {

    my @raw_configs = read_file('email_config.txt');

    foreach my $raw_config ( @raw_configs ) {

        my $newEmailConfig = new EmailConfig();
        $newEmailConfig->init($raw_config);
        push @emailConfig, $newEmailConfig;
    }
}

sub processDataAndSendEmail() {

    my $to = '';

    foreach my $config ( @emailConfig ) {

        foreach my $email ( @{ $config->{emails} } ) {

            print "$email\n";
            $to .= "$config->{name} <$email>, ";
        }
    }

    print "To: $to";
}
</code>```

EmailConfig.pm

```<code>package EmailConfig;

use strict;
use warnings FATAL => 'all';

my $emailConfigRegex = qr/(?<email_name>.*) = (?<email_addresses>.*)/;

sub new {
    my $class = shift;
    my $self = {};
    bless $self, $class;
    return $self;
}

sub init {
    my $self = shift;

    my $emailConfigValue = shift;

    if ($emailConfigValue =~ $emailConfigRegex) {
        $self->{name} = $+{email_name};
        @{$self->{emails}} = split(';', $+{email_addresses});
    }

    my $print_emails = join(",", @{$self->{emails}});
    print "EmailConfig initialized: $self->{name} = $print_emails\n";
}

1;
</code>```

email_config.txt

```<code>John and Julie = john@example.com;julie@example.com
Bobby and Liz = bobby@example.net
Kevin and Jayme = kevin3248@example.com;jayme8396@example.com
Ellen and Mike = mike397987@example.com;ellen397286@example.com
</code>```

答:
From your output, I suspect there's a '\r' character after email adress. Check line endings in email_config.txt, or remove \r character.</p>

```<code>sub init {
...
    (my $email_addresses = $+{email_addresses})=~s/\r//g;
    @{$self->{emails}} = split(';', $email_addresses);
...
}
</code>```

Body:
I have a Perl script that loads names and email addresses from a file, and then tries to concatenate them into a single string to use to send an email. The email address line needs to be a comma separated list of addresses in the form Name <email address>, ....

I expect it to produce a final output of

To: John and Julie <john@example.com>, John and Julie <julie@example.com>, Bobby and Liz <bobby@example.net>, Kevin and Jayme <kevin3248@example.com>, Kevin and Jayme <jayme8396@example.com>, Ellen and Mike <mike397987@example.com>, Ellen and Mike <ellen397286@example.com>,

but instead it is producing only

>,

The following is the full output from the program on my Mac running the latest version of Sierra and Perl 5.18.2.

on master* perl example.pl
EmailConfig initialized: John and Julie = john@example.com,julie@example.com
EmailConfig initialized: Bobby and Liz = bobby@example.net
EmailConfig initialized: Kevin and Jayme = kevin3248@example.com,jayme8396@example.com
EmailConfig initialized: Ellen and Mike = mike397987@example.com,ellen397286@example.com
john@example.com
julie@example.com
bobby@example.net
kevin3248@example.com
jayme8396@example.com
mike397987@example.com
ellen397286@example.com
>, on master* <ellen397286@example.com

I seem to be reading in all the emails correctly since I can print each one individually, but I'm not sure if the problem in the script is the concatenation or the printing of the final concatenated value.

Main Perl program

#!/usr/bin/perl

use strict;
use warnings FATAL => 'all';

use EmailConfig;
use File::Slurp;

# Turn off output buffering
$| = 1;

my @emailConfig = ();

sub main() {
    loadConfig();
    processDataAndSendEmail();
}

main();

sub loadConfig() {

    my @raw_configs = read_file('email_config.txt');

    foreach my $raw_config ( @raw_configs ) {

        my $newEmailConfig = new EmailConfig();
        $newEmailConfig->init($raw_config);
        push @emailConfig, $newEmailConfig;
    }
}

sub processDataAndSendEmail() {

    my $to = '';

    foreach my $config ( @emailConfig ) {

        foreach my $email ( @{ $config->{emails} } ) {

            print "$email\n";
            $to .= "$config->{name} <$email>, ";
        }
    }

    print "To: $to";
}

EmailConfig.pm

package EmailConfig;

use strict;
use warnings FATAL => 'all';

my $emailConfigRegex = qr/(?<email_name>.*) = (?<email_addresses>.*)/;

sub new {
    my $class = shift;
    my $self = {};
    bless $self, $class;
    return $self;
}

sub init {
    my $self = shift;

    my $emailConfigValue = shift;

    if ($emailConfigValue =~ $emailConfigRegex) {
        $self->{name} = $+{email_name};
        @{$self->{emails}} = split(';', $+{email_addresses});
    }

    my $print_emails = join(",", @{$self->{emails}});
    print "EmailConfig initialized: $self->{name} = $print_emails\n";
}

1;

email_config.txt

John and Julie = john@example.com;julie@example.com
Bobby and Liz = bobby@example.net
Kevin and Jayme = kevin3248@example.com;jayme8396@example.com
Ellen and Mike = mike397987@example.com;ellen397286@example.com

Body:
From your output, I suspect there's a '\r' character after email adress. Check line endings in email_config.txt, or remove \r character.

sub init {
...
    (my $email_addresses = $+{email_addresses})=~s/\r//g;
    @{$self->{emails}} = split(';', $email_addresses);
...
}


问:
How to use Ember action helper in element append to the DOM
First, I wanna let you know that I'm just starting at Ember, so, if is there a better way to accomplish the same result, feel free to point at that.

I have a component called "select-room", it should work as the fields "Quartos", "Adultos" and "Crianças" at this site.

In this site when the field "Quartos" is changed, will be added or removed more selects fields on the form, the same happen when the value of "Crianças" change. I was able to accomplish this behavor using DOM manipulation, but when appending a select field like this html+= ''; the action helper don't work.

Link to the full code is at this repo in Github: https://github.com/darwinboaventura/embercvc

What is the best to way to solve this problem?

答:
I solved the problem, here my solution:

app/components/select-rooms.js:

```<code>import Ember from 'ember';

export default Ember.Component.extend({
    name: null,
    quantityRooms: 1,
    rooms: '',
    init() {
        this._super(...arguments);
        this.set('rooms', [1]);
    },
    actions: {
        changeQuantityRooms(value) {
            this.set('quantityRooms', value);
            this.set('rooms', []);

            for (var i = 0; i < this.get('quantityRooms'); i++) {
                this.get('rooms').pushObject(i);
            };
        },
        changeQuantityChildren(value) {
            this.set("quantity" + value.name, value.value);
            this.set(value.name, []);

            for (var i = 0; i < this.get("quantity" + value.name); i++) {
                this.get(value.name).pushObject(i);
            }
        }
    }
});
</code>```

app/templates/components/select-rooms.hbs:

```<code><div class="row">
    <div class="col-sm-6">
        <div class="form-group">
            <label>Quartos</label>

            <select name={{name}} onchange={{action "changeQuantityRooms" value="target.value"}} class="form-control">
                <option value="1">1</option>
                <option value="2">2</option>
            </select>
        </div>
    </div>

    <div class="col-sm-6">
        {{#if rooms}}
            {{#each rooms as |room index|}}
                <div class="row">
                    <div class="col-sm-6 form-group">
                        <label>
                            Adultos <small>+18</small>
                        </label>

                        <select name={{concat name index "-adults"}} class="form-control">
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                            <option value="5">5</option>
                            <option value="6">6</option>
                            <option value="7">7</option>
                            <option value="8">8</option>
                            <option value="9">9</option>
                        </select>
                    </div>

                    <div class="col-sm-6 form-group">
                        <label>
                            Crianças <small>até 17 anos</small>
                        </label>

                        <select name={{concat name index "-children"}} onchange={{action "changeQuantityChildren" value="target"}} class="form-control">
                            <option value="0">0</option>
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                            <option value="5">5</option>
                            <option value="6">6</option>
                            <option value="7">7</option>
                            <option value="8">8</option>
                            <option value="9">9</option>
                        </select>
                    </div>

                    <div class="col-xs-12">
                        {{#if (get this (concat "quantity" name index "-children"))}}
                            <div class="row">
                                <div class="col-xs-12">
                                    <label>Idade das crianças: </label>
                                </div>
                            </div>

                            <div class="row">
                                {{#each (get this (concat name index "-children")) as | child i |}}
                                    <div class="col-sm-4 form-group">
                                        <select name={{concat name index "-children-age-" i}} class="form-control">
                                            <option value="0">0</option>
                                            <option value="1">1</option>
                                            <option value="2">2</option>
                                            <option value="3">3</option>
                                            <option value="4">4</option>
                                            <option value="5">5</option>
                                            <option value="6">6</option>
                                            <option value="7">7</option>
                                            <option value="8">8</option>
                                            <option value="9">9</option>
                                            <option value="10">10</option>
                                            <option value="11">11</option>
                                            <option value="12">12</option>
                                            <option value="13">13</option>
                                            <option value="14">14</option>
                                            <option value="15">15</option>
                                            <option value="16">16</option>
                                            <option value="17">17</option>
                                        </select>
                                    </div>
                                {{/each}}
                            </div>
                        {{/if}}
                    </div>
                </div>
            {{/each}}
        {{/if}}
    </div>
</div>
</code>```

Body:
I solved the problem, here my solution:

app/components/select-rooms.js:

import Ember from 'ember';

export default Ember.Component.extend({
    name: null,
    quantityRooms: 1,
    rooms: '',
    init() {
        this._super(...arguments);
        this.set('rooms', [1]);
    },
    actions: {
        changeQuantityRooms(value) {
            this.set('quantityRooms', value);
            this.set('rooms', []);

            for (var i = 0; i < this.get('quantityRooms'); i++) {
                this.get('rooms').pushObject(i);
            };
        },
        changeQuantityChildren(value) {
            this.set("quantity" + value.name, value.value);
            this.set(value.name, []);

            for (var i = 0; i < this.get("quantity" + value.name); i++) {
                this.get(value.name).pushObject(i);
            }
        }
    }
});

app/templates/components/select-rooms.hbs:

<div class="row">
    <div class="col-sm-6">
        <div class="form-group">
            <label>Quartos</label>

            <select name={{name}} onchange={{action "changeQuantityRooms" value="target.value"}} class="form-control">
                <option value="1">1</option>
                <option value="2">2</option>
            </select>
        </div>
    </div>

    <div class="col-sm-6">
        {{#if rooms}}
            {{#each rooms as |room index|}}
                <div class="row">
                    <div class="col-sm-6 form-group">
                        <label>
                            Adultos <small>+18</small>
                        </label>

                        <select name={{concat name index "-adults"}} class="form-control">
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                            <option value="5">5</option>
                            <option value="6">6</option>
                            <option value="7">7</option>
                            <option value="8">8</option>
                            <option value="9">9</option>
                        </select>
                    </div>

                    <div class="col-sm-6 form-group">
                        <label>
                            Crianças <small>até 17 anos</small>
                        </label>

                        <select name={{concat name index "-children"}} onchange={{action "changeQuantityChildren" value="target"}} class="form-control">
                            <option value="0">0</option>
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                            <option value="5">5</option>
                            <option value="6">6</option>
                            <option value="7">7</option>
                            <option value="8">8</option>
                            <option value="9">9</option>
                        </select>
                    </div>

                    <div class="col-xs-12">
                        {{#if (get this (concat "quantity" name index "-children"))}}
                            <div class="row">
                                <div class="col-xs-12">
                                    <label>Idade das crianças: </label>
                                </div>
                            </div>

                            <div class="row">
                                {{#each (get this (concat name index "-children")) as | child i |}}
                                    <div class="col-sm-4 form-group">
                                        <select name={{concat name index "-children-age-" i}} class="form-control">
                                            <option value="0">0</option>
                                            <option value="1">1</option>
                                            <option value="2">2</option>
                                            <option value="3">3</option>
                                            <option value="4">4</option>
                                            <option value="5">5</option>
                                            <option value="6">6</option>
                                            <option value="7">7</option>
                                            <option value="8">8</option>
                                            <option value="9">9</option>
                                            <option value="10">10</option>
                                            <option value="11">11</option>
                                            <option value="12">12</option>
                                            <option value="13">13</option>
                                            <option value="14">14</option>
                                            <option value="15">15</option>
                                            <option value="16">16</option>
                                            <option value="17">17</option>
                                        </select>
                                    </div>
                                {{/each}}
                            </div>
                        {{/if}}
                    </div>
                </div>
            {{/each}}
        {{/if}}
    </div>
</div>


问:
What is difference between DVM and ART ? Why DVM has been officially replaced with ART in Lollipop?
Since Android Lollipop, Google has replaced DVM with ART because ART is faster than DVM. Is there any other reason for that?</p>

答:
In Android 4.4 and above version, along with Dalvik, Google  introduced a new Android Runtime called “ART”.

Difference between ART vs Dalvik

ART (Android RunTime) has main feature Ahead-of-Time (AOT) compilation,

AOT vs JIT

Android apps format is .apk and all Java classes converted into DEX bytecode. The DEX bytecode format is independent of device architecture and needs to be translated to native machine code to run on the device. This is the same for both the ART and the Dalvik runtimes.

Main Difference, ART (Android RunTime) used Ahead-of-Time (AOT) compilation,Dalvik is used Just-in-Time (JIT) compilation

With Dalvik ,Just-in-Time (JIT) compilation every Time when app run ,It convert dex byte code into machine code and cached.

see here more detail
http://androidboost.over-blog.com/2016/10/art-vs-dalvik.html


问:
Add variable to nested list
Using R base, I would like to add a variable to a nested list where the variable changes for each nested list element. Below is an example. Thank you.</p>

```<code>#CREATE EXAMPLE DATAFRAME
DF <- expand.grid(NAME = c("FRANK", "TONY", "ED"), DATE = seq(as.Date("2014-01-01"), as.Date("2018-12-31"), by = "day"))

#CREATE NESTED LIST
DF <- lapply(1:3, function(i) lapply(2014:2015, function(t) DF[with(DF, as.Date(paste(t, "01", "01", sep = "-")) <= DATE & DATE <= as.Date(paste(t + i, "12", "31", sep = "-"))), ]))

#PRINT NESTED LIST
lapply(DF, lapply, function(x) rbind(head(x), tail(x)))

#I WOULD LIKE TO SIMPLIFY THIS PART
DF[[1]][[1]] <- within(DF[[1]][[1]], GROUP <- 2014)
DF[[1]][[2]] <- within(DF[[1]][[2]], GROUP <- 2015)

DF[[2]][[1]] <- within(DF[[2]][[1]], GROUP <- 2014)
DF[[2]][[2]] <- within(DF[[2]][[2]], GROUP <- 2015)

DF[[3]][[1]] <- within(DF[[3]][[1]], GROUP <- 2014)
DF[[3]][[2]] <- within(DF[[3]][[2]], GROUP <- 2015)

#PRINT MODIFIED NESTED LIST
lapply(DF, lapply, function(x) rbind(head(x), tail(x)))

#I AM SURPRISED THE FOLLOWING DOES NOT WORK
DF <- expand.grid(NAME = c("FRANK", "TONY", "ED"), DATE = seq(as.Date("2014-01-01"), as.Date("2018-12-31"), by = "day"))
DF <- lapply(1:3, function(i) lapply(2014:2015, function(t) DF[with(DF, as.Date(paste(t, "01", "01", sep = "-")) <= DATE & DATE <= as.Date(paste(t + i, "12", "31", sep = "-"))),]))
DF <- lapply(DF, function(x) lapply(2014:2015, function(t) within(x, GROUP <- t)))
lapply(DF, lapply, function(x) rbind(head(x), tail(x)))
</code>```

答:
How about this?
Had to use package dplyr since it makes adding a new variable to the dataframes easier with mutate_.

```<code>library(dplyr) # if not installed, install with install.packages("dplyr")
DF <- expand.grid(NAME = c("FRANK", "TONY", "ED"),
DATE = seq(as.Date("2014-01-01"), as.Date("2018-12-31"), by = "day"))

#CREATE NESTED LIST
DF <- lapply(1:3, function(i) lapply(2014:2015, function(t) DF[with(DF,
as.Date(paste(t, "01", "01", sep = "-")) <= DATE & DATE <= as.Date(paste(t +
i, "12", "31", sep = "-"))), ]))

# loop over the first list with lapply and then loop over the nested lists
# and the desired GROUP values with mapply
DF <- lapply(DF, function(x) mapply(FUN = function(df,number){mutate_(df,
"GROUP" = number)},x, 2014:2015, SIMPLIFY = F))

#PRINT NESTED LIST
lapply(DF, lapply, function(x) rbind(head(x), tail(x)))
</code>```

As to why your way was not working: Think about what function(t) within(xs[[t]], GROUP <- GROUPS[t]) does. It does not return a dataframe.

Title: Add variable to nested list

Body:
Using R base, I would like to add a variable to a nested list where the variable changes for each nested list element. Below is an example. Thank you.

#CREATE EXAMPLE DATAFRAME
DF <- expand.grid(NAME = c("FRANK", "TONY", "ED"), DATE = seq(as.Date("2014-01-01"), as.Date("2018-12-31"), by = "day"))

#CREATE NESTED LIST
DF <- lapply(1:3, function(i) lapply(2014:2015, function(t) DF[with(DF, as.Date(paste(t, "01", "01", sep = "-")) <= DATE & DATE <= as.Date(paste(t + i, "12", "31", sep = "-"))), ]))

#PRINT NESTED LIST
lapply(DF, lapply, function(x) rbind(head(x), tail(x)))

#I WOULD LIKE TO SIMPLIFY THIS PART
DF[[1]][[1]] <- within(DF[[1]][[1]], GROUP <- 2014)
DF[[1]][[2]] <- within(DF[[1]][[2]], GROUP <- 2015)

DF[[2]][[1]] <- within(DF[[2]][[1]], GROUP <- 2014)
DF[[2]][[2]] <- within(DF[[2]][[2]], GROUP <- 2015)

DF[[3]][[1]] <- within(DF[[3]][[1]], GROUP <- 2014)
DF[[3]][[2]] <- within(DF[[3]][[2]], GROUP <- 2015)

#PRINT MODIFIED NESTED LIST
lapply(DF, lapply, function(x) rbind(head(x), tail(x)))

#I AM SURPRISED THE FOLLOWING DOES NOT WORK
DF <- expand.grid(NAME = c("FRANK", "TONY", "ED"), DATE = seq(as.Date("2014-01-01"), as.Date("2018-12-31"), by = "day"))
DF <- lapply(1:3, function(i) lapply(2014:2015, function(t) DF[with(DF, as.Date(paste(t, "01", "01", sep = "-")) <= DATE & DATE <= as.Date(paste(t + i, "12", "31", sep = "-"))),]))
DF <- lapply(DF, function(x) lapply(2014:2015, function(t) within(x, GROUP <- t)))
lapply(DF, lapply, function(x) rbind(head(x), tail(x)))

Body:
How about this?
Had to use package dplyr since it makes adding a new variable to the dataframes easier with mutate_.

library(dplyr) # if not installed, install with install.packages("dplyr")
DF <- expand.grid(NAME = c("FRANK", "TONY", "ED"),
DATE = seq(as.Date("2014-01-01"), as.Date("2018-12-31"), by = "day"))

#CREATE NESTED LIST
DF <- lapply(1:3, function(i) lapply(2014:2015, function(t) DF[with(DF,
as.Date(paste(t, "01", "01", sep = "-")) <= DATE & DATE <= as.Date(paste(t +
i, "12", "31", sep = "-"))), ]))

# loop over the first list with lapply and then loop over the nested lists
# and the desired GROUP values with mapply
DF <- lapply(DF, function(x) mapply(FUN = function(df,number){mutate_(df,
"GROUP" = number)},x, 2014:2015, SIMPLIFY = F))

#PRINT NESTED LIST
lapply(DF, lapply, function(x) rbind(head(x), tail(x)))

As to why your way was not working: Think about what function(t) within(xs[[t]], GROUP <- GROUPS[t]) does. It does not return a dataframe.


问:
Does fragment onStop run on UI thread
I have some fragments loaded in a ViewPager, where each "page" is loaded from a row in a cursor. Each fragment shows an image (JPEG) on the device. When the user dismisses the fragment (i.e swipe/page change, hits back/up, or just closes the app entirely) I want to invoke a method which opens the JPEG file for writing and does an update of its metadata. The actual work is eventually handled by the Apache Commons Imaging library.

I've implemented this by invoking my saveToFile() method from each fragment's life cycle onStop() handler. Does this mean the entire file operation ends up running on the UI thread? Should I definitely set up an AsyncTask for this?

Say the file write for some reason suddenly (for some jpeg) should take a long time, eg 2 minutes. What would then happen? Would the UI just wait (freeze) at this page/fragment before resuming? Or would the process (write to file) carry on "in the background" somehow? Or would the process just be killed, stopped short mid-process?

The way I have this wired up currently (onStop invoking saveToFile(), which calls up the imaging library and then updates the file) seems to work as it should. Even if I end the app, I still see my Toast text popping up, saying "Writing to file..." Seemingly, the process is never disturbed, and I can't say I'm experiencing any UI lag.

答:
onStop() handler. Does this mean the entire file operation ends up
  running on the UI thread? Should I definitely set up an AsyncTask for
  this?

YES

An AsyncTask has several parts: a doInBackground method that does, in fact, run on a separate thread and the onPostExecute method that runs on the UI thread.

You can also use some sort of observer pattern such as EventBus to run async and post results to the UI.

Say the file write for some reason suddenly (for some jpeg) should
  take a long time, eg 2 minutes. What would then happen? Would the UI
  just wait (freeze)

The application will crash because Android will forcefully close it due to ANR (Application Not Responding).

Refer to the official documentation for details on this: https://developer.android.com/training/articles/perf-anr.html

Android applications normally run entirely on a single thread by
  default the "UI thread" or "main thread"). This means anything your
  application is doing in the UI thread that takes a long time to
  complete can trigger the ANR dialog because your application is not
  giving itself a chance to handle the input event or intent broadcasts.

Therefore, any method that runs in the UI thread should do as little
  work as possible on that thread. In particular, activities should do
  as little as possible to set up in key life-cycle methods such as
  onCreate() and onResume(). Potentially long running operations such as
  network or database operations, or computationally expensive
  calculations such as resizing bitmaps should be done in a worker
  thread (or in the case of databases operations, via an asynchronous
  request).

The most effective way to create a worker thread for longer operations
  is with the AsyncTask class.

Here is what I recommend though. Use the above mentioned, EventBus and create a BaseActivity which will automatically save the data for you onClose() by firing an event that runs Async. You then extend that base activity in all the places where you need autosave capabilities.

Here's what I mean with an example that uses EventBus.

```<code>public abstract class BaseActivity extends Activity{

 @Override
 protected void onResume(){
   if(!EventBus.getDefault().isRegistered(this))
       EventBus.getDefault().register(this);
   super.onResume();
 }

 @Override
 protected void onDestroy() {
   if(EventBus.getDefault().isRegistered(this))
     EventBus.getDefault().unregister(this);
   super.onDestroy();
 }

 @Override
 protected void onStop() {
     super.onStop();
     //We fire event and pass the current parent class that inherited this base.
     EventBus.getDefault().post(new EventBusProcessMySaveData(this.getClass()));
 }
}

//Your model class to use with EventBus
public final class EventBusProcessMySaveData{
     private final Class className;

     public EventBusProcessMySaveData(final Class className){
        this.className = className;
     }

     public Class getClassName(){
        return this.className;
     }
}

public class MyMainActivity extends BaseActivity{
  //Do you standard setup here onCreate() and such...

    //Handle Event for Saving Operation, async.
    //This will fire everytime theres an onClose() IN ANY activity that
    //extends BaseActivity, but will only process if the class names match.
    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void methodNameDoesNotReallyMatterHere(final EventBusProcessMySaveData model){
        //We make sure this is the intended receiving end by comparing current class name
        //with received class name.
        if(model.getClassName().equals(this.getClass())){
          //Do whatever you need to do that's CPUintensive here.
        }
    }

}
</code>```

Title: Does fragment onStop run on UI thread

Body:
onStop() handler. Does this mean the entire file operation ends up
  running on the UI thread? Should I definitely set up an AsyncTask for
  this?

YES

An AsyncTask has several parts: a doInBackground method that does, in fact, run on a separate thread and the onPostExecute method that runs on the UI thread.

You can also use some sort of observer pattern such as EventBus to run async and post results to the UI.

Say the file write for some reason suddenly (for some jpeg) should
  take a long time, eg 2 minutes. What would then happen? Would the UI
  just wait (freeze)

The application will crash because Android will forcefully close it due to ANR (Application Not Responding).

Refer to the official documentation for details on this: https://developer.android.com/training/articles/perf-anr.html

Android applications normally run entirely on a single thread by
  default the "UI thread" or "main thread"). This means anything your
  application is doing in the UI thread that takes a long time to
  complete can trigger the ANR dialog because your application is not
  giving itself a chance to handle the input event or intent broadcasts.

Therefore, any method that runs in the UI thread should do as little
  work as possible on that thread. In particular, activities should do
  as little as possible to set up in key life-cycle methods such as
  onCreate() and onResume(). Potentially long running operations such as
  network or database operations, or computationally expensive
  calculations such as resizing bitmaps should be done in a worker
  thread (or in the case of databases operations, via an asynchronous
  request).

The most effective way to create a worker thread for longer operations
  is with the AsyncTask class.

Here is what I recommend though. Use the above mentioned, EventBus and create a BaseActivity which will automatically save the data for you onClose() by firing an event that runs Async. You then extend that base activity in all the places where you need autosave capabilities.

Here's what I mean with an example that uses EventBus.

public abstract class BaseActivity extends Activity{

 @Override
 protected void onResume(){
   if(!EventBus.getDefault().isRegistered(this))
       EventBus.getDefault().register(this);
   super.onResume();
 }

 @Override
 protected void onDestroy() {
   if(EventBus.getDefault().isRegistered(this))
     EventBus.getDefault().unregister(this);
   super.onDestroy();
 }

 @Override
 protected void onStop() {
     super.onStop();
     //We fire event and pass the current parent class that inherited this base.
     EventBus.getDefault().post(new EventBusProcessMySaveData(this.getClass()));
 }
}

//Your model class to use with EventBus
public final class EventBusProcessMySaveData{
     private final Class className;

     public EventBusProcessMySaveData(final Class className){
        this.className = className;
     }

     public Class getClassName(){
        return this.className;
     }
}

public class MyMainActivity extends BaseActivity{
  //Do you standard setup here onCreate() and such...

    //Handle Event for Saving Operation, async.
    //This will fire everytime theres an onClose() IN ANY activity that
    //extends BaseActivity, but will only process if the class names match.
    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void methodNameDoesNotReallyMatterHere(final EventBusProcessMySaveData model){
        //We make sure this is the intended receiving end by comparing current class name
        //with received class name.
        if(model.getClassName().equals(this.getClass())){
          //Do whatever you need to do that's CPUintensive here.
        }
    }

}


问:
SQL Server 2016 group data
My table and data is like this:

How do I group them and get result like this:

答: select ROW_NUMBER() OVER(PARTITION BY categoryid order by categoryid asc) as Num, categoryid,value from democat

Title: SQL Server 2016 group data


问:
can't write ñ, ä, ë, ü in a ubuntu docker container
I need to be able to write ñ, ä, ë, ü in the console of an ubuntu docker container.
I created the image which I create the container from with the following dockerfile:

```<code>FROM ubuntu:17.10
RUN apt-get update -y
RUN apt-get install locales
RUN locale-gen es_CO.UTF-8
ENV LANG es_CO.UTF-8
ENV LANGUAGE es_CO:en
ENV LC_ALL es_CO.UTF-8
</code>```

If I run a python script like this:

```<code>print("ñ")
</code>```

the ñ is printed in the console normally, the problem is when I try to write the letter ñ as an input of a a program, when I type ñ in the keyboard what shows up in the console is ¤. I have already tried to reconfigure the keyboard with setxkbmap but I get an error that says: 'Cannot open display "default display"'.

I also have tried to find a docker ubuntu images with this settings already setted but I have not finded any one. Please help.

答:
Your terminal seems to be correctly set up with UTF-8, and it is able to decode UTF-8 codes. The problem must be in the communication from the keyboard to the terminal.

Create the file ~/.inputrc with the following content:

```<code>set input-meta on
set output-meta on
set convert-meta off
set enable-meta-key on
</code>```

Then, log out, log in again, start a new terminal, and see if it works.

Body:
I need to be able to write ñ, ä, ë, ü in the console of an ubuntu docker container.
I created the image which I create the container from with the following dockerfile:

FROM ubuntu:17.10
RUN apt-get update -y
RUN apt-get install locales
RUN locale-gen es_CO.UTF-8
ENV LANG es_CO.UTF-8
ENV LANGUAGE es_CO:en
ENV LC_ALL es_CO.UTF-8

If I run a python script like this:

print("ñ")

the ñ is printed in the console normally, the problem is when I try to write the letter ñ as an input of a a program, when I type ñ in the keyboard what shows up in the console is ¤. I have already tried to reconfigure the keyboard with setxkbmap but I get an error that says: 'Cannot open display "default display"'.

I also have tried to find a docker ubuntu images with this settings already setted but I have not finded any one. Please help.

Body:
Your terminal seems to be correctly set up with UTF-8, and it is able to decode UTF-8 codes. The problem must be in the communication from the keyboard to the terminal.

Create the file ~/.inputrc with the following content:

set input-meta on
set output-meta on
set convert-meta off
set enable-meta-key on

Then, log out, log in again, start a new terminal, and see if it works.


问:
Why is it recommended to provide optional radix parameter to parseInt()?
I've always used the parseInt() function in Javascript without passing the radix parameter. As per the MDN documentation here, it's stated that not providing this parameter may result in unpredictable behaviour.

Always specify this parameter to eliminate reader confusion and to
  guarantee predictable behavior.

Could somebody clarify what does this unpredictable behavior mean with some code examples?

答:
In older versions of the language, parseInt() would cause the function to obey the normal JavaScript numeric constant syntax rules, including the recognition of a leading zero to denote octal constants, and a leading 0x to denote hex constants. Thus, if your code didn't explicitly insist on base 10, stray (possibly user-supplied) numbers with leading zeros would be interpreted as base-8 values, and leading 0x as hex.

The base-8 behavior is gone since ES5.1 (I think; might have been earlier), but the base 16 behavior is still there. (Probably a leading 0x is a little more rare as an accidental prefix than a simple leading 0.)

My experience looking at code here on Stack Overflow is that parseInt() is overused anyway. It's usually cleaner to convert strings (often, strings taken from DOM element .value properties) to numbers with the unary + operator:

```<code>var count = +document.getElementById("count").value;
</code>```

That won't necessarily give you an integer, of course. However, what it will do is notice that the input string has trailing non-numeric garbage. The parseInt() function will simply stop parsing a string like "123abc" and give you 123 as the numeric value. The leading + will however give you a NaN.

If you need integers, you can always use Math.floor() or Math.round().

edit — a comment notes that ES2015 requires a leading 0o or 0O in "strict" mode for octal literals, but that doesn't apply to parseInt() which (in ES2015) only overrides the default radix for hex strings.

Body:
In older versions of the language, parseInt() would cause the function to obey the normal JavaScript numeric constant syntax rules, including the recognition of a leading zero to denote octal constants, and a leading 0x to denote hex constants. Thus, if your code didn't explicitly insist on base 10, stray (possibly user-supplied) numbers with leading zeros would be interpreted as base-8 values, and leading 0x as hex.

The base-8 behavior is gone since ES5.1 (I think; might have been earlier), but the base 16 behavior is still there. (Probably a leading 0x is a little more rare as an accidental prefix than a simple leading 0.)

My experience looking at code here on Stack Overflow is that parseInt() is overused anyway. It's usually cleaner to convert strings (often, strings taken from DOM element .value properties) to numbers with the unary + operator:

var count = +document.getElementById("count").value;

That won't necessarily give you an integer, of course. However, what it will do is notice that the input string has trailing non-numeric garbage. The parseInt() function will simply stop parsing a string like "123abc" and give you 123 as the numeric value. The leading + will however give you a NaN.

If you need integers, you can always use Math.floor() or Math.round().

edit — a comment notes that ES2015 requires a leading 0o or 0O in "strict" mode for octal literals, but that doesn't apply to parseInt() which (in ES2015) only overrides the default radix for hex strings.


问:
jquery .each , if statements do not work
I am trying to remove empty columns in sharepoint display forms. I am quite new to JQuery so bear with me!

I have:

```<code>$("td.ms-formbody").each(function (index) {
  if (index=6)
  {
    console.log("Mobile");
</code>```

So it loops through all the formbody tags and when it comes to the sixth one it should display "Mobile" to console.log but it is just logging 'Mobile' x the count of the formbody tags. So it seems that the IF is not working. Can anyone advise ?

答:
With index = 6 you are setting the value of the variable index. You should change it to index == 6 or index === 6 (in case you'd like to respect the type of the compared values).

```<code>$("td.ms-formbody").each(function (index) {
    if (index === 6) {
        console.log("Mobile");
    }
}
</code>```

By the way, it seems that you'd like to apply something to the sixth column. You could use a direct selector for that, no need to search for it with a loop.

:nth-child() selector

Body:
I am trying to remove empty columns in sharepoint display forms. I am quite new to JQuery so bear with me!

I have:

$("td.ms-formbody").each(function (index) {
  if (index=6)
  {
    console.log("Mobile");

So it loops through all the formbody tags and when it comes to the sixth one it should display "Mobile" to console.log but it is just logging 'Mobile' x the count of the formbody tags. So it seems that the IF is not working. Can anyone advise ?

Body:
With index = 6 you are setting the value of the variable index. You should change it to index == 6 or index === 6 (in case you'd like to respect the type of the compared values).

$("td.ms-formbody").each(function (index) {
    if (index === 6) {
        console.log("Mobile");
    }
}

By the way, it seems that you'd like to apply something to the sixth column. You could use a direct selector for that, no need to search for it with a loop.

:nth-child() selector


问:
Ordering for key value pairs
I have the following two classes:

```<code>class KeyClass {
    private prop1;
    private prop2;

    hashcode() {
    //implemented properly
    }

    equals() {
    //implemented properly
    }
}

class ValueClass {
    private prop1;
    private prop2;

    hashcode() {
    //implemented properly
    }

    equals() {
    //implemented properly
    }
}
</code>```

I am trying to find out the max pair from a map where objects of these classes are key and value pairs respectively. I also have an com.google.common.collect.Ordering<ValueClass> which uses multiple comparators. I can easily find out the max of values using this ordering, but what I am interested into is the key of the max value.

I can write a certain implementation wherein I can keep track of my key w.r.t the value in a loop and use the ordering to compare values (similar to the conventional way of finding a max value) but I want to know if we already have such case handled by Guava or any other library?

答:
yes.
using the Bidi Map :- Bidi Map

Download jar

How to use.

Example:-

```<code>BidiMap bidiMap = new DualHashBidiMap( );
bidiMap.put( "il", "Illinois" );
bidiMap.put( "az", "Arizona" );
bidiMap.put( "va", "Virginia" );
// Retrieve the key with a value via the inverse map
String vaAbbreviation = bidiMap.inverseBidiMap( ).get( "Virginia" );

// Retrieve the value from the key
String illinoisName = bidiMap.get( "il" );
</code>```

Using the same approach you just need to implement the hascode() and equals() contract of a Map.
Solution :-

we know that HashCode is used to Store in Bucket. Assume hashcode as row number in 2-D matrix and each Row has the linked List of entry[key,value].

implement the hashcode() such that for each entry[key,value] you will get different `bucket no(row no).

Implement equals() method to check the equality in each bucket's entry[key,value].

Complexity :- if you assign each entry[key, value] to the different bucket then SEARCHING and ADDING complexity will be o(1).

please refer the below documents for better understanding of solution:-doc1 doc2

Title: Ordering for key value pairs

Body:
I have the following two classes:

class KeyClass {
    private prop1;
    private prop2;

    hashcode() {
    //implemented properly
    }

    equals() {
    //implemented properly
    }
}

class ValueClass {
    private prop1;
    private prop2;

    hashcode() {
    //implemented properly
    }

    equals() {
    //implemented properly
    }
}

I am trying to find out the max pair from a map where objects of these classes are key and value pairs respectively. I also have an com.google.common.collect.Ordering<ValueClass> which uses multiple comparators. I can easily find out the max of values using this ordering, but what I am interested into is the key of the max value.

I can write a certain implementation wherein I can keep track of my key w.r.t the value in a loop and use the ordering to compare values (similar to the conventional way of finding a max value) but I want to know if we already have such case handled by Guava or any other library?

Body:
yes.
using the Bidi Map :- Bidi Map

Download jar

How to use.

Example:-

BidiMap bidiMap = new DualHashBidiMap( );
bidiMap.put( "il", "Illinois" );
bidiMap.put( "az", "Arizona" );
bidiMap.put( "va", "Virginia" );
// Retrieve the key with a value via the inverse map
String vaAbbreviation = bidiMap.inverseBidiMap( ).get( "Virginia" );

// Retrieve the value from the key
String illinoisName = bidiMap.get( "il" );

Using the same approach you just need to implement the hascode() and equals() contract of a Map.
Solution :-

we know that HashCode is used to Store in Bucket. Assume hashcode as row number in 2-D matrix and each Row has the linked List of entry[key,value].

implement the hashcode() such that for each entry[key,value] you will get different `bucket no(row no).

Implement equals() method to check the equality in each bucket's entry[key,value].

Complexity :- if you assign each entry[key, value] to the different bucket then SEARCHING and ADDING complexity will be o(1).

please refer the below documents for better understanding of solution:-doc1 doc2


问:
How to use multiple SUM in Eloquent laravel if condition like this
How to make the format query on laravel if I have a sql query like this?

```<code> SELECT category,

 SUM(IF(group='core',weight,0))/SUM(IF(group='core',1,0)),

 SUM(IF(group='secondary',weight,0))/SUM(IF(group='secondary',1,0))

 FROM view

 JOIN sub_category USING (id_sub_category)

 JOIN category USING (id_category)

 JOIN gap ON difference = (result-result_sub_category)
</code>```

Thanks before

答:
You have to use DB::raw for the sum, since Laravel doesn't have built-in function for this. Using isn't provided either. So use your model like so:</p>

```<code>View::join('sub_category', 'sub_category.id_sub_category', '=', 'view.id_sub_category')
->get([DB::raw("SUM(IF(group='core',weight,0))/SUM(IF(group='core',1,0))")]);
</code>```

Body:
How to make the format query on laravel if I have a sql query like this?

 SELECT category,

 SUM(IF(group='core',weight,0))/SUM(IF(group='core',1,0)),

 SUM(IF(group='secondary',weight,0))/SUM(IF(group='secondary',1,0))

 FROM view

 JOIN sub_category USING (id_sub_category)

 JOIN category USING (id_category)

 JOIN gap ON difference = (result-result_sub_category)

Thanks before

Body:
You have to use DB::raw for the sum, since Laravel doesn't have built-in function for this. Using isn't provided either. So use your model like so:

View::join('sub_category', 'sub_category.id_sub_category', '=', 'view.id_sub_category')
->get([DB::raw("SUM(IF(group='core',weight,0))/SUM(IF(group='core',1,0))")]);


问:
echo -e equivalent in Windows?
Is there any Linux "echo -e" equivalent in windows so I can use "echo -e \xnnn" to print out the character whose ASCII code is the hexadecimal value nnn ?</p>

答:
There is no equivalent, but you can write your own function.

I would split the problem into two parts.

Convert the hex number to decimal.

Convert the decimal number to ASCII.

Converting from hex to decimal is simple by

```<code>set "myHex=4A"
set /a decimal=0x%myHex%
</code>```

Converting a number to an ASCII is more tricky, it depends of the required ASCII-range

If you only need the range from 32 (space) to 126'~', you could use the =ExitCodeAscii variable

```<code>set "decimal=%1"
cmd /c exit /b %decimal%
echo "%=ExitCodeAscii%"
</code>```

If you need also some special characters like CR, LF, ESC, DEL, it is possible to create them with pure batch.

If you need more than you could use vbscript.

forfiles method

A more general way is to use the command forfiles (Dostips: Generate nearly any character...)

echo-e.bat

```<code>@echo off
set "arg1=%~1"
set "arg1=%arg1:\x=0x%"
forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo(%arg1%"
</code>```

You can call it via echo-e.bat "Hello\x01\x02\x03"
and you get Hello☺☻♥.

ContentLicense: CC BY-SA 2.5

Title: echo -e equivalent in Windows?

Body:
There is no equivalent, but you can write your own function.

I would split the problem into two parts.

Convert the hex number to decimal.

Convert the decimal number to ASCII.

Converting from hex to decimal is simple by

set "myHex=4A"
set /a decimal=0x%myHex%

Converting a number to an ASCII is more tricky, it depends of the required ASCII-range

If you only need the range from 32 (space) to 126'~', you could use the =ExitCodeAscii variable

set "decimal=%1"
cmd /c exit /b %decimal%
echo "%=ExitCodeAscii%"

If you need also some special characters like CR, LF, ESC, DEL, it is possible to create them with pure batch.

If you need more than you could use vbscript.

forfiles method

A more general way is to use the command forfiles (Dostips: Generate nearly any character...)

echo-e.bat

@echo off
set "arg1=%~1"
set "arg1=%arg1:\x=0x%"
forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo(%arg1%"

You can call it via echo-e.bat "Hello\x01\x02\x03"
and you get Hello☺☻♥.


问:
How to avoid SonarQube issue about abstract exceptions?
I am using SonarQube for my code quality analysis. I am coding in java with the use of AbstractJavaSequence from AdroidLogic API.

Many of my project classes extend this class and override execute method which by default declare throws Exception. The SonarQube analysis raises an issue, stating that the class uses a generic exception instead of specific one.

How can I resolve this SonarQube issue?

答:
Just because the method you are overriding throws Exception, it doesn't mean you have to.

You are free to not declare that you throw any exceptions at all, or to throw specific exceptions instead:

```<code>public abstract class ParentClass {
    abstract void doSomething() throws Exception;
}
</code>```

These are all valid (obviously, not all at once):

```<code>public class ChildClass extends ParentClass {
    public void doSomething() {
    }

    public void doSomething() throws MyException {
    }

    public void doSomething() throws Exception {
    }
}
</code>```

There's no reason for you to carry on their bad practices.

Body:
Just because the method you are overriding throws Exception, it doesn't mean you have to.

You are free to not declare that you throw any exceptions at all, or to throw specific exceptions instead:

public abstract class ParentClass {
    abstract void doSomething() throws Exception;
}

These are all valid (obviously, not all at once):

public class ChildClass extends ParentClass {
    public void doSomething() {
    }

    public void doSomething() throws MyException {
    }

    public void doSomething() throws Exception {
    }
}

There's no reason for you to carry on their bad practices.


答:
Change :

```<code>if (index =6)
{
console.log("Mobile");
}
</code>```

To :

```<code>if (index == 6)
{
console.log("Mobile");
}
</code>```

If you use a simple '=' you set the variable

Title: jquery .each , if statements do not work

Body:
Change :

if (index =6)
{
console.log("Mobile");
}

To :

if (index == 6)
{
console.log("Mobile");
}

If you use a simple '=' you set the variable


问:
CollectionView Cell dynamic height for all screensizes
In my project, my collectionview cell comprises of the entire screen width and height, i've set it to horizontal scrolling and for making it dynamic for all screensizes, i am using this method

```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let height: CGFloat = view.frame.size.height
    let width: CGFloat = view.frame.size.width

        return CGSize(width: collectionView.bounds.size.width, height: collectionView.bounds.size.height)
</code>```

its working perfectly fine and takes care of the width and height of all screensizes but the problem is that on scrolling it is cutting of the screen from the right edge, I tried implementing it with a different method viewDidLayoutSubViews() of uicollectionviewdelegateflowlayout and it too takes cares of the screensizes but still has the same issue.The first image is the original cell how it should appear.

the next image is how it cuts off the right edge on scrolling. Initially i've static numberofIteminSection and keeps on cutting with every swipe. This one is the result of third or fourth swipe. I have enabled pagination so i dont know whats the issue here.

I have checked various posts on stack overflow regarding this but nothing seems to help and i am stuck. Any help would be appreciated a lot.

答:
You need to check the screen sizes in sizeForItemAtIndexPath like:

```<code>  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

        let screenSize: CGRect = UIScreen.main.bounds
        let screenWidth = screenSize.width

        if screenWidth == 414{
            return CGSize(width: collectionViewTable.bounds.size.width - 4, height: collectionViewTable.bounds.size.height - 50)

        }else if screenWidth == 375{

            return CGSize(width: collectionViewTable.bounds.size.width - 4, height: collectionViewTable.bounds.size.height - 50)
        }else{

            return CGSize(width: collectionViewTable.bounds.size.width - 4, height: collectionViewTable.bounds.size.height - 50 )
        }
    }
</code>```

Add these functions also and customise according to your need:

```<code>func collectionView(_ collectionView: UICollectionView,
                            layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
            return  UIEdgeInsetsMake( 5,  14, 5,  14)
        }
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
            return 4;
        }

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
        return 4;
    }
</code>```

If this doesn't work then change UIEdgeInsetsMake in insetForSectionAt.

Body:
In my project, my collectionview cell comprises of the entire screen width and height, i've set it to horizontal scrolling and for making it dynamic for all screensizes, i am using this method

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let height: CGFloat = view.frame.size.height
    let width: CGFloat = view.frame.size.width

        return CGSize(width: collectionView.bounds.size.width, height: collectionView.bounds.size.height)

its working perfectly fine and takes care of the width and height of all screensizes but the problem is that on scrolling it is cutting of the screen from the right edge, I tried implementing it with a different method viewDidLayoutSubViews() of uicollectionviewdelegateflowlayout and it too takes cares of the screensizes but still has the same issue.The first image is the original cell how it should appear.

the next image is how it cuts off the right edge on scrolling. Initially i've static numberofIteminSection and keeps on cutting with every swipe. This one is the result of third or fourth swipe. I have enabled pagination so i dont know whats the issue here.

I have checked various posts on stack overflow regarding this but nothing seems to help and i am stuck. Any help would be appreciated a lot.

Body:
You need to check the screen sizes in sizeForItemAtIndexPath like:

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

        let screenSize: CGRect = UIScreen.main.bounds
        let screenWidth = screenSize.width

        if screenWidth == 414{
            return CGSize(width: collectionViewTable.bounds.size.width - 4, height: collectionViewTable.bounds.size.height - 50)

        }else if screenWidth == 375{

            return CGSize(width: collectionViewTable.bounds.size.width - 4, height: collectionViewTable.bounds.size.height - 50)
        }else{

            return CGSize(width: collectionViewTable.bounds.size.width - 4, height: collectionViewTable.bounds.size.height - 50 )
        }
    }

Add these functions also and customise according to your need:

func collectionView(_ collectionView: UICollectionView,
                            layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
            return  UIEdgeInsetsMake( 5,  14, 5,  14)
        }
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
            return 4;
        }

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
        return 4;
    }

If this doesn't work then change UIEdgeInsetsMake in insetForSectionAt.


答:
For some reason best known to themselves, the folk specifying the behaviour of this function set the radix to be a defaultable parameter but then decided to leave the default value up to the implementation! (Perhaps it would have been sensible to insist on a value of 10 but maybe that would have upset folk progamming in the 1970s who still consider octal literals to be useful.)

So for robust progamming, you need to supply the radix parameter yourself.

Title: Why is it recommended to provide optional radix parameter to parseInt()?

Body:
I've always used the parseInt() function in Javascript without passing the radix parameter. As per the MDN documentation here, it's stated that not providing this parameter may result in unpredictable behaviour.

Always specify this parameter to eliminate reader confusion and to
  guarantee predictable behavior.

Could somebody clarify what does this unpredictable behavior mean with some code examples?


问:
Returns 404 after login Laravel 5.4
I'm trying to use the 404 page method in Laravel, it's working fine, the problem is that page 404 is always returned after login, I could not understand why.

My Handler for 404 page

```<code>public function render($request, Exception $exception)
    {
      if($this->isHttpException($exception))
         {
             switch ($exception->getStatusCode())
                 {
                 // not found
                 case 404:
                 return redirect()->route('notfound');
                 break;

                 // internal error
                 case '500':
                 return redirect()->route('notfound');
                 break;

                 default:
                     return $this->renderHttpException($e);
                 break;
             }
         }
         else
         {
                 return parent::render($request, $exception);
        }
    }
</code>```

My routes

```<code>Auth::routes();

Route::get('/', function () {
    return view('welcome');
});

    Route::get('pagina-nao-disponivel', ['as' => 'notfound', 'uses' => 'HomeController@notfound']);
    Route::get('/home', 'HomeController@index')->name('home');
    Route::get('/orders', 'OrderController@index')->name('order');
    Route::post('/orders/create', 'OrderController@create')->name('order::create');
    Route::get('/orders/delete/{id}', 'OrderController@destroy')->name('order::delete');
    Route::get('/orders/approve/{id}', 'OrderController@confirm');
    Route::post('/orders/approve/{id}', 'OrderController@aprove');
    Route::get('/orders/edit/{id}', 'OrderController@edit')->name('order::edit');
    Route::post('/orders/update/{id}', 'OrderController@update')->name('order::update');

    /* Mail Routes */
</code>```

My login controller

```<code>class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = 'home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}
</code>```

Any suggestion? Thank's in advance.

答:
Route::get('/home', 'HomeController@index')->name('home');
in this you can remove /
or
class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

```<code>use AuthenticatesUsers;

/**
 * Where to redirect users after login.
 *
 * @var string
 */
protected $redirectTo = 'home';

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest')->except('logout');
}
</code>```

}

in this you can add '/home' before your home

Title: Returns 404 after login Laravel 5.4

Body:
I'm trying to use the 404 page method in Laravel, it's working fine, the problem is that page 404 is always returned after login, I could not understand why.

My Handler for 404 page

public function render($request, Exception $exception)
    {
      if($this->isHttpException($exception))
         {
             switch ($exception->getStatusCode())
                 {
                 // not found
                 case 404:
                 return redirect()->route('notfound');
                 break;

                 // internal error
                 case '500':
                 return redirect()->route('notfound');
                 break;

                 default:
                     return $this->renderHttpException($e);
                 break;
             }
         }
         else
         {
                 return parent::render($request, $exception);
        }
    }

My routes

Auth::routes();

Route::get('/', function () {
    return view('welcome');
});

    Route::get('pagina-nao-disponivel', ['as' => 'notfound', 'uses' => 'HomeController@notfound']);
    Route::get('/home', 'HomeController@index')->name('home');
    Route::get('/orders', 'OrderController@index')->name('order');
    Route::post('/orders/create', 'OrderController@create')->name('order::create');
    Route::get('/orders/delete/{id}', 'OrderController@destroy')->name('order::delete');
    Route::get('/orders/approve/{id}', 'OrderController@confirm');
    Route::post('/orders/approve/{id}', 'OrderController@aprove');
    Route::get('/orders/edit/{id}', 'OrderController@edit')->name('order::edit');
    Route::post('/orders/update/{id}', 'OrderController@update')->name('order::update');

    /* Mail Routes */

My login controller

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = 'home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

Any suggestion? Thank's in advance.

Body:
Route::get('/home', 'HomeController@index')->name('home');
in this you can remove /
or
class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

use AuthenticatesUsers;

/**
 * Where to redirect users after login.
 *
 * @var string
 */
protected $redirectTo = 'home';

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest')->except('logout');
}

}

in this you can add '/home' before your home


答:
```<code>$("td.ms-formbody").each(function (index) {
  if (index == 6) {
  console.log("Mobile");
  }
}
</code>```


问:
How to use JavaScript global function in Jmeter
How can i use global javaScript function sellerInterface.addBidOnline() in JMeter?
I can use this function in browser, but I do not know how to call it in JMeter.

Use in console

I try using this function in BSF Sampler, but it did not work

enter image description here

答:
As per JMeter Project main page:

JMeter is not a browser, it works at protocol level. As far as web-services and remote services are concerned, JMeter looks like a browser (or rather, multiple browsers); however JMeter does not perform all the actions supported by browsers. In particular, JMeter does not execute the Javascript found in HTML pages. Nor does it render the HTML pages as a browser does (it's possible to view the response as HTML etc., but the timings are not included in any samples, and only one sample in one thread is ever displayed at a time).

If the JavaScript call generates a HTTP Request - you can record it using HTTP(S) Test Script Recorder and replay as HTTP Request sampler. For the time being it is not possible to execute JavaScript from JMeter tests.

You can take a look at WebDriver Sampler which provides JMeter integration with Selenium so each JMeter Thread (virtual user) will have its own real browser so you will be able to execute JavaScript like

```<code>WDS.browser.executeScript('your_script')
</code>```

however real browsers are very resource intensive and the number of browsers you will be able to kick off will be very limited.

Body:
As per JMeter Project main page:

JMeter is not a browser, it works at protocol level. As far as web-services and remote services are concerned, JMeter looks like a browser (or rather, multiple browsers); however JMeter does not perform all the actions supported by browsers. In particular, JMeter does not execute the Javascript found in HTML pages. Nor does it render the HTML pages as a browser does (it's possible to view the response as HTML etc., but the timings are not included in any samples, and only one sample in one thread is ever displayed at a time).

If the JavaScript call generates a HTTP Request - you can record it using HTTP(S) Test Script Recorder and replay as HTTP Request sampler. For the time being it is not possible to execute JavaScript from JMeter tests.

You can take a look at WebDriver Sampler which provides JMeter integration with Selenium so each JMeter Thread (virtual user) will have its own real browser so you will be able to execute JavaScript like

WDS.browser.executeScript('your_script')

however real browsers are very resource intensive and the number of browsers you will be able to kick off will be very limited.


问:
Oracle SQL WITH clause correct use case and performance
I have to perform relatively complicated query involving multiple deep joins and complex predicates, where the result (and criteria) depends of suitable entries available meeting the criteria. There are kinda primary and secondary criteria involved, primary is applied always, and secondary strikes in if the the result is not satisfying. In a nutshell

Return N (pseudo) random  distinct customers and their newest document

The result should contain equal amount of documents of two different type

But if there's not enough different document types or different customers with a document, try to still satisfy the amount of N documents

Compensate the lack of other document type by choosing more another

Compensate the lack of overall document count by using multiple documents of the same customers, when necessary

I choose declarative (query) approach over imperative (cursors and counters). And this is where the WITH clause comes in. Roughly, by using multiple WITH blocks (CTE's) I declare queries (I like to think them as ad-hoc views) to declare two distinct target set for both document types. In the end, I UNION subsets of different CTE's for the final result, performing some COUNT checks to limit the amount.

Multiple CTE's are referencing each other and are referenced from multiple places in the context of COUNT and NOT EXISTS for example. I'm novice with SQL and happened to encounter WITH by a coincidence, and chose to use it intuitively. Is this the correct use case for WITH, or an anti pattern? How does this solution compares in performance to implementing the same functionality with cursors and counters in an imperative style? Have I chosen the wrong approach? We are talking about tables with million entries.

Here is the the query as a whole. Pardon me, I had to obscure the fields due confidentiality.

```<code>    WITH target_documents AS (
        SELECT
            <Necessary fields>
        FROM documents l
        WHERE
            <Suitable document criteria>
    ),
    target_documents_type_1 AS (
        SELECT * FROM target_documents WHERE type = 1
    ),
    target_documents_type_2 AS (
        SELECT * FROM target_documents WHERE type = 2
    ),
    target_customers AS (
        SELECT
            <Necessary fields>
        FROM customers a
        WHERE
            <Suitable customer criteria>
            AND
            EXISTS(
                SELECT 1 FROM target_documents l WHERE l.customer_id = a.customer_id
            )
    ),
    target_customers_type_1 AS (
        SELECT * FROM target_customers a WHERE EXISTS(
            SELECT 1 FROM target_documents_type_1 l WHERE l.customer_id = a.customer_id
        )
        AND ROWNUM <= (<N> / 2)
    ),
    target_customers_type_2 AS (
        SELECT * FROM target_customers a WHERE EXISTS(
            SELECT 1 FROM target_documents_type_2 l WHERE l.customer_id = a.customer_id
        )
        AND a.customer_id NOT IN (
            SELECT customer_id FROM target_customers_type_1
        )
        AND ROWNUM <= <N>
    ),
    -- This is the set, which meets the the primary criteria:
    -- Contains only distinct customers
    -- The amount of different document types is balanced as much as possible
    different_customers_set AS (
        SELECT
            <Necessary fields>
        FROM target_customers_type_1 a -- rows 0--(<N>/2) amount
        JOIN target_documents_type_1 l ON (l.customer_id = a.customer_id)
        WHERE
            l.create_dt = (SELECT MAX(create_dt) FROM target_documents_type_1 WHERE customer_id = l.customer_id)
        UNION ALL
        SELECT
            <Necessary fields>
        FROM target_customers_type_2 a -- rows 0--<N> amount
        JOIN target_documents_type_2 l ON (l.customer_id = a.customer_id)
        WHERE
            l.create_dt = (SELECT MAX(create_dt) FROM target_documents_type_2 WHERE customer_id = l.customer_id) AND
            ROWNUM <= <N> - (SELECT COUNT(*) FROM target_customers_type_1) -- Limit the total to max N rows
    )

    -- Final result: primary criteria result filled with the result of secondary criteria
    SELECT * FROM different_customers_set
    UNION ALL
    SELECT
        <Necessary fields>
    FROM target_customers a
    JOIN target_documents l ON (l.customer_id = a.customer_id AND l.document_id NOT IN (SELECT document_id FROM different_customers_set))
    WHERE
        ROWNUM <= <N> - (SELECT COUNT(1) FROM different_customers_set);
</code>```

Is this the correct usage of WITH clause? Are there some obvious performance issues, where I should refactor? Or should I have done all this imperatively? Also, this query itself defines a cursor, which is used opened repeatedly in a loop (the loop defines certain criteria for customers).

I'm especially concerned, how the optimizer handles those WITH blocks. Is the most efficiently plan always used (so there's not performance penalty compared to using cursors)?

答:
In general this seems like a good place to use CTE. I would not expect any issues for the optimiser.

target_customers_type_2 CTE reference itself (probably should be referencing target_documents_type_2).

Filtering by ROWNUM and generating "random" results should be avoided like a plague. Very difficult to test and debug.

"Cursor used repeatedly in a loop" sounds very worying. Can there be a scope for temporary table use instead?

Body:
I have to perform relatively complicated query involving multiple deep joins and complex predicates, where the result (and criteria) depends of suitable entries available meeting the criteria. There are kinda primary and secondary criteria involved, primary is applied always, and secondary strikes in if the the result is not satisfying. In a nutshell

Return N (pseudo) random  distinct customers and their newest document

The result should contain equal amount of documents of two different type

But if there's not enough different document types or different customers with a document, try to still satisfy the amount of N documents

Compensate the lack of other document type by choosing more another

Compensate the lack of overall document count by using multiple documents of the same customers, when necessary

I choose declarative (query) approach over imperative (cursors and counters). And this is where the WITH clause comes in. Roughly, by using multiple WITH blocks (CTE's) I declare queries (I like to think them as ad-hoc views) to declare two distinct target set for both document types. In the end, I UNION subsets of different CTE's for the final result, performing some COUNT checks to limit the amount.

Multiple CTE's are referencing each other and are referenced from multiple places in the context of COUNT and NOT EXISTS for example. I'm novice with SQL and happened to encounter WITH by a coincidence, and chose to use it intuitively. Is this the correct use case for WITH, or an anti pattern? How does this solution compares in performance to implementing the same functionality with cursors and counters in an imperative style? Have I chosen the wrong approach? We are talking about tables with million entries.

Here is the the query as a whole. Pardon me, I had to obscure the fields due confidentiality.

    WITH target_documents AS (
        SELECT
            <Necessary fields>
        FROM documents l
        WHERE
            <Suitable document criteria>
    ),
    target_documents_type_1 AS (
        SELECT * FROM target_documents WHERE type = 1
    ),
    target_documents_type_2 AS (
        SELECT * FROM target_documents WHERE type = 2
    ),
    target_customers AS (
        SELECT
            <Necessary fields>
        FROM customers a
        WHERE
            <Suitable customer criteria>
            AND
            EXISTS(
                SELECT 1 FROM target_documents l WHERE l.customer_id = a.customer_id
            )
    ),
    target_customers_type_1 AS (
        SELECT * FROM target_customers a WHERE EXISTS(
            SELECT 1 FROM target_documents_type_1 l WHERE l.customer_id = a.customer_id
        )
        AND ROWNUM <= (<N> / 2)
    ),
    target_customers_type_2 AS (
        SELECT * FROM target_customers a WHERE EXISTS(
            SELECT 1 FROM target_documents_type_2 l WHERE l.customer_id = a.customer_id
        )
        AND a.customer_id NOT IN (
            SELECT customer_id FROM target_customers_type_1
        )
        AND ROWNUM <= <N>
    ),
    -- This is the set, which meets the the primary criteria:
    -- Contains only distinct customers
    -- The amount of different document types is balanced as much as possible
    different_customers_set AS (
        SELECT
            <Necessary fields>
        FROM target_customers_type_1 a -- rows 0--(<N>/2) amount
        JOIN target_documents_type_1 l ON (l.customer_id = a.customer_id)
        WHERE
            l.create_dt = (SELECT MAX(create_dt) FROM target_documents_type_1 WHERE customer_id = l.customer_id)
        UNION ALL
        SELECT
            <Necessary fields>
        FROM target_customers_type_2 a -- rows 0--<N> amount
        JOIN target_documents_type_2 l ON (l.customer_id = a.customer_id)
        WHERE
            l.create_dt = (SELECT MAX(create_dt) FROM target_documents_type_2 WHERE customer_id = l.customer_id) AND
            ROWNUM <= <N> - (SELECT COUNT(*) FROM target_customers_type_1) -- Limit the total to max N rows
    )

    -- Final result: primary criteria result filled with the result of secondary criteria
    SELECT * FROM different_customers_set
    UNION ALL
    SELECT
        <Necessary fields>
    FROM target_customers a
    JOIN target_documents l ON (l.customer_id = a.customer_id AND l.document_id NOT IN (SELECT document_id FROM different_customers_set))
    WHERE
        ROWNUM <= <N> - (SELECT COUNT(1) FROM different_customers_set);

Is this the correct usage of WITH clause? Are there some obvious performance issues, where I should refactor? Or should I have done all this imperatively? Also, this query itself defines a cursor, which is used opened repeatedly in a loop (the loop defines certain criteria for customers).

I'm especially concerned, how the optimizer handles those WITH blocks. Is the most efficiently plan always used (so there's not performance penalty compared to using cursors)?