WireGuard: 2 client peers on the same server with Internet connection and port forwarding

Question: Dear ServerFault community,
I have recently bought a home-server. I did not want to host any content on my office IP (126.96.36.199) and I, therefore, bought an OVH VPS with 4 IPs and created a WireGuard tunnel to use the VPS' IP as the homeserver IP.
OVH VPS also forwards all the ports to my homeserver.
I am currently using 2 of the 4 OVH VPS' IPs (220.127.116.11) and (220.127.116.11).
I created two WireGuard tunnels on the VPS on different subnets. One on 10.0.0.0 and one on 10.1.0.0.
My AIM was to achieve a config so that listening to 10.0.0.2 would resolve to 184.108.40.206 and listening to 10.1.0.2 would resolve to 18.104.22.168.
This does work for the first tunnel and for the second tunnel when running by themsleves on AllowedIPs = 0.0.0.0/0.
The problem is that when running togheter on AllowedIPs = 0.0.0.0/0 Internet connection stops.
I tried changing WG1's Allowed IPs to 10.1.0.0/24 but then a WG1 has no internet connection working.
Here are my configuration files:
Server WG0 (OVH VPS):
[Interface]
Address = 10.0.0.1/24
ListenPort = 51821
PrivateKey = {CENSORED}

### Client vpn
[Peer]
PublicKey = {CENSORED}
PresharedKey = {CENSORED}
AllowedIPs = 10.0.0.2/32

Server WG1 (OVH VPS):
[Interface]
Address = 10.1.0.1/24
ListenPort = 51822
PrivateKey = {CENSORED}

[Peer]
PublicKey = {CENSORED}
PresharedKey = {CENSORED}
AllowedIPs = 10.1.0.2/32

OVH VPS' IPTables configuration:
# Generated by iptables-save v1.8.7 on Tue May 31 15:25:37 2022
*filter
:INPUT ACCEPT [1698:235639]
:FORWARD ACCEPT [1053:163056]
:OUTPUT ACCEPT [1451:166474]
:f2b-sshd - [0:0]
COMMIT
# Completed on Tue May 31 15:25:37 2022
# Generated by iptables-save v1.8.7 on Tue May 31 15:25:37 2022
*nat
:PREROUTING ACCEPT [435:15811]
:INPUT ACCEPT [428:15399]
:OUTPUT ACCEPT [32:2255]
:POSTROUTING ACCEPT [119:6298]
-A PREROUTING -d 18.104.22.168/32 -p tcp -m tcp -m multiport --dports 1000:51820 -j DNAT --to-destination 10.0.0.2
-A PREROUTING -d 22.214.171.124/32 -p tcp -m tcp -m multiport --dports 51826:65534 -j DNAT --to-destination 10.0.0.2
-A PREROUTING -d 184.108.40.206/32 -p udp -m udp -m multiport --dports 1000:51820 -j DNAT --to-destination 10.0.0.2
-A PREROUTING -d 22.214.171.124/32 -p udp -m udp -m multiport --dports 51826:65534 -j DNAT --to-destination 10.0.0.2
-A PREROUTING -d 22.214.171.124/32 -p tcp -m tcp -m multiport --dports 21,22,80,25,995,110,443,465,993,143 -j DNAT --to-destination 10.0.0.2
-A PREROUTING -d 18.104.22.168/32 -p udp -m udp -m multiport --dports 21,22,80,25,995,110,443,465,993,143 -j DNAT --to-destination 10.0.0.2
-A PREROUTING -d 188.8.131.52/32 -p tcp -m tcp -m multiport --dports 1000:51820 -j DNAT --to-destination 10.1.0.2
-A PREROUTING -d 188.8.131.52/32 -p tcp -m tcp -m multiport --dports 51826:65534 -j DNAT --to-destination 10.1.0.2
-A PREROUTING -d 184.108.40.206/32 -p udp -m udp -m multiport --dports 1000:51820 -j DNAT --to-destination 10.1.0.2
-A PREROUTING -d 220.127.116.11/32 -p udp -m udp -m multiport --dports 51826:65534 -j DNAT --to-destination 10.1.0.2
-A PREROUTING -d 188.8.131.52/32 -p tcp -m tcp -m multiport --dports 21,22,80,25,995,110,443,465,993,143 -j DNAT --to-destination 10.1.0.2
-A PREROUTING -d 188.8.131.52/32 -p udp -m udp -m multiport --dports 21,22,80,25,995,110,443,465,993,143 -j DNAT --to-destination 10.1.0.2
-A POSTROUTING -s 10.0.0.2/32 -p tcp -m tcp -m multiport --sports 1000:51820 -j SNAT --to-source 18.104.22.168
-A POSTROUTING -s 10.0.0.2/32 -p tcp -m tcp -m multiport --sports 51826:65534 -j SNAT --to-source 22.214.171.124
-A POSTROUTING -s 10.0.0.2/32 -p tcp -m tcp -m multiport --sports 21,22,80,25,995,110,443,465,993,143 -j SNAT --to-source 188.8.131.52
-A POSTROUTING -s 10.0.0.2/32 -p udp -m udp -m multiport --sports 1000:51820 -j SNAT --to-source 188.8.131.52
-A POSTROUTING -s 10.0.0.2/32 -p udp -m udp -m multiport --sports 51826:65534 -j SNAT --to-source 18.104.22.168
-A POSTROUTING -s 10.0.0.2/32 -p udp -m udp -m multiport --sports 21,22,80,25,995,110,443,465,993,143 -j SNAT --to-source 18.104.22.168
-A POSTROUTING -s 10.1.0.2/32 -p tcp -m tcp -m multiport --sports 1000:51820 -j SNAT --to-source 184.108.40.206
-A POSTROUTING -s 10.1.0.2/32 -p tcp -m tcp -m multiport --sports 51826:65534 -j SNAT --to-source 18.104.22.168
-A POSTROUTING -s 10.1.0.2/32 -p tcp -m tcp -m multiport --sports 21,22,80,25,995,110,443,465,993,143 -j SNAT --to-source 22.214.171.124
-A POSTROUTING -s 10.1.0.2/32 -p udp -m udp -m multiport --sports 1000:51820 -j SNAT --to-source 22.214.171.124
-A POSTROUTING -s 10.1.0.2/32 -p udp -m udp -m multiport --sports 51826:65534 -j SNAT --to-source 22.214.171.124
-A POSTROUTING -s 10.1.0.2/32 -p udp -m udp -m multiport --sports 21,22,80,25,995,110,443,465,993,143 -j SNAT --to-source 22.214.171.124
COMMIT
# Completed on Tue May 31 15:25:37 2022

Homeserver WG0 configuration:
[Interface]
PrivateKey = {CENSORED}
Address = 10.0.0.2/32

[Peer]
PublicKey = {CENSORED}
PresharedKey = {CENSORED}
Endpoint = 184.108.40.206:51821
AllowedIPs = 0.0.0.0/0
#AllowedIPs = 10.0.0.0/24

Homeserver WG1 configuration:
[Interface]
PrivateKey = {CENSORED}
Address = 10.1.0.2/32

[Peer]
PublicKey = {CENSORED}
PresharedKey = {CENSORED}
Endpoint = 126.96.36.199:51822
AllowedIPs = 10.1.0.0/24

With my current (pasted here) configuration I can bind (for example Apache2) to 10.0.0.2 and it correctly resolves and allows people to access the server from 220.127.116.11, but when I bind to 10.1.0.2, the IP address 220.127.116.11 is not accessible from the internet from any port and the interface WG1 has no internet connection (eg. when attempting curl --interface wg1 ifconfig.co).
Thank you in advance for your time and help!
Comment: is this question related to a business environment and you are been a professional business administrator?
Comment: Yes @djdomi, the environment is business related, otherwise I would not ask on ServerFault… I just defined the server home-server as it is of relatively small dimensions, but as you can recall from the message it is installed in my office for a production environment.
Comment: and what kind of services should be running? a Webserver is easier to use with a reverse proxy
Comment: I am aware of the possible idea of using a reverse proxy, but as I am going to host databases, docker, emails and anything that could become useful I have the necessity of tunnelling all the ports. @djdomi
Answer: The simplest thing to do would be to add masquerading to your VPS's iptables rules -- that would rewrite the source address of packets forwarded to your Homeserver to use the IP address of the VPS's WireGuard interface through which the packets were forwarded (10.0.0.1 for wg0, and 10.1.0.1 for wg1). This allows your Homeserver to use the routes wg-quick sets up in your default routing table to send traffic back through the correct interface.
To do that, add the following POSTROUTING rules to the end of your VPS's iptables config:
-A POSTROUTING -o wg0 -j MASQUERADE
-A POSTROUTING -o wg1 -j MASQUERADE

Then for your Homeserver's wg0.conf, use this for the VPS peer:
AllowedIPs = 10.0.0.0/24

And for your Homeserver's wg1.conf, use this for the VPS peer:
AllowedIPs = 10.1.0.0/24

However, if you need to preserve the original source IP addresses of external packets (like for logging or authentication etc on your Homeserver), masquerading won't work for you. Instead, you need to add some custom policy routing rules for custom route tables on your Homeserver that will send packets back from services bound to 10.0.0.2 through wg0, and 10.1.0.2 through wg1.
To do that, change your Homeserver's wg0.conf to this:
[Interface]
PrivateKey = {CENSORED}
Address = 10.0.0.2/32
Table = 100
PreUp = ip rule add from 10.0.0.2 table 100 priority 123
PostDown = ip rule del from 10.0.0.2 table 100 priority 123

[Peer]
PublicKey = {CENSORED}
PresharedKey = {CENSORED}
Endpoint = 126.96.36.199:51821
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25

And your Homeserver's wg1.conf to this:
[Interface]
PrivateKey = {CENSORED}
Address = 10.1.0.2/32
Table = 101
PreUp = ip rule add from 10.1.0.2 table 101 priority 124
PostDown = ip rule del from 10.1.0.2 table 101 priority 124

[Peer]
PublicKey = {CENSORED}
PresharedKey = {CENSORED}
Endpoint = 188.8.131.52:51822
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25

Comment: I tried what you suggested but with the table set to 100 and 101 WG0 and WG1 do not work at all, not even one by one. They do not handshake nor connect to the server.
Comment: You probably also need a `PersistentKeepalive` setting in your Homeserver configs if you're relying on the Homeserver to open up the WireGuard connections to the VPS (I will edit my answer to add that). And if you're testing by initiating connections from the Homeserver, make sure you explicitly specify the appropriate WireGuard interface as the connection source (eg `ping -I wg0 10.0.0.1`).
Comment: Thank you for your help, solved!


TRRS > 2 x TRS bypass to amplify laptop headphones not working, headphones channel mute

Question: I'm trying to amplify the headphones output of my laptop as the volume is too low during calls and such. The laptop has a combined TRRS female 3.5 jack output. I've used a splitter to split that into separate headphones and mic TRS, then using a reverse splitter I've connected the microphone directly and diverted the headphones to an amplifier (see picture).
The setup works correctly without the amplifier (ie if I connect the two inputs to the two outputs). Also, with the amplifier in the mix, the mic works fine. The issue is that when I connect the amplifier I can't hear anything from the headphones. Connecting normal headphones with a TRS jack to the amp output I can hear stereo sound and at the same time use the mic from the headset, it's just that the headset doesn't seem to receive sound when connected to the whole setup.
What am I doing wrong? Each component works well individually, so I've (perhaps prematurely) excluded a channels crossing problem...
Answer: The mic should only be a TS - it's mono. Simplest would probably be to take all the barrels off & actually check everything is managing to physically connect to the right connections. A continuity meter could be useful if you have one. If they don't match, grab a soldering iron & start swapping plugs. Make sure you get an accurate pin-out diagram of the compy & amp first. [though if the headset works fine when directly connected, you could use that as your pin-out 'map' for everything else.]
Comment: Not sure why the mic out is a TRS, maybe compatibility? All images are exactly the component I'm using, so that's the way it comes from factory...
Comment: I really don't know - it seems rather odd. First thing Id be doing is seeing exactly how they're wired & whether you're getting continuity. You might end up with either your soldering iron out, or one of those "works if I pull the plug out a bit" solutions.
Comment: The R on the mic connector could be DC voltage to power the microphone
Comment: @Duston - not sure how the logic behind that works. TRRS - one is common, ground, two are stereo out, one is mono in - where does the 5th come from?
Answer: You say "each component works well individually".  Let's assume that your 3.5mm TRS-cable has been tested and that there is no problem with the adapters as such.
In that case there are still several opportunities for problems:
a) the conventions for ground and microphone input that your adapters use differ from the conventions your laptop uses.  Ground can be on the second ring, or it can be on shield.  You wouldn't notice from plugging adapters 1:1 (apart from the adapter cables being quite more susceptible to electromagnetic noise injection like from an active mobile phone).  You wouldn't notice from running only headphones (then the possibly swapped connections are shorted anyway).  If you'd plug the headphone adapters into one another for the headphones but keep the microphone connections unconnected and then plug the headset into this combination, what you should be seeing (and hearing) is that the microphone does not work but the headphones do work.
b) the computer tries figuring out things in a "smart" manner and does not see a load on the headphone connectors because the headphone amp has a reasonably high input impedance.  It may then either use the normal loudspeakers, or may use the output as a "line out".  Usually you should still see some output, but there may be separate volume and/or mute controls for line-out and/or the normal speakers, and those are substituted instead.
c) the computer even tries to figure out whether the TRRS connection has the ground on the second R and the mic on S or vice versa, and without the load from the headphones it fails and does something wrong.
You can probably narrow things down a bit by using a headphone splitter for connecting some arbitrary headphone in parallel with your headphone amplifier input.
Comment: In saying "each component works well individually", I meant I've tested the whole setup connecting the amp out to a normal pair of headphones and keeping the headset microphone connected, and everything works: I get the mic signal from the headset in the computer and I get the sound output (stereo, checked) in the headPHONES.
Comment: I've checked continuity with a multimeter and from the laptop male TRRS jack to the 6.35 mm adapter at the amp input the config is: T > T, R > R, R > S, S > nothing. So indeed a ring on the TRRS is going to the sleeve of the TRS at the amp input. Would that be the issue? That the second ring is being passed to the sleeve and no sleeve is passed through? But then, how is it working with the headPHONES connected?
Answer: wouldnt a Helm DB12 AAAMP solve this problem?  inputs and outputs are trrs and the microphone functionality passes through this compact amp even when the unit is off.


Por que mesmo com margin 0 e padding 0 ainda existe espaço entre os elementos?

Question: Eu tenho 3 botões um do lado do outro e queria que ficassem com 1px de margin apenas entre eles mas ta ficando muito mais:

O html:

TRUCO!

        <button>SIM</button>
        <button class="truco">SEIS!</button>
        <button>NÃO</button>

Aqui o css:
* {
    border: 0;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}
button {
    background: #f00;
    cursor: pointer;
    display: inline-block;
    font: 24px "Alfa Slab One", cursive;
    margin: 1px;
    text-shadow: 1px 1px #fff;
    width: 150px;
}
.truco {
    background: #ff0;
}

Answer: Isto é apenas a maneira como os elementos inline-block se comportam.
Estes espaçamentos são o mesmo que espaçamentos entre palavras. Se colocarmos os elementos todos juntos (palavras todas juntas) não iremos ter nenhum espaço entre os elementos.

Quebras de linha também contam como espaçamento entre os elementos inline-block.

Dito isto, se removermos os espaços (quebras de linhas) entre os botões, este comportamento irá desaparecer:

* {
    border: 0;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}
button {
    background: #f00;
    cursor: pointer;
    display: inline-block;
    font: 24px "Alfa Slab One", cursive;
    margin: 1px;
    text-shadow: 1px 1px #fff;
    width: 150px;
}
.truco {
    background: #ff0;
}

TRUCO!

        <button>SIM</button><button class="truco">SEIS!</button><button>NÃO</button>

TRUCO 2!

        <button>SIM</button>
        <button class="truco">SEIS!</button>
        <button>NÃO</button>

Existem também outras maneiras de remover estes espaços, como adicionar uma margem negativa aos elementos onde a propriedade inline-block foi aplicada, entre outros métodos. Podes ler este artigo que eu criei sobre este tópico há uns anos atrás neste link: Estranho espaçamento entre elementos inline-block


Infinite sequence and power series

Question: infinite sequence $a_{n}$
where $$\lim_{n\to \infty} |na_{n}|=1101 $$
Find R of convergence of the power series $$\sum_{n=1}^\infty a_{n}x^n$$
Anyone can guide me for this question?
Thank you so much!
Comment: What can we say about $\left|\frac{a_{n+1}}{a_n}\right|$ for large $n$?
Comment: @AndréNicolas 1? What does that imply? ratio test?
Comment: The limit of the ratios is $1$, That implies the radius of convergence is $1$ (Ratio Test).
Answer: we are looking for when $\lim\limits_{n\rightarrow\infty}|x|\left|\frac{a_{n+1}}{a_n}\right|<1$
Now from the first equation, it follows that $\lim\limits_{n\rightarrow\infty}|a_n|=\lim\limits_{n\rightarrow\infty}\frac{1101}{n}$, and so, similarly, $\lim\limits_{n\rightarrow\infty}|a_{n+1}|=\lim\limits_{n\rightarrow\infty}\frac{1101}{n+1}$. Thus,
$$|x|\lim\limits_{n\rightarrow\infty}\left|\frac{a_{n+1}}{a_n}\right|=|x|\lim\limits_{n\rightarrow\infty}\frac{1101/(n+1)}{1101/n}=|x|$$
Thus you need $|x|<1$, Or a radius of convergence of $1$.
Answer: Hint. As $n \to \infty$, you have
$$
|a_n| \sim \frac{1101}n
$$ then, by the comparison test, your initial series has the same radius of convergence as
$$
\sum_{n\geq 1} \frac{x^n}n =-\log (1-x)
$$ that is $R=1$.
Answer: $R=\lim {\dfrac{a_n}{a_{n+1}}}=\dfrac{na_n}{(n+1)a_{n+1}}\times \dfrac{n+1}{n}=1$ as $n\rightarrow \infty$
Comment: Would have been happy if downvoters could speak
Answer: The root test will
also show that
$R=1$
since
$n^{1/n}
\to 1$
and
$1101^{1/n} \to 1$.
Answer: It can be proven that the power series and its derivative have the same radius of convergence. So consider the derivative of the above series $\displaystyle \sum_{n=1}^\infty na_nx^{n-1}, b_{n-1} = na_n$, and using root test:
$L = \displaystyle \lim_{n\to \infty} \sqrt[n-1]{\left|b_{n-1}x^{n-1}\right|}= |x|\cdot \displaystyle \lim_{n\to \infty} \sqrt[n-1]{na_n}= |x|$. And the series converges iff $|x| < 1$, thus $R = 1$.

Infinite sequence and power series


Proving that $a_n=\frac{n^2+2n+6}{n^3-3}\to 0$ as $n\to\infty$

Question: $$a_n=\frac{n^2+2n+6}{n^3-3}$$
So I want to show that "$a_n\to a\iff\forall \epsilon>0,\quad\exists N\in\mathbb{N}:n\geq N\implies |a_n-a|<\epsilon$"
Then my rough working:
$|a_n-0| =\left|\frac{n^2+2n+6}{n^3-3}\right|<\epsilon$
Estimate $\frac{n^2+2n+6}{n^3-3}<\frac{b_n}{c_n}$
Require $b_n>n^2+2n+6$, so choose $b_n=2n^2>n^2+2n+6$ for $n\geq 4$
Require $c_n<n^3-3$, so choose $c_n=\frac{n^3}{2}<n^3-3$ for $n\geq 2$
Then let $N=\frac{2n^3}{n^3/2}=\frac{4}{n}$
So now the proof:
$$\text{Fix}\quad \epsilon>0.\quad\text{Pick}\quad N:N>\frac{4}{n}\quad\text{and}\quad N\geq 4$$
$$\implies \forall n\geq N,\quad |a_n-0|=\left|\frac{n^2+2n+6}{n^3-3}\right|<\frac{4}{n}\leq\frac{4}{N}\leq\epsilon$$
Is this correct? Is it completely rigorous? I've just started doing analysis on my own, so please point out if anything is wrong/not conventional so that I can get into good habits at the start. Thanks for any help.
Comment: $N$ can't be related to $n$. You need to express it with the arbitrary $\epsilon$
Comment: @Dror, I see, so if I instead write "Pick $N>\frac{4}{\epsilon}$", does my argument hold?
Comment: $N$ must be fixed "in response" to $\epsilon$ being arbitrary and fixed
Comment: Also $n$ is overloaded and it hurts ;)
Comment: @Dror I don't understand what '$n$ is overloaded' means. Also, by fixing $\epsilon >0$ and then choosing $N>\frac{4}{\epsilon}$, is my proof then complete?
Answer: You should probably specify how you pick $N$ depending on your $\epsilon$, and then use the Archimedean property if you want to be completely rigorous (to show that for all $\epsilon>0$ you find $N$ s.t. $\frac 4 N < \epsilon$).
Alternatively, you could just multiply denumerator and nominator by $n^{-3}$ and use some theorems that allow you to compute limits of sums and fractions.
Answer: An other proof could use L'Hopital's rule. This should be very quick.
$$ f(n) = \frac{n^2 + 2n + 6}{n^3 - 3} ; f^"(n) = \frac{2}{6n} = \frac{1}{3n}$$
which seems to be much easier to prove that this goes to zero as n goes to infinity...
Comment: You made $f$ a function of $x$, not $n$.
Answer: If i were you, i would just multiplicate numerator and denominator by $1/n^2$ both, so that: $a_n = (1 + 2/n + 6/n^2)/(n -3/n^2)$. From the defenition of infinite number, we have $2/n$, $6/n^2$  and $-3/n^2$ all equal to 0: $a_n = (1 + 0 + 0)/(n + 0 + 0) = 1/n$ which is 0 from the same defenition.
Answer: Without getting into the concrete sequence:
You don't really want to show that first two sided implication, as it is just restating the definition.
What does it say, though?
You can read it like:
"If An infinite sequence $a_n$, indexed by $n$ (for poisition), converges to the value $a$ then there is always a position in the sequence for which all of the further elements are closer than whatever distance you wish, to $a$"
So:

The capital $N$ is originally just about the position in the sequence and not the values.
$N$ has to be expressed (If it is by an inequality, then you need more capitals) with $\epsilon$ and with "just numbers".
The mission is to find an experession closer than you originally "intended"

In your concrete example you can just shamelessly divide both the numerator and the denominator by the greatest power of $n$ in it. Then you need to specify many excuses about just usage of arithmetic of limits.
Alternatively you can and should use all the ordinary "re-expression" tricks you have to get a nice and perhaps long ineqality chain that ends and ends obviously. This is essentially what you chose to do. But, you can do it with much less sweat.


Why are the two definitions of reflective subcategory equivalent?

Question: From Wikipedia: Let $A \subseteq B$, where $B$ is a category and $A$ is a full subcategory. On Wikipedia there are two equivalent definitions of reflective subcategory:

the inclusion functor $i$ has a left adjoint $F : B \rightarrow A$
For any $b \in B$, there is an $a_b \in A$ and a morphism $t : b \rightarrow i(a_b)$, such that for any $a \in A$ and morphism $f : b \rightarrow i(a)$, there is a unique morphism $\tilde{f} : a_b \rightarrow a$ such that $i(\tilde{f}) \circ t = f$

I'm trying to prove that the first definition implies the second. Suppose $F$ is left adjoint to $i$. Let $\tau_{a,b}$ be the bijections $Mor_A(F(b), a) \rightarrow Mor_B(b, i(a))$.  I think that $a_b = F(b)$, and the morphism $t : b \rightarrow i(F(b))$ is the unit $\eta_b$.
I'm also guessing that $\tilde{f} = \tau_{a,b}^{-1}(f)$. Therefore, it is required to prove $\tau_{a,b}^{-1}(f) \circ \eta_b = f$.
I'm stuck trying to prove this. Both $\tau$ and $\eta$ appear in this. I'm also not sure how to use the fact that $i$ is an inclusion from a subcategory, because I don't think this theorem is true for a general adjoint pair.
Comment: Small comment. The notations $Mor_A(x,y)$ or $Hom_A(x,y)$ are quite archaic. Usually $A(x,y)$ is used instead. Cheers!
Answer: $\newcommand{\A}{\mathsf{A}}\newcommand{\B}{\mathsf{B}}\require{AMScd}$You say:

I don't think this theorem [$\tau_{a,b}^{-1}(f)\circ\eta_b=f$] is true for a general adjoint pair

This can't even be stated for an adjoint pair since it relies on the fact that $i(x)=x$ and $i(F(x))=F(i(x))$ making $\epsilon$ composable with $\eta$, which isn't usually possible.
However, the general theorem at play here is true: if $L:\B\rightleftarrows\A:R$ are a left-right pair of adjoint functors then for any $b\in\B$ there is an $a_b\in\A$ with an arrow $t:b\to R(a_b)$ such that for all $a\in\A$, $f:b\to R(a)$, there is a unique $\tilde{f}:L(b)\to a$ with $R(\tilde{f})\circ t=f$.
In your case, $R(f)=f$ and $R(a)=a$ etc. so the equation $\tau_{a,b}^{-1}(f)\circ\eta_b=f$ agrees with this but has a minor abuse of notation (strictly, we should write $i(\tau_{a,b}^{-1}(f))\circ\eta_b=f$).
You pick $a_b:=L(b)$ and $t=\eta_b$. You pick $\tilde{f}:=\epsilon_a\circ L(f)$ and you find out that: $$R(\tilde{f})\circ t=R(\epsilon_a)\circ RL(f)\circ\eta_b=R(\epsilon_a)\circ\eta_{R(a)}\circ f=f$$And conversely if $\tilde{f}$ has that property then $\epsilon_a\circ L(f)=\epsilon_a\circ LR(\tilde{f})\circ L(\eta_b)=\tilde{f}\circ\epsilon_b\circ L(\eta_b)=\tilde{f}$ so this arrow $\tilde{f}$ is unique. At least, if you define adjunctions by a pair of natural transformations satisfying the triangle identities.
If you use the definition, "there exists a family of isomorphisms $\tau_{a,b}:\A(L(b),a)\cong\B(b,R(a))$ which are natural in both variables" then we can obviously say there is a unique $\tilde{f}:=\tau_{a,b}^{-1}(f)$ which makes $\tau_{a,b}(\tilde{f})=f$, so it suffices to prove that $\tau_{a,b}(g)=R(g)\circ\eta_b$ for all $g:L(b)\to a$, where $\eta_b=\tau_{L(b),b}(1_{L(b)})$.
But, we can just recognise this as the Yoneda lemma applied to the natural transformation $\tau_{\bullet,b}:\A(L(b),-)\implies\B(b,-)\circ R$.
$$\begin{CD}1@>\mathrm{id}_{L(b)}>>\A(L(b),L(b))@>\A(1,g)>>\A(L(b),a))\\@V=VV@V\tau_{L(b),b}VV@VV\tau_{a,b}V\\1@>>\eta_b>\B(b,RL(b))@>>\B(1,R(g))>\B(b,R(a))\end{CD}$$By naturality and by definition this diagram commutes, but it is stating precisely the equation $\tau_{a,b}(g)=R(g)\circ\eta_b$.
Comment: That solves it, that $\eta$ (defined as $\tau_{a, F(a)}(id_{F(a)}$) is a natural transformation was what I was missing. I checked that.
Comment: Thank you, there is one thing that I don't understand: Does $RL(f) \circ \eta_b = \eta_b \circ f$? It's used in an equation in the middle. Why is this true? Also, did you mean $\eta_{R(a)}$ on the right hand side? Otherwise I can't get composition to work. The codomain of $f$ is $R(a)$ and the domain of $\eta_b$ is $b$.
Comment: @NaomiZhang Yes, $\eta$ is a natural transformation $\mathrm{Id}\implies RL$. To explain why that's true is tricky without more context. There are at least *three* ways to define "adjunction". In one of them, $\eta$ is natural *by definition*: in the others, you need to prove it, but the method of proof is different depending on your starting definition. So I should ask you to say what the definition of adjunction is that you're using. Btw I showed *two* ways to calculate $\tau_{a,b}(g)=R(g)\circ\eta_b$ using two different starting definitions.
Comment: And yes I did mean $\eta_{R(a)}$ that was a careless typo


How to change font_name property for lables in Kivy?

Question: I'm trying to create a label, specify some text for it and use some custom font, using the property "font_name" in the python file, not in kv file. here is the code:
python code:
some_text = bidi.algorithm.get_display(
        arabic_reshaper.reshape(<some_persian_text>))

MDLabel(text=some_text, size_hint=(None, None), font_name="fonts/Shabnam-Bold", size=(300, 100), pos_hint={'center_x': 0.5, 'center_y': .8}))

corresponding kv file:
<SomeScreen>:
    name: 'some_screen'
    AnchorLayout:
        id: main_layout
        size: self.width, self.height
        anchor_x: 'center'
        anchor_y: 'top'
        MDToolbar:
            id: main_toolbar
            title: "TITLE"
            # left_action_items: [["menu", lambda x: side_bar.set_state('open')]]
            left_action_items:[['arrow-left', lambda x: root.go_back()]]
            md_bg_color: app.theme_cls.primary_color
            elevation: 15

As you can see, I have set the Toolbar in the kv file and I'm trying to render some other content for it dynamically in python. The text of the label is in Persian(some right-to-left language spoken in Iran).The bidi library alongside arabic_reshaper enable the app to render right-to-left text. The problem is, when I do this totally in kv file (setting the text in python, creating the label in kv file and setting the text and font_name also in kv file), everything works fine. But when I do it in this way(creating and setting the label content and the font in py file), the font does not work properly and shows some nonsense:

How can I fix this? Thank you.
Answer: It seems that the problem can be solved using markup tags:
'[font = "path/to/font"]your text [/font]'


Use drush to download drupal core files directly into directory rather than subdirectory

Question: When you use drush dl normally, it will download drupal into a subdirectory ie: drupal-7.16
I would like to skip creating the subdirectory and just install the drupal root directory files into the pwd or destination directory.  ie: /var/www/install.php
Can this be done with drush commands?
Other shell workarounds also welcome and will be considered for answer status if this is impossible with drush.
Comment: Be aware that this is an insecure setup.  Check some of the comments below for an explanation of a more secure way to do this.
Answer: drush dl drupal --destination=/var --drupal-project-rename=www

Comment: Can you expand on how this is different than the other answers?
Comment: MPD: It's different because it actually comes closer to answering the question than Greg's answer.
Comment: Thanks lunitin! It IS the solution, but to correctly solve the question it would have to be. --destination=/var --drupal-project-rename=www
Answer: Drush usually creates a sub directory, But you can easily copy all the files from this sub directory "/var/www/drupal-7.12" to its upper folder "/var/www/" with this code
mv * .* ..

Answer: You can specify the name of the destination folder to download Drupal into via the --destination parameter.  For example:
$ cd /var
$ drush dl drupal --destination=www

Aside: Note that it's probably better to put your site in /var/www/mysite.org rather than directly in /var/www; someday, you might want to put a second site on the same server.
Comment: I would go further, and say put it in /var/www/mysite.org/docroot so you can put your private directory in /var/www/mysite.org/private, and make a /var/www/mysite.org/conf for any Apache includes you may need.  Changing all of this after the fact can be a pain.
Comment: FWIW, I use the same structure recommended by MPD in all of my Drupal sites.
Comment: --destination creates the subdirectory still.  The rest is not relevant to the question.


How to add a profile tab via views

Question: On the profile page that is /user/1 for e.g how to add tab MY ADS to be /user/1/myads?
Answer: Create a view page and add a menu item entry: "Default menu tab" to "Menu tab" and select "User Menu" in dropdown in your view.
Answer:
Create a view page
Change the path to: user/%user/myads
Change menu to 'Menu tab' and make sure the parent is '-- My account'

How to add a profile tab via views


Commit Transaction with Spring Data JPA

Question: I downloaded a Spring Data JPA example from here Accessing Data with JPA and it works as expected.
@SpringBootApplication
public class Application {

  private static final Logger log = LoggerFactory.getLogger(Application.class);

  public static void main(String[] args) {
    SpringApplication.run(Application.class);
  }

  @Bean
  public CommandLineRunner demo(CustomerRepository repository) {
    return (args) -> {
      // save a couple of customers
      repository.save(new Customer("Jack", "Bauer"));
      repository.save(new Customer("Chloe", "O'Brian"));
      repository.save(new Customer("Kim", "Bauer"));
      repository.save(new Customer("David", "Palmer"));
      repository.save(new Customer("Michelle", "Dessler"));

      // fetch all customers
      log.info("Customers found with findAll():");
      log.info("-------------------------------");
      for (Customer customer : repository.findAll()) {
        log.info(customer.toString());
      }
      log.info("");

      // fetch an individual customer by ID
      Customer customer = repository.findOne(1L);
      log.info("Customer found with findOne(1L):");
      log.info("--------------------------------");
      log.info(customer.toString());
      log.info("");

      // fetch customers by last name
      log.info("Customer found with findByLastName('Bauer'):");
      log.info("--------------------------------------------");
      for (Customer bauer : repository.findByLastName("Bauer")) {
        log.info(bauer.toString());
      }
      log.info("");
    };
  }

}

Then I tried to change from In-Memory database to a real one. For this I added in the current directory an application.properties file with a single line:
spring.datasource.url=jdbc:h2:C:/users/semaphor/H2Database;DB_CLOSE_ON_EXIT=FALSE

Now when I run the application, I can see that in the expected directory the database file is created.
Now I want to see that the customers are stored in the database and are still there when I restart the application. So I removed some lines where customers were saved in the database at the beginning but they are then not listen with findAll().
I suppose this transaction is not commited but I can't figure out how I can do this. Adding simply the annotation @EnableTranscationManagement to the Application class and @Transactional to the demo() method is not the solution.
What do I have to add to commit the transaction (if that is really the problem)?
Comment: check the creation time of the DB file, maybe it's recreate at startup.
Comment: This '@Transactional' might be ignored when placed there. Can you try externalizing the calls to your repository into a method in another class, and annotate '@Transactional' this method?
Comment: http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html#boot-features-creating-and-dropping-jpa-databases
Check your data with the H2 web console
Comment: Following KayKay suggestion you may want to create an external service annotated with '@Service' and '@Transactional' where you inject an '@Autowired' repository. As far as I remember '@Bean' annotation does not have any transactional capability.
Comment: @Mr_Thorynque I checked it, the file is not recreated.
Comment: @KayKay I'm unsure how to move it in an external class. How is then the method invoked?
Comment: @medveshonok117 I'm a beginner with spring, so I have no idea how to use '@Service', I will try to google that.
Comment: Although the file isn't recreated the schema is, as H2 is considered an embedded DB, at startup the existing schema is dropped and recreated. Hence your data is gone. Set the creation for the schema explicitly to update. The problem is not related to the working of the transaction but with the recreation of the schema.
Comment: @M.Deinum I added 'spring.jpa.hibernate.ddl-auto=update' to the application.properties file and that was the solution. Thank you!
Answer: See M. Deinum's comment below the question.
Adding
spring.jpa.hibernate.ddl-auto=update

to the application.properties was the solution.

Commit Transaction with Spring Data JPA


list colouring of a rather big graph

Question: See the following exercise from Introduction to Graph Theory by Douglas West:

I managed to show part a) easily, mainly because it is a symmetric problem. I showed it as follows:
Without loss of generality, colour the middle vertex by 1. Then the $\bar 1$-vertex connected to the middle vertex has to be either 2 or 4. If it is 2, then the lower segment can't be coloured. If it is 4, then the left segment can't be coloured.

However, in exercise b), I don't even know what is a good place to start. And I'm wondering if I could use the result of a) for b)?
I tried systemizing/generalising the colouring, but I ended up with too many cases. Could someone point me in the right direction?
Comment: https://arxiv.org/pdf/1709.07540.pdf oh wow, this graph was found by a field medalist 22 years ago
Comment: @JorgeFernández o that's so cool!! thanks for the reference
Answer: If the "extra" vertex is coloured $5$, then the left part is the graph from part a).
If the "extra" vertex is coloured $4$, then the second part is the graph from part a).
If the "extra" vertex is coloured $3$, then the right part is the graph from part a).
If the "extra" vertex is coloured $2$, then the third part is the graph from part a).
Comment: oh nice, I guess they split it up for a reason !

list colouring of a rather big graph


MySQL agrupar por mês e ano entre datas

Question: Tenho uma tabela chamda agenda em MySQL assim (a data está no banco de dados em formato date, coloquei no formato português apenas para ficar mais fácil o exemplo):

Eu preciso de uma consulta que me listem os meses e ano que tenham datas cadastradas entre o dia_inicio e o dia_termino, no exemplo da tabela acima o que seria listado seria:
01/2020
02/2020
03/2020
04/2020
05/2020
07/2020

Reparem que o mês 06 de 2020 não aparece, pois não tem dias cadastrados nesse mês.
Tentei algo assim:
SELECT * FROM agenda GROUP BY (BETWEEN agenda.dia_inicio AND agenda.dia_termino)

Sei que existe a função between, mas não é assim que se usa pelo visto. Como fazer?
Comment: Utilize um `GROUP BY YEAR(agenda.dia_inicio), MONTH(agenda.dia_inicio)`.
Answer: Tente da seguinte forma.
SELECT * FROM agenda where (BETWEEN agenda.dia_inicio AND agenda.dia_termino) GROUP BY MONTH(dia_termino), DAY(dia_termino)

Answer: A forma que você está fazendo não esta correto, priemiro o format da data deve ser "2020-03-03" (ANO-MES-DIA) para quer operações com data funcione. Depois se deve escolher uma coluna para se agrupar, até onde eu se não é possível agrupar por intervalo de datas, você deve fazer algo como:
SELECT * FROM agenda where (BETWEEN agenda.dia_inicio AND agenda.dia_termino) GROUP BY genda.dia_inicio

ou
SELECT * FROM agenda where (BETWEEN agenda.dia_inicio AND agenda.dia_termino) GROUP BY genda.dia_termino

Comment: A data está no formato certo, coloquei no formato português apenas para explicar. Mas no seu exemplo deu erro, o mesmo que o meu: Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'BETWEEN agenda.dia_inicio AND agenda.dia_termino) GROUP BY agenda.dia_inicio'

MySQL agrupar por mês e ano entre datas


How to specify the numbers of characters for teaser for views block?

Question: I know we can specify the specify limit for the teaser by going to content type -> manage display -> teasers. I have made the views block for teasers and I want to display only few lines for that content in particular views block and do not want to affect the stand treasure setting. So, is there any setting in Views which specify the teasers limit for the particular Views block?
Answer: On the view settings for the field, click on Rewrite results. Select * Trim this field to a maximum length and enter a value for the maximum allowed length.


Schwarz-Christoffel mapping onto infinite L-shaped region

Question: I'm trying to map the upper half plane onto the infinite L-shaped region
$$
\Omega = \{z = x+iy; \ x > 0, \ y > 0, \ \min(x,y) < 1 \}
$$
My first try is a Schwarz-Christoffel function
$$
F(w) = \int_0^w (\zeta+1)^{-1}\zeta^{-1/2}(\zeta-1)^{-1} \ d\zeta
$$
This guy looks promising, because the integrand seems to have the right turning angles at $\zeta = -1, 0, \text{ and}\ 1$; in addition $F(w)$ seems to satisfy the symmetry
$$
F(-x + iy) = i \overline{F(x + iy)}
$$
Unfortunately, the image appears to be scaled wrong (and lives in the third quadrant).
Question: How can I find the negative real constant by which to flip & scale it to the correct position?
Guess: Calculate $F(\infty)$ by integrating along the positive imaginary axis, then my multiplier will be $\displaystyle \frac{-\sqrt{2}}{|F(\infty)|}$.
Thanks for any tips, especially including a better way to approach the problem.
Comment: My book of conformal transformations says the following does the trick: $$F(z) = 2i\frac{\tanh^{-1}\sqrt{z} - \tan^{-1}\sqrt{z}}{\pi}+1+i$$
Comment: Another approach cut the region along the line of symmetry, from $0$ to $1+i$. Mark the cut as a dashed line. Map halfplane onto one half; then arrange for the dashed preimage to be, say $(-\infty,0)$, and reflect across it. With one more square root you have the map. However, it does not seem to offer advantages over what you are doing, because you also exploit symmetry in your solution. And the $\pi/4$, $3\pi/4$ angles make for a difficult integral.
Comment: You could use [Sage online](http://sagenb.org/)... `var('w')` then `g = (w+1)^(-1)*w^(-1/2)*(1-w)^(-1)*2/pi`, then `g.integral(w)`, and so on... Plotting will be a hassle, but there is an array of plotting functions. Just as Maple, Sage gets the branch of one of two logarithms wrong.
Comment: In a nutshell: wrong quadrant is your fault (should have used $(1-w)$), while wrong scaling is your software's fault, not taking the right branch of logarithm.
Comment: I don't have software, so in fact it's all my fault... ;)
Comment: @MikeMiller - Thanks for your help. See the comment below the answer.
Comment: @bryanj Glad to - cool to see where the book's closed form comes from!
Answer: So, you want to send $-1,0,1$ into $i\infty, 0, +\infty$, thus forming the outer boundary of the $L$-shape. The inner boundary will be formed by $(1,\infty)$ going to $(+\infty+i,1+i)$, and by $(-\infty, -1)$ going to $(1+i, 1+i\infty)$. Makes sense enough. Then the integral should be
$$F(w) = K\int_0^w (\zeta+1)^{-1}\zeta^{-1/2}(1-\zeta)^{-1} \ d\zeta \tag1$$
because we want $F'>0$ when $0<w<1$. Next, $K$ should be $2/\pi$ because when  crossing $w=1$ we pick up $-\pi i$ times the residue there (upper semicircle traced clockwise), and this amount is
$$-\pi i\, \operatorname{res}_{\zeta=1}(\zeta+1)^{-1}\zeta^{-1/2}(1-\zeta)^{-1} =  \frac{\pi i}{2}$$
Something like Maple will give you an antiderivative of (1) at once:
$$
F(w) = \frac{1}{\pi} \log(1+\sqrt{w}) - \frac{1}{\pi} \log(1-\sqrt{w}) + \frac{2}{\pi} \arctan(\sqrt{w})
$$
but will probably not place branch cuts where you want them. To help the stupid program, I replaced $w$ with $\sqrt{r}e^{it/2}$ and then plot using a value of $t$ slighly off Maple's branch cut line.
<code>g:=(1/Pi)*ln(1+sqrt(r)*exp(I*t/2)) - (1/Pi)*ln(1-sqrt(r)*exp(I*t/2)) + (2/Pi)*arctan(sqrt(r)*exp(I*t/2));
display(complexplot(eval(g,t=0.00001),r=0..5,thickness=3), complexplot(eval(g,t=Pi),r=0..5,thickness=3));
</code>

Never mind that the figure appears to be cut off on top and to the right; computer has a hard time grasping the unboundedness of logarithm.
Comment: Thanks! I should've seen closed form for the integral, which you gave, and which agrees with the one in Mike Miller's comments. Substitute $u = \sqrt{w}$, then use partial fractions twice.


Better Way to do this in Pandas?

Question: I'm just seeking some guidance on how to do this better. I was just doing some basic research to compare Monday's opening and low. The code code returns two lists, one with the returns (Monday's close - open/Monday's open) and a list that's just 1's and 0's to reflect if the return was positive or negate.
Please take a look as I'm sure there's a better way to do it in pandas but I just don't know how.
#Monday only
m_list = [] #results list
h_list = [] #hit list (close-low > 0)
n=0 #counter variable
for t in history.index:
    if datetime.datetime.weekday(t[1]) == 1: #t[1] is the timestamp in multi index (if timestemp is a Monday)
    x = history.ix[n]['open']-history.ix[n]['low']
    m_list.append((history.ix[n]['open']-history.ix[n]['low'])/history.ix[n]['open'])
    if x > 0:
        h_list.append(1)
    else:
        h_list.append(0)
    n += 1 #add to index counter
else:
    n += 1  #add to index counter

print("Mean: ", mean(m_list), "Max: ", max(m_list),"Min: ",
  min(m_list), "Hit Rate: ", sum(h_list)/len(h_list))

Answer: You can do that by straight forward :
(history['open']-history['low'])>0
This will give you true for rows where open is greater and flase where low is greater.
And if you want 1,0, you can multiply the above statement with 1.
((history['open']-history['low'])>0)*1
Example
import numpy as np
import pandas as pd

df = pd.DataFrame({'a':np.random.random(10),
                  'b':np.random.random(10)})

Printing the data frame:
print(df)

    a   b
0   0.675916    0.796333
1   0.044582    0.352145
2   0.053654    0.784185
3   0.189674    0.036730
4   0.329166    0.021920
5   0.163660    0.331089
6   0.042633    0.517015
7   0.544534    0.770192
8   0.542793    0.379054
9   0.712132    0.712552

To make a new column compare where it is 1 if a is greater and 9 if b is greater :
df['compare'] = (df['a']-df['b']>0)*1

this will add new column compare:
    a   b   compare
0   0.675916    0.796333    0
1   0.044582    0.352145    0
2   0.053654    0.784185    0
3   0.189674    0.036730    1
4   0.329166    0.021920    1
5   0.163660    0.331089    0
6   0.042633    0.517015    0
7   0.544534    0.770192    0
8   0.542793    0.379054    1
9   0.712132    0.712552    0

Comment: it is better and easier to use the inbuilt way of working with columns in pandas than to work row-wise as you did in your code. This is clear and understandable at least, perhaps also faster. You easily add new columns and do operations to the columns as shown above.
Comment: Thanks, so would it be better to do it this way then extract the data that lands on Mondays?

Better Way to do this in Pandas?


Changing the units for an independent variable in a Poisson model

Question: I'm trying to model a dose-response relationship between the incidence of cancer (dependent variable, counts) and the radiation dose (independent variable in gray). Can I change the unit of the independent variable from gray to milligray (gray × 1000) and have the same response?
I have built two models, 1 with independent variable as gray, and the second model with gray × 1000 as the independent variable. Should the model have similar parameter estimates, just different by a factor of 1000?
I have tried this, and my parameter for dose-response in two separate models goes from 1.000764 per milligray to 2.14 per gray.
Comment: @NickStauner indeed, but the recorded values in milligrays are the values in grays multiplied by 1000. So if you had 0.32 grays, you now record 320 milligrays. If you named your data column "grays" (unsurprisingly, since the measurements were in that unit) and you make a new column called "milligrays", you may well say something like 'milligrays=grays$\times$1000' ... perhaps somewhat confusingly, but the result is as it should be.
Comment: Wouldn't a milligray be gray $\div$ 1000? I think gray × 1000 = kilogray.
Comment: Oh, of course! Man, this reminds me of other mistakes I made in college physics...
Answer: The linear predictor is on a log scale, and $\frac{\log 2.14}{\log 1.000764} \approx 1000$. The response is modelled by a Poisson distribution whose mean increases by a factor of $1.000764$ for a 1 mGy increase in radiation dose, or equivalently a factor of $1.000764^{1000}=2.14$ for a 1 Gy increase.
Answer: I suspect something else is wrong if your parameter changes by a different factor than your units. Here's a simple simulation in R to demonstrate that, as you suspect, multiplying your predictor by 1000 should change the scale of your parameter by the same factor (dividing it):
<code>y=rpois(10000,1);x=rnorm(10000,5);x1000=x*1000    #Generates random count and continuous data
summary(glm(y~x,family='poisson'))$coefficients   #fits Poisson GLM of counts ~ continuous IV

               Estimate  Std. Error   z value  Pr(>|z|)
(Intercept)  0.07375024 0.050409708  1.463017 0.1434629
x           -0.01275800 0.009894814 -1.289363 0.1972721

summary(glm(y~x1000,family='poisson'))$coefficients       #same as above, using multiplied IV

                Estimate   Std. Error   z value  Pr(>|z|)
(Intercept)  0.073750238 5.040971e-02  1.463017 0.1434629 #intercept stats unchanged
x1000       -0.000012758 9.894814e-06 -1.289363 0.1972721 #Estimate and SE differ by x10^(-3)
</code>


File size of an Excel Workbook increases every time I create a new pivot table and save the file

Question: I have a vba macro that creates a pivot table based on some data in an input sheet. Every time the macro runs, the old pivot is deleted and a new one is created.
The problem I'm facing is that every time I save the file after running the macro, the file size increases by roughly 14MB.
This is how I delete the old pivot table:
For Each pivot In reportSht.PivotTables
    pivot.TableRange2.Clear
Next pivot

My theory is that some part of the pivot isn't being deleted but I can't seem to put my finger on what.
Comment: If you delete the connection then the cache will be deleted too.
Comment: Does using `SaveAs` instead of `Save` reduce the file size? • Also read [Remove Pivot Cache to Save Space](https://trumpexcel.com/reduce-excel-file-size/#Remove-Pivot-Cache-to-Save-Space) Use `Debug.Print ActiveWorkbook.PivotCaches.Count` to check the number of PivotCaches in your workbook. • This might be helpful too: [Pivot Cache in Excel – What Is It and How to Best Use It](https://trumpexcel.com/pivot-cache-excel/)
Comment: I'll look into the Pivot Caches but I've also found out that I'm not deleting the connections, which has greatly reduced file size and stopped the file size from growing. I'll post an answer with my solution later.
Answer: I have found the solution to my problem. When I create the pivot tables I also add connections, since I need to display the number of unique entries in the pivot table:
ActiveWorkbook.Connections.Add2 "WorksheetConnection_" & inputDataArea, "", _
    "WORKSHEET;" & ActiveWorkbook.Path & "\[" & ActiveWorkbook.name & "]" _
    & inputSht.name, inputDataArea, 7, True, False

Where inputDataArea is a String with the range used by for the pivot table. My problem was, that I was not deleting these connections when I was deleting the pivot table. So a new connection was being added every time the macro was executed.
I added this piece of code to also remove any connections that are no longer needed after removing the pivot table:
Dim connection As Object

For Each connection In ActiveWorkbook.Connections
    If connection.name <> "ThisWorkbookDataModel" Then connection.Delete
Next connection

The file is still large but manageable and most importantly it's not growing anymore.
Thanks to Pᴇʜ for suggesting that I remove pivot caches and pointing out, that these are deleted along with the connections.


Angular Bootstrap Modal value setting inconsistency

Question: Update 2

    <button style="display:none" data-toggle="modal" data-target="#videoReplace"></button>
  <app-upload-modal [id]="i" ></app-upload-modal>

Update 1:
Here is my upload-modal.ts

export class UploadModalComponent implements OnInit {

  constructor() { }
  @Input()
  id:number;

  @ViewChild('toggleButton')
  private toggleButton : ElementRef;

  ngOnInit() {
  }

  clickToggleButton() {
     this.toggleButton.nativeElement.click(); //trigger button click
  }

}

And upload-Modal.html

  <button #toggleButton  style="display:none" data-toggle="modal" data-target="#videoReplace{index}"></button>

Replace Video

Please upload a MP4 file you want to replace with the existing one. This will replace {{videosToBeReplaced?.video?.title}}

Old Code : First Question
Here is my component.html
At the lower part of the code, there is a modal. Modal value is set when

this method is clicked. As you see, there is a list drawn here uiVideos. For each element of this list, there is a row generating with edit, move and several actions. I have specified the action in above line code.
Problem :
for the first row binded from uiVideos are being shown in Modal. But for the next rows of the uiVideos are not binding to the Modal.
As you can see, I have checked the value in this.videosToBeReplaced.video.itemId, And they absolutely are correct for any of the rows of uiVideos list. but after triggering the modal, The value becomes empty.
And below, there is the code to show the modal.

 0" [value]="progress" showValue="false" mode="{{getProgressBarMode()}}">

            {{c.video.title}}

          <input [(ngModel)]="c.video.title" type="text" class="form-control col-sm-12" *ngIf="c.isEditing">

 0" [value]="progress" showValue="false" mode="{{getSingleProgressBarMode(c)}}">

          <app-content-status-updater [item]="c.video" itemType="video" [isEditing]="c.isEditing" class="col-sm-4"></app-content-status-updater>

            <select [(ngModel)]="c.video.order">
              <option *ngFor="let item of uiVideos;let i=index" value="{{i+1}}">{{i+1}}</option>
            </select>

<button id="videoReplaceTrigger" style="display:none" data-toggle="modal" data-target="#videoReplace"></button>

Replace Video

Please upload a MP4 file you want to replace with the existing one. This will replace {{videosToBeReplaced?.video?.title}}

In component ts following code determines the modals videosToBeReplaced value

OpenUploaderAndBindContent(c: UIVideo) {
    console.log('before c: ' + c.video.itemId + ' - ' + c.video.title);

    this.videosToBeReplaced = new UIVideo();
    this.videosToBeReplaced = c;

    console.log(this.videosToBeReplaced.video.itemId + ' - ' + this.videosToBeReplaced.video.title);
    document.getElementById('videoReplaceTrigger').click();
  }
Answer: Issue
Your problem is related to the operating on the same DOM element for each iteration of for loop.
See your OpenUploaderAndBindContent function.
OpenUploaderAndBindContent(c: UIVideo) {
    console.log('before c: ' + c.video.itemId + ' - ' + c.video.title);

    this.videosToBeReplaced = new UIVideo();
    this.videosToBeReplaced = c;

    console.log(this.videosToBeReplaced.video.itemId + ' - ' + this.videosToBeReplaced.video.title);
    document.getElementById('videoReplaceTrigger').click(); <-- ISSUE 1
  }

You are trigger the same button for each video and eventually this will try to open the same modal. Because button is target the same modal id=videoReplace. Refer below snippet. button is targeting videoReplace.
<button id="videoReplaceTrigger" style="display:none" data-toggle="modal" data-target="#videoReplace"></button>

Solution
The solution of your problem is -

Do not target the same button and modal by id.
You should create the multiple modal for each video so create new modal component say modal-component
Move the following modal content in it.

Make the set the button and model id dynamic by using @Input.

Replace Video

Please upload a MP4 file you want to replace with the existing one. This will replace {{videosToBeReplaced?.video?.title}}

4.Use the modal-component inside the for loop

   <modal-component [id]="i" ></modal-component>

note : modal-component has the input id. This will generate the dynamic id for modal and button.

5.Finally your method will look like -
OpenUploaderAndBindContent(c: UIVideo, index:number) {
    console.log('before c: ' + c.video.itemId + ' - ' + c.video.title);

    this.videosToBeReplaced = new UIVideo();
    this.videosToBeReplaced = c;

    console.log(this.videosToBeReplaced.video.itemId + ' - ' + this.videosToBeReplaced.video.title);
    document.getElementById('videoReplaceTrigger'+index).click(); <-- ID IS GENERATED BY INDEX
  }

Here is the id is generated dynamically.
Comment: Yes, whenever you are calling `OpenUploaderAndBindContent`, you should pass the `index` as well.
Comment: `document.getElementById('videoReplaceTrigger'+index).click();` this is buttonid right? how is this generating?
Comment: ``
but does this produce unique buttons? or I have to add index in UI Id as well? or what is the concept here? how the button id is differing?
Comment: Sing I have updated my question by separating modal and calling . please check what I am doing wrong.
Comment: And  as my modal is a child component, If I want to trigger, I have to access the child control from the parent, right? Or is there other way?
Comment: wherever you are using `id` in modal,  append the id with index. ex : `id="videoReplaceTrigger{{index}}"`
Comment: document.getElementById(...) is null. These buttons are not being find. An update again added at the top.
Comment: You can use `@ViewChild`.
Comment: I have updated your answer. I have put some changes in modal component.
Comment: If want to call the method of modal component then you can use `@ViewChild` in the parent component.
Comment: I have tried your ways bro. but its not working yet. And I had some other questions. I wanted to use same modal, as they have same structure. just few data will changed. which I will change by changing the binded data. To do so, I think, creating Modal for each indivudual, will heavy the DOM.
Comment: This is taking no where. Lets do one thing, you just create the demo in https://stackblitz.com. It will help to get the fix quicker and better.
Comment: Bro I have almost finished it. Ofcourse with your help and the concept. I will let you know when I finish. :) There were some other bussiness scenario that I could not explain here, was causing trouble. Now I figured that out. :)


Nilradical of a primary ideal is a minimal prime

Question: I'd like to show the following claim:
The radical of a primary ideal $\mathfrak q$, $r(\mathfrak q)$, is the smallest prime ideal containing $\mathfrak q$.
Can you tell me if my proof is correct:
I'll use the following two facts:
(i) There is a bijection between ideals $J$ of $R$ containing $I$ and ideals $\overline{J}$ of $R/I$.
(ii) The radical of an ideal $r(I)$ equals the nilradical $n(R/I)$.
(To see this, let $x \in r(I)$. Then $x^n \in I$ and hence $\overline{x}^n = 0$ in $R/I$. On the other hand, let $\overline{x}^n = 0$ then $x^n \in I$ and hence $x \in r(I)$.)
Now for the claim: By (ii), we have $r(\mathfrak q) = n(R/\mathfrak q)$. We know that $n(R/\mathfrak q) = \bigcap_{I \in R/\mathfrak q; I \text{ prime}} I$. Going back to $R$ and using (i) we hence see that $r(\mathfrak q) = \bigcap_{I \subset R; \mathfrak q \subset I } I$. At first I thought that I could write "$\mathfrak q \subset I; I \text{ prime}$" here but I think that might be wrong. (Do you know an example where that's wrong?)
Now we have established that $r(\mathfrak q)$ is the smallest ideal containing $\mathfrak q$ so to finish the proof we want to show that $r(\mathfrak q)$ is prime:
Let $xy \in r(\mathfrak q)$. Then $x^n y^n \in \mathfrak q$ for some $n$. Since $\mathfrak q$ is primary we hence know that for some $m$ we have $x^m$ or $y^m$ in $ \mathfrak q$. Hence $x \in r(\mathfrak q)$ or $y \in r(\mathfrak q)$.
Comment: $r(\mathfrak q)$ is not "the smallest ideal containing $\mathfrak q$", but it is the smallest *semiprime* ideal containing $\mathfrak q$.
Answer: The last paragraph is great: you've shown that $r(\mathfrak q)$ is a prime ideal. The other part is actually easier, for if $\mathfrak p$ is a prime ideal then one shows by induction that if $a \in A$ and $n \geq 1$ are such that $a^n \in \mathfrak p$ then $a \in \mathfrak p$. Hence if $\mathfrak q \subset \mathfrak p$ then $r(\mathfrak q) \subset \mathfrak p$.
Regarding the earlier stuff: it might be safer to write something like $r(I)/I = n(R/I)$. The correspondence between ideals containing $I$ and ideals of $R/I$ preserves the property of being prime, and taking pre-images commutes with intersections, so you should indeed write $r(\mathfrak q) = \bigcap_{I \text{ prime }\supset\ \mathfrak q} I$; but I suspect you already knew this identity. Note that intersecting over all ideals containing $\mathfrak q$ would just give you $\mathfrak q$!


A Dorian scale/chord progressions

Question: I'm currently jamming a song in G Major with focus on the A Minor. The chord progression goes Am C D. I know that the A Minor Blues Scale sounds pretty sleek, but I just have the feeling that A Dorian makes it a lot more interesting, which makes sense to me because I put the focus on the second chord of G Major which is A Minor.
Are there "compulsory" chord progressions in a Dorian Mode? Or can I just jam the Dorian scale over any progression that starts with the Dorian root and has chords the chords of the key? And theoretically I play a I IV V in A Dorian, which gives it this Bluesy/Funky feeling, a bit like Zappa.
Comment: If the song is in Am and you notice that nobody is playing or singing an F note, it's your chance to throw in a D or Bm chord --> boom, you made a little bit Dorian!
Comment: Sorry for my typos though :D
Comment: I'm not sure what you mean by "compulsory." Since it seems like you understand the theory of which scales contain which chords, it sounds like you have already answered your own question: The A dorian scale is a great choice for this progression.
Answer: There are no "compulsory" chords, but if the music is to sound Dorian, then you want to emphasize A and the total progression should have every note in the mode represented, so it could help to add a chord including 'b' in your progression, such as G Major, B minor or E minor.
Depending upon how much you want to follow historical practice, a cadence involving E Major was often added.
Answer: I put the focus on the second chord of G Major which is A Minor
Not only is A minor the "second chord" (i.e., the ii chord) of G major, but A Dorian is the "second mode" of G major. That is, the A Dorian and G major scales have the same key signature. Put another way, A dorian and G major have exactly the same pitches in them.
Are there "compulsory" chord progressions in a Dorian Mode?
In order to make a mode sound "modal", one should simultaneously emphasize the unique pitches in that mode — the ones that differentiate it from other, similar modes — and deemphasize the similarities.
Dorian and (natural) minor are very similar, differing only by the sixth note in the scale:
A minor  = A B C D E F  G
A dorian = A B C D E F# G
More specifically, a scalar passage in minor might contain adjacent F# and G#, F and G, or F and G#, but not F# and G – the latter is unique to Dorian.
Thus, to create a "dorian" chord progression, it helps to emphasize the shift from F# to G or G to F#. VI VII i and III ii i will accomplish this while also clarifying the tonic pitch, which is also necessary to ground the mode. (For example, if you emphasize G instead of A, it's going to wind up sounding like G major.) The progression mentioned in the OP, Am C D, is i III IV in A dorian and also prominently employs the F# G shift.
While i IV v also includes the tonic and the 5-6 (F# G) point of emphasis, the progression overall is so characteristic of major and minor that should be used carefully, if not avoided.

A Dorian scale/chord progressions


How to change/set/assign parameter's value for an entity query?

Question: Say you have an entity query which you're going to use in a loop so that only parameter(s) value(s) changes on every iteration. Is there a way to prepare this query and change the value of the parameters?
Answer: There are some nice examples in the comments on the api documention page for Entity queries https://api.drupal.org/api/drupal/core!lib!Drupal.php/function/Drupal%3A%3AentityQuery/8.2.x
One example assigns a value to a variable, then uses the variable in the query:
<code>$value = 'some value';
$query = \Drupal::entityQuery('entity_type');
$query->condition('field', $value);
$entity_ids = $query->execute();
</code>
In your loop you could re-assign the value as needed before executing the query.
Another example sets up some functions, so that might be an option and then your loop could call the function.
<code>function someFunction($value) {

  $query = \Drupal::entityQuery('entity_type');
  $query->condition('field', $value);
  $entity_ids = $query->execute();

}
</code>
Or you could clone the part that stays the same in your loop and alter the rest.  Using your code as an example...
<code>$base_query = \Drupal::entityQuery('taxonomy_term');
$base_query->condition('vid', 'some_vocabulary');

for ($i = 1; $i <= 10; $i++) {
  $query = clone $base_query;
  $query->condition('tid', $tids[$i]);
  $query->execute();
  //...
}
</code>
Comment: All these examples recreate query from scratch. This doesn't look effective in case of a loop. Consider this example:
`$query = \Drupal::entityQuery('taxonomy_term');`
`$query->condition('vid', 'some_vocabulary');`
`for ($i = 1; $i <= 10; $i++) {`
  `$query->condition('tid', $tids[$i]);`
  `$query->execute();`
  `// ...`
`}`

P.S. Sorry for retarded code formatting, stackexchange is definitely an overthought thing, where is my code formatters damn it?
Comment: I updated the answer and added a section on cloning that should work for your scenario.
Comment: Yeah I see thank you. But yet this is not what I was looking for. Anyway thanks! At least this topic is covered now (on the internet).
Comment: Not sure what you were looking for but it's not supported to re-use an executed entity query. So cloning before executing it is the only option you have and this answer is correct


Momentjs, compare utc dates

Question: Okay, I loop through an array of times which comes from my server in the following format:
2014-04-14T13:00:00Z
2014-04-14T13:15:00Z
2014-04-14T13:30:00Z

Now I want to catch the item which is the next from now.
for (var j = 0; j < array.Times.length; j++) {
    if ((moment(array.Times[j])) > moment()) {
         // tried with new Date(), isAfter(), unix(), utc() ... "
         // got my item
    }
};

This works, but I couldn´t catch the Timezone.
The Time-format which comes comes from the Server is UTC, right?
What I need is the locale Time...!? Or Iam totally wrong?
In Germany I got +2 Hours timezone offset.
http://jsfiddle.net/fool/fDpR4/
Answer: Your date strings are in ISO UTC format, so the dates created from them will have a different time depending on your time zone. So if you create moment("2014-04-14T13:30:00Z"), it will have a local time of 15:30 in your case. So your sample code may already be working correctly, but I don't know your requirements.
If you want the strings to be interpreted as local time, the easiest solution would be to drop the "Z" at the end:
for (var j = 0; j < myArray.length; j++) {
    var dateString = myArray[j].substr(0, myArray[j].length - 1);
    if (moment(dateString) > moment()) {
        console.log(dateString);
        console.log(moment(dateString).toDate());
        break;
    }
}

Comment: hm, is a strange problem... I will report if the issue is fixed.

Momentjs, compare utc dates


Object is possibly 'null' for while utilizing a .match()

Question: I am building out a series of validation functions for my static site generation function. For one of these validation functions I use a series of .match() functions to parse HTML header tags. Here is the validation function so far:
//  2c. Check that each header tag's next header tag is one level higher, lower, or the same level
  const headers = html.match(/<h[1-6][^>]*>.*<\/h[1-6]>/g)
  headers?.forEach((header, index) => {
    if (index === headers.length - 1) return
    const currentLevel = parseInt(header.match(/<h([1-6])/)[1])
    const nextLevel = parseInt(headers[index + 1].match(/<h([1-6])/)[1])
    if (nextLevel && Math.abs(currentLevel - nextLevel) > 1) {
      throw new Error(
        `Content for ${directory}/${slug}${contentExtension} has an invalid header hierarchy.`
      )
    }
  })

The same error, "Object is possible null, occurs with both header.match(/<h([1-6])/) and headers[index + 1].match(/<h([1-6])/). However, this validation function works properly with several Jest test cases I have written out. I understand why this error is happening and how to trigger the validation function, but don't understand how to fix this null object issue.
Some of the attempts to fixing this is first a non-null assertion operator with the problematic parts of the code. This didn't resolve the issue and I also tried a typical if null check for the objects. I also tried checks on the index after .match(), but I realized very quickly this was outside the scope of the error.
Looking at the "Do any of these posts answer your question" section I tried this answer and received a new error of "Forbidden non-null assertion".
Answer: TypeScript is properly warning you that you might not be able to absolutely depend on there always being a match. What if the server that creates the HTML is having issues, and gives you a 404 page instead? Or what if the match fails for some other reason? You should add some logic to not attempt to parse the match result if the match fails.
headers?.forEach((header, index) => {
  if (index === headers.length - 1) return
  const currentLevelMatch = header.match(/<h([1-6])/);
  const nextLevelMatch = headers[index + 1].match(/<h([1-6])/);
  if (!currentLevelMatch || !nextLevelMatch) {
    // you might want to log that this was an unexpected failure
    return;
  }
  const currentLevel = parseInt(currentLevelMatch[1]);
  const nextLevel = parseInt(nextLevelMatch[1]);
  // etc

A more elegant approach than parsing HTML with regular expressions would be to create a document from the HTML string with DOMParser or jsdom - with those, you'll then be able to navigate around the document and its elements using handy methods like .querySelector and .nodeName. One possible approach would be to take the HTML string that one of those methods creates, and proceed to use that (rather than the input, which sounds like it might sometimes have invalid markup).


Confirmation before deleting row

Question: I'm trying to show a UIAlertView before actually deleting a cell from a UITableView
NSIndexPath *_tmpIndexPath;

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(editingStyle == UITableViewCellEditingStyleDelete)
    {
        _tmpIndexPath = indexPath;

         NSLog(@"%d", indexPath.row); // 2
         NSLog(@"%d", _tmpIndexPath.row); // 2

        UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Dete" message:@"Are you sure you want to delete this entry?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil] autorelease];
        [alert show];
    }
}

So both my logs return the correct path.
I have my view delegating the UIAlertView
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"%d", _tmpIndexPath.row);
    if(buttonIndex == 1)
    {
        NSLog(@"%d", _tmpIndexPath.row);
    }
}

Now I can't figure out why in the clickButtonAtIndex() I'm getting an error when trying to log _tmpIndexPath.row
 *** -[NSIndexPath row]: message sent to deallocated instance 0x12228e00

Comment: You can use like this right         UIAlertView *alert;
        [alert setTag:indexPath.row];
Comment: so you will get the row value in clickedButtonAtIndex method..
Comment: Thanks, I was indeed looking for something like that too
Comment: Sorry, I thought you have not seen my comment so, I have posted that as a answer also..;)
Comment: It was :) Just not the answer to this question, but I was looking for something like that too previously
Answer: you will need to retain the indexPath, what is happening is that your indexPath when the alert is dismissed is already deallocated from your system,
Like this
Change
_tmpIndexPath = indexPath;

to
_tmpIndexPath = [indexPath retain];

Comment: That was indeed the solution, thanks. (will accept as answer in 5 min)
Answer: You can try to do this
        UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Dete" message:@"Are you sure you want to delete this entry?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil] autorelease];
[alert setTag:indexPath.row];
        [alert show];

So you can get the value as
[alertView tag]

In clickedButtonAtIndex
Answer: NSIndexPath is a NSObject and you have it autoreleased in your tableView: commitEditingStyle method so assigning it to your instance variable: _tmpIndexPath = indexPath; it gets deallocated later. What you need to do is:
_tmpIndexPath = [indexPath copy]; but be careful because every time you are responsible to release your _tmpIndexPath before setting it again. The cleaner solution is to use properties:
@property (nonatomic, copy) NSIndexPath *tmpIndexPath;
...
self.tmpIndexPath = indexPath;

Answer: Acknowledging the technical answers above, can I suggest that this isn't actually necessary.  If you are using the normal ways to delete items from a table view (edit button and swipe the row) then adding a confirmation in to the flow is going to be contradictory to how people will expect the table to behave.  The user already has to tap (or swipe) before even gaining access to the delete functionality, so they must already be pretty sure they want to do it.
Comment: I'm actually using the normal way, but we had some complaints from users that they accidentally delete items, the alert is just to make sure they want to delete it. (As it's delete from our servers aswel)
Answer: Do you use ARC? If not try _tmpIndexPath = [indexPath retain]; and don't forget release it later

Confirmation before deleting row


Exchange 2010 only allows 1 IMAP/POP3 account to be logged in

Question: We just moved to Exchange 2010 and the IMAP/POP3 accounts are only allowing one person to be logged into them at a time. The second person that tries to login gets an invalid username/password window.
We are in need of setting 6 people up on our firstname.lastname@example.com email so that they can all respond to these emails. They are all set up with IMAP so that they can send replies back to our customers using this same email.
Does anyone know what setting would make so multiple people can be actively logged in?
Answer: You should check your IMAPMaxConcurrency settings for Set-ThrottlingPolicy.

The IMAPMaxConcurrency parameter specifies how many concurrent
  connections an IMAP user can have against an Exchange server at one
  time. A connection is held from the moment a request is received until
  a response is sent in its entirety to the requestor. If users attempt
  to make more concurrent requests than their policy allows, the new
  connection attempt fails. However, the existing connections remain
  valid. The IMAPMaxConcurrency parameter has a valid range from 0
  through 2147483647 inclusive. To indicate that the number of
  concurrent connections should be unthrottled (no limit), this value
  should be set to $null.

http://technet.microsoft.com/en-us/library/dd298094.aspx
Comment: I changed the limit on the IMAP/Connection tab to the max and its still not allowing more then one user to login. This is boggling...


Laravel: rota com parâmetros

Question: Tenho um sistema escolar com uma tela de chamadas onde tem um botão que abre um modal com um formulário para escolher a turma e a data (chamadas/index). Esse formulário vai redirecionar para uma tela com a lista de alunos da turma escolhida para lançar a chamada no dia selecionado anteriormente.
Como eu devo montar uma rota que aceite receber algo parecido com chamadas?turma=1&data=21-08-2017 ?
Mesmo que exista uma forma em que os parâmetros não apareçam na url pra mim já serve.
Desde já agradeço.
Answer: O mais simples possivel, exemplo:
Route::get('chamadas/{turma}/{data}', "ChamadasController@index");

na sua classe controller
class ChamadasController
{
    public function index($turma, $data)
    {
         // ... code
    }
}

a sua url seria isso:
http://site.com/chamadas/1/21-08-2017

Referencias

Routing
Route Parameters
Comment: Não funcionou :( Mostra rota inexistente
Comment: @Matheus a sua rota é um `link` ou um `post`? Essa mensagem é porque está fazendo algo que a aplicação não está configurado corretamente, gostaria que editasse a sua pergunta e conte o que você fez... ??? Se possivel coloque todas as rotas e qual rota está usando ???

Laravel: rota com parâmetros


Parametric Equation for a Cone with Any Direction About the Origin

Question: I'm trying to find the parametric equation for a cone with its apex at the origin, an aperture of $2\phi$, and an axis parallel to some vector $\vec d$. The cone is right-circular and is meant to be able to extend indefinitely as $t$ increases.
The idea is to model the shape of insect repellent spray as it is released from an aerosol can. The spray begins when $t=0$ and continues for all $t \ge 0$. The specified direction vector $\vec d$ is meant to determine the speed of propagation of the cone (in terms of $t$) as well as the direction of propagation (from the apex to the center of the base).
So far I've tried assuming that a general cone along the z-axis with apex at the origin and equation $\begin{pmatrix} x \\ y \\ z \end{pmatrix} = t \begin{pmatrix} \tan(\phi) \cos(\theta) \\ \tan(\phi) \sin(\theta) \\ 1 \end{pmatrix}$ has a direction vector of $\vec a =\begin{pmatrix} 0 \\ 0 \\ 1 \end{pmatrix}$. If I want that cone to go in another direction $\vec d$ than I can use trigonometry to find the rotation angles between $\vec d$ and $\vec a$ along each x-, y-, and z-axis; put those values into the three elemental rotation matrices; and apply those matrices to the original cone equation. This didn't really work out though.
Then I found this post and the implicit cone equation $\vec u \cdot \vec d - |\vec u||\vec v|\cos(\phi) = 0$ (for $\vec u = [x, y, z]$ and some direction vector $\vec d = [d_1, d_2, d_3]$). Only problem is I've never heard the term 'implicit' before and I don't know how to turn that equation into a vector form.
If anyone is able to convert that implicit cone equation into vector form and/or give me the vector equation for a right-circular cone with any direction, I would really appreciate it.
Comment: Start by finding a parameterization of one of the generating circles. There are various ways to do this.
Comment: I've given it a few goes, and now I have a couple of follow-on questions. What is a generating circle, and can a system of three variables be parameterized with only one equation?
Answer: There are several options, depending on exactly what you want to do.

Let $\hat{d}$ be the unit ($\lVert\hat{d}\rVert = 1$) direction vector,
$$\hat{d} = \frac{\vec{d}}{\lVert\vec{d}\rVert} \tag{1}\label{NA1}$$
Let $\hat{u}$ be an unit vector perpendicular to $\hat{d}$; essentially, the direction perpendicular to the spray for which $\varphi = 0$.
If your spray is radially symmetric, then you can pick $\hat{u}$ freely. One way to pick it is to calculate $\hat{e}_x \cdot \hat{d}$, $\hat{e}_y \cdot \hat{d}$, and $\hat{e}_z \cdot \hat{d}$ (the $\hat{e}$ unit vectors being the axis vectors, i.e. $\hat{e}_x = \left [ \begin{matrix} 1 \\ 0 \\ 0 \end{matrix} \right ]$), and let $\hat{e}$ be $\hat{e}_x$, $\hat{e}_y$, or $\hat{e}_z$, depending on which one was closest to zero, then
$$\vec{u} = \hat{e} - \hat{e} \left ( \hat{e} \cdot \hat{d} \right ), \quad
\hat{u} = \frac{\vec{u}}{\lVert\vec{u}\rVert} \tag{2}\label{NA2}$$
If you let
$$
\hat{d} = \left [ \begin{matrix} d_x \\ d_y \\ d_z \end{matrix} \right ], \quad
\hat{u} = \left [ \begin{matrix} u_x \\ u_y \\ u_z \end{matrix} \right ],
\quad
\hat{v} = \hat{d} \times \hat{u} = \left [ \begin{matrix} v_x \\ v_y \\ v_z \end{matrix} \right ] = \left [ \begin{matrix} d_y u_z - d_z u_y \\ d_z u_x - d_x u_z \\ d_x u_y - d_y u_x \end{matrix} \right ]
$$
then the rotation matrix $\mathbf{R}$ that rotates $z$ axis towards $\hat{d}$, $x$ axis towards $\hat{u}$, and $y$ axis towards $\hat{v}$, is
$$
\mathbf{R} = \left [ \begin{matrix}
u_x & v_x & d_x \\
u_y & v_y & d_y \\
u_z & v_z & d_z \\
\end{matrix} \right ] \tag{3a}\label{NA3a}
$$
Because $\mathbf{R}$ is an orthonormal matrix, the inverse rotation is
$$
\mathbf{R}^{-1} = \mathbf{R}^T = \left [ \begin{matrix}
u_x & u_y & u_z \\
v_x & v_y & v_z \\
d_x & d_y & d_z \\
\end{matrix} \right ] \tag{3b}\label{NA3b}
$$
This means that if you have a vector $\vec{p}$ in the coordinate system where the spray is along the positive $z$ axis and $\varphi = 0$ along positive $x$ axis, then
$$\vec{q} = \mathbf{R}\vec{p} \quad \iff \quad \vec{p} = \mathbf{R}^T \vec{q} \tag{4}\label{NA4}$$
i.e. vector $\vec{q}$ is the corresponding vector in the coordinate system where the spray is along $\hat{d}$, and $\varphi = 0$ along $\hat{u}$.

Let's say you want to use spherical coordinates $(r ,\, \varphi ,\, \theta)$ where $r$ is the distance from the nozzle, $\theta$ is the angle to the spray direction vector $\vec{d}$, and $\varphi$ is an angle around the axis of the direction.
Let's say the unit vector $\hat{d}$ describes the spray axis, and $\hat{u}$ describes the direction where $\varphi = 0$, both perpendicular to each other ($\hat{d} \perp \hat{u}$; $\hat{d} \cdot \hat{u} = 0$; $\hat{v} = \hat{d} \times \hat{u}$; $\hat{v} \perp \hat{u}$; and $\hat{v} \perp \hat{d}$).
You do not need to use the rotation matrix $\mathbf{R}$ to generate a vector given $r$ (length), $\theta$ (angle to axis of spray), and $\varphi$ (rotation around axis of spray). The result $\vec{q} = \mathbf{R}\vec{p}$ is equal to
$$
\vec{q}(r, \varphi, \theta) = r \cos(\theta) \hat{d} + r \sin(\theta) \cos(\varphi) \hat{u} + r \sin(\theta) \sin(\varphi) \hat{v}
\tag{5}\label{NA5}
$$

To test whether vector $\vec{p}$ is within the right circular cone that has the apex at origin, axis $\vec{d}$, and aperture $2\theta$, use
$$\vec{p} \cdot \vec{d} \le \lVert \vec{p} \rVert \lVert \vec{d} \rVert \cos(\theta) \tag{6}\label{NA6}$$
Note that when the dot products equal the product of their norms, the two vectors are parallel,
$$\vec{p} \cdot \vec{d} = \lVert \vec{p} \rVert \lVert \vec{d} \rVert \quad \iff \quad \vec{p} \parallel \vec{d}$$
and at the limit,
$$\vec{p} \cdot \vec{d} = \lVert \vec{p} \rVert \lVert \vec{d} \rVert \cos(\theta)$$
the vector is at the surface of the right circular cone.
Answer: For a cone representing the dispersion of a substrate through a medium with the following properties:
Apex displacement vector   $\vec{s}=[\matrix{s_x \ s_y \ s_z}]$,

Axis direction vector     $\vec{d}=[\matrix{d_x \ d_y \ d_z}]$ (non-zero),

Internal angle        $0 < \phi < 2\pi$,

And speed          $0 < v$
Apply the following algorithm to obtain the vector equation of that cone:

if ($d_z$ != $0$) {
  $\vec{j}= \left[\matrix{1 \ 1 \ - \frac{d_x + d_y} {d_x}}\right]$
  } else if ($d_y$ != $0$) {
  $\vec{j}= \left[\matrix{1 \ - \frac{d_x + d_z} {d_y}} \ 1 \right]$
  } else if ($d_x$ != $0$) {
  $\vec{j}= \left[\matrix{- \frac{d_x + d_z} {d_y}} \ 1 \ 1 \right]$  }
$\vec{k} = \vec{d} \times \vec{j}$ (vector cross-product)
$\hat{d} = \frac{1}{\lVert\vec{d}\rVert}\vec{d}$
  $\hat{j} = \frac{1}{\lVert\vec{j}\rVert}\vec{j}$
  $\hat{k} = \frac{1}{\lVert\vec{k}\rVert}\vec{k}$
$g=vt \tan{\left(\frac{\phi}{2}\right)}$       (radius growth modifier)
  $e=\hat{j} \sin{(\theta)} + \hat{k} \cos{(\theta)}$   (ellipse construct)
  $T=vt\hat{d}$           (direction translation)
cone $C$  $C=gc + T + \vec{s}$, or
  $C = \vec{s} + vt \left(\tan{\left(\frac{\phi}{2} \right)} \left( \vec{j}\frac{\sin{(\theta)}}{\lVert\vec{j}\rVert} + \vec{k}\frac{\cos{(\theta)}}{\lVert\vec{k}\rVert} \right) + \vec{d}\frac{1}{\lVert\vec{d}\rVert} \right)$ where $\vec{j} \cdot \vec {d} = 0$ and $\vec{k} = \vec{d} \times \vec{j}$    $\theta \in [0, 2\pi)$ for all $0 < t$.

I haven't figured out how to turn this into one equation though, what with those if/else statements. I was thinking maybe a bunch of kronecker-delta's somehow? But then the $\vec{j}$ part of the equation just got so long that it wasn't worth it. And then they would all have to be substituted as the value for $\vec{k}$ and it was just too confusing.


Reasoning behind statement L(P1) > L - (1/2)ε

Question: Hey Guys I'm studying this proof in real analysis and just this one line gets me:
Suppose that f is bounded and Riemann integrable on [a,b] and ε > 0 is given. Since L = sup{L(P): P is a partition on [a,b]} exists, there is a partition P1 of [a,b] such that
L(P1) > L - (1/2)ε
What exactly does this statement mean? and where does the 1/2 come from?
I'm so confused
Answer: It is just the definition of supreme. If $L<\infty$ is the supremum of a set $A$ of real numbers then
$$\forall \epsilon >0 \exists a\in A : a>L-\epsilon.$$
Since $\epsilon$ is arbitrary the result holds for $1/2\epsilon.$
Probably you have encountered this in the middle of a proof and the reason for $1/2\epsilon$ is technical. Sure there is another term in the proof with the same $1/2\epsilon.$ Thus, when you add both terms you get the "familiar" $\epsilon.$
Comment: Thank you so very much :), Indeed in the ending of the proof you add them to give you a solid epsilon :D


Prove that $n^4$ is congruent to 0 or 1 modulo 5

Question: Prove that $n^4$ for all $n\in{\mathbb Z}$ is congruent to 0 or 1 modulo 5.
Hint from professor: Do so using different cases.
I am confused on how to prove this for all $n$. I understand that you can test a few numbers but I am stuck on  how to show it is true for all $n$.
Comment: Calculate $1^4$,$2^4$,$3^4$ & $4^4$ ...
Answer: Hint:$$(5n+k)^4=\color{red}{5^4}n^4+4\cdot\color{red}{5^3}n^3k+6\cdot\color{red}{5^2}n^2k^2+4\cdot\color{red}5nk^3+\color{blue}{k^4}$$
In general, we have
$$a^b\equiv(a\mod c)^b\pmod c$$
which follows from binomial expansion.
Answer: There are only five numbers modulo $5$. I recommend that you just try them all.
Answer: Hint:
$n\equiv 0,\pm 1,\pm2\mod5$, hence $\;n^2\equiv 0^2,1^2,2^2=0,1,-1$.


How do I make the hover background color fill the height of the link?

Question: How do I make the hover background-color fill the entire height of the navigation bar plus the padding of the text instead of only the text.
I want to make it look like this.

Fiddle
What am I missing? Thank you in advance!
Comment: Please refer to this fiddle for my failed example. http://jsfiddle.net/onestaryx/cRjF4/
Answer: Here you go. I've created a jsfiddle for you. Its working good:
http://jsfiddle.net/cRjF4/3/
Updated CSS:

Comment: Post the changed code as well, link answers may disappear and posting the code gives a better reference for people.
Comment: thank you! I also made an attempt to clean up my fiddle code to only keep the relevant parts for this example. http://jsfiddle.net/onestaryx/cRjF4/22/
Answer: If you wish to colour both the padding and the text try something like:
a:hover{
background-color:yellow;
color:red;
}

Answer: Try to do Anchor link css as
.worknav > li > a {
    text-decoration: none;
    display:inline-block;
    color: #666;
    line-height:65px;

}

Check on http://jsfiddle.net/kka284556/cRjF4/9/
Answer: You can do it by applying padding on anchor tag. Remove height on ul and li tag and instead of height just apply padding on anchor. And also apply background-color on anchor.
It will work i think. If I am right then let me know i'll share some code if you want.
Answer: The main solution idea is line-height css property. If the background height and font-size's line-height the same then the background colour will cover the full height.


Why do we want *unitary* representations of locally compact groups into $B(H)$?

Question: This is related to a previous question of mine but I have a more philosophical issue with the material. Everywhere I have looked for representations of locally compact groups into $B(H)$, everyone says that we want unitary representations but do not say what motivates this. Unitarity is definitely a nice property, but why should we hamper ourselves so much? Why not just map into $GL(H)$ (the invertible operators on $H$)? This is most closely aligned with the representation theory of finite groups and seems completely reasonable. I'm not looking for an "ends justify the means" kind of argument since when developing mathematics we don't even know what the "end" is necessarily but a more intuitive or lower level argument.
Answer: After thinking about this question for a few days, I've come to a few conclusions and observations which I will type here for posterity, I suppose.

In the finite and compact case, we can do a group averaging trick to make the representations unitary. This is not guaranteed in the locally compact setting.
In the finite dimensional case, we can develop the group ring. This is extremely useful in understanding the irreducible representations of the group since any irreducible representation appears in the left regular representation and the left regular representation is naturally occurring in the group ring. Formulating the group ring as the set of elements of the form $\sum_{g\in G}f(g)g$, we know that the product of two elements $\tilde{f} = \sum_hf(h)h$ and $\tilde{g}=\sum_hg(h)h$ is given by $\tilde{f}\tilde{g} = \sum_h\sum_{h'}f(h)g(h')hh' = \sum_h\left(\sum_{h'}f(h')g(h^{-1}h')\right)h$. We naturally see a convolution arise in this expression, so we can identify the functions $f$ and $g$ with elements of the $L^1(G)$ algebra.

This gives us two paths to go by when generalizing: we can either define the group ring of a locally compact group to be given by elements of the form $\int_G f(g)g\,dg$, where this integral is understood as a formal integral and $f\in L^1(G)$ or we can start by asking that the group ring consist of elements of the form $\int_G f(g)g$, where $f$ is continuous and of compact support (as this is the closest analogy we have to "finiteness" without ostensibly being zero). But since we want to create a Banach algebra from this set and convolution lies at the heart of the group ring, we would be forced to complete $C_c(G)$ with respect to the $L^1$ norm and we would end up with $L^1(G)$ again anyway. With this in mind, if one were to go through the machinery of looking at the representation lifted to the group ring as one does in the finite case, one would end up getting that if $\rho:G\rightarrow GL(H)$ for some Hilbert space $H$, then $\lVert\rho(g)\rVert\le M < \infty$ for all $g\in G$ in order to have meaningful operators on $B(H)$. Since the $\rho(g)$ are uniformly bounded in norm, taking cues from the finite and compact cases, we might as well ask that $\rho(g)$ be unitary.
Suppose $\rho:G\rightarrow GL(H)$ is a group homomorphism. One can somewhat run this thought process in reverse and ask the question: what if we work with general (formal) objects of the "group ring" given by
$$\mathbb{C}[G] = \left\{\int_Gf(g)g\,dg:\left\lVert\left(\int_Gf(g)\rho(g)\,dg\right)h\right\rVert<\infty\,\text{ for all }\,h\in H\right\}.$$
Here I have taken the approach that the formal object $\left(\int_Gf(g)g\,dg\right)h = \int_Gf(g)\rho(g)h\,dg$, akin to lifting the representation from the group to the group ring in the finite case. The restriction that $\left\lVert\left(\int_Gf(g)\rho(g)\,dg\right)h\right\rVert<\infty$ merely forces $\int_Gf(g)\rho(g)\,dg$ to be a well-defined operator on $B(H)$. By the uniform boundedness principle, I believe this is equivalent $\left\lVert\int_Gf(g)\rho(g)\,dg\right\rVert<\infty$. No real restrictions have been placed on either $f$ nor $\rho$ at this stage in terms of their analytic properties.
From this we can see that depending on how $\rho$ behaves, $f$ could have wildly varying behavior. For instance, consider $G = (\mathbb{R}^+,\cdot)$ and $\rho(x) = x^3I$. This is a representation but in order for $\left\lVert\int_Gf(g)\rho(g)\,dg\right\rVert<\infty$, $f$ has to have some somewhat restrictive decay properties. Likewise if we consider the opposite situation: let $\rho(x) = x^{-3}I$, again this is a representation but $f$ could have linear growth and still $\int_Gf(g)g\,dg$ would be a well-defined element in $\mathbb{C}[G]$.
So we see that without some restrictions on $\rho$, we cannot say anything meaningful about the group ring. Again, taking cues from the finite and compact cases, we might as well take $\rho$ to be unitary. Making this restriction nearly forces the $L^1(G)$ algebra to pop out naturally (upon considering some norm arguments and the like).
Answer: Note that people don't only study unitary representations.  If $G$ is a real or $p$-adic Lie group, then the study of representations of $G$ is a big part of the theory of automorphic forms and representations (it is the ``local'' part of the theory), and one studies representations that are not necessarily unitary (or, perhaps better, not necessarily unitarizable).
In this context there is another adjective, admissible, discovered by Harish-Chandra, which is of crucial importance, and a key theorem of Harish-Chandra shows that topologically irreducible unitary representations are admissible.

In practice, the emphasis on unitary representations, to the extent it exists, probably arose because one of the first goals of rep. theory of locally compact groups was to generalize the Plancherel theorem from Fourier theory on locally compact abelian groups, and the Peter--Weyl theorem from the theory of compact groups,
by determining the structure of $L^2(G)$ as a $G$-representation.
More generally, the theory of automorphic forms naturally leads to the question
of determining the structure of $L^2(\Gamma\ G)$ as a $G$-representation, where $\Gamma$ is a discrete subgroup of  $G$.
Since $L^2$ spaces are unitary, this leads to a focus on unitary reps.

You might find this post useful for obtaining more background on some of the motivations of the theory.


Error Term of Chebyshev inequality?

Question: Chebyshev inequality tells us that $$Pr[|X-E[X]|\geq a]\leq \frac{Var[X]^2}{a^2}$$
Do you know an Expression (or a paper where this Expression is mentioned) for the error term?
Comment: What do you exactly mean by "the error term"?
Comment: With error term I mean the difference $$\frac{Var[X]^2}{a^2}-Pr[|X-E[X]|\geq a]$$. Can one say something about it or could it be "anything"?
Answer: Unfortunately Chebyshevs inequality is tight, in the sense that there are many random variables which turn the inequality into an equality. For practice purposes if you want a better bound, typically you need higher moments to exist and grow slowly. In other words:
$$P(|X-EX|>c)\leq\frac{E[(X-EX)^k]}{c^k}$$
On the other hand there is an exact statement about the error. It comes directly from the proof of the inequality. Let $Y:=(X-EX)^2$ Then
$$\mbox{Var}(X)=E[Y]=\int_{Y\geq c}YdP+\int_{Y<c}YdP\geq cP(Y\geq c)$$
Where it's clear what was thrown away: the under estimate of the first integral and the entire second integral. That's the exact error. Practically it's difficult to assess so see the above.
On the other hand lower bounds on $P(Y\geq c)$ are considerably more difficult. Large deviations theory gives answers to such questions. There are exist reverse Markov inequalities for positive bounded random variables.
Comment: Is there an equivalent to the reverse markov inequality but depending on the variance?

So $$Pr[X \leq c] \leq t(c, b, E[X], Var[X])$$ where $b$ is the upper bound of $X$ and $t$ is some term?

Error Term of Chebyshev inequality?