Setting up two sites on the same IP machine

Question: I have CentOS 8
I installed LAMP, Varnish, etc.
I setup hosts
/etc/hosts
ip site1.com www.site1.com ip site2.com www.site2.com

I setup Apache like this:
/etc/httpd.conf to include sites-enabled/

I have sites-enabled and sites-available with two configurations, site1.com.conf and site2.com.conf
Here what I included in etc/httpd/conf/httpd.conf
Include conf.modules.d/*.conf

and
IncludeOptional sites-enabled/*.conf

Still it is not working.  Any idea how to fix this?
What i put in site1.com.conf example:
<VirtualHost *:8080>
    ServerName site1.com
    ServerAlias www.site1.com
    DocumentRoot /var/www/site1.com/html
    ErrorLog /var/www/site1.com/html/log/error.log
    CustomLog /var/www/site1.com/html/log/requests.log combined
</VirtualHost>

I manage to get this to work now but the https versions are not working
Can you help guide me how to fix the https versions ?
Thanks
Edit:.
I fixed.
Problem was IncludeOptional conf.d/*.conf was not in httpd.conf
Comment: What do you mean by "not working" exactly? Does literally "nothing" happen? _Something_ must happen... does it not resolve, do you get an error?
Comment: I manage to get site2.com to work problem is when i put http://ip_adress i want him to go to site1.com which is hosted external I try with Redirects but nop working
Comment: Why are you using port 8080 while referring to https sites without a port specified?  https assumes port 443. Also, you need sslcertificate related lines lines and a "SSLEngine on" directive per virtualhost.
Comment: I made the ssl certificates and changed in ssl.conf where exacty i should put sslengine on also ?
Answer: Place the following in your httpd.conf then restart the service.
NameVirtualHost *:8080

<VirtualHost *:8080>
     ServerName site1.com
     ServerAlias www.site1.com
     DocumentRoot /var/www/site1
</VirtualHost>

<VirtualHost *:8080>
     ServerName site2.com
     ServerAlias www.site2.com
     DocumentRoot /var/www/site2
</VirtualHost>

Reference
Comment: i put and restart but nothing should i delete all the httpd.conf extra files i put this data NameVirtualHost right after Include conf.modules.d/*.conf in http.conf should i delete rest modify ?
Comment: @Wed reset your configs to default, then add the `NameVirtualHost` and `VirtualHost` segments.
Comment: i tried that and yum reinstall apache but httpd.conf remain the same
Comment: @Wed run `yum remove apache` and make sure the config files are gone, if not then manually delete them. Then install apache again. Unfortunately, unlike `apt`, `yum` does not have a `purge` feature.
Comment: ok but how I get https://host_ip to redirect to external site and my site www.site2.com to /var/www/site2.com/html ?
Comment: You create a new new `VirtualHost` entry where the `ServerName` is your IP address and use the `Redirect` options to send clients to the specified external site. You can find out more about this by googling `VirtualHost permanent redirect`.
Comment: the https versions don't work how i fix that ? i made the ssl certificates but what to do ?
Comment: @Wed You will have to enable some SSL specific options for it to work. Please use google before asking all these follow up questions. You can easily find how to do this by googling `apache virtualhost ssl config`.
Comment: @MrWhite It's a very hacky way to reset the configs but based on OPs apparent knowledge about webservers I figured it's the easiest way to reset.
Comment: ok and how i get the ssl versions of this site work but https://ip and https://site2.com ?
Comment: @Wed refer to my last comment
Comment: i fixed nevermind i fixed is there a problem now @MrWhite that I yum reinstall httpd ?  I managed to fix my issues but worry about the yum reinstall httpd any problem that may cause ?


Data Transmission Stop from Raspberry Pi

Question: I am trying to establish a communication b/w raspberrypi(Raspbian) and PC(Microsoft XP) through GPIO PINS 14(Tx) and 15(Rx) for sending/receiving data... , RS-232 level converter is using for connection of GPIO to PC serial COM port and Voltage conversion from 3.3V to 12V...
I install minicom (Echo ON) at raspberry side and install Teraterm(ECHO OFF) at PC side.
Whatever I typed on minicom, it successfully appear on Minicom and Teraterm but when I tried same thing on Teraterm, it only appears on Teraterm not on minicom and also blocked by minicom (/dev/ttyAMA0). After that I am not able to send data from minicom to Teraterm.
But I just check one thing more and very surprise that, when shorting GPIO PIN 14& 15 together and starting typing on minicom... it just show me one character and stop after that...
Again I repeat whole process by closing/opening minicom, again it just show character and then stop.
Can you plz guide me why it happening and how do I resolve it?
Answer: I just read from this link that someone was also facing your kind of problem but not exactly what you are facing.
It is happened because Kernel takeover the control on console so It is good and very important to disconnect the connect of console and kernal from the startup.
Now you can follow these step, I am sure you will get rid from this trouble...
Start editing this file by this command
sudo vi /boot/cmdline.txt

Originally it contained:
dwc_otg.lpm_enable=0 rpitestmode=1 console=ttyAMA0,115200 kgdboc=ttyAMA0,115200 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 rootwait

deleted the two parameters involving the serial port (ttyAMA0) to get the following:
dwc_otg.lpm_enable=0 rpitestmode=1 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 rootwait

rebooted (sudo reboot) to confirm that kernel output was no longer going to the serial port. But the serial console was still available. So edited /etc/inittab:
sudo vi /etc/inittab

commented out the following line:
2:23:respawn:/sbin/getty -L ttyAMA0 9600 vt100

Finally, rebooted again and confirmed that nothing was touching the serial port anymore. Then, to test it out installed minicom on the Raspberry Pi:
sudo apt-get install minicom

And ran it:
minicom -b 9600 -o -D /dev/ttyAMA0

After, it is able to send data in both directions!


Checking items in a list against a pyspark RDD

Question: I have the following pyspark RDD with Ids and their counts:
rdd = [('12', 560), ('34', 900), ('56', 800), ('78', 100), ('910', 220), ('125', 410), ('111', 41), etc.]

And I have a regular list:
id_list = ['12', '125', '78']

I want a new list of key, value pairs of 'id' from id_list and 'counts' from rdd.
So expected output:
new_list = [('12', 560), ('125', 410), ('78', 100)]

If rdd was a python dictionary, I could loop over the id_list, check to see if it's in the dictionary and return a new list with key and counts. But I'm lost on how I could do this with an RDD. Please advise.
I could potentially try to convert the RDD into a dictionary but that would defeat the purpose of using spark.
Answer: You can filter the RDD using a lambda function which checks if the key is in id_list:
rdd2 = rdd.filter(lambda x: x[0] in id_list)


Comparing the cardinality of sets

Question: An exercise is the following:
Compare the cardinality of the following sets:

The class of all real numbers $\mathbb{R} =: A$
The class of all polynomials $\mathbb{R}[X] =: B$
The class of all real functions $f:\mathbb{R} \to \{0,1\} =: C$
...

The hint is to use the Cantor-Schröder-Bernstein-Theorem. Is it also possible to show that two sets $A,B$ satisfy $|A| \leq |B|$ and $|A| \neq |B|$? Obviously there is a injective function $f: A \to B$. But if you could show that there is no injective function $f: B \to A$ would that imply $|A| \neq |B|$ ?
Comment: Do you know what $|A|\neq|B|$ means?
Comment: You should probably find that out before attempting this question then.
Comment: Probably not ...
Answer: Sure. $|B|\leq |A|$ means that there exists an injective function $f:B\to A$.
If you can prove that there is no injective function $f:B\to A$ then $|B|\not\leq |A|$, in particular $|B|\neq|A|$
Answer: Of course if you could show that there is no injection from $B$ to $A$, then it it would also mean that there is no bijection from $B$ to $A$, so $|A|$ wouldn't be equal to $|B|$.
Still, it is not the case in your problem. Here is a hint about sets $A$ and $B$: prove that $|\mathbb{R}^n| = |\mathbb{R}|$. Then think how to use this knowledge about $\mathbb{R}^n$ to analyze $\mathbb{R}[x]$.
As for $C$, I would suggest looking at Cantor's diagonal argument.
Answer: Yes, it would. If $A$ and $B$ had the same cardinality, there would by definition by a bijection (and therefore an injection) $f:B\to A$. It follows immediately that if there is no such injection, then $|A|\ne|B|$.
Thus, if you have an injection from $A$ to $B$, then either there is an injection from $B$ to $A$, in which case $|A|=|B|$ by the Cantor-Schröder-Bernstein theorem, or there is no injection from $B$ to $A$, in which case $|A|<|B|$.
In your specific problem there are fairly obvious injections from $A$ to $B$ and to $C$. It is possible to find an injection from $B$ to $A$ directly, but that is not how I would approach the problem. I would (1) note that for each $n$ there is a bijection between the polynomials of degree $n$ and $\Bbb R^{n+1}$; (2) find a bijection between $\Bbb R$ and $\Bbb R^2$; (3) show by induction that $|\Bbb R^n|=|\Bbb R|$ for $n\in\Bbb Z^+$; and (4) use this to show that $|B|=|\Bbb N\times\Bbb R|=|\Bbb R|$. Depending on how much I had already proved about cardinalities, I could skip some of these steps.
I would not that there is an easy bijection between $C$ and $\wp(\Bbb R)$ and apply Cantor's theorem to deal with $C$.
Comment: @joachim: It's sufficient to find one from $(0,1)^2$ to $(0,1)$. Try $$\langle 0.a_1a_2a_3\dots,0.b_1,b_2b_3\dots\rangle\mapsto\langle0.a_1b_1a_2b_2a_3b_3\dots\rangle\;.$$ If you get completely stuck, take a look at [this answer](http://math.stackexchange.com/a/183383/12042), which even shows how to get a bijection.
Comment: Can you give me a hint for a injective function from $\mathbb{R}^2$ to $\mathbb{R}$?
Answer: If you can show that there is no injective function $X\to Y$ and you already know there is an injection $Y\to X$ then you can conclude that $|Y|\leq|X|$ and $|Y|\neq|X|$. Or in short, $|Y|<|X|$.
You could in fact prove that for $A$ and $C$, Cantor's theorem comes to mind.
As for $A$ and $B$, as you say there is an obvious injection $A\to B$, but there is indeed an injection from $B$ to $A$.
Note that $|A|=2^{\aleph_0}$; and $|B|=|\bigcup_{n=1}^\infty\mathbb R^n|\leq(2^{\aleph_0})^{\aleph_0}$, using basic cardinal arithmetics one can deduce the wanted equality.

Comparing the cardinality of sets


Is $A_4 \times \mathbb{Z}_3$ isomorphic to $S_3 \times S_3$?

Question:
Ιs $A_4 \times \mathbb{Z}_3$ isomorphic to $S_3 \times S_3$?

I am trying to find an element of $S_3 \times S_3$ which has an order, let's say  $a$, and $A_4 \times \mathbb{Z}_3$ has no element of such order.
Comment: You could count the elements of order $3$.
Comment: Both groups have elements of orders $1$, $2$, $3$ and $6$.
Comment: Can $S_3\times S_3$ have a normal subgroup isomorphic to $A_4$?
Answer: In $S_3\times S_3$ there are

$1$ element of order $1$
$\color{red}{15}$ elements of order $2$, $(\tau_1,e),(e,\tau_2),(\tau_1,\tau_2)$
$8$ elements of order $3$
$12$ elements of order $6$

while in $A_4\times\mathbb{Z}_3$ there are

$1$ element of order $1$
$\color{red}{3}$ elements of order $2$, $(\tau_1 \tau_2,e)$
$26$ elements of order $3$
$6$ elements of order $6$

so the easiest way to state $S_3\times S_3 \not\simeq A_4\times\mathbb{Z}_3$ is probably to compare the number of involutions (elements with order $2$) in both groups. Or wonder about the largest abelian subgroups, which in the former case are isomorphic to $\mathbb{Z}_3\times\mathbb{Z}_3$ and in the latter case are isomorphic to $\mathbb{Z}_2\times\mathbb{Z}_2\times\mathbb{Z}_3$.
Comment: @user26857: you're right, answer fixed.
Comment: $A_4$ contains only 3 elements of order two. I actually found 3 elements of order two, 26 of order three, and 6 of order six in $A_4\times\mathbb{Z}_3$.
Answer: You could use the following useful facts.

Given $A$ and $B$ groups, $Z(A \times B) = Z(A) \times Z(B)$.
$Z(S_n)=\lbrace id \rbrace$ for all $n \geq 3$.


Hide the http:// in web browsers

Question: The "http://" prefix to regular consumer websites is unnecessary and only complicates. Anyways 99% of the sites people visit use the HTTP protocol, so why do you have to tell the browser that? It should guess it!
I want to hide the "http://" prefix everywhere, in the address/location bar URL, on Hyperlink tips, in the status bar, basically everywhere in a browser.
Any Firefox Add-on to do this? Any other way for another browser?
Comment: @hmemcpy's answer indicates that this can be done, but why?
Comment: Where do you want to hide it? In the browser address bar, or somewhere else? And as others have pointed out, you don't have to tell the browser that so it's not entirely clear what you're after here.
Comment: "why do you have to tell the browser that" <--- you don't. All modern browsers will assume http:// if you do not explicitly type it. Like everyone else, I'm not entirely sure what your reason is for wanting to do this. I don't see what you could gain from it.
Answer: There is a great add-on for Firefox called Locationbar² that does just what you want (and some!). One of its main features is to break the URL into breadcrumbs.
In the options dialog you can specify what protocols you'd like to hide:

Here is what mine looks like:
Comment: Well... yeah :) But now I'd like to ask as well, why do you want to have it disappear completely?
Comment: There's just one problem. The hidden protocols reappear when editing and on rollover. So its not totally invisible :)
Answer: The HTTP:// string is not a prefix of the URL, it's part of the URL. Which is why you can't (and shouldn't) hide it, since the application is displaying the URL.
Answer: 99% might use the HTTP protocol, but there's a lot more than 1% that use HTTP over TLS (ie HTTPS) and they're on different ports, so the browser needs to know which port to open.
Also, the browser does guess it.
Comment: I know this, I wanted a way to HIDE the http:// prefix if that was in the current URL.
Comment: So, you want to control the display of the http:// prefix in the address bar of the users browser ?
Comment: Exactly. Hide it. Permanently, unless the current URL is not using the HTTP protocol.
Comment: In the case of HTTPS, it could just display a lock icon someplace.
Comment: @Jenko: for https i'd like that browsers shows "https" and not only a lock. the lock can be spoofed by a favicon.
Answer: Google Chrome 6 now does precisely what you asked for.  It was released yesterday (2 September 2010).
Answer: Most browser do guess at it. If you enter an address without HTTP:// prefix it will add it on for you.
It would be a browser feature to hide this, and as far as I know, no browsers offer this.
Comment: I know this, I wanted a way to HIDE the http:// prefix if that was in the current URL.
Answer: There is no way to do this, that I know of, on any of the modern browsers.
Comment: Richard, I think Jeremy is after a client-side setting for this. For example, with Google Chrome, http is displayed grey, whilst https is displayed green (or red) - I think he wants to take this a step further and simply only show non-HTTP protocols (and possibly using an icon rather than the code/abbr).
Comment: What a pity! Wish someone would write a Firefox addon to do just that! It would be the most popular addon of all time and they might just consider implementing it into the browser.
Comment: This is a GOOD THING. The ability for web sites to change what is appearing in the address bar would just make phishing so much easier.
Comment: @Peter: Exactly!
Answer: I'm guessing you're thinking something like the iPhone css tricks which scroll the page down a dozen pixels to obscure the url header.
This is not possible with any browser that is currently shipping, even if it was, you wouldn't be able to control that setting via the javascript DOM.
The closest I can think is with a javascript driven popup, which can suggest to the browser that it should hide the url bar. However popups are very much out of vogue.
Comment: ... and newer browsers ignore the hide address bar in popup option to avoid phishing and other attacks.
Comment: Exactly, so that technique is unlikely to be effective.
Answer: If you're unhappy with the browsers out there, roll your own.  Firefox and Chrome are both open-source, so most of the work is already done for you.
Comment: Wouldn't count this as helpful.
Comment: I'm not saying it to be an ass; I'm saying it in case he legitimately hasn't considered it.
Answer: My vote is definitely for the new Google Chrome.  It will hide the "http://"; however, show https, ftp or any other protocol that you feed it.
Comment: Please add comments to specific questions. This is not a forum; please use the answer button only to Answer the initial Question. Thank you.
Answer: Just thought I'd add that Firefox 7 now does this by default also -- though it's still in beta.

Hide the http:// in web browsers


drupal_add_js(), script not executed

Question: I try to include a simple script (below) and cant get it to work.
(function ($) {
  Drupal.behaviors.myModuleBehavior = function (context) {
    alert('say something pretty please');
  }
})(jQuery);

The script is added within a hook_form_alter function
drupal_add_js(drupal_get_path('module', 'my_module') . '/js/my_module_form.js', 'file');

Up to here, no issues. I see the script is added to the long line of js:extends with the correct path. Thus I would expect to receive an alert... but nothing happens.
As I've run out of things to check for and consulted docs, google and this site, only to find that the code should work, is anyone able to point out what might be wrong here?
Answer: I believe the = function (context) bit needs to include the attach:
(function ($) {
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {
      alert('say something pretty please');
    }
  };
})(jQuery);

drupal_add_js(), script not executed


How do I make piano sound kind of like it is in a room and sad?

Question: Like the beginning of this video:

and this video:

I learned these two pieces, but they don't really sound like this. I mean I know I'm not that good at piano yet, but it just doesn't sound like this at all.
Comment: Are you sure you have an accurate transcription?  Are you using the sustain pedal?
Comment: Actually It might just be reverb now that I think about it
Answer: Sad pianos are hard to find! The left hand accompaniment sounds to me like a normal piano, whereas the right hand tune has a lot of reverb, and perhaps some extra sparkle, due to enhanced eq.
Answer: I don't find the renditions here particularly sad.  The second one can be called "solemn".  At any rate, there is a solid amount of reverb added to both recordings to make that "like it is in a room" effect.  That's a post-processing effect.
Putting "sad" into technical instructions for play is somewhat danger-fraught since it is, like many other things, a subtle and organic combination of a lot of components that sound artificial or exaggerated or out of place when done with intent.  It's like trying to follow instructions for "how to I make a sad voice?"
First of all, to put in expressiveness, you need to have mastered the piece to a degree where you are in full control of its execution and have mental capacity to spare to listen to yourself rather than wasting it all on playing.  It needs to express your sadness and make or carry your sadness.  If it doesn't, you are basically asking how to move people to tears by reading off a poem phonetically in a language you don't speak.  Any advice will be quite ad-hoc and not achieve all that impressive results, but there might still be some point to some of it nevertheless.
That being said, there is pedaling technique in order to achieve a certain tranquility and have the notes fall like raindrops in a void without mushing too much over or having too lyric legato lines.  The piano is somewhat thankful in that regard compared to instruments like organ since it achieves that semiautomatically for melodic stuff in higher registers and moderate speed but indeed that's one category where a grand piano has a marked advantage over its more compact upright colleagues.
Then there is some slight hesitation to "strong" notes like chords and/or on-beat notes that one can work in but for that not to be overdone while still having an effect, one already needs a very solid and dependable basic speed and consistent articulation.  Maintaining a basic piano dynamic while still setting some accents in moderation is also advisable.
But the main thing is that you need not as much deliver a rendition of sadness as an expression of it.  And for that, you need to be in control of the instrument and the piece and its notes to a degree where you actually have time to feel sad and have that sadness go into the notes.
Comment: Great first answer; welcome to the site!
Answer: (I listened to the second selection.)  There's no decay.  It sounds like an electric keyboard, not a piano.  There's a harp-like quality to the timbre.


Unbounded subsets of ordinals with countable confinality

Question: Let $\alpha$ and $\beta$ be limit ordinals such that $\alpha > \beta$ and $cf (\beta) > cf(\alpha) = \omega$. It is not true that we can always find an unbounded subset of $\alpha$ with order type $\beta$: For an uncountable successor cardinal $\kappa$ we can find a counterexample by setting  $\alpha = \kappa + \omega$ and $\beta = \kappa$.
But is it possible to find other values for  $\alpha$ and $\beta$, such that there is  an unbounded subset of $\alpha$ with order type $\beta$?
Answer: No: if $S\subset\alpha$ is an unbounded subset with order type $\gamma$, then always $cf(\alpha)=cf(\gamma)$.  The inequality $cf(\alpha)\leq cf(\gamma)$ is trivial, since any unbounded sequence in $S$ is an unbounded sequence in $\alpha$.  For the converse, let $\kappa=cf(\alpha)$ and $f:\kappa\to\alpha$ be strictly increasing and unbounded.  For each $\xi<\kappa$, let $g(\xi)$ be the least element of $S$ which is greater than or equal to $f(\xi)$.  Then $g:\kappa\to S$ is nonstrictly increasing and unbounded.  Letting $A\subset\kappa$ be the set of $\xi$ such that $g(\xi)>g(\theta)$ for all $\theta<\xi$, $g:A\to S$ is strictly increasing and unbounded.  Since $A$ has order-type at most $\kappa$, this proves that $cf(\gamma)=cf(S)\leq \kappa=cf(\alpha)$.


How can i align a icon vertically, when using it in a richText flutter

Question: i am trying to create a simple gesture detector, with some text, and an icon in the start, but i seem to hit a wall when trying to center the icon (yes a row have been tried, but i need something where the width does not go beyond the content withing), here is what i have so far:
<code>Container(
            color: Colors.white,
            child: GestureDetector(
                onTap: () => setState(() {
                      playerNames.remove(name);
                    }),
                child: RichText(
                  text: TextSpan(children: [
                    WidgetSpan(
                      child: Icon(
                        Icons.clear,
                        size: MediaQuery.of(context).size.height * 0.02,
                      ),
                    ),
                    WidgetSpan(
                      child: AutoSizeText(
                        name,
                        maxLines: 1,
                        style: new TextStyle(
                            fontSize:
                                MediaQuery.of(context).size.height * 0.021,
                            color: Color.fromRGBO(0, 0, 0, 0.71)),
                      ),
                    )
                  ]),
                )),
          )
</code>
Answer: Try InlineSpan inside TextSpan
<code>       TextSpan(
            style: TextStyle(fontSize: 24, color: Colors.black),
            children: <InlineSpan>[
              TextSpan(text: 'hello'),
              WidgetSpan(
                alignment: ui.PlaceholderAlignment.middle,
                child: Text( 'Jack',
                    style: TextStyle(fontSize: 40, color: Colors.white),
                ),
              ),
              TextSpan(text: ' doctor'),
            ]
        ),
</code>
Comment: or like most people do, just remove the "ui." and just write PlaceholderAlignment.middle
Comment: There is library dart:ui, a imported it as ui
In nutshell, import "dart:ui" as ui
Comment: who is this ui ? used on alignment I had an issue there


Example of a convex function which goes to $0$ at infinity and behaves like $-1/|x|$ in the origin

Question: I am trying to find an example of a real valued function $f\in C^1(\mathbb{R}\setminus \{0\})$ such that:

in a neighborhood of the origin it behaves like
$$g(x) = -\frac{1}{|x|};$$

$$\displaystyle\lim_{|x|\to\infty} f(x)=0;$$

it is convex "as $|x|\to\infty$, i.e. it is convex at infinity.

I was thinking thinking to consider exactly $g(x) = -\frac{1}{|x|}$, but I realized that actually it is concave.
Could someone please show me an example of such a function?
Thank you in advance.
Comment: Such a function does not exist: The graph of a convex function lies above any of its tangents, so that $\lim_{x \to 0} f(x) = -\infty$ is not possible.
Comment: pick your favorite function that satisfies $2,3$ and use a smooth function with compact support to join it with $-1/|x|$ at some point on the positive real axis
Comment: @MartinR and which is at least "convex as $|x|\to\infty$? I edit the question.
Comment: What about $\min(2-1/x, 1/x)$ for $x > 0$ (with small modifications to make it differentable)? You simply "stitch" two functions with the desired behaviour for $x \to 0$ and $x \to \infty$ together.
Comment: @MartinR thank you for your comment. If I want to move the connecting point to the right? I mean, I would have not exactly (1, 1) but a point further to the right. Thank you in advance.
Answer: Consider the function $f(x)=\frac{\ln(|x|)}{|x|}$.
Clearly $\lim_{x \to 0}f = -\infty$ so it behaves like $-\frac{1}{|x|}$ near $0$. Also, $$\frac{d^2}{dx^2} f = \frac{2 \ln \! \left({| x |}\right)-3}{{| x |}^{3}}>0 \implies x\in\left\{\left(-\infty , -{\mathrm e}^{\frac{3}{2}}\right),
\left({\mathrm e}^{\frac{3}{2}}, \infty \right)\right\}$$
we also have:
$\frac{d}{dx}f = \frac{1-\ln \left({| x |}\right)}{{| x |} x}<0 \implies x\in\{\left(-{\mathrm e}, 0\right), \left({\mathrm e}, \infty \right)\}$. Therefore if $|x| > \mathrm e^{\frac{3}{2}}$, the function becomes convex. Finally, $\lim_{|x|\to\infty}f = 0$. Hope I didn't miss anything.
Comment: @C.Bishop, I'd reckon that shouldn't be possible. See if you're starting with a convex function with a positive first derivative at some point $x=a$, then $f$ is momentarily increasing at $x=a$. Eventually you want it to decrease down to 0 though, which means there the function will attain the value $f(a)$ again at some point greater than $a$, say at $x=b$. Now Rolle's theorem tells you that the secant connecting $(a,f(a))$ and $(b,f(a))$ is actually beneath the function, i.e the function isn't convex.
Comment: @C.Bishop, I think an easier way to see this is as follows: Suppose $f$ is convex for all $x\geq a$ and $D_x(f)(a)>0$, then we need $f'(b)\geq f'(a) > 0$ for all $b>a$. This means the function is strictly increasing over $x\geq a$ which means it can never asymptote to $0$.
Comment: Sam, I am going to accept your answer. But do you think your example could be modified in such a way that the first derivative of $f$ is positive (at least briefly) in the part in which it is convex?
Comment: If you want to answer, here is my new question. Thank you in advance. https://math.stackexchange.com/questions/4593163/example-of-a-convex-function-at-infinity-which-goes-to-0-at-infinity-behaves-li
Answer: Consider the function
$$
  f(x) = -\frac{1}{|x|} + \frac{2}{1+|x|}.
$$
As $x\to 0$, the term $\frac{2}{1+|x|} \to 2$, so $f(x)$ behaves like $-\frac 1 {|x|}$ near $0$. Clearly as $f(x)\to 0$ $|x|\to \infty$. It remains to show that $f(x)$ is convex for $|x|$ large enough. Intuitively, the terms  $-\frac{1}{|x|}$ and $\frac{1}{1+|x|}$ approximately cancel each other as $|x|\to \infty$, but the later one, which is convex (on $(-\infty,0)$ and $(0,\infty)$) is multiplied by two, so it dominates the other one. For an exact proof, take derivate of $f(x)$ at $x>0$ (the convexity for $x\to-\infty$ follows the fact that the function is even):
$$
  f'(x) = \frac{1}{x^2} - \frac{2}{(1+x)^2},
$$
and
$$
  f''(x) = -\frac{2}{x^3} + \frac{4}{(1+x)^3},
$$
which is positive for $x$ large enough.


Why does my item-list not work in Vue.js?

Question: I tried to create my first Vue.js app on my own and therefore relied on the documentation. But there is an error I can not solve. I tried to rebuild the app like in the documentation and made some mistake. The list doesn't display the items and it doesn't add new items to the list. I would be grateful if anyone could give me any advice.
Yours
 Vue.component('workout-item', {
    template: '\

\
        {{ title }}\
        {{ workoutGoal }}\
        {{ workoutDone }} \
        <button v-on:click="$emit(\'remove\')">Remove</button>\

\
    ',
    props: {
        title: String,
        workOutGoal: Number,
        workoutDone: Number
    }
  })

  new Vue({
    el: '#workout-list-example',
    data: {
        newWorkoutText: '',
        newWorkoutGoal: '',
        newWorkoutDone: '',
        workouts: [
            {
                id: 1,
                title: 'Sit-ups',
                workoutGoal: 10,
                workoutDone: 0,
            },
            {
                id: 2,
                title: 'Crunches',
                workoutGoal: 15,
                workoutDone: 0,
            },
            {
                id: 3,
                title: 'Lift-ups',
                workoutGoal: 16,
                workoutDone: 0,
            }
        ],
        nextWorkoutId: 4
    },
    methods: {
        addNewWorkout: function() {
            this.workouts.push({
                id: this.nextWorkoutId++,
                title: this.newWorkoutText,
                workoutGoal: this.newWorkoutGoal,
                workoutDone: this.newWorkoutDone

            })
            this.newWorkoutText=''
            this.newWorkoutGoal=''
            this.newWorkoutDone=''
        }
    }
})

    <form v-on:submit.prevent="addNewBook">
        Add a Book
        <input
        v-model="newBookText"
        id="new-book"
        placeholder="E.g. Three women"
        >

        <button>Append</button>
    </form>

    <form v-on:submit.prevent="addNewWorkout">
        Add a workout
        <input
            v-model="newWorkoutText"
            id="new-workout"
            placeholder="E.g. Push-ups"
        >
        <input
            v-model="newWorkoutGoal"
            id="new-workout"
            placeholder="E.g. 10"
        >
        <input
            v-model="newWorkoutDone"
            id="new-workout"
            placeholder="E.g. 5"
        >
        <button>Append</button>
    </form>

Answer: There is a prop's name mistake for workoutGoal into your props declaration code (it's case sensitive).
(I will ignore the div for the book list here)
props: {
  title: String,
  workOutGoal: Number,
  workoutDone: Number
}

Should be:
props: {
  title: String,
  workoutGoal: Number, // lowercase on 'Out'
  workoutDone: Number
}

Then to use your props, you should use "kebab-case" (hyphen separator). For e.g: myLovelyProp is bound as my-lovely-prop (https://v2.vuejs.org/v2/guide/components-props.html):

Should be:

Finally, do not forget to cast your workout goal and workout done inputs to Number. Since you get it like a string from the field, to match your prop's types:
addNewWorkout: function() {
   this.workouts.push({
   ...
   workoutGoal: Number(this.newWorkoutGoal), // Cast string to number value.
   workoutDone: Number(this.newWorkoutDone)  // Cast string to number value.
})

Comment: Thank you very much


How does one define improper integrals using Darboux sums?

Question:
Q: How does one define improper integrals using Darboux sums?

In my Real Analysis course we defined the Riemann Integral using Darboux sums for functions defined on closed intervals in $\mathbb{R}$. How does one extend this definition to define improper integrals?
Answer: For improper integrals, the function is not necesseraly bounded. So you cannot define neither lower Darboux sums, nor the uppers.


Dynamic array with struct that contains a union in C

Question: I'm kind of new to C, so please bear with me.
I have a struct that contains union of other structs with variable sizes like this:
typedef struct _obj_struct {
    struct_type type;
    union obj {
        struct1 s1;
        struct2 s2;
        struct3 s3;
    } s_obj;
} obj_struct;

typedef struct _t_struct {
    unsigned int number_of_obj;
    obj_struct* objs;
    other_struct os;
    unsigned int loop;
} t_struct;

The struct_type is the type of the struct we use in the union.
How do I go through all elements in the objs?
Is this the right way to do this:
struct1 s1;
struct2 s2;
struct3 s3;

for (j=0; j<t_struct.number_of_obj; j++)
{
    switch (t_struct.obj[j].type) {
        case STRUCT1:
            s1 = t_struct.objs[j].s_obj.s1;
            break;
        case STRUCT2:
            s2 = t_struct.objs[j].s_obj.s2;
            break;
    }
}

Comment: very confusing: you have to defined `STRUCT1` and `STRUCT2` then you can use
Comment: You'd probably need to have a case for STRUCT3 using `s3 = t_struct.obj[j].s_obj.s3;`, presumably.
Answer: The t_struct.obj[j].s_obj is the union, not the actual structure. You have to use t_struct.obj[j].s_obj.s1 etc.
Comment: Yes, I misplaced that when I copied the code. Already fixed, Thanks.
Answer: Unless you need the copy of each structure, use pointers instead:
struct1 *s1;
// ...
s1 = &t_struct.objs[j].s_obj.s1;

Please note, that you have to specify an element of the union as well.
Answer: While accessing a member of union contained inside a struct, the general syntax is
structVariable.unionVariable.memberName

The way you're accessing is fine if you just add the member name at the end. So the correct version would be:
switch (t_struct.objs[j].type) {
    case STRUCT1:
        s1 = t_struct.objs[j].s_obj.s1;
        break;
    case STRUCT2:
        s2 = t_struct.objs[j].s_obj.s2;
        break;
}


Random image in Google slides

Question: How could I insert a random image into Google Slides? like if I use a link, that always leads to a random image, to where I don't even know what the image will be once I present. -Thanks
(This link can be used to go to a random picture: https://source.unsplash.com/random/300x200)
Comment: I have to apologize for my poor English skill. Unfortunately, I cannot understand your question from `How could I insert a random image into Google Slides? like if I use a link, that always leads to a random image, to where I don't even know what the image will be once I present.`. Can I ask you about the detail of your question?
Comment: Thank you for the response. This is not much coding, it is just a small problem. I just would like to know how to "enter an image onto Google Slides, that changes every time you present the slide." (changes to a random image.)
Comment: Thank you for replying. I have to apologize for my poor English skill. Unfortunately, I cannot understand `that changes every time you present the slide.`. In your situation, when the Google Slides is opened, you want to change the image? Can I ask you about the detail of it?
Comment: Yes, exactly. Every time I open the link to the slides, I want the image to change to a completely random image, from anywhere on the internet.
Comment: Thank you for replying. In order to achieve your goal, it is required to retrieve the 1st slide and the image from the URL. In this case, the OnOpen of simple trigger cannot be used. And also, unfortunately, in the current stage, Google Slides cannot use the OnOpen of the installable trigger. By this, I think that in the current stage, your goal cannot be directly achieved. I apologize for this.
Comment: That's okay, it was just something I saw going to set up for me and my friends, therefore, it's not too important, thank you!
Answer: As @Tanaike commented you cannot access a resource that needs authorization using Simple Triggers.

They cannot access services that require authorization.

onOpen(e) Simple Trigger pointing to "https://www.googleapis.com/auth/script.external_request" scope in this case
As a workaround you could change the images every day, using a Time Driven Installable Trigger.
Code.gs
function changeImage() {
  let slideP = SlidesApp.getActivePresentation()
  let slide1 = slideP.getSlides()[0]
  let img = slide1.getImages()[0]
  // Fetch a new image
  let req = UrlFetchApp.fetch('https://source.unsplash.com/random/300x200')
  let blobImage = req.getAs('image/jpeg')
  // Get the properties of the actual image
  let [left, top, width, height] = [
    img.getLeft(),
    img.getTop(),
    img.getWidth(),
    img.getHeight()
  ]
  // Remove the old one
  img.remove()
  // Add the new one with the same attributes
  slide1.insertImage(blobImage, left, top, width, height)
}

Then simply add the function to a Trigger.

Random image in Google slides


Numerical test of integrability with applications in computer vision

Question: In my computer vision course, we are working on extracting a 3D surface from a chain of 2D images taken under several conditions. This procedure is known as Photometric stereo. Prior to extracting the surface $f(x,y)$ numerically, we have to perform what's called a test of integrability :
$$
\frac{\partial^{2}f}{\partial x\partial y}=\frac{\partial^{2}f}{\partial y\partial x}
\tag{1}$$
This sanity test can be tested numerically by discretizing the partial derivative so that it accepts small values (and thus we have to accept that to recover $f$, we recover it starting from small values). Numerically this translates to :
$$
\frac{\partial\displaystyle\left(\frac{\alpha(x,y)}{\gamma(x,y)}\right)}{\partial y}-\frac{\partial\displaystyle\left(\frac{\beta(x,y)}{\gamma(x,y)}\right)}{\partial x}\approx0
\tag{2}$$
where :
$$
\frac{\partial f}{\partial x}=\frac{\alpha(x,y)}{\gamma(x,y)}\qquad\text{and}\qquad\frac{\partial f}{\partial y}=\frac{\beta(x,y)}{\gamma(x,y)}
\tag{3}$$
essentially where $(\alpha(x,y),\beta(x,y),\gamma(x,y))$ are the coordinates of the measured value of the unit-normal vector at some point on the surface $f$.

In short, how can we numerically check if $(2)$ is valid? what algorithm or procedure should we do to discretize the partial differentiation?

I am not familiar with advanced concepts such as discretizing partial differential equations. However, I am familiar with numerical integration techniques.
Source of the discussion: Forsyth, Ponce, Computer Vision: A Modern Approach (Second Edition), 2012
Comment: I would be interested to see an answer to this question. Any references that you can add will almost certainly be helpful.
Comment: I found the book. It told me nothing except that you had already given all the relevant information. The key point that I missed the first time around is that you are doing a sanity check of the measured values and not trying to prove that the vector field is integrable. The critical keywords for you to look up are: "finite difference approximations" and the "space central second order  accurate approximation of the first derivative". This will get you started. Judging the accuracy of ones approximations is  the next step. The key word here is Richardson extrapolation.
Comment: Another point. How accurate are the measurements? Can the error be quantified.and bounded? Finite difference are quite sensitive to errors in the input, so my previous suggestion is not without risk.
Answer: Briefly, the suggestion to consider numerical differentiation is vulnerable against errors in the measurements and this test of integrability is likely to produce many false negatives. Instead we should turn to numerical integration.
The situation is as follows. We are given a $C^1$ vector field $F : \Omega \rightarrow \mathbb{R}^2$ where $\Omega \subseteq \mathbb{R}^2$. We wish to assert that $F$ is integrable, i.e., that there exists a function $\phi : \Omega \rightarrow \mathbb{R}^2$ such that $$F(x,y) = \left(\frac{\partial \phi}{\partial x}(x,y), \frac{\partial \phi}{\partial y}(x,y)\right).$$ Now, if $\Omega$ is an open simply connected subset of $\mathbb{R}^2$, the $F = (f,g)$ is integrable if and only $$\forall (x,y) \in \Omega \: : \: \frac{\partial f}{\partial y}(x,y) = \frac{\partial g}{\partial x}(x,y) \label{a} \tag{1}.$$ What can we do when $f$ and $g$ cannot be subjected to direct mathematical analysis, but can only be measured? Firstly, it is clear that we can only examine finitely many points $(x,y) \in \Omega$. Certainly, derivatives can be approximated using finite differences. In particular, we have the standard space central approximation of the first order derivative, i.e.,
$$ \frac{\partial f}{\partial y}(x,y) = \frac{f(x,y+h)-f(x,y-h)}{2h} + O(h^2), \quad h \rightarrow 0, \quad h \not = 0$$ and $$ \frac{\partial g}{\partial x}(x,y) = \frac{f(x+h,y)-f(x-h,y)}{2h} + O(h^2), \quad h \rightarrow 0, \quad h \not = 0.$$
Here the underlying assumptions are that $f$ and $g$ are of class $C^3$. When $f$ and $g$ can be evaluated at any point, then it is possible to reliably estimate the error and determine if equation $\eqref{a}$ is satisfied to the limit of machine precision. The underlying technique is now as Richardson extrapolation. Deciding when the error estimates are reliable can be done by observing Richardson's fraction. A small sample of this technique is shown in this answer to a question on numerical integration and this answer to a question on sequences.
However, while this is very useful, the finite differences are very vulnerable to measurement errors. Suppose that we cannot measure $f$ exactly, but our instruments return $$\hat{f}(x,y) = f(x,y)(1 + \delta_{(x,y)})$$ for what is hopefully always a small value of $\delta_{(x,y)}$. Then the computed approximation will satisfy
$$ \frac{\hat{f}(x,y+h) - \hat{f}(x,y-h)}{2h} =  \frac{f(x,y+h) - f(x,y-h)}{2h} + \frac{f(x,y+h)\delta_1 - f(x,y-h)\delta_2}{2h}$$
This is disastrous! The measurement error is divided with $h$ and sooner rather than later the computed approximation of the derivative will be utterly useless.
What can we do instead? We want to be sure that $F$ is integrable. We will never certain, but we can look for evidence that supports this conjecture. We compute $$ \oint f(x,y)dx+g(x,y)dy$$ along a selection of closed paths. If $F$ is integrable, then result should be zero. We can use numerical integration to evaluate the integrals. There will still be two contributions to the total error, namely the discretization error and the measurement error. The discretization error will decay as the step size is reduced. However, the measurement error is not amplified as before. If the absolute value of computed value of the integral is less than our error bound, then we have found nothing to suggest that $F$ is not integrable. I suspect that this is as far we can go.


Como adicionar incremento a cada ID e zerar após um novo  PHP

Question: Quero saber quantas linhas tenho em cada  e qual linha será modificada, para isso quero adicionar incremento no id="id_tec_pag'+id_tec_pag+'[]". E que a cada mudança de bloco esse contador reinicie.
Corpo:
            html += '
';
            html += '
';
            html += '                                   <input type="hidden" id="id_tec_pag'+id_tec_pag+'[]"/>';
            html += '                                   <input type="text" name="nome'+cdRegiao+'_tec[]"/>	';
            html += '                                   <input type="text" name="email'+cdRegiao+'_tec[]"/>	';
            html += '                                   <input type="text" name="telefone'+cdRegiao+'_tec[]"/>	';
            html += '                                   <input type="password" name="senha1'+cdRegiao+'_tec[]"/>	';
            html += '                                   <input type="password" name="senha2'+cdRegiao+'_tec[]">	';
            html += '                                   <button type="button" class="removerCampo">  <?=TXT_BOTAO_EXCLUIR?></button>	';
            html += '
';
            html += '
';
            html += '
';
            html += '
';
            html += '
';

            $('#div-regioes').append(html);

            adicionaCampo(cdRegiao);

JS:
    function adicionaCampo(codigo) {
        //$(".adicionarCampo").unbind("click");
        $(".adicionarCampo").on("click", function () {
            novoCampo = $("tr.linhas"+codigo+":first").clone();
            novoCampo.find("input").val("");
            novoCampo.insertAfter("tr.linhas"+codigo+":last");
            removeCampo(codigo);
        });
    }

Comment: Você qual o index (numero da linha) ou o id que está na linha?
Comment: Tente mudar `';` para `id_tec_pag`. Ai voce pega esse id no jquery com o closest. `var row = $(this).closest('tr'); var id = row.find('.id').text()`
Comment: Qualquer modo me ajudaria, por exemplo, tenho um botão que adiciona uma div, e ele começa com um id de região =1, quero saber quantos id_tec_pag o usuário adicionou, quando ele adicionar outra região, no caso região = 2, quero saber quantos id_tec_pag tem na região 2 e assim por diante.
Comment: Como você adiciona esse item na tabela?
Comment: Estava adicionando apenas rows, mas sem diferenciar de qual é qual, com isso não consigo dar um UPDATE nas informações quando o usuário faz edição.
Comment: adiciona um data-id no campo e ai recupera o valor do data-id e soma para obter o n° do novo id.
Answer: Para você recuperar a quantidade de linhas de sua tabela você pode utilizar
var numeroLinhas = document.getElementById('seuId').rows.length;

Se você deseja percorrer cada elemento da sua lista o jquery facilita:
$('#suaTabela > tbody  > tr').each(function() { //Sua regra de negócio });


VerifyCsrfToken, Auth & Trying to get property of non-object

Question: I'm going back to an old project, and the homepage need to be access when logged in, if not, you get redirected to /login. For that I'm using the Auth middleware, but when doing so, I get the following error (see bottom of post with the error and the full error on imgur).
I checked my middleware but don't actually have custom one, I also checked my code to see if I weren't using a weird middleware group or anything, and I can't seem to find an error for now.
In my HomeController.php, if I remove the usage of the Auth middleware, the script continue (but I have another error further along, about Roles & Permissions, which is normal)
    public function __construct()
    {
        $this->middleware('auth');
    }

Normally, I would expect to be redirected, but instead, I get this error :
Trying to get property of non-object
Full error :
Refer this
I shall mention that I have this error on EVERY page that need authentification, and not on the one that doesn't, it's not limited to my HomeController
Thanks !
EDIT :
Here is the full controler where I use the middleware (even if I have the issue elsewhere too)
<?php

namespace App\Http\Controllers;

use App\Sinistre;
use App\Appointment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $sinistres = null;
        if (Auth::user()->hasRole('admin')) {
            $sinistres = Sinistre::all();
        } else {
            $sinistres = Auth::user()->sinistres;
            foreach(Auth::user()->societe AS $societe){
                $sinistres = $sinistres->merge($societe->sinistre);
            }
        }

        $sinistres = $sinistres->unique();

        $appointments = Appointment::orderBy('date_start', 'desc')->with(['sinistre', 'sinistre.user'])->take(8)->get()->reverse();
        return view('pages.home', [
            'sinistres' => $sinistres,
            'appointments' => $appointments,
        ]);
    }
}

Comment: could you post your code where you used the auth class
Comment: I edited the original post with my controller !
Comment: try adding `use Auth` above your class.
Comment: I already have ```use Illuminate\Support\Facades\Auth;``` but if I replace it with ```use Auth;``` I get the same error
Comment: ahh sorry I miss that Auth class.
Comment: it can happen :) . Would you appear to have another idea ? I super stuck on this. And I edited my OP that I get the same error on every page that need authentication, not only my HomeController.
Comment: Check your RedirectIfAuthenticated.php handle function if it has `return $next($request);`
Comment: Make sure `StartSession::class` is before your `VerifyCsrfToken::class` entry in your `Kernel.php` under the `web` middleware
Comment: JoefreyR.Ramos : It has one, here is the code of the file : https://paste.laravel.io/e38866c4-576a-4aa8-9953-e8b5a4c87b95
@apokryfos : I checked it, and it is in the good order :)
Answer: it might mean that you're not logged in try to add this one in the beginning of your index function in controller
    if(Auth::user()){
     //Your Code
    }else{
     return redirect('/');
    }

Comment: I tried that, but it's never reached (I even tried to use ```dd('Are we reached ?');``` and it's not displayed.
Comment: Did you not change the login of Auth? or are you using customize?
Comment: Are you talking about the guard ? If yes, it's the standard one :)


Can a team mate give lifting/climbing support?

Question: Can a team mate give lifting/climbing support so that a player can reach the height where goalie or any opponent cannot reach? Is climbing on the goal post allowed?
Comment: Lifting support probably isn't disallowed but I don't see it as very practical. The ball is moving too fast for two players to construct a "ladder". And it would be hard for a ball fired at this height to go into the net.
Answer: This is classed as unsporting behaviour. The player doing the lifting, or the player doing the climbing is cautioned for unsporting behaviour, and the opponents are awarded an indirect free kick from where the lift/climb occurred.
Although this is not explicitly mentioned in the Laws of the Game, it is known to be unsporting behaviour through tradition.
Each year the United States Soccer Federation releases an Advice To Referees document. This documents fills in the gaps of "tradition" vs what is actually codified in the FIFA Laws of the Game. In the 2014 edition, on pages 50-51:

Referees are urged to review the list of examples of
  unsporting behavior to be found in
  the Interpretation of the Laws of the Game and Guidelines for Referees as well as in
  U.S. Soccer training materials for newer referees. Other examples include:
...

Uses an artificial aid to unfairly assist play – for example, leaning on the
  shoulders of a teammate to increase height, using an article of clothing to avoid
  direct contact with the ball, removing the corner flag on a corner kick, hanging on
  the crossbar.
Comment: It doesn't really give you a huge advantage, but it's playing the game in a way that it's not intended to be played. The caution for unsporting behaviour would be written up as "acts in a manner which shows a lack of respect for the game" - p. 123 of the 2014/15 Laws of the Game (http://www.fifa.com/aboutfifa/footballdevelopment/technicalsupport/refereeing/laws-of-the-game/index.html
Comment: Not much unsporting though.


How can you distinguish instruments by their timbre characteristics?

Question: What I am trying to achieve is to distinguish instruments by their timbre. What I have read so far made me think that different instruments have different number of overtones.
Is it possible to identify an instrument from a list of overtones/harmonics for each (or at least some) instrument represented as, for example, frequencies? Or does it depend on the physical state of an instrument?
Or am I going into completely wrong direction and the timbre is not formed, amongst others, with the number of overtones?
Comment: http://physics.stackexchange.com/questions/78827/what-are-those-characteristics-by-which-every-sound-can-be-identified-uniquely/78829#78829
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/39587/discussion-on-question-by-yuriy-kravets-how-can-you-distinguish-instruments-by-t).
Comment: Related: It is quite hard to only go by timbre by ear, we depend a lot on attack and decay of an instrument https://www.youtube.com/watch?v=thD6TNUoyIk
Comment: @ViktorMellgren the best answer was given by Todd Wilcox. He explained it in a more detailed way than Andrew Huang did.
Answer: A simple list of what overtones are present wouldn't tell you much. What you really want is the relative levels/intensity of each overtone. A list of the overtones with relative intensities for an instrument is called the instrument's spectrum. You might try searching for " spectrum" for the ones you are most interested in. Here's an example for a violin:

Many instruments have virtually the exact same overtones present, and often with very similar relative amplitudes. What is different about them are the relative amplitudes over time. The change in the amplitude of an overtone over time is its time envelope. The combined time envelopes of the different overtones (we'll call it just "envelope" for simplicity) is also a critical aspect of instrument recognition.
Overtones that are relatively stable of a certain period of time are called partials. Overtones that are only audible for short periods of time are usually called transients, and initial transients are important for instrument recognition.
The important aspects of pitched instrument timbre recognition are the envelope and the full overtones spectrum, including partials and transients.
Note that minor components of an instrument's sound (including noises, like breath noise) are also represented in the spectrum, mostly as transients.
Note also that unpitched instruments, like many percussion instruments (e.g., cymbals) or more "noisy" instruments have multiple frequencies present that are not harmonically related and are sometimes called inharmonic components. The frequencies and amplitudes of these less- or non-related overtones creates the spectrum for an unpitched sound and also determines whether a sound is a little bit pitched (like a snare drum). Envelopes and transients are also just as important for unpitched instrument recognition.
Comment: As you say, initial transients are a really important part of perceived timbre, and these often have enharmonic / noise characteristics. Just a quick terminology check - I didn't think 'partial' itself implied a lack of harmonic relationship unless you specified 'enharmonic partial'? e.g. see table at https://en.wikipedia.org/wiki/Overtone#Musical_usage_term
Comment: The precise definition of partial is a component of a signal that is periodic and stable and that can be modelled as a slowly time-varying sinusoid. Partials can be harmonic or inharmonic. A frequency spectrum is made of partials (both harmonic and inharmonic) and transients.
Comment: @joseem "Formant" is used with the same meaning in analysing the sound of musical instruments, to describe the way the resonances of the instrument itself (which are independent of the pitch of the note being played) affect the amplitudes of different harmonics. For example, the existence of formants explains why some instruments have very different tone qualities in their low and high registers. See http://music.columbia.edu/cmc/MusicAndComputers/chapter4/04_04.php for example.
Comment: Quite interesting article @alephzero, on the face of it I agree that narrowing the application of the formant concept to voice sounds only (the original application of the concept) is too restrictive . Still, it's important to note that formants are not the spectrum, but only certain specific (resonance, as you say) frequencies.
Answer: For human ears, the relation of the overtone to the fundamental is perhaps not as important as the pitch area that the overtone sounds in. Our ears have evolved to pick out resonance peaks and valleys (see the concept of vocal formants) that are pertinent to distinguishing vowels. An "ah" sound, for example, has an "ah" quality regardless of the fundamental pitch used when speaking or the specific rank of the overtones that lie within the formant areas.
Instruments have characteristic wave profiles based on how the sounds are formed: e.g., a clarinet will at least start out with just odd-numbered harmonics, a string will produce a sound wave with sawtooth wave qualities as the string slips and is grabbed by the bow, a brass instrument will have some pulse-wave qualities as the air periodically forces itself through the lips. But what further distinguishes these instruments from each other is the resonant peaks and valleys that arise from the shape or construction, that are invariant regardless of the pitch being played. The sound is the result of the combination of the "exciter," and the "resonator" for the source vibrations, similar to the source/filter model used for speech recognition and speech synthesis.
And yes, there are also envelope characteristics, especially pertaining to the start of notes that can help us distinguish different sounds.
There is some incredible technology out there now that can pick instruments out of a mix. I am just sharing a bit I know of the acoustical theory. I haven't learned yet how to do the analysis for quickly identifying the harmonic profile. I finally learned the basic math behind DFT analysis, via The Scientist and Engineer's Guide to Digital Signal Processing, but I think it is going to be a long haul before getting the programming and math down for truly identifying instruments.
Answer: On a practical/engineering approach, once we have the spectral analysis (i.e. the characterization of the frequency spectrum along time in terms of transients, and harmonic and inharmonic partials, as explained in Todd Wilcox's answer), we need to compare our instrument to a reference database of previously catalogued instruments.
This is done by using a rather large number of spectral properties evaluated from the basic spectrum, for example, just to name a few (there are dozens):

spectral contrast - a comparison of the spectral envelope with the reference database
inharmonicity - relative weight of the inharmonic components
dissonance - comparison of the spectral envelope with a perceptual dissonance reference

The database comparison is done by statistical means, as of course no two samples of the same type of instrument (or even of the same exact instrument) are exactly alike.
Clustering algorithms are typically used: several samples of the same type of instrument are classified into a "cluster" in the database. The sample being analysed is then compared to each cluster, to find where it fits better. Here's an example of the result of such process (the process must be repeated for several combinations of different parameters to obtain good matching results):

This picture was obtained with sms-tools (a set of resources developed by the Pompeu Fabra university in Barcelona), Essentia (a very powerful software tool for audio analysis) and samples collections gathered from Freesound. These are invaluable resources for anyone endeavouring in sound analysis.


Eloquent Relationship with multiple many-to-many relationships - Laravel

Question: I have table structures like this :

jobs

id
name

types

id
name

job_type (pivot table)

id
job_id
type_id

tasks

id
description

job_type_task (pivot table)

id
job_type_id
task_id

Notes :

jobs has many types and vice versa
job_type has many tasks and vice versa

My problem is with this table structures, How can I establish a relationship between 'job' and 'tasks' tables to access all tasks associated with a job?
I have tried many solution like using hasMany or hasManyThrough but none is working.
Should i change the table stuctures? or any solution to access tasks via job eloquent model?
Answer: there is no stock laravel relation for your case as your relation is not direct but through 2 entities and laravel only natively support 1 level down so you can check this package that might help you achieve what you need
https://github.com/staudenmeir/eloquent-has-many-deep
also there was a similar question that might be similar to your use case that helps creating a new custom relation since the stocked relations is not enough Custom Laravel Relations? and also this article explains it nicely https://stitcher.io/blog/laravel-custom-relation-classes
here is the implementation of custom relation in case you need it
<?php

namespace App\Relations;

use App\Models\Job;
use App\Models\Task;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\Relation;

class JobTaskRelation extends Relation
{
    /** @var Task|Builder */
    protected $query;

    /** @var Job */
    protected $parent;

    public function __construct(Job $parent)
    {
        parent::__construct(Task::query(), $parent);
    }

    /**
     * @inheritDoc
     */
    public function addConstraints()
    {
        $this->query->join('job_type_task', 'job_type_task.task_id', '=', 'tasks.id')
            ->join('job_type', 'job_type.id', '=', 'job_type_task.job_type_id');
        if (static::$constraints) {
            $this->query->where('job_type.job_id', '=', $this->parent->getKey());
        }
    }

    /**
     * @inheritDoc
     */
    public function addEagerConstraints(array $models)
    {
        $this->query
            ->whereIn('job_type.job_id', $this->getKeys($models))
            ->with('jobTypes')
            ->select('tasks.*');
    }

    /**
     * @inheritDoc
     */
    public function initRelation(array $models, $relation)
    {
        foreach ($models as $model) {
            $model->setRelation(
                $relation,
                $this->related->newCollection()
            );
        }

        return $models;
    }

    /**
     * @inheritDoc
     */
    public function match(array $models, Collection $results, $relation)
    {
        $results = $results->unique('id');
        if ($results->isEmpty()) {
            return $models;
        }

        foreach ($models as $model) {
            $model->setRelation(
                $relation,
                $results->filter(function (Task $task) use ($model) {
                    return $task->jobTypes->pluck('job_id')->contains($model->id);
                })
            );
        }

        return $models;
    }

    /**
     * @inheritDoc
     */
    public function getResults()
    {
        return $this->query->get();
    }
}

and now you job model will be something like this
<?php

namespace App\Models;

use App\Relations\JobTaskRelation;
use Illuminate\Database\Eloquent\Model;

class Job extends Model
{
    public function types()
    {
        return $this->belongsToMany('App\Models\Type');
    }

    public function jobTypes()
    {
        return $this->hasMany('App\Models\JobType');
    }

    public function tasks()
    {
        return new JobTaskRelation($this);
    }
}

and task model will be
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    public function types()
    {
        return $this->belongsToMany('App\Models\Type');
    }

    public function jobTypes()
    {
        return $this->belongsToMany('App\Models\JobType');
    }
}

important note to take care of:
since laravel assumes that when we have a model the table is plural and your scheme define the pivot tables as singular it's important that when you define the pivot models to set $table to the singular table name and you are good to go
now you can use Job::find(1)->tasks or Job::with('task')->get()
you might need to add more functions based on what you need in the future and you will need to maintain it
Using accessor
also another solution that came to my mind did you consider accessor ?
you can define an accessor in your job model so what it does the needed queries to fetch the data if you are just interested about reading the data and it will be much simpler like so
    // app/Models/Job.php
    public function tasksData(): Attribute
    {
        return Attribute::make(
            get: function () {
                $tasks = collect();
                foreach ($this->types as $type) {
                    $tasks = $tasks->merge($type->tasks);
                }
                return $tasks->unique('id');
            },
        );
    }

and in case you always wants it you can add it to model appends and that case laravel will evaluate it will loading the data
protected $appends = ['tasksData'];

Comment: I don't think the given solution will works, because in their case the relationship is between model and model, mine is between pivot_model and model, job_type has many tasks and tasks has many job_type while job_type is a pivot table between jobs and types. But anyway i will try the solution first - thanks for replying.
Comment: it doesn't really matter once you enter the custom domain you can tailor your relation however you want this was just an example but the idea is the same once you define a custom relation you will have full control how the query is constructed and you can make all joins you need to achieve the desired result
Comment: @Luna answer updated to add the custom relation implementation and also I added another solution to use accessor instead of custom relation
Answer: jobs:            id,  name
jobs_types:  job_id, type_id
types_tasks:         type_id, task_id
tasks:                             id, description

SELECT j.name,
       k.description
    FROM jobs        AS j
    JOIN jobs_types  AS jy   ON jy.job_id = j.id
    JOIN types_tasks AS yk   ON yk.type_id = jy.type_id
    JOIN tasks       AS k    ON k.id = yk.task_id
    WHERE j.name = "XYZ"

Note:  There is no need for id in the many-to-many tables, but there is a need for indexes like:
jobs_types:
    PRIMARY KEY(job_id, type_id)
    INDEX(type_id, job_id)

(I do not know how to translate that into Laravel.)
Answer: I know this is late, but in case anyone else is wondering, you could create a method utilizing Query Builder in your Job::class model, and then call as method, not as property. So, Job::find(1)->jobTasks().
The query builder might look something like this:
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class Job extends Model
{
    public function jobTasks($id): Collection
    {
        return DB::('tasks')
            ->join('job_type_task', 'job_type_task.task_id', '=', 'tasks.id'),
            ->join('job_type', 'job_type_task.job_type_id', '=', 'job_type.id')
            ->join('jobs', 'job_type.job_id', '=', 'jobs.id')
            ->join('types', 'job_type.type_id', '=', 'types.id')
            ->select('jobs.*', 'types.name as type_name', 'tasks.description')
            ->where('jobs.id', $id)
            ->get();
    }
}

And then call it as method as mentioned above but pass an $id as an argument.
This won't create an Eloquent Relationship, but it will get you the information you're looking for while utilizing your Job::class model. Relationships can be built in your database for cascading or restricted updates and deletes.
At this point, you can do anything you want with the information. Loop, or map through it and get individual fields as necessary...
Job::find(1)->jobTasks(1)->map(fn($jobTask) => [$jobTask->name => $jobTask->type_name]);


Why does spelling change the consonance/dissonance of the exact same interval?

Question: The interval of F# to A is a minor third, an imperfect consonance. But if we spell the F# as a Gb, suddenly we have created an augmented 2nd, a dissonance. Sonically, these two situations are the exact same thing. Their frequency ratios are exactly the same, the only difference is that they are spelled differently. However, this sonically nonexistent difference somehow changes a consonance to an interval that is considered dissonant. This is not limited to this one situation; the augmented fifth, diminished 7th, and diminished fourth all have consonant equivalents, and yet are somehow considered dissonant. How does spelling change an interval's consonance?
Comment: Does this answer your question? [Why is a minor 3rd consonant but an augmented 2nd dissonant?](https://music.stackexchange.com/questions/21910/why-is-a-minor-3rd-consonant-but-an-augmented-2nd-dissonant)
Comment: [This](https://music.stackexchange.com/questions/21910/why-is-a-minor-3rd-consonant-but-an-augmented-2nd-dissonant) should answer your question.
Comment: This question assumes 12tet - or does it..? And be careful with terminology - those two are not the same *interval* - they're the same distance apart, in semitones.
Comment: @Tim Yes, this assumes 12tet, though playing the same two tones wouldn't create a different sound in any temperament.
Comment: I know this answer was about dissonance but I don't remember the details of the video. Not sure if it was about chords or chord progressions though. https://music.stackexchange.com/a/75189/60885
Comment: @OprenStein - as Aaron states, it actually would - depending upon the key the different temperament was tuned to. Or if the 'intervals were played on violin, trombone or even sung.
Comment: If you search for e.g. xenharmonic wiki you will also find a lot of information regarding different variants of the intervals (there are an infinite amount of intervals that can be called a minor third)
Comment: @Tim playing the same two tones cannot produce a different sound.  In some tuning systems, F sharp and G flat aren't the same tone, but in any 12-tone temperament, whether equal or unequal (and in many tuning systems with more than 12 tones per octave), they are the same tone, and playing that tone with an A will yield the same acoustical result.
Answer: The spelling doesn't make it dissonant or consonant; the consonance or dissonance determines the spelling.
Rather than spell the notes, assign them numbers: C = 0, C# = 1, D = 2, ..., B = 11.
Now consider the C minor scale. The first three pitches are 0, 2, 3.
The E harmonic minor scale also contains 0 and 3: 4 6 7 9 11 0 3 4.
However, if one plays the two scales, the 0-3 in the C minor scale has a very different character than the 0-3 in the E harmonic minor scale.
In order to reflect this contextual different in sound, the otherwise enharmonically equivalent pitches are given different spellings: C D Eb for the C minor context, and C D# E for the E harmonic minor context.
Also, historically, before equal temperament was standardized, C# and Db, for example, were not necessarily the same pitch. Even today, instruments with "continuous" tuning ability, like violin or voice, will adjust notes sharp or flat —that equal temperament would otherwise deem equivalent — to create better intonation of intervals in specific contexts. For example, the minor third or a chord might be adjusted very slightly higher, or the major third very slightly lower, bringing them closer to their just-intoned equivalents.
Comment: Also most wind instruments can adjust notes sharp or flat.
Comment: @phoog Recordings, no. I was just thinking of ensembles in which the director asked whomever had the third of a chord to raise or lower it compared to its equal-tempered basis.
Comment: For the most part, D sharp will be lower than E flat, not the other way around, unless the goal is Pythagorean tuning.
Comment: @phoog But don't musicians (in 12-TET) tend to lower minor thirds and raise augmented seconds?
Comment: @Aaron if they're lowering or raising anything then it's not equal temperament, is it?
Comment: @phoog I'm speaking on-the-fly adjustments during performance, not the initial tuning system.
Comment: @Aaron well in that case, those adjustments are typically in favor of 5-limit just intonation (sometimes 7-limit), where a minor third is 316 cents  and an augmented second could be any of several sizes, but the distance between the 8:5 minor sixth and the 15:8 major seventh is a mere 275 cents.  The Pythagorean sizes are 294 cents and 318 cents.  Do you have any recordings in mind?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/143183/discussion-between-phoog-and-aaron).


How can I use all td space with a textarea?

Question: I would like my textareause all height space with css configuration but I can't. Can you, please, help me? thank you.
<!DOCTYPE html>

    <title></title>

                <textarea class="textarea1"></textarea>

                a

                a

                a

                a

                a

Answer: The td also needs height: 100%. I applied it to all of them, but you might just want to limit it to the one that has the textarea depending on how you implement it. Also made the textarea display: block as that will remove the little bit of white space at the bottom. You could also use vertical-align: top instead of display: block

<!DOCTYPE html>

  <title></title>

        <textarea class="textarea1"></textarea>

        a
 a

 a

 a

 a

Comment: @Alohci ah right, thanks. I'm on a mac and don't have my edge VM's, but FF needs `height: 100%` on the `tr,td`, and I believe edge needs `height: 100%` on the `table,tr,td`. Updated my answer - can you check edge?
Comment: Yes, with the modification, the textarea is about the right size in FF and Edge. - though slightly mispositioned, esp. FF (on Windows).
Answer: try this one

td{
        border: solid black 1px;
        height: 100%;
        padding:0px;
    }
    textarea{
        height: 100%;
        display: block;
    }

    <textarea></textarea>


Learning Resources: Mathematica Notebooks

Question: A while ago, I stumbled upon someone's list of Mathematica notebooks for learning various topics.  I've since lost the link, but I'm wondering now if I could find notebooks again.
So my question is:  Where can we find Mathematica notebooks for learning various topics?
I'm looking for big notebooks that cover the amount of material that a textbook on the subject would cover.  Other than that, I'm sorry I can't get more specific.
Comment: Amazon? Though even there, much can be out of date. Presumably, the availability of such notebooks / content would depend on the subject matter. /////// As an aside .... a very nice summary of issues for new users is given here: http://mathematica.stackexchange.com/questions/18393/what-are-the-most-common-pitfalls-awaiting-new-users
Answer: A place where one can find Mathematica notebooks to learn about various topics is the Wolfram Documentation Center. It is found inside the Mathematica software (Help section) and online:
http://reference.wolfram.com/language/
Another place is the MathWorld website. There are downloadable Mathematica notebooks attached to a good number of mathematical topics. At the top of the topic page just click on the words "Download Mathematica notebook" (if they exist):
http://mathworld.wolfram.com/
There is also a link to a free pdf tutorial entitled "Wolfram Mathematica® Tutorial Collection NOTEBOOKS AND DOCUMENTS":
http://www.johnboccio.com/MathematicaTutorials/13_NotebooksAndDocuments.pdf
The tutorial above is useful even if it refers to an older version of Mathematica.
See also this related question:
https://mathematica.stackexchange.com/questions/18/where-can-i-find-examples-of-good-mathematica-programming-practice


How to program a Monte Carlo simulation of Bertrand's box paradox?

Question: The following problem has been posted on Mensa International Facebook Page:
$\quad\quad\quad\quad\quad\quad\quad\quad$
The post itself received 1000+ comments but I won't go into details about the debate there since I know this is Bertrand's box paradox and the answer is $\frac23$. What make me interested here is how does one answer this problem using a Monte Carlo approach? How is the algorithm to solve this problem?
Here is my attempt:

Generate $N$ uniformly distributed random numbers between $0$ and $1$.
Let the event of box contains 2 gold balls (box 1) selected be less than half.
Count the numbers that less than $0.5$ and call the result as $S$.
Since it's a certainty to get a gold ball if the box 1 is selected and it's only 50% chance of getting a gold ball if the box 2 is selected, hence the probability of getting a sequence GG is
$$P(B2=G|B1=G)=\frac{S}{S+0.5(N-S)}$$

Implementing the algorithm above in R:
N <- 10000
S <- sum(runif(N)<0.5)
S/(S+0.5*(N-S))

The output of program above is around $0.67$ which almost match with the correct answer but I'm not sure this is the correct way. Is there a proper way to solve this problem programmatically?
Answer: Like @Henry, I don't really feel that your solution is a Monte Carlo. Surely, you sample from the distribution, but it doesn't have much to do with imitating the data generating process. If you wanted to use Monte Carlo to convince someone that the theoretical solution is correct, you would need to use solution that imitates the data generating process. I would imagine it to be something like below:
boxes <- list(
  c(0, 0),
  c(0, 1),
  c(1, 1)
)

count_successes = 0
count_valid_samples = 0

for (i in 1:5000) {
  sampled_box <- unlist(sample(boxes, 1)) # sample box
  sampled_balls <- sample(sampled_box)    # shuffle balls in the box

  if (sampled_balls[1] == 1) {            # if first ball is golden
    if (sampled_balls[2] == 1) {          # if second ball is golden
      count_successes = count_successes + 1
    }
    count_valid_samples = count_valid_samples + 1
  }
}
count_successes / count_valid_samples

or using "vectorized" code:
mean(replicate(5000, {       # repeat 5000 times, next calculate empirical probability
  x <- boxes[[sample(3, 1)]] # pick a box
  if (x[sample(2, 1)] == 1)  # pick a ball, check if it is golden
    return(sum(x) == 2)      # check if you have two golden balls in the box
  else
    return(NA)               # ignore if sampled ball is silver
  }), na.rm = TRUE)          # not count if silver

Notice that since you condition of the fact that first ball was already drawn and it is golden, so the above code could simply use two boxes boxes <- list(c(0, 1), c(1, 1)) and then sample from them x <- boxes[[sample(2, 1)]], so the code would be faster since it wouldn't make the 1/3 empty runs that we discount. However since the problem is simple and the code runs fast, we could afford to explicitly simulate the whole data generating process "to be sure" that the result is correct. Besides that, this step is not needed since it would yield same results in both cases.
Comment: @Anastasiya-Romanova秀 you could instead sample from two boxes `boxes <- list(c(0, 1), c(1, 1))` and then `x <- boxes[[sample(2, 1)]]`, but since this is almost the same computation time, why not use the extra step that exactly resembles the sampling process? It does not change anything about the result, but makes the simulation explicit.
Comment: @Anastasiya-Romanova秀 yes, exactly. The code samples a box, then samples a ball from the box, if it is golden (=1) then it checks if the other ball from the box is also golden (1+1=2), if yes then it counts it and in the end it divides the sum by total count (i.e. uses `mean`).
Comment: @Anastasiya-Romanova秀 `return(NA)` returns missing value and then `mean(, na.rm = TRUE)` is used, where `na.rm = TRUE` argument tells the function to ignore the missing values. In other programming languages this could be done differently, e.g. using `continue` or `pass` keywords.
Comment: Does `x <- boxes[[sample(3, 1)]]` mean you take a box from 3 boxes? If so, why it's necessary since we've known you already picked a gold ball?
Comment: Alright Tim, thanks for your answer. Give me time to understand your answer first since I'm fairly new in R. For now, +1 for you & @Henry.
Comment: I have a question. Does `return(sum(x) == 2)` mean if `x` values (1,1) the program will return 1 and 0 otherwise?
Comment: OK, understood. Another question, does `return(NA)` mean it won't be included in calculating mean? For example, suppose we replicate only 5 times then the result are 1, 0, 1, NaN, 1. Does this mean the program will calculate the mean as $\frac{3}{4}$, *not* $\frac{3}{5}$?
Answer: I feel your S/(S+0.5*(N-S)) calculation is not really simulation
Try something like this
N <- 10^6
ballsinboxes <- c("G","G", "G","S", "S","S")
selectedbox <- sample(c(1,2,3), N, replace=TRUE)
selectedball <- sample(c(1,2), N, replace=TRUE)
selectedcolour <- ballsinboxes[(selectedbox-1)*2 + selectedball ]
othercolour <- ballsinboxes[(selectedbox-1)*2 + 3 - selectedball ]
sum(selectedcolour == "G" & othercolour == "G") / sum(selectedcolour == "G")

Answer: Why not simply list the cases?
Here: G is for "gold", S is for "silver", capital is for the initial extraction:
Gg
gG
Gs
... all other cases invove an initial silver (S) extraction and don't satisfy the conditional (initial extraction G).
Such, P(g|G) = 2/3.
Comment: The question asks about Monte Carlo solution.
Comment: No it is not, Monte Carlo is about simulation/randomization.
Comment: Sure, but listing all cases is not Monte Carlo. Square is a rectangle, but rectangle is not a square.
Comment: Well, listing ALL the possibilities is an extreme case of Monte Carlo.
Comment: Tim, get your math right. With infinitely many draws, you get exactly a list of all cases with equal probabilities. I sad "extreme case" and meant limit.


Rows of a Matrix is divisible by 19, show that its Determinant is also divisible by 19

Question: I came across the following problem while self studying:
Let
\begin{equation}
A =
\begin{bmatrix}
2 & 1 & 3 & 7 & 5\\
3 & 8 & 7 & 9 & 8\\
3 & 4 & 1 & 6 & 2\\
4 & 0 & 2 & 2 & 3\\
7 & 9 & 1 & 5 & 4\\
\end{bmatrix}
\end{equation}
Use the fact that 21375, 38798, 34162, 40223, and 79154 are divisible by 19 to show, without evaluating, that $\det[A]$ is divisible by 19.
I noticed that each of these numbers are the entries in the rows of A, but I don't see how that helps me.
Comment: Closely related [Determinant divisible by 23](https://math.stackexchange.com/questions/1567302/determine-a-determinant-is-divisible-by-23-or-not?rq=1)
Answer: Note that $$10^{10} \det(A) = 10^{4+3+2+1+0} \det(A) =  \det \begin{pmatrix} 2 \cdot 10^{4} & 1\cdot 10^3 & 3\cdot 10^2 & 7\cdot 10 & 5 \\
3\cdot 10^{4} & 8 \cdot 10^3 & 7\cdot 10^2 & 9\cdot 10 & 8 \\
3\cdot 10^{4} & 4\cdot 10^3 & 1\cdot 10^2 & 6\cdot 10 & 2 \\
4\cdot 10^{4} & 0 \cdot 10^3 & 2 \cdot 10^2 & 2 \cdot 10 & 3 \\
7 \cdot 10^{4} & 9\cdot 10^3 & 1\cdot 10^2 & 5\cdot 10 & 4  \end{pmatrix}$$  $$ =  \det \begin{pmatrix} 21375 & 1\cdot 10^3 & 3\cdot 10^2 & 7\cdot 10 & 5 \\
38798 & 8 \cdot 10^3 & 7\cdot 10^2 & 9\cdot 10 & 8 \\
34162 & 4\cdot 10^3 & 1\cdot 10^2 & 6\cdot 10 & 2 \\
40223 & 0 \cdot 10^3 & 2 \cdot 10^2 & 2 \cdot 10 & 3 \\
79154 & 9\cdot 10^3 & 1\cdot 10^2 & 5\cdot 10 & 4  \end{pmatrix}$$ which is evidently divisibly by $19$ when calculated via expansion by minors along the first column.
Comment: You don't need the $10^{10}$; you can just say $$ \det\begin{pmatrix} 2 & 1 & 3 & 7 & 5 \\ 3 & 8 & 7 & 9 & 8 \\ 3 & 4 & 1 & 6 & 2 \\ 4 & 0 & 2 & 2 & 3 \\ 7 & 9 & 1 & 5 & 4 \end{pmatrix} = \det\begin{pmatrix} 2 & 1 & 3 & 7 & 21375 \\ 3 & 8 & 7 & 9 & 38798 \\ 3 & 4 & 1 & 6 & 34162 \\ 4 & 0 & 2 & 2 & 40223 \\ 7 & 9 & 1 & 5 & 79154 \end{pmatrix} = 19 \det\begin{pmatrix} 2 & 1 & 3 & 7 & 1125 \\ 3 & 8 & 7 & 9 & 2042 \\ 3 & 4 & 1 & 6 & 1798 \\ 4 & 0 & 2 & 2 & 2117 \\ 7 & 9 & 1 & 5 & 4166 \end{pmatrix}$$
Comment: @BrydenC: Basic determinant rule: You can add any scalar multiple of a column to any _other_ column without changing the determinant.
Comment: Wow, a superb solution (and very fast indeed!)
Comment: Amazing! (+1) $ $
Comment: Can you justify what's going on between the second to last and last steps? How does that first column change like that?
Comment: Yes, that makes sense to me now. Thank you.
Comment: @HenningMakholm You are right, but the answer appears clearer to me.


Loop/Repeat jQuery animation

Question: I have a button on click of which a fish appears and it should randomly over a container at random places. but in my code its just animating only once and not repeating overand overagain. I want my function to be generic so that it can be run over and over of many fishes and be efficient code.
The HTML:

  <input type="button" value="Post" class="post-button" />

The jQuery:
var idgenerated=0;
$('.post-button').on('click',function(e){
    //$('#container img:last-child').append('

');
    $('#rightarrow').after('

');
    $('.pop-up-selectCategory').hide();
    $('.oyster').removeClass('oyster-click');
    animatenewfish(idgenerated);
    idgenerated++;
});

function animatenewfish(idgenerated) {
    console.log("hi");
    var Fishv1 = $("#"+idgenerated),
    theContainer = $("#container"),
    maxLeft = theContainer.width() - Fishv1.width()-100,
    maxTop = theContainer.height() - Fishv1.height()-100,
    leftPos = Math.floor(Math.random() * maxLeft),
    topPos = Math.floor(Math.random() * maxTop),
    imgRight = "Assets/R1gif.gif",
    imgLeft = "Assets/FIsh1.gif";
    console.log(maxLeft+"max");
    console.log(leftPos+"travel");
    if (Fishv1.position().left < leftPos) {
        Fishv1.css("background-image",'url("' + imgRight + '")');
    } else {
        Fishv1.css("background-image",'url("' + imgLeft + '")');
    }

    Fishv1.animate({
        "left": leftPos,
        "top": topPos
    }, 18000, animatenewfish);
}

Comment: http://www.jquerybyexample.net/2012/02/how-to-use-jquery-settimeout-function.html
Comment: http://stackoverflow.com/questions/11401535/how-to-loop-animate-jquery
Answer: put your animation in
setInterval(function(){
    Fishv1.animate({
        "left": leftPos,
        "top": topPos
    }, 18000, animatenewfish(idgenerated));
},18000);

so it will be called after each 18000 milliseconds.
Comment: As i can see OP is calling  `animatenewfish(idgenerated);` function on click.
Answer: change code Where you are calling your function
This code will call function every 500 ms.
  /*Jquery Code*/
  var idgenerated=0;
  $('.post-button').on('click',function(e){

    //$('#container img:last-child').append('

');
    $('#rightarrow').after('

');
    $('.pop-up-selectCategory').hide();
    $('.oyster').removeClass('oyster-click');
    setInterval(function() { animatenewfish(idgenerated); }, 500);
    idgenerated++;

});

Answer: The animate takes an optional callback
Fishv1.animate({
    "left": leftPos,
    "top": topPos
}, 18000, animatenewfish(idgenerated));

How can I loop an animation continuously in jQuery?

Loop/Repeat jQuery animation


Coloring points based on variable with R ggpairs

Question: I'm trying to reproduce the figure in https://tgmstat.wordpress.com/2013/11/13/plot-matrix-with-the-r-package-ggally/ with the code
require(GGally)
data(tips, package="reshape")
ggpairs(data=tips, title="tips data", colour = "sex")

However, in the plot I get the points are not colored based on sex, instead they are all the same color.  I get the following warning

Warning message:
  In warn_if_args_exist(list(...)) :
   Extra arguments: 'colour' are being ignored.  If these are meant to be >aesthetics, submit them using the 'mapping' variable within ggpairs with >ggplot2::aes or ggplot2::aes_string.

I've tried adding ggplot2::aes(colour = sex), but that did not work either.
Does anyone else here have the same problem?  I'm using R version 3.3.1 and GGally_1.2.0.
Thanks.
Comment: what does "did not work" mean?
Comment: @BenBolker I meant that it did not color the points based on the category.  I see your solution below and it worked for me!  Thanks a lot!
Answer: GGally has been under fairly rapid development, so it's not surprising that a blog post from 2013 has out-of-date code.  When I run your code with GGally 1.2.0 I get the same warning.  It works for me if I add the mapping:
require(GGally)
data(tips, package="reshape")
g1 <- ggpairs(data=tips, title="tips data",
  mapping=ggplot2::aes(colour = sex),
  lower=list(combo=wrap("facethist",binwidth=1)))

Following the wiki page for the wrap() incantation to stop complaints about needing to set binwidth in stat_bin ...
Comment: See also [this answer](https://stackoverflow.com/a/46964952/2052738) if you want to change those default colours with a manual scale (`wrap` won't accept `manual_colour_scale`).


RHEL6: httpd can't bind to port

Question: We have RHEL 6.5 server which serves as local YUM server and uses httpd for the purpose. It's running on port 6809. And until yesterday it was running fine. One of my colleague was doing some additional deployment on different server which is supposed to use the YUM server, but the yum couldn't connect. He admits, that he was also doing some work on the YUM server, but he's not aware of doing something related to httpd configuration.
So we realized that the httpd on the YUM server isn't running and refuses to start:
# service httpd start
Starting httpd: (98)Address already in use: make_sock: could not bind to address 172.29.84.41:6809
no listening sockets available, shutting down
Unable to open logs
                                                           [FAILED]

We've already checked that the port 6809 isn't occupied with lsof and netstat:
lsof -iTCP -sTCP:LISTEN -P -n

and
netstat -tupan | grep -Ei LISTEN

All clear, no other process.
We've also greped for Listen in /etc/httpd directory and there is only single directive with 6809 port:
httpd# grep -Ri listen *
conf/httpd.conf:# Listen: Allows you to bind Apache to specific IP addresses and/or
conf/httpd.conf:# Change this to Listen on specific IP addresses as shown below to
conf/httpd.conf:#Listen 188.8.131.52:80
conf/httpd.conf:#Listen 80
conf.d/ssl.conf:# When we also provide SSL we have to listen to the
conf.d/ssl.conf:#Listen 443
conf.d/yum.conf:Listen yum-server:6809
logs/test.log:read(4, "Listen yum-server:6809\nServe"..., 4096) = 496
logs/test.log:listen(3, 511)                          = 0
logs/test.log:write(2, "no listening sockets available, "..., 46no listening sockets available, shutting down
Binary file modules/mod_info.so matches
Binary file modules/mod_wsgi.so matches
Binary file modules/mod_proxy_ftp.so matches
Binary file modules/mod_cgid.so matches

So it isn't a duplicate.
The IP is local to the server.
No httpd process is running either.
We've also reinstalled the httpd RPM.
SELinux isn't running:
# sestatus
SELinux status:                 disabled

Please, what else could be wrong?
Thank you very much for your advices.
Add 2:
To @André Fernandes:
# lsof -n -P -i :6809
# find /etc/httpd -type f | xargs grep Listen
/etc/httpd/conf.d/ssl.conf:#Listen 443
/etc/httpd/conf.d/yum.conf:Listen yum-server:6809
/etc/httpd/conf/httpd.conf:# Listen: Allows you to bind Apache to specific IP addresses and/or
/etc/httpd/conf/httpd.conf:# Change this to Listen on specific IP addresses as shown below to
/etc/httpd/conf/httpd.conf:#Listen 188.8.131.52:80
/etc/httpd/conf/httpd.conf:#Listen 80

To @MadHatter I've shortened the output and removed real names. But the alias yum_server is there:
# cat /etc/hosts
# Do not remove the following line, or various programs
# that require network functionality will fail.
127.0.0.1       localhost.somewhe.re localhost trap-host
172.29.84.41    <FQDN and name> yum-server <other aliases>
...

Add 3:
The ip addr show output:
# ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
2: eth0: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP> mtu 1500 qdisc mq master bond0 state UP qlen 1000
    link/ether 3c:4a:92:ed:c0:28 brd ff:ff:ff:ff:ff:ff
3: eth1: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP> mtu 1500 qdisc mq master bond0 state UP qlen 1000
    link/ether 3c:4a:92:ed:c0:28 brd ff:ff:ff:ff:ff:ff
4: eth2: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP> mtu 1500 qdisc mq master bond1 state UP qlen 1000
    link/ether 68:b5:99:c6:42:4c brd ff:ff:ff:ff:ff:ff
5: eth3: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP> mtu 1500 qdisc mq master bond1 state UP qlen 1000
    link/ether 68:b5:99:c6:42:4c brd ff:ff:ff:ff:ff:ff
6: eth4: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP> mtu 1500 qdisc mq master bond2 state UP qlen 1000
    link/ether 68:b5:99:c6:42:4e brd ff:ff:ff:ff:ff:ff
7: eth5: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP> mtu 1500 qdisc mq master bond2 state UP qlen 1000
    link/ether 68:b5:99:c6:42:4e brd ff:ff:ff:ff:ff:ff
8: bond0: <BROADCAST,MULTICAST,MASTER,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
    link/ether 3c:4a:92:ed:c0:28 brd ff:ff:ff:ff:ff:ff
    inet 172.29.84.41/26 brd 172.29.84.63 scope global bond0
9: bond1: <BROADCAST,MULTICAST,MASTER,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
    link/ether 68:b5:99:c6:42:4c brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.1/24 brd 192.168.1.255 scope global bond1
10: bond2: <BROADCAST,MULTICAST,MASTER,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
    link/ether 68:b5:99:c6:42:4e brd ff:ff:ff:ff:ff:ff
    inet 10.1.212.71/24 brd 10.1.212.255 scope global bond2

Comment: Firstly, you mean duplicate, not duplicit (which is something completely different).  Secondly, what you report doesn't rule out overlapping Listen directives; we need to *see what you see*, not merely be told what you think you know.  Editing into your question the output of `grep -i listen /etc/httpd/conf/httpd.conf /etc/httpd/conf.d/*` would be more dispositive.  Thirdly, the same is true for other things you think you know.  I'm personally very suspicious of SELinux, so I'd like to see *how* you think you've established that it's not the cause.  Show your evidence.
Comment: Possible duplicate of https://serverfault.com/questions/875500/unable-to-stop-an-invisible-socket-on-port-80
Comment: Similar, but not duplicate. Even if we tried to change the port to different, httpd still reports that it can't bind.
Comment: Please read the answer on the linked question. The problem was not the port, but multiple bind directives on the apache config.
Comment: Yes, that's what we've checked as well. It's in the original question: "We've also greped for Listen in /etc/httpd directory and there is only single directive with 6809 port. So it isn't duplicit"
Comment: If you stop your yum httpd instance and do `lsof -n -P -i :6809`, do you get any output? also search recursively through the configs with `find /etc/httpd -type f | xargs grep Listen`.
Comment: @MadHatter I understand, we could have missed something. I've added grep and sestatus outputs into the question.
Comment: Thanks, that deals with my SELinux suspicions.  Could you show how you know that the server has an ip address to which the name `yum-server` resolves?
Comment: @AndréFernandes Outputs have been included.
Comment: @MadHatter I've attached digest of the /etc/hosts
Comment: Thanks, that shows what address the name is likely (though not guaranteed, absent `nsswitch.conf`) to resolve to, but it doesn't prove the server has that address.  Could we get the output of `ip addr show`?
Comment: @MadHatter The ip addr show output has been added. And in the /etc/nsswitch.conf, there is "hosts:      files dns"
Comment: Thanks, I agree that box is ticked.  I'm sorry to have to go through all the basics again, but that's the nature of the enquiry.  Could we see that when the web server is down (ie, now) and you, from the server itself, do `telnet 172.29.84.41 6809`, you get `Connection refused`?
Answer: We've found the reason. It was hidden in the /etc/hosts. The IP and all the line content was there listed twice. Among other entries required by our products, there was the entry added again. When we commented out the second entry, httpd started to behave as expected and stopped double-bind attempts.

RHEL6: httpd can't bind to port


Prove $P(A|B)=P(A\cap B)/P(B)$?

Question: I've been doing some learning for Native Bayes classification. I came across this formula, but I'm having trouble remembering it because I don't know how to get this formula. Can anyone explain how to get ${\displaystyle P(A|B)={\frac {P(A\cap B)}{P(B)}}}$?
Comment: $$P(A\mid B) = \frac{P(A\cap B)}{P(B)}$$ is the universally accepted _definition_ of what $P(A\mid B)$ means, and there is no way to "get this formula" unless you have some _alternative_  definition of the meaning of $P(A\mid B)$ from which we could arrive at $P(A\mid B) = \frac{P(A\cap B)}{P(B)}$.
Comment: My answer [here](http://stats.stackexchange.com/a/239042/127790) has some pictures that might help.
Answer: As already pointed out in the comment, the statement
$$
{\displaystyle P(A|B):={\frac {P(A\cap B)}{P(B)}}}
$$
is the very definition of the conditional probability. Check for example here on wikipedia for an overview.
If you have trouble to remember the definition,

maybe try to imagine how you would try to literally condition on something (event).
how would you write such an expression, if you would condition on the whole event space $\Omega$ - what would you expect as an outcome
and for the peace of mind, show that ${\displaystyle P(\cdot|B):={\frac {P(\cdot\cap B)}{P(B)}}}$ is indeed a probability measure itself

Prove $P(A|B)=P(A\cap B)/P(B)$?


Colliding staccato marks and ties

Question: In Lilypond 2.14.2, I've got two staccato eighth notes connected by a tie:
d'8 \staccato ~ d' \staccato

Unfortunately, the ends of the tie end right at the dots of the staccato, making it look a bit like a smiley face.
Is there a way to offset the tie down a bit to separate them?
Answer: It may be very well worthwhile to try d'8-.( d'-.), that's to say, use a slur instead of a tie.
Comment: I think there's a good chance that this was what the op intended anyway. To tie two staccato notes seems strange to me.
Comment: I had thought so myself. The staccato marks negate the tie, but staccato under a slur is the usual notation for a *jeté* stroke in violin music.
Comment: Confusing ties and slurs is a very common beginner's mistake with any music notation program., and since Lilypond is focused on notation not playback, you don't get instant feedback that a tie here would play back wrongly.

Colliding staccato marks and ties