Why does my memory used (accounting for cache) does not correspond to my processes memory usage?

Question: I am using Ubuntu 10.04 where a number of background jobs run every day. free and top both report that 3.9GB of the 4GB of memory is in use (of which ~90MB is cache/buffers).
When I do a top of ps aux and count the memory usage of my apps, I get to about 50%.
I am only running mysql, apache+passenger, and redis on the machine. It also hosts an NFS share.
Is there another way to check the remaining 49% of in use memory? And to free it without rebooting the server?
This is the output of free:
             total       used       free     shared    buffers     cached
Mem:       4010060    3820592     189468          0      84208     194168
-/+ buffers/cache:    3542216     467844
Swap:       741372     741292         80

ps aux:
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0  23864   472 ?        Ss   Feb02   0:13 /sbin/init
root         2  0.0  0.0      0     0 ?        S    Feb02   0:00 [kthreadd]
root         3  0.0  0.0      0     0 ?        S    Feb02   2:32 [ksoftirqd/0]
root         4  0.0  0.0      0     0 ?        S    Feb02   0:14 [migration/0]
root         5  0.0  0.0      0     0 ?        S    Feb02   0:00 [watchdog/0]
root         6  0.0  0.0      0     0 ?        S    Feb02   0:25 [migration/1]
root         7  0.0  0.0      0     0 ?        S    Feb02   1:30 [ksoftirqd/1]
root         8  0.0  0.0      0     0 ?        S    Feb02   0:00 [watchdog/1]
root         9  0.0  0.0      0     0 ?        S    Feb02   5:17 [events/0]
root        10  0.0  0.0      0     0 ?        S    Feb02   2:06 [events/1]
root        11  0.0  0.0      0     0 ?        S    Feb02   0:00 [cpuset]
root        12  0.0  0.0      0     0 ?        S    Feb02   0:00 [khelper]
root        13  0.0  0.0      0     0 ?        S    Feb02   0:00 [netns]
root        14  0.0  0.0      0     0 ?        S    Feb02   0:00 [async/mgr]
root        15  0.0  0.0      0     0 ?        S    Feb02   0:00 [pm]
root        17  0.0  0.0      0     0 ?        S    Feb02   0:45 [sync_supers]
root        18  0.0  0.0      0     0 ?        S    Feb02   0:47 [bdi-default]
root        19  0.0  0.0      0     0 ?        S    Feb02   0:00 [kintegrityd/0]
root        20  0.0  0.0      0     0 ?        S    Feb02   0:00 [kintegrityd/1]
root        21  0.0  0.0      0     0 ?        S    Feb02   0:47 [kblockd/0]
root        22  0.0  0.0      0     0 ?        S    Feb02   0:27 [kblockd/1]
root        23  0.0  0.0      0     0 ?        S    Feb02   0:00 [kacpid]
root        24  0.0  0.0      0     0 ?        S    Feb02   0:00 [kacpi_notify]
root        25  0.0  0.0      0     0 ?        S    Feb02   0:00 [kacpi_hotplug]
root        26  0.0  0.0      0     0 ?        S    Feb02   0:00 [ata_aux]
root        27  0.0  0.0      0     0 ?        S    Feb02   0:00 [ata_sff/0]
root        28  0.0  0.0      0     0 ?        S    Feb02   0:00 [ata_sff/1]
root        29  0.0  0.0      0     0 ?        S    Feb02   0:00 [khubd]
root        30  0.0  0.0      0     0 ?        S    Feb02   0:00 [kseriod]
root        31  0.0  0.0      0     0 ?        S    Feb02   0:00 [kmmcd]
root        32  0.0  0.0      0     0 ?        S    Feb02   0:07 [khungtaskd]
root        33  0.0  0.0      0     0 ?        S    Feb02  53:01 [kswapd0]
root        34  0.0  0.0      0     0 ?        SN   Feb02   0:00 [ksmd]
root        35  0.0  0.0      0     0 ?        S    Feb02   0:00 [aio/0]
root        36  0.0  0.0      0     0 ?        S    Feb02   0:00 [aio/1]
root        37  0.0  0.0      0     0 ?        S    Feb02   0:00 [ecryptfs-kthrea]
root        38  0.0  0.0      0     0 ?        S    Feb02   0:00 [crypto/0]
root        39  0.0  0.0      0     0 ?        S    Feb02   0:00 [crypto/1]
root        44  0.0  0.0      0     0 ?        S    Feb02   0:00 [pciehpd]
root        45  0.0  0.0      0     0 ?        S    Feb02   0:00 [scsi_eh_0]
root        46  0.0  0.0      0     0 ?        S    Feb02   0:00 [scsi_eh_1]
root        47  0.0  0.0      0     0 ?        S    Feb02   0:00 [kstriped]
root        49  0.0  0.0      0     0 ?        S    Feb02   0:00 [kmpathd/0]
root        50  0.0  0.0      0     0 ?        S    Feb02   0:00 [kmpathd/1]
root        51  0.0  0.0      0     0 ?        S    Feb02   0:00 [kmpath_handlerd]
root        52  0.0  0.0      0     0 ?        S    Feb02   0:00 [ksnapd]
root        53  0.0  0.0      0     0 ?        S    Feb02   0:00 [kondemand/0]
root        54  0.0  0.0      0     0 ?        S    Feb02   0:00 [kondemand/1]
root        55  0.0  0.0      0     0 ?        S    Feb02   0:00 [kconservative/0]
root        56  0.0  0.0      0     0 ?        S    Feb02   0:00 [kconservative/1]
root       246  0.0  0.0      0     0 ?        S    Feb02   2:58 [mpt_poll_0]
root       256  0.0  0.0      0     0 ?        S    Feb02   0:00 [mpt/0]
root       259  0.0  0.0      0     0 ?        S    Feb02   0:00 [scsi_eh_2]
root       278  0.0  0.0      0     0 ?        S    Feb02   0:08 [kdmflush]
root       282  0.0  0.0      0     0 ?        S    Feb02   0:00 [kdmflush]
root       297  0.0  0.0      0     0 ?        S    Feb02   0:36 [jbd2/dm-0-8]
root       298  0.0  0.0      0     0 ?        S    Feb02   0:00 [ext4-dio-unwrit]
root       299  0.0  0.0      0     0 ?        S    Feb02   0:00 [ext4-dio-unwrit]
root       338  0.0  0.0  17096     0 ?        S    Feb02   0:00 upstart-udev-bridge --daemon
root       340  0.0  0.0 147836    80 ?        Ss   Mar02   7:54 /usr/sbin/apache2 -k start
root       349  0.0  0.0  16880     0 ?        S<s  Feb02   0:00 udevd --daemon
root       554  0.0  0.0      0     0 ?        S    Feb02   0:00 [kpsmoused]
root       577  0.0  0.0      0     0 ?        S    Feb02 127:26 [vmmemctl]
root       657  0.0  0.0      0     0 ?        S    Feb02 126:36 [jbd2/sdb1-8]
root       658  0.0  0.0      0     0 ?        S    Feb02   0:00 [ext4-dio-unwrit]
root       659  0.0  0.0      0     0 ?        S    Feb02   0:00 [ext4-dio-unwrit]
root       788  0.0  0.0   6128     4 tty4     Ss+  Feb02   0:00 /sbin/getty -8 38400 tty4
root       791  0.0  0.0   6128     4 tty5     Ss+  Feb02   0:00 /sbin/getty -8 38400 tty5
root       793  0.0  0.0  49312   104 ?        Ss   Feb02   0:04 /usr/sbin/sshd
root       796  0.0  0.0   6128     4 tty2     Ss+  Feb02   0:00 /sbin/getty -8 38400 tty2
root       797  0.0  0.0   6128     4 tty3     Ss+  Feb02   0:00 /sbin/getty -8 38400 tty3
root       801  0.0  0.0   6128     4 tty6     Ss+  Feb02   0:00 /sbin/getty -8 38400 tty6
daemon     804  0.0  0.0  18932     0 ?        Ss   Feb02   0:02 atd
root       805  0.0  0.0  21128   156 ?        Ss   Feb02   0:47 cron
root       851  0.0  0.0  11360   304 ?        Ss   Feb02  15:18 /usr/sbin/irqbalance
root      1374  0.0  0.0      0     0 ?        S    Mar16   0:01 [jbd2/dm-2-8]
root      1375  0.0  0.0      0     0 ?        S    Mar16   0:00 [ext4-dio-unwrit]
root      1376  0.0  0.0      0     0 ?        S    Mar16   0:00 [ext4-dio-unwrit]
root      4088  0.0  0.0      0     0 ?        S    11:58   0:00 [flush-251:0]
root      4329  0.0  0.0  70660   720 ?        Ss   11:59   0:00 sshd: myuser [priv]
myuser    4347  0.0  0.0  70660   744 ?        S    12:00   0:00 sshd: myuser@pts/1
myuser    4348  0.0  0.1  26028  6432 pts/1    Ss   12:00   0:00 -bash
munin     5150  0.0  0.0  39916  2040 ?        Ss   Apr08   8:04 /usr/sbin/munin-node
redis     8110  3.0 38.7 2244244 1553116 ?     Ss   May19  27:58 /usr/bin/redis-server /etc/redis/re
www-data  8433  0.0  0.0 148344  1928 ?        S    May17   0:01 /usr/sbin/apache2 -k start
www-data  8435  0.0  0.0 148336  2132 ?        S    May17   0:01 /usr/sbin/apache2 -k start
myuser   10115  0.0  0.0  26624   592 ?        Ss   12:50   0:00 SCREEN -dR
myuser   10116  0.0  0.0  22808  2548 pts/0    Ss   12:50   0:00 /bin/bash
root     11410  0.0  0.0  27248   396 ?        Ss   Mar16   0:03 rpc.idmapd
root     11439  0.0  0.0      0     0 ?        S    Mar16   0:00 [lockd]
root     11440  0.0  0.0      0     0 ?        S    Mar16   0:03 [nfsd4]
root     11441  0.0  0.0      0     0 ?        S    Mar16   0:00 [nfsd4_callbacks]
root     11442  0.0  0.0      0     0 ?        S    Mar16   0:19 [nfsd]
root     11443  0.0  0.0      0     0 ?        S    Mar16   0:21 [nfsd]
root     11444  0.0  0.0      0     0 ?        S    Mar16   0:20 [nfsd]
root     11445  0.0  0.0      0     0 ?        S    Mar16   0:22 [nfsd]
root     11446  0.0  0.0      0     0 ?        S    Mar16   0:21 [nfsd]
root     11447  0.0  0.0      0     0 ?        S    Mar16   0:20 [nfsd]
root     11448  0.0  0.0      0     0 ?        S    Mar16   0:21 [nfsd]
root     11449  0.0  0.0      0     0 ?        S    Mar16   0:20 [nfsd]
root     11453  0.0  0.0  19032   316 ?        Ss   Mar16   0:09 /usr/sbin/rpc.mountd --manage-gids
myapp     11886  0.0  0.0  11984   196 pts/0    S+   13:03   0:00 /bin/bash shared/worker.sh
myapp     11887  0.1  2.0 180724 81252 pts/0    S+   13:04   0:03 resque-1.10.0: Forked 14745 at 1305
myapp     13085  0.1  2.0 195248 83180 ?        S    13:17   0:03 Rails: /var/www/myapp-prd/current
myapp     14745 80.9  2.0 185908 80900 pts/0    R+   13:29  19:09 resque-1.10.0: Processing myapp_import
www-data 15516  0.0  0.0 148224  1608 ?        S    May17   0:01 /usr/sbin/apache2 -k start
myuser   17579  0.0  0.0  17760  1220 pts/1    R+   13:53   0:00 ps aux
mysql    18736  2.5  1.1 345568 46396 ?        Ssl  Mar16 2349:04 /usr/sbin/mysqld
daemon   21340  0.0  0.0   8304     4 ?        Ss   Mar16   0:00 portmap
statd    21564  0.0  0.0  14600     4 ?        Ss   Mar16   0:00 rpc.statd -L
root     21823  0.0  0.0      0     0 ?        S    Mar16   0:00 [rpciod/0]
root     21824  0.0  0.0      0     0 ?        S    Mar16   0:00 [rpciod/1]
www-data 22353  0.0  0.0 148484  1352 ?        S    May16   0:02 /usr/sbin/apache2 -k start
root     23471  0.0  0.0      0     0 ?        S<   Mar16   0:00 [kslowd000]
root     23472  0.0  0.0      0     0 ?        S<   Mar16   0:00 [kslowd001]
root     23473  0.0  0.0      0     0 ?        S    Mar16   0:00 [nfsiod]
www-data 27001  0.0  0.0 148496  1588 ?        S    May17   0:01 /usr/sbin/apache2 -k start
root     27365  0.0  0.0  23432    20 ?        Ssl  May15   0:00 PassengerWatchdog
root     27368  0.0  0.0 164064  1064 ?        Sl   May15   6:51 PassengerHelperAgent
root     27370  0.0  0.2  61904  8408 ?        S    May15   0:02 Passenger spawn server
nobody   27373  0.0  0.0  72172    28 ?        Sl   May15   0:01 PassengerLoggingAgent
www-data 27383  0.0  0.0 148356  1740 ?        S    May15   0:02 /usr/sbin/apache2 -k start
www-data 27384  0.0  0.0 148492  1444 ?        S    May15   0:02 /usr/sbin/apache2 -k start
www-data 27385  0.0  0.0 148224  1568 ?        S    May15   0:02 /usr/sbin/apache2 -k start
www-data 27386  0.0  0.0 148496  1860 ?        S    May15   0:02 /usr/sbin/apache2 -k start
root     29402  0.0  0.0  16876     4 ?        S<   Mar16   0:00 udevd --daemon
root     29800  0.0  0.0      0     0 ?        S    Mar16   0:00 [kdmflush]
root     29804  0.0  0.0  16876     4 ?        S<   Mar16   0:00 udevd --daemon
www-data 30231  0.0  0.0 148352  1904 ?        S    May16   0:02 /usr/sbin/apache2 -k start
root     31072  0.0  0.0      0     0 ?        S    May12   0:37 [flush-8:16]
syslog   31116  0.0  0.0 126028   388 ?        Sl   May12   0:04 rsyslogd -c4
root     32217  0.0  0.0   6128     4 tty1     Ss+  Mar17   0:00 /sbin/getty -8 38400 tty1

cat /proc/meminfo:
MemTotal:        4010060 kB
MemFree:          155604 kB
Buffers:           48232 kB
Cached:           149308 kB
SwapCached:        42036 kB
Active:          1572044 kB
Inactive:         639616 kB
Active(anon):    1496792 kB
Inactive(anon):   517464 kB
Active(file):      75252 kB
Inactive(file):   122152 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:        741372 kB
SwapFree:             64 kB
Dirty:              1532 kB
Writeback:             0 kB
AnonPages:       1972572 kB
Mapped:             7920 kB
Shmem:                96 kB
Slab:              24384 kB
SReclaimable:      12224 kB
SUnreclaim:        12160 kB
KernelStack:        1368 kB
PageTables:        11632 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     2746400 kB
Committed_AS:    3150752 kB
VmallocTotal:   34359738367 kB
VmallocUsed:      281448 kB
VmallocChunk:   34359449320 kB
HardwareCorrupted:     0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
DirectMap4k:       12288 kB
DirectMap2M:     4132864 kB

One of the things I notice is the high value of Active(anon):    1496792 kB, which according to the docs is:

Memory that has been used more recently and usually not reclaimed unless absolutely necessary.

That's almost 1.5GB right there, is that normal? I do have very long (permanent) running processes (Resque) that fork each time a job comes in.
Comment: Could you post the output of `free`, and of `ps aux`? Maybe we spot something.
Comment: Added `free`, `ps aux`, and `cat /proc/meminfo` output.
Comment: In my opinion this is a normal behaviour of your linux machine.
check out this link for an easy explanation of the memory management in linux:
http://www.linuxatemyram.com/
Comment: I am not sure, I don't see that much caching or buffers going on in the `free` output compared to the memory in use.
Answer: Check your /proc/meminfo output, that will be provide more details of how your memory is beig used. Refer to this article to decipher the terms, scroll down to the meminfo section.
http://www.mjmwired.net/kernel/Documentation/filesystems/proc.txt
Comment: Never got to accept your answer, but this was really helpful in determining my applications memory usage.


React nested routes - undefined match

Question: First time using nested routes, so I am following this example as well as the article:
https://codesandbox.io/s/nested-routes-react-router-y5pt4?from-embed=&file=/src/index.js:2684-2693
https://learnwithparam.com/blog/how-to-handle-nested-routes-in-react-router/
However, the data that I am fetching has a different structure compared to the example, like a collection of articles.
https://content.guardianapis.com/search?api-key=test
What I am trying to do is to use the pillarName as the main navbar. The sectionName as the sub navbar, to map articles that belong to each subcategory.
The problem is that when I console.log(":infoSectionName", match) the WorldNews component, I get an undefined and so I can't map individual articles.
Source Code : https://codesandbox.io/s/spring-silence-g6q66?file=/src/App.js:5802-5811
I would really appreciate your advice.
Comment: your demo actually works
Comment: Yes, I have updated the demo. Thank you
Answer: Try defining route like this:
<code><Route path={`${match.path}/:infoSectionName`} component={WorldNews} />
</code>

React nested routes - undefined match


Vanishing derivative of determinant at degenerate points

Question: Suppose we have a smooth, square matrix valued function
\begin{equation}
A\in C^\infty(\mathbb R,Mat_{n\times n}\mathbb C)
\end{equation}
such that at the point $0\in\mathbb R$ the matrix $A(0)$ maps at least two independent vectors to the zero vector, that is the kernel of $A(0)$ is at least two-dimensional.
My claim is that the derivative of the determinant of $A$ has to vanish at $0$, that is
\begin{equation}
\left.\frac{d}{dt}\right|_{t=0}\det A(t)=0
\end{equation}
How would one go about proving something of this fashion?
Answer: Let $A(0)=USV^\ast$ be a singular value decomposition with the singular values on the diagonal of $S$ arranged in ascending order. As the nullity of $A(0)$ is at least two, the first columns of $S(0)$ are zero.
Define $S(t)=U^\ast A(t)V$ for every $t$ and denote by $\mathbf s_j(t)$ denotes the $j$-th column of $S(t)$. Then
$$
\begin{align*}
\left.\frac{d}{dt}\right|_{t=0}\det S(t)
&=\det(\dot{\mathbf s}_1(0),\mathbf s_2(0),\mathbf s_3(0),\mathbf s_4(0)\ldots,\mathbf s_n(0))\\
&\phantom{=} + \det(\mathbf s_1(0),\dot{\mathbf s}_2(0),\mathbf s_3(0),\mathbf s_4(0),\ldots,\mathbf s_n(0))\\
&\phantom{=} + \det(\mathbf s_1(0),\mathbf s_2(0),\dot{\mathbf s}_3(0),\mathbf s_4(0),\ldots,\mathbf s_n(0)) + \cdots,
\end{align*}
$$
which is equal to zero because $\mathbf s_1(0)=\mathbf s_2(0)=0$. Consequently, $\left.\frac{d}{dt}\right|_{t=0}\det A(t)=\det(UV^\ast)\left.\frac{d}{dt}\right|_{t=0}\det S(t)=0$.


stopping fibonacci input negatiive

Question: so i have made a fibonacci cycle but i need to make it stop when it hits a certain number and it must get higher than that. That part is not the problem mine problem is that i made a html where you can input the number but when you put in a negative number it doesnt do anything can someone help me
here is mine code
$a=0;
$b=1;
$c=$_POST["fibi"];

    for ($i = 0; $i <= $c; $i++) {

        $z = $a + $b;
        echo $z."
";

        if ($c == 0){

            echo 'the highest number is 0';
            break;

            }elseif($c < 0){

                echo "please enter a positive number";
                break;
        }
            elseif($z >= $c){

                echo "the highest number is $latest";
                break;
            }

        $latest = $z;
        $a = $b;
        $b = $z;

            }

    <!DOCTYPE html>

            <meta charset="UTF-8">
            <title>fibi</title>

        <form action="fibi.php" method="post">
            input:<input type= "number" name="fibi"> </form>

Comment: You should really do your homework assignments on your own.
Comment: Always sanitize user input. in that case make sure, it's a positive integer. And do that _before_ you start using that variable.
Comment: i don't even see php tags on the code block.
Comment: [`isset`](https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjS5bSlx4vLAhUHThQKHeSHB2sQFggjMAA&url=http%3A%2F%2Fphp.net%2Fmanual%2Fen%2Ffunction.isset.php&usg=AFQjCNEilnOC2VNydDdQDAXjnJjWAYf6Mg&bvm=bv.114733917,d.bGg), [`empty`](https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&cad=rja&uact=8&ved=0ahUKEwj93sumx4vLAhVGxxQKHaLcClIQFgiYATAB&url=http%3A%2F%2Fphp.net%2Fmanual%2Fen%2Ffunction.empty.php&usg=AFQjCNFOSUbVb_y7NH0-x51nm-gQ4YFk2A) and [`ctype_digit`](http://php.net/manual/en/function.ctype-digit.php) are your friends for validation.
Comment: What action do you want perform if the input is negative?
Comment: if the input is negative i what it to echo something like i tried with elseif($c < 0){

                echo "please enter a positive number";
                break; but that didnt work
Answer: Just add a condition like if($c > 0) around your code.

stopping fibonacci input negatiive


Probability of at least 4 cards of the same denomination out of 13

Question: $13$ out of $52$ cards are chosen randomly. My task is to calculate the probability that these $13$ cards will contain all $4$ of at least one of the $13$ denominations. Can anyone help please?
Answer: The Inclusion-Exclusion should work here.
Let $c_1$ be the condition that all aces are in the $13$ chosen cards. And similuarly define $c_i$ up to $i=13$. Now to calculate all the combinations we have:
$$P = \sum P(c_i) - \sum P(c_i,c_j) + P(c_i,c_j,c_k)$$
$$P = \frac{\binom{13}{1} \cdot \binom{48}{9} - \binom{13}{2} \cdot \binom{44}{5} + \binom{13}{3} \cdot \binom{40}{1}}{\binom{52}{13}} \approx 0.0342$$
Comment: Why do you subtract (13 choose 2) * (44 choose 5)
Comment: @SargsyanGrigor [Inclusion-Exclusion Principle](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle).
Comment: @SargsyanGrigor That is to take care of the double counting. When a set of 13 cards contains two full denominations we have counted it twice, instead of just once.


Check contents of order in commerce

Question: So I have a custom module function that checks a cart order for a certain product type
global $user;
$order = commerce_cart_order_load($user->uid);
$wrapper = entity_metadata_wrapper('commerce_order', $order);

foreach ($wrapper->commerce_line_items as $delta => $line_item_wrapper) {
  $type = $line_item_wrapper->commerce_product->value()->type;
  if($type=='X'){
    //go mental
  }
}

This is used within checkout to display certain list items for "checkout progress" depending on whether a product type is in the cart (i.e show the gift aid stage if there is a donation).
The issue with this is it seems that when the order is no longer within the cart, for example when we hit the payment stage, and further go on to checkout complete. So the function commerce_cart_order_load($user->uid); no longer works. How would I achieve this same functionality checking the order for product of type 'X' when the order status is updated post-shopping-cart?
I think I can use $order = commerce_order_load(); but somehow I need to get the $order_id?
Answer: $order_id = arg(1);
$orderLoad = commerce_order_load($order_id);

foreach ($orderLoad->commerce_line_items['und'] as $line) {
    $line_item = commerce_line_item_load($line['line_item_id']);
    $product_id = $line_item->commerce_product['und'][0]['product_id'];
    $product = commerce_product_load($product_id);
    $type = $product->type;

    if($type == 'X'){
      //go mental
    }
}

If anyone has any improvements to this code (to make it more efficient etc. then please comment below). Thanks.
Comment: I would suggest use [commerce_cart_order_load](http://drupalcontrib.org/api/drupal/contributions!commerce!modules!cart!commerce_cart.module/function/commerce_cart_order_load/7) function directly with an argument for current user id: `$orderLoad = commerce_cart_order_load($uid)`

Check contents of order in commerce


The Function $f:\mathbb{R}^{2}\rightarrow \mathbb{R}^{2}$ defined by $f(r,\theta)=(r\cos\theta,r\sin\theta)$

Question: Let  $f:\mathbb{R}^2\rightarrow \mathbb{R}^2$  be the function defined by $f(r,\theta)=(r\cos\theta,r\sin\theta).$ Then for which of the open subset $U$ of $\mathbb{R}^2$ given below, $f$ restricted to $U$ admit an inverse?

$U=\mathbb{R}^2$
$U=\{x,y \in\mathbb{R}^2:x>0,y>0\}$
$U=\{x,y \in\mathbb{R}^2:x^2+y^2<1\}$
$U=\{x,y \in\mathbb{R}^2:x<-1,y<-1\}$

It is clear 1 is not true as $\sin ,\cos$ are periodical function. Similarly 3 is not true. What about 2nd and 4th ? please help.Thanks in advance.
Comment: This appears to be a duplicate of http://math.stackexchange.com/questions/1586259/on-which-open-set-f-admits-an-inverse#comment3229015_1586259
Comment: Do you want inverse, or continuous inverse.
Answer: To admit an inverse $f$ restricted to $U$ must be bijective, in particular one-one.
$1$ and $2$ are not True since $f(1,2) = f(1,2+2\pi)$.
$4$ is not true since $f(-2,-2\pi) = f (-2,-4\pi)$.
$3$ is not True since $f(0,1/2) = f (0,1/4)$.
Comment: its means its incorrect question?
Comment: f(1, 2) = f(1, 1+2$\pi$), how come?
Comment: there should be $f(1,2+2\pi)$
Comment: That's what I am thinking.
Comment: oh. yes ..i am sorry for that mistake,
Comment: no, problem at all. Edit your answer now.
Comment: we can't take r as negative
Comment: The problem doesn't seem to be properly formulated.
Comment: but f is from $R^2$ to $R^2$.
Comment: yes problem is not well defined
Answer: In options 2 and 4, The determinant of jacobian= $r$ is nonzero everywhere. Thus inverse function theorem guarantees that, for every point $p$ in  $U$, there exists a neighborhood about $p$ over which function is invertible. This does not mean function is invertible over whole domain $U$: in this case $f$ is not even injective since it is periodic : $f(x,y)=f(x,y+2 \pi)$. (And injection is necessary for inverse.)
Comment: I think all options are incorrect???
Comment: @neelkanth of course all options are incorrect. Actually many got confused that using inverse function theorem, options 2  and 4 should be correct. That's why I wrote this.


Show/hide button: put result into POST variable

Question: I have a long list of links in my website's menu. I show the first three links per default, and I have a "Show/hide" button for the rest of the links.
I would like to be able to change the default value (show or hide) according to the visitor's preference.
--> So the default value is "hide" to start with. If the visitor clicks "show" and then clicks a link, I want the next page to be "show" per default. If he then clicks hide, default is "hide".
Below is my menu. 1-2-3 are always shown, 4-5-6 are shown or hidden.

1

2

3

4

5

6

 <input type="button" value="Plus / Moins" onclick="if (
 this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display != 'block') {
 sendMenuDisplay('block');
 this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display = 'block';
 } else {
 sendMenuDisplay('none');
 this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display = 'none';  }" />

My question is: How can I save what the visitor choses (show or hide), put it in a $_POST variable and use it as the default value on the next page?
Thanks for your time and help
Comment: Sorry I realise that is not clear. My question is: How can I save what the visitor chose (show or hide), put in a $_POST variable and use it as the default value on the next page?
Answer: You could POST or PUT the value and put in a cookie or a session attribute for use in subsequent pages.  You could also POST or PUT the value using ajax and put the value in a cookie or session attribute for later use.  You could also store the value in a database and use across user-sessions.
Comment: Those are all good solution, but I don't know how to actually save the value to store it into a POST, database or other. Since show/hide is determined without reloading the page, how can I extract the value? In the "onclick" code, how can I say "onclick show/hide and store that value somewhere"?


iOS7 UIImage drawAtPoint not retina

Question: i am trying to draw an image with the following code:
[img drawAtPoint:CGPointZero];

but the problem is that on an iphone with a retina display the image doesn´t get drawn in retina scale. It seems like the image gets upscaled and then drawn.
I don´t want to use drawInRect because the image is in right size and it´s way slower to use drawInRect.
Any ideas?
Answer: You probably are not setting the appropriate scale factor. When you create the bitmap context one of the arguments is the scale:
void UIGraphicsBeginImageContextWithOptions(
   CGSize size,
   BOOL opaque,
   CGFloat scale
);

According to the official documentation scale is:

The scale factor to apply to the bitmap. If you specify a value of
  0.0, the scale factor is set to the scale factor of the device's main screen.

You're probably passing 1.0f which will result in the issue you've described. Try passing 0.0f.

iOS7 UIImage drawAtPoint not retina


Dirac delta distribution and fourier transform

Question: Dirac delta distribution is defined as
$f(t_{0})=\int_{-\infty }^{\infty } \! f(t)\delta(t-t_{0}) \, dt $ where $f(t)$ is smooth function. Then my question is:
:Calculate Fourier transform $\hat \delta(\omega)$ from $\delta (t-t_{0})$
Solution:
$$\hat \delta(\omega)=\frac{1}{\sqrt{2 \pi} }\int_{-\infty }^{\infty } \! \delta (t-t_{0}) e^{-j \omega t}\, dt   $$

$$\hat \delta(\omega)=\frac {1}{\sqrt{2 \pi}}e^{-j \omega t_{0}}$$

Can someone explain me how they got this solution and write what are the steps between? On internet I always find some general formulas and I don't know how to use them.
Comment: Just follow the given definition...
Answer: You indeed have to start with the definition. The action of the Fourier transform of the distribution $f$ on a test function $\phi$ is defined as
$$(\mathcal F[f], \phi) = (f, \mathcal F[\phi]),$$
which is valid because if $\phi$ is a test function of rapid decay, then so is $\mathcal F[\phi]$, and the functional defined in this way is linear and continuous. From this we obtain
$$(\mathcal F[\delta], \phi) =
(\delta, \mathcal F[\phi]) =
\mathcal F[\phi](0) =
\frac 1 {\sqrt {2 \pi}} \int_{-\infty}^\infty \phi(t) dt,$$
which means that $\mathcal F[\delta]$ is the same functional as $1/\sqrt {2 \pi}$.
The transform of $\delta(t - t_0)$ can be found either in the same way directly or by applying the translation property, which is valid for singular distributions because a linear transformation is defined so as to be consistent with a linear transformation of a regular distribution.
Comment: (+1)  Well written and concise as usual.
Answer: Let $f$ be a smooth integrable function as you commented. Then we can define the Fourier Transform as
$$\mathcal{F}[f](y) := \frac{1}{\sqrt{2\pi}}\int_{\mathbb{R}}f(x)e^{-iyx}\mathrm{d}x$$
We can also derive the inverse of Fourier Transform as:
$$\mathcal{F}^c[f](y):=\frac{1}{\sqrt{2\pi}}\int_{\mathbb{R}}f(x)e^{+iyx}\mathrm{d}x$$
Now lets see what happen wen we apply both to a function
$$f(y) = \mathcal{F}^c[\mathcal{F}[f]](y) =  \frac{1}{2\pi}\int_\mathbb{R}\left(\int_{\mathbb{R}} f(\omega)e^{-i\omega x}\mathrm{d}\omega \right)e^{+iyx}\mathrm{d}x = \int_{\mathbb{R}}f(\omega)\left(\int_{\mathbb{R}}\frac{1}{2\pi}e^{-i(\omega-y)x}\mathrm{d}x\right)\mathrm{d}\omega$$
We can see in this last equality that the  function in brakets acts as a Dirac Delta. So we can relate this as de Dirac as a notation (because the Dirac Delta just have formal sense in distribution theory)
$$\delta(\omega-y) = \frac{1}{2\pi}\int_{-\infty}^{+\infty}e^{-i(\omega-y)x}\mathrm{d}x$$
This is an intuitive constructive way of seen that the Dirac is related to Fourier Transforms. Now for your question we can use the definition on how an Dirac Delta acts
$\hat{\delta}(\omega) = \frac{1}{(2\pi)^{1/2}}\int \delta(t-t_0)e^{-i\omega t}\mathrm{d}t = \frac{1}{(2\pi)^{1/2}}e^{-\omega t_0}$
Where we just used the above
$$f(y) = \int f (\omega)\delta(\omega-y)\mathrm{d}\omega$$
For $f(t):=e^{-i\omega t}/\sqrt{2\pi}$
Answer: We have \begin{align}f(t_{0})=:\int_{-\infty }^{\infty } \! f(t)\delta(t-t_{0}) \, \text{d}t &&(1)  \\ \hat g(\omega):=\widehat{g(\cdot)}(\omega):=\int_{-\infty }^{\infty }e^{-j \omega t}g(t)  \ \text{d}t &&(2) \end{align}
and therefore we get:
$$\widehat{\delta(\cdot-t_0)}(\omega) \stackrel{(2)}{=} \frac{1}{\sqrt{2 \pi} }\int_{-\infty }^{\infty }  \underbrace{e^{-j \omega t}}_{=:f(t)} \delta (t-t_{0})\ \text{d}t\stackrel{(1)}{=}\frac{1}{\sqrt{2 \pi}}f(t_0)=\frac{1}{\sqrt{2 \pi}}e^{-j \omega t_{0}}$$
To be precise this is the Fourier transform of $\delta(\cdot-t_0)$ and not $\delta$. For $\delta=\delta(\cdot)$ we'd have to set $t_0=0$ in above formula and we get $\hat\delta(\omega)=(2\pi)^{-1/2}.$


Continuity of $g(x)$

Question: Define $g(x) = \sum_{n=0}^{\infty} \frac{x^{2n}}{1+x^{2n}}$.
Find the values of x where the series converges and show that we get a continuous
function on this set.
I can show $g(x)$ converges for $x \in (-1,1)$. $f_n(x) = \frac{x^{2n}}{1+x^{2n}}$ is obviously continuous on this set, so all I need to show $g(x)$ continuous is $\sum f_n \rightarrow g$ uniformly. The only thing I can think of is to use Weierstrass M-Test but I can't find the right $M_n$ s.t. $|f_n| \leq M_n$. Suggestions?
Comment: General member doesn't uniformly converge to $0$ on $(-1,1)$.
Answer: Sketch: You can't prove uniform convergence on $(-1,1)$, because the series does not converge uniformly on $(-1,1)$. In point of fact, for $-1<x<1$: $$g(x)-\sum_{k=0}^n f_k(x)\ge\frac12\sum_{k=n+1}^\infty x^{2k}\ge 0$$ and $\sup\limits_{x\in(-1,\alpha]} \sum\limits_{k=n+1}^\infty x^{2k}=\sup\limits_{x\in[\alpha,1)} \sum\limits_{k=n+1}^\infty x^{2k}=\infty$ for all $\alpha\in(-1,1)$ and $n$.
However, what you can and should prove is uniform convegence on compact subsets of $(-1,1)$. For each $\beta>0$, you can make an uniform estimate on $[-\beta,\beta]$ in similar fashion as you'd do for $\sum_k x^{2k}$ (even use Weierstrass M-test, if you want).
Comment: How does $\sup\limits_{x\in(-1,\alpha]} \sum\limits_{k=n+1}^\infty x^{2k}=\sup\limits_{x\in[\alpha,1)} \sum\limits_{k=n+1}^\infty x^{2k}=\infty$? $\sum_{k=n+1}^{\infty} (x^2)^n$ is geometric with $|r| < 1$.
Comment: @chuckyeager Yes, it's $\frac{x^{2n+2}}{1-x^2}$ which diverges to $\infty$ as $x\to\pm1$.

Continuity of $g(x)$


ArgumentError ao chamar função

Question: Estou tentando executar esse meu código abaixo:
class ProdutItem

  attr_reader :price_unit, :x_item, :price_promo

  def initialize(price_unit: , x_item: 1, price_promo: price_unit)
    @price_unit = price_unit
    @x_item = x_item
    @price_promo = price_promo
  end

  def price_qtde(units)
    units_promo = units / @x_item
    units_eo = units % @x_item
    @price_promo * units_promo + @price_unit * units_eo
  end

end

rules = ProdutItem.new(price_unit: 50, x_item: 3, price_promo: 130)
puts rules.price_qtde

Porem está aparecendo esse erro abaixo:

Checkout.rb:11:in `price_qtde': wrong number of arguments (given 0, expected 1) (ArgumentError)

Answer: A função price_qtde recebe um parâmetro (units), mas ao chamar essa função na última linha do seu código, não está informando argumento algum.
Se o valor de units devesse ser 2, então faça:
puts rules.price_qtde 2

ou
puts rules.price_qtde(2)

ArgumentError ao chamar função


Validate pydantic fields according to value in other field

Question: I'm trying to validate some field according to other fields, example:
<code>from pydantic import BaseModel, validator
class MyClass(BaseModel):
    type: str
    field1: Optional[str] = None
    field2: Optional[str] = None
    field3: Optional[str] = None

   @validator("type")
   def has_required_fields(cls, v, values):
       required_fields = {"v1": ["field1", "field3"], "v2": ["field2"]}
       for required_field in required_fields[c]:
           if not values[required_field]:
               raise Exception
</code>
But my issue is that the values dict is empty. How should I access the other fields correctly in this situation?
Comment: Use root validator or take into account that order matters for per-field validation and move type field at the end.
Comment: [The documentation](https://pydantic-docs.helpmanual.io/usage/validators/) mentions both: root validators and validation order.
Comment: I didn't know that order matters, that explains some things
Answer: Fields are validated in order they are initialized. Dictionary is empty because there is no validated fields as the type is the first field to be validated.
-> Reorder the field initialization
or
-> Use root validator
Answer: I believe you need to set "always=True" in the validator if you plan on type being empty when you initialize it. See here:
https://github.com/pydantic/pydantic/issues/691#issuecomment-785101470


Show that if a self-adjoint matrix is triangular, then it must be diagonal.

Question: I want to show that if a self-adjoint matrix is triangular, then it must be diagonal.
Here's my thoughts so far:
Self adjoint is simply $\langle A \pmb x, \pmb y \rangle = \langle \pmb x, A \pmb y\rangle$
If $A$ is lower triangular then $\langle \pmb b, \pmb y \rangle = \langle \pmb x , \pmb c\rangle$ where
$$
\pmb b = \begin{bmatrix}a_{11}x_1 \\ a_{21} x_2 + a_{22} x_2 \\ \vdots \\ \sum_{i=1}^n a_n x_i\end{bmatrix}
$$
We don't really know anything about $\pmb c$ beyond that $A \pmb y = \pmb c$ and the equality shown above.
Intuitively, I want to think of the inner product as being characterized by the identity matrix because then I'd have a straightforward system of equations that would show that $A$ must only have entries along the diagonal...
Another thought is to somehow show that $A$ must be both upper and lower triangular to be self-adjoint which would imply it's diagonal.
I'm not sure how to advance from here.
Answer: Hint: Take $x$ to be the standard basic vector $e_i$ and $y$ to be the standard basic vector $e_j$. So $\langle e_i, Ae_j\rangle=\langle Ae_i, e_j\rangle$. This should give you some info about the matrix $A$.
Comment: @financial_physician: The dot product in the OP is standard. If we "mess things up", we would also have to "mess up" the standard basic vectors $e_i$, and change $A$ accordingly.
Comment: $Ae_j$ would be some column of $A$ but I'm still not sure how that'd help me compare things across the inner product...
Comment: True, $Ae_j$ is the $j$-th column of $A$. Then $\langle e_i, Ae_j\rangle$ is the entry $A_{i,j}$. And the equality for every $i,j$ means that $A_{i,j}=A_{j,i}$, so $A$ is symmetric. Symmetric and triangular means diagonal.
Comment: I don't think $\langle e_i, Ae_j \rangle$ is the $A_{i,j}$ entry unless we know that the inner product is characterized by the identity matrix. Wouldn't this mess things up if we had a permutation matrix or weighted inner product?
Answer: You can check that with the standard inner product, the adjoint of a matrix $A$ is given by the transpose $^tA$ (or conjugate transpose if you are using $\mathbb C^n$ rather than $\mathbb R^n$).
Comment: By "check" I meant it's something you can prove in general without too much trouble
Comment: But checking isn't sufficient is it? I need to do it more generally


Why tilt a violin bow inward? (I.e., stick towards bridge, not towards scroll)

Question: In this recording of Jascha Heifetz he frequently tilts the bow inwards (by which I mean towards the bridge instead of "outwards" towards the scroll).  Here's a frame showing it:

I have never seen this done before.  Is this a known technique, with a known purpose?  Is it used by any other virtuosi?
Comment: It looks to me as though it is because his right arm gets better control by not stretching out as far as he would need to keep the bow at right angles to the string.
Answer: Heifetz uses a Russian bow-hold. This is almost never seen today in classical violinists and is more common in gypsy jazz. Some things are easier with a Russian bow-hold, you naturally apply more pressure near the tip, and some things are more difficult because you don't have any contribution from the fourth finger balancing the bow near the frog or when the bow leaves the string as in the staccato here.
Mischa Elman was another great from about the same time as Heifetz who also used the Russian bow-hold. Here you see him also tilting the bow the "wrong" way, showing the audience more of his bow hair.
Answer: A frame from Hora Staccato. Must be a reason for using this technique for this piece. If you watch this piece through, he also completely changes his bow hold when reversing the bow.
https://www.google.com/search?q=heifitz+upbow+staccato&rlz=1C1CHBD_enUS896US896&oq=heifitz+upbow+stacca&aqs=chrome.1.69i57j33i10i160l2j33i299.13707j0j7&sourceid=chrome&ie=UTF-8#fpstate=ive&vld=cid:a19afb2d,vid:Mag2mc5Vva0
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://music.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://music.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/74923)
Answer: There is not need to do this when it's slow, it even is a mistake. But when very fast, to facilitate repetitive string changing, we tilt it when switching up bow to down bow. When doing this, make sure to not skid.


show specific number of posts on front page for mobile d7

Question: I would like to show only a few posts for mobile I have mobile_detect as well as mobile_detect_ctools mobile_detect_variables, installed and working.
I am using an adaptive theme, $is_mobile successfully in theme/page.tpl but I am unable to use it in settings.php where I believe I need to set.
$conf['default_nodes_main'] = $mobile-frontpage-post-number //(much lower than desktop);
How can I put global $conf vars in page.tpl or get $is_mobile from mobile_detect_variables working in settings.php.
tyvm.
Answer: I ended up just redirecting the mobile devices to mobile front page(view),
I was trying to avoid this, but it does not seem to be much trouble.
Add this code near the top of MYTHEME/page.tpl.php
<?php if ($is_mobile == TRUE && drupal_is_front_page()):
drupal_goto('/mobile');
endif;
?>

Then you can adjust the pager, number of posts etc. I suppose this
is a workaround not an answer.


How to expire just one attribute in a session (Java)

Question: I am looking for a best solution on how to expire just one parameter in within the session in Spring. I have a session that expires in 3 hours, I need to add one parameter to it and expire it in 10 min.
ANy suggestions ?
Thank you
Comment: it's not clear what access to the expired param should produce. Exception?
Answer: You can create a solution where all accesses to a session go through a component, which wraps your session and provides the expiry policy you want. This component could have a session scope.
Comment: Thanks for your reply, I created component but not sure how to set expiration date.

@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class SessionModel {


Last column in grid needs custom title

Question: So I am using ExtJS to render grids with data. I have features on the grid which are good but I want to last row to say "Total of All" but it's repeating the first group title.
Below is my custom group header:
features: [{
        ftype: 'summary'
    }, {
        //ftype: 'grouping'
        ftype: 'groupingsummary',
        groupHeaderTpl: Ext.create('Ext.XTemplate',
            '',
            '{name:this.formatName} ({rows.length})',
            {
                formatName: function(name) {
                    return name.charAt(0).toUpperCase() + name.slice(1);
                }
            }
        ),
        //groupHeaderTpl: '{name} ({rows.length})',
        hideGroupedHeader: true
    }],

And here is the summery type config that is producing the totals title:
columns: [{
                id       :'service-product',
                text   : 'Product',
                flex: 1,
                sortable : true,
                dataIndex: 'PACKAGE',
                summaryType: function(records) {
                    var myGroupName = records[0].get('LISTING');
                    return ''+myGroupName.charAt(0).toUpperCase() + myGroupName.slice(1)+' Totals';
                }
            }

Here is the screenshot with the highlighted title i want to make custom. I have tried a few things. Anyone know how to get a reference to this cell and change the the title?

Thank you in advance :)
Nathan
Comment: Is `myGroupName` "Renting Totals"?
Comment: `var myGroupName = records[0].get('LISTING');` So what ever it is at that time first "renting" then "sales" but then it's down as "renting" again. I want the very last row to be custom.
Answer: You may look at this inside summaryType. I have noticed that when it is invoked for total group it points to Ext.data.Store, and when it is called for 'normal' group it points to Ext.util.Group.
So example summaryType may look like this:
summaryType: function(records) {
    console.log(this.$className);
    if (this.isStore) {
        return "Total of all";
    }
    var myGroupName = records[0].get('group');
    return '' + myGroupName + ' Totals';
}

Working sample: http://jsfiddle.net/b2LS5/4/

Last column in grid needs custom title


General expression for $\sin(2^n x)$

Question: Are there general expressions for $\sin(2^n x)$ and $\cos(2^n x)$ that only involve $\sin x$ and $\cos x$, and that moreover involve only polynomial (in $n$) number of terms?
Edit:
$2^n$ is not polynomial in $n$. A proof that no such expression exits (perhaps using the uniquness of Chebyshev polynomials?) would be gladly accepted.
Comment: For $\sin(2^n x)$, you can repeatedly use $\sin (2x)=2\sin x\cos x$, but you'll end up with a $2^n$ term flying around. You can so something analogous for the cosine.
Comment: $$\sin 2^rx=\sin 2(2^{r-1}x)=2\sin2^{r-1}x\cos 2^{r-1}x $$

Put $r=1,2,3,\cdots ,n-1,n$
Comment: @PeterTamaroff - I know, which is why I specifically stated " polynomial (in n) number of terms".
Comment: The first thing you need to define is term. Are you looking for an expression of the form $\sin(2^nx)=P(\sin(x),\cos(x))$ where $P$ is a polynomial and then you count as term the terms of $P$? Are you looking for more general expressions and you really want to count the number of operations necessary to compute it? These questions are not the same, so it would be good to specify. What kind of expressions you are looking for, and what is a term?
Comment: My initial idea is to use $e^{i 2^n x}=(e^{ix})^{2^n}=(\cos{x}+i \sin{x})^{2^n}$.
Comment: You may be interested in Chebychev polynomial : for every $n \ge 1$, there exist real a polynomial $T_n$ such that $\cos(nx) = T_n(cos(x))$. In particular $T_2 = 2X^2-1$ and $T_{2^n} = T_2 \circ \ldots \circ T_2$ ($T_2$ composed $n$ times with itself).
Answer: If I understand the spirit of the question, no such expressions exist. First, $\cos(2^n \theta)$ is even, so a polynomial in $\sin \theta$ and $\cos \theta$ that is equal to $\cos(2^n \theta)$ contains only even powers of $\sin\theta$, and therefore may be written as a polynomial in $\cos\theta$, as marty cohen notes.
Now, $\cos(2^n \theta)$ has $2^{n+1}$ simple zeros in the interval $[0, 2\pi]$. By contrast, if $p_n$ is a polynomial with real coefficients and "polynomial-in-$n$ terms" (my interpretation of the original question), then $p_n$ has polynomial-in-$n$ roots in the interval $[-1, 1]$ by Descartes rule of signs, and consequently $p_n(\cos \theta)$ vanishes only polynomial-in-$n$ times in $[0, 2\pi]$.
Comment: Welcome to MSE!
Answer: I might be missing something here... but the identity $\cos(2x)=2\cos^2(x)-1$ can be trivially applied $n$ times to obtain an expression with polynomial length:
$$\begin{eqnarray}
\cos(2^nx) & = & 2\left(\cos(2^{n-1}x)\right)^2-1 \\
& = & 2\left(2\left(\cos(2^{n-2}x)\right)^2-1\right)^2-1 \\
& = & 2\left(2\left(2\left(\cos(2^{n-3}x)\right)^2-1\right)^2-1\right)^2-1 \\
& & \vdots \\
& = & 2\left(2\left(\ldots \left(2\left(2\cos^2 x-1\right)^2-1\right)^2\ldots\right)^2-1\right)^2-1 \\
\end{eqnarray}$$
Note that this results in just one occurrence of the $\cos x$ term and the whole expression contains $n$ twos, $n$ squarings and $n$ subtractions of $1$. Thus, length-wise it's polynomial. Of course, getting rid of the squares would blow the size of the formula up exponentially.
Similar approach can be used for $\sin(2^nx)$; it suffices to notice that $$\sin(2^nx)=2^n\sin(x)\cos(x)\cos(2x)\cos(4x)\ldots\cos(2^{n-1}x)$$ and apply the expression above to the $\cos(2^kx)$ terms (resulting in expression of length quadratic in $n$). If one is interested in evaluating the expression, it's possible to do much better (thanks to the high level of redundancy).

General expression for $\sin(2^n x)$


ASP.NET Passing Inconsistent DateTime Format to SQL Server

Question: I know this is an age-old question but I'm not exactly new to it and I haven't found an answer which helps me so far!
I've got an ASP.NET site which displays data from an SQL Server 2005 database.  At the top of the page are 'Date From' and 'Date To' textboxes which are used to filter the data shown beneath.
The data is displayed using an SqlDataSource, and the two dates are passed as parameters to a Stored Procedure.  The textboxes display the dates and accept input in UK date format (dd/MM/yyyy) and it works fine.
Now I've added a new page with exactly the same setup, displaying slightly different data. In the backend I created a new Stored Procedure by copying and pasting my original one, it's almost identical.  And yet on this page I get errors with my dates because they're being read as MM/dd/yyyy, meaning that today's date, for example, 15th August 2011, is passed as 15/08/2011 and isn't a valid date.
I've checked over everything and I can't understand why this should work on one page and not another, especially when I've basically just copied all of the original code and tweaked it slightly.  Can anyone suggest anything I can check that I might not have thought of?
Comment: The problem is definitely with the local report (RDLC). Even though my SQLDataSource works fine, and a GridView is happily populated with the data, filtered by the date parameters I'm passing to the Stored Procedure, the RDLC is taking it upon itself to check the date parameters, and it doesn't seem clever enough to work out that they're in a format other than what it's expecting.  This is so irritating - the report shouldn't care about the dates at all.  There are no dates on the report, no parameters at all, the dates are nothing to do with the report!  Filtering is done in the datasource.
Answer:
The text boxes are strings, which are in the thread local which is set from the browser (langauges).
Convert them to aa DateTime object first, using a local aware transformation, then write the dateTime object to the server. NEVER (!) deal with strings to sql server unless you format them in ISO independent form (2011-08-17 23:52:11).

But in general, ASp.NET will show dates, times, numbers in the local langauge of the browser. Either turn that off, or deal with it. It is nice for the user. So, check locales - user, server process. What is the thread current locale?
Comment: I might have just got closer to the cause of the problem.  On my page that works the data is displayed in a GridView.  On the page that doesn't it's in a report (RDLC).  So I added a GridView to the page that isn't working and that displayed the correct data.  So somehow the problem is with the report.  The report doesn't have any parameters or any date/time fields on it, it should just be displaying the data specified in the DataSource, which is correct because it shows the right data in a GridView!?
Answer: You need to use the SQL convert in stored procedure like:
convert(varchar, @yourdateParameter, 103) for format dd/mm/yyyy

or
convert(varchar, @yourdateParameter, 101) for format mm/dd/yyyy

Hope this helps.
Comment: I've tried that, even though I didn't have to in the sp that's working, and it didn't make any difference.  As per my comment above, it seems that the correct data is being retrieved, it's just the report which is somehow trying to display different data than the datasource is returning.


What is the right way to make an sketch's exported SVG responsive?

Question: i'm learning to use svgs in my sites.
While making myself the code for the shapes it's easy to make it responsive, when i'm trying to use the same tecnique with a Sketch.app exported SVG it doesn't work. Anyone can tell me why?
Here is 2 examples:
first: shapes handcoded: here
second: shapes created with sketch: here
to achieve my goal i'm using this css code:
 .svg-container {
  display: inline-block;
  position: relative;
  width: 100%;
  max-width:1102px;
  padding-bottom: 31%; /** height/width **/
  vertical-align: middle;
  overflow: hidden;
}

.svg-content {
  display: inline-block;
  position: absolute;
  top: 0;
  left: 0;
}

Answer: The Sketch SVG has a hardcoded width and height:
<svg class="svg-content" width="1102px" height="348px"

To make it responsive, change both the width and height to "100%".  Or you can remove them completely, which is the same thing because they default to 100%.
Comment: so stupid! spent hours scratching my head and the problem was so simple! ty very much!


Why does my code do stuff i dont tell it to do?

Question: I'm new to coding so I don't get why my code isn't functioning. I want to have the variable com with input() as a line to write commands in and if the command is for example "delete file", I ask for a file name and it should delete the file. But if I type "delete file" it just shows me this:
Command: delete file
File Name: tester.txt
Contents:
testfile 123 test
File name:

It just shows the contents of the file instead of deleting it. It should only read the contents if com is "open file". I hope you get my problem.
Thats the code:
com = input("Command: ")

if com == "open file" or "openfile":
  file = input("File Name: ")
  f = open(file, "r")
  print("Contents: ")
  print(f.read())

if com == "delete file" or "deletefile":
   filefordelete = input("File name: ")
   if os.path.exists(filefordelete):
      os.remove(filefordelete)
   else:
      print("File does not exist!")

input("Press enter to stop the program")

I want to delete the file when I type into the variable com "delete file". I cant find a solution why it's doing the stuff it should do when the variable com is "open file".
Comment: Computers _do_ what you tell them. However, it might be not what you _meant_ to tell them…
Answer: if com == "open file" or "openfile": evaluates to
if False or "openfile"

"openfile" evaluates to True value in the if statement.
And now since it's an or condition - False or True evaluates to True, therefore your first  if statement is True and the block is executed.
You will need to rewrite your condition like this:
if com == "open file" or com == "openfile":

or
if com in ["open file", "openfile"]:


grunt writes content to console instead of file?

Question: I am trying to add scss to my grunt file so i ran the following command:
npm install grunt-contrib-sass sass --save-dev.
Then i added the following to my Gruntfile.js
grunt.loadNpmTasks('grunt-contrib-sass'); and
grunt.initConfig({
...
sass: {
    dev: {
        files: {
            '<%=meta.src %>assets/css/all2.css': '<%=meta.src %>assets/scss/build.scss'
        }
    },

    dist: {
        files: {
            '<%=meta.dist %>/assets/css/all.min.css': '<%=meta.src %>/assets/scss/build.scss'
        }
    }
},

When i run this i get the output of the build.scss in the console and it creates a empty file?
What am i missing????
Running "sass:dev" (sass) task
#flupdidup {
  font-weight: bold;
}
Running "sass:dist" (sass) task
#flupdidup {
  font-weight: bold;
}
Done, without errors.
Process terminated with code 0.

a minimal recreation of the issue can be found here: https://github.com/Peter-Optiway/grunt-sass-issue
Comment: Can you remove `<%=meta.src %>` and see if it works fine?
Comment: Possible to get a minimal git repo for debugging?
Comment: @TarunLalwani sadly that didn't change any thing `'./app/assets/css/all2.css': './app/assets/scss/build.scss'`
Comment: @TarunLalwani https://github.com/Peter-Optiway/grunt-sass-issue when i open this up in visual studio and run sass:dev or sass:dist i get the error in question.
Answer: Switching to grunt-sass was always an option, but your issue was not because of that. The issue was because you had sass install using npm.
npm install -g sass

When you look at that
$ sass --help
Compile Sass to CSS.

Usage: dart-sass <input>

-s, --style         Output style.
                    [expanded (default)]

-c, --[no-]color    Whether to emit terminal colors.
    --[no-]trace    Print full Dart stack traces for exceptions.
-h, --help          Print this usage information.
    --version       Print the version of Dart Sass.

It has no output parameter. While grunt-contrib-sass expects the sass to be install from the ruby gem.
$ sudo gem install sass

Now sass will have different options
$ sass --help
Usage: sass [options] [INPUT] [OUTPUT]

Description:
  Converts SCSS or Sass files to CSS.
...

And now the build works fine
$ cat ./dist/assets/css/all.min.css
main #flupdidup {
  font-weight: bold;
  background: #eeffcc; }

/*# sourceMappingURL=all.min.css.map */

Comment: In the end `grunt-sass` was a better option as it does not rely on ruby, but you get the 50 points for your effort!
Answer: I managed to fix the issue by changing to the grunt-sass package instead.
npm install --save-dev load-grunt-tasks load-grunt-tasks
Then i added the following to my Gruntfile.js require('load-grunt-tasks')(grunt); and it just worked.
Comment: Have a look at the answer I posted


Pedaling in Shostakovich Op. 87

Question: I've never played any Shostakovich before, and I was curious about whether/how I should go about pedaling in his preludes and fugues from Op. 87.
I'm treating the pieces like Bach, but there seems to be some impossible lines unless you pedal. I would appreciate some suggestions for how to pedal in these types of fugues, as the score doesn't have pedal markings, and I want to pedal cleanly (to be honest I avoid pedaling unless the score dictates it, so I don't have a great sense of its capability beyond what composers specify).
See the attached image for an example from no. 4 e minor fugue.
Specifics from the excerpt: The A and C# in the left hand are tied to the next measure when the LH should then play F#. Meanwhile, the RH plays the dotted-half A on beat 1 and then the dotted-half D on beat 2.
If my focus on pedaling is missing the intention of how Shostakovich wrote this, then feel free to clarify how I should approach these sorts of "awkward" phrases.
I understand these are questions better suited for a teacher, but I don't have one right now, so any guidance is greatly appreciated.
Thank you for your time and help.
Comment: Maybe the brackets are indicating not just which hand to use but also the pedaling.
Answer: There is no point in avoiding the pedal just because the form of a piece dates back to the harpsichord era.
Shostakovich wrote 250 years later, in the era of Rachmaninov, Horowitz etc. His fugues treat the instrument like the modern concert grand it had become, and that definitely includes using the pedal judiciously even if there are no explicit marks. (You'll notice that some effects, like the pedal points in the E major prelude, are virtually impossible to achieve without a modern grand piano.)
So yes, pedal and no pedal can achieve quite different effects on the same piece of music, and it is always advisable to use or not use it as a deliberate choice. And yes, many players use the pedal to mask insecurities in their phrasing or attack. But a blanket ban is inappropriate for 20th-century music.
Edit: How to play these types of bar depends on your instrument and your physiology.
My own span is enough to hold the right hand f#+a comfortably and barely to catch the left hand a+d without arpeggiating, so in a pinch I could play bar 18 without pedal by assigning the long d to the left hand. But bar 19 is beyond anyone who can't reach a 12th, so you'll have to use the pedal. A couple other places (b. 61, 112, 127) force your hand in a similar way. So you'll have to work out a good balance between catching all notes and separating the voices anyway, and you might as well use it for bar 18, too.
Other than that, I'd probably avoid the pedal in the pp section and for the second theme, because it tends to blur fast scales; but definitely use it for most ff passages. Many of the fugues in op. 87 descend into nothingness, but this one is about the gradual rise from 0 to 100, so the final chords really profit from the enhanced resonance that the pedal adds to the sound.

Pedaling in Shostakovich Op. 87


Sitemap and XML sitemap

Question: I originally had a sitemap using the sitemap module. I've now installed and enable dthe xml sitemap module instead. After following the instructions and configuring xml sitemap, when I go to mysite/sitemap.xml all I see is an unstyled page with an ugly table listing the Links.
How would I go about styling this sitemap? I was expecting it to work like the Sitemap module does and generate a page using a default template, but I guess I was wrong, or am I?
How should a sitemap.xml display after it's been set up?
Answer: Sitemap.xml is used to provide a way for search engines to index your site. It should not be used by your website users.
Comment: Thank you @Serpiente

Is it common to be using both the sitemap and xml sitemap modules at the same time?
Comment: I can only talk for myself - I am doing that yes.

Sitemap and XML sitemap


Android add a picture in the top right of a button programmatically

Question: I have a button and I want to pro grammatically add a picture of a green tick to the top right button after it has been selected, how would one do that?
Comment: Provided details are too less to help you
Comment: I am not sure how to make it less vague, how does one add a picture to the top right hand corner of a button
Comment: Add a ImageButton in your XML and programatically set the image src as per requirement
Comment: doesnt an imageButton cover the entire button with an image?
Comment: either the src that you set should be equal to size of your image view else set the image as image button background... it will entire image in give imagebutton space
Answer: First call the relative layout family and using LayoutPram update the position of the picture
<code>ImageView imageView = (ImageView)findViewById(R.id.theImage);

Button myBtn = (Button)findViewById(R.id.myButton);
myBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
               RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)imageView.getLayoutParams();
               params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
               params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
               imageView.setLayoutParams(params);
          }
      });
</code>
Try this!
Answer: Use ImageButton and onClick swap out the image
Its a vague answer but your question is also vague
Comment: dont want the whole button to be a picture, just i want a small picture in the top right hand corner


What exactly is *the* blues and how do you learn it (as opposed to: learn *a* blues)?

Question: I realize this may sound like a stupid question, but I sense there is more to it than "play random blues scales over a 12-bar blues progression" to the blues tradition.
What techniques, resources and literature is there?
What makes up the tradition, besides the recordings of the greats?
Most importantly, how do you set to learn the blues, being already proficient enough to play a blues piece from a transcription?
Do you transcribe and learn licks from the greats?
You explore variations on progressions or the 12-bar form is set (as opposed to, say, jazz)?
Comment: @ToddWilcox: you tell me. Is composing expected of a blues player or just improvising over certain forms or standards?
Comment: @ToddWilcox: if no form is set, what makes a blues piece... blues? :) Or, if you prefer, what's some common "bluesy" forms and progressions? That's kind of the point of the question. I'm from Europe and I had a classical-ish education - but I keep hearing about this blues thing, but what *defines* it exactly?
Comment: If you study "the greats" and the not-so-greats you'll quickly see that no form is set, not even 12-bar blues. I'm not sure what the difference is between "the blues" and "a blues" in your question, maybe because I've never heard or read the latter phrase before. Are you looking to compose your own music in the blues style?
Comment: "A blues piece", that is.
Comment: I'm more inclined to recommend artists, myself. Robert Johnson, for sure. Son House, Muddy Waters, Bo Diddly, Sonny Boy Williams, Stevie Ray Vaughan, ZZ Top, Willie, Dixon, John Lee Hooker, Allman Brothers, Eric Claptop, Jimi Hendrix, Led Zeppelin, B. B. King, John Mayall. Just keep listening (and maybe playing along) until you know what you want to know. http://en.wikipedia.org/wiki/List_of_blues_musicians
Answer: Blues is a language, with grammar and vocabulary. The difference between learning to play the blues and learning to play a blues is the same as the difference between learning to speak a language and learning just some words or phrases in that language.
In the vocabulary instead of words you are using scales and chords. In the grammar instead of order of words you are using harmonies.
The vocabulary in blues includes the scales: minor and major blues, minor and major pentatonic, mixolydian, and dorian. Those are used prominently, but there are many more. Some like to use the lydian b7 mode, for example. The vocabulary also includes the dominant 7 chords, which are very common.
The grammar (harmony) includes the various I7 IV7 V7 progressions (in different orders), like the classic 12 bar blues. The harmony in general tends to be heavily based in dominant 7 chords.
That's a very simplistic overview, and there's much more to it (minor blues, other modes, swing, the list goes on), but hopefully it is enough to give you an idea of what blues is as a language. If you want to learn the language you have to dive into it: teachers, lessons, books, tutorials, listening, transcription, practice, Music SE!, etc.
Comment: The principal characteristics of the blues are: 12-measure phrases in AAB structure; 4/4 rhythm with a back-beat (emphasis on beats 2and 4) heavy dependence on the I-IV-V chord progression, and pentatonic melody.
Comment: This is an answer I kind of like, because it suggests more detailed questions than I can come up with: "what are the various progressions", "what are the scales", "when to use which scale"?  But if I'm not asking too much - where do I start looking for the answers to these questions? :)
Comment: @SomeDudeOnTheInterwebs Lessons. The exact place where you want to start will depend on your experience. The best thing you can do is getting a good teacher. Another option is getting literature about the subject. There's a lot of blues theory books, but you'll need to be able to read sheet music. You can also look for video lessons in youtube and similar sites, for many of those you don't need to know how to read music. If you don't know the basics of music theory, you might want to start there instead of going directly into blues.
Comment: Can read music, know theory. Absolutely no blues teachers where I live (really, I swear).
Comment: @SomeDudeOnTheInterwebs What instrument do you play? Some popular piano blues books are  "Blues Piano: Hal Leonard Keyboard Style Series" by Mark Harrison, and  "Improvising Blues Piano" by Tim Richards. Either would be a great starting point. If you are looking for learning material in general It's a good idea to go into a site like Amazon, type "blues ", and see which books are available and you might like,  the customer reviews will be very helpful there.
Comment: Some of my favorite blues is all just one chord. E.g., Bo Diddly, "Who Do You Love?" I'm not sure if blues is really about chord progressions.
Comment: @ToddWilcox I included one common harmonization dynamic as example, but I never claimed or implied that "blues is about chord progressions" (unless I'm missing something?). If anything I said that there's much more to it, and that I'm overly simplifying. I don't know if your comment makes much sense in that context anyway, since you can harmonize any given musical idea (including Who Do You Love?) in many different ways.
Comment: There has to be somebody somewhere nearby, they might be hard to find but I bet they are there. (http://en.wikipedia.org/wiki/Liri_Blues_Festival )
Comment: JCPedroza Sorry, my comment was really in response to @Some Dude On The Interwebs and his comment about more detailed questions like "what are the various progressions". I'm not a huge fan of your answer but not on its face, just in terms of how it encourages the thinking that somehow what makes blues blues is the chords and scales and in your words, the "grammar and vocabulary".
Comment: @ToddWilcox Blues as a language with grammar and vocabulary is not my construct. "Musical vocabulary" is a very common idiom in both jazz and blues (I'm surprised you haven't heard it before). Let me ask you this: if a musical style is not about its scales, chords, harmonies, rhythms, melodies (the grammar and vocabulary) then about what it is? If blues is not about its language, its grammar, its vocabulary, then about what it is? Note that we are in a music theory site, and that's the context we are dealing with.


How do I create a field with a vector type in MySQL?

Question: I created a table in MySQL. I want to store a name, a surname and a vector of doubles, but   the problem is: how do I create a vector column in MySQL? My vector contains 130 elements.
Comment: Two main options: 1) Create a binary BLOB or 2) print your vector to text (each number separated by ";",for example) and save the column as a text string.  Look at this post: [BLOB vs VARCHAR for storing arrays in a mySQL table](http://stackoverflow.com/questions/3106548/blob-vs-varchar-for-storing-arrays-in-a-mysql-table).
Comment: A vector sounds basically like a table.  In relational database modeling, you are probably looking for a 1-to-many relationship.
Answer: There are essentially two ways you can do that.
A simple one is to create a LONGBLOB or LONGTEXT field where you will store a serialized version of your vector.
But this is a quite ugly solution from a database modeling perspective because the DBMS is not capable of performing searches or to index the content of those vectors.
The correct way would be to use two tables in a 1-to-many relationship.
It means, you would have a table table_A with the following structure:
CREATE TABLE table_A ( -- records
    id        INT UNSIGNED NOT NULL AUTO_INCREMENT,
    name      TEXT,
    surname   TEXT,
    PRIMARY KEY (id)
);

And a table table_B containing the values in the vector and an association with their respective records in table_A:
CREATE TABLE table_B ( -- vector values
    parent    INT UNSIGNED NOT NULL,
    id        INT UNSIGNED NOT NULL, -- for indexing, in case the order of the vector elements matter
    value     TEXT,
    PRIMARY KEY (parent, id),
    FOREIGN KEY (parent) REFERENCES table_A (id) ON DELETE CASCADE ON UPDATE CASCADE
);

Working exemple: http://sqlfiddle.com/#!2/79521/2
With this format you are capable of allowing the DBMS to perform searches and manage the values of the vectors.
Answer: I suggest you to take a look at the JSON data type. This way you can store your vector in a more efficient way than text or varchar, and you can access your data directly form MySQL without having to parse the whole thing.
Take a look at this link : https://dev.mysql.com/doc/refman/5.7/en/json.html
You'll just have to store your vector in a JSON form like this [24, 12, 54, 39, ...]


8 under clef and timing questions

Question: Please look at the below graphic, there are a few things that are confusing me:
1 - Why is there an 8 under the treble clef?
2 - This is in common 4/4 time, yet one of the beginning 8th notes (in each of the "bunch" of 4 notes) is actually a half note... which would throw the whole timing off for that bar... right?
Even when using Guitar Pro to put that in, if I put it in as a bunch of 8th notes it works, but if I try to put the first note as as a half and the rest 8ths it gives me an error :(
I mean the beams above say it's a group of 8 notes, but the "circle" in the note is not filled in which makes it a half note... right?
Answer: It's an octave clef. It's telling you all the notes written are actually down an octave. Since the guitar is already a transposing instrument where everything is transposed down an octave, it's essentially showing you the actual notes being played instead of the implied octave transposition. So for simplicity's sake you can just ignore it and play as you would with with a normal treble clef.
The lowest pitch a guitar can play in standard is E2 which is below the staff on the bass clef. Typically in guitar sheet music they notate this note on E3 so they can use the treble clef and it's just implied that the note is down an octave. With the octave clef, the note is actually an E2 even though it is written where E3 typically is because everything is down an octave.
You second question has is actually addressed in this question. Pretty much there are two ideas happening at once, the eigth note patterns and the whole note pattern that can be perceived as two different parts. Pretty much you would just play the half notes for the duration of the half note and play the eight notes while the whole note is sustained.
If they were two different parts, one would looks like this:

And another would look like this.

Since you are doing both, they become what you see in your score.
Comment: @Ryan this looks like a good guide: https://www.youtube.com/watch?v=M-hW6vs-wzI . If not, just search for "notating multiple voices guitar pro".
Comment: Thanks for answering!
> it's essentially showing you the actual notes being played instead of the implied octave transposition.
Can you elaborate a bit on that please?
Comment: Also, the second part you explained perfectly, I now get that :) But any idea how I write that in Guitar Pro?
Comment: In Guitar Pro, you can write this as two voices: One for the half notes and one for the quarter notes.
Comment: Usually guitar sheet music doesn't use the 8 below the clef, because everybody knows it's supposed to be there for guitar. This clef symbol is most often used for the tenor vocal part in a piece of choral music, to distinguish it from the soprano and alto parts.
Answer: To answer the second question, you can use the "voices" feature of GP6 :

You can have 4 voices. Each voice has it's own "bar duration count" which is independent from the other.
To change the current voice, use the "1", "2", "3" and "4" buttons. When you'll add a note, it will be added to the currently selected voice.
The notes from the other voices are greyed.
The last button displays all the notes of all the voices, without greyed notes.
Here's how your example would look, depending on the voice selected and when the multi-voice option is on :
Answer: Adding to Dom's excellent answer, the tails on the dots are the clue. There's one set of notes with up tails, and one with down tails. Showing two parts to the line. Trouble is, it's a compromise, as it looks like the first note in the bar could be a minim with a tail AND a beam. Of course, this sort of note doesn't get used. It's written like that (and has been for centuries) for convenience, and I guess we've just got used to it!
I suppose, technically, the first quaver OUGHT to be written as a quaver rest, as the piece would sound exactly the same, but, why bother?

8 under clef and timing questions


Slice indices must integer

Question: I am working on ODE circuit suddenly face this problem . How to solve it ?
Comment: Use `N//2+1` in place of `N/2+1` both in line 13 and 14
Comment: what should i write instead of it ?
Comment: That was also worked, thank you so much, to share your solution with me.@FBruzzesi
Answer: Most probably, if your N/2 is not an integer, you get such an error.
I would change to w[0:int(N/2)+1] = 2....
This is also available for every place you divide N/2.

Slice indices must integer


Data center router/firewall recommendations

Question: I'm looking for help deciding on a new router for our data center equipment. Currently, we've got about 10 machines, each with their own firewall. I'd like to get them all behind a single router and also create a vpn tunnel to our main office.
Requirements:

Gigabit Ethernet
Firewall
Cisco compatible point-to-point VPN

Traffic primarily consists of external HTTP requests, averaging ~10Mb/s, surging up to ~150Mb/s.
The router at the main office is a Cisco 2821.
Answer: Cisco 2911 ISR G2 should be sufficient, speced forwarding capacity of about 180Mbit. You get three GE copper interfaces in the standard configuration. If you need a fibre uplink the 2921 has an SFP slot in the standard configuration
To get the IOS firewall and full crypto features you need 2911-SEC-K9 bundle.
Having a second router for redundancy might be a good idea too.


How to add a tab to shop pages?

Question: I'm on Drupal 8 with Commerce 2.
I created a view page to display the list of products in the stores.
Here is the way of my sight :
/store/3/produits
Can not add a tab to shop pages.
I am desperate.
Can you explain why the "Edit" tab on the page is missing ?

Here is my view, it is very simple :

Here is my page "Produits", there is no tab :
Comment: Because you need a default stub tab first in order to add more tabs on to it.
Comment: So, create a default menu tab at boutiques/%/list, which is the same exact output as boutiques/%. Then, your Products tab should show.
Comment: @Kevin I do not understand how to do that. Can you give me an answer with an example ? Thank you
Comment: @Kevin Some screenshots
Comment: Those mentions do not work if I never had any interaction with the post ;) But as Kevin stated, you need to have a stub tabs first.
Comment: @ZenImagine It would be helpful if you upload views.view.YOUR_PRODUCTS.yml file here.
Comment: @drugan You must use this question https://drupal.stackexchange.com/questions/242251/the-menu-tabs-show-an-error I can not delete this page because it is related to my second question.
Answer: UPDATE: install Commerce Multistore module and have store/ID/edit, store/ID/products, user/ID/stores views tabs created by default for you
UPDATE: Add store/ID/edit, store/ID/products, user/ID/stores views tabs
Tabs can be automatically created for you by Views.
WDTutorials video: Tabs With Views in Drupal 8
You have to create a views' page having /some-path  which lists some entities (nodes, fields or products as in your question). Then you need to make it a Default menu tab (parent menu tab). So, if no any child tabs are present then the content for this tab will be displayed. It might be seen a bit confusing but you should choose Already exists option while creating this (newly created) menu tab. After that just create as many duplications of this page as you need and choose for each duplication a Menu tab option (child menu tab). Again, you might be confused which menu or menu entry to choose for children menu tabs. Actually, it does not matter a lot. For your view you may choose Products entry though <Main navigation> menu might be also a good choice. Do not ignore weight option assigning a proper value for each child tab. It helps to place tabs in the exact order you want. Leave 0 weight for the parent tab increasing it by 1 for each next tab.
Then, edit the path so it looks like /some-path/child-1 and add a filter criteria for a child tab (page). In the video the filter criteria is a node's published/unpublished status and in your case it should be a store ID. The ID of a particular store might be found on the /admin/commerce/stores by hovering over a store's Edit tab.
See more on the relative drupal.org issue:
https://www.drupal.org/node/2880510#comment-12185171
Comment: Fairly speaking I am still the same as you learning Drupal 8 views. Now I've found some trick how to display  store/%/products. I am going to make a video if I don't find already existing somewhere else.  As for the no "Edit" option you should look for permissions on the view (view tab).
Comment: Thank you, the tabs seem to work on I go into the ID path of the shop. On the other hand, it does not work with a contextual filter and a path with %
Comment: Here is the path to a shop "/store/3" to apply to all the shop, I created in my view a contextual filter with the ID and I put the "path / store/%/products". But nothing works as expected.
Comment: What really annoys me is that I manage to create tabs on the assembly of my site without any problem (even on the user and group pages), but on the pages of the shop it is a big big problem . Another thing, when you view a shop page there is no tab "Edit" is very weird.
Comment: On simplytest, try to create a shop with two or three products. Now on the page of your shop, create a list of the products of the current shop (a view with a contextual filter). The path should be / store / ID / products and the tabs "View; Edit; Products". Please tell me if you have succeeded, thank you.
Comment: I look forward to seeing how you did it. Regarding the "Edit" tab, the shop page is not a view and the tab should have been created by default by the "Commerce" module. There is an "Edit" tab on the nodes and products, I did not create it. It is displayed by default.
Comment: Can you tell me the solution you found in your previous comment? For the "Edit" tab I do not understand what to do, because the "Edit" tab is not a view. Thank you
Comment: @ZenImagine  As I said earlier I want to give an answer (may be a video screencast or even a patch for drupalcommerce) which might be useful for many users. The issue of displaying products enabled for a particular store is quite generic one if you have a site with many sellers (marketplace). So, please wait a bit. I'll post the answer as soon as I find the most appropriate solution. The one which I have right now is just a workaround, not a real solution.

How to add a tab to shop pages?


How do joint test, r-squared behave when using autocorrelation / heteroskedasticity robust std. errors?

Question: Recently we discussed on SO how to update a standard linear regression summary with NeweyWest standard errors. I used coeftestfrom the sandwich package. It was told to use unclass to update my already existing summary like this:
library(sandwich)
library(lmtest)
temp.lm <- lm(runif(100) ~ rnorm(100))
temp.summ <- summary(temp.lm)
temp.summ$coefficients <- unclass(coeftest(temp.lm, vcov. = NeweyWest)

Now I wonder whether the joint parameters shown in the summary aren't affected at all when using a NeweyWest VC matrix? I mean with this code they are not affected obviously – but is this correct? Note this is not a syntax but a stats question :) Stuff like
Residual standard error: 1.177 on 83 degrees of freedom
Multiple R-squared: 0.7265, Adjusted R-squared:  0.71
F-statistic:  44.1 on 5 and 83 DF,  p-value: < 2.2e-16

remains the same. Are there any cases that need adjustment as well?
Answer: The $R^2$ is the sum of squared residuals divided by the total variation in your outcome; neither of these statistics change when robust/HAC standard errors are applied, so the $R^2$ doesn't change either. Adjusted $R^2$ alters the formula somewhat, but only based upon the number of observations and the number of predictors in your model, which don't change under robust standard errors, so this value remains unchanged as well.
The F statistic can't incorporate heteroskedasticity or autocorrelation---it requires homoskedasticity and no correlations among the errors (actually, it requires that the errors be distributed according to identical normal distributions conditional on your predictors). This statistic can't be corrected. Instead, to perform robust joint tests, you need to use a Wald test that follows the $\chi^2$ distribution under the null hypothesis. So, yes, the F statistic doesn't change when you apply the robust/HAC standard errors, but that's because it isn't robust.
Comment: Thanks for the elaborate explanation. Still though this leaves me with a problem. Temp.summ in the example above still displays the f-statistic, even if only a Wald test would be meaningful. Is there a way to change that (also change the label)? Have you seen  linear.hypothesis (deprecated) in Farnsworth Econometrics in R? http://cran.r-project.org/doc/contrib/Farnsworth-EconometricsInR.pdf
Comment: @ran2, Yes the linear.hypothesis() function looks like it would work. So long as your getting a new package, this one might be simpler: http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/aod/html/wald.test.html

I assume that the R^2, F, etc output is from the LM function, right? Since you haven't specified the HAC standard errors at that point, you can't change that display.
Comment: yes it's from the LM function. True, I can't change the display initially, but what I do is update the coefficients after specifiying a NeweyWest VC matrix. Now that you helped me, the only thing I do to is another update for the joint tests. I´d like to update the joint test by using the Wald test summary. I am using summary to get nice Sweave base reports and would like to use that also for robust regression.


NFL Overtime Rules - why are they like this?

Question: Why do the NFL's overtime rules allow for a team to potentially lose without their offense ever taking the field? What caused the league to decide on this format for OT and why did they decide to have different rules during the season and in the playoffs.
It seems very different from OT rules in all other American sports leagues...
More details on the rules here
Answer:
Why do the NFL's overtime rules allow for a team to potentially lose
  without their offense ever taking the field?

NFL's overtime is a variant of sudden death in that if the first team scores a touchdown, that team wins.

What caused the league to decide on this format for OT?

The 2009 NFC Championship Game. In short, the Saints won with a field goal without the Vikings taking the field. This was the sudden death format before they altered it in response to this game.
On the first possession, if the team in possession of the ball scores a field goal, the other team has an opportunity to score. In other words, NFL overtime is sudden death unless the first possession results in a field goal.

Why did they decide to have different rules during the season and in the playoffs.

There are different rules during the season vs. the playoffs because in the playoffs, a winner needs to be determined. In the regular season, a tie can be achieved.
Comment: Did the NFL explain why they still allow for a team to lose in OT without touching the ball (in the case of their opponent scoring a TD)?
Comment: @pacoverflow Didn't find anything from the NFL regarding this. Fun fact: Since the rules have changed (ie, OT games since 2012 to the conclusion of the 2018 season), the team who wins the coin toss has won 50% of overtime games. [Source](https://www.reddit.com/r/nfl/comments/aic4gt/since_the_overtime_rule_change_in_2012_the_team/)
Answer: I'm adding to the accepted answer to respond to comments in the question.

It seems very different from OT rules in all other American sports leagues

Every American sports league is designed to accommodate television viewership, so when OT rules are different from regulation rules, the trade-off is to end the game quickly without seeming overly unfair or unusual.

In NHL, OT is sudden death. Since possession is fluid and earned when the puck drops, this isn't inherently unfair. However, to shorten OT, teams play 3-on-3. This opens up space on the ice to increase scoring, but some think it's too unlike 5-on-5, which  disadvantages some teams more than others.
In NBA, scoring is frequent and possession is earned on tip-off, so it's easy to add 5 minutes of regular play and determine a winner. This is the league with the least drama concerning OT rules.
In MLB, scoring is infrequent, but possession is deterministic: each team will get 3 outs every inning. The current method of extra innings is fair, but it leads to some very long baseball games, which is why the league has considered starting extra innings with a runner on second to increase scoring and determine winners faster. The trade-off is to sacrifice some of the "purity" of the sport to make OT more watchable for fans and less tiring for players.
In NFL, the old sudden death rules -- first score wins, period -- ended games quickly, which is good for a sport that often televises games back-to-back-to-back on Sundays. But it was blatantly unfair, with possession determined by a coin flip. The new rules are fairer, but not ideal. Still, the league determined that fans and players are happier with this than if an entire quarter of normal football were played. Other leagues implement shoot-out-style OT, where offenses take turns scoring from a set yard line -- this faces similar criticism to NHL's 3-on-3, where the game is sufficiently changed such that certain teams benefit more in OT than they do playing by the "real rules".

why did they decide to have different rules during the season and in the playoffs

As exchange_knowledge noted, the primary difference is that a playoff requires a winner and loser.
Another important difference is that in the playoffs, since the stakes are higher, the television audience is willing to watch a longer OT. So instead of prioritizing timeliness, leagues with unusual OT rules prioritize fairness.
For example, if the MLB ever implements a runner-on-second in OT, they will not do so in the playoffs. And in the NHL playoffs, teams play 5-on-5 sudden death periods instead of 3-on-3, and the shootout is also removed.


Suppress stdout from check_output but write it to a log instead

Question: I have the following code:
try:
    subprocess.check_output(command.split())
except subprocess.CalledProcessError as e:
    count_failure.increment()
    logger.error(e.__dict__)
    return

When check_output() fails, then I would like to suppress that message from stdout, but write it to my logger instead.
Right now the stdout error message messes up my tqdm progress bar:
[hobbes3@hobbes3 bin]$ ./mass_index.py
34%|█████████████████████████████████████████▋                                                                                | 13/38 [00:00<00:14,  1.75it/s]
unable to open file: path='/mnt/data/samples/irs_990/foo.xml' error='Permission denied'
100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 38/38 [00:02<00:00,  5.96it/s]

Also, the actual message Permission denied isn't stored inside e. My e.__dict__ only says
{'returncode': 22, 'cmd': ['/opt/splunk/bin/splunk', 'add', 'oneshot', '/mnt/data/samples/irs_990/foo.xml', '-index', 'main', '-sourcetype', 'irs_990'], 'output': b'', 'stderr': None}

Comment: redirect `stderr` ? `subprocess.check_output(command.split(),stderr=subprocess.STDOUT)`
Answer: that is because the command you're running is issuing error messages to standard error stream.
check_output only captures standard output, unless you use an extra parameter. So either:
subprocess.check_output(command.split(),stderr=subprocess.STDOUT)

so errors are also in the output, or (python 3):
subprocess.check_output(command.split(),stderr=subprocess.DEVNULL)

to suppress this error message completely.
To get a proper exception message with standard error in it, you would have to redirect error stream to a specific pipe so you wouldn't have stderr=None
subprocess.check_output(command.split(),stderr=subprocess.PIPE)

But that could cause deadlocks between output and error streams (depending on how the program outputs to output or error, if the pipes aren't read in a smart way (ex: with threading), one write could block because of buffer full while you're reading the other one which is empty).
Maybe in your case you'd be better off with subprocess.Popen and communicate which handles that case nicely (with threads or whatever works underneath)
p = subprocess.Popen(command.split(),stderr=subprocess.PIPE,stdout=subprocess.PIPE)
output,error = p.communicate()

(and keep the same exception handling)
Comment: if you're fine with error coming stdout, then it's okay. Else I have provided more alternatives
Comment: How do I capture the exact message `unable to open file: path='/mnt/data/samples/irs_990/foo.xml' error='Permission denied'` to `logger` then?
Comment: Never mind, `e` is getting the entire error now: `2018-12-06 21:51:40 [ERROR  ] (Thread-11 ) {'returncode': 22, 'cmd': ['/opt/splunk/bin/splunk', 'add', 'oneshot', '/mnt/data/samples/irs_990/foo.xml', '-index', 'main', '-sourcetype', 'irs_990'], 'output': b"unable to open file: path='/mnt/data/samples/irs_990/foo.xml' error='Permission denied'\n", 'stderr': None}`. Thanks!
Comment: @Jean-FrançoisFabre Why redirecting error stream to the pipe would cause deadlock?
Comment: depending on how the program outputs to output or error, if the pipes aren't read in a smart way (ex: with threading), one write could block because of buffer full while you're reading the other one which is empty. It _could_ cause deadlock, not 100% all the time


How to only push to one branch in Hg?

Question: I have a Hg repo with 3 branches in it, but two of them are inactive (since I have already merged them into my default branch). hg heads shows 3 heads, one for each branch, even though hg branches shows 2 of those branches as 'inactive'.
When I try to push my default branch (using hg push --branch default http://...) to another repo, the merge is aborted with the message "abort: push creates new remote branches: !"
From the Hg push man pages, "By default, push will not allow creation of new heads at the destination, since multiple heads would make it unclear which head to use. In this situation, it is recommended to pull and merge before pushing."
I've already done that, but I still cant push --branch default without it getting aborted.
Any help is appreciated. Thanks!
Answer: If changesets on default have ancestor changesets on other branchs you have to push those changesets too.  It's not possible for a changeset to exist in a repo without all of its changesets also existing.
So try:
hg push --branch default --new-branch

which says "yeah, I know this push sends across a branch name that the remote repo hasn't previously seen before" (it also requires Mercurial 1.6 or later IIRC)>
Also, you can take those inactive heads and make them closed heads with:
hg update thebranch
hg commit --close-branch -m 'closing'

Because "named branches are forever" many folks choose to reserve them for long lived concepts like "stable" and "experimental" and use bookmarks, anonymous branches, or clones for features, releases, and other transitory things.  See this for a guide on those other options.
Comment: Your answer is correct, but it doesn't mean I have to like it ;)
Comment: Surely it does.  I use git more than I use Merucrial, and I also have a .gitconfig that requires hand editing because git can't update it.  Mercurial is unwilling to corrupt your config and git is if you ask it to.  They're both valid choices so long as they're documented.  I dunno whose article you linked to there, but that guy could use an editor.
Comment: Here's where the git docs explain that `git config` will cease to work as advertised if you use includes: https://github.com/gitster/git/commit/9b25a0b52e09400719366f0a33d0d0da98bbf7b0
Comment: Fair enough.  I avoid named branches entirely.  I'm a clones as branches guy.
Comment: @bambams I wish comments could be downvoted so I could downvote yours.
Answer: To push a single branch you just use -b
hg push -b myBranch

as for the specific issue, you may want to look into closing branches. I know SourceTree offers it, but I'm not sure on the specifics
Comment: That's because the branch you are pushing hasn't been pushed to the server yet. If you're pushing an existing branch, this answer works.
Comment: Thanks, this was the answer I was looking for. Simply how to push a single branch.
Answer: You can FORCE it!
Here is how:
1. Pull from your repository
2. hg push --rev nnn -f (replace nnn with your Rev # of your working branch)
3. do NOT force before PULLing. if you do things will get out sync and you are screwed

If you are using something like RhodeCode then check it out after forcing it and you will see that your latest branch is there.
However I think that later on Mercurial is going to ask you to push the other branch again, even if you close it, Mercurial will try to create that branch on a server.
I'm a Git user also and ran into the same situation because a customer is using Mercurial but I would like to use Git workflow style.
I think it is doable but I have not figured out 100% yet.

How to only push to one branch in Hg?


Nutch No agents listed in 'http.agent.name'

Question: <code>Exception in thread "main" java.lang.IllegalArgumentException: Fetcher: No agents listed in 'http.agent.name' property.
        at org.apache.nutch.fetcher.Fetcher.checkConfiguration(Fetcher.java:1166)
        at org.apache.nutch.fetcher.Fetcher.fetch(Fetcher.java:1068)
        at org.apache.nutch.crawl.Crawl.run(Crawl.java:135)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:65)
        at org.apache.nutch.crawl.Crawl.main(Crawl.java:54)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:616)
        at org.apache.hadoop.util.RunJar.main(RunJar.java:156)
</code>
Every time i run ./nutch crawl urls -dir crawl -depth 3 -topN 5 . nutch decides to throw this error. I have both my nutch-site.xml & nutch-default.xml set with.
<code> <property>
  <name>http.agent.name</name>
  <value>blah</value>
  </property>
</code>
Took the description out to make its easier to read. But I fail to see where else the agent name can be specified. if anybody has any advice I would be grateful.
Answer: using 1.3? If so make sure you changed nutch-site.xml (and not default) in runtime/local/conf
Changing the conf in NUTCH_HOME/conf won't be copied to the runtime dirs unless you rebuild with ant.
Comment: The mailing list seems not working.I try to subscribe the nutch mailing list a few times,but failed
Answer: Try giving the agent name for http.robots.agents also. It worked for me. I didn't get that message thereafter!!!


Is there a module that provides payment processing but not a shopping cart?

Question: I am building a website that allows users to "upgrade" their content. The user can choose a "premium" listing and once paid for their node will appear higher in a list of nodes.
I'm looking for a module that can do this, or a module that can at least provide the payment page so that I could customise the node editing process and direct them to this page, take their payment then update the node.
I know something like Ubercart can provide the payment processing but it has a very set payment checkout process that is more oriented to a shopping cart checkout process and would take a lot of time to customise for what I want.
Any recommendations on how to do this?
Im running Drupal 7.
Answer: Have you tried some of those ?

lm_paypal:

This module provides an interface to PayPal using Instant Payment
  Notifications (IPN). It currently supports paid memberships
  (subscriptions), donations (tip jar) and paid adverts (classified
  ads).

Payment API: this one need a specific module for the payment platform

This module can be used by other modules to collect and track payments. Through this API, any module can provide a payment form and payments can be handled and tracked centrally.

How to build a paid membership site with Drupal 7 (paid module)
Comment: Payment API I think is exactly what im looking for. cheers