Plot angles around $360^\circ$ (North)

Question: I want to plot wind angles. I typically have around 25 observations (the amount is not important here). I want to use a line chart to quickly see the trend (veering or backing) and the amount of oscillation. I also calculate statistics of the values.
Mostly this is trivial. But how to manage the situation when wind is around North?
E.g. I have observations 5, 10, 350, 345, 355, 0, 5. This produces a non-informative plot because the values are seemingly so separate although in reality they are not. Calculating average produces wrong result (153, the right should be 359).
OK, I get it right using negative values for the big numbers. (350 = -10)
Now the question: what kind of algorithm should i write to make a decision about when I need this value changing or is there another means to handle this?
Comment: And if your remaining question is about plotting the data, I'd recommend just plotting the angle against some arbitrary radius (in polar coordinates). No loss of information, and it has an obvious visual meaning.
Comment: Actually, I think I've answered a variation on this question previously. Please consider the following linke: [Average and standard deviation of timestamps (time wraps around at midnight)](http://stats.stackexchange.com/questions/114842/average-and-standard-deviation-of-timestamps-time-wraps-around-at-midnight) In particular, this presents a statistically-sound method for determining the mean value of circular data, which is also the location parameter of the von Mises distribution.
Comment: @user777 Some over-mathematical statistician just threw you in at the deep end. I once attended a lecture by a very famous geophysicist (later murdered, but that's another story) who kept flagging that you need different statistics when you have directions. A very famous statistician was sitting behind me and kept muttering "Just different spaces, otherwise nothing different". They were both right.
Comment: I'm far from being an expert in this are but here are some texts that may provide some guidance .. *The Analysis of Directional Time Series: Applications to Wind Speed and Direction* http://www.amazon.com/dp/0387971823/ref=wl_it_dp_o_pC_nS_ttl?_encoding=UTF8&colid=3E9G0WFO52DJG&coliid=I1ZMZF7ECEQQZ2   *Directional Statistics* http://www.amazon.com/dp/0471953334/ref=wl_it_dp_o_pd_S_ttl?_encoding=UTF8&colid=3E9G0WFO52DJG&coliid=I13MO0ODQVSJ4U
Comment: @user777 "a bit of a nightmare": I know that is jokingly put, and circular statistics are strange territory on first encounter. But circular statistics can be simpler than mainstream (e.g. outliers are rare as they have so little space in which to hide) and just as beautiful; trigonometry and geometry appear naturally and helpfully.
Comment: @NickCox But from my admittedly breif excursion, there are all sorts of divergent integrals and Bessel functions and all manner of perplexity to circular data! I completely understand the argument that when you have circular data, you should encounter it on its own terms, rather than forcing the round data into a square paradigm (to coin a phrase) -- it just requires a willingness to encounter a different paradigm that can be quite demanding! That's all I mean.
Answer: The question implies that you want a linear plot (and not a circular plot). That being so, a general principle that usually works is to rotate the scale so that the vector mean is at the centre. The vector mean is the arctangent of the ratio of the sum of sines to the sum of cosines. Some care is needed to catch the four-quadrant character of the calculation (not to mention the fact that most such data arrive in degrees and trigonometric routines commonly assume use of radian measure).
The vector mean for your example of $5, 10, 350, 345, 355, 0, 5$ degrees is $358.9^\circ$.
A direction close to the vector mean will often work just as well. For example, with one kind of circular data I work with, the vector mean is often close to North-East but, unsurprisingly, no law of nature makes that exact. A convention to put NE at the center of a scale is helpful, however. Let's spell out that it can be more helpful to choose a standard scale for a series of related graphs than to optimise each separately.
In the case of winds, winds from every direction at some time or another are likely in most topographic situations, although usually with different frequencies. (For a variety of reasons wind is rarely measured instrumentally on very steep slopes.) But note in particular that two modes opposite on the circle are possible in some cases, as when two modes are up-valley and down-valley winds (anabatic and katabatic), onshore or offshore, etc. In such cases, it can be best to avoid cutting the circle at a mode.
In general, two principles that usually do not contradict are

Put the vector mean at or near the middle of the scale.
Avoid cutting the scale (i.e. choosing the ends of the scale, which are necessarily identical) to cut a mode that is interesting or important.

One often cited example dataset in circular statistics concerns turtle migration between land and sea in which there are two modes for direction, and the usual wry comment is that evidently some of the turtles are confusing backwards and forwards. The same phenomenon has been observed in political science, although with different players.
Answer: Operating under the assumption than the period is 360 degrees, if the angle is greater than 180, subtract from 360. That should give you the right averages.
Comment: Could you please expand on this thought? It's not immediately clear why this will produce a correct answer to OP's question.
Comment: This is very unclear. Do you mean that $270^\circ$ should become $90^\circ$? If so, $90^\circ$ and $270^\circ$ are combined, which is usually not at all what is needed. If not, and you imply that $270^\circ$ should become $-90^\circ$, then that just moves angles from one side of the graph to the other. It doesn't do anything necessarily to make the graph more effective or easier to understand.
Comment: Following this recommendation, any set of angles fluctuating around 0 would be coded variously as values near 0 and other values just under 360, thereby averaging close to 180: just about as wrong as it possibly can be. This problem was specifically pointed out in the question itself. As a general principle, then, it seems like a poor choice.

Plot angles around $360^\circ$ (North)


Properties of Legendre/Cramer's transformation of the moment generating function

Question: Let $X \in L^1$ be a random variable on some probability space, define $M(\theta) \equiv E(e^{\theta X})$ as its moment generating function and let $D(M) \equiv \{\theta \in \mathbb{R} : M(\theta) < \infty\}$.  I'm reading a really toxic set of lecture notes which has the following lemma as an exercise and I cant find the same theorem online.  I'm having trouble proving bullet point (iii) in particular:

My attempt at a proof follows.  You may ignore bullet point (i) and (ii) if you wish, but they may be helpful:
For ease in notation I define $f_a(\theta) \equiv a\theta - \log(M(\theta))$
Bullet point (i): Note $f_a(0) = 0 \leq \sup_\theta f_a(\theta) = I(a)$, convexity follows easily since $\forall a, b \in \mathbb{R}$, $$(\lambda a + (1-\lambda)b)\theta - \log (M(\theta)) = \lambda (a \theta - \log(M(\theta))) + (1-\lambda)(b\theta - \log (M(\theta))) \leq \lambda I(a) + (1-\lambda)I(b)$$ and we can take the supremum of the LHS over $\theta$.
We also have, by the convexity of $-\log(x)$ and Jensen's inequality, $$-\theta \mu = E(-\log(e^{\theta X})) \ge -\log(E(e^{\theta X})) = -\log (M(\theta))$$  Rearranging gives $f_\mu(\theta) \leq 0$ for all $\theta$ (trivially for $\theta$ such that the mgf is infinite) so that the supremum $I(\mu) \leq 0$.  Lastly, we see that for each $b \leq a \leq \mu$, we have the existence of a $\lambda \in [0,1]$ so that $a = \lambda b + (1-\lambda)\mu$.  From convexity, non-negativity and the fact that $I(\mu) = 0$, it is immediate that $I(a) \leq \lambda I(b) \leq I(b)$.  The identical set of ideas works for $\mu \leq a \leq b$
Bullet point (ii):  For $a \ge \mu$, and any $\theta < 0$, we have trivially $f_a(\theta) \leq f_\mu(\theta) \leq 0$ from bullet point (i).  The conclusion is trivial from here, and a similar set of inequalities is true for the other case.
Bullet point (iii):  This is where I am lost.  I know that $M'(\theta)$ exists $\forall \theta \in \mathbb{R}$ since $X \in L^1$ (for those who are unaware of how to prove this, simply find an appropriate dominating function for the difference quotient and apply dominated convergence), and moreover $M'(\theta) = E(Xe^{\theta X})$.  So for the last part of (iii), we can note that $f_a(\theta)$ is concave in $\theta$ and differentiable so that any critical point is a global maximum.  Thus, it suffices to find $\theta$ so that (just take the derivative and set to 0) $$a - \frac{M'(\theta)}{M(\theta)} = 0$$
This would actually solve the whole question, as it will show that we have a convex function that is finite at every point in $\mathbb{R}$ (and thus finite on any open interval $(a,b)$) and is thus continuous (see here for example for a proof of this fact: Proof of "every convex function is continuous").  I just need help with the existence of such a $\theta$.  Please help if you can!
(As a sidenote, the fact that this is an exercise in a set of lecture notes is genuinely utterly cruel)
Comment: for a different look at the convexity of the cumulant, you may enjoy  https://math.stackexchange.com/questions/600908/convexity-of-log-of-moment-generating-function
Comment: Are these lecture notes available online? If yes, would you mind giving a link to the lecture notes? Thanks!
Answer: Here is the proof that for any given $a$, if we define
$$g(\theta) = \frac{\mathbb{E_\mu}[X e^{\theta X}] }{ \mathbb{E_\mu} [e^{\theta X} ] }$$
there exists $\theta^*$ s.t. $g(\theta^*) = a$.
First, here is the intuition: You are given that X ~ $\mu$ and $\mu$ has full support on $\mathbb{R}$. You can consider $a$ as the expectation of $X$ under the measure $\mu_\theta$ where :
$$ d \mu_\theta = \frac{e^{\theta x}}{\mathbb{E_\mu}[e^{\theta X}] } d \mu $$
First, note that this measure is well defined for all $\theta$ since your MGF is finite for all $\theta$. As $\theta$ grows, this measure puts more and more mass on larger values, so eventually, under this measure, the expectation will arbitrarily grow. (Provided that $\mu$ puts mass on these large values, which is how we will use that full support condition) We can play the same game with negative $\theta$s, and we will show that you can get $g(\theta)$ to be arbitrarily large and small. Since $g(\theta)$ is continuous, intermediate value theorem will give you the result.
Now, let's do it rigorously:
Let $M$ be large. We know that $\mu(X \geq M) = \epsilon$ for some $\epsilon > 0$ since $X$ has full support on $\mathbb{R}$.
We also have that $$\lim_{\theta \rightarrow \infty} \mathbb{E_\mu}[X e^{\theta (X-M)} 1_{X < M} ] = 0$$ by dominated convergence theorem, so there exists a $\theta_1$ s.t.  $|\mathbb{E_\mu}[X e^{\theta_1 (X-M)} 1_{X < M} ]| < \epsilon$
We also have by a similar argument a $\theta_2$ s.t. $|\mathbb{E_\mu}[ e^{\theta_2 (X-M)} 1_{X < M} ]| < \epsilon$
In what follows, let $\theta = \max(\theta_1, \theta_2)$
$$ \frac{\mathbb{E_\mu}[X e^{\theta X}] }{ \mathbb{E_\mu} [e^{\theta X} ] } = \frac{\mathbb{E_\mu}[X e^{\theta X} 1_{X \geq M} ]  }{ \mathbb{E_\mu} [e^{\theta X} ] } + \frac{\mathbb{E_\mu}[X e^{\theta X} 1_{X < M} ]}{ \mathbb{E_\mu} [e^{\theta X} ] }$$
For the first term, we have that $\frac{\mathbb{E_\mu}[X e^{\theta X} 1_{X \geq M} ]  }{ \mathbb{E_\mu} [e^{\theta X} ] } \geq \frac{ M \mathbb{E_\mu}[ e^{\theta X} 1_{X \geq M} ]  }{ \mathbb{E_\mu} [e^{\theta X} ] } = \frac{ M \mathbb{E_\mu}[ e^{\theta X} 1_{X \geq M} ]  }{ \mathbb{E_\mu}[ e^{\theta X} 1_{X \geq M} ] + \mathbb{E_\mu}[ e^{\theta X} 1_{X < M} ] }$
Now, let's divide top and bottom by $\mathbb{E_\mu}[ e^{\theta X} 1_{X \geq M} ]$. Note that we can do this because $\mu$ has full support. We get
$$\frac{M}{1 + \frac{\mathbb{E_\mu}[ e^{\theta X} 1_{X < M} ]}{\mathbb{E_\mu}[ e^{\theta X} 1_{X \geq M} ]}}  =  \frac{M}{1 + \frac{\mathbb{E_\mu}[ e^{\theta (X - M) } 1_{X < M} ]}{\mathbb{E_\mu}[ e^{\theta (X - M)} 1_{X \geq M} ]}} > \frac{M}{2}$$.
where for the last inequality we note that $\mathbb{E_\mu}[ e^{\theta (X - M)} 1_{X \geq M} ] \geq \epsilon$ since $e^{\theta (X - M)} \geq 1$ when $X \geq M$.
The second term is thankfully easier; we divide top and bottom by $e^{\theta M}$
$$\frac{\mathbb{E_\mu}[X e^{\theta (X - M)} 1_{X < M} ]}{ \mathbb{E_\mu} [e^{\theta (X-M)} ] } \geq -1$$
where again we invoke the fact $\mathbb{E_\mu} [e^{\theta (X-M)} ] > \epsilon$.
Now, we are done, since we showed that for an arbitrary $M$, there exists a $\theta$ s.t. $g(\theta) > M/2 - 1$. We can play the same game with $-M$ which gives us another $\theta'$ s.t. $g(\theta) < -M/2 + 1$, which completes the proof by continuity of $g$ and intermediate value theorem.
Comment: That's two of my questions you're answering today; really awesome!  I should really be able to think on these things and get them myself at this point - I have no idea how I'm going to ever do my own research
Comment: I will put this chat link here: https://chat.stackexchange.com/rooms/111003/sharing-grad-student-struggle-with-another-grad-student so that you can ping me for particularly important questions (TBH I don't really know how chat works on stackexchange).; let me know if this does not work.
Comment: I'm so sorry I never replied to this - I completely forgot.  The link unfortunately doesn't work at the moment (I'm not sure if it did but now doesn't since it's been too long).  Either way, thanks again for your help on this problem.
Answer: It is enough to use strict convexity, shift properties and quadratic approximations of cumulant generating function, all of independent interest.
Define it as $\psi_X(\theta)\triangleq \log \mathbf{E}\mathrm{e}^{\theta X}$, Hoelder's Inequality implies
: $$ \mathbf{E}\mathrm{e}^{p_1\theta_1 X_1+p_2\theta_2X_2}\leqslant  \left(\mathbf{E}\mathrm{e}^{\theta_1 X}\right)^{p_1} \cdot \left(\mathbf{E}\mathrm{e}^{\theta_2 X}\right)^{p_2}
$$
for positive $p_1,p_2$ such that $p_1+p_2=1$ and any $\theta_1\not=\theta_2$, thus by taking the logarithm we obtain that $\psi(\cdot)$ is convex. The equality happens when $\mathrm{e}^{\theta_1X}\propto \mathrm{e}^{\theta_2X}$, equivalently when $X$ is constant a.e.
As for the quadratic approximation, take $x_0$ such  $\mathbf{P}\{X>x_0\}>0$ (e.g. median). By $\mathrm{e}^{t}\geqslant 1+t+\frac{\max(t,0)^2}{2}$ we get
$$
\psi(\theta) = \theta x_0 + \log\mathbf{E}\mathrm{e}^{\theta(X-x_0)} \geqslant \theta x_0 + \theta\mathbf{E} (X-x_0) + \frac{v\theta^2}{2} = \theta\mathbf{E}X+\frac{v\theta^2}{2},
$$
for some constant $v$ (we can take $v =\mathbf{E}(X-x_0)^2\mathbb{I}\{X>x_0\}>0$).
Now, assuming $X$ is not constant, we deal with the function
$$
f_a(\theta) = \theta a - \psi_X(\theta) = -\psi_{X-a}(\theta),
$$
which is strictly concave (by the first fact) and falls to negative infinity at both infinities (majorized by $O(t)-\frac{t^2v}{2}$ due to the second fact). So it has a unique global maximum.
Since we know that the first derivative exists, the global unique maximizer $\theta$ satisfies
$$
0=\frac{\partial f_a(\theta)}{\partial \theta} = a-\frac{\partial \psi_X(\theta)}{\partial \theta},
$$
as claimed.


Expectation of log skew normal distribution

Question: What is the expected value and expected variance of a log skew normal distribution?
In case I have the terminology wrong, I'm referring to data that is lognormal with some skew mild skew when it's log transformed so it would have params y ~ logskewnormal(loc, scale, alpha).
edit: Got a great answer from JimB, code below to reproduce the expected value of the mean!
<code>import numpy as np
import scipy.stats as stats
from scipy.special import erf, erfc

a, mu, sig = 1.1, 3.9, 1.25
skewnorm_dist = stats.skewnorm(a=a, loc=mu, scale=sig)

exp_mu_hat = []
for _ in range(10000):
    X = skewnorm_dist.rvs(1000)
    Y = np.exp(X)
    exp_mu_hat.append( Y.mean() )

print( np.mean(exp_mu_hat) )

term1 = np.exp(mu + 0.5*(sig**2))
term2 = erf((a*sig) / (np.sqrt(2) * np.sqrt(a**2 + 1))) + 1
exp_mu = term1*term2
print(exp_mu)
</code>
Comment: If the distribution of a random variable is skewed after you take a log transformation it wasn't lognormal to begin with
Comment: How would you suggest parameterizing it then? You are right, it is skewed after taking a log transform, but fitting that skewed log transformed data with a skew normal distribution does lead to a data generating process that pretty closely matches my data
Comment: @Glen b: He thinks about the exp of the skew Normal distribution: https://web.williams.edu/Mathematics/sjmiller/public_html/342/handouts/LinStoyanov_LogSkewNormalDistrAreMomentIndeterminate.pdf
Comment: Thanks, the question was previously not clear that this is was what was sought.
Answer: I wonder if you mean the following:
If $X\sim N(\mu,\sigma^2)$, then $Y=e^X$ has a log normal distribution.
So if $X\sim \text{SkewNormal}(\mu,\sigma,\alpha)$, then are you really interested in $Y=e^X$?
If so and the pdf of $X$ is defined to be
$$\frac{\sqrt{\frac{2}{\pi }} e^{-\frac{(\mu -\log (x))^2}{2 \sigma ^2}} \Phi \left(\frac{\alpha  (\log (x)-\mu )}{\sigma }\right)}{\sigma  x}$$
then the mean and variance are
$$\mu_Y=2 e^{\mu +\frac{\sigma ^2}{2}} \left(1-\Phi \left(-\frac{\alpha  \sigma }{\sqrt{\alpha ^2+1}}\right)\right)$$
$$\sigma^2_Y=2 e^{2 \mu +\sigma ^2} \left(e^{\sigma ^2} \left(1-\Phi \left(-\frac{2 \alpha  \sigma }{\sqrt{\alpha ^2+1}}\right)\right)-2 \left(1-\Phi \left(-\frac{\alpha  \sigma }{\sqrt{\alpha ^2+1}}\right)\right)^2\right)$$
where $\Phi(.)$ is the cdf of the standard normal distribution.
Comment: You're correct in your assumptions! Thanks for forwarding that bit on the error function I have yet to come across one. I just simulated it out and your formula matches up perfectly with monte carlo simulations, thank you! Adding in the Python code to my post for anyone interested in learning (only simulated the mean but they should get the point)

Just curious but how did you derive these formulas?
Comment: I'll modify the answer to align with the notation I use the most:  the cdf of the standard normal distribution:  $\Phi()$.


factory isnt recognized by controller

Question: I have a controller, "ListController", which needs to be populated with server side data.
app.controller("ListController", function(){
  var bar = this;
  bar.venues = MyFactory.load();
}

and I wanted to get the json array from the server, so i was thinking to create a factory leveraging "$http" as such:
app.factory("MyFactory", ["$https", function($https){
  var myService = {};
  myService.load = function(){
    $http.get("scripts/Query.php").success( function(rows){
      myService.rows = rows;
      return myService.rows;
    };
  };
  return myService;
}]);

So, i was thinking that MyFactory would be able to be called from inside the app controller.
app is the same variable, of type:  angular.module("BarMe", []);
The error i get in my javascript is:  MyFactory is undefined
Answer: You didn't inject factory in your controller.
Try like this
app.controller("ListController", function(MyFactory){

}

More over your method has a callback direct assign won't bring you any data
Try like this
MyFactory.load().then(function(data){
  bar.venues = data;
});

You also have to return $http with response from factory
myService.load = function(){
   return $http.get("scripts/Query.php").success( function(rows){
      return rows;
    };
  };

Comment: i have it setting myService.rows = rows, and then returning essentially rows.   Kinda redundant.    So, the success i was having `return  rows;` but it seems that it still gives me an injector error for MyFactory
Comment: can you provide your fullcode with html ?? it'll be better if you can provide jsfiddle
Comment: Oh, i seemed to get it working.  Your way worked.  It seems like i was having issues like you said.  I thought i mightve not needed the "then" function.  Thanks!

factory isnt recognized by controller


How to extract data out of a specific PHP array

Question: I have a multi-dimensional array that looks like this:
The base array is indexed based on category ids from my catalog.
$cat[category_id]

Each base array has three underlying elements:
['parent_id']
['sort_order']
['name']

I want to create a function that allows us to create a list of category_id's and names for a given parent_category_id in the correct sort order.  Is this possible?  Technically it is the same information, but the array is constructed in a weird way to extract that information.
Here is an example definition for the array:
$cat = array();
$cat[32]['parent_id']= 0;
$cat[32]['sort_order']= 1;
$cat[32]['name']= 'my-category-name1';
$cat[45]['parent_id']= 0;
$cat[45]['sort_order']= 0;
$cat[45]['name']= 'my-category-name2';
$cat[2]['parent_id']= 0;
$cat[2]['sort_order']= 2;
$cat[2]['name'] = "my-category-name3";
$cat[3]['parent_id']= 2;
$cat[3]['sort_order']= 1;
$cat[3]['name'] = "my-category-name4";
$cat[6]['parent_id']= 2;
$cat[6]['sort_order']= 0;
$cat[6]['name'] = "my-category-name5";

Comment: Could you please provide a more complete example of your array? (best with `var_export`).
Comment: If sort_order is numeric and unique for any set of categories at the same level in the heirarchy, use that to index the array... Otherwise this is a standard recursive parent->child array building.
Comment: Arrays and array functionality in PHP are very flexible. However, I don't understand your array structure. Can you print_r() your array? If you put the output between a pre tag, it would show up very nicely:

Comment: @ChristianSciberras: `'.print_r($yourArray,1).'';?>` seems more elegant, no? ;-)
Comment: @Brad - But more code intensive, and less IDE-friendly (the IDE can't know about the pre inside the string ;)
Answer: Assuming it's something of this sort:
$ary = Array(
  0 => Array(
    'parent_category_id' => null,
    'sort_order' => 0,
    'name' => 'my-category-name0'
  ),
  1 => Array(
    'parent_category_id' => 0,
    'sort_order' => 1,
    'name' => 'my-category-name1'
  ),
  2 => Array(
    'parent_category_id' => 0,
    'sort_order' => 2,
    'name' => 'my-category-name2'
  ),
  3 => Array(
    'parent_category_id' => null,
    'sort_order' => 0,
    'name' => 'my-category-name3'
  ),
  4 => Array(
    'parent_category_id' => 3,
    'sort_order' => 0,
    'name' => 'my-category-name4'
  )
);

You can use a combination of a foreach and usort to achieve what you're going for.
// @array: the array you're searchign through
// @parent_id: the parent id you're filtering by
function getFromParent($array, $parent_id){
  $result = Array();
  foreach ($array as $category_id => $entry){
    if ($entry['parent_category_id']===$parent_id)
      $result[$category_id] = $entry;
  }
  usort($result,create_function('$a,$b','return ($a["sort_order"]>$b["sort_order"]?1:($b["sort_order"]<$a["sort_order"]?-1:0));'));
  return $result;
}

var_export(getFromParent($ary,0));

EDIT Sorry, fixed some syntax errors. Tested, and works (at least to result in what I was intending)
EDITv2 Here's the raw output from the above:
array (
  0 =>
  array (
    'parent_category_id' => 0,
    'sort_order' => 1,
    'name' => 'my-category-name1',
  ),
  1 =>
  array (
    'parent_category_id' => 0,
    'sort_order' => 2,
    'name' => 'my-category-name2',
  ),
)

(Used var_export just for you @FelixKling)
EDITv3 I've updated my answer to go along with the OP's update. I also now make it retain the original "category_id" values in the result array.
Answer: First you create an empty array, it will be used to store your result.
$result = array();

You need to iterate through your initial array, you can use foreach().
Then, given your parent_category_id simply use an if statement to check whether it's the given id or not.
If it is, just construct and push your result to your $result array.
Use any of the sort functions you like
Use the magic return $result;
You're done.
Answer: function returnSortedParents($categories, $target_parent){

    $new_list = array();

    foreach($categories as $index => $array){
        //FIND ONLY THE ELEMENTS MATCHING THE TARGET PARENT ID
        if($array['parent_category_id']==$target_parent){
            $new_list[$index = $array['sort_order'];
        }

    return asort($new_list);  //SORT BASED ON THE VALUES, WHICH IS THE SORTING ORDER
}


How to show a series is conditionally convergent

Question: $a_k=\begin{cases}\frac{1}{(k-1)^2} - \frac{1}{k}, n \text{ is odd }\\ \frac{1}{k-1} - \frac{1}{k^2}, k \text{ is even }\end{cases}$
I have to show the series is conditionally convergent, i.e; the series itsrlf is convergent but not absolutely.
I'm really unable to show how to prove this. I mean I even tried at least to show that the series isn't absolutely convergent but there are only $2$ test in my book to check absolutely convergent, namely root test, ratio test, but by using these two I fail to conclude anything, even how to show the series is infact convergent?
I'm requesting please I want details solution in this case, please give me answer in answer section rather comment, it would be great help.
Thanks in advance.
Answer: If $\sum |a_n| <\infty$ then $\sum |a_{2n}| <\infty$. But $\sum |a_{2n}|=\sum (\frac 1 {2n-1} -\frac 1 {4n^{2}})=\infty$ because  $\sum \frac 1 {2n-1}=\infty$ (by comparison with the harmonic series)  and $\sum \frac 1 {4n^{2}}<\infty$. Hence the series is not absolutely convergent.
Conditional convergence  is very easy and you can do it yourself. Write down the partial sums explicitly. You see lots of cancellations and you will get the parial sums in the form $s_n=1+c_n$ with $c_n \to 0$. (I will let you write down what exactly $c_n$ is). Hence $\sum a_n$ converges with sum $1$.


A question on the Euler prime of odd perfect numbers

Question: A number $N \in \mathbb{N}$ is said to be perfect if $\sigma(N)=2N$, where $\sigma=\sigma_{1}$ is the classical sum-of-divisors function.  For example, $\sigma(6)=1+2+3+6=2\cdot{6}$, so that $6$ is perfect.  (Note that $6$ is even.)
It is currently unknown whether there are any odd perfect numbers.  Euler proved that an odd perfect number, if any exists, must take the form $N = q^k n^2$ where $q$ is prime satisfying $q \equiv k \equiv 1 \pmod 4$ and $\gcd(q,n)=1$.  We call $q$ the Euler prime of the odd perfect number $N$.
In what follows, we denote the abundancy index of $x \in \mathbb{N}$ as $I(x)=\sigma(x)/x$.
MOTIVATION
Since the non-Euler part $n^2$ is deficient but not almost perfect, we know (from this preprint) that
$$I(n^2) < \frac{2n^2 + D(n^2)}{n^2 + D(n^2)},$$
where $D(n^2)={2n^2}-\sigma(n^2)$ is the deficiency of $n^2$.
When the Descartes-Frenicle-Sorli conjecture that $k=1$ is true, we also know that we have the lower bound
$$\frac{5}{3} \leq I(n^2),$$
whereupon we obtain, from the last two inequalities, the following lower bound
$$\frac{n^2}{D(n^2)} > 2.$$
(When $k=1$, ${n^2}/D(n^2)=(q+1)/2$, so that ideally we should have ${n^2}/D(n^2) \geq 3$ since $q \geq 5$.)
From the following Answer 1 and Answer 2 to a related MSE question, we obtain improved upper bounds for $I(n^2)$ by successively computing the mediant of
$$I(n^2) = \frac{2n^2 - D(n^2)}{n^2}=I_0$$
and the upper bounds $u_i$ (for $I(n^2)$) given by
$$u_0 = \frac{2n^2 + D(n^2)}{n^2 + D(n^2)}$$
$$u_1 = \frac{\bigg(2n^2 - D(n^2)\bigg)+\bigg(2n^2 + D(n^2)\bigg)}{n^2 + \bigg(n^2 + D(n^2)\bigg)} = \frac{4n^2}{2n^2 + D(n^2)}$$
$$u_2 = \frac{\bigg(2n^2 - D(n^2)\bigg)+4n^2}{n^2 + \bigg(2n^2 + D(n^2)\bigg)}=\frac{6n^2 - D(n^2)}{3n^2 + D(n^2)}$$
$$u_3 = \frac{\bigg(2n^2 - D(n^2)\bigg)+\bigg(6n^2 - D(n^2)\bigg)}{n^2 + \bigg(3n^2 + D(n^2)\bigg)} = \frac{8n^2 - 2D(n^2)}{4n^2 + D(n^2)}$$
$$u_4 = \frac{\bigg(2n^2 - D(n^2)\bigg)+\bigg(8n^2 - 2D(n^2)\bigg)}{n^2 + \bigg(4n^2 + D(n^2)\bigg)} = \frac{10n^2 - 3D(n^2)}{5n^2 + D(n^2)}$$
$$\ldots \ldots \ldots$$
$$\ldots \ldots \ldots$$
$$\ldots \ldots \ldots$$
(That is, $u_i = \text{mediant}(u_{i-1},I_0)$.)
Note that it is easy to prove that $u_i$ (for $i=0, 1, 2, \ldots$) is a strictly decreasing sequence.
The resulting lower bounds for ${n^2}/D(n^2)$ (on assuming $k=1$) are:
$$u_0 : \frac{n^2}{D(n^2)} > 2$$
$$u_1 : \frac{n^2}{D(n^2)} > \frac{5}{2}$$
$$u_2 : \frac{n^2}{D(n^2)} > \frac{8}{3}$$
$$u_3 : \frac{n^2}{D(n^2)} > \frac{11}{4}$$
$$u_4 : \frac{n^2}{D(n^2)} > \frac{14}{5}$$
$$\ldots : \ldots$$
QUESTIONS

(1) Do the resulting lower bounds for ${n^2}/D(n^2)$ (using this procedure) have a closed form?
(2) Does the lower bound ever reach $3$, or is it possible to prove that it does not?
Comment: (+1) for your effort about this unsolved problem. Recently I've seen a new  paper published by an author in arXiv on a conjecture due to you. Isn't required a response, good week.
Answer: It appears that the numerators of the lower bounds form OEIS sequence A016789.  Hence, the lower bounds have the closed form
$$\frac{3i + 2}{i + 1}.$$
Consequently,
$$\frac{3i + 2}{i + 1}=3-\frac{1}{i + 1},$$
so that the lower bounds never reach $3$.


Pythagorean triples

Question: So I am given that $65 = 1^2 + 8^2 = 7^2 + 4^2$ , how can I use this observation to find two Pythagorean triangles with hypotenuse of 65.
I know that I need to find integers $a$ and $b$ such that $a^2 + b^2 = 65^2$, but I don't understand how to derive them from that observation.
Here is my attempt.
$65^2 = (8^2+1^2)(7^2+4^2) = 8^27^2 + 1^24^2 + 1^27^2 + 8^24^2 = (8\cdot7)^2 + 4^2 + 7^2 + (8\cdot4)^2$ but now I am stuck here, any suggestions!
Comment: Another way is to derive the triple from more famous triples. With 65, for example, since $65 = 5 \times 13$, and since $3^2 + 4^2 = 5^2$ and $5^2 + 12^2 = 13^2$, we can multiple the first triple by 13 and the second triple by 5, giving us: $$39^2 + 52^2 = 65^2$$ and $$25^2 + 60^2 = 65^2.$$
Comment: use Euclid's formula
Comment: yes, but i am not using the observation here. Thanks though
Comment: The formula there.    http://math.stackexchange.com/questions/153603/diophantine-equation-a2b2-c2d2/736164#736164
Comment: If it is necessary to solve the system of the formula there.  http://www.artofproblemsolving.com/blog/104785
Answer: Use the Brahmagupta-Fibonacci Identity
$$(a^2+b^2)(c^2+d^2)=(ac-bd)^2+(ad+bc)^2.$$
This identity can be verified by multiplying out each side, and in nicer ways.
From the Identity, we get
$$65^2=(8^2+1^2)(7^2+4^2)=(8\cdot 7-1\cdot 4)^2 +(8\cdot 4+1\cdot 7)^2.$$
We can get another representation of $65^2$ as the sum of two squares by letting $c=4$ and $d=7$.
Remark: The Identity gives the useful result that the product of two numbers, each the sum of two squares, is itself the sum of two squares.
Comment: @Leo: Maybe this will help you see how we can get two triples: $$\begin{align} \\
(a^2 + b^2)(c^2 + d^2) & = \\
& = a^2c^2 + a^2d^2 + b^2c^2 + b^2d^2 \\
& = a^2c^2 +  b^2d^2 \pm 2acbd + a^2d^2 + b^2c^2 \mp 2adbc \\
& = (ac \pm bd)^2 +  (ad \mp bc)^2\\
\end{align}$$
Comment: Much thanks, but this is one Pythagorean triple,How can i get another one form the same observation
Comment: I added a line about how.
Answer: Hint If $m,n$ are integers then $(m^2-n^2, 2mn, m^2+n^2)$ is a Pytagorean triple.
Comment: how is this useful when using the observation
Comment: Just take $m = 8$ nad $n=1$...
Comment: @leo If $m=8, n=1$ then the triple is....
Answer: As I said we need to solve a system of equations.
The system of equations:
$$\left\{\begin{aligned}&x^2+y^2=z^2\\&q^2+t^2=z^2\end{aligned}\right.$$
the solutions have the form:   $$x=4p^4-s^4$$   $$y=4p^2s^2$$   $$q=4ps(2p^2-s^2)$$   $$t=4p^4-8p^2s^2+s^4$$   $$z=4p^4+s^4$$
$p,s,k$ - integers.
Formulas you can write a lot, but will be limited to this. Will make a replacement.
$$a=p^2+s^2-k^2$$
$$b=p^2+s^2+k^2-2pk-2ks$$
$$c=p^2+k^2-s^2+2ps-2kp$$
$$r=s^2+k^2-p^2+2ps-2ks$$
The solution then is.
$$x=2ab$$
$$y=a^2-b^2$$
$$q=2cr$$
$$t=c^2-r^2$$
$$z=a^2+b^2$$
Answer: If we solve $C=m^2+n^2$ for $n$, we get $n=\sqrt{C-m^2}$. We can then try values of $m$ to see which one(s) yield a positive integer for $n$, where
$$\text{To ensure }n<m:\biggl\lceil\sqrt{\frac{C}{2}}\space\space\biggr\rceil \le m\le\bigl\lfloor\sqrt{C}\bigr\rfloor:\text{ to ensure }n\in\mathbb{N}$$
$$\text{In the example of }65\qquad m_{min}=\lceil\sqrt{32.5}\space\rceil = 6\qquad m_{max}=\lfloor\sqrt{65}\rfloor = 8$$
If we test $n=\sqrt{C-m^2}$ using $m=6,7\text{, and }8$, we find positive integers for $n$ where $m=7\Rightarrow n=4$ and $m=8\Rightarrow n=1.$
$$\text{Using Euclid's formula }f(7,4)=(33,56,65)\quad f(8,1)=(63,16,65)$$

Pythagorean triples


Example such that $ f_1(x)$ is reducible but $f(x)$ is irreducible.

Question: (The (mod p) Irreducibility Test)
Let $p$ be a prime an suppose that $f(x) \in \mathbb Z[x]$ with $\deg f(x) \geq 1$. Let $f_1(x)$ be the polynomial in $\mathbb Z_p[x]$ obtained from $f(x)$ by reducing all the coefficients of $f(x)$ modulo $p$. If $f_1(x)$ is irreducible over $\mathbb Z_p$ and $\deg f_1(x)=\deg f(x)$, then $f(x)$ is irreducible over $\mathbb Q$.
I know that if   $f_1(x)$ is reducible , then $f(x)$ can be reducible or irreducible.
I want example such that $f_1(x)$ is reducible but  $f(x)$  is irreducible.
Answer: You have $(x+1)^2=x^2+2x+3$ over $\mathbb F_2$, but $x^2+2x+3$ is irreducible over $\mathbb Q$: It has no Zero.
Answer: The polynomial $x^4+1$ is irreducible in $\Bbb Q$ but it's reducible in  every $\Bbb Z_p$ for any prime $p$, for instance in $\Bbb Z_2$ we have:
$$x^4+1=x^4-2x^2+1=(x^2-1)^2 $$


Read/Write SQL Server views in MS Access using SCHEMABINDING

Question: I am having to redevelop an MS Access 2003/2010 ADP project, that uses SQL Server views as the RecordSource for all its forms, into an MS Access 2016 ACCDB.
I have tried using pass through queries to get the data and this works fine for readonly columns, however when I want to change the value in one of the bound columns, it says that the RecordSet is not updateable, which is what you might expect if using a view.
But I have now read that if you define the view with SCHEMABINDING like this:
ALTER VIEW [dbo].[vwQuote_MinibusesDetails]
WITH SCHEMABINDING
AS
    SELECT ...

and add a UNIQUE CLUSTERED INDEX like this:
CREATE UNIQUE CLUSTERED INDEX CIX_vwQuote_MinibusesDetails
ON vwQuote_MinibusesDetails (txtQuoteNo, txtVersion, txtVehicleNo);

and then add the view to your project as a DSN-less TableDef like this
stConnect = "ODBC;Driver=SQL Server;Server=" & SERVER_NAME & ";Database=" & APP_DATABASE & ";Trusted_Connection=Yes"
Set td = CurrentDb.CreateTableDef(stLocalTableName, dbAttachSavePWD, stRemoteTableName, stConnect)
CurrentDb.TableDefs.Append td

it becomes editable as if it were a table.
However, when I open the TableDef in Access it shows all the rows and columns as if it were editable, but if I try to edit a column, it says that there is a Write Conflict with another user's changes, when I am 100% sure that there isn't because I am the only person using it.
Any ideas? (I am using Access 2010 at the moment)
Comment: You might have more luck adding the tables (not the views) as linked tables and trying to update them in the Access db.
Comment: [Note](https://support.office.com/en-us/article/create-an-access-project-89c48da0-55a4-45d4-9ee5-95f67383d4cb): Access 2010 is the last version of Access that supports working with Access project (.adp) files. Additionally, it works best with SQL Server 2008 or earlier. And this SQL Server version has past its [end of life support](https://learn.microsoft.com/en-us/support/sql/end-support-sql-server-2008). Consider re-tooling your products and workflow.
Answer: But why do all that truckloads of work? There is zero reason to do all that extra work.
Simply bind and set the forms data source to a view. It is assumed that you will simply link all of the existing views on the client side. Access will thus see all the views as simply tables, and views (as opposed to Pass through queries) are read/write.
So, there is no need to:
Have ANY connection strings in your code. If you ARE using connection strings in code, then you approach is all wrong. Just link to the views, and set the forms data source as that view.
At this point, the forms can edit data.
As for a pass-through quires to drive combo boxes? Do NOT do this. While a PT query is likely the fastest way to pull data, the access client cannot filter PT queries. So you ONLY EVER want to use a PT query for cases in which the client side does NOT have to filter the results. If you bind a combo box to a PT query, then Access needs and wants to ONLY pull the one value from that table for display. And since the access client can't filter a PT query, then it will scan the WHOLE data source for that combo box to get the one value that is currently displayed. If you use a linked table (or even a view) to that source that drives the combo box, then the access client can filter that dataset to the ONE row. So, do NOT use a PT query for ANY case in which client side filtering is required. A linked view (or linked table) is fine in these cases.
So, just bind the forms directly to the linked table, or the linked view.
If the table has 1 million rows of data, and you say do this:
Docmd.OpenForm "frmInvoice",,,"InvoiceNum = 1234"
Access will open the form to the ONE row of data, and ONLY pull one row down the network pipe. This is despite that the form in question is bound to a table of 1 million rows. The form will load instant, and you not had to write any sql, any connection stuff, and not really do anything different then how you developed typical access applications.
Bound forms are how and why Access saves huge development dollars. If you jump to .net, then you have all kinds of tools and wizards that can help you around this issue. So in .net, you could adopt the dataset designer, or use the newer entity framework.
In Access, we don't have this huge tool box of data designers and tools, so if you attempt to hand code, and code up the data sources for a form, then you get the worst possible outcome (you write truckloads of code, and don't have all those cool tools for un-bound forms).
Simply link your forms to linked tables (or views) and you now have a working data bound form without any code. If you need to load the form, then use the 20+ year standard approach of the "where" clause of the open form command to open the form to the one record. The access client will ONLY pull what you put in the "where" clause.
So, to wire up a form for editing of data, ZERO code is required. The only developer efforts will then to ensure that the form does not pull un-necessary data to the client.
Comment: How do you link to the Views without using some kind of Connection String? This isn't a homebrew on my desktop, it's a commercial system that has to get through all the SQL Server logon security. I have to use "TrustedConnection=Yes", and if I do that then the View is read-only. I shall try using The Ben B's suggestion of linking to the base tables instead of the Views, since most of the Views just seem to be taking a selection of fields from their respective single base tables - although that itself is a data visibility security issue, but as the app is only for internal use it should be ok.
Comment: OK, if I link the base tables using "TrustedConnection=Yes", then they are editable in an Access query window. The next issue is whether Access will allow me to use them as the form DataSource (for example, PassThrough queries can't be used as a form DataSource), and then I will be debating whether to keep strict Hungarian notation by using the "tbl" prefix or to give the linked tables a "vw" prefix to minimise the code changes...
Comment: Your re-link code, or using linked table manager requires a connection string. But no need for  connection strings in your code. The point that you don't in "general" as a result need connection strings "all over the place" in your code is the point here. Both links to sql tables, and links to views are read/write and both can be used as a direct data source for the forms. (so again, no connection strings required in your form code). When you link to a view, you are prompted for the PK. If your re-link code creates links to views, then an extra step of setting the PK is required.
Comment: There is zero benefit to basing a form on a access client side query, or basing such forms on a server side view (waste of developer time). Just link to the tables, and then base the forms on that linked table. For a sub form, you could used a view with a sort, or even a client side query for sorting when required. For reports client side sql queries are fine if one table. For multiple SQL joins, then move the query to a server side view and base the report on that view. Views will respect the "where" clause of the open form, or open report.  Views perform as good as pass-trough queries.
Comment: as for changing the notation and table names? Why? Keep them the same as they were before, and thus all of the existing VBA code will tend to work as before with the fewest changes possible. If you change table names then a truckload of sql and queries will now be broken. Your goal is to change as little as possible, and every change in table names etc. will cost you time and efforts.
Comment: And dump the use of schema-binding. I see zero reason for adopting or introducing that into this mix - it is of no use or of any kind of advantage here. It is not required.   I do recommend you stick with ADO, but if this was a non adp project migration then I would recommend that you continue to use DAO if that is what the original application was using. In your case, the code will have been ADO - so continue to use that data object in your VBA code. Again, little changes should be required to that VBA code. The linked tables will already have a connection.


Custom module for adding CSS file in admin section

Question: How do I include admin.css in my theme so that it's loaded in the admin section (and preferably only the admin section)?
Right now when I add admin.css via the x.libraries.yml file, it's only loaded on the front-end.
Update:
So... based on your comments/answers I've created a module admin-css. But nothing happens. The file isn't loaded. What am I doing wrong?
Inside admin_css.info.yml :
name: Admin CSS
description: Alters the Admin CSS for better usability.
package: Custom

type: module
core: 8.x

Inside admin_css.libraries.yml :
admin-css:
  version: 1.x
  css:
    theme:
      css/admin.css: {}

Inside admin_css.module :
<?php

function admin_css_attachments(array &$attachments) {
    $is_admin = \Drupal::service('router.admin_context')->isAdminRoute();
    if ($is_admin) {
      $attachments['#attached']['library'][] = 'admin_css/admin-css';
      return;
    }

}

Comment: are you using the same themes in front-end and backend ?
Comment: No I'm not, I'm using the standard theme for back-end. But I'd like to include an admin.css in my theme, just for a few minor changes to the admin section.
Answer: Unless you use the same theme for front and backend, that's not the right approach.
If something transcends the theme layer, e.g. you have functionality that you need to apply to two separate themes, it belongs in a module.
See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module for instructions to actually accomplish that, specifically the section on Attaching a library to all (or a subset of) pages which contains a contrived code example:
function contextual_page_attachments(array &$attachments) {
  if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
    return;
  }

  $attachments['#attached']['library'][] = 'contextual/drupal.contextual-links';
}

Comment: Of course :) See the code example. It will need to be in a module though, for obvious reasons a theme's functionality is only loaded/invoked when it's actively being used. Executing functionality from one theme when a different theme is being used to render the page could be disastrous
Comment: You'll need to change the logic in the attachments hook function to match your requirements, that's just a contrived example that uses a different condition. Searching "programatically determine admin page in drupal 8" should give you the answer
Comment: I'm using the standard theme for backend, but I'd like to include an admin.css in my theme, just for a few minor changes to the admin section. Literally 6 lines of CSS. Is it at all possible?
Comment: I've updated the question, could you take a look at it? Thanks!
Comment: I've done just that (based on http://stackoverflow.com/questions/4483200/how-to-check-if-the-user-is-in-the-admin-part-of-drupal), but still no luck.
Comment: None of those answers are for Drupal 8, I don't have the exact method to hand you'll need to google it
Comment: The answer provided is for Drupal 8, at least says the answerer (and it has 30 upvotes). I'm just puzzled as how to implement it in the module. I'm obviously still doing something wrong.
Comment: Oh right, I missed the 2nd part. Yes that's the correct method, would be best to ask a new question/raise a bug report if it doesn't work
Answer: The hook is called "hook_page_attachments"
so you have to rename your function from
function admin_css_attachments(array &$attachments) {

to
function admin_css_page_attachments(array &$attachments) {

Answer: You can also use the Asset Injector module to add css to your admin theme: https://www.drupal.org/project/asset_injector


Popup image from SQL fetch array displays same image

Question: i have some code which pops up new window which works ok and will open the matching image from the database search
JavaScript

html

        <?php echo $results['siteid']; ?>
        <?php echo $results['description']; ?>
        <a href="javascript:void(0)" onclick="CenterWindow(800,500,50,'../../admin/Test Photo Upload/<?php echo $results['location']; ?>','demo_win');">Open Image

I want to change the popup window to have just the image type of popup without the browser which works with this code but gives me the same image for all the links in that particular search, so my code seems to give me the first result in the table?
CSS

JavaScript

html

        <?php echo $results['siteid']; ?>
        <?php echo $results['description']; ?>
        Open Image

    <img src="../../admin/Test Photo Upload/<?php echo $results['location'];?>"/>

Thank you
<?php
    $query = $_POST['txtidforgallery'];
    // gets value sent over search form

    $min_length = 3;
    // you can set minimum length of the query if you want

    if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then

        $query = htmlspecialchars($query);
        // changes characters used in html to their equivalents, for example: < to >

        $query = mysql_real_escape_string($query);
        // makes sure nobody uses SQL injection

        $raw_results = mysql_query("SELECT * FROM photos
            WHERE (`siteid` LIKE '%".$query."%') OR (`siteid` LIKE '%".$query."%')") or die(mysql_error());

        // * means that it selects all fields, you can also write: `id`, `title`, `text`
        // articles is the name of our table

        // '%$query%' is what we're looking for, % means anything, for example if $query is Hello
        // it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query'
        // or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query'

        if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following

        ?>

            Site ID
            Photo Description

          <?php
            while($results = mysql_fetch_array($raw_results)){
            // $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop

Comment: So what is really your problem? because I can not see any issues with your code. whatever you have in `$results['location']` will be shown.  I don't see more than one image in your code or any loop to show more than one image
Comment: $results['location'] is a database of images but only the first one will display, Location has row 1 = IMG_1.jpg, row 2 has IMG 2.jpg, etc but every link displays IMG 1 the 'function CenterWindow' code works fine but not the 'lightbox_open'
Comment: of course, because you have to put it in a loop!!
Comment: can you please share the section of your code which you are fetching the data from your database to `$results`?
Answer: OK, from the information you provided I can see that you have a number of records.
A simple loop which shows all the records would be like this. So I put your loop in the
 and show every record in a row. each roe has it's own Open Image link, that if  you click on each of them, the image of that record would be shown...
Your css looks OK so I did not changed it...
JavaScript

php & html

    <?php
    while($results = mysql_fetch_array($raw_results)){
    ?>

        <?php echo $results['siteid']; ?>
        <?php echo $results['description']; ?>
        <a href="#" onclick="lightbox_open('../../admin/Test Photo Upload/<?php echo $results['location']; ?>');">Open Image

    <?php } ?>

Please note that src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" is just a dummy 1x1 pixel image, because  tag requires src property and it can not be empty.
And then you can change it in a way that meets your needs...
Comment: Work perfectly, Thank you so much
Comment: You are welcome. if this answer helps you then please select it as accepted answer and give it an upvote  :)
Answer: HTML
<a class="fancybox" rel="group" href="/img<?php echo $user_id ?>/<?php echo $value ?>">

        <div style="background: url('/img<?php echo $user_id ?>/<?php echo $value ?>'); ">

Comment: Please add this code on your php file  :
Comment: This code will do nothing if you do not use _fancyBox Plugin_


NGINX is TLS 1.2 only due to PCI DSS certification. How can I warn the others?

Question: How do I redirect those browsers that do not support TLS 1.2 to a page that'll explain the situation to them.
Comment: According to http://blog.varonis.com/ssl-and-tls-1-0-no-longer-acceptable-for-pci-compliance/ TLS 1.1 is acceptable for those browsers.
Comment: that's not my question. My question is how do I redirect those without TLS 1.2 to a web page where they can find out why they can't access.
Answer: Unless the clients are accessing the site with regular HTTP before trying to go to HTTPS they will not be able to be redirected. The webserver will not be able to create a successful encrypted channel so the client would not be able to obtain any redirect.
Comment: So what's can be done that'll catch all http and https calls and redirect them to where they are told they must have TLS 1.2? I can't believe nothing can be done.
Answer: Here you go.  Edit as needed.
<code>// If the user is using an older version of TLS

if ($ssl_protocol != "TLSv1.2") {
  return 302 /outdated;
}
</code>


How to return the user after finishing the network request?

Question: in this method I wanted to get the user's list after finishing the request not immediately because it is giving 0 user's list from Firebase?
Why run blocking  coroutine is not working here?
   fun getAllFollowingsLists(uid: String): List<User> {
        val users = mutableListOf<User>()
        val collection = FirebaseFirestore.getInstance().collection("users")
            .document(uid).collection("followings")

        runBlocking {
            collection.get().addOnCompleteListener {
                for (k in it.result!!) {
                    Log.i(TAG, "getAllFollowingsLists: ${k.toObject(User::class.java)} ")
                    users.add(k.toObject(User::class.java))
                }
            }
        }
        return users
    }

Comment: Have you checked [this answer](https://stackoverflow.com/questions/51594772/how-to-return-a-list-from-firestore-database-as-a-result-of-a-function-in-kotlin) ?
Comment: Yeah, thank you. But why runBlocking is not working here? it should suspend the thread
Answer: Because addOnCompleteListener is not blocking, it finished without waiting for get() to finish. Instead it put a listener which will run when get() finishes.
addOnCompleteListener is not async, so the runBlocking is useless here.
You should do whatever you want to do with the List<User> after the for loop in the listener.


Why is the following JSON invalid?

Question: The following JSON is not passing validation.  The validator complains at the first string value starting at "Can an officer...
It looks like the start of a valid string value for the key.  What on earth could be wrong with this?
{
   "DUI": {
      "Can an officer arrest me because he smelled alcohol on my breath?":"
No, odor alone is not sufficient basis for arrest. However, odor combined with other observations such as weaving, slurred speech, and bloodshot eyes
may be enough to give an officer probable cause to arrest you for DUI.",
      "Can I be convicted if I refused to take the breath test or the result was below .08?":"
Yes, in Washington the prosecutor can prove DUI one of two ways: 1. Blood or breath test result above .08, OR  2. Proof the person was under the
influence of or affected by liquor or drugs.

Additionally, if a person refused to take a test, that fact may be introduced as evidence at trial.",
      "How can I be arrested if I wasn't driving my car?":"
A person who is in physical control of a vehicle and appears to be under the influence of drugs or alcohol may be arrested and charged under RCW
46.61.504.",
      "What can I do now that I have been charged?":"
Contact an attorney to find out what options are available to you."
   }
}

Answer: Doesn't seem to like some line breaks present in your pasted JSON:
Parse error on line 3:
...ohol on my breath?":"
No, odor alon
-----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

I pasted the JSON from your question into the validator and removed unnecessary line breaks - this works:
{
    "DUI": {
        "Can an officer arrest me because he smelled alcohol on my breath?": "
No, odor alone is not sufficient basis for arrest. However, odor combined with other observations such as weaving, slurred speech, and bloodshot eyes may be enough to give an officer probable cause to arrest you for DUI.",
        "Can I be convicted if I refused to take the breath test or the result was below .08?": "
Yes, in Washington the prosecutor can prove DUI one of two ways: 1. Blood or breath test result above .08, OR  2. Proof the person was under the influence of or affected by liquor or drugs.

Additionally, if a person refused to take a test, that fact may be introduced as evidence at trial.",
        "How can I be arrested if I wasn't driving my car?": "
A person who is in physical control of a vehicle and appears to be under the influence of drugs or alcohol may be arrested and charged under RCW 46.61.504.",
        "What can I do now that I have been charged?": "
Contact an attorney to find out what options are available to you."
    }
}

http://jsonlint.com/

Why is the following JSON invalid?


How can I split a column into 2 in the correct way in Python?

Question: I am web-scraping tables from a website, and I am putting it to the Excel file. My goal is to split a columns into 2 columns in the correct way.
The columns what i want to split: "STATUS"
I want this form:
First example: Estimated 3:17 PM --> Estimated and 3:17 PM
Second example: Delayed 3:00 PM --> Delayed and 3:00 PM
Third example: Canceled --> Canceled and (empty cell)
So, I need to separete the FIRST word (in the first column), and after that the next characters.
How Can I do this?
Here my relevant code, which is already contains a formatting code.
df2 = pd.DataFrame(datatable,columns = cols)
df2['a'] = df2['FLIGHT'].str[:2]
df2['b'] = df2['FLIGHT'].str[2:].str.zfill(4)
df2["UPLOAD_TIME"] = datetime.now()
mask = np.column_stack([df2[col].astype(str).str.contains(r"Scheduled", na=True) for col in df2])
df3 = df2.loc[~mask.any(axis=1)]

if os.path.isfile("output.csv"):
    df1 = pd.read_csv("output.csv", sep=";")
    df4 = pd.concat([df1,df3])
    df4.to_csv("output.csv", index=False, sep=";")

else:
    df3.to_csv
    df3.to_csv("output.csv", index=False, sep=";")

Here the excel prt sc from my table:
Comment: Possible duplicate of [How can I split a column into 2 in the correct way?](https://stackoverflow.com/questions/46522269/how-can-i-split-a-column-into-2-in-the-correct-way)
Answer: You can use str.split - n=1 for split by first whitespace and expand=True for return DataFrame, which can be assign to new columns:
df2[['c','d']] = df2['STATUS'].str.split(n=1, expand=True)

Sample:
df2 = pd.DataFrame({'STATUS':['Estimated 3:17 PM','Delayed 3:00 PM']})

df2[['c','d']] = df2['STATUS'].str.split(n=1, expand=True)
print (df2)
              STATUS          c        d
0  Estimated 3:17 PM  Estimated  3:17 PM
1    Delayed 3:00 PM    Delayed  3:00 PM

If no whitespace in input get None in output:
df2 = pd.DataFrame({'STATUS':['Estimated 3:17 PM','Delayed 3:00 PM', 'Canceled']})

df2[['c','d']] = df2['STATUS'].str.split(n=1, expand=True)
print (df2)
              STATUS          c        d
0  Estimated 3:17 PM  Estimated  3:17 PM
1    Delayed 3:00 PM    Delayed  3:00 PM
2           Canceled   Canceled     None

and if need replace None to empty string use fillna:
df2[['c','d']] = df2['STATUS'].str.split(n=1, expand=True)
df2['d'] = df2['d'].fillna('')
print (df2)
              STATUS          c        d
0  Estimated 3:17 PM  Estimated  3:17 PM
1    Delayed 3:00 PM    Delayed  3:00 PM
2           Canceled   Canceled


How to swap row and columns Panda

Question: Im trying to fetch data using Yahoo's API to get stock prices, and show them on an excel sheet. All works fine except when I try to transpose the data I get this error:
AttributeError: 'MultiIndex' object has no attribute 'tz_localize'

Here is my code:
import pandas as pd
import matplotlib.pyplot as plt

#Data Source
import yfinance as yf

#DATA
stocks = ['AAPL', 'MSFT', 'NEE', 'AMGN', 'TU', 'ZM', 'TSLA', 'TTD', 'SEDG', 'APPN', 'TWLO', 'MMM', 'ABBV', 'SHW', 'K', 'HON', 'AFL', 'JNJ', 'ABT', 'EMR', 'FSLR', 'SPWR', 'ENPH', 'ACC.OL']
data = yf.download(tickers=stocks, period='3d', interval='1d')

#Clean data
columns = ["Adj Close", "High", "Low", "Open", "Volume"]
data.drop(columns=columns, axis=1, inplace=True)

data = data.T

#Remove timezone
data.index = data.index.tz_localize(None)

#Print data
print(data)

#Send to excel
datatoexcel = pd.ExcelWriter("FromPython.xlsx", engine='xlsxwriter')
data.to_excel(datatoexcel, sheet_name='Sheet1')
datatoexcel.save()

Can somebody explain what's going wrong and how I can fix? Thank you!
Comment: you are transposing the data so the index is now columns, try `data.columns = data.columns.tz_localize(None)` instead of using `index`
Answer: When you call data.T the DataFrame's index is composed of your symbols, which have no timezone. Maybe you want to remove timezone before transposing?

How to swap row and columns Panda


How to make a fluid, stacked column layout in HTML?

Question: I need to build a layout similar to the one at www.PInterest.com, where - depending on the browser width (yes responsive design) the amount of columns varies. The problem is not the horizontal stacking but the vertical. How do i make the boxes different height and stack on top of each other som that it will not let the highest box determine the height for the entire row?
Using ASP.NET MVC 3, HTML/HTML5, CSS/CSS3
Comment: think of columns instead of rows. http://stackoverflow.com/q/9205790/575527 and by the way, pinterest "columns" are not actual columns. they are dynamically placed divs, each positioned allover the page. debug the page, all "sections" are made of **sibling divs** distributed into columns.
Answer: Make three elements (div, for example), that are fluid in their width. These will serve as your columns. Put the elements you want inside each column with the respective
.
I just made this as an example: http://jsfiddle.net/N4zkF/
I think viewing the example would be more helpful than me explaining it in words. The three columns are bordered in red, blue, and green. The content of each has a gray/black background and a fixed height.

This answer was edited. Last time I linked the wrong jsfiddle (was wondering why I got a downvote). Hopefully this will help you, OP.
Answer: u need to set the width of the colums with a percentage and have a min-width on each of the columns..
Say u want 3 column's,for a responsive design -- set the width of all 3 columns as width:33% and add a min-width for the least resolution that you are supporting,
say,1024x768 in that case -- 1000px is the total width that you might have at the minimum (ignoring the extra 24px for the browsers scroll bar on each sides).. so,let the min-width:333px.. so,if the width of the browser is more,it'll occupy the space.. else,min-width will be set anyway so you need not worry about the layout getting screwed..
here's a fiddle to get you started - jsfiddle.net/mvivekc/XwYDr
here's a nice tutorial that i stumbled upon
-- http://matthewjamestaylor.com/blog/perfect-multi-column-liquid-layouts
-- http://css-tricks.com/the-perfect-fluid-width-layout/


When input new value is passed it does not affect #np and #total_amount automatically until I refresh the web page

Question: When I change input value (id=input") after selecting option (change from string to value) it does not refresh automatically in #np and #total_amount

function myFunction() {
  var x = document.getElementById("work").value;
  console.log(x);
  if (document.getElementById("work").value == "article") {
    var w = 5;
    if (document.getElementById("input")) {
      // renamed x to z
      var z = document.getElementById("input").value;
      var wc = w * z;
      // not .value but .textContent
      document.getElementById("total_amount").textContent = +wc;
      document.getElementById("np").textContent = +wc;
    }
  }
}

  <input type="number" value="0" id="input" name="word_count" value="500" style="text-align: center;" />
  <select id="work" onchange="myFunction();" name="work">
    <option disabled selected> -Select - </option>
    <option value="article">Article
    </option>
  </select>

 Total amount:

 NP:

I did like to see the results in #np and #total_amount change when I pass a new value to input after selecting from option
Answer: You have an event handler assigned to the <select> element, but not to the <input> element. So when the input value is changed, your function isn't getting called and your "total_amount" and "np" values aren't updated.
You need to attach an event handler to the change event of your <input> tag. I'm not exactly sure how or what you want to calculate, but here's an example of what I mean using your code (look at my added comments on the HTML section):

function myFunction() {
  var x = document.getElementById("work").value;
  console.log(x);
  if (document.getElementById("work").value == "article") {
    var w = 5;
    if (document.getElementById("input")) {
      var z = document.getElementById("input").value;
      var wc = w * z;
      document.getElementById("total_amount").textContent = +wc;
      document.getElementById("np").textContent = +wc;
    }
  }
}

  <input type="number" onchange="myFunction()" id="input" name="word_count" value="500" style="text-align: center;" />
  <select id="work" onchange="myFunction();" name="work">
    <option disabled selected> -Select - </option>
    <option value="article">Article
    </option>
  </select>

 Total amount:

 NP:

Comment: thanks a lot for that observation, now it's working


Differentiable and injective function

Question: I'm having trouble with the following exercise:
Let $f:U \to \mathbb{R}^{M}$ be a differentiable application in $a \in U \subset \mathbb{R}^{N}$, an open set. If $f'(a) \in \mathcal{L}(\mathbb{R}^N,\mathbb{R}^{M})$ is injective, then there are $c,\delta>0$, such that for every $v \in \mathbb{R}^{N}$ with $|v|<\delta$ implies $|f(a+v)-f(a)| \geq c|v|$
My hint was to define a continuous function $F:S(0,1) \to \mathbb{R}$, with $F(v) = |f'(a)v|$.
I know that in a compact a continuous function has a minimum $v_{0}$, such as $F(v) \geq F(v_{0})$, for every $v \in S(0,1)$, and that $F(v_{0}) > 0$. Otherwise, if $F(v_{0}) = 0$, then $f'(a)v_{0}=0$, but $f'(a)$ is injective, so $v_{0} =0$, which is absurd as $v_{0} \in S(0,1)$.
I also know that, as $f$ is differentiable in $a \in U$, and for $v \in \mathbb{R}^{N}$ with $|v|<\delta$, $|r(v)| = |f(a+v)-f(a)-f'(a)v| < c|v|$
Now I don't know how to proceed. Help would be most appreciated!
Answer: Let $\varepsilon:=\frac12\min_{S(0,1)} F>0$. By the definition of differentiability you can find $\delta>0$ such that
$$|f(a+v)-f(a)-df(a)(v)|\le \varepsilon |v|$$ for all $0<|v|\le\delta$. Then
$$|f(a+v)-f(a)|\ge |df(a)(v)|-|f(a+v)-f(a)-df(a)(v)|\ge 2\varepsilon|v|-\varepsilon|v|=\varepsilon|v|.$$

Differentiable and injective function


Oracle initialization of collection elements with not null constraint

Question: What is the initialization value for NOT NULL element in the collection (Table/Varray)? It seems like the NULL but it is NOT NULL. Tested in Oracle LIVE SQL (Oracle Database 19c Enterprise Edition - 220.127.116.11.0)
declare
    type TArrNotNull IS table of number NOT NULL;
    type TArrAllowNull IS table of number;
    arrNotNull TArrNotNull := TArrNotNull();
    arrAllowNull TArrAllowNull := TArrAllowNull();
begin
    -- NOT NULL ARRAY ELEMENTS
    DBMS_OUTPUT.PUT_LINE('======== table/Array of number NOT NULL example ==========');
    arrNotNull.Extend;
    IF arrNotNull(1) is null then
       DBMS_OUTPUT.PUT_LINE('NULL !!!');
    else
       DBMS_OUTPUT.PUT_LINE('NOT NULL BUT WHAT ???->['||COALESCE(arrNotNull(1),100)||']');
       DBMS_OUTPUT.PUT_LINE('NOT NULL BUT WHAT + 1 BECOMES NULL (LIKE REAL NULL)???->['||COALESCE(arrNotNull(1)+1,100)||']');
    end if ;

    DBMS_OUTPUT.PUT_LINE('======== table/Array of number example ==========');

    -- NOT NULL ARRAY ELEMENTS
    arrAllowNull.Extend;
    IF arrAllowNull(1) is null then
       DBMS_OUTPUT.PUT_LINE('OK IS NULL !!!');
    else
       DBMS_OUTPUT.PUT_LINE('NOT NULL !!!');
    end if ;
end;

RESULTS:
Statement processed.
======== table/Array of number NOT NUMBER example ==========
NOT NULL BUT WHAT ???->[]
NOT NULL BUT WHAT + 1 BECOMES NULL (LIKE REAL NULL)???->[100]
======== table/Array of number example ==========
OK IS NULL !!!

UPD: Also the same if you assign the value to the NUMBER variable.
tst:=arrNotNull(1);
if tst is null then
   DBMS_OUTPUT.PUT_LINE('N NULL !!!');
else
   DBMS_OUTPUT.PUT_LINE('N NOT NULL !!!+++');
end if;

if (tst+1) is null then
   DBMS_OUTPUT.PUT_LINE('N+1 NULL !!!+++');
else
   DBMS_OUTPUT.PUT_LINE('N+1 NOT NULL !!!+++');
end if;

RESULT:
N NOT NULL !!!+++
N+1 NULL !!!+++

Comment: Interesting, I get `NULL !!!` for the first part in 11gR2, both locally and on a [db<>fiddle](https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=b11b77add5c7bf8941082403861d3b2a); but the same as you [on an 18c fiddle](https://dbfiddle.uk/?rdbms=oracle_18&fiddle=b11b77add5c7bf8941082403861d3b2a). Not sure if that's an intentional change or a bug; I suspect the latter...
Comment: Also, [`dump()` thinks it is null...](https://dbfiddle.uk/?rdbms=oracle_18&fiddle=71b5e91a27a614e28f89634ae1a6455c). And for what it's worth, 126.96.36.199 shows `NULL !!!`, but 188.8.131.52 shows the same as 18c and 19c. Probably something to raise directly with Oracle?.
Comment: i have tried to dump the value and got `null`
Answer: Very interesting. Didn't find a "value" for 18+, but in 12c you get a NULL.
I did shrink your code a little:
declare
    type TArrNotNull IS table of varchar2(100) NOT NULL;
    arrNotNull TArrNotNull := TArrNotNull(1, 2, 3);
begin
    begin
        arrNotNull(2) := to_number(NULL); -- will throw, because null is not allowed
        dbms_output.put_line('arrNotNull(2) is null now');
    exception
        WHEN others THEN
            dbms_output.put_line('arrNotNull(2) couldn''t be set to null');
    end;

    arrNotNull.Extend;
    dbms_output.put_line('arrNotNull(4): >>>' || nvl(arrNotNull(4), 'NULL') || '<<<');
end;

Result in 12c:
arrNotNull(2) couldn't be set to null
arrNotNull(4): >>>NULL<<<

Result in 18c (same like yours):
arrNotNull(2) couldn't be set to null
arrNotNull(4): >>><<<

Also interesting is, that an Extend on a nullable Table of has NULL as default value:
declare
    type TArrNotNull IS table of varchar2(100);
    arrNotNull TArrNotNull := TArrNotNull(1, 2, 3);
begin

    arrNotNull.Extend;
    dbms_output.put_line('arrNotNull(4): >>>' || nvl(arrNotNull(4), 'NULL') || '<<<');
end;

Result on all versions:
arrNotNull(4): >>>NULL<<<


Course Dependency Checking for an Engineer

Question: tl;dr : Is the dependency in the figure attached accurate?
Long Version : I am through with my engineering and am shifting to math for grad school. I am looking forward to re-learning (reviewing) everything (Calculus on wards) that is relevant to me. I have created a rough diagram of what I have to learn, which books I have to refer and the dependency I predict by checking out course prerequisites at Stanford, Princeton, UCLA etc.
I am not entirely new to any of these subjects; there is always a little familiarity but what I want now is mastery. I will be learning by myself.

For Differential Equations, I am thinking of using Simmons and for Numerical Optimization, Nocedal and Boyd for Convex Optimization. Fluid Mechanics is Batchelor.
Numerical Analysis I am yet to decide a book on but it could be a Numerical Methods for Engineers type book.
Link to the Computational Science Part : Here.
Does this sequence seem OK? Should I do anything differently
Note: I'll be spending about 15 days - a month per subject (which I think will be sufficient since I only have to fill in some holes). All subjects on the same horizontal level, I will working on together.
Comment: @Whoever down voted, Please explain the reason. The question is objective (People can have facts not opinions about prerequisites)and non-localized (every engineer who wishes to shift to math needs to brush up these things).
Answer: It is certainly a good idea to start with linear algebra as this subject is basic to most other subjects. However since you are shifting to math for grad school i would recommend looking at some other text book because Strang is to obsessed with matrices. It is helpful to view linear algebra from little more abstract point of view if one considers doing more math in the future. Also for ordinary differential equations your going to need jordan canonical forms wich are not covered much in Strang.
You can do numerical analysis after linear algebra and multivariable calculus, but it is not a prerequisite for most subjects that follow in your graph. The book on functional analysis  by Kreyszig for instance can be read without any knowledge of numerics (I did that myself.). Knowing a bit about functional analysis might make learning numerical analysis simpler.  I do not know anything about fluid mechanics but i think you should study this subject after functional analysis because the theory of partial differential equations involves a lot of functional analysis.
Comment: So, Should I go LA > Multivariable > Functional > Numerical and then the rest?
Comment: Yes, that would be a way to do it. One thing that is not on your list, but could be very useful would be real analysis. Real analysis  is used heavily in some probability books and also in more advanced books on functional analysis.
Comment: Where do you recommend I put that?
Comment: After multivariable calculus.


Headphone AMP Inputs

Question: The following headphone amp has  two inputs. I have no idea what the "Link" inputs are.
Does someone know if it is possible to connect 4 inputs in generall?
Purpose: one guitar, one e-piano with two outputs each should be amplified with this amp.
Headphone amp: Millenium HP1
Answer: My guess is that the Link jacks serve as outputs containing the same signal that you put in. The Thomann page for this amp states "Input signal can be looped through".
Connecting multiple inputs is not the purpose of a headphone amp, which takes one stereo signal as input, amplifies it, and provides that signal to one or more headphone outputs. To properly handle four inputs, you'd need a small mixer (which usually has one headphone output as well).
As a crutch: many keyboards offer a mono signal if you only plug in one cable. You can plug than into one channel, and one of the guitar outputs into the other. You will then hear the keyboard in one ear and the guitar in the other. Since your amp provides no way of changing the panning, there's nothing you can do about that.
An additional hack, which may or may not work: apparently, this amplifier accepts "balanced input", which means that you can plug a stereo jack into each input, and the amp will amplify the difference between the signals on the left and right channel of that jack. Since your signals are not phase-locked, amplifying the difference is pretty much the same as amplifying the sum. So if you happen to have two "mono jack to stereo jack" adapters, you can try plugging the guitar into one channel and the keyboard into the other. (If you don't, I'd rather invest the money into a mixer.)
Comment: I don't like accepted answers with zero score. If it is good enough to answer the question it is good enough for at least one upvote.

Headphone AMP Inputs


How to read an attachment from jira and save using Rest Api

Question: I have used attachment id to get the attachment details using rest api it executed and fetched a document from rest api but how shall i read this attachment and save in physical folder no matter of whether the attachment it is zip file pdf nor a document ?
<code>    public Attachment GetAttachment(string attachmentId)
    {
        var request = new RestRequest()
        {
            Method = Method.GET,
            Resource = ResourceUrls.AttachmentById(attachmentId),
            RequestFormat = DataFormat.Json
        };

        return Execute<Attachment>(request, HttpStatusCode.OK);
    }
public class Attachment
{
    public string self { get; set; }
    public string filename { get; set; }
    public Author author { get; set; }
    public string created { get; set; }
    public int size { get; set; }
    public string mimeType { get; set; }
    public string content { get; set; }
    public string thumbnail { get; set; }
}
</code>
But how to read an attachment?
Answer: getContent() and then base64 decode the returned string, I believe. The content type is set based on the name (extension) of the attachment when it was uploaded and can be used to determine what kind of data is in the decoded attachment content.
Comment: How to get the content of attachment a sample illustrating that ? Content property i get the url as "jira/secure/attachment/39532/1.doc" if i use in browser it prompts for save of that document.


Flexslider view with pictures from nodes tagged with a taxonomy term

Question: I need to group 10 images (random choice) of nodes belonging to a content type, and belonging to taxonomy foo with the term bar, in a Flexslider. How can I  setup that content pane view ?
Precision : each node can have one up to ten images.
I created a content view,

with that image field
Filtered by content type
Sort criteria : Global Random
Contextual filter : Content : taxonomy foo(provide default value : taxonomy term ID from URL)

If I use format unformatted list / display all items, it gives me a list of expected images. But if I use Flexslider format, it groups all the images of a single node in each slide ! I understand that the query result is grouped by nodes, when I just need its images ...
View preview
Comment: Is the image field in the content type a multivalue field or do you have single fields for the images?
Comment: @Volker, it's a multi value field indeed
Answer: I suspect the "Multiple field settings" in the view image field configuration. Try to uncheck "Display all values in the same row".
Comment: My bad, you're right :)
Comment: Don't worry, we all overlook things... :) Glad it worked.


Acessar variável fora de loop for

Question: Como acesso a variável cookies fora do loop?
cookies = []
for i in get_cookies(url):
   cookies = '='.join(i) + '; '
print(cookies)

Está retornando apenas isso:
personalization_id="v1_8yKL+7c5RUQ+HHELlnh5dw==";
Preciso que retorne todos os outros em uma única linha, quando dou print(i), está retornando:
('_twitter_sess', 'BAh7CSIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%250ASGFzaHsABjoKQHVzZWR7ADoPY3JlYXRlZF9hdGwrCDzJKCprAToMY3NyZl9p%250AZCIlMDY3NjhlNWQ2NzIwZWIzOWFhOGY4YmNjM2QyZTJlODY6B2lkIiU3OTY2%250AMmM1YjYzYmViYTgxYmZhNDM5OWVjYzJiMzU3Mg%253D%253D--1986635940f2d9bf0f775422f9999122b0279d8c')('ct0', '94d313ad03ce413f521761c16b4bfb63')('guest_id', 'v1%3A155978044447406891')('personalization_id', '"v1_8yKL+7c5RUQ+HHELlnh5dw=="')

preciso que fique assim:
_twitter_sess=BAh...; ct0=123... assim por diante
Comment: Se a ideia é concatenar tudo você precisa de fazer `cookies += ` em vez de `cookies =`
Comment: Guilherme não ficou claro sua dúvida poderia explicar melhor?
Answer: Seu código:
cookies = []
for i in get_cookies(url):
   cookies = '='.join(i) + '; '
print(cookies)

Você definiu cookies como uma lista, mas quer que o resultado seja uma string; dentro do laço de repetição você está sobrescrevendo o valor de cookies, ou seja, o valor anterior sempre será perdido. Assim, depois de finalizar o laço, apenas o último cookie estará em cookies.
Para corrigir isso você 1) inicia corretamente a variável cookies e 2) utiliza a concatenação ao invés da atribuição dentro do laço.
cookies = ''
for i in get_cookies(url):
   cookies += '='.join(i) + '; '
print(cookies)

Mas é Python, você não precisa fazer tudo isso na mão, basta utilizar as ferramentas que a linguagem te proporciona:
cookies = ';'.join(f'{name}: {value}' for name, value in get_cookies(url))

Comment: ah - eu que confundi uma coisa aqui. precisa sim :-) (vou apagar os comentários)
Comment: Isso funcionou, acabei de fazer outra pergunta parecida com essa, não consegui editar :/, mas isso resolveu cara, obrigado mesmo.
Comment: o código funciona, mas veja que não tem motivo nenhum para ter aquele `for` ali.

Acessar variável fora de loop for


Specific computation for the degree of maps from $S^1$ to $S^1$.

Question: I've started learning about the degree of a map in my algebraic topology course. Looking at text references it seems as though my professor is giving a less general and more concrete description of the degree of maps from $S^1\rightarrow S^1$ but I am having trouble with the computations. Let me write out the set up.
Definition:Let $p:\mathbb{R}\rightarrow S^1$ be the exponential mapping $p(x)=(\cos(2\pi x),\sin(2\pi x))$.
Theorem (The Path Lifting Lemma). If $\alpha:[0,1]\rightarrow S^1$ is a continuous function and $x\in\mathbb{R}$ is such that $p(x)=\alpha(0)$, then there exists a unique continuos function $\tilde{\alpha}:[0,1]\rightarrow\mathbb{R}$ called a lift of $\alpha$ such that $p(\tilde{\alpha}(s))=\alpha(s)$ for all $s\in[0,1]$ and $\tilde{\alpha}(0)=x$.
Definition: Let $\pi:[0,1]\rightarrow S^1$ be the quotient map obtained by restriction the map $p$ to the interval $[0,1]$.
Definition: Given a continuous map $f:S^1\rightarrow S^1$, let $\alpha=f\circ \pi$ and $\tilde{\alpha}:[0,1]\rightarrow\mathbb{R}$ be a lift. We call the degree of $f$ denoted $deg(f)$ the integer $\tilde{\alpha}(1)-\tilde{\alpha}(0)$.
Now the particular exercise I am stuck on is computing the degree of the maps $f,g:S^1\rightarrow S^1$; $f(x,y)=(-x,-y)$ and $g(x,y)=(x,-y)$
For $f$ I have the following computations. It is simple enough to compute $\alpha(0)=(f(\pi(0))=(-1,0)$. Then I can let $x=1/2$ so that $p(1/2)=(-1,0)=\alpha(0)$. This also makes $\tilde{\alpha}(0)=1/2$ as stated in the theorem. What I am stuck on is what is the correct way to compute $\tilde{\alpha}(1)$. I know that $p(\tilde{\alpha}(1))=\alpha(1)=(-1,0)=\alpha(0)$. This means that $\tilde{\alpha}(1)$ needs to be any odd integer divided by 2 since $p(k)=(-1,0)$ only when $k$ is an odd integer divided by 2 but it seems to me that any odd integer will work. If anybody can point out what I am missing or what my mistake is it will be greatly appreciated.
Comment: In this case, there exists a (unique up to an integer) continuous function $\alpha: \mathbb{R} \rightarrow \mathbb{R}$ such that $f(e^{2i\pi t})=e^{2i\pi\alpha(t)}$. By definition the degree of $f$ is $\alpha(1)-\alpha(0)$.
Answer: Let us write $q : [0,1] \to S^1$ for the quotient map in order to not confuse it with the real number $\pi$. We have $q = p \mid_{[0,1]}$.
Identifying $(x,y) \in \mathbb R^2$ with $x + iy \in \mathbb C$, we can write $p(x) = e^{2\pi ix}$. Then $f(z) = -z$ and $g(z) = \overline z$.

For  $\alpha = f \circ q$ we have $\alpha(t) = -e^{2\pi i t}$. A lift is given by $\tilde \alpha(t) = t + 1/2$ because $p(\tilde \alpha(t)) = e^{2\pi i(t + 1/2)} = e^{2\pi it} e^{\pi i} = - e^{2\pi it} = \alpha(t)$. Thus $\deg(f) = \tilde \alpha(1) - \tilde \alpha(0) = 1$.
For  $\alpha = g \circ q$ we have $\alpha(t) = \overline{e^{2\pi i t}} = e^{\overline{2\pi i t}} = e^{-2\pi i t}$. Obviously a lift is given by $\tilde \alpha(t) = -t$. Thus $\deg(g) = \tilde \alpha(1) - \tilde \alpha(0) = -1$.


How to make #states work when dependant element is modified with JS .click()

Question: We have custom JS that changes the value of some radio buttons using .click() and we have #states defined in other form elements that react to changes in those radio buttons.
The #states work fine when the radios are manually clicked but don't work when they are clicked through our custom JS .click() (the radio button values change, but the #states are not fired).
This is how the #states is defined:
<code>'#states' => array(
  'invisible' => array(
    ':input[name="field_measure_system[und]"]' => array('value' => 'METRIC'),
   ),
),
</code>
and this is how the JS modifies the radio button:
<code>$('a.tab-metric').click(function() {
$('#edit-field-measure-system-und-metric').click();
</code>
Thanks!
Comment: Instead of `$('#edit-field-measure-system-und-metric').click();` try `$('#edit-field-measure-system-und-metric').attr('checked', true).trigger('click');` or simply ``$('#edit-field-measure-system-und-metric').trigger('click');``
Comment: Quick note: Post jQuery 1.6.1 `.prop()`(and not `.attr()`) method is preferred way to get/set boolean style attributes like 'checked' and 'disabled'. So the above will become- `$('#edit-field-measure-system-und-metric').prop('checked', true).trigger('click');`

I guess I need to change my habit as well :)
Comment: hey @mirnazim! thanks so much for your reply. I'm afraid it doesn't work though :( the two options suggested in the first comment work exactly as now (radios are checked but #states aren't fired).  The one in the second comment doesn't even check the radios (does nothing).  Tricky one !
Comment: Please share some more code in relation to the context. Best way would be to put the relevant JS/HTML on http://jsfiddle.net/ and share the link. It could be the that problem is somewhere other than the code you shared.
Comment: I've put together a [little module](https://github.com/rafamd/states) that creates a field in the user entity (field_measure_system radio buttons) at install time.  It alters the user profile/registration form to add some links (US Metric UK) and a drop down that's conditionally shown with #states.  When going to the registration form, you see that #states works fine when the radios are clicked by hand but not when the US, Metric or UK links are clicked.  The radio buttons selection changes (with states.js) but the #states that depends on that radios seem not to recognize those changes. TNKS!
Comment: on jsfiddle it works !  http://jsfiddle.net/AZdvQ/
Answer: Drupal states are bound to the change event, therefore you need to trigger that one too. The following snipped should do what you want:
<code>$('#id-of-radio-button').trigger('click').trigger('change');
</code>


Image not loading when $_SERVER["DOCUMENT_ROOT"] is inside echo vs inside src attribute

Question: Why does this work:
<img src='<?php $_SERVER["DOCUMENT_ROOT"];?>/images/image.png' width=50 height=50>

But this does not:
$documentroot = $_SERVER['DOCUMENT_ROOT'];
echo("");

Both file paths are correct. The issue is that the first one loads the image but the second one loads the thumbnail error when an image fails to load.
Comment: Because for one thing, you never echo'd the first one and doesn't do anything, where the 2nd one works because you're most likely on a hosted service that only lets you go to the public root instead of the server's system root. Would you like this to be an answer instead of a comment?
Answer: You've got two different (but related) entities here:
$_SERVER['DOCUMENT_ROOT'] gives you the server's native operating system path where the files are stored, like /var/www/mysite/public. The public should never see this.
The src attribute contains the address for the image. This can be a full address starting with http://, an absolute path starting with /, or a relative path.
In the case it starts with a slash, it is interpreted to be anchored at the document root directory. I.e., src="/images/foo.png" means that your file is actually stored in /var/www/mysite/public/images/foo.png. You don't need to ever add the /var/www/mysite/public part -- the web server does that for you.


Existential theory

Question: We have that a formula $\alpha(x_1,x_2,\dots, x_k)$ is existential if it is of the form $$\exists t_1\exists t_2\cdots \exists t_l\beta(x_1,\dots,x_k, t_1,\dots,t_l)$$
where the formula $\beta(x_1,\dots,x_k, t_1,\dots,t_l)$ is quantifier-free, i.e., it doesn't contain the quantifiers $\exists$ and $\forall$.
If the formula $\beta(x_1,\dots,x_k, t_1,\dots,t_l)$ doesn't contain negation, it is called positive existential.
Which is the definition of an (positive) existential sentence?
Is the (positive) existential theory the set of all the (positive) existential formulas or the set of all (positive) existential sentences? Or is the definition of the (positive) existential theory entire different?
P.S. I have posted this question also here.
Answer: Disclaimer: Definitions may vary from person to person, book to book or article to article. Thus if you are reading a book or taking a course, you should refer to that litterature for the definition they mean. The bellow explanations are based on what I percieve as the most common definition.
A sentence is a formula without free variables. Thus a (positive) existential sentence is just a sentence on the form:
$ \exists t_1...\exists t_l\beta(t_1,...,t_l) $ where $\beta$ is quantifier free.
There is no The (positive) existential theory, but rather we say that a theory is existensial if it is a set of (positive) existensial sentences (or possibly possible to axiomatize using such sentences). If we would take the set of all existential sentences it would include things such as $\exists x (P(x) \wedge \neg P(x))$ and thus would be inconsistent.
Comment: Which of the definitions, (positive) existential formula, (positive) existential sentence, (positive) existential theory, is closed under the union ($\lor$) and the intersection ($\land$) ? Or none of them?
Comment: @MaryStar (positive) existential formulas and sentences are closed, up to equivalence, under $\vee$ and $\wedge$ and thus Theories are too.
Comment: What do you mean that they are closed **up to equivalence** ?
Comment: @MaryStar The sentence $(\exists x\,\varphi(x))\land (\exists y\, \psi(y))$ is no longer existential, since it is not explicitly in the form given in Ove's answer. However, it is equivalent to the sentence $\exists x\, \exists y\, (\varphi(x)\land \varphi(y))$, which is existential.
Comment: We say that sentences $\theta$ and $\eta$ are equivalent if for all structures $M$, $M\models \theta$ if and only if $M\models\eta$. Equivalently, your favorite proof system for first-order logic can prove $\theta \leftrightarrow \eta$. Often it's useful to consider the notion of equivalence of sentences *relative to a theory*. So $\theta$ and $\eta$ are equivalent relative to $T$ if for all $M\models T$, $M\models \theta$ if and only if $M\models \eta$, equivalently $T\vdash \theta\leftrightarrow \eta$. The first definition I gave is then the special case that $T$ is the empty theory.
Comment: All of this terminology would be covered very early in almost any introductory book on first-order logic or model theory. I strongly recommend you pick one up and start reading!

Existential theory


What are the sports facilities at the Orlando Disney World?

Question: I've been both a little amazed and confused the past couple of weeks as the NBA and MLS plan to resume play in Orlando after COVID-19 related shutdowns halted the leagues' seasons.
Both leagues are to restart as they hold games at Disney World in Orlando.
What has made me confused - as someone who's never been to Disney World and thinks it's not much more than a massive theme park with some other entertainments - is how are the 2 leagues accommodated at the same time?
We're talking about 100s of players, with multiple games happening everyday (at least in the beginning), hospitality for them and all the coaches, trainers, etc.
I guess all basketball games can happen on 1 court so long as there are no simultaneous games. Soccer would be harder as the pitch quality would be sabotaged with continuous use.
So there would have to be either many fields, or just one artificial turf.
Can artificial turf withstand multiple games a day and still be in shape for top tier matches for weeks? And when teams don't play, they need to practice which requires having few other courts and fields, as well as gyms, and administrative facilities for team meetings, massages, entertainment, etc for many teams all at once.
Since there won't be any fans, the facilities don't need to have capacities for 10s of thousands of fans as usual. But I assume the quality for the athletes should be just as good as their home stadiums/arenas to keep injury rates low, and avoid lower quality of game play.
So are there really enough top tier sports facilities at Orlando Disney World to host both leagues at the same time?
If so, why does it have so much high quality sports facilities? Has it always been a hub for sports?
Or strictly sports talking, the facilities aren't as high level and these leagues and players acknowledge that, yet agreed to play there to finish their seasons?
Comment: Yes, artificial turf can hold up that well. Daily usage of high level for months is within design limits, and can be done for years before replacement, on a high quality surface.
Answer: Disney World Orlando, whilst being renowned as every kids' favourite theme park, is also home to the ESPN Wide World of Sport Complex
This complex includes sporting facilities such as:

The Arena - an indoor complex that can be converted to host 6+ regulation-sized Basketball courts
HP Field House - another indoor complex that can host Basketball (is the current host of the Orlando Invitational college basketball tournament)
Marathon Sports Fields - an outdoor complex comprising of 12 fields, 4 multi-purpose fields, 4 Baseball fields, and 4 Softball fields. Some of these fields are used for the Walt Disney Pro Soccer Classic pre-season tournament, which feature some MLS teams.
There are also facilities for field and track athletics, gymnastics, field hockey, tennis...

Other Venues at ESPN WWOS
Facilities Map
Comment: Great, detailed answer - and amazing how big this is!  I knew it had a lot from my niece going there to play soccer tournaments, but ...


A geometry problem regarding polygons, angles, and diagonals.

Question: The sum of the interior angles in polygon $M$ is $1980$. If the number of diagonals in polygon $N$ is 70 more than the number of diagonals in polygon $N$, then what is the sum of the number of sides on polygons on polygons $M$ and $N$?
Comment: Why did you ask this question?
Answer: The formula for the sum of the interior angles of a polygon is $180(x-2)$ where $x$ is the number of sides.
$180(x-2)=1980$
$x-2=11$
$x=13$
The formula for the number of diagonals in a polygon is $\frac {x(x-3)}2$ where x is the number of sides.
$\frac{13(13-3)}2=65$
$135=\frac{x(x-3)}2$
$x^2-3x-270=0$
$(x-18)(x+15)=0$
The negative value is extraneous, so the number of sides on polygon $N$ is 18.
Therefore, the answer is $13+18=31$.


Induction: How to prove each number can be written as sum of natural numbers such that sum of inverses of these numbers will be 1.

Question:
For every $n>32$, prove that $n$ can be written as sum of a number of natural numbers such that sum of inverses of these numbers will be 1. Suppose the statement is correct for $33, 34, ..., 73$.

I want to prove this by strong induction. if $n$ is even, we know $n=2+2k$. Also $2k=k+k$ and we know $k=\sum{a_i}$ such that $\sum1/a_i$ is 1.
Therefore $2k=\sum(2a_i)$ and for inverses we have: $\sum1/(2a_i) = 1/2*\sum1/a_i = 0.5$
Now since $n = 2 + 2k$, $n = 2 + \sum 2a_i$ and $(1/2 + \sum 1/(2a_i) = 0.5 + 0.5 = 1)$
I'm not sure how can i prove the statement for odd numbers though. Any ideas?
Thanks in advance.
Answer: Same trick, let $N=2k+3+6\ge 75$ be odd. Then $k\ge 33$ is by strong induction "in the good list" of numbers having the given property, we have a representation $k=a+b+\dots+z$ with $1=\frac 1a+\frac 1b+\dots +\frac 1z$, and from here we get
$$
\begin{aligned}
N &=(2a)+(2b)+\dots+(2z)+3+6\ ,\qquad\text{with}\\
1 &=\frac 12+\frac 13+\frac 16
\\
&=
\underbrace{\frac 1{2a}+\frac 1{2b}+\dots+\frac 1{2z}}_{=1/2}+\frac 13+\frac 16\ .
\end{aligned}
$$


anonymous function usefulness

Question: Why not write the anonymous function content only instead of the anonymous function AND the anonymous function content?
Answer: Because you don't write an anonymous function then immediately call it. It's usually passed to some other function that does things with it (e.g. uses the anonymous function to map an array to another array).
Answer: They're commonly used for callbacks. You can't just write the content, because your code doesn't execute it directly.
Comment: If not directly, when is it executed? It doesn't even have a name!
Comment: It is executed whenever the function you pass it to decides, just like if you passed it a named function. As for it not having a name, so what? If you malloc memory in C it doesn't have a name, just an address. An anonymous function is the same. Under the hood you're usually creating a function somewhere on the stack, and really just passing a pointer to that function.
Answer: Probably the biggest use is for one-off functions that won't be used anywhere else or need to be created on demand, dynamically.   That way, they don't need to "pollute" the namespace.
For example, in python:
x_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y_values = map(lambda x: x**x + 2x + 3, x_values)

By using the lambda, I don't need to create a function in the module namespace just for one polynomial (x^2 + 2x + 3).
There are many areas where they come in handy, especially in functional programming (lookup closures or currying, for example).
Answer: It is there so that you don't have to create a function wrapper that is essentially useless.
Answer: They exist because there are lots of times you want to have method semantics with expression syntax.
var l = new List<int>() { 1, 2, 3, 4, 5 };
var a = l.Where( i => i > 3 );  // a = 4, 5

I didn't want to bother writing a new method predicate that checked if an integer was greater than three.  I want the meaning of a method where I can only put an expression.  The anonymous function lets me have both. Woot! :)
Answer: If you are asking "Why use a lambda expression?", then there are a few answers. For one, lambda expressions, being shorthand, are usually easier to read and understand than the much more verbose alternatives of full anonymous functions (i.e. with the delegate() term), or a full blown function and delegate. Lambda expressions are also ideal for performing short, simple, "expressive" computations (i.e. simple mathematics on a set of input), which is quite frequent in software programming.
Lambda expressions are a powerful tool that can help improve the expressiveness, simplicity, and readability of your code.
Answer: I don't know if this even applies, since it is specific to Javascript and I don't see a Javascript tag, but....it's not uncommon to create+call an anonymous function at once. It's often done in the sake of preserving the global scope from variable pollution.
var x = 1;
(function(){
    var x = 2;
})();
x == 1;

anonymous function usefulness


What is the difference between Win 2k3 Server user CALs and Win 2k3 Terminal Server user CALs?

Question: Here are 5 Server 2003 User CALs
Here are 5 Terminal Server 2003 User CALs
apart from the price disparity, what is the difference?
Comment: possible duplicate of [Can you help me with my software licensing question?](http://serverfault.com/questions/215405/can-you-help-me-with-my-software-licensing-question)
Answer: Server CALs allow users to connect to services (ex File Shares, Printers, IIS Sites).
TS CALs allow users to RDP into TS Sessions on the server.
Comment: XP Desktop is restricted to 10 concurrent users and has an extraordinarily limited set of file sharing capabilities compared to Server 2003 (which is also very limited compared to Server 2008 & R2).
Comment: but I can do file shares for free with any xp desktop, why would I need to buy licenses to share folders that are on a win 2k3 server?