text:
Q: How to set socket timeout in C when making multiple connections? I'm writing a simple program that makes multiple connections to different servers for status check. All these connections are constructed on-demand; up to 10 connections can be created simultaneously. I don't like the idea of one-thread-per-socket, so I made all these client sockets Non-Blocking, and throw them into a select() pool.
It worked great, until my client complained that the waiting time is too long before they can get the error report when target servers stopped responding.
I've checked several topics in the forum. Some had suggested that one can use alarm() signal or set a timeout in the select() function call. But I'm dealing with multiple connections, instead of one. When a process wide timeout signal happens, I've no way to distinguish the timeout connection among all the other connections.
Is there anyway to change the system-default timeout duration ?

A: connect timeout has to be handled with a non-blocking socket (GNU LibC documentation on connect). You get connect to return immediately and then use select to wait with a timeout for the connection to complete.
This is also explained here : Operation now in progress error on connect( function) error.
int wait_on_sock(int sock, long timeout, int r, int w)
{
    struct timeval tv = {0,0};
    fd_set fdset;
    fd_set *rfds, *wfds;
    int n, so_error;
    unsigned so_len;

    FD_ZERO (&fdset);
    FD_SET  (sock, &fdset);
    tv.tv_sec = timeout;
    tv.tv_usec = 0;

    TRACES ("wait in progress tv={%ld,%ld} ...\n",
            tv.tv_sec, tv.tv_usec);

    if (r) rfds = &fdset; else rfds = NULL;
    if (w) wfds = &fdset; else wfds = NULL;

    TEMP_FAILURE_RETRY (n = select (sock+1, rfds, wfds, NULL, &tv));
    switch (n) {
    case 0:
        ERROR ("wait timed out\n");
        return -errno;
    case -1:
        ERROR_SYS ("error during wait\n");
        return -errno;
    default:
        // select tell us that sock is ready, test it
        so_len = sizeof(so_error);
        so_error = 0;
        getsockopt (sock, SOL_SOCKET, SO_ERROR, &so_error, &so_len);
        if (so_error == 0)
            return 0;
        errno = so_error;
        ERROR_SYS ("wait failed\n");
        return -errno;
    }
}

A: am not sure if I fully understand the issue, but guess it's related to the one I had, am using Qt with TCP socket communication, all non-blocking, both Windows and Linux..
wanted to get a quick notification when an already connected client failed or completely disappeared, and not waiting the default 900+ seconds until the disconnect signal got raised. The trick to get this working was to set the TCP_USER_TIMEOUT socket option of the SOL_TCP layer to the required value, given in milliseconds.
this is a comparably new option, pls see https://www.rfc-editor.org/rfc/rfc5482, but apparently it's working fine, tried it with WinXP, Win7/x64 and Kubuntu 12.04/x64, my choice of 10 s turned out to be a bit longer, but much better than anything else I've tried before ;-)
the only issue I came across was to find the proper includes, as apparently this isn't added to the standard socket includes (yet..), so finally I defined them myself as follows:
#ifdef WIN32
    #include <winsock2.h>
#else
    #include <sys/socket.h>
#endif

#ifndef SOL_TCP
    #define SOL_TCP 6  // socket options TCP level
#endif
#ifndef TCP_USER_TIMEOUT
    #define TCP_USER_TIMEOUT 18  // how long for loss retry before timeout [ms]
#endif

setting this socket option only works when the client is already connected, the lines of code look like:
int timeout = 10000;  // user timeout in milliseconds [ms]
setsockopt (fd, SOL_TCP, TCP_USER_TIMEOUT, (char*) &timeout, sizeof (timeout));

and the failure of an initial connect is caught by a timer started when calling connect(), as there will be no signal of Qt for this, the connect signal will no be raised, as there will be no connection, and the disconnect signal will also not be raised, as there hasn't been a connection yet..

A: You can use the SO_RCVTIMEO and SO_SNDTIMEO socket options to set timeouts for any socket operations, like so:
    struct timeval timeout;
    timeout.tv_sec = 10;
    timeout.tv_usec = 0;

    if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout,
                sizeof timeout) < 0)
        error("setsockopt failed\n");

    if (setsockopt (sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout,
                sizeof timeout) < 0)
        error("setsockopt failed\n");

Edit: from the setsockopt man page:
SO_SNDTIMEO is an option to set a timeout value for output operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for output operations to complete.  If a send operation has blocked for this much time, it returns with a partial count or with the error EWOULDBLOCK if no data were sent.  In the current implementation, this timer is restarted each time additional data are delivered to the protocol, implying that the limit applies to output portions ranging in size from the low-water mark to the high-water mark for output.
SO_RCVTIMEO is an option to set a timeout value for input operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for input operations to complete. In the current implementation, this timer is restarted each time additional data are received by the protocol, and thus the limit is in effect an inactivity timer. If a receive operation has been blocked for this much time without receiving additional data, it returns with a short count or with the error EWOULDBLOCK if no data were received. The struct timeval parameter must represent a positive time interval; otherwise, setsockopt() returns with the error EDOM.

A: Can't you implement your own timeout system?
Keep a sorted list, or better yet a priority heap as Heath suggests, of timeout events. In your select or poll calls use the timeout value from the top of the timeout list. When that timeout arrives, do that action attached to that timeout.
That action could be closing a socket that hasn't connected yet.


text:
Q: How to get active filters attribute code in state.phtml I have been working on Magento C.E 1.9.0.2, and I am implementing custom AJAX product loader, I have achieved everything but I am not able to filter out my product collection as per the selected filters. All I need to have the attribute code of selected filters, which I think can be achieved from state.phtml, where we have the active filters. But, I am not able to get the correct method to to get the active filter's attribute code and current selected values. Need help....

A: $appliedFilters = Mage::getSingleton('catalog/layer')->getState()->getFilters();

and you get fetch like that
foreach ($appliedFilters as $item) {
    $item->getName(); // Name of the filter
    $item->getLabel(); // Currently selected value
    $item->getFilter()->getRequestVar(); // Filter code (usually attribute code, except category filter, where it equals "cat")
}

reference

A: Building on the answer above, you need a little more code to use this within the loop of state.phtml:
<?php
$_filters = $this->getActiveFilters();
$appliedFilters = Mage::getSingleton('catalog/layer')->getState()->getFilters();
$attributeCodes = array();

// Loop to get all attribute codes indexed by attribute name
foreach ($appliedFilters as $item) {
    $attributeCodes[$item->getName()] = $item->getFilter()->getRequestVar();
}

// The rendering loop
foreach ($_filters as $_filter) {
    $attributeCode = $attributeCodes[$_filter->getName()];

    if ($attributeCode === 'some_thing') {
        // Something
    }
}
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript join using ampersand as delimiter I've got an array that needs to become a string separated by ampersands.
Input:
arr = ['incomplete', 'complete', 'processing']

Desired Output:
"query[]=incomplete&query[]=complete&query[]=processing"

My attempt:
"query[]="+arr.join("&query[]=")

Result:
"query[]=incomplete&query[]=complete&query[]=processing"

I've also tried different ways of trying to escape the ampersand, but I always end up with "& amp;" in my output.  For this string to work on the backend, I need a simple ampersand alone.
I have achieved my intended goal with an iterator, but I'll bet that javascript offers a more elegant way to accomplish this.  So I'm asking this as a learning exercise.


text:
Q: KVM/Libvirt bridged/routed networking not working on newer guest kernels I have a dedicated server running Debian 6, with Libvirt (0.9.11.3) and Qemu-KVM (qemu-kvm-1.0+dfsg-11, Debian).
I am having a problem getting bridged/routed networking to work in KVM guests with newer kernels (>2.6.38). NATted networking works fine though.
Older kernels work perfectly fine as well.
The host kernel is at version 3.2.0-2-amd64, the problem was also there on an older host kernel.
The contents of the host's /etc/network/interfaces (ip removed):

# Loopback device:
auto lo
iface lo inet loopback

# bridge
auto br0
iface br0 inet static
  address   176.9.xx.xx
  broadcast 176.9.xx.xx
  netmask   255.255.255.224
  gateway   176.9.xx.xx
  pointopoint   176.9.xx.xx
  bridge_ports eth0
  bridge_stp off
  bridge_maxwait 0
  bridge_fd 0
  up route add -host 176.9.xx.xx dev br0 # VM IP
  post-up mii-tool -F 100baseTx-FD br0

# default route to access subnet
up route add -net 176.9.xx.xx netmask 255.255.255.224 gw 176.9.xx.xx br0

The output of ifconfig -a on the host:

br0       Link encap:Ethernet  HWaddr 54:04:a6:8a:66:13
          inet addr:176.9.xx.xx  Bcast:176.9.xx.xx  Mask:255.255.255.224
          inet6 addr: fe80::5604:a6ff:fe8a:6613/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:20216729 errors:0 dropped:0 overruns:0 frame:0
          TX packets:19962220 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:14144528601 (13.1 GiB)  TX bytes:7990702656 (7.4 GiB)

eth0      Link encap:Ethernet  HWaddr 54:04:a6:8a:66:13
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:26991788 errors:0 dropped:12066 overruns:0 frame:0
          TX packets:19737261 errors:270082 dropped:0 overruns:0 carrier:270082
          collisions:1686317 txqueuelen:1000
          RX bytes:15459970915 (14.3 GiB)  TX bytes:6661808415 (6.2 GiB)
          Interrupt:17 Memory:fe500000-fe520000

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:6240133 errors:0 dropped:0 overruns:0 frame:0
          TX packets:6240133 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:6081956230 (5.6 GiB)  TX bytes:6081956230 (5.6 GiB)

virbr0    Link encap:Ethernet  HWaddr 52:54:00:79:e4:5a
          inet addr:192.168.100.1  Bcast:192.168.100.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:225016 errors:0 dropped:0 overruns:0 frame:0
          TX packets:412958 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:16284276 (15.5 MiB)  TX bytes:687827984 (655.9 MiB)

virbr0-nic Link encap:Ethernet  HWaddr 52:54:00:79:e4:5a
          BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:500
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

vnet0     Link encap:Ethernet  HWaddr fe:54:00:93:4e:68
          inet6 addr: fe80::fc54:ff:fe93:4e68/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:607670 errors:0 dropped:0 overruns:0 frame:0
          TX packets:5932089 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:500
          RX bytes:83574773 (79.7 MiB)  TX bytes:1092482370 (1.0 GiB)

vnet1     Link encap:Ethernet  HWaddr fe:54:00:ed:6a:43
          inet6 addr: fe80::fc54:ff:feed:6a43/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:922132 errors:0 dropped:0 overruns:0 frame:0
          TX packets:6342375 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:500
          RX bytes:251091242 (239.4 MiB)  TX bytes:1629079567 (1.5 GiB)

vnet2     Link encap:Ethernet  HWaddr fe:54:00:0d:cb:3d
          inet6 addr: fe80::fc54:ff:fe0d:cb3d/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:9461 errors:0 dropped:0 overruns:0 frame:0
          TX packets:665189 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:500
          RX bytes:4990275 (4.7 MiB)  TX bytes:49229647 (46.9 MiB)

vnet3     Link encap:Ethernet  HWaddr fe:54:cd:83:eb:aa
          inet6 addr: fe80::fc54:cdff:fe83:ebaa/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1649 errors:0 dropped:0 overruns:0 frame:0
          TX packets:12177 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:500
          RX bytes:77233 (75.4 KiB)  TX bytes:2127934 (2.0 MiB)

The guest's /etc/network/interfaces, in this case running Ubuntu 12.04 (ip removed):

# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

# The loopback network interface
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
        address 176.9.xx.xx
        netmask 255.255.255.248
        gateway 176.9.xx.xx                # Host IP
        pointopoint 176.9.xx.xx            # Host IP
        dns-nameservers 8.8.8.8 8.8.4.4

The output of ifconfig -a on the guest:

eth0      Link encap:Ethernet  HWaddr 52:54:cd:83:eb:aa
          inet addr:176.9.xx.xx  Bcast:0.0.0.0  Mask:255.255.255.255
          inet6 addr: fe80::5054:cdff:fe83:ebaa/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:14190 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1768 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:2614642 (2.6 MB)  TX bytes:82700 (82.7 KB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:954 errors:0 dropped:0 overruns:0 frame:0
          TX packets:954 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:176679 (176.6 KB)  TX bytes:176679 (176.6 KB)

Output of ping -c4 on the guest:

PING google.nl (173.194.35.151) 56(84) bytes of data.
64 bytes from muc03s01-in-f23.1e100.net (173.194.35.151): icmp_req=1 ttl=55 time=14.7 ms
From static.174.82.xx.xx.clients.your-server.de (176.9.xx.xx): icmp_seq=2 Redirect Host(New nexthop: static.161.82.9.176.clients.your-server.de (176.9.82.161))
64 bytes from muc03s01-in-f23.1e100.net (173.194.35.151): icmp_req=2 ttl=55 time=15.1 ms
From static.198.170.9.176.clients.your-server.de (176.9.170.198) icmp_seq=3 Destination Host Unreachable
From static.198.170.9.176.clients.your-server.de (176.9.170.198) icmp_seq=4 Destination Host Unreachable

--- google.nl ping statistics ---
4 packets transmitted, 2 received, +2 errors, 50% packet loss, time 3002ms
rtt min/avg/max/mdev = 14.797/14.983/15.170/0.223 ms, pipe 2

The static.174.82.xx.xx.clients.your-server.de (176.9.xx.xx) is the host's IP.
I have encountered this problem with every guest OS I've tried, that being Fedora, Ubuntu (server/desktop) and Debian with an upgraded kernel. I've also tried compiling the guest kernel myself, to no avail.
I have no problem with recompiling a kernel, though the host cannot afford any downtime.
Any ideas on this problem are very welcome.

EDIT: I can ping the host from inside the guest.

A: Ok, I have found the solution myself. Apparently, the article on the Hetzner wiki wasn't complete. Redirects were still being sent, resulting in Hetzner (where we have our server) blocking the traffic. I am not sure how it had to do with what kernel version the guests were running, if someone can explain that I would very much like to hear it.
You can find out if you suffer from the same problem by executing the following command:
for file in `find /proc/ -iname send_redirects`; do echo $file; cat $file; done
which outputs something like:
/proc/sys/net/ipv4/conf/all/send_redirects
0
/proc/sys/net/ipv4/conf/default/send_redirects
1
/proc/sys/net/ipv4/conf/lo/send_redirects
1
/proc/sys/net/ipv4/conf/eth0/send_redirects
0
/proc/sys/net/ipv4/conf/br0/send_redirects
1
/proc/sys/net/ipv4/conf/vnet1/send_redirects
1
/proc/sys/net/ipv4/conf/vnet0/send_redirects
1
/proc/sys/net/ipv4/conf/virbr0/send_redirects
1
/proc/sys/net/ipv4/conf/virbr0-nic/send_redirects
1
/proc/sys/net/ipv4/conf/vnet2/send_redirects
1
/proc/sys/net/ipv4/conf/vnet3/send_redirects
1
I have to admit I do not know which ones should or should not be 0, but I have set them all to 0, and now it works fine, so I'll leave it at that.
for file in `find /proc/ -iname send_redirects`; do echo 0 > $file; done

A: I had the same issue, thanks for sharing your solution.
I think the setting is needed only on physical and bridge interface (eth0 and br0).
You can make the change persistent by setting it into /etc/sysctl.d/
#/etc/sysctl.d/10-no-icmp-redirects.conf
# Hetzner says:
# Because of our network setup, the Host machine could send ICMP
# "redirect" messages to all guests, telling them to find the Hetzner
# gateway directly.  That is impossible: Hetzner would throw away the
# traffic from the virtual interfaces because of their non registered
# MAC addresses (ie different from the main interface).
net.ipv4.conf.all.send_redirects=0
net.ipv4.conf.eth0.send_redirects=0
net.ipv4.conf.br0.send_redirects=0
net.ipv4.conf.default.send_redirects=0


text:
Q: Sometime when accessing a menu: "Ubuntu 16.04 has experienced an internal error" Sometime, when I try to access some menu (may be inside an application or desktop, doesn't matter), I got the following error. The menu and submenu disappear for a while. After that, I can continue using the system.

And the lspci gave me the following output:
$ lspci -k | grep -EA3 'VGA|3D|Display'
00:02.0 VGA compatible controller: Intel Corporation Haswell-ULT Integrated Graphics Controller (rev 0b)
        DeviceName:  Onboard IGD
        Subsystem: Dell Haswell-ULT Integrated Graphics Controller
        Kernel driver in use: i915


text:
Q: Why do I get an extra white page before my TikZ picture? I've created a little diagram in TikZ.
Only problem is, it's quite big, so I figured I should use landscape mode for it.
Only problem is, when I put it between
\begin{landscape}
\input{erd.tikz.tex} % my diagram
\end{landscape}
I get an extra white page before the diagram itself.
I can't seem to understand why, any idea?
Thanks.
Here is the document:
\documentclass[border=0.4in]{article}

\usepackage{tikz}
\usetikzlibrary{shapes.multipart}
\usetikzlibrary{matrix}
\usetikzlibrary{positioning}
\usetikzlibrary{calc}
\usepackage{scalefnt}
\usepackage{geometry}
\usepackage{pdflscape}

\makeatletter

\begin{document}

\section{Foo}
Foo bar bar bar foo, foo bar.
\newgeometry{left=2cm,bottom=3cm}
\begin{landscape}
\input{erd.tikz.tex}
\end{landscape}
\restoregeometry
\section{Zip}
Boom boom, zip.

\end{document}

A: use
\begin{landscape}
\resizebox{!}{0.95\textheight}{\input{erd.tikz.tex}}
\end{landscape}

The image is too big. The reason why it is placed on the following page.


text:
Q: What does stub.callsArg(index) from Sinon.JS do? Seriously, I can't figure this out. The documentation gives us:
stub.callsArg(index) - Causes the stub to call the argument at the provided index as a callback function. stub.callsArg(0); causes the stub to call the first argument as a callback.
However, I've got no idea where this list of arguments to be indexed into is. Maybe I just don't understand what a stub is...

A: A stub is a noop function with programmable behavior. In your case callsArg(index) will program the stub to expect a function at index and immediately invoke it.
function sayHi() {
  console.log('hi');
}
var stub = sinon.stub().callsArg(2);
stub('abc', 42, sayHi); // prints "hi"


text:
Q: Interpolating Gaussian mixture. How many points is sufficient for complete reconstruction Consider the following Gaussian mixture of $N$ components:
\begin{align}
f(x)=  \sum_{i=1}^N p (s_i)  e^{-\frac{(x-s_i)^2}{2}}\big/ \sqrt{2\pi}
\end{align}
where we assume that

*

*$\max_{i} |s_i| \le C$

*$p (s_i)$ is probability distribution (i.e.,  $\sum_i p(s_i) =1 $ and $1 \ge p(s_i) \ge 0 $

*$p(s_i)$ is symmetric. That is, if $s_i \neq 0$, then there exists $j$ such that $i \neq j$ and  $s_i=-s_j$ and $p(s_i)=p(s_j)$.

*we know the value of $N$
Otherwise, we have no knowledge of $s_i$'s or $p(s_i)$
My question is the following: Suppose we are allowed to evaluate/sample $f$ at any $K$ points we desire.  How many samples $K$ do we require to completely reconstruct $f$?
Unfortunately, $f$ is not bandlimited in the Fourier domain otherwise we could have used Nyquist criteria.  However, because of the Gaussian tail, it is almost bandlimited, plus we have additional information about its structure (i.e., we know $N$).  So, therefore, I am curious if $K<\infty$ is enough.
This question must have been asked before but I couldn't find any reference and don't really know for what keywords to search.
Some thoughts
One can set this up as a linear algebra problem. First, choose $K$ samples $x_i$ at which we will evaluate $f$ then and let
\begin{align}
F=[f(x_1),\ldots, f(x_k) ]^T
\end{align}
also define a matrix $E$ such that
\begin{align}
E_{ij}= e^{-\frac{(x_i-s_j)^2}{2}}\big/ \sqrt{2\pi}
\end{align}
and let
\begin{align}
P=[p(s_1),...p(s_N)]
\end{align}
Therefore, our problem can be written as
\begin{align}
E P=F
\end{align}
we are interested in recovering $E$ and $P$ based on the knowledge of $F$.

A: Since
$$\sum_{i=1}^K p(s_i)e^{-(x_j-s_i)^2/2}=e^{-x_j^2/2}\sum_{i=1}^K p(s_i)e^{x_js_i-s_i^2/2}=e^{-x_j^2/2}\sum_{i=1}^K \underbrace{p(s_i)e^{-s_i^2/2}}_{q_i}e^{x_js_i}$$
it is equivalent to consider the system of equations
$$\require{cancel}\cancel{e^{x_j^2/2}}\cancel{e^{-x_j^2/2}}\sum_{i=1}^K q_i\left[e^{s_i}\right]^{x_j}=\alpha_je^{x_j^2/2}\qquad j=1,\ldots,N$$
which should be solvable with $N=2K$ interpolation points $x_j$ taken at random in $(-C,C)$ (without considering the further constraints).

A: I doubt whether exact recovery of the function from a finite number of test points is possible in general. And if it is possible, it will be difficult. But there are very practical ways to bound the error and based on this error bound to devise designs of test points to minimise the error. For simplicity I will largely ignore the constraints on the coefficients and the values for $s$ as I do not think they change the basics of the problem.
The vector space spanned by the set of functions $\{f(x)=\exp(-\frac {(x-s)^2} {2})\mid s\in\mathbb{R}\}$ is a reproducing Hilbert space (RKHS) with kernel $K(x,s)=\exp(-\frac {(x-s)^2} {2})$. Since $K$ is a positive definite function, this space is infinite dimensional. Your equation $EP=F$ will always have a unique solution, no matter how many (distinct) interpolation points you choose in $F$. Furthermore, this solution can be characterised as the function with minimum Hilbert-space norm among all interpolating functions and of course by construction it is a N-component function.
But this Hilbert space is large and in general there will be other interpolating functions, some of them also with $N$-components. This can be demonstrated by a simple example with N=2. In the picture below I plot the functions $\frac{1}{2}\exp(-\frac {(x+ 1)^2}{2})+\frac{1}{2}\exp(-\frac {(x- 1)^2}{2})$ and $\frac{1}{2}\exp(-\frac {(x+ 2)^2}{2})+\frac{1}{2}\exp(-\frac {(x- 2)^2}{2})$. Note that the graphs intersect. If you happen to choose these points for interpolation you have two possible 2-component interpolants and you will not be able to distinguish between them from the test points alone.

One may argue that these intersections look like very special points, which may be avoided. But if you allow larger $N$ these functions can get more and more complicated and the intersections harder and harder to describe. The full space (without constraints) is actually universal, which means you can approximate every continuous(!) function on a compact interval in the uniform norm.
That said, if you do not require exact recovery but can live with approximation then RKHS theory provides you with pointwise error estimates. Those are based on the kernel function $K$, the fill distance of your design of test points, which is basically the largest possible distance to any of your test points and the norm of your target function $f$. For details see Chapter 14 of Gregory E. Fasshauer, "Meshfree Approximation Methods with MATLAB" and in particular Example 15.1 for the approximation order of the Gaussian kernel.
Finally, the Gaussian kernel is known to be numerically fickle. See cit.loc. Example 16.1 for a discussion of the condition number of Gaussians. This can be addressed by various methods, such as pre-conditioning and choosing a better basis. See cit.loc. Chapter 34 for a discussion of those issues.


text:
Q: Trying to install Ruby 1.8.7-p249 on Ubuntu 16 results in an SSL error There's a lot of questions regarding this on Stackoverflow, but the answers appear to be out of date or not applicable to my situation.
I've followed the instructions in this answer - https://stackoverflow.com/a/9440944/1446264
And after running
rvm pkg install openssl
rvm install ruby-1.8.7-p249 --with-openssl-dir=/usr/share/rvm/usr

I'm still left with the following error on the server.
make[1]: *** [ossl.o] Error 1
make[1]: Leaving directory `/usr/share/rvm/src/ruby-1.8.7-
p249/ext/openssl'
make: *** [all] Error 1`

I think the reason must be because the version of openssl installed after running rvm pkg install openssl is too new.
openssl version  gives me 1.0.1f
and
rvm pkg install openssl installed openssl-1.0.1i
On my development machine, I'm running openssl-0.9.8zh without any issues, so ideally I'd like to be able to use this version of openssl.
Is there any way of specifying a version number when running rvm pkg install openssl? so I could do something like rvm pkg install openssl -v 0.9.8zh. I've not come across any such syntax.
Does anyone have any ideas as to how I can resolve this? I've been battling for hours. I've tried installing Ruby from source as well as with RVM and Rbenv but the openssl issue persists.


text:
Q: BATCH: Looking to "thread" commands and capture output to txt n00b here.
I am creating a simple batch file and need the following:
I have about 15 commands I need to "thread". Running a simple batch file forces me to wait after each command is executed to start the next. So my research lead me to the "START" command. This works but the new window created for each command disappears so research then lead me to "CALL" which keeps each window open after its executed so I can monitor the output. Next I needed to have each window output to a log file.
I cant seem to capture this info. Everything I have tried yields an empty txt file, although it does create the file itself.
Example.
ECHO Starting up processes
start "Process 1" call ping www.google.com > Googleresults.txt
start "Process 2" call ping www.apple.com > Appleresults.txt

Any ideas? Much appreciated!

A: This will be the easiest built in way to do this by utilizing powershell as well.
ping google.com>Googleresults.txt | start "process 1" powershell Get-Content Googleresults.txt -Wait -Tail 10 | ping apple.com>Appleresults.txt | start "process 2" powershell Get-Content Appleresults.txt -Wait -Tail 10
taskkill /FI "WINDOWTITLE eq process*">nul

You need to seperate each command with pipe | to start them asyncronously, it redirects to file and we pretty much start new windows and tail the files using powershell.


text:
Q: Android Webview and WP current user I have a wordpress site and an android app using webview, is it possible to get the current user info from wordpress to android?

A: I found a way by adding a custom cookie to my site and parse it using this code. But if you guys have better solution or if this will have problem in the future, tell me :)


text:
Q: SQL Server regional settings database wise I have an SQL Server instance with 3 databases.  (A, B & C).
The operating system has regional / date & time settings of India.
My requirement is  :
Database A should get regional settings of India.
Database B should get regional settings of US.
Database C should get regional settings of Dubai.
Currently, I am concerned with date & time only.
So, If I execute the query on the different databases:
Select getdate()

It should return the date & time based on the database's regional setting (which i am trying to find how to set).
For Eg : The Operating System's Current Date & Time is 3rd November  6:18 pm
Database A (India Time) should Give 3rd November  6:18 pm
Database B (US Time) should Give 3rd November  7:49 pm
Database C (Dubai Time) should Give 3rd November  4:49 pm
I am unsure about how do I change the settings database wise from server or by passing some parameters via connection string or is it really possible to accomplish this.
or I would have to write my own function for doing this.


text:
Q: MySQL Connector/Python stored procedure insert not committing I'm writing a python script to monitor a few 1wire sensors off of a Raspberry Pi and store the results in a MySQL database.
Using the MySQL Connector/Python library I can successfully connect to the database, and run the query however the transaction doesn't seem to fully commit. I know the query runs successfully since the out param is set to the new auto-incremented ID.
CREATE TABLE `lamp`.`sensors` (
 `SensorID` int(11) unsigned NOT NULL AUTO_INCREMENT,
 `SensorSerial` char(15) NOT NULL,
 `SensorFamily` tinyint(4) NOT NULL,
 PRIMARY KEY (`SensorID`),
 UNIQUE KEY `SensorID_UNIQUE` (`SensorID`),
 UNIQUE KEY `SensorSerial_UNIQUE` (`SensorSerial`)
)

CREATE PROCEDURE `lamp`.`AddSensor` (sensorSerial char(15),
                         sensorFamily tinyint, out returnValue int)
BEGIN
 INSERT INTO sensors (SensorSerial,SensorFamily) VALUES (sensorSerial,sensorFamily);
 SET returnValue=LAST_INSERT_ID();
END

However when I attempt to query the table (Select * from sensors) I get 0 results. If I run the procedure from the MySQL Workbench or from a .Net application everything works as expected. Which means I'm missing something when it comes to the Connector/Python, but I have no clue what. I'm extremely baffled since the auto-increment value does increase but no records are added. There are also no errors reported
 def Test(self):
    #this line works fine
    #self.RunProcedure("INSERT INTO sensors (SensorSerial,SensorFamily) VALUES ('{0}',{1})".format(self.ID,self.Family),False,())
    #this line does not?
    args=self.RunProcedure('AddSensor',True,(self.ID,self.Family,-1))
    if args[2]>=1:
        logging.debug("Successfully added sensor data '{1}' for sensor '{0}' to the database".format(self.ID,value))
        return True
    else:
        logging.critical("Failed to add Data to Database for unknown reason. SensorID: {0} Type: {1} Data:{2}".format(self.ID,self.Family,value))

def RunProcedure(self,proc,isStored,args):
    try:
        logging.debug("Attempting to connect to database.")
        connection=mysql.connector.connect(user='root',password='1q2w3e4r',host='localhost',database='LAMP')
    except mysql.connector.Error as e:
        logging.exception("Failed to connect to mysql database.\r\n {0}".format(e))
    else:
        logging.debug("Successfully connected to database.")
        try:
            cursor=connection.cursor()
            if isStored:
                args = cursor.callproc(proc,args)
                return args
            else:
                cursor.execute(proc,args)
            #these do not seem to solve the issue.
            #cursor.execute("Commit;")
            #connection.commit()
        except mysql.connector.Error as e:
            logging.exception("Exception while running the command '{0}' with the args of '{1}' exception is {2}".format(proc,args,e))
        finally:
            logging.debug("Closing connection to database")
            cursor.close()
            connection.close()

Output from to the log looks like this;
2013-06-09 13:21:25,662 Attempting to connect to database.
2013-06-09 13:21:25,704 Successfully connected to database.
2013-06-09 13:21:25,720 Closing connection to database
2013-06-09 13:21:25,723 Successfully added sensor data '22.25' for sensor '10.85FDA8020800' to the database

**Edit
Not sure why but adding autocommit=True to the connection.open params seems to have resolved the issue. Since it was a problem with committing why didn't connection.commit() or the cursor.execute('commit;') correct the issue?

A: The problem is actually in your code:
    ..
    try:
        cursor=connection.cursor()
        if isStored:
            args = cursor.callproc(proc,args)
            return args
        else:
            cursor.execute(proc,args)
        connection.commit()
    except mysql.connector.Error as e:
    ..

If you are using the Stored Routine, you are immediately returning, so commit() will never be called.


text:
Q: how to edit the configuration file of boost in slave using buildbot ShellCommand? So I am trying to build and test boost in the remote slave( mac ). I want to edit tools/build/v2/user-config.jam file so that I could use the toolset=clang.
How can I add
//in user-config.jam
// toolset will use clang

using clang
   : ...etc

in the user-config.jam file?

A: It turns out that unix has a nice little command called
echo

so what I can do is use this command to edit that file.
ShellCommand(
    name = "append config instruction"
    command=['echo','I am adding this configuration cause it was missing','>','~/user-config.jam']
 )

This command will add that line in the configuration file.
if you want to make it look like
"I am adding this configuration cause it was missing" I meant to add "" then
echo "\"xyz\"" > text.txt


text:
Q: How can I check a negative solution of a twos complement subtraction equation? Hey guys I'm still trying to get the hang of twos complement arithmetic and I can get the correct answer, since I'm working on practice problems with solutions.
When I take the answer that's in binary, I can't  seem to equate it out to the decimal answer before applying twos complement  and adding the numbers.
000100-111001   In decimal it's 4 - 57= -53
Becomes
0001000+000111  which would be 4 + (-57)?
Giving a solution of 001011
How can 001011 be proven as equaling -53?
Thanks!

A: To answer your question, first 001011 is not equal to -53. This is the wrong answer. We know it must be positive since the highest order bit is a 0, not a 1. 001011 is actually equal to 11 (in base ten).
Let's do 4 - 57 now as an example. This is the same as 4 + (-57). Converting to binary (I will use just a byte for this example) we get: 4 is 0000 0100, 57 is 0011 1001. To convert 57 to negative 57 use two's complement:
1. Negate it: 1100 0110
2. Add one: 1100 0111So now we get the following equation:
  0000 0100
+ 1100 0111
------------
  1100 1011

We achieve the answer by simply adding down the rows. The answer we have gotten is 1100 1011. We know it is negative because the highest order bit (which here is leftmost) is a 1. To find its magnitude, we apply two's complement:
1. Negate: 0011 0100
2. Add one: 0011 0101
And this is equal to 53 in base ten.
Another way to see if it is correct is to add it with the positive version of the number.
  1100 1011
+ 0011 0101
------------
 10000 0000

Since two's complement is defined as the number subtracted from 2^n where n is the number of bits, you will always get this result for the sum. Knocking off the 1s digit it's interesting how what remains is just 0 - and any number plus its negative is zero.


text:
Q: JOI full path to key erroring out So Im writing a schema validation using JOI. https://github.com/hapijs/joi
I want to make a small change to the behavior of the error being thrown.
This is the error I got right now :
[
    {
        "name": "api_schema",
        "message": "\"architect\" with value \"Someasda2342432ssda\" fails to match the required pattern: /^[a-zA-Z_ ]{2,50}$/"
    }
]

But what I would like to receive is  :
[
        {
            "name": "api_schema",
            "message": "\"api_config.team_info.architect\" with value \"Someasda2342432ssda\" fails to match the required pattern: /^[a-zA-Z_ ]{2,50}$/"
        }
    ]

As you can see, I need that the error message indicates all the path to the failed key, not just its name. I know JOI has the ability to customize the error messages, and I can do that, but I dont find a way to get the value of the entire path to the key that failed.
Can someone advise?

A: You can use callback option. Something like this
const schema = Joi.object().keys({
  a: Joi.string()
});

const object = { a: 123 };
const err = Joi.validate(object, schema, (err, value) => {
  // console.log('original error', err);
  err.newValidationError = 'new message ' + err.details[0].message;
  return err;
});

console.log(err);

If you are using with Hapi, you can also look at failAction as answered here


text:
Q: Colonists land on a new planet, plants turn out to be toxic I'm trying to find a book where colonists land on a new planet but the food supply / plants turn out to be toxic to people. In the end the people realize the plants aren't actually toxic, but extremely concentrated with healthy minerals - and if they dilute them, the plants are very healthy and nutritious.
[edits added]: this book was read in the early 90s or late 80s so it is not Orson Scott Card's Pathfinder (from 2010) or The Green Book - which had glass like plants, not 'toxic' plants which were just super concentrated nutrients. Thanks for your help so far everybody, but we're still looking for the answer.

A: The Faces of Ceti by Mary Caraker

Arriving at the Tau Ceti system they intend to colonize, 500 Earth pioneers are surprised to find not one, but two habitable planets. An ideological rift between them suggests a division of the colonists, and the absorbing plot follows the struggle for survival on the smaller planet, surrounded by harsh conditions, poisonous plants, and the native, possibly intelligent, hlur. These are interesting animals, something like burbling kangaroos, and the question of whether they are sentient fuels a heated debate about killing and eating them in the face of a severe food shortage. Teenagers Maya and Brock risk their lives to discover the secret of the hlur and why they can eat the indigenous plants when earthlings cannot.


text:
Q: Proving $\left(1 + \frac{t}{\sqrt{n}}\right)^n e^{-\sqrt{n} t} \le (1+t)e^{-t}$ I would like to prove the inequality
$$\left(1 + \frac{t}{\sqrt{n}}\right)^n e^{-\sqrt{n} t}  \le (1+t)e^{-t}$$
for $t > 0,n \in \Bbb N_{>0}$.
This is claimed in this answer, but I don't know how to proceed. I only know that $(1+\sqrt n t/n)^n \leq e^{\sqrt n t}$, so the LHS is bounded by $1$...

A: If we set $n=z^2$ and switch to logarithms, the LHS turns into
$$ g(z) = z^2 \log\left(\frac{z+t}{z}\right) - t z = z \int_{0}^{t}\frac{z}{u+z}\,du-z\int_{0}^{t}1\,du = -\int_{0}^{t}\frac{1}{\frac{1}{u}+\frac{1}{z}}\,du$$
that clearly is a decreasing function over $(1,+\infty)$ for any $t>0$.


text:
Q: Prism and Using Unity IoC in Prism I am a total newbie on Prism. I have been getting to understand a lot from questions on SO and from various Blogs. I am using latest build – V2
I want some explanations on things that may be pretty easy things for you guys but it's just not getting into my brains (small one for that).
Instead of doing it all right the first time , for which I have spent more than two weeks looking at various blogs, webcast …., I thought to start  a project and learn.  The amount of information on those hundreds of sites was overwhelming and difficult to digest.
Currently my project  is setup like this
Shell  --  Menu Module- ViewModel - - ->   Menu Service -- -- > Menu Repository  --- Data
All are in different assembly
MyShell ---  MenuModule                 ---MyServices --  Myrepository
Shell  is required to reference modules ( thought I am sure I can add it using string) later on .
ViewModel has a reference to View - Can live with it for now
View Model requires to use menu service   and menu service uses repository
All are built with constructor injection. I have it working now  by having  module reference  MyService  and Myrepository projects and then registering types at module level.
But this does not feel good.  I don't want to hard reference any projects.  If we are referencing  projects why use IoC. In MenuModule.cs ( which is in the root of module) I  can register views  with unity container
I think I am getting a feel that  the answer to this one may lie in the first question

*

*Is Configuration file the answer/
Should I use configuration file for
true decoupling?

*If (somehow) we can
register types from code, should we
register types at module level ( I
don't want to  have hard reference to projects)

*I need to know the
Interfaces in advance so do you
recommend separate assembly for just
Interfaces?

Bear with me if the questions sound real stupid 

A: You don't need a configuration file for true decoupling.  All you need is to register your types in your shell's bootstrapper.  I usually break up my projects and refs like this.
Contract Assembly
(Contains only a few simple types and interfaces)
Referenced by:

*

*Shell

*Modules

Shell
(Contains concrete implementations of interfaces defined in Contract assembly)
Referenced by:

*

*No one

Modules
(Declares dependencies on interfaces defined in Contracts assembly, for instance IMenuRegistry)
Referenced by:

*

*No one (I use a Directory Module to search for modules in a directory)

Here's a sample project I put together.  In this sample I reference the module from the shell for simplicity's sake, but you can remove that reference and use a directory module catalog to load the compiled module at runtime:
http://dl.getdropbox.com/u/376992/CAGMenus.zip
Hope this helps,
Anderson

A: You're definitely on the right track. Use the configuration file to register your types, and put the interfaces in a separate assembly.


text:
Q: Is there anyway to implement Card with 2 countries flags and some text I am using react-native-element library with expo I am using Expo with react-native-element I want to implement a country flag on the left side and right side and text between them in the Card component but I can't find the way something like in the pic.
country1 vs matchtime & date country2

A: you should use flexbox and styling to get the components to be positioned like you want.
The most important part is to understand how the flexbox layout works and how it divides the screen. Look into it and try to understand how flexDirection should be used.
Here's an Expo snack with an example of how you can achieve the result you want, it should look something like this:


text:
Q: Work Stealing: join a recursive task requires stealing? I'm trying to understand the effect of work stealing on recursive tasks:
One of the advantages of work stealing is that the current worker/thread is  likely to execute its own spawned tasks; increasing data locality.
However, what happens in the common case when a worker join on its spawned tasks?
For example:
Future<String> a=pool.submit(()->doA());
b=doB();
return a.get()+b;

I think here the current thread will get blocked, thus unable to take the work from its own queue, thus another worker will have to steal those works. This would deny the locality advantage of work stealing. However, according to wikipedia (https://en.wikipedia.org/wiki/Work_stealing)
"Work stealing is designed for a "strict" fork–join model of parallel computation"
I must have some mistake in my reasoning, but I can not found it.
More in the details, consider the following code:
Future<String> res=pool.submit(()->{
  Future<String> a=pool.submit(()->doA());
  b=doB();
  return a.get()+b;
  });
res.get();

This code should start the computation inside a worker. Such worker will spawn a new task. Then he try to get the result for this nested task. How is this nested task executed?

A: The fork-join pool provides a high performance, parallel, fine-grined task execution framework for Java Programmers.
It solves the problem by divide and conquer. Splitiing the task into sub-tasks. A task creates a sub-task by fork() method.
When task client submits/invokes/executes a fork join task, the task gets into a shared queue, this shared queue is used to feed unshared double ended queue (aka "deque") managed by the WorkerThread.
One or more WorkerThreads are called a Fork-Join pool.
A WorkerThread pulls off the task from the shared queue, and they go a head and process the work (using the unshared queue).
Each WorkerThread (which is actually a Java thread) in Fork-Join-Pool runs in a loop that continually scans for (sub-)task to execute.
The goal is to try to keep the WorkerThreads as busy as possible so we want them to always have something to do.
The goal is maximize processor core utilization.
Each WorkerThread has it's, double ended queue (aka "deque")  that serves as its main source of task.
Above and beyond, that other shared queue that used to get, non-fork join task into the fork-join pool, in 1st place.
The "deque" are implemented by WorkQueue (which is a Java class that's nested inside ForkJoinPool). Some important methods in that class are push(), pop() and poll().
At some point, the task can't make any progress, since it's wait for the sub-task to complete by the join() method .
This join is different from a join in a Java thread.
In Java Thread Join if a task doesn't return a result, is blocks, and waits to this other thread to finish.
If in Fork-Join the join() happens to block, then the WorkerThread stops working on the current thread and start executing the sub-task..
Whenever you are calling a fork() inside compute method inside of a RecursiveTask<> or  RecursiveAction  that is always running in the context of thread in the fork-join-pool.
If a task a RecursiveTask<> or  RecursiveAction is running by the WorkerThread calls fork(), that new ForkJoinTask* is pushed onto the head of that workers "deque" thread.
It pushes it, in LIFO order, Last In First Out.
When we call join() for this task, that task would be poped from the head of the "deque" (top of the stack)  and is run to completion(keep running till it's done) in the WorkerThread.
Why do we do LIFO? Why do we push at the front and pop at the front ? In order to improve locality of reference, improve cache performance, so that you get the processing as quickly as possible, sometimes called fresh work before stale.
The ForkJoinTask enables fine-grained data parallelism.
A ForkJoinTask is lighter than a Java thread, it doesn't have it's own runtime stack .
A ForkJoinTask associates a chunk of data along with a computation on that data.
A real Java thread has it's own stack, registers, a lot of other resources that allow it to be scheduled independently managed by the thread scheduler, that the operating system has internally.
A large number of  ForkJoinTask can run in a much smaller number of WorkerThreads in the Fork-Join-Pool.
The number of WorkerThreads is typically (if not specified) a function of the number of cores. Each WorkerThread is a Java thread object with all it's accoutrements that you expect from a normal thread.
A ForkJoinTask has two important methods that control parrallel processing and merging the results, these are fork() and join().
A fork() arranges to asynchronously execute this task in the appropriate thread pool. A fork() is like a lightversion of Thread.start().
A fork() doesn't create a Java worker thread (at least not directly), But eventually, it will run on a Java Thread.
It doesn't start to run immediately but instead it places the sub-Task on the head of the work queue.
A join() returns of the computation when the sub-Task is finished.
Join in a Fork-Join pool is different from the classic Java thread join.
Java thread is used as a barrier syncronizer to wait for another thread to finish and then you join with it (You can't proceed until the other one is done).
A join in a regular thread blocks the calling thread.
The join in a Fork-Join pool doesn't simply block the calling thread, instead, the WorkerThread is assigned to run the pending sub-tasks.
When the WorkerThread encounteres a join() it processes any other sub-tasks until it notices the target sub-task is done.  The WorkerThreads doesn't return to the caller until this sub-tasks results are finished.
A Join in a fork-join task is not block, it holds the current task, so the computation to be continued only after it's sub-tasks created by the join() finished.
The WorkerThread figures out, that the task is blocked till the sub-task is finished so it start to work on the sub-task.
A WorkerThread processes it's own "deque" in a LIFO order, by popping  (sub-)tasks from it's own "deque".
WORK STEALING
When a WorkerThread doesn't have anything else to do - "idle" .If WorkerThread's own queue is empty, it will go and try to "steal" a sub-task from the tail of some other busy thread "deque", that is selected randomlly, inorder to maximaize core utilization.
The tasks are "stolen" in FIFO order, since an older stolen task may provide a large unit of work.
Push() and  pop() are only called by the owning worker thread  (To the top of the "deque") that is the reason they are most efficient they use wait-free "Compare-And-Swap" CAS operations. CAS is a hardware level of atomically check and set the value of lock in memory – it never blocks . push() and pop() has a very lightweight locking.
Poll() may be called from another thread to "steal" as sub-task. When we call poll() that's because the other thread has been randomly assigned to try to "steal" sub-task from the end of this deque in FIFO order. Poll() is initiated by another thread, as a result it may not always be wait-free, so sometimes it has to "yield" and come back and try later again. "stealing" is fast but it may not be as fast as pushing and popping.


text:
Q: Chinese Remainder Theorem for rings: why not for modules? This is a followup to Analog to the Chinese Remainder Theorem in groups other than Z_n. . I shouldn't have used the comments to ask a new question, in fact...
Here is the statement of the Chinese Remainder Theorem, as it occurs in most books and websites:
(1) Let $R$ be a commutative ring with unity, and $I_1$, $I_2$, ..., $I_n$ be finitely many ideals of $R$ such that ($I_i+I_j=R$ for any two distinct elements $i$ and $j$ of $\left\lbrace 1,2,...,n\right\rbrace$). Then, $I_1I_2...I_n=I_1\cap I_2\cap ...\cap I_n$, and the canonical ring homomorphism $R/\left(I_1I_2...I_n\right)\to R/I_1 \times R/I_2 \times ... \times R/I_n$ is an isomorphism.
But there seems to be another, even more general form of (1) which doesn't get even half of the attention:
(2) Let $R$ be a commutative ring with unity, and $I_1$, $I_2$, ..., $I_n$ be finitely many ideals of $R$ such that ($I_i+I_j=R$ for any two distinct elements $i$ and $j$ of $\left\lbrace 1,2,...,n\right\rbrace$). Let $A$ be an $R$-module. Then, $I_1I_2...I_n\cdot A=I_1A\cap I_2A\cap ...\cap I_nA$, and the canonical $R$-module homomorphism $A/\left(I_1I_2...I_n\cdot A\right)\to A/I_1A \times A/I_2A \times ... \times A/I_nA$ is an isomorphism.
I am wondering: is (2) a trivial corollary of (1)? Because otherwise I don't see any reason why (2) shouldn't appear in literature as "the" Chinese Remainder Theorem, with (1) being but a corollary. Or is (2) wrong? The only way I see to get (2) from (1) is to apply (1) to the ring $R\oplus A$ (with multiplication on $R\oplus 0$ inherited from $R$, multiplication between $R\oplus 0$ and $0\oplus A$ given by the $R$-module structure on $A$, and multiplication on $0\oplus A$ given by $0$), which seems quite artificial to me. Am I missing something very obvious?

A: The second result you're talking about is also sometimes called the Chinese remainder theorem, and can be derived from the Chinese remainder theorem for rings by "tensoring the CRT isomorphism" with $A$. Explicitly, (1) gives
$R/\prod_{k=1}^n I_k\cong\prod_{k=1}^n R/I_k$
via the natural map. This is an isomorphism of rings as well as an isomorphism of $R$-modules. Therefore, upon tensoring with $A$, it becomes

$A/\big(\prod_{k=1}^nI_k\big)A\simeq \prod_{k=1}^n A/I_kA$
via the natural map, using the canonical isomorphism $R/I\otimes_RA\cong A/IA$ as well as the fact that tensor product commutes with finite direct products. It follows that the kernel of $A\rightarrow\prod_{k=1}^n A/I_kA$, which is clearly $\bigcap_{k=1}^n I_kA$, is equal to $\big(\prod_{k=1}^n I_k\big)A$. So, you've derived (2) from (1). Keep in mind that (2) is an isomorphism of $R$-modules, while (1) is an isomorphism of rings (as well as $R$-modules).


text:
Q: rabbitmq constantly alert Node seems down in Prometheus I setup rabbit-mq cluster version 3.8.2 .
I enabled Prometheus module in all rabbit to scrape data out of it for monitoring.
my alert system constantly shows that the rabbit is down but its not.
anyone can help me with that.
problem to scrape rabbitmq on rabbitmq1:15692 for more than 10 minutes. Node seems down.

A: Have you checked port 15692 in the RabbitMQ node? It will probably show you that the connection is refused.
I would recommend monitoring port 5672 to make sure your node is up. But you can also have problems with RabbitMQ, given that the prometheus plugin does not work correctly and the port is not always answered.


text:
Q: Use formula inside script I would like to use a formula inside a custom function, like this for example:
function myFunction(range, value) {
    var countNumber = COUNTIF(range; value); // COUNTIF is a formula that can be used in the spreadsheet
    if (countNumber > 0) {
        return "RESULT";
    } else {
        return "OTHER RESULT";
    }
}

And then:
=MYFUNCTION(A1:A5,"VALUETOTEST")

I would like to simplify a huge formula:
Something like:
=IF(SUM(COUNTIFS(G182:G186;"ERROR";H182:H186;"62");COUNTIFS(G182:G186;"ERROR";H182:H186;"ALL"))>0;"ERRO";IF(SUM(COUNTIFS(G182:G186;"RETEST";H182:H186;"62");COUNTIFS(G182:G186;"RETEST";H182:H186;"TODOS"))>0;"RETEST";IF(COUNTIF(G182:G186;"UNIMPLEMENTED")>0;"UNIMPLEMENTED";"SOLVED")))

A: You have three ways of performing these actions.

*

*Add the Sheet Formulas to the sheet itself in the ranges that you need. Then read the data from the result cells (wherever you set it to write to) using your GAS Function. You can then perform further processing using the results.

*Use your GAS function to write Sheet Formulas into your sheet. Then use more GAS to read that result and process the data. The method for this can be found here: https://developers.google.com/apps-script/reference/spreadsheet/range#setFormula(String)

*You can create a Custom Sheet Formula using GAS that you then use in your sheet. GAS can then read that result and process the information. This will require some research into JS as a whole to know how to recreate, combine, and perform the operations that you need the data in the sheet to perform.
You can find a guide to make Custom Formulas here: https://developers.google.com/apps-script/guides/sheets/functions
And a guide to JS here: http://www.w3schools.com/js/default.asp
W3 Schools has a quite comprehensive guide to JS. GAS uses all native JS methods as it is a JS coding environment. Check the GAS Reference for more on GAS-specific methods that may perform what you need.
If what you need is to check conditions and/or iterate through rows, try something like this:
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getRange(startRow, startColumn, numRows, numColumns);
var values = range.getValues(); //This is a 2D array; iterate appropriately
  for (i = 0; i < values.length; i++) {
    if (values[i] == conditionToCheck) {
      //perform code..OR
      //continue; <- This works to skip the row if the condition is met
    } else {
      //perform alternate code if condition is not met
    }
  }
}

As I mentioned, .getValues() creates a 2D array. If you need to iterate through columns and rows, you will need 2 for() loops like so:
for (i = 0; i < values.length; i++) { //iterates through the rows
  for(j = 0; j < values[i].length; j++) { //iterates through the columns in that current row

It is important to mention how GAS handles 2D arrays. values[i][j] denotes how much i rows there are and j columns. You can visualize like so:
values = [[A1, B1, C1],[A2, B2, C2],[A3, B3, C3]]
This is an array of arrays where the outer array is an array of the rows, while the insides are an array of cell values by column in that row.

A: Custom functions in google apps script do not have access to spreadsheet function. You may try using this =IF(COUNTIF(A1:A5,"VALUETOTEST")>0,"RESULT","OTHER RESULT")
If there is a huge formula for result, try creating functions for the result
function result1() {
     return "RESULT";
}

function result2() {
     return "OTHER RESULT";
}

Then use this =IF(COUNTIF(A1:A5,"VALUETOTEST")>0,RESULT1(),RESULT2())
Try this - copy the below function in apps script, and use this as Formula =myFunction("G182:G186","H182:H186") remeber to ensclose the range with ' " '  because you will be passing the range as string, and note both the ranges must be of equal length.
function myFunction(aRange, bRange) {

    var cond_1 = "ERROR";
    var cond_2 = "62";
    var cond_3 = "ALL";
    var cond_4 = "RETEST";
    var cond_5 = "TODOS";
    var cond_6 = "UNIMPLEMENTED";

    var sheet = SpreadsheetApp.getActiveSpreadsheet();
    var aRange = sheet.getRange(aRange);
    var aValues = aRange.getValues();
    var bRange = sheet.getRange(bRange);
    var bValues = bRange.getValues();
    var count = 0;
    var tmplength = 0;

    if (aValues.length != bValues.length) {
        return "Range length does not Match";
    }

    for (i = 0; i < aValues.length; i++) {

        if (aValues[i] == cond_1 && bValues[i] == cond_2) {
            count += 1;
        }
        if (aValues[i] == cond_1 && bValues[i] == cond_3) {
            count += 1;
        }

        if (count > 0) {
            return "ERROR";
        } else {
            count = 0;

            if (aValues[i] == cond_4 && bValues[i] == cond_2) {
                count += 1;
            }
            if (aValues[i] == cond_4 && bValues[i] == cond_5) {
                count += 1;
            }

            if (count > 0) {
                return "RETEST";
            } else {
                count = 0;

                if (aValues[i] == cond_6) {
                    count += 1;
                }
                if (count > 0) {
                    return "UNIMPLEMENTED";
                } else {
                    return "SOLVED";
                }
            }
        }
    }
}

A: This is how I solved my problem. I thank to people who helped me to reach this result!
// Like COUNTIFS
var countConditionals = function(cells, condition1, condition2) {

  var count = 0;

  for (i = 0; i < cells.length; i++) {

    if (cells[i][0] == condition1 && cells[i][1] == condition2) {
      count++;
    }

  }

  return count;
}

// Like COUNTIF
var countConditional = function(cells, condition) {

    var count = 0;

    for (i = 0; i < cells.length; i++) {

        if (cells[i][0] == condition) {
          count++;
        }

    }

  return count;
}

//Whole Formula
function verificaStatus(cells, db) {

  const ERROR  = "ERROR";
  const ALL    = "ALL";
  const RETEST = "RETEST";
  const NOTYET = "UNIMPLEMENTADED";
  const SOLVED = "SOLVED";

  var countErrors    = countConditionals(cells, ERROR, db);
  var countErrorsAll = countConditionals(cells, ERROR, ALL);
  var sumErrors      = countErrors + countErrorsAll;

  if (sumErrors > 0) {
    return ERROR;
  } else {

    var retest    = countConditionals(cells, RETEST, db);
    var retestAll = countConditionals(cells, RETEST, db);
    var sumRetest = retest + retestAll;

    if (sumRetest > 0) {
      return RETEST;
    } else {

      var countNonCreated = countConditional(cells, NOTYET);

      if (countNonCreated > 0) {
        return NOTYET;
      }

    }

  }

  return SOLVED;

}


text:
Q: How to protect the identity of committers, when a git repository has several remotes? Our company has a project that we want to release as open source. The repository is hosted internally, and it contains a history that includes the names and emails of our team.
The open source project would be hosted on an external repository, Github. For illustration purposes, let us assume that the team members are Alice, Bob and Charlie, and the company name is ACME.
Is it possible to leverage git to to accomplish the following:

*

*keep committing as Alice et al, with full transparency in our internal repo

*when publishing code to the public repo, the commits should be squashed into one, as if they were made by a user called ACME (rather than Alice et al)

*one of the team members,Bob, will act as a bridge between the internal and external repos. His responsibility is to work internally as Bob, and occasionally push the accumulated team-commits to the remote repo, as ACME.

The main idea is to withhold the identity of our colleagues, to protect their privacy. The external repository is there to allow others to contribute to the project, without letting them into our infrastructure.
The world should see that all the work done by the company was committed by ACME, and be unable to look at the history prior to the day the code was released as open source.
How can this be accomplished, or what are the alternatives we could consider?

A: The identity of a commit (or, for that matter, any object inside Git) is a cryptographic checksum of its contents.  The contents of a commit include the author's and commiter's name and email addresses.  If you make another commit that's otherwise exactly the same as a commit that has an un-obscured name and/or email address, but has the name and/or email address obscured, that other commit is a different commit.
The result is that you have two entirely different, and immiscible, repositories.  This is a maintenance nightmare.  It can be done, but it is definitely not worth doing.


text:
Q: No enum constant com.telefonica.iot.cygnus.sinks.OrionSink.DataModel.BYSERVICEPATH I have created my agent_01.conf to use postgresql sink, below you can find the configuration. But I'm getting the following error
16/02/09 16:39:27 ERROR node.AbstractConfigurationProvider: Sink postgresql-sink has been removed due to an error during configuration
cygnus_1 | java.lang.IllegalArgumentException: No enum constant com.telefonica.iot.cygnus.sinks.OrionSink.DataModel.BYSERVICEPATH
cygnus_1 |  at java.lang.Enum.valueOf(Enum.java:236)
cygnus_1 |  at com.telefonica.iot.cygnus.sinks.OrionSink$DataModel.valueOf(OrionSink.java:77)

The configuration file is the following
cygnusagent.sources = http-source
cygnusagent.sinks = postgresql-sink
cygnusagent.channels = postgresql-channel
cygnusagent.sources.http-source.channels = postgresql-channel
cygnusagent.sinks.postgresql-sink.channel = postgresql-channel
# sink class, must not be changed
cygnusagent.sinks.postgresql-sink.type = com.telefonica.iot.cygnus.sinks.OrionPostgreSQLSink
# true if the grouping feature is enabled for this sink, false otherwise
cygnusagent.sinks.postgresql-sink.enable_grouping = false
# the FQDN/IP address where the PostgreSQL server runs
cygnusagent.sinks.postgresql-sink.postgresql_host = myIPaddress
# the port where the PostgreSQL server listens for incomming connections
cygnusagent.sinks.postgresql-sink.postgresql_port = 5432
# the name of the postgresql database
cygnusagent.sinks.postgresql-sink.postgresql_database = database
# a valid user in the PostgreSQL server
cygnusagent.sinks.postgresql-sink.postgresql_username = username
# password for the user above
cygnusagent.sinks.postgresql-sink.postgresql_password = password
# how the attributes are stored, either per row either per column (row, column)
cygnusagent.sinks.postgresql-sink.attr_persistence = row
# select the table type
#cygnusagent.sinks.postgresql-sink.data_model = by-service-path
cygnusagent.sinks.postgresql-sink.data_model = by-service-path
# number of notifications to be included within a processing batch
cygnusagent.sinks.postgresql-sink.batch_size = 100
# timeout for batch accumulation
cygnusagent.sinks.postgresql-sink.batch_timeout = 30

I have also tried with by-destination and using column, but without success. Is there anything wrong with the configuration?

A: According to Fiware team,
data_model can take the following values:
dm-by-service
dm-by-service-path
dm-by-entity
dm-by-attribute

In the particular case of OrionPostgreSQLSink, the valid subset is dm-by-service-path and dm-by-entity


text:
Q: Install Mercurial and TortoiseHG on CentOS 6.5 How to install Mercurial and TortoiseHG on CentOS 6.5?
This is not trivial, as there is no official RPM for this.
See procedure as a bash script below.
I hope this helps

A: This procedure is a joining of instructions from several locations.
Create a script with the content below and run it as root.
#!/bin/bash
# Installation of mercurial and TortoiseHG

APPS_BASE=/opt
HG_BIN=$APPS_BASE/bin
HG_REPOS=$APPS_BASE/repos

checkResult()
{
    if [ $1 -ne 0 ]
    then
        echo;echo ERROR: $2 failed;echo
        exit 1
    else
        echo;echo Action $2 OK;echo
    fi
}

######### Start here #########

echo;echo Adding epel-release repository
yum -y install http://ftp.uninett.no/linux/epel/6/i386/epel-release-6-8.noarch.rpm
checkResult $? "yum install epel-release"

# Get more prereq packages
echo;echo Install some more packages needed
yum -y install PyQt4-devel python-devel python-iniparse gcc gettext
checkResult $? "yum install PyQt4-devel python-devel python-iniparse gcc gettext"

yum --enablerepo=epel -y install qscintilla-python python-keyring python-sphinx Django
checkResult $? "yum install qscintilla-python python-keyring python-sphinx Django"

# Install Mercurial from source to bootstrap
echo;echo Get and install Mercurial from source
mkdir $HG_BIN $HG_REPOS

cd $HG_REPOS
wget https://www.mercurial-scm.org/release/mercurial-2.4.2.tar.gz
checkResult $? "wget for mercurial"

tar xzvf mercurial-2.4.2.tar.gz
cd mercurial-2.4.2/
make local
checkResult $? "make local for mercurial"

# Get a Mercurial clone, to stay up to date
echo;echo Get and install Mercurial stable
./hg clone https://www.mercurial-scm.org/repo/hg#stable ../hg
checkResult $? "hg clone https://www.mercurial-scm.org/repo/hg#stable"

cd ../hg
make local
checkResult $? "make local for mercurial stable"

echo;echo Create link for hg
cd $HG_BIN
ln -s $HG_REPOS/hg/hg .

# now get a TortoiseHg clone
echo;echo Get the TortoiseHG
cd $HG_REPOS
$HG_BIN/hg clone https://bitbucket.org/tortoisehg/thg thg
checkResult $? "hg clone https://bitbucket.org/tortoisehg/thg"

echo;echo Create links for thg
cd thg
ln -s ../hg/mercurial/
ln -s ../hg/hgext/
cd $HG_BIN
ln -s $HG_REPOS/thg/thg .

echo;echo Install kdiff3
yum -y install kdiff3
checkResult $? "yum install kdiff3"

# Cleanup
echo;echo Cleanup
rm -rf $HG_REPOS/mercurial-2.4.2/ $HG_REPOS/mercurial-2.4.2.tar.gz

echo;echo Add $HG_BIN to path
echo "export PATH=$HG_BIN:$PATH" >> /etc/profile

Once this is done, you will have two links
/opt/bin/hg - mercurial
/opt/bin/thg - tortoiseHg
Of course you can easily move things around as you see fit.
EDIT: If anyone has an idea on how to get the nautilus extensions working, please add here!
EDIT 2: (Contributed by @Will-I-am-davidon). Needed to install some more packages to get the thg working: yum install PyQt qscintilla qscintilla-python

A: Didnt work for me sorry !!! After having been spent 2 Hours finding the issue for "incorrect data format" I just removed checkSum() and everywhere below wrote ECHO
it worked for me 100%
THANKs =)

A: In my case i wanna update my production server with a project of my own hosted in BitBucket.org, so you try as i did with Installing on CentOS 6.3

A: As outlined in Mercurial Download, create /etc/yum.repos.d/mercurial.selenic.com.repo and paste in the following:
[mercurial.selenic.com]
name=mercurial.selenic.com
baseurl=https://www.mercurial-scm.org/release/centos$releasever
enabled=1
# Temporary until we get a serious signing scheme in place,
# check https://www.mercurial-scm.org/wiki/Download again
gpgcheck=0

Then you can issue the command sudo yum install hg.


text:
Q: Save values from FOR loop for further analysis How do I save the values from the For Loop from the following code? When I pint the variable "lm5", it has a total of two values. When I tried to save it to a new variable, it only shows the last value.
Ideally, I would like to save the lm5,lm10,lm20 for another round of IF statement analysis. Could you please advise how to proceed? Thanks in advance!
even<-c(2,4)

for( i in even){
  m5<-rollmean(test[,i],5,fill=NA)
  m10<-rollmean(test[,i],10,fill=NA)
  m20<-rollmean(test[,i],20,fill=NA)
  lm5<-tail(m5[!is.na(m5)],1)
  print(lm5)
}

A: There are a few data structures at your disposal to achieve this.
Vectors
even<-c(2,4)
lm5_vector = c()
for( i in even){
  m5<-rollmean(test[,i],5,fill=NA)
  lm5_vector<-c(lm5_vector,tail(m5[!is.na(m5)],1))
}
print(lm5)

This will store elements of each iteration into a vector. Finally printing both elements of the vector. We are storing the result in what is called an atomic vector. The disadvantage of this is that you would need to initialize a new vector for lm10, lm20 and so on.
The alternative is the following.
Lists + Vectors
The list data structure allows us to store all the values you wish to store under one convenient name. Lists allow us to nest other data structures. Hence we nest an atomic vector under a list.
even<-c(2,4)
result_list = list(lm5 = c(),lm10 = c(),lm20 = c())
for( i in even){
  m5<-rollmean(test[,i],5,fill=NA)
  result_list$lm5<-c(result_list$lm5,tail(m5[!is.na(m5)],1))
}
print(result_list)


text:
Q: Format a text on cell in two color in Coldfusion Using Coldfusion 10, I need to format a cell contents in two color(Black and Blue). Let a cell on spreadsheet contains a string "Text1: Text2". where color of "Text1" should be black and "Text2" should be blue.
I have tried below code, but it produces all blue text.
SpreadsheetAddRow(spreadsheetData,"Text1: Text2",1,1);
format1=StructNew();
format1.color="black";
SpreadsheetFormatRow(spreadsheetData,format1,1);
format1.color="blue";
SpreadsheetFormatRow(spreadsheetData,format1,1);

How I can apply two color to format single cell ?

A: It is not supported with the built in functions. However, you can tap into the underlying POI library and use a RichTextString to accomplish this.
Assuming you have already created the worksheet and an empty cell:
spreadsheetData = SpreadSheetNew("Sheet1", true);
SpreadsheetAddRow(spreadsheetData,"",1,1);

Grab reference to the underlying Workbook and create fonts with the appropriate colors:
wb = spreadsheetData.getWorkbook();
Colors = createObject("java", "org.apache.poi.ss.usermodel.IndexedColors");
greenFont = wb.createFont();
greenFont.setColor(Colors.GREEN.index);
blueFont = wb.createFont();
blueFont.setColor(Colors.BLUE.index);

Then create a RichTextString object and append each part of the text with the desired color:
// Using GREEN and BLUE for demo purposes
richString = createObject("java", "org.apache.poi.xssf.usermodel.XSSFRichTextString").init();
richString.append("Text1: ", greenFont);
richString.append("Text2", blueFont);

Finally, apply the RichTextString to the empty cell, ie A1 you created earlier. Note, unlike in CF, the indexes are 0-based.
cell = wb.getSheet("Sheet1").getRow( 0 ).getCell( 0 );
cell.setCellValue(richString);


text:
Q: Choosing right Maven repository I would like to use ToStringBuilder from Apache Commons Lang in my IntelliJ IDEA java project. I place ID org.apache.commons in Download Library from Maven menu  and found many links:

I suppose this means that many maven repositories has this library. How to know which one is correct one? What is the logic of finding right library source?

A: Just to add to your sentence

I suppose this means that many maven repositories has this library

I know the following popular maven repos.
https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
https://search.maven.org/search?q=commons-lang3
As far as common-lang3 library is concerned, all the repos have the correct library.
While searching in intellij, it also displays other libaries which use commons-lang3.
You have to select group id, artifact id and version to set the dependency.


text:
Q: $u=(3/2)nRT$ when $T=0$ Why does a body with $0\ K$ temperate does the internal energy NOT become $0\ J$? My lecturer said it had to do with some quantum mechanics, but I never really got any answers from him. I really want to understand this to better understand thermal physics.

A: If the internal energy becomes zero, that means the particles constituting the body come to complete rest. This implies that the particles constituting the body have a definite position and momentum. According to Heisenberg's uncertainty principle
$\Delta x \Delta p \geq \frac{\hbar}{4\pi}$
So if a particle is at rest i.e has a definite position and zero momentum, this inequality isn't satisfied and hence it is not possible to have zero internal energy at absolute zero.


text:
Q: Pause video and buffering for VLC stream (using libvlc) and restart live view without initializing player again I am using this libvlc wrapper (https://github.com/ZeBobo5/Vlc.DotNet) to stream live video from IP camera. And there is a problem I need to solve with this:
I use initialized VlcControl in two WPF windows. On the main window there is live video-stream and when the snapshot is taken, it opens the image editor with the taken snapshot. In this second window it is possible to switch to the camera live view and the problem is here:
if video is paused on the main window and started in image editor, it starts exactly where it was stopped, not the live view. Moreover, it does not stop buffering the video that leads to unnecessary network load.
I have already tried to stop player at main window and to re-initialize VlcControl in the image editor, but it takes about 10 seconds to start streaming, which is not the solution.
Also it is possible to continue stream without pausing it, but it creates unnecessary network load of 4k frames, which is not the option.
I have also asked the question in the GitHub, but none of the suggestions worked for me: https://github.com/ZeBobo5/Vlc.DotNet/issues/576
Here is the code that is used to remove VlcControl from one UI and add to another.
public sealed class LiveVideoVlcPlayer : ILiveVideoPlayer
{
    private readonly VlcControl _videoPlayer;

    /// <param name="vlcLibraryDirectory"></param>
    /// <param name="options">VLC options can be given here. Please refer to the VLC command line documentation.</param>
    /// <inheritdoc />
    public LiveVideoVlcPlayer(IDirectoryInfo vlcLibraryDirectory, string[] options)
    {
        _videoPlayer = new VlcControl();
        _videoPlayer.SourceProvider.CreatePlayer(vlcLibraryDirectory.DirectoryInfo, options);
        _videoPlayer.Background = Brushes.White;
    }

    /// <inheritdoc />
    public void Dispose()
    {
        _videoPlayer?.Dispose();
    }

    public void AddToUiChildren(UIElementCollection children)
    {
        if (children.Contains(_videoPlayer))
             return;
        children.Add(_videoPlayer);
    }

    public void Pause()
    {
        _videoPlayer.SourceProvider.MediaPlayer.Pause();
    }

    public void Play(Uri videoSource)
    {
        // https://wiki.videolan.org/Documentation:Streaming_HowTo/Command_Line_Examples/
            _videoPlayer.SourceProvider.MediaPlayer.SetMedia(videoSource);
            _videoPlayer.SourceProvider.MediaPlayer.Play();
    }

    /// <summary>
    ///     Continue paused video.
    /// </summary>
    public void Play()
    {
        _videoPlayer.SourceProvider.MediaPlayer.Play();
    }

    /// <summary>
    ///     Removing the player from a visual thee will pause the video
    /// </summary>
    /// <param name="children"></param>
    public void RemoveFromUiChildren(UIElementCollection children)
    {
        Pause();
        if (!children.Contains(_videoPlayer))
            return;
        children.Remove(_videoPlayer);
    }
}

And here is the code that initializes new VlcPlayer. This code is used in the main window and video player is passed to the image editor as argument.
_vlcLibraryDirectory = new DirectoryInfoWrap(_pathWrap.Combine(currentDirectory, "libvlc", IntPtr.Size == 4 ? "win-x86" : "win-x64"));
var options = new string[]
{
    "--network-caching=50"
    // VLC options can be given here. Please refer to the VLC command line documentation.
};
try
{
    LogManager.Debug("Initialise VLC player.");
    _liveVideoVlcPlayer = new LiveVideoVlcPlayer(_vlcLibraryDirectory, options);
}
catch (Exception exception)
{
    LogManager.Error("Failed to initialise VLC player. Is libvlc package installed?", exception);
}

What I want is to find the way to stop the streaming and buffering(to reduce network load) and restart its as a live stream with the least possible time for loading the live view.


text:
Q: how to align logo with nav bar how to align logo with nav bar? i just need to align the logo in my navigation bar because i can't use margin and padding it only applies in one page. Please help me here's my code

    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
      Toggle navigation

    </button>

    <?php
      if (file_exists ('images/logo.jpg'))
      {
         echo'

    <?php echo " ".$x; ?>

Thanks in advance :)

A: Is this what you're searching for?

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>

If yes, here's the code with your php-code inside.

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>

        <?php
            if (file_exists ('images/logo.jpg')) {
                echo '';
            }
                else
            {
                echo '';
            }
        ?>

Hope this helps.


text:
Q: Como puedo obtener los dias restantes que le quedan a una fecha de firebase/firestore? ¡Hola!
Estoy tratando de obtener los días restantes de una fecha de mi base de datos de firestore.

Esta es la imagen de la fecha de mi base de datos, lo que busco es obtener la cantidad de días restantes entre la fecha de hoy y la fecha de mi base de datos.
Lo estoy haciendo en Next.js
he intentado restando la fecha de hoy con la de mi base de datos pero no funciona :(
si alguien sabe como hacerlo que me ayudeeee
Muchas gracias.


text:
Q: Pandas not plotting code. I'm new to coding and am trying to understand a lecture on Quantopian by going through the code but when I run the code in PyCharm, there is no output. Can someone tell me what's going on and advise me on how to resolve this?
Below is my a piece of code (2.7.13):
import numpy as np
import pandas as pd

import statsmodels
import statsmodels.api as sm
from statsmodels.tsa.stattools import coint
# just set the seed for the random number generator
np.random.seed(107)

import matplotlib.pyplot as plt

X_returns = np.random.normal(0, 1, 100) # Generate the daily returns
# sum them and shift all the prices up into a reasonable range
X = pd.Series(np.cumsum(X_returns), name='X') + 50
X.plot();

The sole output, when I run this, is: "Process finished with exit code 0"

A: Just add plt.show() at the end:
import numpy as np
import pandas as pd

import statsmodels
import statsmodels.api as sm
from statsmodels.tsa.stattools import coint
# just set the seed for the random number generator
np.random.seed(107)

import matplotlib.pyplot as plt

X_returns = np.random.normal(0, 1, 100) # Generate the daily returns
# sum them and shift all the prices up into a reasonable range
X = pd.Series(np.cumsum(X_returns), name='X') + 50
X.plot()
plt.show()


text:
Q: How to customize the Plaid widget element Is there any way to customize the plaid widget element from application in Angular ?
Here I am trying to change the color of "Continue" button. Can anyone suggest ?
Plaid Widget

A: You can customize parts of the widget from the Plaid dashboard -- however the color of the Continue button can't be customized.


text:
Q: Unable to boot kernel and rootfile system in Qemu I am using ts-4900 freescale board. I am not able to boot the kernel and rootfile system (initrd) in Qemu. I did the following kernel configuration steps.

*

*export the cross compiler parth

*export LOADADDR=0x10008000

*make esse_defconfig

*make menuconfig ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf-

*make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- uImage

The image is in /arch/arm/boot/uImage, and and I have working rootfile system (initrd).
Now i am trying to boot in Qemu using bellow step.
qemu-system-arm -M vexpress-a9 -cpu cortex-a9 -kernel uImage -initrd /home/mahesh/mahesh/ts_4900/initrd.

then the error.


text:
Q: Voltage drop through a resistor compared to a Zener diode A variant of this question has been asked a few times, but not received a response. Usually, we get an analogy with water pressure, or gravity, or a version of Ohm's law; not the actual cause-effect relationship.
Recently I have been reading about Zener diodes and how when reverse biased they drop a consistent amount of voltage. So for example, a simple circuit with only a battery and a diode would drop some fixed amount of voltage through the diode (to reverse bias it) and the rest of the electric potential would be dropped somewhere else.
In contrast, a resistor will drop as much voltage as required through it (as long as it is within its thermal limits).
I still do not understand why a resistor does not drop a fixed amount of voltage. What is the fundamental principle that causes this behaviour? Why doesn't this principle also affect diodes?
Thank you for your help.
Edit - addendum for clarity:
My main confusion is why a resistor does not drop a fixed amount of voltage but a variable one depending on battery voltage. If you use the analogy of gravity and friction, would a small amount of friction drop any amount of potential energy? Would it not drop a fixed amount depending on how significant the friction is? Since voltage is a per charge quantity, it would follow that an electron could drop as much or as little voltage as required at a resistor.. how does it do that regardless of resistor value?
Ohm's law offers an explanation of what happens, but not why it happens if that makes sense.

A: The voltage drop across a resistor is given by Ohm's law:
$$V = IR$$
Where:

*

*\$V\$ is voltage in volts

*\$I\$ is current in amperes

*\$R\$ is resistance in ohms

simulate this circuit – Schematic created using CircuitLab
Take the above circuit as an example.  The total resistance \$R\$ is the sum of \$R1\$ and \$R2\$.  That gives a current through both resistors of 5 amperes.  That five amperes flows through both resistors.  The voltage across \$R2\$ is therefore \$V = 10 \times 5 = 50 volts\$.

simulate this circuit
In comparison, the current through this second circuit is 1 ampere.  By Ohm's law, there's now only 10 volts across \$R2\$.  The voltage across \$R2\$ always varies depending on the total resistance and the total voltage.
Now replace \$R2\$ with a Zener diode:

simulate this circuit
Zener diodes do not follow Ohm's law.  It is a diode, and has rules all its own.
When current flows through a reverse biased Zener diode, the voltage across the diode is set by the construction and the materials of the diode.
The voltage at \$V_{out}\$ for the Zener diode will stay pretty much the same, regardless of the value of \$R1\$ (over a fairly large range.)  If I change \$R1\$ to 1000 or 10000 ohms, \$V_{out}\$ will stay in the vicinity of 5.1V.
The voltage drop across the diode is fixed by the construction and materials.  As long as the reverse voltage is above the Zener voltage there will be a constanct voltage across the diode.  The voltage drop is (largely) independent of the current.
The voltage drop across a resistor is fixed by the resistance and the current through the resistor.  Anything that changes the current changes the voltage drop.  That's pretty much what Ohm's law tells you:  Voltage is dependent on current and resistance.

I see in comments that you "understand how Ohm's law works" and that you want to know "why the resistor behaves this way," and that you think that an "electron will seek to drop all this potential energy."
Ohm's law is descriptive - it puts mathematics to an observed behaviour.
If you want the physics behind how a resistor does what it does, then you're going to have to wait for someone else to answer.  I don't have a clear model in my mind of how different types of resistors work.  I know Ohm's law, and that I've used it quite a bit to get usable results.  I don't know the actual physics of what happens to individual electrons, though.

A: Because a resistor resists the current and the voltage (V_Out in the schematics posted by JRE) is the result of this resistance effect called Voltage Drop in combination of the other resistor R2.
R1 is giving a limited amount of current to V_Out while R2 is removing a limited amount of current from V_Out. The word limited is important because the limit is defined by the resistor value.
The higher the impedance of the resistor, the less current will cross it and the more voltage will drop.
The higher the voltage at the resistor input, the higher the current will flow through and the less the voltage will drop. Hence, the higher the voltage at the input of the resistor, the higher voltage at its output.
Note that the output voltage is always the result of the current limiting resistor (R1) and the load resistance between the limiting resistor and ground (here R2 but not forcibly a resistor.)
If the output of the current limiting resistor (R1) is left floating, the output voltage will be the same as the input voltage.
And if it's connected directly to ground it will be zero.
A zener diode will always limit the voltage to a fixed value. However a zener always needs some current limiting device, such as a resistor, else the current flowing through the zener will be infinite and will burn it out.
Current have to flow through the zener in order to maintain the desired voltage. This amount of current is defined by the current limiting resistor (R1).

A: Draw the I_V curve for resistor and diode in series.
Tie diode to 0 volts.
Tie resistor to +10 volts, and tilted toward zero
(I would draw this --- as I have in the past here on stackX --- but stackX
no longer lets my browser use the drawing/schem tool)
The interception of the diode and resistor line is the operating point for those 2-elements in series cicuit.
Now draw a steeper resistor curve, again starting at +10 vols. This is the model for a lower value resistor (allows more current)
Notice the intercept point moves up on the diode curve --- higher current.
Add this visualization method to your cognitive gifts.


text:
Q: How can I create URLs that only include the query string? I want to use URL rewriting in apache web server to have these types of URLs:
www.mysite.com/user.php?id=user1
www.mysite.com/user.php?id=user2
www.mysite.com/user.php?id=me
www.mysite.com/user.php?id=you
www.mysite.com/user.php?id=every_thing

be changed to
www.mysite.com/user1
www.mysite.com/every_thing

and
www.mysite.com/user1/

I have tried this in my .htaccess.
RewriteEngine On
RewriteRule (.*) user.php?id=$1

It didn't work. What is the problem?
And I should say I have other directories like:
www.mysite.com/images/
www.mysite.com/videos/

So how can I also make it so it doesn't conflict?

A: You will need in your root .htaccess:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST} \s(.+?)/+[?\s]
RewriteRule ^(.+?)/$ /$1 [R=301,L]

RewriteCond %{THE_REQUEST} \s/+user\.php\?id=(\S+) [NC]
RewriteRule ^ /%1? [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?)/?$ /user.php?id=$1 [L,QSA]

A: Adapted from wordpress's .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(user\d) /user.php?id=$1 [L]
</IfModule>


text:
Q: Change of variables example in an ODE I do not understand how this was obtained

Why the $(y')^2$ becomes $y'$ and the $y'$ becomes $(y')^2$ and why $y^2$ becomes $x^2 (y')^3$ in the new ode?
How does $\frac{d y(x)}{d x}$ change under this change of variables?

A: You are changing the direction of dependence. Without changing variable names this means that you are deriving a differential equation for the inverse function $x(y)$. Now
$$
x=x(y(x))\\
1 = x'(y(x))y'(x)\\
0=x''(y(x))y'(x)^2+x'(y(x))y''(x)
$$
and with the last two together
$$
0=x''(y)+x'(y)^3y''(x)
$$
So replacing the $y$ derivatives in the original equation gives
$$
-\frac{x''(y)}{x'(y)^3}-\frac{1}{yx'(y)^2 }+\sin(x(y))\frac{y}{x'(y)}+\cos(x(y))y^2=0
$$
Now multiply with $-x'(y)^3$ to get
$$
x''(y)+\frac{x'(y)}{y}-\sin(x(y))yx'(y)^2-\cos(x(y))x'(y)^3=0
$$
Finally to get the claimed equation you need to exchange the variable names $x,y$.

A: IMO Leibniz's notation is a bit easier to follow.
$$\frac{d^2y}{dx^2} - \frac1y \left(\frac{dy}{dx}\right)^2 + \sin(x) y \frac{dy}{dx} + \cos(x) y^2 = 0$$
By the chain rule,
$$\frac{dy}{dx} = \frac1{\frac{dx}{dy}} \implies \frac{d^2y}{dx^2} = -\frac1{\left(\frac{dx}{dy}\right)^2} \frac{d\frac{dx}{dy}}{dx} = -\frac1{\left(\frac{dx}{dy}\right)^2} \frac{d^2x}{dy^2} \frac{dy}{dx} = -\frac1{\left(\frac{dx}{dy}\right)^3} \frac{d^2x}{dy^2}$$
The ODE transforms to
$$-\frac1{\left(\frac{dx}{dy}\right)^3} \frac{d^2x}{dy^2} - \frac1y \left(\frac1{\frac{dx}{dy}}\right)^2 + \sin(x) y \left(\frac1{\frac{dx}{dy}}\right) + \cos(x) y^2 = 0,$$
simplifies to
$$- \frac{d^2x}{dy^2} - \frac1y \frac{dx}{dy} + \sin(x) y \left(\frac{dx}{dy}\right)^2 + \cos(x) y^2 \left(\frac{dx}{dy}\right)^3 = 0,$$
and with the last variable change, we end up with
$$-\frac{d^2y}{dx^2} - \frac1x \frac{dy}{dx} + x \sin(y) \left(\frac{dy}{dx}\right)^2 + x^2 \cos(y) \left(\frac{dy}{dx}\right)^3 = 0$$
Multiply by $-1$ and swap out $\frac{dy}{dx}$ for $y'$ to get the exact same ODE.


text:
Q: ExtJs customization In a customized ExtJs file, I found the following code. Actually what is doing in the following code.
This code is written in an xtype.js file and which is included in the jsp page.
Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath('Ext.ux', 'js/ext-ux');

Ext.require([
    'Ext.form.field.ComboBox'
]);

Ext.define('Ext.ux.UDComboBox', {
    extend: 'Ext.form.field.ComboBox',
    alias: 'widget.udComboBox',
    directArgs : false,
    skipValue : false,
    firstOptionDefault : false,
    forceSelection : true,
    typeAhead : true,
    queryMode : 'local',
    triggerAction : 'all',
    selectOnFocus : true,
    allowBlank : false,
    emptyText : '-Select One-',
    valueField : '',
    lastQuery : '', // This is used with store.filter function.
    returnAsObject : true,
    fieldStyle: 'background-image: none;',
    msgTarget:'side',
    hideTrigger:false,// if true hide the drop down icon
    skipFirstOption : false
});

And in our file, for creating combobox, we use xtype: 'udComboBox'.

A: Ext.Loader.setPath('<TopLevel.path.NameSpace>', 'js/ext-ux'); }
// Namespace by convention should be in lower case
Ext.define('<TopLevel.path.NameSpace>.<ComponentName>', {
     extend: 'Ext.form.field.ComboBox',
     // alias by convention should be in lower case
     alias: 'widget.<componentname>'
});
}

*

*Top-level namespaces and constructors  names should be UpperCamelCase

*Alias xtype should be in lower case
So a example of your configuration can be: your company
// --Filename: app/js/components/UdComboBox.js <-Filename as Name
Ext.define('MyCompany.libs.UdComboBox', {
    extend: 'Ext.form.field.ComboBox',
    alias: 'widget.udcombobox',
    ....
});

// --Filename: app/app.js
Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath('MyCompany.libs', 'js/components');

Ext.require([
        //This is only because we are instantiate by xtype, if you use Ext.create this is not need it.
        'MyCompany.libs.UdComboBox'
    ]);

Ext.onReady(function() {
        Ext.create("Ext.container.Viewport", {
            layout: 'fit',
             items : [{
                 xtype : "udcombobox"
             }]
         });
});

// --Filename: app/app2.js
Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath('MyCompany.libs', 'js/components');

Ext.onReady(function() {
        Ext.create("Ext.container.Viewport", {
            layout: 'fit',
             items : [{
                 xtype : "panel"
             },
             new Ext.Create('MyCompany.libs.UdComboBox',{
                ..config..
             })
            ]
         });
});


text:
Q: Open SecondViewController on startup insted FirstViewController I have TabBarController with two navigations controllers as on an attached image.
If my app will be run first time should be opened Second View Controller.
For navigation controllers I use below code:
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];

    cysViewController *cvc =[sb instantiateViewControllerWithIdentifier:@"cysViewController"];
    questionViewController *qvc = [sb instantiateViewControllerWithIdentifier:@"questionViewController"];
    UINavigationController *nav = (UINavigationController *) self.window.rootViewController;
    nav.viewControllers = [NSArray arrayWithObjects:cvc,qvc, nil];
    [(UINavigationController *)self.window.rootViewController popToViewController:qvc animated:NO];

but for tabBarController I have no idea how to do that.

A: You could change the selected index by changing the value of selectedIndex.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:    (NSDictionary *)launchOptions {
   UITabBarController *tabController = (UITabBarController *)self.window.rootViewController;
   tabBarController.selectedIndex = 1;
}


text:
Q: Relation of subsets of a quotient sets by the same relation I have a set $\mathbb{A}$ and an equivalence relation $\sim$ defined on that set. Now I take a subsets $A \subset \mathbb{A}$. Can I just say $A/\sim \subset \mathbb{A}/\sim$?
As I understand it I can't, since there can be $\mathbb{A} := \{x,y\}$ with $x \sim y$ while $A := \{x\}$ ($x,y \in \mathbb{A}$, $x \in A$, $y \notin A$).
From this follows $\{\{x,y\}\} = \mathbb{A}/\sim$ but $\{\{x\}\} = A/\sim$ and we know $\{\{x\}\} \not\subset \{\{x,y\}\}$.
This especially comes into play, when I want to do set operations on subsets of $\mathbb{A}$ and I want to have the intersection of two subsets in regard to the equivalence classes.
Disclaimer: I hope the title actually describes what I'm asking. I'm happy about any hint for clarification.

A: Strictly speaking, the equivalence relation on $A$ is not $\sim$, but is the restriction of $\sim$ to $A$, i.e. the relation $\sim_A$ defined for $x,y \in A$ by $x \sim_A y$ if and only if $x \sim y$. (But this is just me being pedantic.)
As you identify, it's certainly not the case that $A/{\sim_A} \subseteq \mathbb{A}/{\sim}$. However, it is the case that, for all $U \in A/{\sim_A}$, you have $U \subseteq \mathbb{U}$ for some $\mathbb{U} \in \mathbb{A}/{\sim}$. Maybe this is the relationship between $A/{\sim_A}$ and $\mathbb{A}/{\sim}$ that you were trying to identify?
To the best of my knowledge, there isn't a succinct symbol for this; it's an example of a subquotient.


text:
Q: Xdotool using "DISPLAY=:0" not works in Crontab I need to run shell script contains Xdotool codes in /home/z/Desktop/tempo/run.sh. I've tried many ways of DISPLAY=:0 but always not works.
I've tried each of below codes, and not works:
* * * * * export DISPLAY=:0 cd /home/z/Desktop/tempo; ./run.sh
* * * * * export DISPLAY=:0; cd /home/z/Desktop/tempo; ./run.sh
* * * * * export DISPLAY=:0 && cd /home/z/Desktop/tempo; ./run.sh
* * * * * DISPLAY=:0 cd /home/z/Desktop/tempo; ./run.sh
* * * * * DISPLAY=:0; cd /home/z/Desktop/tempo; ./run.sh
* * * * * DISPLAY=:0 && cd /home/z/Desktop/tempo; ./run.sh

Running directly also not works:
* * * * * export DISPLAY=:0 xdotool mousemove 20 20
* * * * * export DISPLAY=:0; xdotool mousemove 20 20
* * * * * export DISPLAY=:0 && xdotool mousemove 20 20
* * * * * DISPLAY=:0 xdotool mousemove 20 20
* * * * * DISPLAY=:0; xdotool mousemove 20 20
* * * * * DISPLAY=:0 && xdotool mousemove 20 20

I always don't see my mouse moving on each line of codes above.
I've also tested Xdotool codes to make invalid website URI request and see the logs. Sadly the logs still blank.

A:  * * * * * DISPLAY=:0 xdotool mousemove 20 20

At least should work as long as it's in the crontab of the same user as the one having the X session on the corresponding display.
If another user is to do the mousemove, you need to grant him access to your display. This can be done by giving him the MIT Magick Cookie for your display and let him install it in his own X auth store (using xauth), or it can be done with:
xhost +si:localuser:the-user

Or it can be done by granting him access to your own X auth store, for instance, by doing:
setfacl -m u:the-user:r ~/.Xauthority

And change the crontab line to:
* * * * * DISPLAY=:0 XAUTHORITY=~me/.Xauthority xdotool...

If that other user is root you don't need the setfacl step, but I would not run xdotool as root, no reason for that. You can run it as your own user.

A: cron jobs don't even have a tty, let alone an X display.
If you want to test a GUI replaying inputs (or generating synthetic load), look for that. Don't try to (ab)use cron.