If $a+b+c \ge 1$ and $a,b,c>0$, prove that $\frac{1}{2a+s}+\frac{1}{2b+s}+\frac{1}{2c+s} \ge \frac{1}{s}$, where $s=ab+bc+ca$.

Question: What I know is that $$s \le \frac{(a+b+c)^2}{3} \ge \frac{1}{3}$$But as you can see the sign is pointing to different sides. So I can't see how this could be helpful. Just a small observation. I don't have any other ideas and I'd like to get some help. Thanks.
Answer: first we prove $a+b+c=1$ case:
$\dfrac{1}{2a+s}+\dfrac{1}{2b+s}+\dfrac{1}{2c+s} \ge \dfrac{1}{s} \iff s^3+s^2-4abc\ge 0$
let $x=3a,y=3b,z=3c,3u=x+y+z=3,3v^2=xy+yz+xz=9s,w^3=xyz=27abc$
$s^3+s^2-4abc\ge 0 \iff v^6+3v^4-4w^3 \ge 0 \iff v^6+3v^4\ge 4w^3$
accoding to $uvw$ method, $w^3\le 3v^2-2+2\sqrt{(1-v^2)^3}$
$\iff v^6+3v^4 \ge 12v^2-8+8\sqrt{(1-v^2)^3} \iff v^6+3v^4 -12v^2+8\ge 8\sqrt{(1-v^2)^3} \iff (v^6+3v^4 -12v^2+8)^2 \ge 64(1-v^2)^3 \iff v^{12}+6v^{10}-15v^8+8v^6 \ge 0 \iff v^6+6v^4-15v^2+8 \ge 0 \iff (v-1)^2(v^2+8)(v+1)^2\ge 0$
when $v=1$ the "="hold $\implies x=y=z=1 \implies a=b=c=\dfrac{1}{3}$
for $a'+b'+c'>1$, let$ a'+b'+c'=k(a+b+c) \to k > 1, ,a'=ka,b'=kb,c'=kc,s'=k^2s$
$\dfrac{1}{2a'+s'}+\dfrac{1}{2b'+s'}+\dfrac{1}{2c'+s'} \ge \dfrac{1}{s'} \iff \dfrac{1}{2\frac{a}{k}+s}+\dfrac{1}{2\frac{b}{k}+s}+\dfrac{1}{2\frac{c}{k}+s} \ge \dfrac{1}{s}$
$\frac{a}{k} < a \implies \dfrac{1}{2\frac{a}{k}+s}>\dfrac{1}{2a+s} $ so the inequlity hold.
QED.
Comment: What do you mean by "according to $uvw$ method"? And this entire solution seems weird to me, there has to be a cleaner one. I have no idea how you've come up with all this. Have you used some kind of a general method for solving inequalities?
Comment: ya ,I learn this uvw method in SE. It is a well known method which especially for $a+b+c,ab+bc+ac,abc$, you can download a pdf paper from web(sorry I forgot the link.)
Comment: Do you mean this pdf paper?
http://ohkawa.cc.it-hiroshima.ac.jp/AoPS.pdf/The%20uvw%20method0.pdf
Comment: @mathh exactly! :)


Create like/unlike functionality with Laravel

Question: I have a list of properties for a real estate application and im trying to implement a like/unlike functionality based on each property detail. The idea is to add a like or remove it matching the current property and user. This is my code so far, but it only remove likes so it doesnt work as expected. If anyone can suggest for a better approach ill be appreciated.
//Controller
public function storeLike($id)
{
    $like = Like::firstOrNew(array('property_id' => $id));
    $user = Auth::id();

    try{
        $liked = Like::get_like_user($id);
    }catch(Exception $ex){
        $liked = null;
    }

    if($liked){
        $liked->total_likes -= 1;
        $liked->status = false;
        $liked->save();
    }else{
        $like->user_id = $user;
        $like->total_likes += 1;
        $like->status = true;
        $like->save();
    }

    return Redirect::to('/detalle/propiedad/' . $id);
}

// Model
public static function get_like_user($id)
{
    return static::with('property', 'user')->where('property_id', $id)
                                           ->where('user_id', Auth::id())->first();
}

// Route
Route::get('store/like/{id}', array('as' => 'store.like', 'uses' => 'LikeController@storeLike'));

Answer: @Andrés Da Viá Looks like you are returning object from model. In case there is no data in database, it will still return an object - so far my guessing. Can you do something like below in the if($liked){ code?
Try this instead:
if(isset($liked -> user_id)){

Also try to print $liked variable after try and catch blocks. Use var_dump.
If this still does not work for you then let me know. I will try to create code based on your question.
Comment: I have made a few changes in my code and it seems to work this way. First i check if there is a property with a given user like associated. If it is then i remove 1 from total_likes otherwise i add 1. The problem is that when $liked is already created it will always remove 1. So im wondering how to add 1 or remove 1 when like is already created
Comment: @AndrésDaViá Check the status? If `$liked` is present and `$liked -> status = FALSE` - that means it is unliked, then change the status to liked one. Same scenario goes for `status = TRUE`. If `$liked` is not present then its simple thing to put new status.
Answer: Fix it by adding a where clause in my model to make the status equal to True ->where('status', 1)->first();


Theory of Major and Minor Chord Sounds

Question: Since a major triad is comprised of a minor-third stacked on top of a major-third, and a minor triad is comprised of a major-third stacked on top of a minor-third, they should, in "theory", have the same mix, so should sound similar, at least.
Obviously they don't, but why not? Is it something to do with the overtones/harmonics which the blend of two differing intervals produce?
Comment: The fifth is still in the same place relative to the root, regardless of the third.
Answer: A major triad does not contain "a minor third followed by a major third" and a minor triad does not contain "a major third followed by a major third".

A major triad contains the root, major third, fifth.
A minor triad contains the root, minor third, fifth.

Or, counting in semitones:

Major triad: root, root + 4, root + 7
Minor triad: root, root + 3, root + 7

The difference in sound is accounted for by the one different note.

I see where your confusion comes from - you're looking at the interval from the first to the third, then the third to the fifth -- 4 + 3 for major, 3 + 4 for minor. But it's the interval from the root that's significant.
The fifth is an "important" interval because it echoes a frequency that is a strong harmonic in the root note. If you gently finger one third of the way up the E string of a guitar, and pluck, you will hear a B tone. That is the 2nd harmonic of E (the first is another E, one octave higher). B is E's fifth.
So, playing the fifth along with the root note is almost not a harmony, but a strengthening of the harmonics, making the sound stronger and deeper.
You can play inversions of the triad. For example a C major triad could be C-E-G, or G-C-E. But listeners will perceive that the root note is C because the G reinforces it. Neither E nor G is reinforced in the same way. The E - or Eb in a minor chord - is then heard as a modifier to that "power chord", making it sound major or minor.
Answer: This is a great question, and one that is logical.  Yes, technically, major and minor triads are indeed built that way and can be thought-of as such.  They can also be built and thought-of in the way slim described in his answer as well.
Interestingly enough, I would say that the majority of factors that influence how we perceive major and minor chords aren't actually theory related.
Much in the same way you use similar ingredients to make a large variety of food (take flour for example!) so too is intervallic function and pitch choice, and like many things in life, is largely dependent on context which I will expand upon in a moment.
In Set Theory you can actually prove that major and minor triads are exactly the same chord - which is always hilarious to watch a roomful of theory students as their minds explode.  Mine certainly did when I first learned of it.  But I digress.
When you hear a triad, I am willing to bet that you are probably not hearing it as a sum of two distinct intervals.  Instead, you are probably perceiving the chord as a single, cohesive unit.  Hearing distinct intervals would be pronounced in, let's say, an orchestral score where different instrument timbres can accentuate different pitches, but for sake of simplicity, let's discuss it as it occurs on a piano.
We're going to take a little shift here:
It has been proven in psychological studies that humans group together like stimuli - especially with respect to aural stimulus.  Tangentially, but not completely unrelated, this is one of the reasons why you don't constantly feel your underwear throughout the day.
In another example, if you were listening to three different conversations simultaneously, it would be difficult to describe each conversation.  However, if you heard a conversation, a jet going by, and a police siren, such disparate sounds would be easy to remember and describe.
Such is the case with major and minor chords.  Because each chord contains a perfect-fifth where the fifth is harmonically supported by the root's overtone series, the fifth essentially becomes non-existent, as you would likely hear the overtone without the fifth's presence.  This is why in four-part writing the fifth is usually the first note to be dropped from a chord voicing, and the same applies to Jazz as well.
The root establishes a "tonality" as it were, and the third merely denotes the "quality" or "color" of the chord, and the fifth is nothing more than overtone support.  This is why chords that contain the same intervals sound differently from one another.
Earlier I referenced context, and context is important to note here as it can affect how a chord is perceived as well.  For example, a major chord in the lowest register will sound very different from a major chord in the highest register (even using the same pitches!)  Further, that same chord will sound differently played by a saxophone choir or tuned bass drums.
Apart from timbral context, major and minor chords can sound different depending on their harmonic function as well in a given key, tonal center, or pitch collection.
Hope that helps.
Comment: Playing TWO notes from a chord, earlier, made me think that some of what you state is right. In context is the key, excuse the pun. When one's ear is tuned to, say Cmaj, the C+E is obviously a major blend. But - follow on with E+G, and it's still (in my ears) major. In a different context, say E minor, E+G sounds minor, only because it is. All this we maybe know - but the original question still stands - WHY ? (or WHY NOT? )
Comment: I fail to see how my answer does not fully answer your question.  The reason why E+G still sound "major-y" in C major is not only the context I mentioned, but also aural memory.  Aural memory helps define how the listener experiences context.  Even though you're not playing "C", it is still in your aural memory, which provides a context for the E+G.  If you were to play, say, an "F#", giving your aural memory a different context, you would find that the E+G would take on a different role.
Answer: Function, function, function.
To use colors for a moment: let's say that a major third in this case is red, and that a minor third is blue. Bear with me.
Say we have two squares, where for one, the bottom half is red, and the top half is blue, while on the other, vice versa.
Now, turn off the logic in your brain for a moment that says, "Well, just flip one over and they're the same."
In this case, these two things are different.  They look different.  The frequencies that these colors give off in that order are different.  One has red on the bottom, one has blue on the bottom.  The function of color in each case is different.
In the same sense, having a major third on the "bottom" of a chord sounds and IS different than having a minor third.  Yes, both contain similar elements, both have a major and minor third, but the way these tones function in the chord as a whole is what makes them different.
In a major chord, the bottom interval, in equal temperament, is 400 cents; a minor chord has 300 cents in the bottom interval.  This is the relationship between the root and the third of the chord, its quality "center" if you will.  The difference between having 400 vs. 300 on the bottom is a matter of function, and not makeup.  Just because something has two of the same things in it, does not make it the same.
Function, function, function.
Comment: JPDoherty, thanks for an interesting answer.I got thinking again, and your last para. made me play a minor triad, root position. This (obviously) sounded to me like a minor chord, yet when I played 1st inversion, to me it sounded like a major 6th.2nd inversion - jury's out right now.So it could well be the relationship between 'bottom' note and other two, as human ears apparently hear the lowest note as the base - yes base - or root of the chord.
Comment: Well, the inverse of a minor third is a major sixth, so the outer tones would give that impression.  Doubling the b3 up an octave strengthens the "minor-ness" of that inversion. So, Eb, G, C, Eb (up an octave)
Answer: Hypothesis:
Natural: Major triad: C E G,  3 notes with vertical relationship (has nothing to do with static  harmonic overtones).
Manipulated: Minor triad: The major third (is omitted) and replaced by a minor third, in fact a b10 (!),  who can resolve over the 9th or b9th  to the root (Eb -> D(b) - > C)
This b10 is  an appoggiatura and has a horizontal relationship(tension to) with the root of the chord. An appoggiatura can be played together with his resolution and other chord notes. A minor chord has a smooth "dissonance", better named tension of the b3 to 1 (cfrt. counterpoint).
Conclusion: The minor third has a horizontal (modal) contrapuntal origin (idem for the minor 7(b7)) but is, still being a tension, assimilated as a vertical member of the chord.
Rem.
See the blues :simult. use of  horizontal minor third <->vertical major third
              : Gerswhin blues-chord
I suppose that the importance of the harmonic overtones series to explain harmony is surestimated. They are palettes of colours of 1 groundtone(sinustone)  and doesn't imply  horizontal connection to the next chord  .The seventh of a V7 is no vertical chordnote but a horizontal!
Vertical harmony-(theory) stops beyond the "5th" of the sinustone. This is the point where  horizontal harmony/counterpoint begins to add  colors(tensions)( and not consonance or dissonance)  to the chord.
A dimension  which some physicians(even theory by Leonard Bernstein) forget about music: mouvement(time).

Theory of Major and Minor Chord Sounds


how do I plot non-ordered data with matplotlib

Question: plot yaxis is strange for non-ordered data
a=[0.0, 1.875, 4.8248495370370375, 7.236701388888889, 11.050578703703705]
b=['26', '37', '44', '64', '64']
c=['95', '89', '87', '80', '100']
d=['226', '214', '204', '185', '239']
plt.plot(a,b); plt.show() ## OK
plt.plot(a,c); plt.show() ## y axis strange
plt.plot(a,d); plt.show() ## y axis strange

How do I plot this?
Comment: convert b, c, and d to floats....
Answer: You have three lists with items as strings (b, c, d). For correct plotting by coordinates you need to convert it to int or float values like this:
import matplotlib.pyplot as plt

a = [0.0, 1.875, 4.8248495370370375, 7.236701388888889, 11.050578703703705]
b = ['26', '37', '44', '64', '64']
c = ['95', '89', '87', '80', '100']
d = ['226', '214', '204', '185', '239']
plt.plot(a, list(map(float, b)))
plt.show()
plt.plot(a, list(map(float, c)))
plt.show()
plt.plot(a, list(map(float, d)))
plt.show()


How to translate metatag token into text?

Question: I'm trying to get the data from meta tag using node_load and for some reason when is using the default field, which is Token it gives me this ugly array.

Instead of title and description that contain the strings.
Do you know how I can translate the Token into the actual text?
Answer: I was running a very out-dated Metatag version. Once I update to the latest version I was able to run metatags_get_entity_metatags and get all the meta tag the way it supposes too.


PHP - failed to open stream: no such host is known

Question: Hi i have a issue in simple html dom code it show this error :-

file_get_contents(http://www.arakne-links.com)
  [function.file-get-contents]: failed to open stream:
  php_network_getaddresses: getaddrinfo failed: No such host is known.
  in D:\xampp\htdocs\scrap\simple_html_dom.php on line 75

because this url http://www.arakne-links.c is not working now i want
to know is there any way to skip the url which is not working..
here is the code which i am using
ini_set('display_errors', 'on');
include_once('../../simple_html_dom.php');

// create HTML DOM

$htmls =  file_get_html('http://info.vilesilencer.com/top');
foreach($htmls->find('a[rel="nofollow"]') as $e):
$test = $e->href;
$url  = array( $test );
$html = array();
foreach( $url as $key=>$value ) {

// get html plain-text for webpage & assign to html array.

$html = file_get_html( trim($value) );

// echo html plain text:
echo $html->find('title', 0)->innertext;

}
endforeach;

Please Help me to fix this issue.
Thankyou
Comment: where you are using the `file_get_content` function.
Comment: i thing i fix it and get in next url but now there is new error i replace this code $html = file_get_html( trim($value) );

// echo html plain text:
echo $html->find('title', 0)->innertext;    with    $html = @file_get_html( trim($value) );

if($html){
  echo $html->find('title', 0)->innertext;
}else{
    //Error
 echo 'not working';
}   but now it showing some notice
Comment: hello MIss poo i am using file_get_content here echo $html->find('title', 0)->innertext;  its a simple_html_dom.php function
Comment: what notice it is showing?
Answer: How about checking the URL before parsing?
ini_set('display_errors', 'on');
include_once('simple_html_dom.php');

function urlOk($url) {
    $headers = @get_headers($url);
    if($headers[0] == 'HTTP/1.1 200 OK') return true;
    else return false;
}

// create HTML DOM

$htmls =  file_get_html('http://info.vilesilencer.com/top');
foreach($htmls->find('a[rel="nofollow"]') as $e):
    $test = $e->href;
    $url  = array( $test );
    $html = array();
    foreach( $url as $key=>$value ) {
       // get html plain-text for webpage & assign to html array.
       if (urlOk(trim($value))) {
           $html = file_get_html( trim($value) );
           echo $html->find('title', 0)->innertext;
           echo "
";
       } else {
         echo 'Error: URL '.$value.' doesn\'t exist.
';
       }
}
endforeach;
?>

Comment: thanks this is exactly i am looking for but need small help more petra i'm getting this error Notice: Trying to get property of non-object in D:\xampp\htdocs\scrap\example\scraping\example_scraping_imdb.php on line 22   ..... its came when title tag not found in line 22. is there any way to work line 22 only if the title tag found
Comment: Do you need the 'else' part, when title is not found? Otherwise just cut off notices with error_reporting(E_ALL ^ E_NOTICE);


Angular dynamic flag icon in span based on mat-select change

Question: I have a mat-select and I would like to change a flag icon in a span in the mat-label, based on the selected option.
The initial flag is shown, after a click no change occurs in the span.
The flags in the option list are working correctly, so the question only concerns the label.
I am trying something like:
HTML:
    <mat-form-field>
    <mat-label>

      {{ selectedLanguage }}
    </mat-label>

    <mat-select
      [(ngModel)]="selectedLanguage"
      name="selectedLanguage"
      id="selectedLanguage"
    >

      <mat-option
        *ngFor="let language of languages"
        [value]="language"
        (click)="changeLanguage(language)"
      >

        {{ language }}
      </mat-option>
    </mat-select>
  </mat-form-field>

TS:
    selectedLanguage: string = environment.defaultLanguage;

    constructor(
    private store: Store<State>,
    private translateService: TranslateService) {}

    changeLanguage(language: string): void {
    this.selectedLanguage = language;
    }

    getLanguageFlag(language: string): string {
    let style = 'flag-icon flag-icon-';
    return language === 'en' ? `${style}gb` : `${style}${language}`;
    }

I've also tried a getter/setter, but the setter didn't seem to work when using the mat-select.
Thanks in advance for your help!
Comment: What library are you using for flags?
Answer: I tested it and you code works. You should just check if 2-letter country code is correct.
I don't know if you just didn't copy it correctly, but you are missing closing <mat-form-field> tag in you HTML, so check that also.
Working example
Comment: Thanks for the help! Wow, really stupid... the text was not visible due to the toolbar having a fixed height
Comment: Welcome. Consider upvoting and accepting my answer if it helped you.
Answer: The final solution, based on Nenad's help:
(the flag before the option, no label above the select input)
<mat-form-field>

<mat-select
  [(ngModel)]="selectedLanguage"
  name="selectedLanguage"
  id="selectedLanguage"
>
  <mat-option
    *ngFor="let language of languages"
    [value]="language"
    (click)="changeLanguage(language)"
  >

    {{ language.toUpperCase() }}
  </mat-option>
</mat-select>
</mat-form-field>


Which app they used here?

Question: If you listen to the intro it is processed/arranged with "people whispering" voices
How can we achieve such effect ?
do you know an app or a way to achieve it ?
And how can you describe the atmosphere that the listeners achieve by applying this effect ?
Thanks
Answer: Its just sampling. All you need is a mic and something that records. The rest is effects processing such as reverb.
Any standard DAW will provide the tools you need.

Which app they used here?


Tootip não funciona no flutter

Question: Estou seguindo esse tutorial clique aqui.
E o tooltip não apareceu. Será que está faltando alguma coisa no meu código logo abaixo?
import 'dart:typed_data';

import 'package:flutter/material.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Align(
          alignment: Alignment.center,
          child: Text("Nomeação de lideres"),
        ),
        backgroundColor: Colors.teal[900],
      ),
      body: Container(
        padding: EdgeInsets.all(16),
          child: Column(children: <Widget>[
            Container(
              margin: EdgeInsets.all(10),
              child: Tooltip(
                  message: 'My Account',
                  child: FlatButton(
                    child: Icon(
                      Icons.access_time,
                      size: 100,
                    ),
                  )),
            ),
          ]),
       ),
    );
  }
}

Resultado da minha tela;
Answer: É porque o seu botão não está com o método de click implementado...
Experimente implementar o onPressed(){}
class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Align(
          alignment: Alignment.center,
          child: Text("Nomeação de lideres"),
        ),
        backgroundColor: Colors.teal[900],
      ),
      body: Container(
        padding: EdgeInsets.all(16),
          child: Column(children: <Widget>[
            Container(
              margin: EdgeInsets.all(10),
              child: Tooltip(
                  message: 'My Account',
                  child: FlatButton(
                    onPressed: () {
                      // Faltou isso aqui
                    },
                    child: Icon(
                      Icons.access_time,
                      size: 100,
                    ),
                  )),
            ),
          ]),
       ),
    );
  }
}

Obs.: Lembrando que hoje nas versões atuais o FlatButton foi substituído por TextButton ou ElevatedButton.

Tootip não funciona no flutter


How to order a view by access control on files?

Question: I have a view that displays a series of nodes in a blog format.  Each node has a file attached to it.  How do I make the nodes with files that the user has to login to see come last in the list?
I've been looking through the options available in Views and have come up short there.  I was hoping I could create a relationship on the file, but I can't find any properties that relate to access control.
My other thought was that I could do this in a template, but I'm not sure if there is a template that will let me change the order of the rows in the view.  Are those variables passed to the template by reference?
Many thanks.
Comment: The best way is implement [hook_views_query_alter()](https://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7) and alter your query based on the logged in user role.
Comment: Did you try https://drupal.org/project/draggableviews module?
Comment: That is the right idea, but the files are going to be changing frequently and I don't want to put that responsibility on my client.  How can I automate this?
Answer: In views under the Advanced section when you select the Theme: Information link, you can select to override a specific field.
Choose the most appropriate naming convention as this will dictate the scope of your override. Copy the text given by views and copy this into a new file in your theme called the .tpl.php file name you chose.
Once there you can add a conditional statement before outputting your field with user_access to check if your user has the right permissions to view the downloads.
You might have to specify the permission in your own module with hook_permission.


What could go wrong if I do gradient descent by class?

Question: For example, when training on CIFAR10, each minibatch typically contains images from all 10 classes (assuming a moderately large batch size such as 64). What could go wrong if I train on a homogeneous batch of airplane images, followed by a homogeneous batch of automobile images, and so on?
I want to do that in order to calculate some statistics within each class during the training.
Answer: Stochastic gradient descent (and variants) works only with the assumption of (in poor words) representative gradients, i.e. the distribution should be almost similar (representative) of your dataset.
Pretty sure that you have no guarantees that SGD converges in that case (might happen however, but you can't know that)
If you come from Statistic, you could see this in this fashion:

SGD uses an estimator of the gradient (which variance depends on which algorithm of the SGD family you pick).
Now, this works only if the estimator is well defined

See "Curriculum Learning"


When two quadratics seems to output the same values are they necessarily the same?

Question: Joel is thinking of a quadratic and Eve is thinking of a quadratic. Both use $x$ as their variable. When they evaluate their quadratics for $x=1$, they get the same number. When they evaluate their quadratics for $x=2$, they both again get the same number. And when they evaluate their quadratics for $x=3$, they again both have the same result. Are their quadratics necessarily the same?
If $x=1$ results in $k_1$, $x=2$ in $k_2$ and $x=3$ in $k_3$ then three equations can be made by inputting these values in $ax^2+bx+c=k_i$
$a+b+c=k_1$
$4a+2b+c=k_2$
$9a+3b+c=k_3$
Using these equations we find the quadratic coefficients in terms of $k_i$:
$a=\frac{k_1-2k_2+k_3}{2}$
$b=\frac{-5k_1+8k_2-3k_3}{2}$
$c=3k_1-3k_2+k_3$
Now I'm stuck on what to do, hitherto I've followed hints but the answer still eludes me.
Comment: You're almost all the way there.  You've demonstrated that knowing those three values determines $a$, $b$, and $c$.  So...?
Comment: As for a simpler proof that knowing $n+1$ points for a degree $n$ polynomial is enough to uniquely determine the polynomial... suppose you had two distinct degree $n$ polynomials, $f$ and $g$.  Then $f-g$ is a degree at most $n$ polynomial with at least $n+1$ roots, those roots occurring at exactly those $x$ values that we knew $f$ and $g$ gave the same outputs for.  However, by FTA we know a nonzero degree $n$ polynomial has $n$ or fewer roots, a contradiction.  Therefore $f-g$ must be identically zero and thus the same.
Comment: After a bit of subtraction I get
\begin{align}
3a+b&=k_2-k_1\\
5a+b&=k_3-k_2\\
\end{align}
what can you do with these equations?
Comment: Think about what would happen if they just evaluate at two points. Then you don't have a unique solution
Comment: Once you've convinced yourself that being given $n+1$ distinct points for a degree $n$ polynomial is enough to uniquely identify the polynomial, another way to think about the polynomial is as $f(x) = k_1\dfrac{(x-2)(x-3)}{(1-2)(1-3)} + k_2\dfrac{(x-1)(x-3)}{(2-1)(2-3)} + k_3\dfrac{(x-1)(x-2)}{(3-1)(3-2)}$ via [Lagrange interpolation](https://en.wikipedia.org/wiki/Lagrange_polynomial), noting that in the above polynomial if you plug in the corresponding values of $x$ you trivially get the corresponding values of $k$ as the output.  It can be simplified from there as you wish by expanding.
Answer: The graph of a quadratic is a parabola, which is defined by three points, or three inputs and outputs. Since the two quadratics have three inputs which give identical outputs, they must be the same quadratic.
You might be wondering how to prove that a parabola is defined by three points or three inputs and outputs. Here's a link with the exact question: Prove that three points define a unique parabola
Hope this helped!


How can I manage swing UI default font sizes without quaqua?

Question: We are trying to get quaqua out of our application. We had been using a call to quaqua to set the font size to be smaller with a call like this:
System.setProperty("Quaqua.sizeStyle", "small");

Is there an easy to do the same sort of thing without using quaqua? Or does anyone know another good look and feel for OS X?
Answer: I also had an almost similar challenge, setting all font to a specific font. The code below will change the font size for all *.font properties in UIManager to a particular size
private static void setFontSize() {
    int fontSize = 12;
    Hashtable defaults = UIManager.getDefaults();
    Enumeration keys = defaults.keys();
    while (keys.hasMoreElements()) {
        Object key = keys.nextElement();

        if ((key instanceof String) && (((String) key).endsWith(".font"))) {
            FontUIResource font = (FontUIResource) UIManager.get(key);
            defaults.put (key, new FontUIResource(font.getFontName(), font.getStyle(), fontSize));
        }
    }
 }

Comment: From a comment on answer http://stackoverflow.com/a/8120380/873282 : It easier to use deriveFont(): tree.setFont(tree.getFont().deriveFont(24f));


Aplicação Laravel 4 não escreve em arquivos

Question: Tenho um servidor Apache instalado no Sistema Operacional CentOS 7 e uma aplicação construída através do Framework Laravel 4.2, já alterei as permissões dos diretórios do sistema com o comando:
sudo chmod -R 777 /var/www

Porém ainda assim a aplicação não esta conseguindo escrever em seus diretórios, retornando o seguinte erro:

Não entendo o porquê de não estar funcionando, as permissões de escrita foram dadas aos diretórios.
Answer: Descobri o que estava bloqueando os acessos a escrita nos diretórios, trata-se do SELinux, uma implementação da arquitetura MAC (Mandatory Access Control) para o Linux que provê políticas de segurança sobre todos os processos.
Então é necessário informar ao SELinux o diretório que o Apache estará utilizando com o comando:
sudo chcon -R -t httpd_sys_rw_content_t /var/www/Questionnaire/app/storage

O Apache deve ser capaz de escrever no diretório storage sem problemas.

Ainda que não recomendado (por motivos de segurança), é possível também desabilitar o SELinux, seguindo os passos abaixo:
01. Verificar o status do SELinux.
$ sestatus

02. Desabilitar o SELinux apenas na sessão atual.
$ sudo setenforce 0

03. Desabilitar o SELinux permanentemente.
03.01. Abra para edição o arquivo de configuração do SELinux
$ sudo vi /etc/selinux/config

03.02. Modifique a definição SELINUX para disabled.
SELINUX=disabled
03.03. Salve o arquivo e reinicie o sistema operacional
$ sudo shutdown -r now

03.04. Após reiniciar verifique o status do SELinux, deve constar como disabled.

Referências:

https://linuxize.com/post/how-to-disable-selinux-on-centos-7/
https://pt.wikipedia.org/wiki/SELinux
https://tecadmin.net/install-laravel-framework-on-centos/
http://gesielbernardes.eti.br/configurar-selinux.html


switch case não executa

Question: Tenho o seguinte código:

MENU

           Dashboard

          Meu Perfil

           Meus Cursos

           Meu Curriculum

  <?php

    $tela = "";

    if(!isset($_GET['rotina'])){

      $tela = "homesys.php";

   } else {

    $rotina = $_GET['rotina'];

    switch($rotina) {

      case "profile":

        echo $rotina;

        // $tela = "perfil.php";
        break;

      default:
        $tela = "homesys.php";
        break;

    }

  }

  ?>

    <?php include_once("../views/$tela");?>

Quando clico na opção Meu Perfil, o switch case não executa. Onde está o erro?
Answer: É necessário colocar a variável $tela entre chaves. Use o seguinte código: <?php include_once("../views/{$tela}");?>.
E outra, o trecho $tela = "perfil.php"; dentro do case "profile" está comentado no seu código.

switch case não executa


Given the expression n = p × k + r , (0 ≤ r < k). Find the values of p and r when known n and k

Question: I've been trying to do this but I'm getting an error Time Limit Exceeded, please help!
Example of input and exepected output

Input#1: 5 2
Output#1: 2 1

#include<stdio.h>
    int main(){
        long long n, k, p, r;
        scanf("%lld %lld", &n, &k);
        if (r >= 0 && r < k){
            if (n >= 1){
                p = (n - r) / k;
                r = n / (p * k);
            }
        }
        printf("%lld %lld", p, r);
        return 0;
    }

Comment: The variable r is not initialized. So this statement if (r >= 0 && r < k){ invokes undefined behavior.
Comment: `p` must be initialised too with a default value should none of the conditions be true.
Comment: Use `-Wall -Wextra -Werror` compiler options if using *gcc* or *clang*, or if using something else figure out how to turn on warnings. It will save you hours and hours of hitting your head against a wall trying to figure out easily avoidable bugs.
Comment: Maybe I'm missing something here, but how exactly can you find 2 unknowns in a single equation?
Comment: Get used to *always* check the return value of `scanf` and friends – it returns the number of successfully scanned values, if that doesn't match the number of values that *should* be scanned then some input error occurred.
Comment: Please [edit] and dd some examples of input and expected output.
Answer: The variable r is not initialized and has an indeterminate value
long long n, k, p, r;

So this if statement
if (r >= 0 && r < k){

at once invokes undefined behavior.
What you need is to include the header
#include <stdlib.h>

and to use the function lldiv declared in this header that calculates the quotient and the remainder of two numbers.
Here is a demonstration program.
#include <stdlib.h>
#include <stdio.h>

int main( void )
{
    long long int n = 100, k = 13;

    lldiv_t result = lldiv( n, k );

    long long int p = result.quot;
    long long int r = result.rem;

    printf( "p = %lld, r = %lld\n", p, r );
}

The program output is
p = 7, r = 9

Or instead of the function you could use the two operators / and % like
p = n / k;
r = n % k;

Comment: Could you clarify why `lldiv` is required here? The OP might not be aware.
Answer: Here you can take the reference from the code written in python, I first calculate the highest multiple of k (less than k) divisible by n. It is calculated by the // operator in python. Like, 37/5=7.4 but 37//4 gives 7 (floor of 7.4).  Then I calculate r and finally prints them
# 37 = p*5 + r
# take n=37 and k=5

n,k = map(int,input().split())  # take n,k as input
p = n//k                        # it will max multiple of k divisible by n
r = n - (p*k)                   # r = 37 - (7*5)
print("p =",p," and r=",r)      # print answer here

Comment: Wrong language... Many things that are fine for one language can be done better in another one, see `lldiv` in other answer. Apart from, if a compiler sees `p = n/k; r = n%k;` it might optimise to use a CPU command to calculate both at once, if available – like intel's DIV command.


How can I control node access based on entity reference to multiple users

Question: I have multiple uses for this functionality now but mainly for a private message system.
What I want to do:

Configure a content type with an entity reference to users
Create nodes of that type and select multiple users using the entity reference field
Limit visibility of each node of that type to the users selected in that field

I believe there was a module for this in D7, though I can't find it now. But I've had no success finding one for D9.
Is there a module or set of modules anyone is aware of that could provide this kind of access control?
If a module was to be built, any suggestions for best way to approach it? (Is it a really bad idea to put some conditional logic in a template... "if logged in uid = one of values in field x, print, otherwise don't" ? (I don't know the twig syntax for that))
(Since I mentioned private messages, I'm aware of the D9 PM module. But for a lot of reasons, I'd rather just use nodes and comments system. The node+comment system is already well developed and the only thing missing really is multiple-user visibility control.)
Answer: Yes, it's a bad idea to do this in templates as their output will be cached by default.
If it's just for viewing the full node via its canonical URL (/node/123 or /my-node-alias) you can achieve that easily by implementing hook_ENTITY_TYPE_access in a custom module.
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Implements hook_ENTITY_TYPE_access().
 */
function MYMODULE_node_access(EntityInterface $entity, $operation, AccountInterface $account) {

  // Check node type and operation.
  if ($entity->bundle() === 'article' && $operation === 'view') {

    $uids = [];
    // Get the allowed users.
    if ($users = $entity->get('field_users')->getValue()) {
      $uids = array_column($users, 'target_id', 'target_id');
    }
    // Add the node author.
    $uids[$entity->getOwnerId()] = $entity->getOwnerId();

    // Return "forbidden" if current user is not in that list.
    return AccessResult::forbiddenIf(!isset($uids[$account->id()]))
      ->cachePerUser()
      ->addCacheableDependency($entity);
  }

  // No opinion.
  return AccessResult::neutral();
}

But note that this hook is not called from Views or entity queries for performance reasons and for proper functioning of the pager system. For that you need to implement a different access strategy, see [Drupal API] Node access rights and [Question] Views Search Ignoring Custom Node Access permissions.
Note also that this hook is bypassed for user 1 (if you during development wonder why breakpoints/dump() are ignored).
Comment: @aharown07 – Yes
Comment: Much appreciated! The additional views info is also a huge help. On views: in practical terms that means users without access to the node will be able to see it in a view (unless the view is otherwise configured to hide those nodes)? But a node link in a view would still go through hook_ENTITY_TYPE_access if you click it. Am I right?
Comment: Maybe this should be a separate post, but the context here helps: Can anyone steer me toward a hook (or other method) that would be called from views? I'm using regular views access controls and block controls as a solution now, but I'm a little paranoid, so... what if some view breaks and links are visible to users who should not see them? So I'd like a layer that would do a similar access check on the link from views also.
Answer: I added condition to give the node author access also, without including the author in the entity reference field:
<?php
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Implements hook_ENTITY_TYPE_access().
 */
function MYMODULENAME_node_access(EntityInterface $entity, $operation, AccountInterface $account) {
  if ($entity->bundle() === 'pm' && $operation === 'view') {
    if ($users = $entity->get('MYFIELDNAME')->getValue()) {
      $uids = array_column($users, 'target_id', 'target_id');
      $author_id = $entity->getOwnerID();
      if (isset($uids[$account->id()]) || $author_id == $account->id()) {
        return AccessResult::neutral();
      }
    }
 return AccessResult::forbidden();
  }
}

Comment: Maybe there's a more efficient way to do that?
Comment: Answer 2 seems obsolete after updates to Answer 1: at the moment, with Node View Permissions installed, the author of the node also has visibility when not listed in the entity reference field.


Compound angles formula derivation(crown molding)

Question: So I've been trying to get my head around this for a week now. It's a practical problem, but the geometry seems more involved then I initially thought.
When you want to attach a crown molding to a wall with a certain spring angle and wall angle, you can cut the molding laying flat with a miter saw, setting both miter and bevel angle to a certain degree, as illustrated here:
https://www.blocklayer.com/crown-molding.aspx
The formula behind this calculator is as follows:
$$Miter = \arctan(\cos(B) * \tan(A/2)) \\
Bevel = \arcsin(\sin(B) * \sin(A/2)) $$
With $A$ the wall angle and $B$ the spring angle.
Now my real question is, how to arrive at these formulas?
I've made a number of drawings, but frankly they are all awful :)
I've tried composing the normal vectors as in this answer:
How to calculate compound angles
But didn't get too far.
Can someone point me in the right direction?
Thanks!!
Answer: You can find a comprehensive explanation at the following link. If there is anything else you need help on, just leave a comment under this answer.
http://jansson.us/nsideboxderive.html
Comment: Thanks!! I saw a ton of calculator sites, but none with a detailed (and graphical!) explanation.
I can see clearly now :)
Answer: HINT:
Try to draw a 3d trig right angled triangles yourself.
Given are the angles $( A,B).$
Since you cutting away one half you need to consider only its half angle $( A/2)$ at corner.
See where unit edge length $1$ comes in. Draw its components in a right triangle involving angle $B$:
$$( \sin B, \cos B )$$
Recognize in these right triangles required angles $(Mit,Bev)$
$$ \dfrac{\sin Bev}{\sin A/2} = \sin B  $$
$$ \dfrac{\tan Mit}{\tan A/2} = \cos B . $$


Holomorphic function in an annulus

Question: I'm trying to do a question but I have a doubt on holomorphic functions, here is the problem.

Let $A = \{z ∈ \mathbb{C} : \frac{1}{R}< |z| < R\}$. Suppose that $f : A → \mathbb{C}$ is holomorphic and
  that $|f(z)| = 1 $ if $|z| = 1$.
  Show that $f(z) = {\left(\overline{f(\bar{z}^{−1})}\right)}^{-1}$ when $ |z| = 1 $ and deduce that this holds for all $z ∈ A$.

Now, my problem is with the final deduction...
I think I need something about the zeroes of f as the right-hand side of the equality could not be defined at some point.
Am I right or is there a way to prove that a function with these properties can never be zero in A?
Thank you all.
Comment: If $|z|=1$ then $(\bar z)^{—1}=z$.
Comment: p.s. knowing that it is never zero i think the most is done as the rhs is holomorphic as well and you just use the uniqueness theorem as |z|=1 has a limit point in A
Comment: Max. modulus principle gives me an upper bound for the modulus of the function doesn't it? What I need is a lower (positive) bound..
I'm not even sure if it is true that such a function has to be non zero, a mobius transformation which maps the unit circle to itself can actually have zeros...
Comment: i think it is true, actually it must be by the uniqueness theorem!
Comment: Yes, you don't need to prove it doesn't have any zeroes, it follows from the uniqueness theorem.
Comment: but for the uniqueness theorem i need the function on the rhs to be holomorphic in A. and it is not if f has zeroes in A, that's why I am worried about them!
Answer: $f(z) \cdot \overline{f(1/\,\overline{z})}$ is well-defined and holomorphic on $A$ and equal to $1$ for $|z|=1$.  Then it is constant on $A$, since level sets of non-constant holomorphic functions are discrete.
Comment: thank you, really helpful! I couldn't see the last part so easily (don't really understand the terminology)
anyway I did get it using identity theorem!

Holomorphic function in an annulus


Hereditary cardinality and products of sets

Question: To start, suppose that $\lambda$ is an infinite cardinal and suppose that $\alpha, \beta \in \mathbf{H}_\lambda$, where $\mathbf{H}_\lambda = \{x : \left|\operatorname{trcl}(x)\right| < \lambda\}$. I'm wondering, is it true that $\alpha \times \beta \in \mathbf{H}_\lambda$? I feel as though it ought to be, but I'm really not sure how to show it.
Explicitly, the notion of transitive closure I've been working with is defined as $\operatorname{trcl}(x) = \bigcup_{n \in \mathbf{N}} U(x, n)$, where $U(x, 0)= x$ and $U(x, n+1)= \bigcup U(x,n)$. So my thought was that if one could show by induction that $\left|U(\alpha \times \beta, n)\right| < \lambda$ for all $n \in \mathbf{N}$, then we could conclude that $|\operatorname{trcl}(\alpha \times \beta)| < \lambda$, but I'm having a hard time finishing the induction. I was hoping someone could help me sort this out? Any assistance is appreciated.
Answer: Remember the definition of the Cartesian product:
$$A\times B=\{\{\{a\},\{a,b\}\}:a\in A,\>b\in B\}.$$
From this, we get
$$
\begin{align}
\operatorname{trcl}(A\times B)=&(A\times B)\cup\bigcup(A\times B)\cup\bigcup{}^2(A\times B) \cup \operatorname{trcl} \bigcup{}^2(A\times B)\\
=&(A\times B)\cup (\{\{a\}:a\in A\}\cup \{\{a,b\}:a\in A,b\in B\})\cup (A\cup B)\cup \operatorname{trcl}(A\cup B)
\end{align} $$
($\bigcup^2 X$ means $\bigcup\bigcup X$.)
and you can check that each set mentioned above has cardinality $<\lambda$.
Comment: This is really nice, thanks!


Change template of Drag & Drop module on node add form

Question: I am using Drag & Drop Upload module for multiple images uploading.
But the template I see on node add form (FRONTEND) is this :
And I want to change it to this :
I don't know where can I find the HTML for this template, so I can change it.
Thank you so much for your help!
Comment: Just use css !!
Comment: Thanks @NikhilM , There are actually alot of changes, and I really need to change HTML for this, for example the default is using Tables, I need divs. I am sure that must be possible to change the template.
Comment: I see, changing the filed templates is bit tricky. I would do it with `CSS` which is much faster.
Answer: You can do this by updating css into that module.
Or once try to use HTML5 Drag & Drop File module. Hope this module provided that you want.

HTML5 drag & drop + HTML5 file upload with XHR2. Allows the user to
  drag & drop files into a Image/File Field and uploads it immediately
  behind the scenes. In theory it should work for as many files as the
  field allows.


Dell PowerEdge R710 - how to assign IP address to 4 available NICs and iDRAC?

Question: I have a DellPowerEdge R710 server, brand new, with no configuration. How can I assign the IP address to its 4 NICs and iDRAC? Thanks!
I would like to install ESXi 5.5 on that server and be able to manage it remotely.
Comment: Judging from this and your past questions here on ServerFault, you might consider taking a step back and realizing that you need to learn more about the equipment and software you are wanting to run direct from the OEMs or through formal training avenues.
Comment: You should stop wasting our time and go speak to your manager about getting some much needed education - you really need it. You might also find http://slash7.com/2006/12/22/vampires/ an interesting if uncomfortable read.
Comment: This is a very broad question.  Please provide more details such as the OS you are going to install and what type of configuration you wish to achieve with the network interfaces.
Comment: Do you mean you just have one IP address?  What operating system is installed?
Answer: You can access the DRAC BIOS by using CTRL+E during POST, can set IP address in this BIOS for iDRAC interface.
For 4 ports on the integrated NIC you set IP address during OS installation or network interfaces configuration process.
Comment: you can set ip addressing to your 4 ports through ESXi configuration setup menu, once you install OS, hence ESXi in your case.
Comment: Ok, I will do it for iDRAC with no problems now, thanks! ;) I would like to install on this server ESXi. How can I assign IP addresses for my 4 NICs with ESXi? And what do you mean by `network interfaces configuration process`? Can it be done in BIOS too? Or through iDRAC?
Comment: Hmm, havent seen such option in ESXi before. Can it be done through iDRAC too? (Instead of ESXi way)? Will check it tomorrow
Comment: Heres what I meant: http://i59.tinypic.com/2441rbq.png I can only configure the management network with ESXi, what about other, 4 ports?
Comment: so once you configure your management network, you assign ips to other interfaces through ESXi shell cli or Vcenter vsphere client.
Answer: Since the other answer covered the iDRAC part of the question this will cover the VMWare ESX part.  On the console of the host you can configure the management network for the host.  As your screenshot indicates you can select which NICs to configure for management.  By selecting all of the NICs this will place them on the same virtual switch and into an active-standby team.  The host will be accessible from the IP you designate as the management IP in the console.
Using the VMWare vSphere Client you can configure multiple virtual switches with different subnets and even assign them directly to an individual NIC to segment traffic onto multiple networks.  Please reference the VMWare Networking Documentation for more information.
It is also possible to configure the network interfaces via the console or ssh session.
Please refer to VMWare documentation for best practices regarding networking with virtual hosts.


In $(\mathbf Z/p^r \mathbf Z)^*$, finding an element with order $p-1$.

Question: Let $p$ be an odd prime number.
I want to prove that $(\mathbf Z/p^r \mathbf Z)^*$ is an cyclic group.
I have known that $\overline {p-1} \in (\mathbf Z/p^r \mathbf Z)^*$ is of order $p^{r-1}$.
Since the order of the group is $(p-1)p^{r-1}$, if we find an element with order $p-1$, we conclude that $(\mathbf Z/p^r \mathbf Z)^*$ must have an element with order $(p-1)p^{r-1}$.

$\because$ Every finite commutive group has an element with order of its exponent.

So how to I find the existence of an element with order $p-1$?
Answer: I think it is possible by induction, for $r=1$ it is the classical result I assume to be true.
Take $0\leq x\leq p-1$ such that $x$ is of order $p-1$ in $\mathbb{Z}/p \mathbb{Z}^*$. We will be looking for an element of order $p-1$ in $\mathbb{Z}/p^2 \mathbb{Z}^*$ under the form :
$$x_2=x+\alpha p $$
Where $\alpha$ is to be determined, we have :
$$x_2^{p-1}=x^{p-1}+(p-1)\alpha x^{p-2} p\text{ mod } p^2 $$
$$x_2^{p-1}=x^{p-1}-\alpha x^{p-2}  p\text{ mod } p^2 $$
Now because $x$ is of order $p-1$ we have $x^{p-1}=1+t_1p$ hence :
$$x_2^{p-1}=1+(t_1-\alpha x^{p-2})  p\text{ mod } p^2 $$
Hence $\alpha$ must verify the equation $t_1-\alpha x^{p-2}=0$ mod $p$. This is clearly solvable because $x^{p-2}$ can be inversed mod $p$, hence one can construct $\alpha$ such that :
$$x_2:=x+\alpha p\text{ is of order dividing } p-1 $$
Now $x_2=x$ mod $p$ so its order must be divided by the order of $x$ mod $p$ which is $p-1$ hence $x_2$ is exactly of order $p-1$.
Assume now that $x_{r-1}$ is of order $p-1$ in $\mathbb{Z}/p^{r-1} \mathbb{Z}^*$ then define :
$$x_r:=x_{r-1}+\alpha p^{r-1} $$
Likewise, this define an element in $\mathbb{Z}/p^{r} \mathbb{Z}^*$ and :
$$x_r^{p-1}=x_{r-1}^{p-1}+(p-1)\alpha x_{r-1}^{p-2} p^{r-1}\text{ mod } p^r $$
$$x_r^{p-1}=x_{r-1}^{p-1}-\alpha x_{r-1}^{p-2} p^{r-1}\text{ mod } p^r $$
But $x_{r-1}^{p-1}=1+t_{r-1}p^{r-1}$ hence we have that :
$$x_r^{p-1}=1+(t_{r-1}-\alpha x_{r-1}^{p-2}) p^{r-1}\text{ mod } p^r $$
Now the equation in $\alpha$ : $t_{r-1}-\alpha x_{r-1}^{p-2}=0$ mod $p$ is solvable hence one can find $\alpha$ such that $x_r$ is of order dividing $p-1$, now by construction $x_r$ mod $p^{r-1}$ is $x_{r-1}$ hence its order must be divided by $p-1$, finally $x_r$ is an element of order $p-1$ in $\mathbb{Z}/p^r \mathbb{Z}^*$.
Comment: I appreciate your answer. It is very good.


Html builder in .net 1.1?

Question: I'm currently doing some maintenance on some existing .net 1.1 VB code that creates HTML from code.
It mainly consists of a bunch of stringbuilder.Append("
").
Isn't there a clean way to create HTML tags?
Answer: HtmlTextWriter should be in .NET 1.1. I thank that is the cleanest way using only .NET 1.1 types.

Html builder in .net 1.1?


Grab all users who have last logged in between two dates in another table

Question: I want to grab all users that have last logged in between two specific days. How can this be done?
Note: the reason why I did sub.updated_at is because:

the login session may last for more than a day
same users may log in on different pc and start a secondary session
I need to get the very last session started by the user and then check when it was last updated.

Example build: http://sqlfiddle.com/#!9/39849/11
So from the example on sqlfiddle I would expect the query to select Bill, because updated_at, for his last record, is between 2019-09-15 00:00:00 and  2019-09-15 23:59:59. One of John's entries was also updated between those dates but his latest record was updated on 2019-09-18 12:00:00 hence why John should not be selected.

This is a possible solution, but I have concerns about performance, indexing update_at should have a positive effect, but what if we have 1mil+ users and an even greater number of user logins:
SELECT *
FROM
(
    SELECT *
    FROM (
        SELECT *
        FROM `user_logins`
        WHERE `updated_at` >= '2019-09-15 00:00:00'
        ORDER BY `user_logins`.`id`  DESC
    ) as sub
    GROUP BY `sub`.user_id
) as sub
WHERE `sub`.updated_at BETWEEN '2019-09-15 00:00:00' and '2019-09-15 23:59:59'

SELECT *
FROM (
    SELECT *
    FROM `user_logins`
    WHERE `updated_at` BETWEEN '2019-09-15 00:00:00' and '2019-09-15 23:59:59'
    ORDER BY `user_logins`.`id`  DESC
) as sub
WHERE NOT EXISTS (
        SELECT 1
        FROM user_logins
        WHERE user_id = sub.user_id
            and updated_at > '2019-09-15 23:59:59'
    );

Comment: Please frame SQL questions with **relevant and minimal sample data** showcasing your requirements, and **corresponding expected output**. Please read this link: [Why should I provide a Minimal Reproducible Example for a very simple SQL query?](https://meta.stackoverflow.com/q/333952/2469308)
Answer: You query may be simplified to -
SELECT U.*, UL.*
FROM users U
JOIN user_logins UL ON U.id = UL.user_id
JOIN (SELECT user_id, MAX(updated_at) updated_at
      FROM user_logins
      GROUP BY user_id) UL2 ON UL2.updated_at = UL.updated_at
                            AND UL2.user_id = UL.user_id
WHERE DATE(UL2.updated_at) BETWEEN DATE('2019-09-15 00:00:00') AND DATE('2019-09-15 23:59:59')
ORDER BY UL.id DESC

Here is the fiddle.
Comment: This query grabs single user and i need to grab all users who fit the criteria.
Comment: So,  http://sqlfiddle.com/#!9/39849/1, from fiddles example, if i was to use your query, excluding limit, i would select both Tim and John if updated_at was between `2019-09-15 00:00:00` and `2019-09-15 23:59:59`. Instead of just Tim.
Comment: @user3402600, I have updated the query. Please try now. Here is the updated fiddle - http://sqlfiddle.com/#!9/39849/55
Comment: Thanks for that Ankit, however, your query still selects John.
Comment: Did you see the fiddle in the comment? it is perfectly selecting both the records.
Comment: Yes, i have. It should only be selecting Tim
Comment: You need only tim or the fiddle in answer is giving you only Tim?
Comment: I need only Tim to be returned
Comment: That's pretty good, thanks... the use of subqueries within join didn't pass my mind. One thing to note,  `JOIN user_logins UL ON U.id = UL.user_id` cause query to scan the whole table, which will cause issues once users table grows.
Comment: @user3402600, When table grows this much so that it creates performance issues, You can have indexes or partitioning on the table to improve performance. BTW if this answer solves your problem, Please consider up-voting and accept.


Como acessar o conteudo desse subArray?

Question: Eu consigo acessar o conteúdo de um Array assim:
{{teste02[0]}}

E obtenho como retorno o seguinte:
{"assigned_date":"1969-12-31 21:00:00.000","user_id":"101","role_id":"101","group_id":
{"path":"/administrador","displayName":"Administrador","icon":"",
"name":"administrador","description":"","parent_path":"",
"creation_date":"2017-08-18 11:04:28.846","id":"302",
"created_by_user_id":"-1","last_update_date":"2017-08-18 11:04:28.846"},"assigned_by_user_id":"-1"}

Porém o que eu realmente preciso é acessar o conteúdo do subArray name. Já tentei {{teste02[0][0].name}} mas nada me é retornado, como poderia acessar isso?
Comment: Descobri, na verdade o modo como deveria ter colocado era assim: `{{teste02[0].group_id.name}}`, não sei se nesse caso fecho a pergunta ou apenas respondo a mesmo com isso, se puderem me indicar o correto a fazer agradeço
Comment: Você pode responder o que fez para resolver e se tiver referencias sobre o assunto postar na sua resposta.!
Answer: O problema estava no modo como tentei acessar o conteúdo do subArray, eu havia errado o caminho completo que precisava disponibilizar para acessar seu conteúdo.
Inicialmente eu havia colocado assim: {{teste02[0].name}}
Porém antes de conseguir acessar esse conteúdo havia o subArray group_id. No fim o correto era colocar assim : {{teste02[0].group_id.name}}

Como acessar o conteudo desse subArray?


To find integrating factor of differential equation

Question: I have a differential equation of form
$$(4x^2 y + 5x^3 y^2 ) \, dx +(2x^3 + 3x^4 y) \, dy=0$$
I have tried everything but I do not know how they came up with $ xy $ as IF. Can anybody help me? Thanks.
Comment: That isn't an equation
Comment: Is your expression equal to zero?
Answer: You're looking for a function $u(x,y)$ such that the following holds:
$$\frac{\partial u}{\partial x}N(x,y)-\frac{\partial u}{\partial y}M(x,y)=u(x,y)\left(\frac{\partial M}{\partial y}-\frac{\partial N}{\partial x}\right)$$
where $M$ and $N$ are taken from the differential equation, $M(x,y)dx+N(x,y)dy=0$.
Replacing the appropriate expressions and dividing through by $u$ gives
$$\begin{align*}\frac{u_x}{u}(2x^3+3x^4y)-\frac{u_y}{u}(4x^2y+5x^3y^2)&=(4x^2+10x^3y)-(6x^2+12x^3y)\\
&=-2x^2-2x^3y
\end{align*}$$
You want $\dfrac{u_x}{u}$ and $\dfrac{u_y}{u}$ to be functions of $x$ and $y$, respectively; denote them as $F(x)$ and $G(y)$.
$$F(x)(2x^3+3x^4y)-G(y)(4x^2y+5x^3y^2)=-2x^2-2x^3y$$
Solving for $F(x)$, you have
$$F(x)=\frac{G(y)(4x^2y+5x^3y^2)-2x^2-2x^3y}{2x^3+3x^4y}$$
Notice that letting $G(y)=\dfrac{1}{y}$, you have
$$F(x)=\frac{4x^2+5x^3y-2x^2-2x^3y}{2x^3+3x^4y}=\frac{2x^2+3x^3y}{x(2x^2+3x^3y)}=\frac{1}{x}$$
This gives you the provided integrating factor,
$$\begin{align*}u(x,y)&=\exp\left(\int\frac{dx}{x}+\int\frac{dy}{y}\right)\\&=\exp\left(\ln x+\ln y\right)\\&=xy
\end{align*}$$
Answer: Notice that $$\frac{\frac{\partial}{\partial y}(4x^2y+5x^3y^2)-\frac{\partial}{\partial x}(2x^3+3x^4y)}{y(2x^3+3x^4y)-x(4x^2y+5x^3y^2)}=\frac{1}{xy}$$ is a function of $xy$ only.
Thus $$e^{\int^{xy}\frac{1}{v}\,dv}=xy$$ is the IF for this DE.
PS: Attached is an explanation if you are interested

In case you are wondering what equation (1.2.1) is.
Comment: Which rule is this
Comment: Hi, I have edited my answer. You can look through the attached images to understand the reason.


Does Quick Edit function work for embedded entities?

Question: I have a view which creates a block of User data related to the author of the node. The view display is a view mode of the User entity.
I see my entity when the block is placed on the node page; but there is no quick edit functionality. Is this expected behavior?
Answer: It does work, for Nodes, when set to Show: Content | Full Content.
However, it does not work for Users. Fairly expected as when you go to a user page, ex: /user/1 there is no quick edit feature there to begin with.


Find a splitting field of $x^2 + 1$ over $\mathbb{Z}_3$

Question: We know that $x^2 -3$ is irreducible in $\mathbb{Q}[x]$. We also know that $\sqrt{3}$ solves $x^2 - 3$. As a result, $x^2 - 3 = (x-\sqrt{3})(x+\sqrt{3})$. This implies that the splitting field of $x^2 - 3$ over $\mathbb{Q}$ is $\mathbb{Q}(\sqrt{3})$.
At the same time, we also know that the field $\mathbb{Q}[x]/(x^2 - 3)$ has element that solves $x^2 - 3$. So I suppose $\mathbb{Q}[x]/(x^2-3)$ is isomorphic to $\mathbb{Q}(\sqrt{3})$.
Now I have the following question

Find a splitting field of $x^2 + 1$ over $\mathbb{Z}_3$

One answer would be $\mathbb{Z}_3[x]/(x^2 + 1)$. But does it make sense to say one splitting field is $\mathbb{Z}_3 (\alpha)$ where $\alpha$ solves $x^2 + 1$?
Comment: I think you mean $\mathbb Z_3 [x] / (x^2 + 1)$.
Comment: @JacksonHsu Yes, you are right. Thank you.
Answer: let $\alpha$ is root of $f(x)=x^2+1$ in Extended field of $\mathbb{Z}_3$,therefore
$$f(\alpha)=f(-\alpha)=\alpha^2+1=0$$
on the other hand
$$-\alpha=2\alpha$$
as a result
$$\mathbb{Z}_3(\alpha)=\{a+b\alpha|\,a,b\in\mathbb{Z}_3\}\cong \frac{{{\mathbb{Z}}_{3}}[x]}{({{x}^{2}}+1)}=a+bx+\left\langle {{x}^{2}}+1 \right\rangle$$
Answer: Yes of course.  It's a basic theorem in field theory that for each field $F$ and irreducible polynomial $f(x) \in F[X]$, there exists some field extension $E$ of $F$ such that $f$ has a root (say $\alpha$) in $E$.  Since your polynomial has degree $2$, $\mathbb{Z}_3(\alpha)$ is necessarily the splitting field of $x^2+1$ over $\mathbb{Z}_3$
Answer: The idea is that if $ f $ is irreducible in $ K[x] $ where $ K $ is a field, then the ring homomorphism $ \phi : K[x] \to K[\alpha] $ ($ \alpha $ is a root of $ f $) defined by $ \phi(p(x)) = p(\alpha) $ has kernel $ (f) $, so by the first isomorphism theorem we have $ K[x]/(f) \cong K[\alpha] $. Since $ (f) $ is maximal, this quotient is actually a field, which gives $ K[x]/(f) \cong K(\alpha) $.
Since $ x^2 + 1 $ is irreducible in $ \mathbb{F}_3[x] $, we conclude that $ \mathbb{F}_3[x]/(x^2 + 1) $ is a field which contains a root of $ x^2 + 1 $, and it contains the other root since the two roots sum to zero. Since it is the smallest such field, we conclude that it is in fact the splitting field of $ x^2 + 1 $ over $ \mathbb{F}_3 $.


Disadvantage of precision at k

Question: Suppose 10 documents were retrieved (rectangle with black color is relevant document). In the following table, Precision @ k is calculated. P@10 or "Precision at 10" corresponds to the number of relevant results among the top 10 documents.

| rank(K)| Precision@K    |
| ------ | -------------  |
| 1      | (1/1) = 1.0    |
| 2      | (1/2) = 0.5    |
| 3      | (2/3) = 0.67   |
| 4      | (3/4) = 0.75   |
| 5      | (4/5) = 0.80   |
| 6      | (5/6) = 0.83   |
| 7      | (6/7) = 0.86   |
| 8      | (6/8) = 0.75   |
| 9      | (7/9) = 0.78   |
| 10     | (7/10) = 0.70  |

The more relevant documents are at the front, the more influence it has and earn more points. So then we have greater Precision@k. So, if we swap ranks 8 and 9 we get the following results:

| rank(K)| Precision@K    |
| ------ | -------------  |
| 1      | (1/1) = 1.0    |
| 2      | (1/2) = 0.5    |
| 3      | (2/3) = 0.67   |
| 4      | (3/4) = 0.75   |
| 5      | (4/5) = 0.80   |
| 6      | (5/6) = 0.83   |
| 7      | (6/7) = 0.86   |
| 8      | (7/8) = 0.875  |
| 9      | (7/9) = 0.78   |
| 10     | (7/10) = 0.70  |

Wikipedia says: Precision at k documents (P@k) is still a useful metric (e.g., P@10 or "Precision at 10" corresponds to the number of relevant results among the top 10 documents), but fails to take into account the positions of the relevant documents among the top k.
Unfortunately I don't get the last sentence. How does it mean here?
We could even see that changing the position changes the precision @ k.
Answer: You need to understand

but fails to take into account the positions of the relevant documents among the top k

in the context of a fixed $k$. In your example, with $k=10$, precision at $k=10$ does not change if we swap ranks 8 and 9, as we see in the bottom rows in your tables.
Conversely, precision at $k=8$ does change, because here it is not just a question of the relative position among the top $k=8$ - rather, the document either is among the top $k=8$, or it isn't. (And among the top $k=8$, order again does not matter.)
Comment: And that's why we use measurements like (Normalised) [Discounted Cumulative Gain](https://en.wikipedia.org/wiki/Discounted_cumulative_gain). (+1 of course)
Comment: Yes, that is right.
Answer: That's a great example by Stephan. To expand a bit more, the idea with Precision @ K is that you measure the presence or absence of true results within the top K results, independent of where they are.
That last sentence

but fails to take into account the positions of the relevant documents among the top k

means that the rank or the order of the observations is not taken into account by a metric like Precision @ k. Meaning, if you care about the order or position of where the relevant documents are (1st,3rd, 8th, etc..) then, this metric isn't useful.
Specifically, here's an example. Suppose, you have 10 true relevant documents among the top 20 hits, it won't tell you where those 10 are. They could be the top 10, or they could be documents 11-20.  Precision at K=20, will only tell you you have 50% precision at K=20. However, if you test a few different Ks you would figure out that now at K=18, you'll have precision=8/18, and at K=10, you'll have 0 precision. But if you only test K=20, you wouldn't know where they are.

Disadvantage of precision at k


What is an example of a nearest neighbor relationship being non-symmetric?

Question: Context
I'm the new guy on my team, and the one with the most (but not much) math knowledge. I've been tasked to check an intern's work on implementing spectral clustering correctly in code. In that direction, I'm reading this pdf about spectral clustering and the kinds of similarity graphs that can be used in practice. It mentions a KNN graphs with the caveat that the neighborhood relationship is not symmetric, so the resulting graph is directed and needs to be made so.
So I read about nearest neighbor graphs:

The nearest neighbor graph (NNG) for a set of n objects P in a metric space (e.g., for a set of points in the plane with Euclidean distance) is a directed graph with P being its vertex set and with a directed edge from p to q whenever q is a nearest neighbor of p (i.e., the distance from p to q is no larger than from p to any other object from P).1

Which had me read about neighborhoods, open balls and open sets.
All of this is to say that I hope I've done enough work/research to ask for an example:
My question:
When (or under what conditions) is a point $p$ a neighbor of $q$ but $q$ not a neighbor of $p$? Let's say that all these points are in $\mathbb{R}^2$ and the measure is symmetric, like Euclidean or Manhattan distance, which is the case for my particular application.
If you can't tell from my wording, I'm not a math genius. Answers that don't rely on an advanced understanding of topology or complicated notation are appreciated. A simple example will do. I'm okay with basic proofs too.
Comment: Not entirely sure what you are asking, but if you consider the three points $\{0,1,5\}$ on the number line, then the nearest neighbor to $5$ is $1$ but the nearest neighbor to $1$ is $0$.  Does that answer your question?
Comment: @lulu answers it perfectly. Thank you.
Answer: We don't even have to go to $\mathbb{R}^2$ - this already happens in $\mathbb{R}$!
Consider for example $0,1,$ and $1000$ as points on the number line. Clearly the nearest neighbor of $1000$ is $1$, but the nearest neighbor of $1$ is not $1000$.
Note that thinking about this more, it's in fact very rare for the nearest neighbor relation to be symmetric. A good exercise is to figure out exactly when the nearest neighbor relation in a set of three points on the number line is symmetric. (Note that there's a subtlety here around what happens if one point is equidistant from the other two.) For simplicity, first consider the case where the first two points are at $0$ and $1$, and the third point is $>1$; the general idea will be the same.
Comment: Thanks. I've been trying to draw pictures on paper to come up with an example for 20 minutes. I feel dumb now, but I'm super appreciative.
Answer: Other folks answered your real question, but I figured I'd also answer the question you asked.
If we are in a space $X$ with metric $d$, and we define (a basis for) the open sets of this space to be the $\epsilon$-balls about all points in $X$,
$$
B_d(x,\epsilon) = \{ y \, | \,d(x,y) < \epsilon \},
$$
then because of the symmetry property of the metric $d(p,q) = d(q,p)$, it follows that $p \in B_d(q,\epsilon) \Leftrightarrow q \in B_d(p,\epsilon)$.  In other words, if you define your neighborhoods relative to the metric on a space, then having $p$ in a neighborhood of $q$ implies that $q$ is in a neighborhood of $p$.
As is pointed out in Noah Schweber's answer, the "nearest" part of the definition of a "nearest neighbor graph" is what makes the relation non-transitive. In the notes you linked on spectral clustering, the notion of an "$\epsilon$-neighborhood graph" (p. 3) corresponds to the notion of two points being within some standard-size neighborhood of each other without necessarily being each other's nearest neighbors; and the relationship so created is symmetric.
There are other ways to define neighborhoods than using a metric function, but in general they still have this property.  In the context of point-set topology, we just have a space $X$ and a collection of subsets of $X$ that we call "open sets", along with certain axioms (the union of open sets is an open set, etc.)  In this context, a "neighborhood of a point $p$" is just an open set containing $p$.  But even in this context, saying that "$q$ is in a neighborhood of $p$" implies that "$p$ is in a neighborhood of $q$", since both statements are just saying that there exists an open set containing both $p$ and $q$.
Comment: So, I think this actually gets to the heart of my question... I always thought of a neighborhood to be a ball around a point, as you say here. In this case, the relationship is symmetric. But the wording of the wikipedia article gives this other heuristic about "the distance from p to q is no larger than from p to any other object from P"... The two definitions seem to contradict each other, so I'm not sure which one to go with in my mind (especially because I have a practical application for all of this).
Comment: @rocksNwaves:  As was pointed out in [Noah Schweber's answer](https://math.stackexchange.com/a/4159128/248639), the "nearest" part of the definition of a "nearest neighbor graph" is what makes the relation non-transitive.  In the notes you linked on spectral clustering, the notion of an "$\epsilon$-neighborhood graph" (p. 3) corresponds to the notion of two points being in *some* neighborhood of each other without necessarily being each other's *nearest* neighbors; and the relationship so created *is* symmetric.
Comment: Aaahh! That's the distinction I was missing. I wish we could combine your two answers into one!


Boss rc3 Looper: playback is happening during recording

Question: I just bought a used rc3 looper. The loops are playing back before I finish them, and I cant seem to delete it once I've recorded to a track. I was wondering if anyone had any advice.
Comment: Maybe a start: http://my.boss.info/support/by_product/rc-3/owners_manuals/
Comment: "The loops are playing back before I finish them": how long are your loops? Is it during recording or overdubbing.
"I've recorded to a channel": what do you mean by channel? There is only of what I would consider a channel in RC3
Comment: Thank you,I meant track I'm just a newb. It was during recording when I had reverb on the amp.
Answer: While it's stopped, press and hold the footswitch until "CL" flashes, indicating that the track is cleared out. It sounds like there is already a loop saved on that track.
Comment: Thank You, It  didn't have anything saved on the track but I had the reverb on my amp on and it stopped when I turned off the reverb.


How to use inverse information matrix and Delta method to find sample variation?

Question: Explain how the inverse of the information matrix and the Delta Rule be used to generate an approximate sampling variance for the estimated proportion exp(beta 0 + beta 1)/(1+exp( beta 0 + beta 1))?

I believe I am needing to find the estimated proportion of the exposed group/when x=1. I think I need to take the inverse logit with respect to beta 1 and use this in the Delta rule somehow.
Any help would be appreciated on how to do this.
Comment: This looks like a homework/self-study problem, in which case the `self-study` tag needs to be added. You also need to show your attempt(s) at solving this problem if you want a good response.
Comment: Thanks , have edited question now.
Answer: [The picture does not show the complete setup, but it seems to be a logistic regression problem with $y \mid x \sim \text{Bernoulli}(\pi(x))$ where $\pi(x) = \exp[\beta_0 + \beta_1 x] / (1 + \exp[\beta_0 + \beta_1 x])$, and $x$ is a binary predictor. The model assumption is necessary to ensure that the regularity conditions of CLT for the MLE holds.]
First, we need the asymptotic distribution of the MLE $\hat \beta = (\hat \beta_0, \hat \beta_1)$. If $\beta$ is the true value of the regression parameter vector, then from the CLT of the MLE (Wikipedia) we have (the regularity conditions justifying the CLT holds under a logistic regression framework)
$$
\hat \beta \stackrel{a}{\sim} N\left(\beta, I(\beta)^{-1}\right)
$$
where $X \stackrel{a}{\sim} f$ means $X$ is approximately distributed as $f$, and $I(\beta)^{-1}$ is as given. (Derivation of this inverse Fisher information matrix is cumbersome. Fortunately, the final form of the matrix is given here, saving us a substantial amount of work.)
Let $g(\beta) = \exp[\beta_0 + \beta_1] / (1 + \exp[\beta_0 + \beta_1]) = 1 - 1/(1 + \exp[\beta_0 + \beta_1])$ (which is $\pi(1)$ in my notation). Then by the delta method (Wikipedia) we have ($g$ is a smooth function with infinitely many derivatives, so we don't have to worry about the regularity conditions)
$$
g(\hat \beta) \stackrel{a}{\sim} N \left(g(\beta), \left( \frac{\partial g}{\partial \beta} \right) I(\beta)^{-1} \left(\frac{\partial g}{\partial \beta} \right)^T \right).
$$
Here
$$
\frac{\partial g}{\partial \beta} = \left( \frac{\exp[\beta_0 + \beta_1]}{(1+\exp[\beta_0 + \beta_1])^2},  \frac{\exp[\beta_0 + \beta_1]}{(1+\exp[\beta_0 + \beta_1])^2}  \right) =  \frac{\exp[\beta_0 + \beta_1]}{(1+\exp[\beta_0 + \beta_1])^2} (1, 1)
$$
(Verify!) Use the above gradient with the given inverse Fisher information matrix $I(\beta)^{-1}$ to get the approximate variance of $g(\hat \beta)$, which is $\left( \frac{\partial g}{\partial \beta} \right) I(\beta)^{-1} \left(\frac{\partial g}{\partial \beta} \right)^T$. [You may find the identity
$$
(1, 1)
\begin{pmatrix}
a_{11} & a_{12} \\
a_{12} & a_{22}
\end{pmatrix}
\begin{pmatrix}
1 \\
1
\end{pmatrix}
=
a_{11} + 2 a_{12} + a_{22}
$$
helpful.]


Comparison of triangle areas

Question: Let $ABC$ be a triangle in the plane and $X,Y$ and $Z$ points on the segments $BC,CA$ and $AB$. $X,Y$ and $Z$ are not identical to any corner of $ABC$.
Additionally, for a given $X$, let $P$ be the intersection of segment $CA$ and the line through $X$ parallel to $AB$. Finally, $Q$ shall be the intersection of $AB$ and the line through $X$ which is parallel to $CA$.
I want to prove the following two statements: For a given $X$ on $BC$,

if point $Y$ is located between $P$ and $A$ and point $Z$ is located between   $Q$ and $B$, then $A_{XYZ}>A_{XPZ}$. See picture
if point $Y$ is located between $C$ and $P$ and point $Z$ is located between $A$ and $Q$, then $A_{XYZ}>A_{XPZ}$. See picture

The statements seem kind of clear to me geometrically if I compare the perpendicular heights of the two triangles ($Y$ has a bigger distance to line $ZX$ than $P$). But have you got any ideas about how to prove it?
Thank you in advance for your help!
Answer: In case 1 (see picture) draw from $Y$ a line $YH$ parallel to $AB$. It follows from the hypotheses that $YH>PX$. But the heights of triangles $YXZ$ and $PXZ$ with respect to commmon base $AB$ (dashed lines in the picture) are proportional to $PX$ and $YH$, so the height of $YXZ$ is greater than the height of $PXZ$. It follows that the area of $YXZ$ is greater than the area of $PXZ$.
A similar argument holds for case 2.
Comment: Thank you! I would prove case 2 by [drawing lines parallel to $BC$](http://postimg.org/image/j325kceb5/). Is that what you intended?
Comment: I'd rather do [exactly the same construction](http://i.stack.imgur.com/pfi80.png): one still has $YH>PX$.

Comparison of triangle areas


Calculate total no . of case per category, given case rate per $100,000$ and total no. of cases

Question: I have the information on case rate per category
Eg - $$A \to 97 \text{ per } 100,000$$
$$B \to 169 \text{ per } 100,000$$
$$C \to 189 \text{ per } 100,000$$
$$D \to 234 \text{ per } 100,000$$
$$E \to 241 \text{ per } 100,000$$
$$F \to 420 \text{ per } 100,000$$
The total no. tests is $148,126$ and the total no. of confirmed cases is $10,490$
How should I calculate the total no. of cases per category?
Thank you
Comment: Are the categories mutually exclusive and exhaustive?  That is, does every case belong to exactly one of the six categories?
Comment: You need cathegory weights $w_i$, then you'll have $N\sum\limits_{n=1}^{6} p_iw_i=n=10490$ where $N$ is total population and $p_1=97\cdot 10^{-5},\,\ldots,\,p_6=420\cdot 10^{-5}$ then $Np_iw_i$ will be the desired value.
Comment: Yes, every case belong to exactly one of the six categories
Comment: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference?page=2&tab=Votes Here is a Mathjax tutorial to help you format math text on this site.
Answer: We have $$
97 + 169 + 189 + 234 + 241 + 420=1350$$
So out of $10490$ cases, we expect that $$\frac{97}{1350}\cdot10490 = 753.726$$ cases belong to category A, and so on for the other categories.


Why does MUI DatePicker prevent rendering in my project (working sandbox MRE included?)

Question: I created a codesandbox with a minimal working implementation of MUI's Datepicker:
https://codesandbox.io/s/proud-pond-fb4rm?file=/src/App.js
*Edited to add my index.tsx:
<code>import React from 'react';
import ReactDOM from 'react-dom';
import {DatePicker, LocalizationProvider} from "@mui/lab";
import {TextField} from "@mui/material";
import AdapterDateFns from "@mui/lab/AdapterDateFns";

ReactDOM.render(
  <LocalizationProvider dateAdapter={AdapterDateFns}>
    <DatePicker
      renderInput={(props) => <TextField {...props} />}
      value={null}
      onChange={() => null}
    />
  </LocalizationProvider>
  , document.getElementById('root')
)
</code>
This implementation throws errors in my project (prevents rendering), although I have the same versions installed. I linked my package-lock file for good measure in case I'm wrong.
Clearly not a bug, and seemingly not a mismatch in package versions, what else could be causing this?
package-lock.json
Comment: Your codesandbox implementation isn't about your problem. Without your current code, impossible understand the reason for the errors
Comment: @Codebling "The above error" is identical to the one you see below (Uncaught TypeError) - that's my bad for cropping the way I did
Comment: @VitaliyRayets I've edited my original question to add the code. It's as barebones as can be, which leads me to believe the answer lies in my package-lock file
Comment: You have error from `MobileDatePicker`, but in code you use `DatePicker`, i think you miss something
Comment: What is "the above error" listed in the first stack trace?
Comment: @VitaliyRayets I see what you're saying, but that's all happening in the library
Comment: I tried with your package-lock.json and I still can't get the line numbers to match up. It looks like it's trying to read `utils.formats.keyboardDate` but `formats` is undefined. I'm not sure why that may be. I don't see the error in the codesandbox that was linked to. Are you able to post a codesandbox that does reproduce it?
Comment: Are you using `ThemeProvider`? (Here are [a](https://github.com/mui-org/material-ui/issues/30068) [few](https://stackoverflow.com/a/70532844/675721) [links](https://github.com/mui-org/material-ui/issues?q=cannot+read+properties+of+undefined) for my own reference)
Comment: Can you show us the top most error?
Answer: As suspected, the clue was in my package-lock.json. Note to self: Always a good idea to have a look there when issue has been isolated and confirmed unique to a given project!
I had two different versions of @date-io/date-fns installed:

1.x.x (entry in package-json)
2.x.x (installed as dependency)


With Microsoft Excel VBA, can you access one sheet from another?

Question: I'm writing some Excel VBA code and one section displays a message by selecting an entire sheet which then pops up with the desired text, Sheet2 if you like. However, the following code then refuses to run with complaint:
Method 'Range' of object '_Worksheet' failed.

In the code being called I still refer to the sheet I try to modify with Sheet1, for example  Sheet1.Range(Cells(1, 1), Cells(101, 101)).Value = "", but to no avail.
What am I doing wrong please?
Answer: That is because the Cells Object is not fully qualified.
Change your code to
Sheet1.Range(Sheet1.Cells(1, 1), Sheet1.Cells(101, 101)).Value = ""

Comment: Thanks. My apologies... though it was purely `intentional` :D
Comment: @mehow: Browser issues I guess
Comment: ah yeah thats OK the point is the answer is there for anyone with same problems in the future
Comment: Sorry, I never replied - worked a treat. Many thanks.


What's the default expiration time for block caches?

Question: This article explains the cache setting in Drupal 7.
I'm using Blockcache_alter to cache some blocks. It's not clear to me how long those blocks are cached.
Answer: Nothing special here. It's the same as on your admin/config/development/performance page. Module Block Cache Alter just alters 'cache' key for block and does not interfere with the mechanism of caching in Drupal.
Example 1:
Minimum cache lifetime: none,
Cron: every day,
Block cache will be flushed every day or if someone flush cache manually.
On node or comment submit: the whole block cache will be flushed.

In Example 1 the whole block and page cache will be flushed immediately on every new comment, node, vote submit because of Minimum cache lifetime: none. See where cache_clear_all() is called.
Example 2:
Minimum cache lifetime: 12 hours,
Cron: every 6 hours,
Block cache will be flushed every 12 hours or if someone flush cache manually.
On node or comment submit: only block cache older than 12 hours will be flushed.

Block and page cache items which are older than 12 hours will be flushed immediately on every new comment, node, vote submit. See where cache_clear_all() is called.
Cron period is important because Drupal tries to flush caches on every cron run.
This behaviour can be changed with Cache Expiration module.


Is it true that $\lim_{m\to\infty}\int_{a+1/m}^{b-1/m}=\int_{a}^{b}$?

Question: Is it true that
$$
\lim_{m\to\infty}\int_{a+1/m}^{b-1/m}=\int_{a}^{b}
$$
as long as the integral on the right hand side exists? Or is this expression a non-trivial result? (I do not really recall if it is a definition, please let me know)
Edit for precision: Suppose $f:(a,b)\to\mathbb{R}$ is continuous and the integral $\int_a^bf(x)\,\mathrm{d}x$ is exists. Is it true that
$$
\lim_{m\to\infty}\int_{a+1/m}^{b-1/m}f(x)\,\mathrm{d}x=\int_{a}^{b}f(x)\,\mathrm{d}x?
$$
Comment: If $f:[a,b]\to\mathbb R$ is Riemann integrable, or Lebesgue integrable, or even Denjoy-Perron integrable, the function  $F(x)=\int_a^x f(t)\,dt$ is continuous.  Also, for any of those integrals $\int_{a+h}^{b-h} f(t)\,dt = F(b-h)-F(a+h)$.  So obviously...
Comment: Yes its true. I think using the definition of an integral as a limit of reimann sums makes the proof pretty straightforward.
Comment: @B.S.Thomson Makes sense. I should have updated the post; what if $f$ is continuous over an open interval $(a,b)$ and the integral $\int_a^bf(x)\,\mathrm{d}x$ exists, would the equality still hold?
Comment: @Mr.MathDoctor What you mean by $\int_{a}^{b}f(x)dx$ exist, if $f:(a,b)\to \mathbb{R}$?
Comment: @Mr.MathDoctor When $f$ is not defined in $a$ and $b$ the integral is improper and then it is calculated by the limits of the integrals $\int_{c}^{d}f(x)dx$ $c\to a$ and $d\to b$, with $a\leq c <d \leq b$. If this is the case, proving it is relatively easy.
Comment: @GreyFox Yes, this is what I meant. How would you prove it? I thought it could be used what B.S.Thomson said for the case $[c,d]$, but the problem about taking limits $c\to a^{+}$ and $d\to b^{-}$ is kinda problematic, as the antiderivative is not continuous at the endpoints of $(a,b)$.
Comment: @Mr.MathDoctor Do you want a kind of $\epsilon$-$\delta$ proof?
Comment: @GreyFox Sure. If you have time for it, please do. Otherwise, if it's taking too much of your time, do you know a theorem that says something like my question?
Answer: The poster has clarified enough perhaps to understand what the difficulty is.
One problem that many students have with starting to study integration past a first calculus course is that there are too many integrals to contend with:

The Riemann integral.  Integrable functions are bounded and it is always proved that $F(x)=\int_a^x f(t)\,dt$ is continuous.

The Newton integral.  Integrable functions have to be derivatives, so $F'(x)=f(x)$ everywhere, $F(x)=\int_a^x f(t)\,dt$ and of course $F$ is continuous (it is differentiable).

The improper Riemann integral.  For  $f$ to be integrable in this sense on $[a,b]$ there has to be (i) a finite set $S\subset [a,b]$, and (ii) a
continuous function $F:[a,b]\to\mathbb R$ so that the Riemann integral
$F(d)-F(c) = \int_c^d f(t)\,dt$  if $[c,d]$ contains no point of the finite set $S$.
Then define $\int_a^b f(t)\,dt =F(b)-F(a).$

So continuity of $F$ is part of the definition.   [Usually your text describes it with limits, but that is the same thing.]

Continuous bounded functions.   If $f:[a,b]\to\mathbb R$ is continuous just on $(a,b)$ and $f$ is bounded then $f$ is Riemann integrable, back to case #1.

Continuous unbounded functions.   If $f:[a,b]\to\mathbb R$ is continuous just on $(a,b)$ and $f$ is unbounded then it is not Riemann integrable, but
might have an improper Riemann integral.  Usually that is defined by writing
$\lim_{u\to a+, v\to b-} \int_u^v f(t)\,dt$ but that is exactly the same thing as saying that there is a continuous function  $F$ as in #3.

Lebesgue integral.  This can be defined as $\int_a^b f(t)\,dt =F(b)-F(a)$ if there is an absolutely continuous function $F$ with $F'=f$ almost everywhere.  But absolutely continuous functions are continuous.

Denjoy-Perron integral.  This can be defined as $\int_a^b f(t)\,dt =F(b)-F(a)$ if there is an ACG${}_*$   function $F$ with $F'=f$ almost everywhere.  But ACG${}_*$ functions are continuous.

In short: for all of these integrals, the indefinite integral $F(x)=\int_a^x f(t)\,dt$  is always continuous.  So the question here is immediate.
You can  in every case claim that
$$\lim_{m\to\infty} \int_{a+\frac1m}^{b-\frac1m} f(t)\,dt = \int_a^b f(t)\,dt.$$
In fact if this is not true then the function is not integrable in any of these senses and you cannot write the expression $\int_a^b f(t)\,dt$ anyway.
You will, however,   encounter discontinuous indefinite integrals when you study the Riemann-Stieltjes integral $\int_a^b f(t)\,dg(t)$.

Postscript.
Problem (related maybe):  Does there exist a function $f:(0,1]\to\mathbb R$ that is continuous and for which the limit of the sequence
$$  \lim_{m\to\infty} \int_{\frac1m}^{1} f(t)\,dt $$
exists but for which
$$  \lim_{u\to 0+} \int_{u}^{1} f(t)\,dt $$
does not exist?  Such a function is not then integrable in the improper Riemann sense and so the integral  $  \int_{0}^{1} f(t)\,dt $ does not exist.
Answer: Yes.  Take $f(x) =\frac{d}{dx} \sin \frac{\pi}{x} $.  Observe
that $\int_{\frac1m}^{1} f(t)\,dt= \sin \pi - \sin m\pi = 0$
but
$$  \lim_{u\to0+} \int_{u}^{1} f(t)\,dt =  \lim_{u\to0+} \left[\sin \pi -  \sin \frac{\pi}{u}\right] $$
does not exist so $f$ is not integrable on $[0,1]$  (in the sense of the improper Riemann integral or any sense).
Answer: Since improper integral $$\int_{a}^{b} f(x)dx$$ exist it means that fixing a point $c\in (a,b)$ (for example $c= (a+b)/2$), then the following limits exists:
$$\lim_{t\to a^{+}}\int_{t}^{c}f(x)dx\quad \text{and}\quad \lim_{s\to b^{-}}\int_{c}^{s}f(x)dx,$$
and
$$\int_{a}^{b} f(x)dx = \lim_{t\to a^{+}}\int_{t}^{c}f(x)dx + \lim_{s\to b^{-}}\int_{c}^{s}f(x)dx.$$
In particular, for the sequence $t_{m} = a + \frac{1}{m}\to a^{+}$ and $s_{m}= b-\frac{1}{m}\to b^{-}$ we have:
$$\int_{a}^{b} f(x)dx = \lim_{t\to a^{+}}\int_{t}^{c}f(x)dx + \lim_{s\to b^{-}}\int_{c}^{s}f(x)dx.\\
\,\\
=\lim_{m\to \infty}\int_{t_{m}}^{c}f(x)dx + \lim_{m\to \infty}\int_{c}^{s_{m}}f(x)dx\\
\,\\
=\lim_{m\to \infty}\int_{t_{m}}^{c}f(x)dx + \int_{c}^{s_{m}}f(x)dx.$$
Since $[t_{m},s_{m}]\subset(a,b)$ holds for any $m$, we have that:
$$\lim_{m\to \infty}\int_{t_{m}}^{c}f(x)dx + \int_{c}^{s_{m}}f(x)dx = \lim_{m\to \infty}\int_{t_{m}}^{s_{m}}f(x)dx,$$
and grouping the equations and using the expression of $t_{m}$ and $s_{m}$, it follows that
$$\int_{a}^{b} f(x)dx = \lim_{m\to \infty}\int_{a-\frac{1}{m}}^{b+\frac{1}{m}}f(x)dx.$$
I hope it is clear for you.


followUserLocation prop not working for React Native MapView

Question: I'm very puzzled by a certain issue I'm having. I'm simulating a freeway drive, and I'm trying to follow the user location. By default this should already be on if showsUserLocation is true. That prop works. However the simulator is not centering on the user location as it moves. In my code below all the props work, except for the followUserLocation... what am I doing wrong?
<code>return (
  <View style={styles.container}>
    <MapView
      style={styles.map}
      showsUserLocation={true}
      followUserLocation={true}
      showsCompass={false}
    >
    </MapView>
  </View>
</code>
Answer: I think the flowUserLocation has been broken in react-native until the most recent release (0.19).  Now when I change the location in the Xcode debugger, the map will follow that location.
See comments on the release: https://github.com/facebook/react-native/releases
And this commit: https://github.com/facebook/react-native/commit/3d0ff69e40f0262e0ffc6f6023ec958b52eeb986


Wordpress Theme - Parse Error: Unexpected end of file

Question: Atualizei meu site Wordpress do PHP 5.2 para o PHP 7.0 e quando estou tentando restaurar este site para um novo host, estou recebendo um erro no meu tema personalizado:

Parse error: syntax error, unexpected end of file in /opt/bitnami/apps/wordpress/htdocs/wp
  -content/themes/insight/functions.php on line 125

Segue o código:
<?php

function register_my_menus() {
  register_nav_menus(
    array( 'top-menu' => __( 'Menu Topo' ), 'bottom-menu' => __( 'Menu Inferior' ))
  );
}
add_action( 'init', 'register_my_menus' );

if ( function_exists( 'add_theme_support' ) ) {
  add_theme_support( 'post-thumbnails' );

}

if(function_exists('add_theme_support')) {

   add_image_size( 'sobre', 550, 210, true );

   add_image_size( 'clientes', 180, 150, true );

}

function wpprogrammer_post_name_in_body_class( $classes ){
    if( is_singular() )
    {
        global $post;
        array_push( $classes, "{$post->post_type}-{$post->post_name}" );
    }
    return $classes;

}
function add_category_to_single($classes) {
    if (is_single() ) {
        global $post;
        foreach((get_the_category($post->ID)) as $category) {

            $classes[] = "category-".$category->category_nicename;
        }
    }

    return $classes;

}
add_filter('body_class','add_category_to_single');
add_filter( 'body_class', 'wpprogrammer_post_name_in_body_class' );

add_custom_background();

register_sidebar();

function nerdy_get_images($size = 'thumbnail', $limit = '0', $offset = '0', $gallery_id = 'footer') {
    global $post;
    $images = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID') );
    if ($images) {
        $num_of_images = count($images);
        if ($offset > 0) : $start = $offset--; else : $start = 0; endif;
        if ($limit > 0) : $stop = $limit+$start; else : $stop = $num_of_images; endif;
        $i = 0;
        foreach ($images as $image) {
            if ($start <= $i and $i < $stop) {
            $img_title = $image->post_title;
            $img_description = $image->post_content;
            $img_caption = $image->post_excerpt;
            $img_url = wp_get_attachment_url($image->ID);
            $preview_array = image_downsize( $image->ID, $size );
            $img_preview = $preview_array[0];
            ?>

                <img src="<?php echo $img_preview; ?>" alt="<?php echo $img_caption; ?>" title="<?php echo $img_title; ?>">

            <?
            endif;
            }
            $i++;
        }
    }
}

add_action('init', 'creat_post_cliente');

function creat_post_cliente()
{
    register_taxonomy_for_object_type('category', 'cliente');
    register_taxonomy_for_object_type('post_tag', 'cliente');
    register_post_type('cliente',
        array(
        'labels' => array(
            'name' => __('Cliente', 'cliente'),
            'singular_name' => __('cliente Custom Post', 'cliente'),
            'add_new' => __('Adicionar nova cliente', 'cliente'),
            'add_new_item' => __('Adicionar nova cliente', 'cliente'),
            'edit' => __('Edit', 'cliente'),
            'edit_item' => __('Edit cliente', 'cliente'),
            'new_item' => __('New cliente', 'cliente'),
            'view' => __('View cliente', 'cliente'),
            'view_item' => __('View cliente', 'cliente'),
            'search_items' => __('Search cliente', 'cliente'),
            'not_found' => __('No cliente found', 'cliente'),
            'not_found_in_trash' => __('No cliente found in Trash', 'cliente')
        ),
        'public' => true,
        'hierarchical' => true,
        'has_archive' => true,
        'supports' => array(
            'title',
            'editor',

            'thumbnail'
        ),
        'can_export' => true,
        'taxonomies' => array(
            'category'
        )

    );

} ?php>

Answer: Isso é erro de digitação, não existe tag de fechamento assim no PHP:
?php>

Em PHP você deve usar:
?>

Ou como é um script sem HTML, só para as funções, você pode omitir o ?>, ou seja nem fechar.