solution to $\square\chi=f$.

Question: For an open set $U \subseteq \mathbb{R}^4$, if $f:U \to \mathbb{R}$ is a "good" (for example, smooth) function, is there a solution to the following equation?
$$\left( \Delta - \frac{1}{c^2}\frac{\partial^2}{\partial t^2}\right)\chi(x, y, z, t)=f(x, y, z, t)$$
Context
I want to transform Maxwell's equations
$$\operatorname{rot}E(x,t)+\frac{\partial B(x, t)}{\partial t}=0$$
$$\operatorname{div}B(x,t)=0$$
$$\operatorname{rot}H(x,t)-\frac{\partial D(x,t)}{\partial t}=i(x,t)$$
$$\operatorname{div}D(x,t)=\rho(x,t)$$
into the following form with the electrical potential $\phi$ and the vector potential $A$:
$$B(x,t)=\operatorname{rot}A_L(x,t)$$
$$E(x,t)=-\frac{\partial A_L(x,t)}{\partial t} -\operatorname{grad}\phi_L(x,t)$$
$$\square A_L(x,t)=-\mu_0i(x,t)$$
$$\square \phi_L(x,t) = -\frac{1}{\epsilon_0}\rho(x,t)$$
$$\operatorname{div}A_L(x, t)+\frac{1}{c^2}\frac{\partial\phi_L(x,t)}{\partial t}=0$$
In order to do this, we need the existence of a solution to the equation
$$\square\chi = -\left(\operatorname{div}A_0 + \frac{1}{c^2}\frac{\partial \phi_0}{\partial t}\right)$$
where $A_0$ and $\phi_0$ is a special solution to the following equations:
$$B(x,t)=\operatorname{rot}A(x,t)$$
$$E(x,t)=-\frac{\partial A(x,t)}{\partial t} -\operatorname{grad}\phi(x,t)$$
$$\operatorname{grad}\left( \operatorname{div}A(x,t)+\frac{1}{c^2}\frac{\partial \phi(x,t)}{\partial t}\right) + \left( \frac{1}{c^2}\frac{\partial^2}{\partial t^2}-\Delta\right)A(x,t)=\mu_0 i(x,t)$$
$$-\operatorname{div}\left(\frac{\partial A(x,t)}{\partial t}\right) - \Delta \phi(x,t)=\frac{\rho(x,t)}{\epsilon_0}$$
If it exists, $A_L$ and $\phi_L$ are defined as follows:
$$A_L = A_0 + \operatorname{grad}\chi$$
$$\phi_L = \phi_0 - \frac{\partial}{\partial t}\chi$$
Answer: The answer to the question if whether a solution $\chi$ to the the following equation exists
$$
-\frac{1}{c^{2}}\square=\left(\Delta - \frac{1}{c^2}\frac{\partial^2}{\partial t^2}\right)\chi=f\;\text{ in }\;\Bbb R^4\equiv \Bbb R^3\times \Bbb R \label{w}\tag{W}
$$
under mild smoothness requirements on the datum $f$ is yes: I explain below why it is so in a constructive way, by actually constructing an explicit solution in two steps:

Construction of a fundamental solution: what is needed is a slightly modified fundamental solution of the D'Alembert operator, precisely the solution of the following equation:
$$
\square \mathscr{E}(x,t)=-c^2\delta(x,t)\label{da}\tag{DA}
$$
where $\delta(x,t)\equiv \delta(x)\times\delta(t)$ is the usual tensor product of Dirac measures respectively on the spatial and on the time domain. Once  $\mathscr{E}(x,t)$ has been determined, we can find, provided certain compatiility conditions on $f$ are fulfilled (see below), a distributional solution $\chi(x,t)$ to the posed problem by convolution
$$
\chi(x,t)=\mathscr{E}\ast f(x,t)\label{s}\tag{S}
$$
The minimal requirements on $f$ is that the convolution product at the right term of \eqref{s} should exists as a distribution.
The regularity problem: prove that, provided $f$ is a "good" (for example $C^2$ smooth) function, the distribution $\chi$ in \eqref{s} is a "good" function in the same way.

Calculation of the modified fundamental solution for the D'Alembert operator in $\Bbb R^{3+1}$

We construct $\mathscr{E}$ as a distribution of slow growth (i.e. $\mathscr{E}\in \mathscr{S}^\prime$, see for example [1] §8.1-§8.2, pp. 113-116 or [2], §5.1-§5.2, pp. 74-78) by applying to PDE \eqref{da} the Fourier transform $\mathscr{F}_{x\to\xi}$ respect to the spatial variable $x$. By proceeding this way, \eqref{da} is transformed into the following ODE:
$$
\frac{\partial^2 \hat{\mathscr{E}}(\xi,t)}{\partial t^2} + c^2|\xi|^2\hat{\mathscr{E}}(\xi,t)=-c^2\delta(t)\label{1}\tag{1}
$$
Consider its equivalent standard form
$$
\frac{\partial^2 \hat{\mathscr{E}}_p(\xi,t)}{\partial t^2} + c^2|\xi|^2\hat{\mathscr{E}}_p(\xi,t)=\delta(t)\label{1'}\tag{1'}
$$
which has the same solutions, just multiplied by the constant $-c^2$: by solving it (see here, [1] §10.5, p. 147 or [2], §4.9, example 4.9.6 pp. 77-74 and §15.4, example 15.4.4) we get the following distribution
$$
\hat{\mathscr{E}}_p(\xi,t)= H(t)\frac{\sin c|\xi|t}{c|\xi|}\iff\hat{\mathscr{E}}(\xi,t)= -cH(t)\frac{\sin c|\xi|t}{|\xi|}\label{2}\tag{2}
$$
where $H(t)$ is the usual Heaviside function. Then, taking the inverse Fourier transform $\mathscr{F}_{\xi\to x}^{-1}\big(\hat{\mathscr{E}}\big)$ we get the sought for solution of \eqref{da} (see [1] §9.8, p. 135 and §10.7, p. 149)
$$
\mathscr{E}(x,t)=-\frac{H(t)}{4\pi t}\delta_{S_{ct}}(x)=-c\frac{H(t)}{2\pi }\delta\big(c^2t^2-|x|^2\big)\label{3}\tag{3}
$$
where

$S_{ct}=\{x\in\Bbb R^3 | |x|^2=x_1^2+x_2^2+x_3^2=c^2t^2\}$ is the spherical light wave surface,
$\delta_{S_{ct}}(x)$ is the Dirac measure supported on $S_{ct}$, otherwise called single layer measure.

Now, given any distribution $f\in\mathscr{D}(\Bbb R^{3+1})$ for which the convolution with $\mathscr{E}$ exists (for example any distribution of compact support) using \eqref{3} in formula \eqref{s} gives a generalized solution of \eqref{w}.

Construction of a regular solution

Instead of recurring to the standard (and complex) methods of regularity theory we will try a trickier way by looking carefully at the structure of \eqref{3} and on how this distribution acts on the space of infinitely smooth rapidly decreasing functions: precisely, given $\varphi\in\mathscr{S}$ we have that
$$
\begin{split}
\langle\mathscr{E},\varphi\rangle&=-\frac{1}{4\pi}\int\limits_{0}^{+\infty}\langle\delta_{S_{ct}},\varphi\rangle\frac{\mathrm{d}t}{t}\\
&=-\frac{1}{4\pi}\int\limits_{0}^{+\infty}\frac{1}{t}\int\limits_{S_{ct}}\varphi(x,t)\,\mathrm{d}\sigma_x\mathrm{d}t
\end{split}\label{4}\tag{4}
$$
From \eqref{4} we see that $\mathscr{E}$ acts on $\varphi\in\mathscr{S}$ as a spherical mean respect to the spatial $x\in \Bbb R^3$ variable and as a weighted time integral mean with weight function $t\mapsto {1\over t}\in L^1_\mathrm{loc}$  respect to the time variable $t\in\Bbb R_+$.
This implies that \eqref{4} is meaningful also for functions which are not in $\mathscr{S}$ nor are infinitely smooth. Precisely, provided that

$\varphi(\cdot,t)\in L^1_\mathrm{loc}(\Bbb R^3)$ for almost all $t\in\Bbb R_+$, without any growth condition at infinity and
$\varphi(x,\cdot)\in L^1_\mathrm{loc}(\Bbb R)$ with $|\varphi(x,t)|=O(t^{-\varepsilon})$ as $t\to\infty$ a.e. on $\Bbb R^3$ with $0<c\le\varepsilon$.

equation \eqref{4} is meaningful. Then, by putting
$$
\varphi(y,\tau)=f(x-y,t-\tau)
$$
and by using \eqref{4} jointly with the definition of convolution between a distribution and a function, i.e.
$$
\mathscr{E}\ast\varphi (x,t) \triangleq \langle \mathscr{E}, \varphi(x-y,t-\tau)\rangle
$$
we get the sought for solution
$$
\chi(x,t)=\mathscr{E}\ast f(x,t)=-\frac{1}{4\pi}\int\limits_{0}^{+\infty}\frac{1}{\tau}\int\limits_{S_{c\tau}}f(x-y,t-\tau)\,\mathrm{d}\sigma_y\mathrm{d}\tau
\label{S}\tag{WS}
$$
Notes

The hypothesis $n=3$, i.e. the fact that we are working in a $3$D space, is essential for defining the structure of \eqref{3}. The inverse transform of $\hat{\mathscr{E}}$ in \eqref{2} has not the same structure on every $\Bbb R^n$: in monographs on hyperbolic PDEs, this concept is also stated by saying that Huygens's principle does not hold in even spatial dimension.
The regularity of the solution we have obtained is very weak: in particularly we do not know the smoothness of $\chi$ for a given smoothness of $f$. Deeper methods are required for the investigation of this problems.

[1] V. S. Vladimirov (1971)[1967], Equations of mathematical physics, Translated from the Russian original (1967) by Audrey Littlewood. Edited by Alan Jeffrey, (English), Pure and Applied Mathematics, Vol. 3, New York: Marcel Dekker, Inc., pp. vi+418, MR0268497, Zbl 0207.09101.
[2] V. S. Vladimirov (2002), Methods of the theory of generalized functions, Analytical Methods and Special Functions, Vol. 6, London–New York: Taylor & Francis, pp. XII+353, ISBN 0-415-27356-0, MR2012831, Zbl 1078.46029.

solution to $\square\chi=f$.


Binary t-Test Order

Question: I'm performing a t-test for some simple data. The data I imported (plant.growth) had column one (pesticide) has whether the plant received pesticide A or B and column two had the amount grown in inches (height).
When I run the t test, t.test(height~treatment), my t-value and my confidence intervals are negative. I would prefer them to be positive but I don't know how to get the binary data to flip (ie have the sample mean of A be subtracted from the sample mean of B. I'm still really new to R, and I can't seem to find a simple way to do this.
Thank you for your help!
Answer: treatment <- relevel(treatment, ref = "B")
t.test(height ~ treatment)

Or alternatively
treatment <- factor(treatment, levels=c("B","A"))

would also have worked.

Binary t-Test Order


Protractor addMockModule additional arguments not working?

Question: This seems so, so easy, but I can't figure out why this simple code doesn't work.
I am adding a mock module to mock my API backend in my Angular E2E tests. I'm using Protractor 1.6.0. I need to pass additional arguments to the mocked module, which, according to the Protractor docs, is possible by just sending them as additional arguments. However, my function claims it has no arguments...
var mock = function() {
  // This is undefined and arguments.length is 0....why???
  var env = arguments[0];
  var mocks = angular.module('mocks.login', ['MyApp', 'ngMockE2E']);
  mocks.run(function($httpBackend) {
    $httpBackend.whenGET(env.apiBase + '/companies').respond([]);
  });
};

browser.addMockModule('mocks.login', mock, {apiBase: ""});

If it matters, I'm doing this in my Protractor config file in an onPrepare, as I'm trying to mock the API calls used during a user's login. Any help would be much appreciated.
Comment: Have you tried to move your code from `onPrepare` in Protractor config to `beforeEach` in your test suite?
Answer: Appearantely the args should be passed as array.
This is how it worked for me:
        var test =  {
            val1: 'val1',
            val2: 'val2'
        };
       browser.addMockModule('mockModule', function( args) {
            angular.module('mockModule', [])
                .value('TEST', args[0]);

        }, [test]);

Answer: This works for me:
var mock = function(args) {
    // args.apiBase should be available here
    var env = args;
    var mocks = angular.module('mocks.login', ['MyApp', 'ngMockE2E']);
    mocks.run(function($httpBackend) {
        $httpBackend.whenGET(env.apiBase + '/companies').respond([]);
    });
};

browser.addMockModule('mocks.login', mock, {apiBase: ""});


Issues with connecting to OPENVPN

Question: I am trying to configure Mullvad on openVPN - Debian
I have followed their online tutorial -
<code>Install OpenVPN and resolvconf (sudo apt-get install openvpn resolvconf)
Extract the configuration files into /etc/openvpn/
Start with sudo /etc/init.d/openvpn start
</code>
And when trying to start, I get the error -
[FAIL] Starting virtual private network daemon: mullvad_linux failed!
I have no idea why it is doing this and I have spent hours trying to fix it.
Your help would be appreciated greatly
Comment: Read your syslog.  The OpenVPN daemon, and scripts give lots of useful information.  Possibly adjust your config to verb 4 for even more detail.
Answer: I had the same error when trying this on my Raspberry Pi 2. First I found that starting the OpenVPN with this command returns some useful information.
sudo /usr/sbin/openvpn --config /etc/openvpn/mullvad_linux.conf
This made it clear I needed to update the config file with the correct path for the other ca.cert, mullvad.crt, mullvad.key, crl.pem by prefixing them with /etc/openvpn
Next I ran into a error with invalid ciphers which prompted me to upgrade to the latest version of OpenVPN. I found a nice guide here (replacing the version number with 2.3.6).
http://www.raspberrypi.org/forums/viewtopic.php?t=89216&p=637279
Then I had an error related to IPv6 so I enabled that by editing /etc/modules using this guys instructions.
http://www.raspberrypi.org/forums/viewtopic.php?f=66&t=15886
That left me with OpenVPN that initialized and then I got some weird timeouts but switching the config to connect to Sweden seemed to fix that!
Answer: What specifically did you do for step 2 - extract the configuration files? Usually you need to tell openvpn what configuration file to use, unless there is only one conf file. You need something that looks like openvpn.conf and a certificate to go along with it, usually something.pem ... On RHEL, you'd put it in  /etc/openvpn/ ... Also, I'm not sure when it asks you for the credentials ... you may need to edit the conf file to point to a passwords file or the like if you want to run it as a daemon / service.
I'd try running openvpn on the CLI and pass it the configuration file...
<code> sudo openvpn openvpn.conf </code> and replace openvpn.conf with the actual conf file path...

Issues with connecting to OPENVPN


Thread safety when storing pointers to object in container

Question: I have a question about good code practice when a mutex needs to be implemented. Consider the following code example where there is a manager class (Group) which holds a container of pointers to an object (Person).
If the Group class is shared by multiple threads, what is the correct method to access the public methods of the Person object?
Because when I execute 'getPerson()', I retrieve the pointer. But when I try and execute the 'getName()' it is possible the person object is already removed/deleted. How is this done the nice way?
EDIT: this example is not multi threaded, but consider this class used in multithreaded environment :)
class Person
{
public:
    Person(std::string name, std::string place) :
    m_name(name),
    m_place(place) {};

    ~Person() {};

    std::string getName(){return m_name;}
    std::string getPlace(){return m_place;}

private:
    std::string m_name;
    std::string m_place;
};

class Group
{
public:
    Group() :
    m_persons(100) {};

    ~Group(){};

    void createPerson() {
        std::lock_guard<std::mutex> l(m_mtx);
        Person* p = new Person("John", "London");
        m_persons.push_back(p);
    }

    void removePerson(int index) {
        std::lock_guard<std::mutex> l(m_mtx);
        m_persons.erase(m_persons.begin() + index);
    }

    Person* getPerson(int index) {
        std::lock_guard<std::mutex> l(m_mtx);
        return m_persons[index];
    }

private:
    std::vector<Person*> m_persons;
    std::mutex m_mtx;

};

int main() {
   Group g();
   g.createPerson();
   g.createPerson();

   std::cout << g.getPerson(0).getName();
}

Comment: `removePerson` does not destroy any `Person`, so that's not a problem in itself. You do need to figure out how to manage the lifetime of `Person`s, though. Does the `Group` own them, or somebody else, or are they shared (and if they are, who gets to share them)?
Comment: I would say in this example, group owns them. Yes I quickly wrote this example and I also have a memory leak apparently. Lets say that removePerson also deletes the pointer. Is the only solution then to create helper methods in Group to access the public methods of Person safely?
Comment: Re, "I would say...group owns them." What happens when you decide later on that it must be possible for a single person to belong to more than one group? That's a very realistic possibility, and it's the kind of architectural thing where preparing for it early on could save you a _lot_ of re-writing later.
Answer:
when I execute 'getPerson()', I retrieve the pointer. But when I try and execute the 'getName()' it is possible the person object is already removed/deleted.

The "already deleted" part sounds like a good use-case for std::shared_ptr (https://en.cppreference.com/w/cpp/memory/shared_ptr)
If you use shared pointers everywhere, then you never explicitly delete an object: You allow the shared_ptr class to automatically delete it when (and only when) the last reference is destroyed or re-assigned.
That doesn't solve the problem of what it means for one thread to obtain a reference to a person via their membership in a particular group while another thread simultaneously removes that same person from the same group. That's a higher-level race condition that you probably can only prevent or cope with by implementing some appropriately high-level and application-specific policy.


Visualize Covariance when only probability mass and marginal functions are given

Question: I am trying to intuitively understand Covariance like here. So if a random sample set given, I could draw rectangles with them, one of the cornes being fixated on mean $(\overline{x},\overline{y})$. Something like below.

I saw an example for Covariance where just the joint pmf was given and Covariance was calculated as below.

This was weird, because if I try to visualize the points location as per formula used above, it would be perfect rectangle like below, suggesting the X and Y are independent. It does not make sense to directly draw them from joint pmf, to observe any trend, then how come they could be used in teh Covariance formula?  How do I visualize this particular situation when only pmf is given? I understand inequal probability would have had given a scatter if samples are drawn from this distribution, but then we should have used sample data in Covariance formula, not these right?

The above example was taken from Probability and Statistics for engineering and the sciences by Devore link here, page 208.
Update 1:
I have constructed 3d bar as below, to illustrate that probability also adding weight (here height), to the measure, which would not be evident from 2D perspective (which is inclusive in this case). Looking at 3D, one could say, oh ok green is more (with higher bars, larger volume), so positive covariance. Will this visual inference would be correct? If this is so, only issue here is the 3d bars are not rightly rendered issue created
Comment: In your example, the random variables are discrete, which explains your difficulty in reproducing the first graph; I don't think that you can visualise the covariance between your particular set of random variables using the methodology in that link.
Comment: (1) The six points in your second graph have different probabilities, which makes it difficult to visualize the covariance. (2) There are infinitely many joint distributions that have the marginal distributions of your $X$ and $Y.$ Only the one in which $p(x,y) = p_{{}_X}(x)\times p_{{}_Y}(y),$ for $x=100, 250$ and $y = 0, 100, 200$ has $X$ and $Y$ independent. For example, the upper left probability in your first table would be $p(0,100) = (.5)(.25) = 0.125$ (_not_ $.20)$ and so on.
Comment: let us drop independence for a moment and focus on how to visualize them? Because I am writing a detailed tutorial for myself where I started with intuition of contrivance (and not yet gotten into correlation), so want my transition to be smooth. If visualization is for random sample and I am lost in visualizing the given example it would be a discontinuity in the flow of understanding. Instead of constructing rectangle, probably I should go for 3d cubes with height equal to respective joint probability?
Answer: In an Answer to this question @Glen_b shows how to generate a bivariate normal sample with a given population correlation $\rho.$ Below, I use this method to show samples of size $n = 2000$ from each of three bivariate
normal distributions with respective correlations $\rho = .1, -.5, .9.$ In each case $\mu_x = \mu_y = 0$ and $\sigma_x = \sigma_y = 1,$ so that all marginal distributions are standard normal.
<code>set.seed(1103);  n=2000
rho = .1; x1 = rnorm(n);  z = rnorm(n);  y1 = rho*x1 + sqrt(1-rho^2)*z
rho =-.5; x2 = rnorm(n);  z = rnorm(n);  y2 = rho*x2 + sqrt(1-rho^2)*z
rho = .9; x3 = rnorm(n);  z = rnorm(n);  y3 = rho*x3 + sqrt(1-rho^2)*z
r1=round(cor(x1,y1),3); r2=round(cor(x2,y2),3); r3=round(cor(x3,y3),3)
par(mfrow=c(1,3))
   plot(x1,y1, pch=".", main=paste("r = ",r1))
     abline(h=0, col="green2"); abline(v=0, col="green2")
   plot(x2,y2, pch=".", main=paste("r = ",r2))
     abline(h=0, col="green2"); abline(v=0, col="green2")
   plot(x3,y3, pch=".", main=paste("r = ",r3))
    abline(h=0, col="green2"); abline(v=0, col="green2")
par(mfrow=c(1,1))
</code>

You are correct that concentrations of points in the first and third quadrants
add positive terms to the sample covariance and hence tend to make the sample
correlation positive; similarly, points in quadrants two and four add negative
terms to the sample covariance.
However, do not confuse zero correlation with independence: if $X$ and $Y$ are
independent, then $\rho_{x,y} \approx 0.$ But correlation near $0$ is not necessarily an indication of independence. (Perhaps see the Wikipedia article
on correlation and dependence for examples.)
Comment: thank you very much for detailed answer, but as I said I am in a flow from covariance and not yet into correlation. I have already visualized like above using random samples to illustrate the concept of covariance, only thing is I want such visualization for example also, else it would be a discontinuity
Comment: The correlation is the covariance divided by the product of the two standard deviations.  I have no idea what you mean by 'discontinuity'. If you are looking for something that will make your method work, then perhaps take the comment by @InfProbSciX more seriously.
Comment: sorry, by discontinuity I meant as a metaphor, in my understanding. for discrete X and Y, for random samples we are able to visualize how co variance acts as a measure by plotting rectangles with one corner fixated at mean. But when a joint pmf is given, I am lost. The  x and y from pmf are not samples per se, but all possible x and y values with different probabilities. Because they are not randomly scattered, which could have given a visual hint of covariance, they are distributed in rectangles though with diff probabilities. Thatis, when X=100, y could take multiple values. (tbc)
Comment: how could I then visualize them without taking in to account their diff probability is naturally next question because that is how I visualized for random samples earlier. What is the missing piece that is prohibiting me to visualize? Probably if they had given samples instead of pmf, I could have visualzed? If so, then covariance calculation for given pmf will not make any sense. If it makes sense, then there should be a way to visualize them just like we did for random samples. Isnt it?
Comment: The example in Jay Devore's book is a fine start. But I sense that you need to be familiar with a much wider range of examples for a more comprehensive understanding. The examples I gave and the ones in the Wikipedia link were my effort to help with that.
Comment: I have done an elaborate work already on visualizing covariance before coming to this example, that is why its important I crack it. Please find my work [here](https://www.scribd.com/document/392307777/30-Correlation-Main-DRAFT) so far, in which I start from Covariance and plan to end with Correlation. I have gone very detailed in creating the intuition with visuals. I did not share this earlier, because this could be a too much of a context, but you could have a quick glance as its only very basic concept, but just elaborated like spoon feeding. I share this so you could understand.. (tbc)
Comment: .. my current flow. I have already clearly illustrated visuals for random sample, but want to convince myself and readers, it applies even though just pmf is given, so a right context should be built with visuals for that as well if current visual cannot be applied directly. For eg, I am thinking may be, creating 3d rectangles, with height denoting probability value, could give visual sense of underlying covariance. In earlier random case, we were able to stick with 2D visual because of uniform distribution (afaik).
Comment: of course there are few more unresolved doubts on same subject for me like one [here](https://math.stackexchange.com/questions/2980197/why-divide-by-n2-for-covariance/2982455#2982455), [here](https://math.stackexchange.com/questions/2982674/single-to-double-summation-via-vector-matrix-problem), etc which I have not gotten answer yet, so marked in my draft as "discontinuity in understanding".


What is the interpretation of the "C" parameter in the five parameters logistic curve?

Question: I'm using the following equation for the 5-parameters logistic curve:
$$
y = A + \frac{D-A}{\Bigl(1+\exp\bigl(B(C-x)\bigr)\Bigr)^S}
$$
What is the interpretation of the $C$ parameter?
I found some docs which say that it corresponds to the inflection point, some other docs which say that it corresponds to the $y$-value at the midpoint of the two asymptotes, as in the case $S=1$ (the case of the 4-parameters logistic curve).
But this is not true:
x <- seq(46, 53, length.out = 100)
A <- 30; D <- 100; B <- 5; C <- 50; S <- 10
y <- A + (D-A)/(1+exp(B*(C-x)))^S
plot(x, y, type = "l")
abline(v = C, col = "red", lwd = 2)

Is there an interpretation of $C$?
Answer: $C$ is manifestly a location parameter.
It helps to understand that when $x$ and $y$ have a unit of measure, the choices of their origin and basic unit are essentially arbitrary.  You can exploit that to make choices that simplify the formula and therefore reveal the essential shape of the curve.
Mathematically, this means you should rewrite the formula $y=f(x;\theta)$ in the form
$$\frac{y - \nu}{\tau} = f_0\left(\frac{x-\mu}{\sigma}; \theta^\prime\right)$$
where $\theta^\prime$ has four fewer parameters than $\theta=(A,B,C,D,S).$
In terms of the graph $\Gamma(f)=\{(x, f(x;\theta))\mid x\in \mathbb R\}$ this has the familiar geometric interpretation: the transformation of $x$ stretches the horizontal axis by $\sigma\gt 0$ and then shifts that axis by $\mu;$ the transformation of $y$ is the inverse of a rescaling by $\tau$ and shift of $\nu.$  Equivalently, on a plot of $\Gamma(f_0)$ simply relabel any ordinate $x$ as $\mu+x\sigma$ and any abscissa $y$ as $\nu + y\tau.$
This can usually be done by inspection.  In the present case, the curve takes the form
$$y = f(x; (A,B,C,D,S))$$
which with simple algebraic manipulations can be written
$$\frac{y-\nu}{\tau} = \frac{y-A}{D-A} = \left(1 + \exp(-B(x-C))\right)^{-S} = \left(1 + \exp\left(-\frac{x-\mu}{\sigma}\right)\right)^{-S}$$
from which we can just read off the equations
$$\tau=D-A,\ \nu = A,\ \mu=C,\ \sigma=\frac{1}{B}$$
and identify the underlying shape as
$$f_0(z;S) = \left(1 + \exp(-z)\right)^{-S}.$$
To understand these particular shapes, plot them on semi-log axes: that is, consider the graphs of $\log_2(y) = \log_2(f_0(x)) = -S\log_2(1 + \exp(-x)).$

Evidently $S$ is the value of $\log_2(y)$ when $z=0:$ that is, it establishes a logarithmic scale for $y$ by making the value of $f_0(0)$ equal to $S.$ Given this interpretation of $S,$ $\mu = C$ becomes meaningful as corresponding to the unique point where $\Gamma(f_0)$ equals $S.$
Comment: Thanks. I knew C is a location parameter. But I need a "nice" interpretation, short and suitable for non-statisticians, as in the case S=1. I accept your answer for the good work.
Comment: There are many possible useful characterizations of $C.$  For instance, you could choose $f_0(z;S) = 2^S(1+\exp(-z))^{-S}-1,$ in which case $C$ is the intercept of $f_0.$ Of course this choice of $f_0$ changes the interpretations of $A$ and $D-A,$ suggesting you might want to reparameterize the family.
Answer: There's no direct interpretation of $C$.
To get the value of $x$ corresponding to the midpoint between the two asymptotes, one solves an easy equation and one gets
$$
xmid = C - \frac{\log\Bigl(2^{\frac{1}{S}}-1\Bigr)}{B}.
$$
x <- seq(49, 60, length.out = 100)
A <- 30; D <- 100; B <- 1; C <- 50; S <- 10
y <- A + (D-A)/(1+exp(B*(C-x)))^S
plot(x, y, type = "l")
xmid <- C - log(2^(1/S) - 1)/B
abline(v = xmid, col = "red", lwd = 2)
abline(h = (A+D)/2, col = "red", lwd = 2)


Armazenar List Na memória ou em Cookie

Question: boa tarde.
Tenho uma aplicação que possui todo um nível de gerenciamento de permissões de acessos a páginas e uma série de outras configurações.
Sempre quando um usuário se autentica, eu monto uma lista com todos os menus (links/páginas) que este usuário pode acessar no sistema. O que acontece é que neste momento (homologação da versão mais recente) a lista está sendo populada a cada requisição/refresh de uma página. O que eu quero é saber se tem alguma forma de armazenar isso em algo que eu possa consultar sempre que precisar, sem a necessidade de ir no banco de dados.
Até o momento eu já utilizei (tentativas):

Session: funciona, mas não gosto de usar, ainda mais que a aplicação possui um volume diário de +10k pessoas;
UserData do FormsAuthentication: Tentei converter uma viewModel para JavaScriptSerialization, mas como o tamanho ficou enorme, o mesmo acabou não sendo criado e não gerado o cookie;
OutputCache da ActionResult: Esse método foi um dos que mais gostei, porém ele não é específico para cada sessão/login e sim para a aplicação como um todo;

Espero que possam me ajudar, porque a um bom tempo venho quebrando muito a cabeça para pensar nesta solução.
Abraços!
Answer: Há, ainda, a solução do Stack Overflow: Redis.
O Redis pode ser instalado no Windows.
O time do Stack Overflow escreveu um excelente módulo de integração do Redis à sua aplicação ASP.NET MVC.
A serialização JSON fica por conta deste outro pacote.
Se precisar de ajuda com estes componentes, só fazer outras perguntas.
Comment: Entendi. Não tinha conhecimento sobre o Redis ainda. Mas com relação aos 3 itens que eu citei acima, apenas a Session funcionou, mas ninguém recomenda o uso dela, então estou praticamente sem nenhuma solução ainda...
Comment: Por isso mesmo. O Redis funciona como um mecanismo de sessão, cujas chaves são expiráveis. Você instancia um valor tendo como chave alguma identificação do usuário e expira este valor depois de um determinado tempo. Sendo o Redis um grande dicionário (chave-valor), você pode colocar qualquer coisa no valor, incluindo HTML e JSON, se assim desejar.
Comment: então eu posso fazer um "Redis["teste"].Value = listMenu (List)"? E ele também expira igual uma session?
Comment: Pode. Sim, expira igual Session. Você pode expirar manualmente, se quiser.
Comment: me desculpa a pergunta, mas o que eu ganho usando o Redis ao invés da Session?
Comment: Fica isolado do mecanismo de Session normal, que tem um problema clássico de balanceamento; Tão simples de usar quanto a Session normal; Você pode usar Redis como uma cache de qualquer coisa, e não apenas de Sessions, mas também de dados que não mudam muito.

Armazenar List Na memória ou em Cookie


Paginamento de paginas php

Question: ola estou criando um sistema de pesquisa e preciso criar um paginamento pensei em usar $_SESSIONporem notei que daria erro segue a baixo o codigo q desenvolvi ate agora
Pesquisa:
<?php
if(isset($_GET['PG'])){
    if(isset($_SESSION['pg'])){

        $id=$numpg-$_SESSION['pg'];

    }else{
        $_GET['PG']=0;
    }
}else{
    $_GET['PG']=0;
}
if(is_numeric($_GET['PG'])){
?>

<?php
$i=0;
?>

<?php
    $ps=$_GET['PS'];
    $sql="SELECT id FROM indexes WHERE (modo!=4 and nome LIKE '%$ps%') ORDER BY id DESC";
    $exe=mysqli_query($link,$sql);
    $numrow=mysqli_num_rows($exe);
    if($_GET['PG']==0){
        $sql="SELECT nome,foto,vew,tkm,modo,id FROM indexes WHERE (modo!=4 and nome LIKE '%$ps%') ORDER BY id DESC LIMIT 12";
    }else{
        $sql="SELECT nome,foto,vew,tkm,modo,id FROM indexes WHERE (modo!=4 and nome LIKE '%$ps%') and (id <= $id) ORDER BY id DESC LIMIT 12";
    }
    $exe=mysqli_query($link,$sql);
    //echo e($numrow);
    while($row=MYSQLI_FETCH_ARRAY($exe)){
        $nome=$row['nome'];
        $foto=$row['foto'];
        $vew=$row['vew'];
        $tkm=$row['tkm'];
        $modo=$row['modo'];
        $pxid= $row['id'];

        $i++;

?>

: <?php echo e($vew); ?>

<a class="sb-preview-img" href="<?php ?>">
<img class="card-img-top" src="../_img/<?php echo e($foto) ?>"    style="width:100%;">

<?php echo e($nome) ?>
<?php if($modo == 1){ ?>

<?php }else if($modo == 2){?>

<?php }else{ ?>

<?php } ?>

<?php
if($i==4){
?>

<?php
$i=0;
?>

<?php
}
if($numrow>12){
 $_SESSION['pg']=$pxid;
}
}
?>
<?php
if($numrow>12){
    if($i>0 and $i<4 ){
      ?>

      <?php
    }
?>

  <?php
    $pg=$numrow/12;
    $pg = ceil($pg);
    //echo $pg;
    for($i=1;$pg>=$i;$i++){
    if($i==1){
  ?>

<a href="?PS=<?php echo e($_GET['PS']) ?>&PG=0">1

    <?php
    }else{
    ?>

<a href="?PS=<?php echo e($_GET['PS']) ?>&PG=<?php echo e($i)?>"><?php echo e($i)?>

    <?php
    }
    }
    ?>

<?php
}
?>

<?php

}else{

}
?>

Answer: Encontrei alguns artigos e vídeos exatamente com sua duvidas, veja se isso te esclarece:

Sistema de Paginação de Resultados usando Bootstrap, PHP e MySQL - Canal: Zero Bugs
Como fazer paginação PHP e MySQLi? - Canal: Celke - PHP
Como fazer Paginação em PHP com MySQL - DevMedia
Bom espero que estes Vídeos e Artigo te ajudem assim como me ajudaram a realizar a paginação.

Paginamento de paginas php


How do I convert a Linux C USB read to Android?

Question: I have Tire Pressure Management System (TPMS) adapter that plugs into USB (http://store.mp3car.com/USB_TPMS_Version_2_20_4_Sensor_Kit_p/com-090.htm). I have it working with the original Windows software, as well as Linux C code to read the tire pressures and temperature. I'm now trying to use this adapter on Android and am having some difficulty. I can detect the device fine, but my reads are all returning -1 bytes read, whatever I try. Here's the C code I'm trying to convert:
int TpmsPlugin::readUsbSensor(int sid, unsigned char *buf)
{
  int r, transferred;

  buf[0] = 0x20 + sid;
  r = libusb_interrupt_transfer(mDeviceHandle, ENDPOINT_OUT, buf, 1, &transferred, INTR_TIMEOUT);
  if (r < 0) {
    DebugOut() << "TPMS: USB write interrupt failed, code " << r << endl;
  }

  r = libusb_interrupt_transfer(mDeviceHandle, ENDPOINT_IN, buf, 4, &transferred, INTR_TIMEOUT);
  if (r < 0) {
    DebugOut() << "TPMS: USB read interrupt failed, code " << r << endl;
  }

  return r;

The value of sid is 1, 2, 3 or 4 depending on the wheel. The values are then extracted with:
    lfPressure = ((float)buf[0]-40) * PRESSURE_SCALE * KPA_MULTIPLIER;
    lfTemperature = (float)buf[1]-40;

You can see full implementation of this driver here as well: https://github.com/otcshare/automotive-message-broker/blob/master/plugins/tpms/tpmsplugin.cpp
My Android version is able to find the USB device, get permission to use it, connect to it, get the UsbEndpoints (it lists two), but whether bulkTransfer() or controlTransfer() I try, I've failed. In particular, I've tried a lot of different controlTransfer values based on all the docs I could find. Here is some code that I've tried:
UsbInterface intf = TpmsSectionFragment.device.getInterface(0);
UsbEndpoint endpoint_in = null, endpoint_out = null;
for (int i = 0; i < intf.getEndpointCount(); i++) {
    UsbEndpoint ep = intf.getEndpoint(i);
    if (ep.getDirection() == UsbConstants.USB_DIR_IN)
        endpoint_in = ep;
    else if (ep.getDirection() == UsbConstants.USB_DIR_OUT)
        endpoint_out = ep;
}

UsbDeviceConnection connection = gUsbManager.openDevice(TpmsSectionFragment.device);
connection.claimInterface(intf, false);
int timeout = 1000;
int length = 4;

while (true) {
    for (int sensorId = 1; sensorId <= 4 && mReadThreadActive; sensorId++) {

        byte[] tpmsRaw = new byte[length];
        tpmsRaw[0] = (byte) (0x20 + sensorId);
        int out_len = connection.bulkTransfer(endpoint_out, tpmsRaw, 1, timeout);
        int in_len = connection.bulkTransfer(endpoint_in, tpmsRaw, 4, timeout);
        //int out_len = connection.controlTransfer(0x42, 0x0, 0x100, 0, tpmsRaw, tpmsRaw.length, timeout);
        //int in_len = connection.controlTransfer(0x41, 0x0, 0x100, 0, tpmsRaw, tpmsRaw.length, timeout);

Any thoughts on what I could be doing wrong are greatly appreciated. I'm happy to try a few different things to debug further if you have any suggestions.
Thanks!
Comment: Your libusb code implies you need to use an **interrupt transfer** rather than the synchronous bulk or control transfer methods you tried.  Please read the documentation at http://developer.android.com/reference/android/hardware/usb/UsbRequest.html particularly "Requests on bulk endpoints can be sent synchronously via bulkTransfer(UsbEndpoint, byte[], int, int) or asynchronously via queue(ByteBuffer, int) and requestWait(). **Requests on interrupt endpoints are only send and received asynchronously**."  I'm seeing suggestions the missile launcher code might be a relevant example.
Comment: sounds like a cool project.
Comment: Chris, thank you so much for the response. With a few tweaks I just got it to work. I'll post a note with code below.
Answer: Here's the solution based on the help from Chris. I converted the calls to queue / requestWait:
ByteBuffer buf = ByteBuffer.allocate(4);
buf.put(0, (byte) (0x20 + sensorId));

UsbRequest send = new UsbRequest();
send.initialize(connection, endpoint_out);
Boolean sent = send.queue(buf, 1);
UsbRequest r1 = connection.requestWait();

send.initialize(connection, endpoint_in);
send.queue(buf, 4);
UsbRequest r2 = connection.requestWait();

The other thing I needed to tweak was this call and set the second parameter to true:
connection.claimInterface(intf, true);

That's it. Done. Thanks for the help!


Find matching values in SQL based on multiple variables

Question: UPDATED! I want to find rows in table_20220121 where two variables matches the table_20220121_b. Also, there could be several matches in table_20220121, but I only want the one with the biggest [Time since 1970]-value, that is, I want the output to be the row with number 88 and 1391 in table_20220121. Thanks!
drop table table_20220121
drop table table_20220121_b
drop table table_output

CREATE TABLE table_20220121
(
number  float,
IP   nvarchar(100),
[Time since 1970]   float,
[Timestamp]   nvarchar(100),
[Scroll Depth Threshold] float
);
INSERT INTO table_20220121
VALUES
(84,'999.999.99.111',1635332371761,'2021-10-27T12:59:31.761+02:00',0.7),
(85,'999.999.99.111',1635332377747,'2021-10-27T12:59:37.747+02:00',0.7),
(86,'999.999.99.111',1635332387744,'2021-10-27T12:59:47.744+02:00',0.7),
(87,'999.999.99.111',1635332388600,'2021-10-27T12:59:48.600+02:00',0.8),
(88,'999.999.99.111',1635332397761,'2021-10-27T12:59:57.761+02:00',0.8),
(1387,'999.999.99.999',1640983016936,'2021-12-31T21:36:56.936+01:00',0.4),
(1388,'999.999.99.999',1640983030370,'2021-12-31T21:37:10.370+01:00',0.5),
(1389,'999.999.99.999',1640983055463,'2021-12-31T21:37:35.463+01:00',0.5),
(1390,'999.999.99.999',1640983100401,'2021-12-31T21:38:20.401+01:00',0.6),
(1391,'999.999.99.999',1640983115461,'2021-12-31T21:38:35.460+01:00',0.6)
;

CREATE TABLE table_20220121_b
(
IP   nvarchar(100),
[Scroll Depth Threshold] float
);
INSERT INTO table_20220121_b
VALUES
('999.999.99.999',0.6),
('999.999.99.111',0.8)
;

select * from table_20220121;
select * from table_20220121_b;
go

Actually, this below is the ANSWER to my question. I have provided it here in the question section just for clarity:
with matches as (
   select *, Row_Number() over(partition by ip order by [Time since 1970] desc) rn
   from table_20220121 ta
   where exists (
       select * from table_20220121_b tb
       where ta.ip=tb.ip
         and ta.[Scroll Depth Threshold] = tb.[Scroll Depth Threshold]
   )
)
select number, ip, [Time since 1970], Timestamp, [Scroll Depth Threshold]
/* into table_output */
from matches
where rn = 1;

Comment: Do not post answers in questions. You are welcome to answer your own question
Answer: The syntax you have tried to use is not supported by SQL Server (and you're using 'string literals' so if the syntax were supported, it would always return true); however you can just join the tables using multiple criteria and take the top n
select top(1) ta.*
/* into table_output */
from table_20220121 ta
join table_20220121_b tb on ta.ip = tb.ip
  and ta.[Scroll Depth Threshold] = tb.[Scroll Depth Threshold]
order by [Time since 1970] desc;

Alternatively you can join and filter for multiple rows using row_number to filter for the maximum value per group:
with matches as (
    select *, Row_Number() over(partition by ip order by [Time since 1970] desc) rn
    from table_20220121 ta
    where exists (
        select * from table_20220121_b tb
        where ta.ip=tb.ip
          and ta.[Scroll Depth Threshold] = tb.[Scroll Depth Threshold]
    )
)
select number, ip, [Time since 1970], Timestamp, [Scroll Depth Threshold]
/* into table_output */
from matches
where rn = 1;

Comment: Thanks. I have updated by question now. Your code provided me with my desired output.
Comment: Your answer indeed solves my question, but I need a more general answer. For example, the table table_20220121_b can have many rows, so it does not work when I test on my big table.
Comment: Ok I have updated above with an alternative method - your question was quite explicit about finding the *one* row, but assuming (you haven't made it clear) you want to do this for multiple IP addresses, you can use *row number* to partition by IP groups.


Find the MLE $\hat\theta$ for $\theta$

Question: I am trying to learn by myself, this is the problem I came across.
If $X_1, X_2 ..... X_n$ be an i.i.d. sample from $N(\theta, \theta^2)$ distribution, where $\theta > 0$ is unknown parameter.
What is the MLE $\hat\theta$ of $\theta$? And how do I show that MLE is consistent for $\theta$?
Comment: Welcome. Where are you stuck? What have you tried?
Answer: This is pretty straightforward. The PDF of each $X_i$ is : $$f_{X_i} (x) = \dfrac{1}{\theta\sqrt{2\pi}}\cdot \exp\left[-\dfrac{1}{2}\left(\dfrac{x - \theta}{\theta}\right)^2\right]\quad\quad\text{for}~i=1, 2, \cdots, n$$
Thus, the likelihood equation will be : $$L = \prod_{i=1}^n \dfrac{1}{\theta\sqrt{2\pi}}\cdot \exp\left[-\dfrac{1}{2}\left(\dfrac{x_i - \theta}{\theta}\right)^2\right] = \dfrac{1}{\theta^n (2\pi)^\frac{n}{2}}\cdot \exp\left[-\dfrac{1}{2}\sum_{i=1}^n \left(\dfrac{x}{\theta} - 1 \right)^2\right]$$
Therefore, $$-\log L = n \log \theta +\dfrac{n}{2} \log (2\pi) + \dfrac12 \displaystyle\sum_{i=1}^n \left(\dfrac{x}{\theta} - 1 \right)^2$$
In order to maximize $L$ , we must have $\dfrac{dL}{d\theta} = 0$ . Differentiating $L$ , equating to $0$ , we get : $$\dfrac{n}{\theta} - \sum_{i=1}^n \left(\dfrac{x}{\theta} - 1 \right)\cdot \dfrac{x_i}{\theta^2} = 0\quad~\implies~\quad \left(\dfrac{1}{\theta} \right)^2\cdot \sum_{i=1}^n x_i ^2 - \left(\dfrac{1}{\theta}\right) \cdot \sum_{i=1}^n x_i - n = 0$$ Solving this quadratic equation, we get that : $$\text{MLE}(\theta) ~=~ \hat{\theta} ~=~ \dfrac{2 \cdot \displaystyle\sum_{i=1}^n x_i^2}{\displaystyle\sum_{i=1}^n x_i + \sqrt{\left(\sum_{i=1}^n x_i \right)^2 + 4n\cdot \sum_{i=1}^n x_i^2} }$$
Check my calculation once. I may be wrong somewhere.
Comment: Presumably the quadratic has two solutions (why does you final expression not include $n$?) and you may need to check which if either gives a maximum: for example I would expect something strange to happen in some cases if $\sum x_i < 0$
Comment: My final expression had a small typo, I fixed it almost immediately after writing my answer. The other root of the quadratic is not a correct answer because $\theta$ would have been negative in that case.
Comment: @Henry yes, we should check whether the 2nd derivative is positive or not. I have omitted that in my solution. However, in most cases, I have seen that the equation which we get after setting $\frac{dL}{d\theta} = 0$ produces a solution which actually maximizes the log-likelihood (and not minimizes it). I don't know why this happens. It'll be helpful if you can say why $\hat{\theta}$ maximizes $L$, without calculating the 2nd derivative.
Comment: I see your point.  If $n=2, x_1=-1,x_2=-2$ then your expression gives $\hat \theta=2.5$ and a quick curve sketch shows this strange result is indeed the maximum of the likelihood
Comment: Intuitively that's clear. However, that's surely not a rigorous thing. Anyway, it serves our purpose.

Find the MLE $\hat\theta$ for $\theta$


how to applay 2d mask on 1d array

Question: What is the best way to apply a 2d mask on a 1d array? let's say we have the array a of the shape (k, n) the array b of shape (k, 1) and a mask of shape (k, n)
I want to compute
c = np.zeros_like(a)
for i in range(a.shape[1]):
    c[mask[:, i], i] = a[mask[:, i], i] - b[mask[:, i]]

is there a more efficient way than use np.repat?
c[mask] = a[mask] - np.repeat(b, a.shape[1], axis=1)[mask]

for example:
a = np.arange(25).reshape(5, 5)
b = np.ones((5, 1))
mask = np.random.randint(0, 2, (5, 5), dtype=np.bool)
c = np.zeros_like(a)
c[mask] = a[mask] - np.repeat(b, a.shape[1], 1)[mask]

Comment: Still somewhat problematic since b can't be masked either.
Comment: i have edited to c=np.zeros_like(a), thanks.
Comment: Oh... is that the question? You can use `np.broadcast_to(b, mask.shape)[mask]`, which should consume no additional memory. idk about efficiency, though: it's not any more efficient than `np.repeat`; for exploiting sparsity, you'd probably need to use something more powerful than numpy.
Comment: Please share a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
Answer: The way how you initialize c array is out of question.
Then, to perform your "selective" substitution, run:
c = np.where(mask, a - b, c)

Details:

a - b - Subtract b from each column of a. For the time being,
with no mask.
np.where(...) - Take values from a - b, but only elements "indicated"
by True values in the mask. Other elements take from c.
c = ... - Save the result back in c.

This way the mask is applied to 2-D arrays:

original c array,
and a temporary array, created by subtraction of broadcasted b
array form a.

how to applay 2d mask on 1d array


Sed: execute alternative command when output from previous one is empty

Question: I wanted to modify dig command to automatically apply a reverse lookup to any A record I receive in output.
Therefore, I've created the following function:
dt ()
{
    remove=$(echo $@ |  sed 's^https*^^' | sed 's^[,/*:]^^g' );
    dig any +trace +nocl +nodnssec $remove | sed "s/\($remove.*A\s*\([0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\)\)/dig -x \2 +short | xargs echo \"\1 ->\"/e"
}

With this code I have the following output (only A record part is shown so to avoid the question getting bigger):
domain.com.      1200    A        220.127.116.11 -> server224-3.web-hosting.com.

However, now I also need to make a whois lookup using the IP I receive from dig output, but only in case dig -x \2 +short doesn't give any result (stackoverflow.com can be a good example of a domain with A records that do not have PTR).
I tried something like this to check exit code of regular host command (since dig implies that output is successful even if it's empty) and execute proper command depending on the result:
dig any +trace +nocl +nodnssec "$remove" | sed -e "s/\($remove.*A\s*\([0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\)\)/echo -n \"\1 -> \"; host \2 | grep -q ''; if [ ${PIPESTATUS[0]} -eq 0 ]; then dig -x \2 +short; else whois \2 | grep 'network:Network-Name:';fi; /e"

But it seems that sed somehow affects the value of ${PIPESTATUS[0]} array.
I wanted to do these modifications in sed because I needed something that will print lines on the go. If I  use variables and modify the output from them, the function will work slower, at least visually.
Maybe awk can be of use here, but I am not sure how I should write the code using this command.
Is there a way around this problem? Can sed be used for this purpose or should I use some other tool? Thanks.
Comment: You have: `remove=$(echo $@ |  sed 's^https*^^' | sed 's^[,/*:]^^g' );` — you should consider: `remove=$(echo "$@" |  sed -e 's^https*^^' -e 's^[,/*:]^^g' );`.  The change uses one `sed` invocation instead of two; that's uncontroversial.  Using `$@` unquoted is usually a danger sign, but it does flatten out white space and newlines, so it isn't absolutely wrong. Unquoted, there's no difference between `$@` and `$*`; quoted, there is.  It isn't absolutely clear what's best there, but `"$@"` is usually the correct way to quote arguments. —— None of this has anything much to do with your problem.
Comment: I just made the mistake of trying to look at the far right end of your sed scripts.  They're too long and unreadable to be interesting to me, I'm sorry to say.  At least, not while I'm at work and need to be doing other stuff as soon as the compilation is done.
Comment: @JonathanLeffler thank you for your recommendations. And sorry for not using "-E" parameter for sed (which would make the regex a bit smaller and easier to look at). Just wanted to make sure I leave out any possible edits that could add more mistakes to the line, since it was written ~9 months ago (when I didn't know about ERE option), so I might also need to review the regex itself.
Comment: Also, I will certainly add "-e" flag to optimize the line for "remove" variable per your recommendation. I am also trying to figure out how to make my code more readable. Most probably I should at least break lines by "\" or something.
Comment: I think you're writing a shell script (fragment) with the `sed` scripts.  I wonder if you'd do better having an actual second script that you invoke with a few (one, two, …) appropriate arguments.  If it's unreadable, it's unmaintainable.  It may be correct, but it is hard to tell.  I seem to be unusual these days, but I write lots of scripts, and most of them aren't very big, at least when they start out.  I have over 600 programs (scripts and executables) in my `$HOME/bin` directory.
Comment: Or, if you don't like shell scripts, consider making another function which takes the appropriate arguments and runs the code.
Answer: The good old' bash gives you variety of tools grep, awk, xargs, while read and so on. Using sed with e command with inside checking PIPESTATUS and executing xargs.... is just unreadable and very long too read. It's not clear to me what do you want to do, as too much happens on one line.
The dig command results zero status on success - you can check it's output if it has zero length when it "fails".
Consider the following script:
dt () {
    remove=$(
        <<<$1 \
        sed 's#^http[s]?://\([^/]*\).*#\1#'
    )
        dig any +trace +nocl +nodnssec "$remove" |
        tr -s '\t' |
        awk -v "remove=${remove}." '{
                if ($1 == remove && $3 == "A") {
                        print
                }
        }' |
        while IFS= read -r line; do
                IFS=$'\t' read -r _ _ _ ip _ <<<"$line"
                if ! dig_result=$(dig -x "$ip" +short); then
                        echo "Dig error" >&2
                        exit 1
                fi
                if [ -z "$dig_result" ]; then
                        printf "%s -> no-result-from-dig\n" "$line"
                else
                        printf "%s -> %s\n" "$line" "$dig_result"
                fi
        done
}

First dig is run. Notice the "$remove" is quoted.
Just a precaution - I squeze  the tabulators in the output.
Then I filter - the first column should have "$remove". with a dot and the third column should be an "A"
Then for each line (as there are meny)
I get the ip address (ok, maybe ip=$(<<<"$line" cut -f4) would be cleaner and simpler).
I get the result from the dig -x using the ip address
If the result is empty I print "no-result-from-dig" if it not, I print the result.

Running:
dt stackoverflow.com
dt google.pl

Outputs:
stackoverflow.com.      300     A       188.8.131.52 -> no-result-from-dig
stackoverflow.com.      300     A       126.96.36.199 -> no-result-from-dig
stackoverflow.com.      300     A       22.214.171.124 -> no-result-from-dig
stackoverflow.com.      300     A       22.214.171.124 -> no-result-from-dig
google.pl.      300     A       188.8.131.52 -> waw02s16-in-f3.1e100.net.

The reason your command did not work is that $PIPESTATUS was quoted inside " quotes thus expanded before running the shell. You should escape the $ so that's \$PIPESTATUS or pass it inside nonexpading  single quotes " ... "'$PIPESTATUS'" ... ".
Comment: Thank you so much! That's the solution I've been looking for! I will need to adjust some things, but now I can see some good examples on how to develop the function further.


Don't understand concatenation operator (++)

Question: I have a question about list concatenation. The function plus plus (++) work is different with parentheses
(++ "abc") ("xyz") >>> it's xyzabc
(++) "abc" "xyz"   >>> it's abcxyz

I think it's because:
(++ "abc") ("xyz") >>> "xyz" ++ "abc"
(++) "abc" "xyz"   >>> "abc" ++ "xyz"

But why, and have any document talk about that?
I continue to test with "subtract" function. The result as my expect:
(subtract 10) (5) >>> -5
(subtract) 10 5   >>> -5

Comment: https://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-280003.4
Comment: `(op x) => \a -> a op x`; `(x op) => \a -> x op a`; `(op) x y => \x y -> x op y`
Comment: @freestyle maybe, I think so, but you have any document talk about function (++) implement like that?
Comment: The function is called `(++)`. `(++ "abc")` is *not* a normal function call - see how it doesn't even contain the name of the function! `((++) "abc")` would do what you expect.
Answer: Since ++ is an operator, Haskell expects it to be in an infix position. Adding parens on either side will tell Haskell to treat it as a prefix function. That's why
(++) "abc" "xyz"      -- "abc" ++ "xyz"

works the way it does. However, having a paren on just one side of an operator, like (++ "abc") or ("abc" ++) is something special called a section - it essentially produces a function that would "fill in" the missing argument
(++ "abc")        -- equivalent to `\x -> x ++ "abc"`
("abc" ++)        -- equivalent to `\x -> "abc" ++ x`

Then, (++ "abc") ("xyz") is equivalent to (\x -> x ++ "abc") ("xyz") is equivalent to "xyz" ++ "abc".
Comment: +1, beat me to finding the "section" concept. I think it would be nice to add a little about the `subtract` function that the OP mentions; how the same logic doesn't apply because `subtract` is a function and not an operator. (Showing the difference between `(-) 10 5` and `(subtract) 10 5`).
Comment: The last one looks wrong `(- 2) 1` is a type error, since that's unary minus. Also, `subtract 2 1` yields -1. Indeed, `(-e)` is a special-case since it is not a section, precisely because unary minus exists which conflicts :-( `subtract` exists to be able to express these missing sections.
Comment: @chi Ack. I keep getting bitten by this. I don't even use unary minus in my code, I'm perfectly happy with `negate`.
Answer: Let's start with the second one. This is a case of prefix notation. Here, and if you are aware of the prefix notation of using operators, you would see the result "abcxyz" to be more intuitive. Basically, in this representation of operational expressions, the operator comes first, followed by the sequence of operands, which in this case is two. So, it treats "abc" as the first operand and "xyz" as the second operand and does the concatenation in the standard expected manner, i.e. the second/right operand is added to the right of the first/left operand.
Whereas, the first one is a case of currying. Basically, concatenation (++), being a multi-argument function can be equally expressed as a series of one argument functions, where by supplying one argument at a time, we are transforming our original function requiring n arguments (better read "expression" as denoted in Haskell) into another function which takes n-1 arguments. So, here the original 2-argument function (++) gets converted to a 1-argument function (++ "abc"). Now, it can be read as a function which appends "abc" to any string provided as an input, which is confirmed by our output as well.
Comment: It's important to note that operator sections are one step beyond currying. `(++ "abc")` and `("abc" ++)` are both legal, as is `((++) "abc")`, but `("abc" (++))` is not. Since binary operators are, well, binary, you can specify the single argument in either position, not just the first one as with ordinary multi-argument functions.


Reference variable from object in another class

Question: I've got two classes, one called "Territory" which constructs an object with the following variables: "posX" and "posY", like this:
public Territory(int column, int row)
{
    posX = column;
    posY = row;
}

Then in another class, "World" I do the following:
Territory territory1 = new Territory(0, 0);

But then when I try to reference some of the variables from that object, i.e. like this:
System.out.println("Coordinates: " + territory1.posX);

I get the error:
cannot find symbol - variable territory1

Any help?
EDIT:
Here are the full classes:
Territory:
public class Territory
{
    public int posX;
    public int posY;
    public int armies;
    public String owner;

    public Territory(int column, int row)
    {
        posX = column;
        posY = row;
        armies = 0;
        owner = null;
    }
}

World:
public class World
{
    public World()
    {
       Player player1 = new Player();
       Player player2 = new Player();

       Territory territory1 = new Territory(0, 0);
       Territory territory2 = new Territory(1, 0);
       Territory territory3 = new Territory(0, 1);
       Territory territory4 = new Territory(1, 1);
    }

    public java.lang.String toString()
    {
        System.out.println(territory1.getposX);
    }
}

Comment: Issue is probably with the scope of `territory1` though, based on the error, and not with the access modifiers of its fields.
Answer: your toString() method doesn't recognize 'territory1' because it was declared in the other method
This should work
public class World
{
     Territory territory1, territory2, territory3, territory4;

    public World()
    {
       Player player1 = new Player();
       Player player2 = new Player();

       territory1 = new Territory(0, 0);
       territory2 = new Territory(1, 0);
       territory3 = new Territory(0, 1);
       territory4 = new Territory(1, 1);
    }

    public toString()
    {
        if( territory1 != null)
            System.out.println(territory1.posX);
    }
}

Comment: I tried both of these and neither worked, still getting the same error. I updated the post to show full code.
Comment: @RyanEder nahh. of course that won't fix your problem. why don't you post your full code earlier. your `toString()` method doesn't recognize `territory1` because it was declared in the other method
Comment: @Voicu not aware of it. It seem that my answer is totally out! deleting
Answer: If you are not able to access the attribute of a class in another class then it means the attribute is not visible to that class. Check the access specifier for the attributes. You may have to use a getter(public method to get the value of a private variable) for the variable.


How to use / configure the Course Requirements module?

Question: When using the Course module, you may also want to use the Course Requirements module, so that a user cannot be enrolled in a 2nd course until a 1st course is completed.
However, it's not obvious how to actually use / configure the Course Requirements module. So how is this module supposed to be used/configured?
Answer: The Course Requirements module does not have a lot (any?) docu. But comment nr 3 of issue # 2148985 helps to make it work, i.e.:

Add a node reference field to your Course content type (to references other courses).
Go to admin/config/course/requirements and select that node reference field you just added.
Add courses through the node reference field.

After completing these steps, this is how it should work:

The courses you add in the field should block that course from being enrolled into without completing the referenced courses.
After completing a course it should also tell you what courses required that course for completion.


Can I plug a 2.5A 250V~ cable to a synth that is 100 - 240v?

Question: I just got my new synthesizer, Waldorf Blofeld Keyboard.
I live in Korea and the power plug that came with won't match.
This is the plug that came with the keyboard:

and this is the receptacle on the back of the keyboard:

The Waldorf specs are
Nominal voltage: DC12V
Supply Voltage: 100-240v
Maximum current consumption: 0.3 A
Maximum power consumption: 5 W
I have playstation cable which is 2.5A 250V~

Could I plug this to my Waldorf Blofeld Keyboard ?
Would it be ok ?
Comment: This is just a pair of wires, which doesn't do anything. 2.5A 250V~ only specifies how much electric power can flow through this cable. (That is, don't plug it into a 380V socket. Or don't use it for welding.)
Comment: @Tim This is the cable that came with the Blofeld. https://imgur.com/6PcoEWQ
Comment: I'm voting to close this question as off-topic because altough this is about a musical instrument it is better answered on a site for electrical engineering or household appliances.
Comment: Show us a pic of the lead that *did* come with it.
Comment: surely this is off-topic here?
Comment: Surely this is off-topic here...but do you need to hold a white cat in your arms while you play it?
Comment: Since you've linked the Sweetwater site, it looks like you probably bought it from the US? That's a North American-style plug. I've edited your image into the body to make that more obvious.
Comment: @DmitriUrbanowicz even that is unlikely to be disastrous... the cable would probably survive 380 V without problem, and I doubt you'll find any welding trafo with a C7 connector! The synth probably _won't_ like 380 V, but fortunately you also won't find a europlug-compatible 380 V outlet, so...
Answer: The 2.5A and 250V on the cable is just the highest current (Ampere) and voltage (Volts) that it's safe to use at. Provided that your mains supply is in the range 100V to 240V then that's no problem.
If you're not sure about the voltage in your country take a look at the Mains electricity by country article on Wikipedia.
Comment: @HyunYooPark the cable is just a cable. It won't increase the voltage. If your wall socket has 240, 220 or even 120V, it will deliver the same to your keyboard's power supply.
Comment: @HyunYooPark - 250v ~ . The '~' means ac voltage. Dc is more like '='. There is a big difference  in electricity between the two. And they're not compatible.
Comment: But the Playstation keyboard says 250v ~
does this mean I shouldn't use the cable ?
Answer: A simple cable with just wires and no electronics inside, as the one your photo shows, will simply forward any voltage. It won't change it.
The label on the cable specifies the maximum voltage it was made for. You can use it for any lower voltage as well. The ~ says that the voltage is alternating, in contrast to = where the voltage is constant (aka. direct).
I'm not sure how many different Waldorf Blofeld models exist, but one looks like this:

If your keyboard has this connector labelled AC In (alternating current in), then your cable will fit into the wall on one side and into the keyboard on the other side.
No serious electronics engineer would construct a 12 V= plug with that kind of connector, simply because everybody expects to put 110 V~ or 230 V~ into it.
A typical low voltage DC connector looks like this:

So there's no way you could accidentally mix a high voltage AC cable with a low voltage DC plug.
If your keyboard has a low voltage DC connector, then you need a power supply that converts 110 or 230 V~ to 12 V= like this (should have been shipped):

As you can see, it has the high voltage connector on one side and the low voltage connector on the other side.
Answer: This answer was provided before we had final details & pictures
To plug what to what??
If your cable fits the power supply for the keyboard, then that's fine.
If you're considering plugging it straight into the Waldorf directly, it will go BOOOM big time.
[I'm assuming it's the first - the second really shouldn't be physically possible. If it was, someone would have set their house on fire by now]
Comment: @HyunYooPark - The terminal/jack on the keyboard is labeled "AC-IN".  You cable will both fit _and_ work based upon the specs you've quoted. :)
Comment: The shape of the jack looks fitting, but I was worried about the specs. https://www.sweetwater.com/store/detail/BlofeldKB--waldorf-blofeld-keyboard-white
Answer: Cite from the FAQ at https://support.waldorfmusic.com/products/Blofeld%20Keyboard

Can I use my Blofeld Keyboard with the power grid in my country?  The device comes with a wide range power supply which covers everything between 50-60 Hz and 110-240V. You just need a power cord with a "figure of 8" cable, also known as C7 connector and the other plug matching the power grid standard in your country. A voltage converter is not needed.

Cite from https://www.power-plugs-sockets.com/south-korea/

In South Korea the power plugs and sockets are of type C and F. The
  standard voltage is 220 V and the standard frequency is 60 Hz.

So your cable should fit.
Comment: @Tim The FAQ says that the power supply works with everything between 50-60 Hz, so there should be no problem.
Comment: Not sure whether 60Hz or 50Hz is good for the keyboard. Would that be relevant?
Answer: No. The 250v is AC, and the keyboard is DC, and only 12volts. Completely incompatible.Playstation plug is a 'figure of eight' or 'Grundig' plug, used exclusively for mains powered items. It also gets used to power the black boxes (psu) which do transform 250vac into the 12vdc that your keyboard requires. But do not connect up direct. I can't think how you could anyway, as the keyboard will have a round socket for power, so it wouldn't (thankfully) fit.
EDIT _ I get it now! The figure of eight plug will fit your keyboard, it's just that the end which goes in the wall socket isn't right for your country! Any wire with the right plug ito the wall, and a figure of eight at the other end will do!
Comment: FWIW the [images here](https://www.sweetwater.com/store/detail/BlofeldKBBk--waldorf-blofeld-keyboard-black) suggest that the keyboard only has an AC-IN terminal, meaning the powersupply should be internal.  Thus it's fine (subject to the caveat that mains voltage must fall within the stated 100-240v range; which appears to hold for Korea, as Korea uses 220V).
Comment: "Assuming the wall ac is within the spec figures" means simply that assuming the voltage coming out of the socket in the wall is around 240/250vac. There's nothing else it could mean! The spec figures on the keyboard you stated.
Comment: You look at several items that *are* working from a wall socket. There will be a plate on them stating voltage - just like it does on the bottom of that plug. They'll probably say 220v, 230v, 240v. If so, they're the same as your keyboard. Think about it - plugs are different so it's (almost) impossible to put the wrong things together. Why haven't you asked the shop the keyboard came from?
Comment: I think you mistaken the keyboard version with the desktop version.The blofeld keyboard version power socket have the shape of 8. https://www.sweetwater.com/store/detail/BlofeldKB--waldorf-blofeld-keyboard-white
Comment: It would be good to clarify whether the OP intends to plug the Playstation cable directly into the keyboard (via a DC-IN terminal), or use it to replace the stock wall cable for connecting from the wall outlet to the keyboard's powersupply brick/input. This answer is assuming the former case, although the latter scenario is more plausible and would work just fine given the stated "Supply Voltage: 100-240v".  As long as the wall outlet provides a volatage within that range it's fine to plug it into the AC-IN terminal (just **not** the DC-IN one).  As in 'wall -> power supply -> keyboard'.
Comment: @aroth I'm going to connect this straight to the Blofeld without going through any power supply brick.
The 8 shape plug is going in straight to Blofeld, and the other side is going straight to the multi plug socket.
Comment: If the keyboard has a socket that the figure of eight plug fits, then that will do the trick. It does say 'detachable ac in' on the specs, so assuming the wall ac is within the spec figures, it will be fine. NEVER plug that figure of eight into an XLR (canon) socket. It fits well, and cost me best part of £1000 to repair a keyboard I inadvertently did that with (in the dark on stage). NEVER again!
Comment: What do you mean by " so assuming the wall ac is within the spec figures " ?
This is the hole in my Blofeld Keyboard that I'm going to plug the cable. https://imgur.com/p12G0Gr
Comment: @Tim How do I know how much voltage is coming out of the wall ? Sorry if I'm keep misunderstanding, but to put it simple, is it a yes ? I could use the cable to my blofeld ?
Comment: @Tim I see,I did send a email, but waiting for the reply. Thanks for you answers !
Answer: The Waldorf Blofeld requires a "tip positive" DC barrel connector supplying 12 Volt at least at 500 mA. The mains should only connect connect to a step down transformer and rectifier to convert it from 250 Volts AC to 12 Volts DC. Only use the mains PlayStation cable to the mains transformer.
Comment: OP says the socket on the keyboard is figure of eight. That's mains only, not DC. I thought it was a DC socket, but comment says no.
Answer: User-available electric connections are generally engineered not to fit if they are not supposed to be connected.
Exceptions do exist, but your device has 100-240v range exactly not to be an exception.
So if it fits, plug (and play).


Using multithreading to get continuous beep sound

Question: I'm trying to create a program in C++ where I play a beep sound, with a frequency and duration of the user's choice.
The program needs to continue running while playing the beep sound.
I figured out I should use multi-threading for this, but I don't have any experience with this.
For example, this is a simple program, but I get an error when I use _beginthread:
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <process.h>

using namespace std;

int freq = 0;
int sec = 0;
int mil = 0;

void beepTone(int freqq, int mill)
{
    Beep(freqq, mill);
    _endthread();
}

int main()
{
    cout << "Frequency?" << endl;
    cin >> freq;
    cout << "Duration?" << endl;
    cin >> sec;
    mil = 1000 * sec;
    _beginthread(beepTone(freq, mil), 0, NULL);
    cout << "Test Threading";
    return 0;
}

Argument of type "void(*)(int freqq, int mill)" is incompatible with parameter of type "_beginthread_proc_type"

I think the point of this testing program is pretty clear.
I have code that runs, but in this code I can't choose my own frequency and duration:
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <process.h>

using namespace std;

void beepTone(void *arg)
{
    Beep(1000, 3000);
    _endthread();
}

int main()
{
    _beginthread(beepTone, 0, NULL);
    cout << "Test Threading";
    cin.get();
    return 0;
}

This one plays 1000Hz for 3 sec while continuing the program.
Can anyone help me on how can I tell the thread which frequency and duration to play?
Comment: can you use c++11; or must it be c++98?
Comment: vs2017 supports C++11, so you can use standard facility `` instead of function like `_beginthread`.
Comment: It don't have to be c++98 specific, but to be honest I have no idea what the difference is between those two you said, and how to change between them..
If it can help you, I'm working with visual studio 2017 and i start my programs by just creating a new c++ project. So everything is in standard settings I guess.
Comment: Thank you for the quick respons, but i'm not totally getting how i should implement the  in my code.
Like I said, I'm totally new to threading..
Comment: `_beginthread` is a C function. It expects a specific signature for the thread function pointer. You violate that contract. C++11 introduced threading into C++. C++ threads allow you to pass *any* function as a thread function. Visual Studio 2017 supports C++17, so you can take advantage of the C++ [threads](http://en.cppreference.com/w/cpp/thread).
Answer: Your first example fails to compile because you are actually calling beepTone() and then trying to pass its void return value to the start_address parameter of _beginthread(), which will not work.  You need to pass beepTone() itself to that parameter, not its return value.
Your second example is correctly passing beepTone() itself to _beginThread(), but is not passing any data to beepTone().
Now, to accomplish what you want, _beginthread() has an arglist parameter that you can use to pass user data to your thread function.  That is what you need to use to send your beep values to the thread so it can then pass them to Beep().
Try something like this:
#include "stdafx.h"
#include <Windows.h>
#include <process.h>
#include <iostream>

using namespace std;

struct beepParams
{
    int freq;
    int mil;
};

void __cdecl beepTone(void *arg)
{
    beepParams *params = static_cast<beepParams*>(arg);
    Beep(params->freq, params->mil);
    delete params;
    _endthread();
}

int main()
{
    int freq = 0, sec = 0, mil = 0;

    cout << "Frequency?" << endl;
    cin >> freq;
    cout << "Duration?" << endl;
    cin >> sec;
    mil = 1000 * sec;

    beepParams *params = new beepParams;
    params->freq = freq;
    params->mil = mil;

    if (_beginthread(&beepTone, 0, params) == -1)
        delete params;

    cout << "Test Threading";
    //...
    cin.get();

    return 0;
}

That being said, if you are using C++11 or later, consider using std::thread instead:
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <thread>

using namespace std;

struct beepParams
{
    int freq;
    int mil;
};

void beepTone(beepParams params)
{
    Beep(params.freq, params.mil);
}

int main()
{
    int freq = 0, sec = 0, mil = 0;

    cout << "Frequency?" << endl;
    cin >> freq;
    cout << "Duration?" << endl;
    cin >> sec;
    mil = 1000 * sec;

    beepParams params;
    params.freq = freq;
    params.mil = mil;

    thread t(beepTone, params);
    t.detach();

    cout << "Test Threading";
    //...
    cin.get();

    return 0;
}

Comment: Well. Son of a gun. I finally get a chance to sit down and answer this one and you beat me by about 20 seconds.
Comment: The first example is missing a calling convention on the thread procedure definition.
Comment: @IInspectable the calling convention of the thread procedure in `_beginthread()` is `__cdecl`. Most C/C++ compilers default to `__cdecl` when a calling convention is not explicitly stated. Obviously, if you configure the compiler's default to be something other than `__cdecl` then you need to state the calling convention explicitly so it matches the expected definition.


Infinite sub-sequences that make up a sequence

Question: A sequence $\{a_n\}$ can be broken into sub-sequences, $\{a_n\}^1_{k_1}, \{a_n\}^2_{k_2}, \dots,\{a_n\}^m_{k_m}$, if every element in $\{a_n\}$ belongs to at least one of the sub-sequences.
I had to prove that if all these sub-sequences converge to $L_1, L_2, \dots , L_M$ correspondingly, then these are $all$ the possible partial limits of $\{a_n\}$.
Now, if the number of sub-sequences is finite, there is no problem.
Assume there is another limit, $L\notin \{L_1, L_2, \dots , L_M\}$.
Say $L_1, L_2, \dots , L_M$  are ordered, such that $L_1< L_2< \dots < L_M$. So there is an $1\le i \le m$ such that $L_i<L<L_{i+1}$.
Choose $\epsilon=\frac 1 2 min\{|L_2-L_1|,|L_3-L_2|,\dots, |L-L_i|, |L_{i+1}-L| ,\dots, |L_m-L_{m-1}|\}$.
For every $l$, there exists a $K_l$ such that for every $k>K_l$, $|a_{n_{k_l}}-L_l|<\epsilon$. Choose $N=max\{K_1, K_2, \dots, K_m\}$.
So, for every $n>N$ we get that all the elements of all the sub-sequences are in disjoint surroundings of their limits. There is also an infinite number of elements of the sequence $\{a_n\}$ in the $\epsilon$ surrounding of $L$, since $L$ is a partial limit. But $L$ is in a disjoint surrounding so for $n>N$ there are no elements of the sub-sequences in the $\epsilon$ surrounding of $L$. But by the definition written above, every element of $\{a_n\}$ is found in at least one of the sub-sequences. Contradiction.
But this bothers me - what if there is an infinite number of sub-sequences. Then $L$ might not have an infinite number of elements from some sub-sequence in its $\epsilon$ surrounding, but each sub-sequence could have one element in the $\epsilon$ surrounding of $L$, and still $L$ can be a partial limit of $\{a_n\}$ since there is an infinite number of elements in its surrounding.
What do you think?
Answer: The result does not hold in general when the given family of subsequences is infinite.
For each positive integer $n$ there is a unique pair $\langle k,m\rangle$ of non-negative integers such that $n=2^k(2m+1)$. Define a sequence $\sigma=\langle a_n:n\in\Bbb Z^+\rangle$ by setting
$$a_{2^k(2m+1)}=\begin{cases}
-1,&\text{if }m\le k\\
k,&\text{if }m>k\;.
\end{cases}$$
For each $k\in\Bbb N$ the subsequence $\sigma_k=\langle a_{2^k(2m+1)}:m\in\Bbb N\rangle$ converges to $k$, and every term of $\sigma$ is in exactly one of the subsequences $\sigma_k$ for $k\in\Bbb N$. Thus, the set of limits of these subsequences is precisely $\Bbb N$. However, each term of the subsequence $\langle a_{2^k}:k\in\Bbb N\rangle$ of terms $a_{2^k(2m+1)}$ for which $m=0$ is $-1$, so this subsequence converges to $-1\notin\Bbb N$.


Linking image field to an external URL

Question: I have a list of images on my node that I want to output wrapped in an anchor tag for linking to external webpages. Images are coming from fields in my content type. I'm not using the Views or the Panels module, and I've edited my page.tpl.php and node.tpl.php files for a rather intricate "About Us" page.
So how do I do this? I'm using Drupal 7.
Answer: You can create a custom field formatter (theme function for fields) where you can define how the image field should be rendered. Here you can add the a tag or any other special markup.
There are a lot of guides on how to do this, both here on the site and on the web, so I won't go into details about how to create a field formatter here, but it's nothing more than a few hooks and a theme function.
Answer: If you want to have the option to add a url to each image, there's a module Link Image Field for that. The port to Drupal 7 is not yet finished however (but it looks like there's working code).
Answer: This is an updated answer to this question, not just for the original post as it was posted a year ago.
To perform this feature in Drupal 7, the module Image Link Formatter fits perfectly:

This module is the result of the discussions around a requested feature to allow an image field to be displayed with a link to a custom URL

Linking image field to an external URL


What do Spain get for winning Euro 2012?

Question: So Spain, the winners of Euro 2012, now have a UEFA Trophy in their hands and a handful of winners medals for good measure.
But, are there any additional benefits/ prizes of winning the European Cup?
Answer: Spain won €23 million according to the following calculation:

€8m fixed for playing in UEFA EURO 2012.
€0.5m for the draw against Italy.
€1m for winning the game against Ireland.
€1m for winning the game against Croatia.
€2m for participating in the quarter-final against France.
€3m for participating in the semi-final against Portugal.
Finally, €7.5m for winning UEFA EURO 2012.

Participating teams at the UEFA EURO 2012 final tournament will pay
  the fixed participation contribution fee per team of €8m. Further, a
  performance bonus at the group stage of €0.5m per draw and €1m per win
  was fixed, as well as a bonus of €1m to the third-placed team in the
  group. The quarter-finalists will each receive €2m, the semi-finalists
  €3m, the runners-up €4.5m and the winners of UEFA EURO 2012 €7.5m.
  Thus the total amount available for distribution is €196m (up from
  €184m for UEFA EURO 2008).

Source
Answer: In addition to the financial benefits detailed in Dor Cohen's answer, Spain also achieved:
Fifa World Ranking Points
Spain will have picked up a considerable number of Fifa World Ranking points by winning this tournament and via the manner in which they did so.  With continental cup tournaments carrying a 3.0x multiplier, Spain will have further cemented their World #1 status.
Source
Record
This is the first time in history that a team has won 3 back-to-back major tournaments, those being:

UEFA Euro 2008
Fifa World Cup 2010
UEFA Euro 2012

I wouldn't be too surprised if they made it four at the 2014 World Cup.
Prestige
All in all, what may matter more than any financial or statistical benefit is that the team can say they are the best.


Proving, that $\text{Arg}(-i\sin(x))=\pi/2\text{sgn}(x)$ on $(-\pi,\pi)$

Question: Alright. I thought, that $\text{Arg}(-i\sin(x))=3\pi/2$, however, the Wolfram Alpha tells a different story. I am sure that it must be kind of true, because $\text{Arg}(\sin(x))$ is the result of sum of $\sum_{n=0}^\infty\frac{\sin((2n+1)x)}{2n+1}$, which is a fourier series of the sign function. But I have a little problem proving this fact.
Comment: What's your $x$? Real? Complex?
Comment: See https://en.wikipedia.org/wiki/Atan2#Definition_and_computation
Comment: @Vim: Would $\text{sgn } x$ make sense for non-real $x$?
Comment: I don't know. But since what you want to know I the first place is $\sin$ instead of $\text {sgn}$ so I think it makes no difference.
Comment: The problem resides in the range of $\arg$: do you take it to be $[-\pi, \pi)$, or $[0, 2\pi)$, or something else? Also, $\arg (- \textrm i \ \sin x)$ must depend on the sign of $x$, so it cannot be $\frac {3 \pi} 2$ as you write. Finally, your input to Wolfram Alpha does not contain $- \textrm i$. Quite many mistakes in such a short question.
Comment: Come on, @Vim, let's stop playing: the OP uses a Fourier series for $\arg \sin x$ - have you ever seen Fourier series for a complex variable? The whole post indicates a real variable.
Comment: @AlexM. I know little about Fourier :)  I suppose it is too trivial for real $x$, though.
Answer: This is true $\text{Arg}(-i\sin(x))=\frac{\pi}{2}\cdot \text{sgn}(x)$,  $x\in(-\pi,\pi)$
Recall that the principal argument $\text{Arg}(z)$ lies in the domain $-\pi<\text{Arg}(z)\le \pi$.
Setting $y=\sin x$, then $y \in [-1,1]$. Note that  $z=-iy$  is a pure imaginary complex  number, and the sign of the imaginary part is $\pm$ (liying on the $y$-axis) depends on the sign of the number $y$. Thus,   $\text{Arg}(-iy)=\pm\frac{\pi}{2}=\frac{\pi}{2}\text{sgn}(x)$.
Answer: As noted in the comments there are some mistakes in the question, and I don't understand what the Fourier series have to do with the problem.
Anyway, we  have:
$$
-\pi<x<0 \Rightarrow \sin x<0 \Rightarrow -i\sin x =i |\sin x| \Rightarrow \mbox{arg}(i |\sin x|)=\frac{\pi}{2}
$$
$$
x=0 \Rightarrow \sin x=0 \Rightarrow -i\sin x =0 \Rightarrow \mbox{arg}(-i \sin x)=0
$$
$$
0<x<\pi \Rightarrow \sin x>0 \Rightarrow -i\sin x =-i |\sin x| \Rightarrow \mbox{arg}(-i |\sin x|)=-\frac{\pi}{2}
$$
so the correct result is:
$
 \mbox{arg}(-i \sin x)=-\frac{\pi}{2}\mbox{sgn}(x)
$ for $-\pi <x<\pi$.
Comment: $\sum_{n=0}^{\infty}\frac{\sin((2n+1)x)}{2n+1}=\lim_{r\to1+}\Im\int\sum e^{ix}r^ne^{i2nx}dx=\lim_{r\to1+}\Im\int\frac{e^{ix}}{1-re^{2ix}}dx=\Im( i\frac{1}{2}(\ln(1-e^{ix})-\ln(1+e^{ix})) ) =Arg\frac{1-e^{ix}}{1+e^{ix}}=Arg(\frac{-i\sin(x)}{1+\cos(x)})=Arg(-i\sin(x))$
and simultaneously
$K\text{sgn}(x)=\sum_{n=0}^{\infty}\frac{\sin((2n+1)x)}{2n+1}$ set the constant $K$ accordingly so that the equality holds. Don't have the time to check it.


Are more features always better?

Question: Was discussing with a friend: suppose we have one model that uses 1,000 features and another that uses 100,000 features.  Assuming their first 1,000 features are the same, shouldn't the one with 100,000 features always do at least as well as the 1,000 feature model?
I say this because, if there's a correlation between an additional feature and the target variable, it can learn this.  If there's no correlation, the model should learn to ignore.  So more features should always be at least as good as a model with only a subset of the same features.
My friend claims features can actively hamper model performance so that more isn't always better...how is this possible?
Thanks!
Comment: Your friend is right.  Irrelevant features allow models to mistake noise for signal.  Read about bias and variance.
Comment: Have you considered the [p>>n problem or the curse of dimensionality?](https://stats.stackexchange.com/questions/10423/number-of-features-vs-number-of-observations)
Answer: It depends on what you want your model to achieve.  Are these features necessary to your model?  For example, gene expression dataset usually have 10000 features (one for each gene), but they are all usually necessary to help determine significant genetic pathways.  If the features are not helpful, then a small feature size that provides a similar accuracy to a model with a large feature is always more helpful because performance increases in terms of obtaining classification/regression results faster.
Too many features is often a bad thing. It may lead to overfitting, which makes your model specifically fit to your data, and makes the model perform horribly with another dataset.  Another thing to note is that a larger feature usually requires a larger sample size, otherwise you will also be doing a lot of regularization.
That is why there is are lot of research papers in the field of feature reduction.
Answer: The probability of a spurious feature-target correlation in the training set is small, but nonzero. So, we use a test set.  The probability of a spurious feature-target correlation in the training set that also holds in the test set is even smaller.  However, with each new feature (hypothesis), you increase the risk that this occurs.  It's worse with a small number of observations (and better with more).
But, say that your friend has the first 100 features and you have 1000 and you're trying to predict housing prices.  It may be that location is the 101$^{st}$ feature. There is something to be said for restricting the variance of the model while keeping all of the features---e.g., with shrinkage, dropout, or ensembles.
I think that the answer to your question is that more information is always better, but that it comes with a risk.
Comment: Brilliant answer, thank you! That's just it - information in the information-theoretic sense - rather than noisy, low-information signal.

Are more features always better?


Need help deleting kivy widgets

Question: I have two main files.py and demo.kv. When executing the add_item function, I add 4 widgets (Label - 3 and MDRaisedButton - 1) and they form a string.
I want some way to press the 'delete this' button in a row to delete that particular row.
I imagine I'd need some way to differentiate between these generated rows somehow but I haven't gotten that figured out yet either. I'd be extatic if someone had an elegant solution for this, as I've been stuck here for quite some time.
main.py
from kivy.lang import Builder
from kivy.core.window import Window

from kivymd.app import MDApp
from kivymd.uix.label import MDLabel
from kivymd.uix.button import MDRaisedButton

Window.size = (500, 600)

finalPrice = []

finalItems = []

finalCounter = []

class MainApp(MDApp):

    def build(self):
        self.theme_cls.primary_palette = 'Blue'
        return Builder.load_file('demo.kv')

    def add_item(self, name, price, counter):

        mdRB = MDRaisedButton(text='delete this')
        mdRB.bind(on_press=self.delete_mdRB)

        self.root.ids.basketItems.add_widget(
            MDLabel(text=name, adaptive_height=True, adaptive_width=True)
        )
        self.root.ids.basketItems.add_widget(
            MDLabel(text=price, adaptive_height=True, adaptive_width=True, width=60, size_hint_x=None)
        )
        self.root.ids.basketItems.add_widget(
            MDLabel(text=counter, adaptive_height=True, adaptive_width=True, width=120, size_hint_x=None)
        )
        self.root.ids.basketItems.add_widget(
            mdRB
        )

    def delete_mdRB(self):
        for child in [child for child in self.root.ids.basketItems.children]:
            self.root.ids.basketItems.remove_widget(child)

        finalPrice.clear()
        print(finalPrice)

        finalItems.clear()
        print(finalItems)

        finalCounter.clear()
        print(finalCounter)

if __name__ == '__main__':
    MainApp().run()

demo.kv
#:import Factory kivy.factory.Factory

<Bases@Popup>
    auto_dismiss: True
    title: 'Item'

    background_normal: ""
    background_color: (26/255, 149/255, 184/255, .9)

    ScrollView:
        size: self.size

        GridLayout:

            size_hint_y: None
            height: self.minimum_height
            width: self.minimum_width

            cols: 3

            size: root.width * 0.5, root.height * 0.5
            row_default_height: 35
            row_force_default: True
            center: root.width / 1, root.height / 1

            Label:
                text: ''
            Label:
                text: ''
            Button:
                text: 'Close'
                font_size: 12
                on_release: root.dismiss()

            Label:
                text: 'Name'
                font_size: 12
                text_size: self.size
                halign: 'left'
                valign: 'middle'

            Label:
                text: 'Кол-во'
                font_size: 12
                text_size: self.size
                halign: 'right'
                valign: 'middle'
            Label:
                text: 'Basket'
                font_size: 12

            Label:
                text: f'Item 1 290$'
                font_size: 12
                text_size: self.size
                halign: 'left'
                valign: 'middle'
            AnchorLayout:
                anchor_x: 'right'
                TextInput:
                    id: name_input
                    multiline: 'False'
                    width: 60
                    size_hint_x: None
            Button:
                text: '+'
                on_press:
                    app.add_item('Item 1', '290', name_input.text)

            Label:
                text: f'Item 2 250$'
                font_size: 12
                text_size: self.size
                halign: 'left'
                valign: 'middle'

            AnchorLayout:
                anchor_x: 'right'
                TextInput:
                    id: name_input2
                    multiline: 'False'
                    width: 60
                    size_hint_x: None
            Button:
                text: '+'
                on_press:
                    app.add_item('Item 2', '250', name_input2.text)

BoxLayout:
    orientation: 'vertical'

    MDToolbar:
        title: 'Store'

    MDBottomNavigation:

        MDBottomNavigationItem:
            name: 'Items'
            text: 'Main'
            icon: 'home'

            MDBoxLayout:
                orientation: 'vertical'
                pos_hint: {'center_y':0.5}
                adaptive_height: True
                spacing: 2

                MDRaisedButton:
                    text: 'Items'
                    pos_hint: {"center_x":.5}
                    width: dp(250) + (self.ids.lbl_txt.texture_size[0] - self.ids.lbl_txt.texture_size[0])
                    on_release: Factory.Bases().open()

        MDBottomNavigationItem:
            name: 'Basket'
            text: 'Basket'
            icon: 'basket'

            ScrollView:
                size: self.size

                GridLayout:
                    size_hint_y: None
                    height: self.minimum_height
                    width: self.minimum_width

                    size: root.width * 0.5, root.height * 0.5
                    row_default_height: 35
                    row_force_default: True
                    center: root.width / 1, root.height / 1

                    id: basketItems
                    cols: 4
                    spacing: 4

Answer: A Convenient way to do this is to put everything that you want to delete at one time into a single widget, so you can just delete that single widget. In your case, that single widget can be a BoxLayout that contains your three Labels and the Button. Then by using another BoxLayout instead of a GridLayout inside the ScrollView, each row can become a single BoxLayout. So changing the kv to use a BoxLayout:
    MDBottomNavigationItem:
        name: 'Basket'
        text: 'Basket'
        icon: 'basket'

        ScrollView:

            BoxLayout:
                orientation: 'vertical'
                size_hint_y: None
                height: self.minimum_height
                center: root.width / 1, root.height / 1
                id: basketItems
                spacing: 4

Then, the add_item() method can just add a BoxLayout to the basket and the delete_mdRB() can just delete that BoxLayout:
def add_item(self, name, price, counter):

    box = MDBoxLayout(adaptive_height=True)
    mdRB = MDRaisedButton(text='delete this')
    mdRB.bind(on_press=partial(self.delete_mdRB, box))  # pass the box to be removed

    box.add_widget(
        MDLabel(text=name, adaptive_height=True, adaptive_width=True)
    )
    box.add_widget(
        MDLabel(text=price, adaptive_height=True, adaptive_width=True, width=60, size_hint_x=None)
    )
    box.add_widget(
        MDLabel(text=counter, adaptive_height=True, adaptive_width=True, width=120, size_hint_x=None)
    )
    box.add_widget(
        mdRB
    )
    self.root.ids.basketItems.add_widget(
        box
    )

def delete_mdRB(self, box, button):
    box.parent.remove_widget(box)
    # for child in [child for child in self.root.ids.basketItems.children]:
    #     self.root.ids.basketItems.remove_widget(child)

    finalPrice.clear()
    print(finalPrice)

    finalItems.clear()
    print(finalItems)

    finalCounter.clear()
    print(finalCounter)

Need help deleting kivy widgets