问:
Two forms and buttons bootstrap ajax
I have a problem with my page. It's in HTML, Bootstrap, and PHP.

I have two forms in the HTML page. First is the contact form, and the other is in a modal and that's the distribution form.

The problem is the data in the distribution form because when I click the button, it sends the contact form only and not the distribution form.

Here is the code.

Distribution form:

```<code><div class="col-lg-12 animated slideInUp">
        <form name="sentMessage" action="contact_me.php"  id="contactForm2" novalidate>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="NOMBRE *" id="name" required data-validation-required-message="Por favor introduce tu nombre.">
                        <p class="help-block text-danger"></p>
                    </div>
                    <div class="form-group">
                        <input type="email" class="form-control" placeholder="EMAIL *" id="email" required data-validation-required-message="Por favor introduce tu E-mail.">
                        <p class="help-block text-danger"></p>
                    </div>
                    <div class="form-group">
                        <input type="tel" class="form-control" placeholder="TELEFONO *" id="phone" required data-validation-required-message="Por favor introduce tu numero de Telefono.">
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <textarea class="form-control" style="height:135px;" placeholder="TU MENSAJE *" id="message" required data-validation-required-message="Por favor introduce tu mensaje."></textarea>
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <div class="clearfix"></div>
                <div class="col-lg-12 text-center">
                    <div id="success"></div>
                    <button type="submit" class="btn btn-primary">UNIRME AL EQUIPO</button>
                </div>
            </div>
        </form>
    </div>
</div>
</code>```

Contact form:

```<code><div class="col-lg-12">
    <form name="sentMessage" action="contact_me.php" id="contactForm" novalidate>
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <input type="text" class="form-control" placeholder="NOMBRE *" id="name" required data-validation-required-message="Por favor introduce tu nombre.">
                    <p class="help-block text-danger"></p>
                </div>
                <div class="form-group">
                    <input type="email" class="form-control" placeholder="EMAIL *" id="email" required data-validation-required-message="Por favor introduce tu E-mail.">
                    <p class="help-block text-danger"></p>
                </div>
                <div class="form-group">
                    <input type="tel" class="form-control" placeholder="TELEFONO *" id="phone" required data-validation-required-message="Por favor introduce tu numero de Telefono.">
                    <p class="help-block text-danger"></p>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <textarea class="form-control" placeholder="TU MENSAJE *" id="message" required data-validation-required-message="Por favor introduce tu mensaje."></textarea>
                    <p class="help-block text-danger"></p>
                </div>
            </div>
            <div class="clearfix"></div>
            <div class="col-lg-12 text-center">
                <div id="success"></div>
                <button type="submit" class="btn btn-primary">Enviar Mensaje</button>
            </div>
        </div>
    </form>
</div>
</code>```

JavaScript contact_me:

```<code>$(function() {

    $("input,textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "../contact_me.php",
                type: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message
                },
                cache: false,
                success: function() {
                    // Success message
                    $('#success').html("<div class='alert alert-success'>");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("<strong>Tu mensaje ha sido enviado. </strong>");
                    $('#success > .alert-success')
                        .append('</div>');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("<div class='alert alert-danger'>");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('</div>');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            })
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});
</code>```

答:
The problem is caused because you've got the same id names in both forms. It's important to keep id names unique for each page (as a matter principle and good practice) but if you don't, jQuery grabs the first matching id - which is why only the inputs from the first form are submitted.

I suggest changing the ids of the second form to name_1, email_1, phone_1 and message_1 (to make them unique) and then in the script replace:

```<code>// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
</code>```

With:

```<code>// Determine which form is being submitted
var form_0 = $form.attr('id') === 'contactForm2' ? true : false;

// If it's the first form, assign the values from that form,
// otherwise assign the values from the second form
var name = form_0 ? $('#name').val() : $('#name_1').val();
var email = form_0 ? $('#email').val() : $('#email_1').val();
var phone = form_0 ? $('#phone').val() : $('#phone_1').val();
var message = form_0 ? $('#message').val() : $('#message_1').val();
</code>```

and then the correct values are submitted with the appropriate form.

Hope this helps.

If you're not familiar with the 'ternary' operators in the code above - they're just handy shortcuts for if{} else{} statements - check out: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

Title: Two forms and buttons bootstrap ajax

Body:
I have a problem with my page. It's in HTML, Bootstrap, and PHP.

I have two forms in the HTML page. First is the contact form, and the other is in a modal and that's the distribution form.

The problem is the data in the distribution form because when I click the button, it sends the contact form only and not the distribution form.

Here is the code.

Distribution form:

        <form name="sentMessage" action="contact_me.php"  id="contactForm2" novalidate>

                        <input type="text" class="form-control" placeholder="NOMBRE *" id="name" required data-validation-required-message="Por favor introduce tu nombre.">

                        <input type="email" class="form-control" placeholder="EMAIL *" id="email" required data-validation-required-message="Por favor introduce tu E-mail.">

                        <input type="tel" class="form-control" placeholder="TELEFONO *" id="phone" required data-validation-required-message="Por favor introduce tu numero de Telefono.">

                        <textarea class="form-control" style="height:135px;" placeholder="TU MENSAJE *" id="message" required data-validation-required-message="Por favor introduce tu mensaje."></textarea>

                    <button type="submit" class="btn btn-primary">UNIRME AL EQUIPO</button>

        </form>

Contact form:

    <form name="sentMessage" action="contact_me.php" id="contactForm" novalidate>

                    <input type="text" class="form-control" placeholder="NOMBRE *" id="name" required data-validation-required-message="Por favor introduce tu nombre.">

                    <input type="email" class="form-control" placeholder="EMAIL *" id="email" required data-validation-required-message="Por favor introduce tu E-mail.">

                    <input type="tel" class="form-control" placeholder="TELEFONO *" id="phone" required data-validation-required-message="Por favor introduce tu numero de Telefono.">

                    <textarea class="form-control" placeholder="TU MENSAJE *" id="message" required data-validation-required-message="Por favor introduce tu mensaje."></textarea>

                <button type="submit" class="btn btn-primary">Enviar Mensaje</button>

    </form>

JavaScript contact_me:

$(function() {

    $("input,textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "../contact_me.php",
                type: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message
                },
                cache: false,
                success: function() {
                    // Success message
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Tu mensaje ha sido enviado. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("
");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('
');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            })
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

Body:
The problem is caused because you've got the same id names in both forms. It's important to keep id names unique for each page (as a matter principle and good practice) but if you don't, jQuery grabs the first matching id - which is why only the inputs from the first form are submitted.

I suggest changing the ids of the second form to name_1, email_1, phone_1 and message_1 (to make them unique) and then in the script replace:

// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();

With:

// Determine which form is being submitted
var form_0 = $form.attr('id') === 'contactForm2' ? true : false;

// If it's the first form, assign the values from that form,
// otherwise assign the values from the second form
var name = form_0 ? $('#name').val() : $('#name_1').val();
var email = form_0 ? $('#email').val() : $('#email_1').val();
var phone = form_0 ? $('#phone').val() : $('#phone_1').val();
var message = form_0 ? $('#message').val() : $('#message_1').val();

and then the correct values are submitted with the appropriate form.

Hope this helps.

If you're not familiar with the 'ternary' operators in the code above - they're just handy shortcuts for if{} else{} statements - check out: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator


来源: stackexchange

问:
Low pass filter in iPhone
I have code that implements a low-pass filter in order to detect a blow on the mic.
I can't understand how to determine the frequency and pick my own ALPHA:

```<code>lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults;
</code>```

This should detect a blow on the mic.

I want to get a new ALPHA to implement a lowpass filter with fc = 1 khz or higher.

How do i pick another ALPHA to do that ?

They took ALPHA=0.05 and according to Wikipedia formula, with sample rate of 30 times a second which they did, I got fc of 1.2 Hz.

Or should I take a sample rate of 44.1 kHz ? We sample the signal at 30 Hz.

答:
This page gives perhaps a clearer version of the formula, with code for choosing alpha:

```<code>void lowPassFrequency(double* input, double* output, int points)
{
    double RC = 1.0/(CUTOFF*2*3.14);
    double dt = 1.0/SAMPLE_RATE;
    double alpha = dt/(RC+dt);
    output[0] = input[0]
    for(int i = 1; i < points; ++i)
    {
        output[i] = output[i-1] + (alpha*(input[i] - output[i-1]));
    }
}
</code>```

Note that it works on all sample points at once, rather than over time as in original question.

ContentLicense: CC BY-SA 3.0

Title: Low pass filter in iPhone

Body:
I have code that implements a low-pass filter in order to detect a blow on the mic.
I can't understand how to determine the frequency and pick my own ALPHA:

lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults;

This should detect a blow on the mic.

I want to get a new ALPHA to implement a lowpass filter with fc = 1 khz or higher.

How do i pick another ALPHA to do that ?

They took ALPHA=0.05 and according to Wikipedia formula, with sample rate of 30 times a second which they did, I got fc of 1.2 Hz.

Or should I take a sample rate of 44.1 kHz ? We sample the signal at 30 Hz.

Body:
This page gives perhaps a clearer version of the formula, with code for choosing alpha:

void lowPassFrequency(double* input, double* output, int points)
{
    double RC = 1.0/(CUTOFF*2*3.14);
    double dt = 1.0/SAMPLE_RATE;
    double alpha = dt/(RC+dt);
    output[0] = input[0]
    for(int i = 1; i < points; ++i)
    {
        output[i] = output[i-1] + (alpha*(input[i] - output[i-1]));
    }
}

Note that it works on all sample points at once, rather than over time as in original question.


问:
Make div appear next to other
I have started a huge revision on my css knowledge.
I am trying to do the following:
I want to create a wrapper div that contains to divs with some text and some content.I want each div with class item-2 inside that div to have a width:50%
and appear next to another item-2.
Here is a snippet of my code:

body{
  background:rgba(10,10,10,.8);
}
.wrapper{
  position:relative;
  width:100%;
  margin:auto;
}
.item-2{
    text-align:center;
    display:inline-block;
    width:50%;
    border:2px solid blue;
 }
.demo{
  margin:auto;
  height:5em;
  width:5em;
  background:yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='wrapper'>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>

</div>  </code>```

As you can see it's div appears below its previous div.However I want them to be next to each other.How can I achieve this? I would like an explanation to your solution sa as to improve my knowledge

答:
Flex can keep them in one row.

```<code>.wrapper {
  display: flex;
 }
</code>```

And remove display: inline block for items. If you want in small devices they are under each other add this to .wrapper

```<code>  flex-wrap: wrap;
</code>```

And we need a min-width for items. .items: min-width: 250px;. If your device has enough space (500px) they will remain in one line, else the second item goes to next line.

Title: Make div appear next to other

Body:
I have started a huge revision on my css knowledge.
I am trying to do the following:
I want to create a wrapper div that contains to divs with some text and some content.I want each div with class item-2 inside that div to have a width:50%
and appear next to another item-2.
Here is a snippet of my code:

body{
  background:rgba(10,10,10,.8);
}
.wrapper{
  position:relative;
  width:100%;
  margin:auto;
}
.item-2{
    text-align:center;
    display:inline-block;
    width:50%;
    border:2px solid blue;
 }
.demo{
  margin:auto;
  height:5em;
  width:5em;
  background:yellow;
}

Title 1

Title 1

As you can see it's div appears below its previous div.However I want them to be next to each other.How can I achieve this? I would like an explanation to your solution sa as to improve my knowledge

Body:
Flex can keep them in one row.

.wrapper {
  display: flex;
 }

And remove display: inline block for items. If you want in small devices they are under each other add this to .wrapper

  flex-wrap: wrap;

And we need a min-width for items. .items: min-width: 250px;. If your device has enough space (500px) they will remain in one line, else the second item goes to next line.


问:
How to handle "View count" in redis
Our DB is mostly reads, but we want to add a "View count" and "thumbs up/thumbs down" to our videos.

When we stress tested incrementing views in mysql, our database started deadlocking.

I was thinking about handling this problem by having a redis DB that holds the view count, and only writes to the DB once the key expires. But, I hear the notifications are not consistent, and I don't want to lose the view data.

Is there a better way of going about this? Or is the talk of redis notifications being inconsistent not true.

Thanks,

Sammy

答:
Redis' keyspace notifications are consistent, but delivery isn't guaranteed.

If you don't want to lose data, implement your own background process that manually expires the counters -  i.e. copies to MySQL and deleted from Redis.

There are several approaches to implementing this lazy eviction pattern. For example, you can use a Redis Hash with two fields: a value field that you can HINCRBY and a timestamp field for expiry logic purposes. Your background process can then SCAN the keyspace to identify outdated keys.

Another way is to use Sorted Sets to manage the counters. In some cases you can use just one Sorted Set, encoding both TTL and count into each member's score (using the float's integer and fractional parts, respectively), but in most cases it is simpler to use two Sorted Sets - one for TTLs and the other fur values.

Title: How to handle "View count" in redis


问:
R plot points at irregular dates
I am trying to plot a graph of fund prices at irregular dates.

E.g.

```<code>salpr = c(1, 1.2, 1.4, 1.6, 2, 5, 7, 9)
         # yyyy-mm-dd
saldt = c("2015-01-01", "2015-01-07", "2015-01-14", "2015-02-01",
          "2015-03-01", "2015-04-01", "2015-05-01", "2015-06-01" )
dd = data.frame(saldt,salpr)
</code>```

Here is my effort ...

```<code>with(dd, plot(saldt, salpr, xaxt="s"))

axis.Date(1, at=seq(min(as.Date(dd$saldt)), max(as.Date(dd$saldt)), by="months"), format="%m-%Y")
text(dd$saldt, dd$salpr+0.5,dd$salpr)
</code>```

I want to use plot as I've don't have access to ggplot on my controlled environment.

Any help appreciated.

Title: R plot points at irregular dates

Body:
I am trying to plot a graph of fund prices at irregular dates.

E.g.

salpr = c(1, 1.2, 1.4, 1.6, 2, 5, 7, 9)
         # yyyy-mm-dd
saldt = c("2015-01-01", "2015-01-07", "2015-01-14", "2015-02-01",
          "2015-03-01", "2015-04-01", "2015-05-01", "2015-06-01" )
dd = data.frame(saldt,salpr)

Here is my effort ...

with(dd, plot(saldt, salpr, xaxt="s"))

axis.Date(1, at=seq(min(as.Date(dd$saldt)), max(as.Date(dd$saldt)), by="months"), format="%m-%Y")
text(dd$saldt, dd$salpr+0.5,dd$salpr)

I want to use plot as I've don't have access to ggplot on my controlled environment.

Any help appreciated.

Body:
Simple code as below seems to do what you are after (?)

salpr = c(1, 1.2, 1.4, 1.6, 2, 5, 7, 9)
# yyyy-mm-dd
saldt <- as.Date(c("2015-01-01", "2015-01-07", "2015-01-14", "2015-02-01",
          "2015-03-01", "2015-04-01", "2015-05-01", "2015-06-01" ))
dd <- data.frame(saldt,salpr)


问:
how to convert a single text file to a csv
Im trying to take in a table from a text file and then output it (or convert it) to a csv for easier manipulation. I looked and cannot find any specific help on this task.

The text file looks something like this:

```<code>C#             CLA OLA Quiz Exam FinalExam
c1234501    10 20 10 30 30
c1234502     9 10  5 20 20
c1234503    10 17  8 27 27
c1234504     8 14 10 29 15
c1234505     7 18  3 24 27
</code>```

and I would like to get it to output like this:

```<code>C#,CLA,OLA,Quiz,Exam,FinalExam,
c1234501,10,20,10,30,30,
c1234502,9,10,5,20,20,
c1234503,10,17,8,27,27,
c1234504,8, 14, 10, 29, 15,
c1234505,7, 18,  3, 24, 27,
</code>```

with the comma as the delimiter.
So far Ive come up with this code:

```<code>tab = read.delim(file, header = TRUE)
write.table(tab, file="name_file.csv",sep=",",col.names=TRUE,row.names=FALSE)
</code>```

but the results arent what I thought they would be:

```<code>"C.","CLA.OLA.Quiz.Exam.FinalExam"
"c1234501","10 20 10 30 30"
"c1234502"," 9 10  5 20 20"
"c1234503","10 17  8 27 27"
"c1234504   "," 8 14 10 29 15"
"c1234505   "," 7 18  3 24 27"
</code>```

any help would be greatly appreciated. Thanks!

答:
In explicit terms:

```<code>tab <- read.table("name_file.txt", comment="", header=TRUE)
write.csv(tab, "name_file.csv", row.names=FALSE, quote=FALSE)
</code>```

I know you didn't ask for it, but if you're essentially using R as a file converter, it might be more convenient to just use sed or something similar through a console/terminal. F.ex:

```<code>sed -E 's/[[:blank:]]+/,/g' name_file.txt > name_file.csv
</code>```

Body:
Im trying to take in a table from a text file and then output it (or convert it) to a csv for easier manipulation. I looked and cannot find any specific help on this task.

The text file looks something like this:

C#             CLA OLA Quiz Exam FinalExam
c1234501    10 20 10 30 30
c1234502     9 10  5 20 20
c1234503    10 17  8 27 27
c1234504     8 14 10 29 15
c1234505     7 18  3 24 27

and I would like to get it to output like this:

C#,CLA,OLA,Quiz,Exam,FinalExam,
c1234501,10,20,10,30,30,
c1234502,9,10,5,20,20,
c1234503,10,17,8,27,27,
c1234504,8, 14, 10, 29, 15,
c1234505,7, 18,  3, 24, 27,

with the comma as the delimiter.
So far Ive come up with this code:

tab = read.delim(file, header = TRUE)
write.table(tab, file="name_file.csv",sep=",",col.names=TRUE,row.names=FALSE)

but the results arent what I thought they would be:

"C.","CLA.OLA.Quiz.Exam.FinalExam"
"c1234501","10 20 10 30 30"
"c1234502"," 9 10  5 20 20"
"c1234503","10 17  8 27 27"
"c1234504   "," 8 14 10 29 15"
"c1234505   "," 7 18  3 24 27"

any help would be greatly appreciated. Thanks!

Body:
In explicit terms:

tab <- read.table("name_file.txt", comment="", header=TRUE)
write.csv(tab, "name_file.csv", row.names=FALSE, quote=FALSE)

I know you didn't ask for it, but if you're essentially using R as a file converter, it might be more convenient to just use sed or something similar through a console/terminal. F.ex:

sed -E 's/[[:blank:]]+/,/g' name_file.txt > name_file.csv


问:
Conflict on IIS 7.5 with web.config when mixing different versions of ASP.NET
I am setting up a new website on new web servers that are running IIS 7.5, which is new to me.  I have ran into a problem when deploying an ASP.NET app that is using the 4.0 framework.  I get error messages about conflicts with the web.config file associated with the Default Web Site.  The asp.net app defined in the default website is using the 2.0 framework currently.

My 4.0 framework app is defined as an application under the default website.  Both are using different Application Pools.

I tried adding this to my 4.0 apps config file, but it did not seem to help:

```<code><location path="." inheritInChildApplications="false">
</code>```

How do I get around this web.config conflict issue?

Update for error message:

```<code>There is a duplicate 'system.web.extensions/scripting/scriptResourceHandler' section defined.

The config file for the 4.0 app does not even have this section.  The default website app does have this.
</code>```

答: Have you tried putting the location tag around the system.web section of the default web application?  It sounds like that is what you want to prevent inheritance on, not the 4.0 app (if I understand you right, the 4.0 app is the "child" app of the 2.0 default app).</p>

ContentLicense: CC BY-SA 2.5

Body:
I am setting up a new website on new web servers that are running IIS 7.5, which is new to me.  I have ran into a problem when deploying an ASP.NET app that is using the 4.0 framework.  I get error messages about conflicts with the web.config file associated with the Default Web Site.  The asp.net app defined in the default website is using the 2.0 framework currently.

My 4.0 framework app is defined as an application under the default website.  Both are using different Application Pools.

I tried adding this to my 4.0 apps config file, but it did not seem to help:

<location path="." inheritInChildApplications="false">

How do I get around this web.config conflict issue?

Update for error message:

There is a duplicate 'system.web.extensions/scripting/scriptResourceHandler' section defined.

The config file for the 4.0 app does not even have this section.  The default website app does have this.


问:
JavaScript (jQuery) just keeps appending data to a

I'm trying to write a simple chat application in Python using Django. Basically I have an empty div which I then use jQuery to append some HTML to from some JSON I get from the server. I've checked the output from the server and the JSON returned is correct so it is not a problem with Django or Python.

This is my JavaScript:

```<code><script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function() {
        window.setInterval(function() {
            $.getJSON("/chat/messages/" + String({{ channel.id }}) + "/", function(data) {
                $("#id_chat_area").html() // clear all HTML in the div before we start printing chat messages
                $.each(data, function(key, val) {
                    $("#id_chat_area").append("<p>" + String(val.username) + ": " + String(val.message) + "</p>")
                });
            });
        }, 5000); // length of time to refresh the function 1000 = 1 second
    }, false);
</script>
</code>```

as you can see I have:

```<code>$("#id_chat_area").html()
</code>```

which I thought would completely clear the div of HTML every time the loop iterates but instead the data returned from the JSON just keeps printing forever without end just appending data on every loop round without clearing the div. Can anyone suggest some code that would clear the div every time that function is executed by the browser so it just shows the data from the last iteration of the loop?

If there is anymore information you need I would be happy to provide it. I'm stumped on this one.

答:
change

$("#id_chat_area").html() to $("#id_chat_area").html("") might help.

My thought process is that one calls for the html .html() and the other clears it .html("")..

Title: JavaScript (jQuery) just keeps appending data to a <div>

Body:
I'm trying to write a simple chat application in Python using Django. Basically I have an empty div which I then use jQuery to append some HTML to from some JSON I get from the server. I've checked the output from the server and the JSON returned is correct so it is not a problem with Django or Python.

This is my JavaScript:

as you can see I have:

$("#id_chat_area").html()

which I thought would completely clear the div of HTML every time the loop iterates but instead the data returned from the JSON just keeps printing forever without end just appending data on every loop round without clearing the div. Can anyone suggest some code that would clear the div every time that function is executed by the browser so it just shows the data from the last iteration of the loop?

If there is anymore information you need I would be happy to provide it. I'm stumped on this one.


问:
Function Not Defined in Angular
Hi I keep getting this error.  I am trying to make broken image icons not appear in an Angular Ionic app.  I have tis function but it keeps saying anonImg is not defined.  Im not sure how to define this?

function anonImg(image){
  image.src = 'https://instagramimages-a.akamaihd.net/profiles/anonymousUser.jpg';
     }```
</div>
</div>
</p>

<p>and my html is </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><ion-content class="climb-pics">
      <img ng-src="{{urlForImage(selected_.images)}}"/>
      <img onerror="anonImg(this);" ng-src="{{urlForImage(selected_.imageTwo)}}"/>
      <button type="button" class="button button-assertive" ng-click="closeModal(1)">Close</button>
      <p> </p>
    </ion-content></code>```

Should I be wrapping the function in a function or something? I just don't now what to do when I get the error "ReferenceError: anonImg is not defined"

Here is my controller code:

```<code>    .controller('ClimbController', ['$scope', '$stateParams', 'Products', 'Climbs', '$ionicModal', '$localStorage', '$cordovaCamera', '$cordovaFile',
    function($scope, $stateParams, Products, Climbs, $ionicModal, $localStorage, $cordovaCamera, $cordovaFile) {

        $scope.product_id = $stateParams.productId;
        console.log('ClimbController: ' + $scope.product_id);
        // ClimbsController: 2

        $scope.urlForImage = function(imagePath) {
            console.log('imagePath: ' + imagePath);
            return Products.urlForImage($scope.product_id, imagePath);
        }

        var filename = Products.getFilenameFromLocalStorage($scope.product_id);
        console.log(filename);

        var climbId = $stateParams.climbId;
        var areaId = $stateParams.areaId;

        if (!isNaN(climbId)) {
            climbId = parseInt(climbId);
        }

        if (!isNaN(areaId)) {
            areaId = parseInt(areaId);
        }

        $scope.selected_ = {};
        $scope.items = [];
        $scope.details = true;
        $scope.data = '';
        $scope.noteParams = {
            text: null
        };

        // looping though all data and get particular product
        $scope.selectClimb = function(areas){
            areas.forEach(function(data) {
                if(data._id == climbId){
                    $scope.selected_ = data;
                }
            });
        }

        // get all posts // try some function to get a single produt from server
        $scope.getPosts = function(){
            Products.loadGuidebook(filename).then(function(data) {
                // NOTE: data = the whole feed.json file
                console.log(data);

                // data = feed.json file

                var climbs = [];
                data.areas.map(function(area) {
                    if (area._id === areaId) {
                        climbs = area.climbs;
                    }
                });
                $scope.selectClimb(climbs);
            },
            function (error) {
                console.log(error);
            });
        }

        // picture slider logic
        $scope.allImages = $scope.images;

        //hide div with broken images
        anonImg = function(image){
            image.src = 'https://instagramimages-a.akamaihd.net/profiles/anonymousUser.jpg';
        }

        $scope.load();
        $scope.getPosts();
    }
])
</code>```

答:
You have not posted the Controller code, You should have $scope in your controller and the function should be defined as,</p>

```<code>$scope.anonImg = function(image){
  image.src = 'https://instagramimages-a.akamaihd.net/profiles/anonymousUser.jpg';
}
</code>```

Title: Function Not Defined in Angular

Body:
Hi I keep getting this error.  I am trying to make broken image icons not appear in an Angular Ionic app.  I have tis function but it keeps saying anonImg is not defined.  Im not sure how to define this?

function anonImg(image){
  image.src = 'https://instagramimages-a.akamaihd.net/profiles/anonymousUser.jpg';
     }

and my html is

<ion-content class="climb-pics">

      <button type="button" class="button button-assertive" ng-click="closeModal(1)">Close</button>

    </ion-content>

Should I be wrapping the function in a function or something? I just don't now what to do when I get the error "ReferenceError: anonImg is not defined"

Here is my controller code:

    .controller('ClimbController', ['$scope', '$stateParams', 'Products', 'Climbs', '$ionicModal', '$localStorage', '$cordovaCamera', '$cordovaFile',
    function($scope, $stateParams, Products, Climbs, $ionicModal, $localStorage, $cordovaCamera, $cordovaFile) {

        $scope.product_id = $stateParams.productId;
        console.log('ClimbController: ' + $scope.product_id);
        // ClimbsController: 2

        $scope.urlForImage = function(imagePath) {
            console.log('imagePath: ' + imagePath);
            return Products.urlForImage($scope.product_id, imagePath);
        }

        var filename = Products.getFilenameFromLocalStorage($scope.product_id);
        console.log(filename);

        var climbId = $stateParams.climbId;
        var areaId = $stateParams.areaId;

        if (!isNaN(climbId)) {
            climbId = parseInt(climbId);
        }

        if (!isNaN(areaId)) {
            areaId = parseInt(areaId);
        }

        $scope.selected_ = {};
        $scope.items = [];
        $scope.details = true;
        $scope.data = '';
        $scope.noteParams = {
            text: null
        };

        // looping though all data and get particular product
        $scope.selectClimb = function(areas){
            areas.forEach(function(data) {
                if(data._id == climbId){
                    $scope.selected_ = data;
                }
            });
        }

        // get all posts // try some function to get a single produt from server
        $scope.getPosts = function(){
            Products.loadGuidebook(filename).then(function(data) {
                // NOTE: data = the whole feed.json file
                console.log(data);

                // data = feed.json file

                var climbs = [];
                data.areas.map(function(area) {
                    if (area._id === areaId) {
                        climbs = area.climbs;
                    }
                });
                $scope.selectClimb(climbs);
            },
            function (error) {
                console.log(error);
            });
        }

        // picture slider logic
        $scope.allImages = $scope.images;

        //hide div with broken images
        anonImg = function(image){
            image.src = 'https://instagramimages-a.akamaihd.net/profiles/anonymousUser.jpg';
        }

        $scope.load();
        $scope.getPosts();
    }
])

Body:
You have not posted the Controller code, You should have $scope in your controller and the function should be defined as,

$scope.anonImg = function(image){
  image.src = 'https://instagramimages-a.akamaihd.net/profiles/anonymousUser.jpg';
}


问:
Swift 3: How to get text from individual textfields that are in different collectionView cells?
I have a simple UICollectionView that has 3 cells. The cell has it's own class and all 3 cells use this class. The cell class just has a UITextField that is the cells size. I want to know how to be able to get hold of whatever is entered in each of the 3 cells UITextFields and pass it into my SecondController. How do I achieve this? Thank you guys. Code is below:

```<code>import UIKit

class FirstCell: BaseCell {

    var secondController: SecondController?

    let textField: UITextField = {
        let tv = UITextField()
        tv.textColor = .white
        return tv
    }()

    override func setupViews() {
        super.setupViews()
        backgroundColor = .lightGray

        addSubview(textField)

        textField.frame = CGRect(x: 12, y: 0, width: self.frame.width, height: self.frame.height)
    }
}

private let reuseIdentifier = "Cell"

class SecondController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView?.backgroundColor = .white
        self.collectionView?.alwaysBounceVertical = true

        self.collectionView?.register(FirstCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Print", style: .plain, target: self, action: #selector(handlePrint))
    }

    func handlePrint() {
        // print here...
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 3
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: 50)
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? FirstCell

        cell?.secondController = self

        if indexPath.item == 0 {
            cell?.textField.placeholder = "First Textfield"
        }

        if indexPath.item == 1 {
            cell?.textField.placeholder = "Second Textfield"
        }

        if indexPath.item == 2 {
            cell?.textField.placeholder = "ThirdTextfield"
        }

        return cell!
    }

}
</code>```

答:
create protocol

```<code>protocol MyCellTextFieldDelegate {
    func didChangeTextTo(text: String)
}
</code>```

then

```<code>extension SecondController: MyCellTextFieldDelegate {
    func didChangeTextTo(text: String) {
        //doStuff
    }
}
</code>```

inside your cell change

```<code>var secondController: SecondController?
</code>```

to

```<code>weak var delegate: MyCellTextFieldDelegate?
</code>```

and change your method to be like

```<code>override func setupViews() {
    super.setupViews()
    backgroundColor = .lightGray
    addSubview(textField)
    textField.delegate = self //this line
    textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) //and this line
    textField.frame = CGRect(x: 12, y: 0, width: self.frame.width, height: self.frame.height)
}
</code>```

and your cell class

```<code>class FirstCell: BaseCell, UITextFieldDelegate {
    //other code

    private func textFieldDidChange() {
        self.delegate?.didChangeTextTo(text: (self.textField.text ?? ""))
    }
}
</code>```

and inside cellForItemAt

```<code>cell?.delegate = self
</code>```

Edit: if you would like to get UICollectionViewCell that calls this, you should add

```<code>var tag: Int = 0
</code>```

inside your cell and inside cellForItemAt

```<code>cell?.tag = indexPath.row
</code>```

and then change your MyCellTextFieldDelegate func to pass not only text but tag as well.

Body:
I have a simple UICollectionView that has 3 cells. The cell has it's own class and all 3 cells use this class. The cell class just has a UITextField that is the cells size. I want to know how to be able to get hold of whatever is entered in each of the 3 cells UITextFields and pass it into my SecondController. How do I achieve this? Thank you guys. Code is below:

import UIKit

class FirstCell: BaseCell {

    var secondController: SecondController?

    let textField: UITextField = {
        let tv = UITextField()
        tv.textColor = .white
        return tv
    }()

    override func setupViews() {
        super.setupViews()
        backgroundColor = .lightGray

        addSubview(textField)

        textField.frame = CGRect(x: 12, y: 0, width: self.frame.width, height: self.frame.height)
    }
}

private let reuseIdentifier = "Cell"

class SecondController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView?.backgroundColor = .white
        self.collectionView?.alwaysBounceVertical = true

        self.collectionView?.register(FirstCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Print", style: .plain, target: self, action: #selector(handlePrint))
    }

    func handlePrint() {
        // print here...
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 3
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: 50)
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? FirstCell

        cell?.secondController = self

        if indexPath.item == 0 {
            cell?.textField.placeholder = "First Textfield"
        }

        if indexPath.item == 1 {
            cell?.textField.placeholder = "Second Textfield"
        }

        if indexPath.item == 2 {
            cell?.textField.placeholder = "ThirdTextfield"
        }

        return cell!
    }

}

Body:
create protocol

protocol MyCellTextFieldDelegate {
    func didChangeTextTo(text: String)
}

then

extension SecondController: MyCellTextFieldDelegate {
    func didChangeTextTo(text: String) {
        //doStuff
    }
}

inside your cell change

var secondController: SecondController?

to

weak var delegate: MyCellTextFieldDelegate?

and change your method to be like

override func setupViews() {
    super.setupViews()
    backgroundColor = .lightGray
    addSubview(textField)
    textField.delegate = self //this line
    textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) //and this line
    textField.frame = CGRect(x: 12, y: 0, width: self.frame.width, height: self.frame.height)
}

and your cell class

class FirstCell: BaseCell, UITextFieldDelegate {
    //other code

    private func textFieldDidChange() {
        self.delegate?.didChangeTextTo(text: (self.textField.text ?? ""))
    }
}

and inside cellForItemAt

cell?.delegate = self

Edit: if you would like to get UICollectionViewCell that calls this, you should add

var tag: Int = 0

inside your cell and inside cellForItemAt

cell?.tag = indexPath.row

and then change your MyCellTextFieldDelegate func to pass not only text but tag as well.


问:
Microsoft Access 2007 & VBA & CSV and ...stuff
I have an assignment for work purpose which isn't really hard to do but I'm not a proficient access user so I, hereby, come to you guys :)

I'm about to write VBA code that is actually a custom CSV files loader. It's going to parse some files and insert their content in the appropriate tables.
My question is: What is the most appropriate way of creating this loader and triggering it?
I guess I have to create a VBA Module in my database project, but then what are the possiblities for the user to invoke the script and load the files ?
Like... is there any file system browser control that I can pop open and ask the user to choose a csv file then load it or whatever else ?

Thank you for your hints guys

Miloud B

答:
From the user's point of view, it is probably easiest for you to create a form (or a series of forms) to take them through the import process.  You can then attach your VBA code to those forms.

You can use the FileDialog to let the users select a file.  It's the same dialog box that comes up when you want to open a file in any other Windows program.  Microsoft explains how to use it here.  It's not the clearest explanation, but if you Google "Access FileDialog" or "Access OpenFileDialog" you can find more examples.


问:
Flask Data is not stored to database
I am Creating a Flask Application.Application is running perfectly on local server. There is no error but the data is not stored in the database. What am i Missing?

1.routes.py

```<code>from flask import Flask,render_template,request
from models import db ,User
from forms import SignupForm

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:////Database.db"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db. init_app(app)

app.secret_key ='development_key'

@app.route('/' , methods=['GET','POST'])
def index():
    form = SignupForm() #form object
    if request.method == 'POST':
        if form.validate() == False:
            return render_template('index.htm' , form=form)
        else:
        #new user to be added to database   newuser = User(form.fname.data,form.lname.data,form.email.data,form.password.data)
            db.create_all()
            db.session.add(newuser)
            db.session.commit()
            return render_template('profile.htm')
    elif request.method == 'GET':
        return render_template('index.htm',form=form)

@app.route('/aboutus')
def aboutus():
    return render_template('aboutus.htm')

@app.route('/profile')
def profile():
    return render_template('profile.htm')

@app.route('/contactus')
def contactus():
    return render_template('contactus.htm')
</code>```

2.app.py

```<code>from routes import app
app.run(debug = True)
</code>```

3.forms.py

```<code>from flask_wtf import FlaskForm as Form
from wtforms import StringField,PasswordField,SubmitField
from wtforms.validators import DataRequired,Email,Length

class SignupForm(Form):
    fname = StringField('First Name',validators=[DataRequired("Please Enter Your FirstName")])
    lname = StringField('Last Name',validators=[DataRequired("Please Enter Your LastName")])
    password = PasswordField('Password',validators=[DataRequired("Password Can't Be Empty"), Length(min=8,message="Password Must Be 8 character Long")])
    email = StringField('Email',validators=[DataRequired("Please Enter Your Email") , Email("Please Enter A Valid Email")])
    submit = SubmitField('Register')
</code>```

4.models.py

```<code>from flask_sqlalchemy import SQLAlchemy
from werkzeug import generate_password_hash, check_password_hash

db = SQLAlchemy()

class User(db.Model):
    __tablename__= "users"
    id=db.Column(db.Integer,primary_key=True)
    fname = db.Column(db.String(100))
    lname = db.Column(db.String(100))
    email = db.Column(db.String(100),unique=True)
    password = db.Column(db.String(100))

    def __init__(self,fname,lname,email,password):
        self.fname=fname
        self.lname=lname
        self.email=email
        self.set_password(password)

    def set_password(self,password):
        self.password=generate_password_hash(password)

    def check_password(self,password):
        return check_password_hash(self.password,password)
</code>```

答:
I tried your code. The database wasn't being created. Try something like this instead to ensure your database file is in the proper place:</p>

```<code>import os
basedir = os.path.abspath(os.path.dirname(__file__))

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'Database.db')
</code>```

Title: Flask Data is not stored to database

Body:
I am Creating a Flask Application.Application is running perfectly on local server. There is no error but the data is not stored in the database. What am i Missing?

1.routes.py

from flask import Flask,render_template,request
from models import db ,User
from forms import SignupForm

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:////Database.db"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db. init_app(app)

app.secret_key ='development_key'

@app.route('/' , methods=['GET','POST'])
def index():
    form = SignupForm() #form object
    if request.method == 'POST':
        if form.validate() == False:
            return render_template('index.htm' , form=form)
        else:
        #new user to be added to database   newuser = User(form.fname.data,form.lname.data,form.email.data,form.password.data)
            db.create_all()
            db.session.add(newuser)
            db.session.commit()
            return render_template('profile.htm')
    elif request.method == 'GET':
        return render_template('index.htm',form=form)

@app.route('/aboutus')
def aboutus():
    return render_template('aboutus.htm')

@app.route('/profile')
def profile():
    return render_template('profile.htm')

@app.route('/contactus')
def contactus():
    return render_template('contactus.htm')

2.app.py

from routes import app
app.run(debug = True)

3.forms.py

from flask_wtf import FlaskForm as Form
from wtforms import StringField,PasswordField,SubmitField
from wtforms.validators import DataRequired,Email,Length

class SignupForm(Form):
    fname = StringField('First Name',validators=[DataRequired("Please Enter Your FirstName")])
    lname = StringField('Last Name',validators=[DataRequired("Please Enter Your LastName")])
    password = PasswordField('Password',validators=[DataRequired("Password Can't Be Empty"), Length(min=8,message="Password Must Be 8 character Long")])
    email = StringField('Email',validators=[DataRequired("Please Enter Your Email") , Email("Please Enter A Valid Email")])
    submit = SubmitField('Register')

4.models.py

from flask_sqlalchemy import SQLAlchemy
from werkzeug import generate_password_hash, check_password_hash

db = SQLAlchemy()

class User(db.Model):
    __tablename__= "users"
    id=db.Column(db.Integer,primary_key=True)
    fname = db.Column(db.String(100))
    lname = db.Column(db.String(100))
    email = db.Column(db.String(100),unique=True)
    password = db.Column(db.String(100))

    def __init__(self,fname,lname,email,password):
        self.fname=fname
        self.lname=lname
        self.email=email
        self.set_password(password)

    def set_password(self,password):
        self.password=generate_password_hash(password)

    def check_password(self,password):
        return check_password_hash(self.password,password)

Body:
I tried your code. The database wasn't being created. Try something like this instead to ensure your database file is in the proper place:

import os
basedir = os.path.abspath(os.path.dirname(__file__))

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'Database.db')


答:
Try this code...

body{
  background:rgba(10,10,10,.8);
}
.wrapper{
  position:relative;
  width:100%;
  margin:auto;
}
.item-2{
    float:left;
    text-align:center;
    box-sizing: border-box;
    display:inline-block;
    width:50%;
    border:2px solid blue;
 }
.demo{
  margin:auto;
  height:5em;
  width:5em;
  background:yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='wrapper'>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>

</div>  </code>```

Title: Make div appear next to other

Body:
Try this code...

body{
  background:rgba(10,10,10,.8);
}
.wrapper{
  position:relative;
  width:100%;
  margin:auto;
}
.item-2{
    float:left;
    text-align:center;
    box-sizing: border-box;
    display:inline-block;
    width:50%;
    border:2px solid blue;
 }
.demo{
  margin:auto;
  height:5em;
  width:5em;
  background:yellow;
}

<div class='wrapper'>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>

</div>


问:
Where to store sensitive files for heroku platform?
I have a private key file for a Firebase access which I don't want to store in GitHub repo obviously.

I am well aware duplicate question, but it's quite old and I don't see much of useful information there. Something might have changed since then hopefully?

So far I have a heroku branch with a commit that contains this private key and whenever I want to release new app version I am rebasing this branch onto master so the commit sits on top. However it's quite a hassle.

It would be probably enough to have some secure offsite storage that can be accessed through some regular credentials that can be stored in env variables. I want to avoid S3 as they require credit card just for a registration.

Any other options?

答:
What's wrong with setting up multi-line environment variables in Heroku (as suggested by the other question that you have linked to)?

If you're on Rails 5.1, there is now another option though - encrypted secrets. This allows you to commit an encrypted version of your private key file to version control, and just have the master key in Heroku. This appears to be based on the sekrets gem, which could be an option for older Rails versions - but you'll want to read the docs and do some research there, if that's your preferred route.


答:
.empty()

This method removes not only child (and other descendant) elements, but also any text within the set of matched elements. This is because, according to the DOM specification, any string of text within an element is considered a child node of that element.

So to empty your div use:

$("#id_chat_area").empty();


问:
RxJava2 order of sequence called with compleatable andThen operator
I am trying to migrate from RxJava1 to RxJava2. I am replacing all code parts where I previously had Observable<Void> to Compleatable. However I ran into one problem with order of stream calls. When I previously was dealing with Observables and using maps and flatMaps the code worked 'as expected'. However the andthen() operator seems to work a little bit differently. Here is a sample code to simplify the problem itself.

```<code>public Single<String> getString() {
    Log.d("Starting flow..")
    return getCompletable().andThen(getSingle());
}

public Completable getCompletable() {
    Log.d("calling getCompletable");
    return Completable.create(e -> {
                Log.d("doing actuall completable work");
                e.onComplete();
            }
    );
}

public Single<String> getSingle() {
    Log.d("calling getSingle");
    if(conditionBasedOnActualCompletableWork) {
        return getSingleA();
    }else{
        return getSingleB();
    }
}
</code>```

What I see in the logs in the end is :

```<code>  1-> Log.d("Starting flow..")
  2-> Log.d("calling getCompletable");
  3-> Log.d("calling getSingle");
  4-> Log.d("doing actuall completable work");
</code>```

And as you can probably figure out I would expect line 4 to be called before line 3 (afterwards the name of andthen() operator suggest  that the code would be called 'after' Completable finishes it's job). Previously I was creating the Observable<Void> using the Async.toAsync() operator and the method which is now called getSingle was in flatMap stream - it worked like I expected it to, so Log 4 would appear before 3. Now I tried changing the way the Compleatable is created - like using fromAction or fromCallable but it behaves the same. I  also couldn't find any other operator to replace andthen(). To underline - the method must be a Completable since it doesn't have any thing meaning full to return - it changes the app preferences and other settings (and is used like that globally mostly working 'as expected') and those changes are needed later in the stream. I also tried to wrap getSingle() method to somehow create a Single and move the if statement inside the create block but I don't know how to use getSingleA/B() methods inside there. And I need to use them as they have their complexity of their own and it doesn't make sense to duplicate the code. Any one have any idea how to modify this in RxJava2 so it behaves the same? There are multiple places where I rely on a Compleatable job to finish before moving forward with the stream (like refreshing session token, updating db, preferences etc. - no problem in RxJava1 using flatMap).

答:
You can use defer:

```<code>getCompletable().andThen(Single.defer(() -> getSingle()))
</code>```

That way, you don't execute the contents of getSingle() immediately but only when the Completablecompletes and andThen switches to the Single.

Body:
I am trying to migrate from RxJava1 to RxJava2. I am replacing all code parts where I previously had Observable<Void> to Compleatable. However I ran into one problem with order of stream calls. When I previously was dealing with Observables and using maps and flatMaps the code worked 'as expected'. However the andthen() operator seems to work a little bit differently. Here is a sample code to simplify the problem itself.

public Single<String> getString() {
    Log.d("Starting flow..")
    return getCompletable().andThen(getSingle());
}

public Completable getCompletable() {
    Log.d("calling getCompletable");
    return Completable.create(e -> {
                Log.d("doing actuall completable work");
                e.onComplete();
            }
    );
}

public Single<String> getSingle() {
    Log.d("calling getSingle");
    if(conditionBasedOnActualCompletableWork) {
        return getSingleA();
    }else{
        return getSingleB();
    }
}

What I see in the logs in the end is :

  1-> Log.d("Starting flow..")
  2-> Log.d("calling getCompletable");
  3-> Log.d("calling getSingle");
  4-> Log.d("doing actuall completable work");

And as you can probably figure out I would expect line 4 to be called before line 3 (afterwards the name of andthen() operator suggest  that the code would be called 'after' Completable finishes it's job). Previously I was creating the Observable<Void> using the Async.toAsync() operator and the method which is now called getSingle was in flatMap stream - it worked like I expected it to, so Log 4 would appear before 3. Now I tried changing the way the Compleatable is created - like using fromAction or fromCallable but it behaves the same. I  also couldn't find any other operator to replace andthen(). To underline - the method must be a Completable since it doesn't have any thing meaning full to return - it changes the app preferences and other settings (and is used like that globally mostly working 'as expected') and those changes are needed later in the stream. I also tried to wrap getSingle() method to somehow create a Single and move the if statement inside the create block but I don't know how to use getSingleA/B() methods inside there. And I need to use them as they have their complexity of their own and it doesn't make sense to duplicate the code. Any one have any idea how to modify this in RxJava2 so it behaves the same? There are multiple places where I rely on a Compleatable job to finish before moving forward with the stream (like refreshing session token, updating db, preferences etc. - no problem in RxJava1 using flatMap).

Body:
You can use defer:

getCompletable().andThen(Single.defer(() -> getSingle()))

That way, you don't execute the contents of getSingle() immediately but only when the Completablecompletes and andThen switches to the Single.


问:
Linux C - child process thinks the pipe is empty
I have a problem with this homework exercise. I am learning the Linux C so I am a beginner.

Now the exercise is simple: I have to create a child process. Now the parent process needs to read a text file (e.g. a.txt) and sends through a pipe. The child process reads from pipe and prints the content of the pipe to the terminal. But I don't understand that the child process doesn't read the pipe because it thinks the pipe is empty.

I post the code what I did so far:

```<code>#include "myinclude.h" //a separate file which contains all needed headers to run the program.

#define MERET 80

int main(int argc,char *argv[]){

    int pfd[2];
    int status;
    char buffer[MERET];
    pid_t pid;
    FILE *fp1,*fp2;
    if(argc != 2){
        printf("Nincs eleg argumentum");
    }
    if(pipe(pfd) < 0){
        syserr("pipe");
    }
    if((pid = fork()) < 0){
        syserr("fork");
    }
    if(pid == 0){
        close(pfd[1]);
        if ((fp1 = fdopen (pfd[0],"r")) <0){
                    syserr("fdopen");
            }
        printf("mukodsz");
        while(fgets(buffer,MERET,fp1) != NULL){//something here is not good
            printf("%s",buffer);
            fprintf(stdout,"Siker");
        }
        close(pfd[0]);
        exit(0);
    }
    close(pfd[0]);
    if ((fp1 = fdopen (pfd[1],"w")) == NULL){
        syserr("fdopen");
    }
    if((fp2 = fopen(argv[1],"r")) < 0){
        syserr("fopen");
    }
    while(fgets(buffer,MERET,fp2) != NULL){
        fprintf(fp1,"%s",buffer);
        //fprintf(stdout,"Siker\n");
    }
    close(pfd[1]);
    wait(&status);
    //fprintf(stdout,"Siker");
    exit(0);
}
</code>```

In my language "siker" means Success. I used it to debug the program but while loop of the child process is not printing anything.

答:
When you fdopen. you must fclose.

If you close the original file descriptor instead, all not-yet-written data in buffers associated with the FILE* get lost.

Body:
I have a problem with this homework exercise. I am learning the Linux C so I am a beginner.

Now the exercise is simple: I have to create a child process. Now the parent process needs to read a text file (e.g. a.txt) and sends through a pipe. The child process reads from pipe and prints the content of the pipe to the terminal. But I don't understand that the child process doesn't read the pipe because it thinks the pipe is empty.

I post the code what I did so far:

#include "myinclude.h" //a separate file which contains all needed headers to run the program.

#define MERET 80

int main(int argc,char *argv[]){

    int pfd[2];
    int status;
    char buffer[MERET];
    pid_t pid;
    FILE *fp1,*fp2;
    if(argc != 2){
        printf("Nincs eleg argumentum");
    }
    if(pipe(pfd) < 0){
        syserr("pipe");
    }
    if((pid = fork()) < 0){
        syserr("fork");
    }
    if(pid == 0){
        close(pfd[1]);
        if ((fp1 = fdopen (pfd[0],"r")) <0){
                    syserr("fdopen");
            }
        printf("mukodsz");
        while(fgets(buffer,MERET,fp1) != NULL){//something here is not good
            printf("%s",buffer);
            fprintf(stdout,"Siker");
        }
        close(pfd[0]);
        exit(0);
    }
    close(pfd[0]);
    if ((fp1 = fdopen (pfd[1],"w")) == NULL){
        syserr("fdopen");
    }
    if((fp2 = fopen(argv[1],"r")) < 0){
        syserr("fopen");
    }
    while(fgets(buffer,MERET,fp2) != NULL){
        fprintf(fp1,"%s",buffer);
        //fprintf(stdout,"Siker\n");
    }
    close(pfd[1]);
    wait(&status);
    //fprintf(stdout,"Siker");
    exit(0);
}

In my language "siker" means Success. I used it to debug the program but while loop of the child process is not printing anything.


问:
How to create and put variable into block in Django templating engine?
I want to create variable inside "if" block and call this var in other place</p>

```<code>{% for obj in events %}
{% if obj.calendar == instance %}
{% my_var = obj.title %}
    <div class="col-md-2">
         <div class="thumbnail" data-toggle="modal" data-target="#myModal">
            <div class="event_title">{{ obj.title }}</div>
            <div class="event_content">{{ obj.content }}</div>
        </div>
    </div>
   {% endif %}
{% endfor %}
</code>```

答:
Use the with statement available for standard Django templates. Example from this answer:

```<code>{% with name="World" greeting="Hello" %}
<html>
<div>{{ greeting }} {{name}}!</div>
</html>
{% endwith %}
</code>```

Body:
I want to create variable inside "if" block and call this var in other place

{% for obj in events %}
{% if obj.calendar == instance %}
{% my_var = obj.title %}

{{ obj.title }}

{{ obj.content }}

   {% endif %}
{% endfor %}

Body:
Use the with statement available for standard Django templates. Example from this answer:

{% with name="World" greeting="Hello" %}
<html>
<div>{{ greeting }} {{name}}!</div>
</html>
{% endwith %}


问:
SELECT with INNER JOIN doesn't work
I want to get rows from my table which:
-has the same id like parameter
-has date lower than today

This is my tasks table structure:

```<code>id | title | project_id | date
</code>```

And projects table:

```<code>id | name
</code>```

So, my query should give me name of project too.

I wrote something like this:

```<code>$query= 'SELECT *
        FROM tasks WHERE (user_id = :id AND date < CURDATE())
        INNER JOIN projects
        WHERE project_id = projects.id';
</code>```

What is incorrect here?

Without combining INNER JOIN and WHERE, queries works fine:

```<code>'SELECT * FROM tasks INNER JOIN projects WHERE project_id = projects.id';

'SELECT * FROM tasks FROM tasks WHERE (user_id = :id AND date < CURDATE())'
</code>```

Any ideas? Thanks!

:id parameter is binding with PDO (correctly for sure)

答:
The where clause comes after the group by. Also, use proper ON clause to do the joining.

```<code>select *
from tasks
join projects on tasks.project_id = projects.id
where user_id = :id
    and date < CURDATE()
</code>```

Title: SELECT with INNER JOIN doesn't work

Body:
I want to get rows from my table which:
-has the same id like parameter
-has date lower than today

This is my tasks table structure:

id | title | project_id | date

And projects table:

id | name

So, my query should give me name of project too.

I wrote something like this:

$query= 'SELECT *
        FROM tasks WHERE (user_id = :id AND date < CURDATE())
        INNER JOIN projects
        WHERE project_id = projects.id';

What is incorrect here?

Without combining INNER JOIN and WHERE, queries works fine:

'SELECT * FROM tasks INNER JOIN projects WHERE project_id = projects.id';

'SELECT * FROM tasks FROM tasks WHERE (user_id = :id AND date < CURDATE())'

Any ideas? Thanks!

:id parameter is binding with PDO (correctly for sure)

Body:
The where clause comes after the group by. Also, use proper ON clause to do the joining.

select *
from tasks
join projects on tasks.project_id = projects.id
where user_id = :id
    and date < CURDATE()


问:
Set header of <p:dialog> in dynamically
I have to set head for < p : dialog> in JSF.I have written into setHeaderName() for name getter and setter.But I can not see the name of the header of < p : dialog>
How to change dynamically head of p:dialog in PrimeFaces.</p>

答:
So long time after, but if you want to change the header via JS you can do this

PF('widgetVarname').getJQ().find(".ui-dialog-title").text("new title you want")

Hope this helps

Title: Set header of <p:dialog> in dynamically

Body:
I have to set head for
 in JSF.I have written into setHeaderName() for name getter and setter.But I can not see the name of the header of

How to change dynamically head of p:dialog in PrimeFaces.


问:
Calculate N-th decimal digit of pi
What I need:

Function to calculate N-th decimal digit of Pi. Example:

```<code>>>> pi_digit(1)
1
>>> pi_digit(2)
4
>>> pi_digit(3)
1
>>> pi_digit(4)
5
</code>```

What did I tried:

While searching, found that code. It actually does what I need except one thing - it calculates all N digits, while I need only last. Is this possible to accomplish in efficient way? (if I just slice string for last character it wouldn't be so fast). Thanks in advance.

Why I need it:

I'm going to put that script, which would append digits to text file, onto my server and leave it for 20-30 days, and check the output.

答:
see:

Unbounded Spigot Algorithms for the Digits of Pi

Jeremy Gibbons

The program under discussion is written in Haskell [5], a lazy
  functional programming language. As a secondary point of this paper,
  we hope to convince the reader that such languages are excellent
  vehicles for expressing mathematical computations, certainly when
  compared with other general-purpose programming languages such as
  Java, C, and Pascal, and arguably even when compared with computer
  algebra systems such as Mathematica.

https://www.cs.ox.ac.uk/jeremy.gibbons/publications/spigot.pdf

it can be implemented with pidigits

https://github.com/transmogrifier/pidigits

pidigits is avalaible through Python Package Index (PyPI) using pip.

```<code>>>> pip install --upgrade pidigits
</code>```

Title: Calculate N-th decimal digit of pi

Body:
What I need:

Function to calculate N-th decimal digit of Pi. Example:

>>> pi_digit(1)
1
>>> pi_digit(2)
4
>>> pi_digit(3)
1
>>> pi_digit(4)
5

What did I tried:

While searching, found that code. It actually does what I need except one thing - it calculates all N digits, while I need only last. Is this possible to accomplish in efficient way? (if I just slice string for last character it wouldn't be so fast). Thanks in advance.

Why I need it:

I'm going to put that script, which would append digits to text file, onto my server and leave it for 20-30 days, and check the output.

Body:
see:

Unbounded Spigot Algorithms for the Digits of Pi

Jeremy Gibbons

The program under discussion is written in Haskell [5], a lazy
  functional programming language. As a secondary point of this paper,
  we hope to convince the reader that such languages are excellent
  vehicles for expressing mathematical computations, certainly when
  compared with other general-purpose programming languages such as
  Java, C, and Pascal, and arguably even when compared with computer
  algebra systems such as Mathematica.

https://www.cs.ox.ac.uk/jeremy.gibbons/publications/spigot.pdf

it can be implemented with pidigits

https://github.com/transmogrifier/pidigits

pidigits is avalaible through Python Package Index (PyPI) using pip.

>>> pip install --upgrade pidigits


问:
Why does the command, alert($(this).attr("id")); return "undefined"?
Why does the command

```<code>alert($(this).attr("id"));
</code>```

return "undefined"? I'm using it in ASP NET and Internet Explorer 8.

答: Either this does not have an ID, or it's not the element you think it is.

Body:
Why does the command

alert($(this).attr("id"));

return "undefined"? I'm using it in ASP NET and Internet Explorer 8.


问:
how can I add mark every two index in String
```<code>def Change(_text):
    L = len(_text)
    _i = 2
    _text[_i] = "*"
    _i += 2
    print(_text)
</code>```

How can I add a mark e.g:* every two Index In String

答:
Are you trying to separate every two letters with an asterix?

```<code>testtesttest
te*st*te*st*te*st
</code>```

You could do this using itertools.zip_longest to split the string up, and '*'.join to rebuild it with the markers inserted

```<code>from itertools import zip_longest

def add_marker(s):
    return '*'.join([''.join(x) for x in zip_longest(*[iter(s)]*2, fillvalue='')])
</code>```

Body:
def Change(_text):
    L = len(_text)
    _i = 2
    _text[_i] = "*"
    _i += 2
    print(_text)

How can I add a mark e.g:* every two Index In String

Body:
Are you trying to separate every two letters with an asterix?

testtesttest
te*st*te*st*te*st

You could do this using itertools.zip_longest to split the string up, and '*'.join to rebuild it with the markers inserted

from itertools import zip_longest

def add_marker(s):
    return '*'.join([''.join(x) for x in zip_longest(*[iter(s)]*2, fillvalue='')])


问:
Is there an easy way to reload css without reloading the page?
I'm trying to make a live, in-page css editor with a preview function that would reload the stylesheet and apply it without needing to reload the page. What would be the best way to go about this?</p>

答:
There is absolutely no need to use jQuery for this. The following JavaScript function will reload all your CSS files:</p>

```<code>function reloadCss()
{
    var links = document.getElementsByTagName("link");
    for (var cl in links)
    {
        var link = links[cl];
        if (link.rel === "stylesheet")
            link.href += "";
    }
}
</code>```

Body:
There is absolutely no need to use jQuery for this. The following JavaScript function will reload all your CSS files:

function reloadCss()
{
    var links = document.getElementsByTagName("link");
    for (var cl in links)
    {
        var link = links[cl];
        if (link.rel === "stylesheet")
            link.href += "";
    }
}


问:
Is that possible using queryDSL?
There are two entities A and B relate one to many.

I want to extract "B_2" with there parent("A_1") and children("B_1", "B_2", "B_3") of there parent. So I try my code below.

```<code>from(QB.b).join(QB.b.a, QA.a).fetch().join(QA.a.bList).fetch().where(QB.b.name.eq("B_2"));
</code>```

But result B.a.bList are just proxy object. And it occur to N+1 problem.
Anyone help?

答:
For the purposes of this example, let's called the Querydsl query types for entity A a and for entity B b.

```<code>.from(a)
.innerJoin(b)
.on(a.a_id).eq(b.a_id)
.where(b.name.eq("B_2"))
.fetch();
</code>```

Title: Is that possible using queryDSL?

Body:
There are two entities A and B relate one to many.

I want to extract "B_2" with there parent("A_1") and children("B_1", "B_2", "B_3") of there parent. So I try my code below.

from(QB.b).join(QB.b.a, QA.a).fetch().join(QA.a.bList).fetch().where(QB.b.name.eq("B_2"));

But result B.a.bList are just proxy object. And it occur to N+1 problem.
Anyone help?

Body:
For the purposes of this example, let's called the Querydsl query types for entity A a and for entity B b.

.from(a)
.innerJoin(b)
.on(a.a_id).eq(b.a_id)
.where(b.name.eq("B_2"))
.fetch();


问:
Comparing two sheets with unique column matching
How do I compare two sheets in Excel of huge dataset in easy way whether VBA or with formulas?

I have two sheets with 10 columns each. Each sheet has B column with unique batch numbers. I want to compare rows with same B column values between the two sheets and if any difference in other 9 columns, copy entire row to another new sheet.

For example:

Sheet one is master sheet.  Sheets one and two have same names but the ages are different for name "b", so I need name b and age in sheet three and the age cell should be in color in sheet 3 because the age is different.

If I have a large number of columns instead of only age its difficult to identify, usually I use vlookup on each column by name as unique and use if function to check match or not.

答:
You may try the code given below.

Prerequisites:
1) Code assumes that there are three sheets in the workbook named Sheet1, Sheet2 and Sheet3

2) Sheet1 and Sheet2 have 10 columns each with same headers.

The code below compare the data on Sheet2 with data on Sheet1 based on column B i.e. if a value from column B on Sheet2 is found in column B of Sheet1, the code will compare the data for all the columns of both the sheets and if the data doesn't match or different, the data will be copied to the Sheet3.

```<code>Sub CompareAndCopyUnMatchedData()
Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet
Dim x, y, z, dict1
Dim i As Long, j As Long
Dim str As String
Application.ScreenUpdating = False
Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")
Set ws3 = Sheets("Sheet3")
ws3.Cells.Clear
ws1.Range("A1:J1").Copy ws3.Range("A1")
x = ws1.Range("A1").CurrentRegion.Value
y = ws2.Range("a1").CurrentRegion.Value
Set dict1 = CreateObject("Scripting.Dictionary")
For i = 2 To UBound(x, 1)
    dict1.Item(x(i, 2)) = x(i, 1) & "," & x(i, 2) & "," & x(i, 3) & "," & x(i, 4) & "," & x(i, 5) & "," & x(i, 6) & "," & x(i, 7) & "," & x(i, 8) & "," & x(i, 9) & "," & x(i, 10)
Next i
For i = 2 To UBound(y, 1)
    If dict1.exists(y(i, 2)) Then
        If dict1.Item(y(i, 2)) <> y(i, 1) & "," & y(i, 2) & "," & y(i, 3) & "," & y(i, 4) & "," & y(i, 5) & "," & y(i, 6) & "," & y(i, 7) & "," & y(i, 8) & "," & y(i, 9) & "," & y(i, 10) Then
            str = y(i, 1) & "," & y(i, 2) & "," & y(i, 3) & "," & y(i, 4) & "," & y(i, 5) & "," & y(i, 6) & "," & y(i, 7) & "," & y(i, 8) & "," & y(i, 9) & "," & y(i, 10)
            z = Split(str, ",")
            ws3.Range("A" & Rows.Count).End(3)(2).Resize(1, 10).Value = z
        End If
    End If
Next i
Set dict1 = Nothing
Application.ScreenUpdating = True
End Sub
</code>```

Edit:
If you are interested to highlight the cell on Sheet2 which doesn't match with the corresponding cell on Sheet1, you can achieve this with the conditional formatting.
To do so, select the whole data on Sheet2 starting from cell A1 and make a New Rule for conditional formatting using the formula given below and set the format as per your choice.
As a result say Sheet2!E10 doesn't match with Sheet1!E10 then Sheet2!E10 will be highlighted or formatted as per the format you set in the conditional formatting.

Formula to be used for conditional formatting is as below...

```<code>=A1<>Sheet1!A1
</code>```

Body:
You may try the code given below.

Prerequisites:
1) Code assumes that there are three sheets in the workbook named Sheet1, Sheet2 and Sheet3

2) Sheet1 and Sheet2 have 10 columns each with same headers.

The code below compare the data on Sheet2 with data on Sheet1 based on column B i.e. if a value from column B on Sheet2 is found in column B of Sheet1, the code will compare the data for all the columns of both the sheets and if the data doesn't match or different, the data will be copied to the Sheet3.

Sub CompareAndCopyUnMatchedData()
Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet
Dim x, y, z, dict1
Dim i As Long, j As Long
Dim str As String
Application.ScreenUpdating = False
Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")
Set ws3 = Sheets("Sheet3")
ws3.Cells.Clear
ws1.Range("A1:J1").Copy ws3.Range("A1")
x = ws1.Range("A1").CurrentRegion.Value
y = ws2.Range("a1").CurrentRegion.Value
Set dict1 = CreateObject("Scripting.Dictionary")
For i = 2 To UBound(x, 1)
    dict1.Item(x(i, 2)) = x(i, 1) & "," & x(i, 2) & "," & x(i, 3) & "," & x(i, 4) & "," & x(i, 5) & "," & x(i, 6) & "," & x(i, 7) & "," & x(i, 8) & "," & x(i, 9) & "," & x(i, 10)
Next i
For i = 2 To UBound(y, 1)
    If dict1.exists(y(i, 2)) Then
        If dict1.Item(y(i, 2)) <> y(i, 1) & "," & y(i, 2) & "," & y(i, 3) & "," & y(i, 4) & "," & y(i, 5) & "," & y(i, 6) & "," & y(i, 7) & "," & y(i, 8) & "," & y(i, 9) & "," & y(i, 10) Then
            str = y(i, 1) & "," & y(i, 2) & "," & y(i, 3) & "," & y(i, 4) & "," & y(i, 5) & "," & y(i, 6) & "," & y(i, 7) & "," & y(i, 8) & "," & y(i, 9) & "," & y(i, 10)
            z = Split(str, ",")
            ws3.Range("A" & Rows.Count).End(3)(2).Resize(1, 10).Value = z
        End If
    End If
Next i
Set dict1 = Nothing
Application.ScreenUpdating = True
End Sub

Edit:
If you are interested to highlight the cell on Sheet2 which doesn't match with the corresponding cell on Sheet1, you can achieve this with the conditional formatting.
To do so, select the whole data on Sheet2 starting from cell A1 and make a New Rule for conditional formatting using the formula given below and set the format as per your choice.
As a result say Sheet2!E10 doesn't match with Sheet1!E10 then Sheet2!E10 will be highlighted or formatted as per the format you set in the conditional formatting.

Formula to be used for conditional formatting is as below...

=A1<>Sheet1!A1


问:
Search only children of a protractor webElementFinder using CSS
I have a protractor webElementFinder testElement. I want to match only its  div children (NOT grandchildren or any other further descendants) and thus testElement.find('div') will not work as it will find all descendant divs.

If protractor worked like jQuery (which would make sense since Angular is smart enough to use jQuery if its present and protractor is built with Angular in mind), I would just do testElement.find(' > div') which would work despite the find argument not being a valid CSS selector by itself; however because protractor just uses built in Element functions, that CSS selector is not valid by itself, and protractor throws an error.

I could go this route Angular JS, Protractor locator, get direct children of element since xpath natively lets you look at children, but I'd much rather use CSS than xpath.

答:
The solution depends on a few things:

if testElement is an ElementFinder (const testelement = element(by.css('.some-selector'))), then you can do testelement.all(by.css('div')). Be aware of the all, because you are talking about chrildren, you will find all children with all. It will return an ElementArrayFinder, see the docs

if testElement is a selector (const foo = '.testElement'), then you can do $$('.testElement > div'). This will return all the  It will return an ElementArrayFinder, see the docs

I hope you can add the selector of testElement to the css selector with the >, the advantage you will get from this is that you will get all elements that are a direct children of the testElement-selector


问:
Changing the load order of files in an R package
I'm writing a package for R in which the exported functions are decorated by a higher-order function that adds error checking and some other boilerplate code.

However, because this code is at the top-level it is evaluated after parsing. These means that
the load order of the package files is important.

To give an equivalent but simplified example, suppose I have a package with two files (Negate2 and Utils), and I require Negate2.R to be loaded first  for the function 'isfalse( )' to be defined without throwing an error.

```<code># /Negate2.R
Negate2 <- Negate

# -------------------

# /Utils.R
istrue <- isTRUE
isfalse <- Negate2(istrue)
</code>```

Is it possible to structure NAMESPACE, DESCRIPTION (collate) or another package file in order to change the load order of files? The internal working of the R package structure and CRAN are still black magic to me.

It is possible to get around this problem using awkward hacks, but the least repetitive way of solving this problem. The wrapper function must be a higher-order function, since it also changes the function call semantics of its input function. The package is code heavy (~6000 lines, 100 functions) so repetition would be...problematic.

Solution

As @Manetheran points out, to change the load order you just change the order of the file names in the DESCRIPTION file.

```<code># /DESCRIPTION
Collate:
    'Negate2.R'
    'Utils.R'
</code>```

答:
R loads files in alphabetical order. To change the order, Collate field could be used from the DESCRIPTION file.

roxygen2 provides an explicit way of saying that one file must be loaded before another: @include. The @include tag gives a space separated list of file names that should be loaded before the current file:

```<code>#' @include class-a.r
setClass("B", contains = "A")
</code>```

If any @include tags are present in the package, roxygen2 will set the Collate field in the DESCRIPTION.

You need to run generation of roxygen2 documentation in order to changes to take effect.

Body:
I'm writing a package for R in which the exported functions are decorated by a higher-order function that adds error checking and some other boilerplate code.

However, because this code is at the top-level it is evaluated after parsing. These means that
the load order of the package files is important.

To give an equivalent but simplified example, suppose I have a package with two files (Negate2 and Utils), and I require Negate2.R to be loaded first  for the function 'isfalse( )' to be defined without throwing an error.

# /Negate2.R
Negate2 <- Negate

# -------------------

# /Utils.R
istrue <- isTRUE
isfalse <- Negate2(istrue)

Is it possible to structure NAMESPACE, DESCRIPTION (collate) or another package file in order to change the load order of files? The internal working of the R package structure and CRAN are still black magic to me.

It is possible to get around this problem using awkward hacks, but the least repetitive way of solving this problem. The wrapper function must be a higher-order function, since it also changes the function call semantics of its input function. The package is code heavy (~6000 lines, 100 functions) so repetition would be...problematic.

Solution

As @Manetheran points out, to change the load order you just change the order of the file names in the DESCRIPTION file.

# /DESCRIPTION
Collate:
    'Negate2.R'
    'Utils.R'

Body:
R loads files in alphabetical order. To change the order, Collate field could be used from the DESCRIPTION file.

roxygen2 provides an explicit way of saying that one file must be loaded before another: @include. The @include tag gives a space separated list of file names that should be loaded before the current file:

#' @include class-a.r
setClass("B", contains = "A")

If any @include tags are present in the package, roxygen2 will set the Collate field in the DESCRIPTION.

You need to run generation of roxygen2 documentation in order to changes to take effect.


问:
UIView Rotation No XIB
I have a simple window based ipad app with no extra xibs or classes, just your app delegate .h and .m.

I have successfully added a UIView as a subview to 'window' but it has no rotation. How can I get a view added with working rotation. (No extra xib files if possible.)

Thanks.

答: You need a custom view controller for your view that implements the method shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation. Return YES for every orientation you wish to allow rotation to.

Title: UIView Rotation No XIB


问:
QJsonValue::isUndefined does not work correctly
```<code>#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonValue>
#include <QJsonObject>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    char json[] = "{ id: 12}";
    QJsonDocument doc = QJsonDocument::fromJson(json);
    QJsonValue v = doc.object()["no-defined"];
    Q_ASSERT(v.isUndefined());  // assert failed.

    return a.exec();
}
</code>```

I want to use QJsonValue::isUndefined() to judge if I define the key, but in the test code, v.isUndefined() return false, not true. I don't know the reason, is there any  explanation?

答:
After running a test:

```<code>#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    char json[] = "{ id: 12}";
    QJsonDocument doc = QJsonDocument::fromJson(json);
    QJsonValue v_ar = doc.object()["no-defined"];
    QJsonValue v_o = doc.object().value(QString("no-defined"));
    qDebug() << "Array-operator:" << v_ar.isUndefined() << v_ar.toString() << v_ar.type(); //returns: false ""
    qDebug() << "Object-operator:" << v_o.isUndefined() << v_o.toString(); //returns true ""
    qDebug() << "direct object call:" << doc.object().value("no-defined").isUndefined() << doc.object().value("no-defined").toString(); //returns true ""
    qDebug() << "direct array call:" << doc.object()["no-defined"].isUndefined() << doc.object()["no-defined"].toString(); //returns false ""
    return a.exec();
}
</code>```

which results in:

```<code>Array-operator: false "" 0
Object-operator: true ""
direct object call: true ""
direct array call: false ""
</code>```

You can see that there is something wrong with the array operator. Instead of returning a JsonValue::Undefined it returns a JsonValue::NULL (0). A way around would be using

```<code>QJsonValue v = doc.object().value("no-defined");
</code>```

or better:

```<code>Q_ASSERT(doc.object().value("no-defined").isUndefined());
</code>```

According to QT-BUG it is meant that way. If you call the array operator a new item is created with a default value of NULL.

Body:
#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonValue>
#include <QJsonObject>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    char json[] = "{ id: 12}";
    QJsonDocument doc = QJsonDocument::fromJson(json);
    QJsonValue v = doc.object()["no-defined"];
    Q_ASSERT(v.isUndefined());  // assert failed.

    return a.exec();
}

I want to use QJsonValue::isUndefined() to judge if I define the key, but in the test code, v.isUndefined() return false, not true. I don't know the reason, is there any  explanation?

Body:
After running a test:

#include <QCoreApplication>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    char json[] = "{ id: 12}";
    QJsonDocument doc = QJsonDocument::fromJson(json);
    QJsonValue v_ar = doc.object()["no-defined"];
    QJsonValue v_o = doc.object().value(QString("no-defined"));
    qDebug() << "Array-operator:" << v_ar.isUndefined() << v_ar.toString() << v_ar.type(); //returns: false ""
    qDebug() << "Object-operator:" << v_o.isUndefined() << v_o.toString(); //returns true ""
    qDebug() << "direct object call:" << doc.object().value("no-defined").isUndefined() << doc.object().value("no-defined").toString(); //returns true ""
    qDebug() << "direct array call:" << doc.object()["no-defined"].isUndefined() << doc.object()["no-defined"].toString(); //returns false ""
    return a.exec();
}

which results in:

Array-operator: false "" 0
Object-operator: true ""
direct object call: true ""
direct array call: false ""

You can see that there is something wrong with the array operator. Instead of returning a JsonValue::Undefined it returns a JsonValue::NULL (0). A way around would be using

QJsonValue v = doc.object().value("no-defined");

or better:

Q_ASSERT(doc.object().value("no-defined").isUndefined());

According to QT-BUG it is meant that way. If you call the array operator a new item is created with a default value of NULL.


问:
Efficient way to check if individual arrays inside a 2-d array have equal lengths
Let's say we have a 2D array

int[][] arr = new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7 }, { 8, 9 } };

Here, arr[1] has a length of 3.

Is there any efficient way to check if all the 1-d arrays present within the 2-d array have equal lengths?

Say, without looping through the array or may be through using any data structure which can be preferred instead of a int[][]?

答:
If you use java8, the below code (look at the inline comments) is much simpler, which uses basic stream (i.e., internal iteration) methods:

```<code>int[][] arr = new int[][] { { 1, 2 }, { 3, 4}, { 6, 7 }, { 8, 9 } };
final int[] firstSubArray = arr[0];//get the first array size
//Now with stream skip first element & check the size with rest
boolean isSubArraysSameSize = Arrays.stream(arr).//get stream from array
            skip(1).//skip first element
            allMatch(subArray ->
              subArray.length == firstSubArray.length);//check rest all sizes match
System.out.println(isSubArraysSameSize);
</code>```

Body:
If you use java8, the below code (look at the inline comments) is much simpler, which uses basic stream (i.e., internal iteration) methods:

int[][] arr = new int[][] { { 1, 2 }, { 3, 4}, { 6, 7 }, { 8, 9 } };
final int[] firstSubArray = arr[0];//get the first array size
//Now with stream skip first element & check the size with rest
boolean isSubArraysSameSize = Arrays.stream(arr).//get stream from array
            skip(1).//skip first element
            allMatch(subArray ->
              subArray.length == firstSubArray.length);//check rest all sizes match
System.out.println(isSubArraysSameSize);


答:
range is ambiguous in this situation.  To investigate further, provide EXPLAIN SELECT ... and perform these steps:

```<code>FLUSH STATUS;
SELECT ...;
SHOW SESSION STATUS LIKE "Handler%";
</code>```

and look at the largest number that comes out.  Possible cases:

Same as number of rows in the table -- You need INDEX(project_id).

Same as number of rows in output (103?) -- Then it did the optimal, namely leapfrog through the table, not do some big "range" scan like it implied.  As for "3 seconds" -- that will take some more head scratching.

Some other number -- What version are you running?  (This may take more investigation.)  And provide SHOW CREATE TABLE delivery_ticket.

Title: Yii2 eager loading with subquery instead of array with id's

Body:
For a big application I am using the following query to get all projects with relations:

  $project_query = Project::find()->With(['category', 'deliveryTickets', 'garbagePerProjects', 'hourLogs',
        'materialPerProjects', 'employeePerProjects', 'contact', 'invoices'])
        ->where(['project.organization_id' => $this->organization_id]);

which generates the following query, for example :

SELECT * FROM `delivery_ticket` WHERE `project_id` IN (124, 137, 147, 148, 149, 219, 222, 241, 1263, 1324, 1325, 1333, 1378, 1423, 1499, 1627, 1687, 1688, 1689, 1690, 1705, 1706, 1962, 2047, 2643, 2774, 2876, 2912, 3005, 3287, 3334, 4251, 4570, 4758, 4963, 5644, 6168, 6605, 6639, 6991, 7000, 7003, 7098, 7530, 7531, 7733, 7734, 7823, 7927, 8452, 8752, 8868, 8903, 8914, 8916, 8917, 8921, 8923, 8931, 8947, 8948, 8949, 8952, 8969, 9042, 9134, 9136, 9137, 9280, 9671, 10262, 10272, 10712, 10730, 11436, 11459, 11520, 11641, 11774, 11776, 12028, 12178, 12323, 12831, 12884, 13050, 13478, 13479, 13595, 13651, 13716, 13946, 14431, 14447, 14523, 15303, 15343, 16269, 16270, 16491, 16513, 17950, 17951)

Mysql explain shows that it is using range instead of eq_ref

therefor my page takes 3 seconds to load.

How can turn this query in a subquery ?

Body:
range is ambiguous in this situation.  To investigate further, provide EXPLAIN SELECT ... and perform these steps:

FLUSH STATUS;
SELECT ...;
SHOW SESSION STATUS LIKE "Handler%";

and look at the largest number that comes out.  Possible cases:

Same as number of rows in the table -- You need INDEX(project_id).

Same as number of rows in output (103?) -- Then it did the optimal, namely leapfrog through the table, not do some big "range" scan like it implied.  As for "3 seconds" -- that will take some more head scratching.

Some other number -- What version are you running?  (This may take more investigation.)  And provide SHOW CREATE TABLE delivery_ticket.