Weakly inaccessible cardinal such that $\kappa^{<\kappa}=\kappa$

Question: Was looking at the Cantor's attic page for weakly compact cardinals and thought it was kind of odd that they only stipulate $\kappa^{<\kappa}=\kappa$ when many of the equivalent conditions obviously imply inaccessibility, some even explicitly including it (I'm sure some of the ones I'm unfamiliar with don't imply it, and this particular condition probably has some significance I'm unaware of, but anyway).
That got me thinking about how much weaker the condition $\kappa^{<\kappa}=\kappa$ is than inaccessibility. First off, it holds for successor cardinals if and only if the predecessor satisfies GCH, but let's add the additional condition that $\kappa$ is a limit. It's fairly easy to see that it cannot hold for $\kappa$ singular, so we're left with the case where $\kappa$ is weakly inaccessible but not strongly.
The simplest example I can come up with is that it is consistent relative to some very mild assumptions (I think the consistency of one inaccessible suffices) that $\mathfrak c$ is weakly inaccessible and that $2^\alpha=\mathfrak c$ for all $\alpha < \mathfrak c.$ In this case $\kappa^{<\kappa}=\kappa$ holds for $\kappa=\mathfrak c$ and clearly it is not strongly inaccessible.
(I know this to be true from various results I've seen, but I think this even holds in the situation when we force $\kappa$ Cohen reals into a model of GCH where $\kappa$ is inaccessible... but please correct me if I'm wrong.)

Is there a simpler example (either conceptually or in terms of proof difficulty), or a particularly interesting example of a different character?
Is this an optimal example in terms of consistency strength? (It would seem to be provided my remark above about only needing one inaccessible is correct.)
Answer: So if I understand your question correctly, you are looking for examples in which $\kappa$ is weakly inaccessible, but not strongly, yet satisfies $\kappa^{<\kappa}=\kappa$.
Conceptually, your example is the easiest. First note that to find such an example you need to start with a situiation which has consistency strength at least a (strongly) inaccessible, as  ZFC+ a weakly inaccessible has the same strength as ZFC + a (strongly) inaccessible (this is as any weakly inaccessible is strongly inaccessible in Gödels constructible universe).
Now in this situation, there must be some cardinal $\lambda<\kappa$ so that $2^\lambda=\kappa$. Moreover, after $\lambda$ up to $\kappa$, the continuum function must constantly evaluate to $\kappa$. That is, there is some minimal $\lambda_0<\kappa$ so that for all $\lambda_0\leq\lambda<\kappa$, $2^\lambda=\kappa$.
So the only thing that really is variable is the value of $\lambda_0$. The minimal possible value is, of course, $\omega$, which is exactly your example. Starting with an inaccessible $\kappa$ + GCH, for any regular $\delta<\kappa$ we can find a forcing extension in which $\lambda_0$ is exatly $\delta$.
I am quite sure that it is even consistent that $\lambda_0$ is singular, though this would require much higher consistency strength than just an inaccessible (but dont quote me on that...) [edit: upon further reflection, you may quote me on that. It is however quite interesting how such a singular $\lambda_0$ can look. A prominent result of Shelah gives $\lambda_0\neq\aleph_\omega$. In fact his PCF theory proves that a singular $\lambda_0$ must be a fixpoint of the $\aleph$-function, if I am not mistaken.]. So this might be an interesting example.
Here is another example: In the usual construction of a model in which $2^\omega$ is real-valued measurable (or equivalently, in which there is a countably additive measure on the reals, that measures every subset of $\mathbb R$ and which extends the Lebesgue measure) one starts with a measurable cardinal $\kappa$ (so in particular, $\kappa$ is (strongly) inaccessible) and adds with a specific forcing $\kappa$ new reals. In the extension, $\kappa=2^\omega$ satisfies $\kappa^{<\kappa}=\kappa$, is weakly inaccessible and real-valued measurable. So this is a construction where such a situation naturally pops up.
Comment: Did you mean to say, in the last paragraph, "... a $countably$ additive measure on the reals..." ?
Comment: Starting with a c.t.m. $M$  of ZFCI which satisfies "$k$ is strongly inaccessible", we can get a forcing extension M' that satisfies "$2^{\omega}=k$ and $k$ is weakly inaccessible" and force over M' to get an extension M'' that still satisfies "$2^{\omega}=k$ and $k$ is weakly inaccessible" but also satisfies MA (Martin's Axiom). And MA implies that if $2^{\omega}=k$ then $k^{<k}=k.$
Comment: Yes, you are right, it should have been countably additive. Regarding your first comment, if you force with the finite support product of $\kappa$-many Cohen forcings, then you will automatically get $\kappa^{<\kappa}=\kappa$, no need to additionally force MA.
Comment: Good point about MA.... BTW (but you likely know) that if we assume there is a  least real-measurable cardinal $k$ then by elementary means there is a countably additive measure on $P(\Bbb R)$ that extends Lebesgue measure.


Using NLOPT/Gurobi for solving mixed constraint optimization

Question: I am currently working on a project, and I want to use R and NLOPT package (or Gurobi) to solve the following optimization problem:
Find min ||y-y_h||_L^2 such that x = Ay_h, y >= 0, where x, y are given vector of size 16*1, A = 16*24 matrix is also given.
My attempt:
R code
nrow=16;
ncol = 24;
lambda = matrix(sample.int(100, size = ncol*nrow, replace = T),nrow,ncol);
lambda = lambda - diag(lambda)*diag(x=1, nrow, ncol);
y = rpois(ncol,lambda) + rtruncnorm(ncol,0,1,mean = 0, sd = 1);

x = matrix (0, nrow, 1);
x_A1 = y[1]+y[2]+y[3];
x_A2 = y[4]+y[7]+y[3];
x_B1 = y[4]+y[5]+y[6];
x_B2 = y[11]+y[1];
x_C1 = y[7]+y[8]+y[9];
x_C2 = y[2]+y[5]+y[12];
x_D1 = y[10]+y[11]+y[12];
x_D2 = y[3]+y[6]+y[9];
x_E1 = y[13]+y[14]+y[15];
x_E2 = y[18]+y[19]+y[23];
x_F1 = y[20]+y[21]+y[19];
x_F2 = y[22]+y[16]+y[13];
x_G1 = y[23]+y[22]+y[24];
x_G2 = y[14]+y[17]+y[20];
x_H1 = y[16]+y[17]+y[18];
x_H2 = y[15]+y[21]+y[24];

d <- c(x_A1, x_A2,x_B1, x_B2,x_C1, x_C2,x_D1, x_D2,x_E1,
       x_E2,x_F1, x_F2,x_G1, x_G2,x_H1, x_H2)
x <- matrix(d, nrow, byrow=TRUE)

A = matrix(c(1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, #x_A^1
             0,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0, #x_A^2
             0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, #x_B^1
             1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, #x_B^2
             0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, #x_C^1
             0,1,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0, #x_C^2
             0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0, #x_D^1
             0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, #x_D^2
             0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0, #x_E^1
             0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,0, #x_E^2
             0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0, #x_F^1
             0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,0, #x_F^2
             0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,1,0,0,0,0, #x_G^2
             0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1, #x_G^1
             0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0, #x_H^1
             0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1), #x_H^2
           nrow, ncol, byrow= TRUE)

Tried two codes to solve the problem: min ||y - y_h||_L^2 where x= Ay_h, y>=0 where x,y,A are all given above.
# f(x) = ||yhat-y||_L2
eval_f <- function( yhat ) {
  return( list( "objective" = norm((mean(yhat-y))^2, type = "2")))
}

# inequality constraint
eval_g_ineq <- function( yhat ) {
  constr <- c(0 - yhat)
  return( list( "constraints"=constr ))
}

# equalities constraint
eval_g_eq <- function( yhat ) {
  constr <- c( x-A%*%yhat )
  return( list( "constraints"=constr ))
}

x0 <- y

#lower bound of control variable
lb <- c(matrix (0, ncol, 1))

local_opts <- list( "algorithm" = "NLOPT_LD_MMA",
                    "xtol_rel" = 1.0e-7 )
opts <- list( "algorithm" = "NLOPT_LD_AUGLAG",
              "xtol_rel" = 1.0e-7,
              "maxeval" = 1000,
              "local_opts" = local_opts )
res <- nloptr( x0=x0,
               eval_f=eval_f,
               eval_grad_f = NULL,
               lb=lb,
               eval_g_ineq = eval_g_ineq,
               eval_g_eq=eval_g_eq,
               opts=opts)
print(res)

Gurobi code:
**#model <- list()
#model$B <- A
#model$obj <- norm((y-yhat)^2, type = "2")
#model$modelsense <- "min"
#model$rhs <- c(x,0)
#model$sense <- c('=', '>=')
#model$vtype <- 'C'
#result <- gurobi(model, params)
#print('Solution:')
#print(result$objval)
#print(result$yhat)**

My question: First, when I ran the R code above, it kept giving me this message:
Error in is.nloptr(ret) :
  wrong number of elements in gradient of objective
In addition: Warning message:
In is.na(f0$gradient) :
  is.na() applied to non-(list or vector) of type 'NULL'
I tried to avoid computing gradient, as I do not have any information on the density function of y. Could anyone please help me fix the error above?
For the Gurobi code, I got this message: Error: is(model$A, "matrix") || is(model$A, "sparseMatrix") || is(model$A,  .... is not TRUE
But my matrix A is correctly inputted, so what does this error mean?
Comment: Please do not post pictures of code here. Include a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input data we can copy/paste into R to run.
Comment: @MrFlick: I fixed it. Thank you very much, since i'm new here. But it's annoying to learn that LATEX doesn't work on this forum;p Could you please help me resolve this issue, as I spent ~7 hours on it already, and still could not see how I could avoid using gradient but still makes the "NLOPT" code work:(
Comment: Nobody here wants to help me fix the code above??;)
Answer: I start to use nloptr only several days ago. This question is already an old one but I will still answer it. when you are using 'nloptr' with 'NLOPT_LD_AUGLAG' algorithm, the 'LD' stands for local and using gradient... So you need to choose something else with 'LN' in the middle. For ex., 'NLOPT_LN_COBYLA' should work fine without gradient.
Actually you can just look up the nloptr package manual.


Abstract Algebra: For a group K satisfying H⊂K⊂G, prove that either K=G or K=H

Question: Let $G$ be a (not necessarily finite) group and let $H$ be a subgroup of G with exactly two distinct cosets. For a group $K$ satisfying $H \subset K \subset G$, prove that either $K=G$ or $K=H$.
So far, I have split the proof into two cases.
i) When G is finite and ii) when G is infinite.
For i) I said that since$ |G:H| =2, H=|G|/2$.
Also, $2= |G:H| = |G|/|H| = |G|/|K| x |K|/|H| = (|G:H|) x (|K:H|)$.
I then go to consider if $|G:K|=1$ or $|K:H|=1$.
For ii) I don't know how to proceed as there are no theorems that work with an infinite group. I considered splitting ii) into further cases since an infinite group can have an infinite subgroup of finite order, a finite subgroup of infinite order, and an infinite subgroup of infinite order. However, I am struggling with this portion.
Any help is appreciated in advance!
Comment: Please try to make the titles of your questions more informative. For example, *Why does $a<b$ imply $a+c<b+c$?* is much more useful for other users than *A question about inequality.* From [How can I ask a good question?](https://math.meta.stackexchange.com/a/589/): *Make your title as descriptive as possible. In many cases one can actually phrase the title as the question, at least in such a way so as to be comprehensible to an expert reader.* You can find more tips for choosing a good title [here](https://math.meta.stackexchange.com/a/10144/).
Answer: Even if $G$ is infinite, $|G/H|=2$. If $K$ is an intermediate subgroup, we have $2=|G/H|=|G/K||K/H|$. Since $2$ is prime, $|G/K|$ is either $1$ or $2$. If it is $1$, then $G=K$. If it's $2$, then $|K/H|=1$, so $K=H$.
Answer: You don't need to split into cases.
Suppose $H\ne K$. Then there exists $x\in K$, $x\notin H$.
Take $g\in G$; if $g\in H$, then $g\in K$ by assumption. If $g\notin H$, then $Hg=Hx$ because there are just two cosets, so $h=gx^{-1}\in H$, by definitions of right coset, therefore $g=hx\in K$. Hence $K=G$.
An obvious modification holds for left cosets.
Comment: So, will the proof still be valid if it is split into two cases or would using the left and right coset argument create a better proof?
Comment: @ljc_growl You gain nothing at all by splitting into the finite and infinite case.


what is the odds to catch the virus

Question: Let's see the 7-day average rate to test positive is $4\%$, and I'll be in school for one month. What's the possibility I'll catch a virus this month? $1-0.96^{30}=0.7$, so the possibility is $70\%$ I will catch the virus in one month. This result cannot be right, what's wrong with my model? Thanks.
Comment: @Aksakal Would you believe the events to be independent? // There's a "related" question on the right that gives me an idea for an analogy. Say I want to go to one of the top 30 colleges in the world, each of which has a 4% admission rate. I apply to all, so my chance of getting in is $1-0.96^{30} = 70\%$. I don't believe that number.
Comment: @Dave, schools are probably independent in their decisions, they don't collude. they use common factors, of course, but that's conditional part. think of probability as $y_i=X_i\beta+\varepsilon_i$, then independence is about $\varepsilon_i$ not $X_i\beta$, which can be conditional part
Comment: If you assume that there's 4% to catch a virus in one day, then your number is right. It's a power of compounding! If the propensity was so high, I'd skip the activity.
Comment: @Dave, assumption of independence is implicit here. If OP didnt think the hazard rate is independent then the hazard rate itself is obviously not enough to make conclusions.
Comment: independence assumption is actually quite common in epidemiology models, e.g. take a look at SIR. the problem in these calculations is truly not the independence, but conditionality. you need to personalize the probability to your situation, e.g. risk factors such as health (diabetes etc.) and behavior.
Comment: @Aksakal Maybe that's what I'm thinking in my analogy. If I have a perfect GPA and perfect SAT, I might have a pretty good chance of getting into multiple schools. If I have mediocre scores, I won't get in anywhere.
Comment: Do you mean that 4% test-positive for the first time each day?  Because after Day 25, it'd seem like $\frac{4 \%}{\mathrm{day}} \times 25\,\mathrm{day}=100 \%$ would have tested-positive, assuming no reinfections in that time.  Or assuming that the first 4% keep testing-positive each day?  Or, what'd be the model?
Comment: Also remember testing positive is not necessarily the same thing as having the virus.
Answer: Your computation is right, but the assumption of independence is not met. Your risk of getting an infection on the secand day is not the same as on the first day.
Let's say we are talking chickenpox, which is a "catchy" disease. If one child in your class has chickenpox, you have a high risk of catching it the very first day. If you did not get it on the first day, then there is probably no child with chickenpox in your class and you are quite safe of getting it the next few days.
Let's say we are talking CoVid19. Let's say there is some kind of background immunity gained from other Corona viruses in the years gone by. If the infection rate is as low as 4% on one day because many pupils already have background immunity, then their risk is not going to grow much from repeated exposition.
All these and likely many more are reasons for the assumptions behind your formula not being met.
Comment: that's not how diseases are spread or reported. if you're given 4% unconditional probability of contracting a disease, then this number probably includes the overall environment. in the chickenpox example it would include prevalence of chickenpox in the country. of course, the conditional probability would be drastically different if you knew who's sick. that doesn't invalidate unconditional calculations. you're confusing these things
Comment: Thank you for the discussion. I feel it all depends on the assumption of a 4% positive test rate. If it's based on a large sample and  4% is the infection rate(which is not necessarily equal to the positive test rate), then my model is right, the odds of catching the virus in 30 days is very high. On the other hand, if 4% is based on a small sample, the independence btw. each day doesn't hold, then the odds will be much lower. Thank you, guys!
Comment: forty thousand people have been tested each day on average and the 4% positive test rate is drawn out of them. The population in the city is 80 million. The sample size is only 0.5% of the population, so it's counted as a small sample. The independence doesn't hold here. I never took the case-design class. I hope my reasoning is correct.

what is the odds to catch the virus


3 DIV's - Center Middle and Others taking up rest of room

Question:
I need to have 3 DIV's - you can see 3 colors in the above image.
The middle DIV needs always be 960px and alls needs to be centered (you can see the 2 grey lines above).
The other 2 DIV's need to take up all the other available space. If I zoom in and out of the page the red and yellow DIV's need to expand with the page while the middle green one remains centered.
I've tried DIV solutions and Table solutions and I can't get it to fit.
HTML

any advice would be appreciated.
thx
** Update:
http://jsfiddle.net/scxAq/
working on this... with limited success...
Answer: You need to show us the css code to understand what exactly are you doing.
But from what I understand, I think you need this:
#div2{
    margin-left:auto;
    margin-right:auto;
}

This will center the middle div.
I hope this is what you need.
Answer: Kind of trappy but it should work in a responsive way.
Code:

test

test

test

CSS:
#wrapper {
    width:100%;
    position:relative;
    overflow:hidden;
}
#div2 {
    z-index:2;
    margin:0 auto;
    width:960px;
}
#div1, #div3 {
    position:absolute;
    top:0;
    width:50%;
    z-index:1;
}
#div1 {
    margin-left:-480px; /* half of central div */
}
#div1 > * {
    margin-left:480px; /* half of central div */
}
#div3 {
    right:0;
    margin-right:-480px; /* half of central div */
}
#div2 > * {
    margin-right:480px; /* half of central div */
}

Live demo (try to resize the window)
Answer: HTML

hello world!

 blah balh blah blah balh blah blah balh blah

CSS
.left{
float: left;
width:auto;
background-color:red;
height:30px;
 }
.center{
float: left;
width:960px;
background-color:blue;
margin:auto;
height:30px;
}
.right{
float: left;
width:auto;
background-color:yellow;
height:30px;
}


Cannot build C++ code using lapack

Question: I wrote a simple code to test boost and lapack
But it doesn't work well
My code :
#include  < iostream>
#include < boost/numeric/bindings/traits/ublas_matrix.hpp>
#include < boost/numeric/ublas/matrix.hpp>
#include < boost/numeric/bindings/lapack/syev.hpp>
#include < boost/numeric/ublas/io.hpp>

namespace ublas = boost::numeric::ublas;
namespace lapack = boost::numeric::bindings::lapack;

int main() {
  ublas::matrix<double> A(3,3);
  ublas::vector<double> B(3);
  A(0,0)=1;
  A(1,1)=2;
  A(2,2)=4;
  A(0,1)=.5;
  A(0,2)=.25;
  A(1,2)=.3;

  lapack::syev('V','L',A,B);
  std::cout << A << std::endl;
  return 0;
}

My option g++ to build on ubuntu 10.04
g++ -llapack test.cpp
It's error :
no matching function for call to 'syev(char....... )'
If there's not "lapack::syev('V','L',A,B);" It's build okay!
Plz Help me !!
Answer: Please install the libboost-all-dev package.
Comment: I have installed all package about boost and lapack.I copy folder "boost-numeric-bindings" to /usr/include/boost/numeric and g++ can recognize header from lapack.But it can't call function from lapack !!!!!!!!
Comment: Do you have `liblapack-dev` installed?

Cannot build C++ code using lapack


Correct Intuition? Standard Deviation and distance in $n$ dimensional space.

Question: Basic Question
Is there an intuitive explanation of standard deviation in terms of Euclidean distance in $n$ dimensional space?
Longer Version of Question
To begin a more detailed sketch of my question, for simplicity let's just focus on the simple case of a discrete random variable that is uniformly distributed. In this case, the variance is given by the following formula, which I've abducted straight from Wikipedia:
$$ \frac1{n}\sum_{i =1}^n (x_i - \mu)^2$$
where $\mu$ is the mean. The standard deviation is then the square root of this. Now, I can't help noticing that the square root of the sum returns the euclidean distance from the vector $X = (x_1, x_2, \dots, x_n)$ to the vector $\vec \mu = (\mu, \mu, \dots, \mu)$. That is, the standard deviation can be expressed as:
$$ \frac1{\sqrt{n}}|X - \vec \mu |$$
So I wonder, is there any significant conceptual relationship between this distance $|X - \vec \mu |$ and standard devation or is this just a coincidence?
Even More Details...
I have looked up many explanations of standard deviation and its cousin variance. Here are some that I've seen already, each sort of following from the previous one:

We square the values before summing to get rid of the sign, which is obviously not important. This explanation is often criticised by hardcore statisticians and I can sort of see why: it doesn't explain why squaring beats taking the absolute value.
We square the values so that we pay a greater price for greater deviations. This explains why squaring beats taking absolute values. But why not raise to the power of $4$, or $6$, or any other even power before summing? What is so special about $2$?
The thing that is so special about $2$ is that it's the second moment of intertia, whereas the mean is the first moment, so mechanically it makes sense. I don't follow this. My intuition is totally OK with the mean: the point where, if I put my finger, the weights on either side will balance. But the second moment is harder for me to imagine physically like this.

Note, this is a question about intuition. I "understand" the mathematical formula at a shallow level: what all its terms mean, how to calculate it given a dataset. But I am not comfortable with my grasp on why this formula is "the best" one to use in so many applications e.g. the least squares method to fit data. I'm particularly confused as to why squaring is chosen as opposed to raising to some other even power e.g. $9234324$.
And this is where my intuition steps in and tries to provide an explanation that goes right back to the fundamental theorem of Pythagoras: euclidean distance. Here is my thought process: "The number $2$ is special. It's the unique power that makes Euclidean distance work. So maybe it's also the unique number that makes variance work." But then why the multiplying factor of $\frac1{\sqrt{n}}$? Is it just simply a case of: swallow it up and accept the definition, or can this intuition be resolved somehow?
Comment: Related: https://math.stackexchange.com/questions/1860579/why-work-with-squares-of-error-in-regression-analysis, https://math.stackexchange.com/questions/1621759/neural-network-cost-function-why-squared-error, https://math.stackexchange.com/questions/1872055/is-minimizing-the-squared-errors-optimal
Answer: There is certainly a very clear "conceptual relationship" between the standard deviation and Euclidean distance: If we treat the whole available sample (the $x_i$'s) as a vector, then the Euclidean distance is a measure of how much this vector deviates from the vector containing the mean value, which is "the center" of the population.
But the standard deviation attempts to measure how much a single observation, not the whole sample, deviates "on average" from the mean value. Ah, then, why are we dividing by $\sqrt {n}$ and not by $n$?
Well, this becomes clear if we consider a vector $\mathbf x = (x,x,x,...x)$
Then, euclidean distance becomes
$$\sqrt {\sum_{i =1}^n (x_i - \mu)^2}=\sqrt n |x-μ|$$
So due to the square-root, Euclidean distance is not linearly additive, as we move from the one dimension, to $n$ dimensions : it does not increase by a factor of $n$, but only by a factor of $\sqrt {n}$. So to recover the "individual distance on average" we have to divide by $\sqrt n$.
Comment: Great explanation. I do still worry a small bit about the "on average" bit. We're not exactly measuring "how much a single observation... deviates 'on average' from the mean value". Otherwise we'd be back at just taking the absolute value of the deviations, summing, and dividing by $n$ i.e. $\frac1{n}\sum_{i =1}^n |x_i - \mu|$. Still, this is a good intuitive explanation, thanks for sharing it.
Comment: ...it seems to me like the standard deviation wants to measure how much the *whole* population vector deviates from its average, and then normalise this for the number of elements so that the special case of $(x, x, x, \dots, x)$ gives you back exactly the average deviation...
Comment: @ColmBhadal We also do that, i.e. taking the average of the absolute deviation. It is called, ahem, "average absolute deviation". The use of second moments instead of the absolute deviations, has many arguments behind it, from mathematical convenience, to properties of statistical distributions, to the connection to Euclidean distance... your second comment has promise.
Comment: Yes I feel a bit more settled in my soul about the whole thing now, especially since I recently saw a result (not the proof though) of Gauss relating least squares to the normal curve. Making the second comment a bit more rigorous: We want to normalise the euclidean distance by multiplying it by a function of $n$ so that the result gives exactly the average absolute deviation for a "hyper-cubic" vector i.e. $(x, x, x, \dots, x)$. With this condition, by your above argument, the only solution is to multiply by $\frac1{\sqrt{n}}$. Yes I think I'm satisfied. For now.


Galois group of $f$ is cyclic if $\deg f$ is prime

Question: Hello I am learning Galois Theory by myself and got lost in the following exercise:
Let $f$ be an irreducible polynomial of degree $n$, and suppose that the splitting field of $f$ is generated by a single root of $f$.
a) Show that the Galois group of $f$ is cyclic if $n$ is prime, and that it is either cyclic or a Klein 4-group, if $n = 4$.
b) Let $K$ be any Galois extension of $\mathbb Q$ of degree $n$. Show that there exists an irreducible polynomial
$f$ of degree $n$ having $K$ as its splitting field, and that $K$ can be generated by a single root of this
polynomial.
Thanks
Answer: a) Hint:  The order of the Galois group of a polynomial is the same as the degree of its splitting field. Furthermore, any group  of prime order is cyclic. A group of order $4$ is abelian, and is either cyclic or isomorphic to Klein's Vierergruppe.
b) Hint: Think of the Theorem of the Primitive element.
Comment: However, the order of the Galois group (equivalently the degree of splitting field of $f$) itself might not be prime. For example, it may happen that $\mathrm{Gal} (f) \simeq S _{p} $. In fact, the Galois group of any irreducible polynomial of prime degree $p$ with all but two roots in $\mathbb{R}$, is isomorphic to $S_p$.
Comment: @penseur_32 the splitting field of $f$ is generated by a single root of $f$ so has degree $\deg f$, by assumption.


Why do I get IllegalStateExceptions every time I start an Activity that uses support Fragments?

Question: I use the Android support library to use fragments in pre Honeycomb Applications.
If I add a fragment inside the onCreate method of my activity the activity crashes with an IllegalStateException.
08-04 10:19:49.100: ERROR/AndroidRuntime(18501): FATAL EXCEPTION: main
08-04 10:19:49.100: ERROR/AndroidRuntime(18501): java.lang.RuntimeException: Unable to start activity ComponentInfo{net..../net.....homescreen...Main}: java.lang.IllegalStateException: Activity has been destroyed
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at android.os.Looper.loop(Looper.java:123)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at android.app.ActivityThread.main(ActivityThread.java:3691)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at java.lang.reflect.Method.invokeNative(Native Method)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at java.lang.reflect.Method.invoke(Method.java:507)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at dalvik.system.NativeStart.main(Native Method)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501): Caused by: java.lang.IllegalStateException: Activity has been destroyed
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1257)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:535)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:519)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at net.....AbstractActivity.onCreate(AbstractActivity.java:103)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at net.....homescreen...Main.onCreate(..Main.java:51)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
08-04 10:19:49.100: ERROR/AndroidRuntime(18501):     ... 11 more

The onCreate of the AbstractActivity looks like this:
protected void onCreate(Bundle savedInstanceState) {
    if (menuEnabled) {
        FragmentManager fragmentManager = getCompatibleFragmentManager();
        FragmentTransaction transaction = fragmentManager
                .beginTransaction();
        transaction.add(new OptionsMenuFragment(), OPTIONS_MENU_IDENTIFIER);
        transaction.commit();
    }
    super.onCreate(savedInstanceState);
}

If I debug the call I see that the fragmentmanager throws this exception because the activity is null. It seems that the fragmentmanager is not initialized at all.
What am I doing wrong?
Answer: It turns out that the FragmentActivity from the compatibility packages initializes the fragment manager in the onCreate method itself.
If I move the call to super to the beginning of my onCreate method everything works fine.
Comment: I also get IllegalStateException using Fragments from compatibility library... but it's not related with this, my calls to super are already at the beginning of onCreate (also in the superclasses)
Comment: Nice, just came back with the same problem and was confused that I could not upvote... It seems I'm not a fast learner.
Comment: I have had the same problem with child fragment (both top-level fragment and child fragment were initially added in `onCreate`, after calling `super`). The issue has been solved by moving child fragment creation into `onStart`.


Am using the below Function to decrypt a code ? Could any help to resolve?

Question: function ibp_crypto_decrypt ( p_session_id in RAW) return raw is
l_decrypted_raw     RAW(2048);
l_encrypted_raw     RAW(2048) := p_session_id;
l_key               RAW(128) := UTL_RAW.cast_to_raw('abcdefgh');
begin
dbms_output.put_line('l_encrypted_raw '||'='||l_encrypted_raw);
l_decrypted_raw := DBMS_CRYPTO.decrypt(src => l_encrypted_raw,
                                       typ => DBMS_CRYPTO.des_cbc_pkcs5,
                                       key => l_key);
DBMS_OUTPUT.put_line('Decrypted : ' || UTL_RAW.cast_to_varchar2(l_decrypted_raw))   ;
return l_decrypted_raw;--RAWTOHEX(UTL_RAW.cast_to_varchar2(l_decrypted_raw));
exception when others
then
dbms_output.put_line(' ibp_crypto_decrypt'||'='||sqlerrm||dbms_utility.format_error_backtrace);
end;

ibp_crypto_decrypt=ORA-28817: PL/SQL function returned an error.
ORA-06512: at "SYS.DBMS_CRYPTO_FFI", line 67
ORA-06512: at "SYS.DBMS_CRYPTO", line 44
ORA-06512: at "IBOXV5_TEST.IBK_CRYPTO_ENCRYPTION", line 28

Answer: I've completed your example with the encryption of an actual value and it works as expected. Are you sure you correctly encrypted the value ?
DECLARE
    l_input VARCHAR2(30) := utl_raw.cast_to_raw('12345678');
    l_encrypted_raw RAW(2048);
    l_decrypted_raw RAW(2048);
    l_key RAW(128) := utl_raw.cast_to_raw('abcdefgh');
BEGIN
    l_encrypted_raw := dbms_crypto.encrypt(src=>l_input, typ=>dbms_crypto.des_cbc_pkcs5, key=>l_key);
    l_decrypted_raw := dbms_crypto.decrypt(src=>l_encrypted_raw, typ=>dbms_crypto.des_cbc_pkcs5, key=>l_key);
    dbms_output.put_line('Decrypted : ' || utl_raw.cast_to_varchar2(l_decrypted_raw));
END;
/

Comment: Has the question been resolved by my answer? If yes please accept the answer and close the question or else comment.
Comment: When you use `utl_raw.cast_to_raw` and `utl_raw.cast_to_varchar2` the above error sometimes could happen. When you encode something like `12345678`, it is ok. But if you try something longer, you'll get `ORA-06512: at "SYS.DBMS_CRYPTO_FFI", line 67`
Answer: Oracle support said:

When you are passing the encrypted value to the decrypt function or for storage within database, do not use UTL_I18N.RAW_TO_CHAR instead use RAWTOHEX or UTL_ENCODE.BASE64_ENCODE. Similarly for converting back to raw do not use UTL_I18N.STRING_TO_RAW instead use HEXTORAW or UTL_ENCODE.BASE64_DECODE.

So, the answer depends on how you create RAW value that is passed to your function.
From my experience in Oracle 12.2 using UTL_RAW.cast_to_raw function also sometimes causes ORA-06512: at "SYS.DBMS_CRYPTO_FFI", line 67 in decryption function.


Do I need specific configuration for Spatialite with GeoDjango?

Question: According to https://docs.djangoproject.com/en/1.3/ref/contrib/gis/db-api/, Spatialite supports GeoQuerySet.distance(). However, having imported an area list (MultiPolygon as mpoly attribute), I'm trying to do the following:
Area.objects.all().distance(center)

And instead of something usable, I only get an error message: "ValueError: SQLite does not support linear distance calculations on geodetic coordinate systems."
What's wrong here, do I need some special configuration on Spatialite or is the documentation plain wrong?
Answer: You don't need to do anything regarding spatialite, but rather change the coordinate system (srid) you're using. Spatialite does distance calculations only on geographic coordinate systems, not geodetic. Check the SRID do you have in your model definition. Alternatively you can also switch to the postgis backend.
Comment: Excellent, I've set my Geometry field to 900913 and at least something worked. Have to figure out which projection I really need, but that's a great start. Thanks!
Comment: How to do that in a PointField() ??


Can I set default access settings?

Question: The Webform module defaults to allowing anonymous and authenticated users to submit a form.
The vast majority of the webforms we use are for internal staff that have a particular Drupal role.
Is there a setting for defaulting to a particular role/roles when creating a new form? There seems to be for everything else.
We are using Drupal 9.5.x and Webform 6.1.x.
Comment: Based on https://www.drupal.org/project/webform/issues/2875833 it is likely someone here has to invent a way.
Answer: Looking at webform.api.php there is a specific hook for that:
<code>/**
 * Implements hook_webform_access_rules_alter().
 */
function mymodule_webform_access_rules_alter(array &$access_rules) {
  if (isset($access_rules['create'])) {
    $access_rules['create']['roles'] = ['editor', 'moderator'];
  }
}
</code>
Comment: Many thanks - so the solution to this would be to write a module.  OK, one for the backlog...!

Can I set default access settings?


Evaluate the Basis and Dimension of $V \times W$

Question: I was coming across a question where I had to find the basis and dimension of $V \times W$, where $V$ and $W$ both are finite dimensional vector spaces.
Consider a particular case where $V = \mathbb{R}^2$ and $W = M_2(\mathbb{R})$ over the field $\mathbb{R}$.
I am aware of the dimesions of the vector spaces that I mentioned in the above particular case. I came across with What is the difference between Cartesian and Tensor product of two vector spaces as well. But I couldn't find what exactly the basis will look like in the above case. Also there was a second thought that where exactly the problem occurs if I conclude above's dimension as 8 and not 6, since basis is the smallest spanning and largest linearly independent then there must be a violation for the same as concluding dimension to be 8 will also include 2 linearly dependent vectors. Therefore its tempting to look for the structure of basis. If someone can help?
Thanks in advance :)
Comment: Well $M_{2}(\Bbb{R})$ as a vector space over $\Bbb{R}$ is same as $\Bbb{R}^{4}$ over $\Bbb{R}$. So what do you get when you takr the product $\Bbb{R}^{2}\times \Bbb{R}^{4}$?. It is just $\Bbb{R}^{6}$.
Comment: It could look as $$\left\{\left((1,0),\begin{pmatrix}0&0\\0&0\end{pmatrix}\right),\left((0,1),\begin{pmatrix}0&0\\0&0\end{pmatrix}\right),\left((0,0),\begin{pmatrix}1&0\\0&0\end{pmatrix}\right),\left((0,0),\begin{pmatrix}0&1\\0&0\end{pmatrix}\right),\left((0,0),\begin{pmatrix}0&0\\1&0\end{pmatrix}\right),\left((0,0),\begin{pmatrix}0&0\\0&1\end{pmatrix}\right)\right\}...$$ But in practice, we identify it at $\mathbb R^6$...
Comment: Didn't even realized to look that way, thanks!
Answer: In case you are dealing with a finite product of vector spaces $V_{1}\times V_{2}\times...\times V_{m}$ then often this is denoted by $\displaystyle\bigoplus_{i=1}^{m}V_{i}$ (direct sum) . where $V_{i}$ have dimension $n_{i}$ (say) . Let $\{v_{k}^{i}\}_{k=1}^{n_{i}}=\{v_{1}^{i},...,v_{n_{i}}^{i}\}$ be a basis for $V_{i}$ for each $i=1,2,...m$
Let $(z_{i,j}^{k})_{j=1}^{m}=\begin{cases} v_{k}^{i}\,,i=j\\0\,,i\neq j\end{cases}=(0,0,...,v_{k}^{i},0,...,0)$ for $k=1,2,...,n_{i}$ . That is for a fixed $i$ $z_{i,j}^{k}$ represents the element in the product whose $i$-th component has the $k$-th basis vector  and has $0$ in all other components.
Then $\displaystyle\bigcup_{i,k}\{(z_{i,j}^{k})_{j=1}^{m}\}$ i.e the collection of all $(z_{i,j}^{k})_{j=1}^{m}$ as $i$ varies over $1,2,..m$ and $k$ varies over $1,2,...,n_{i}$ , is a basis for $\displaystyle\bigoplus_{i=1}^{m}V_{i}$  and it's cardinality is $\displaystyle\sum_{i=1}^{m}n_{i}=\sum_{i=1}^{m}\dim(V_{i})$.
Now it will take you a little work to prove that the set as I described above is a basis. Namely you will need to work componentwise and use linear independence of each basis . Showing it is a spanning set is relatively easier. You just take a vector $(x_{1},...,x_{m})$ and write each $\displaystyle x_{i}=\sum_{k=1}^{n_{i}}c^{i}_{k}v_{k}^{i}$ and  write it as $\displaystyle(\sum_{k=1}^{n_{1}}c^{1}_{k}v_{k}^{1},\sum_{k=1}^{n_{2}}c^{2}_{k}v_{k}^{2},...,\sum_{k=1}^{n_{m}}c^{m}_{k}v_{k}^{m})$ and then use linearity.
From these it directly follows that your space will have dimension $4+2$ .
Note that this was a general construction. You will someday learn about Direct Sums or Coproducts and see that a basis is given by $\bigsqcup_{i\in I} \mathcal{B}_i $ for $\bigoplus_{i\in I} V_{i} $ where $I$ can be any indexing set (countable or uncountable) and $\mathcal{B_{i}}$ is a basis for $V_{i}$ for each $i\in I$. Ignore this part if it confuses you right now. Even my notation is not entirely correct but as a set the basis is simply $\bigsqcup_{i\in I} \mathcal{B}_i $.


Reading large datasets from website in pandas returns only 1.000 lines?

Question: I'm trying to brush up my pandas skills by playing around with the open NY Taxi data.
I want to get the data directly from the website in chunks and filter only those rows that happenened in March 2017. When I try to do that for some reason that I do not understand, only 1.000 rows get downloaded. pd.read_csv() does not seem to download the whole file. It seems like only the first 1.000 rows of the file get processed.
How do I get the whole file processed?
I've read up on how to use pd.read_csv() to download data in chunks and then iterate over it. I've played around with the chunksize but to no avail. I still only get around 1.000 rows.
chunk_list = []

for chunk in pd.read_csv("https://data.cityofnewyork.us/resource/biws-g3hs.csv", chunksize=100000):

    chunk["tpep_pickup_datetime"] =pd.to_datetime(chunk["tpep_pickup_datetime"], format='%Y-%m-%d')
    chunk["tpep_dropoff_datetime"]=pd.to_datetime(chunk["tpep_dropoff_datetime"], format='%Y-%m-%d')
    chunk_filter=chunk[(chunk["tpep_pickup_datetime"]>="2017-03-01")&(chunk["tpep_pickup_datetime"]<"2017-04-01")]

    # Once the data filtering is done, append the chunk to list
    chunk_list.append(chunk_filter)

df_concat = pd.concat(chunk_list,ignore_index=True)

df_concat.info()

I would expect to access the whole csv file with it 100m+ rows. When I use df_concat.info() on the result I only ever get 1.000 rows:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 17 columns):
dolocationid             1000 non-null int64
extra                    1000 non-null float64
fare_amount              1000 non-null float64
improvement_surcharge    1000 non-null float64
mta_tax                  1000 non-null float64
passenger_count          1000 non-null int64
payment_type             1000 non-null int64
pulocationid             1000 non-null int64
ratecodeid               1000 non-null int64
store_and_fwd_flag       1000 non-null object
tip_amount               1000 non-null float64
tolls_amount             1000 non-null float64
total_amount             1000 non-null float64
tpep_dropoff_datetime    1000 non-null datetime64[ns]
tpep_pickup_datetime     1000 non-null datetime64[ns]
trip_distance            1000 non-null float64
vendorid                 1000 non-null int64
dtypes: datetime64[ns](2), float64(8), int64(6), object(1)
memory usage: 132.9+ KB

Where do I have to tweak to code to process all rows?
Thanks!
Comment: You'd be better downloading the whole file and reading in chunks. This looks like a conflict with pagination on the site.
Answer: The problem is not about reading. But about the source.
You can manually download and read the file itself ("https://data.cityofnewyork.us/resource/biws-g3hs.csv"), it's only 1000 rows long
You should use this link instead:
pd.read_csv("https://data.cityofnewyork.us/api/views/biws-g3hs/rows.csv?accessType=DOWNLOAD", chunksize=100000)

or better to download it an parse it locally


Base Out State Probabilities by Batting Order Position

Question: I am looking for the number of PA's (Plate Appearances) that occurred in each of the 24 possible base-out states split by batting order position. I am interested especially in the years 2010-2015 in MLB. Baseball Reference provides plate appearances by batting order position, and by base-out state, but not the two combined. Is there anywhere online where this data can be obtained? Thanks.
Comment: I'm not sure this is on topic; or rather, it's specifically *off topic* by the [help] but we're somewhat discussing changing that.  But either way, it seems overly specific... it's possible [opendata.se] would be a better fit for this question.  I am *fairly* confident the answer is that you'd have to pull the information yourself; it's not actually hard to do that, particularly for the period in question (given it's so short).  You can easily pull the PBP data for all 6 seasons from BR and just classify each PA separately.
Comment: You can check out my github repo, https://github.com/snoopy369/Sports.SE , which has some examples of how to do something akin to this - none of them browse PbP pages but the concept isn't substantially more complex (just more pages).
Answer: This post has out state by lineup spot but not base-out state:
https://fantasy.fangraphs.com/runs-and-batting-order/
This one has PA with men on by lineup spot:
https://www.twinkietown.com/2020/5/29/21271449/twinkietown-analytics-fundamentals-come-learn-baseball-with-john-sabermetrics-rbis-misleading-stat
That should get you closer
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/24754)


Delegate software install/uninstall power to users/groups

Question: I would like to have support personnel install and uninstall software across the domain, with no less and no more admininstrative capabilities. How do I do so?
Comment: Run any program that could potentially do anything and require any and all privileges?  Far too broad.
Comment: @GregAskew Yes, and only for a targeted group, as I have mentioned.
Answer: You can't.
You have a few options:

Make users that need to install software (like tech staff) local administrators on client computers. They don't need Domain Admin for this. Use GPP or Restricted Groups in GPO to do this.
Use self-service install options like Group Policy Software Distribution Publishing, where users can add published programs themselves through Add/Remove programs in the control panel. Or use the SCCM 2012 Software Catalog feature, which accomplishes a similar result with more flexibility.
Push software down yourself, so that you don't even need the tech staff to go install it. This is the best, but most complicated way. SCCM, Altiris, LanDesk, and other configuration management systems are what you would use to accomplish this.


Is it possible to create/manage Roles using a .yaml file?

Question: I'm trying to secure some REST URLs that are present in my ApiController.php so that users with certain privileges can access these REST APIs.
I created some users and assigned them with some Roles using the below link:
https://www.drupal.org/docs/user_guide/en/user-concept.html
As you can see, I'm creating roles in Drupal Admin following below steps:
Drupal UI → People → Role → Add New Role     // line 4
After that, I added a few permissions in permission.yml:
xyz.permissions.yml
edit permission:
  title: 'edit permission'

And updated routing file to secure APIs:
xyz.routing.yml
xyz.update:
  path: '/update'
    _controller: 'ApiController::update'
    _permission: 'edit permission'

This is working fine. i.e. users that have "edit permission" can access URL "/update".
But, I don't want to do step on line 4 rather I would like to use some .yaml file to create Roles.
Answer: User roles are defined in YML files called user.role.ROLENAME.yml.
Do a config export (drush cex) to get an idea how these files should look like (they will be written to your config/sync directory).
Then create your custom role YML files in my_module/config/install and they will be created when you enable your module (if you took a YML file from config/sync as blueprint, remove the uuid and default_config_hash keys)
The file should look something like this:
langcode: en
status: true
dependencies: {  }
id: my_custom_role
label: My custom role
weight: 1234
is_admin: null
permissions:
  - 'do fancy stuff'

Comment: @commonpike This is the "super" administrator role thats has ALL permissions enabled by default, without explicitly listing them one by one. E.g. if you install a new module, that super admin role can instantly access everything, without manually adding any new permission from that new module.
Comment: This helped a lot! Thanks
Comment: thanks. what does the 'is_admin' do, or where is this documented ?
Comment: Thanks - still kind of confused, because there is usually only one administrator role - Administrator - is `is_admin` used to create multiple admin roles ? Also, if `is_admin: true` I suppose you don't have to add `permissions`.


Enviar email uma vez por dia

Question: Boa Tarde,
Como eu faço para enviar email uma vez por dia. Eu utilizo o phpmailer.
Eu tentei usar o while, porém não sei que função determina a quantidade de a cada 24 horas.
meu código:

$assunto = "[RemocenteR] Nova Tarefa Cadastrada!";
    $mensagem = "Prezado usuário, foi enviada uma tarefa pelo sistema remocenter para você. Acesse o menu e verique as tarefas pendentes";
    $dadosDaTarefa = '

';
    $dadosDaTarefa .= 'Dados da Tarefa';
    $dadosDaTarefa .= '
';
    if($TA_TAREFA != ""){
      $dadosDaTarefa .= 'Tarefa: ' . $TA_TAREFA;
      $dadosDaTarefa .= '
';
    }
    if($TA_DESCRICAO != ""){
      $dadosDaTarefa .= 'Descrição: ' . $TA_DESCRICAO;
      $dadosDaTarefa .= '
';
    }
    if($TA_PRAZO != ""){
      $dadosDaTarefa .= 'Prazo: ' . $TA_PRAZO_BR;
      $dadosDaTarefa .= '
';
    }
    if($TA_PRIORIDADE != ""){
      $dadosDaTarefa .= 'Prioridade: ' .$TA_PRIORIDADE;
      $dadosDaTarefa .= '
';
    }
    if($TA_SOLICITANTE != ""){
      $dadosDaTarefa .= 'Soliciante: '. $TA_SOLICITANTE;
      $mensagem .= $dadosDaTarefa;
    }
    $mensagem .= '

';
    $mensagem .= 'Mensagem gerada automaticamente pelo Sistema!';

    if(sendMail('email@example.com',$FET_USUARIO['US_EMAIL'], $mensagem, $assunto)){
     echo '';
    }
    echo ("");
  }

Obrigada pela força
Comment: Já ouviu falar de Cron Job? Acho que será a melhor saída.
Comment: Sim, só que é um sistema de tarefas web que eu tenho, e digamos que enquanto a tarefa nao for concluida ele envia um email por dia, lembrando o usuario para finalizar a tarefa. Teria como fazer essa comunicação do cronjob com o meu sistema web ?. Obrigada
Comment: Sim, criar um cronjob pra fazer uma requisição curl pra sua api web que inicializa o script de envio de email diário
Answer: Para isso voce deve utilizar CRON.
O que são as Cron Jobs?
As Cron Jobs são como as Terefas Agendadas do Windows: são tarefas executadas automaticamente de X em X tempos… Fazendo uma analogia à vida real é quando você tira o lixo pra fora ou arruma seu quarto, provavelmente você faz isso seguindo sempre um mesmo intervalo de tempo… De 2 em 2 dias, de 1 em 1 semana e por ai vai.
Como criar uma Cron Job?
Se o seu site roda em algum servidor especializado e você tem um painel de controle como o cPanel recomendo que dê uma olhada lá pois existe uma interface web prontinha para gerenciar as crons… se você não tem esse painel ou não tem acesso à ele vai ter que ir direto ao shell / terminal do seu servidor e começar a gastar o dedo.
A definição de uma cron job consiste em uma linha com 6 valores separados por espaço, assim:
minuto hora dia mes dia-da-semana linha-de-comando

Vamos a alguns exemplos de configuração de tempo antes de criar a cron em si:
Cron Job que rode todo dia as 06:00am
0 6 * * * linha-de-comando

Referencia
Answer: Da forma que está tentando fazer não irá funcionar. PHP é diferente de outras linguagens que fica rodando de forma intermitente no servidor. Ele possui um ciclo de começo, meio e fim. E o fim é o fim mesmo.
Para resolver o seu problema, você pode utilizar CronJobs (Linux) ou o Agendador de tarefas (windows).
A definição é simples: agende a execução diária do seu script. Pode ser programado para rodar a cada 24 horas ou em outros intervalos.
Sendo assim, a cada 24 horas o seu script será chamado e enviará os emails.
Para Cron, pode olhar no link abaixo:
Como rodar cron job no servidor
Cron (ambientes Linux):
1 2 3 4 5 /root/script.php

Para o agendador de tarefas, pode utilizar o link abaixo:
Executar script PHP no agendador de tarefas do Windows
Agendador de tarefas (Task Scheduler - ambientes Windows):
c:/caminhocorreto/php [ -f ] c:/caminho/para/o/script.php

Além do que, o Agendador de Tarefas é visual.
Comment: Obrigada. Vou tentar

Enviar email uma vez por dia


How to find gprs strenght?

Question: I am developing one app related to wi-fi,gprs.
I want to check in two conditions ,
1)if wifi is connected i am getting signel strength and do my work based on strength
2)at the same thing i want to get gprs strength also.
If any one has idea please help me.
Thanks in advance.
Answer: Get an instance of WifiManager, then call isWifiEnabled()
WifiManager wifi = your_context.getSystemService(your_context.WIFI_SERVICE);
boolean wifiEnabled = wifi.isWifiEnabled();

You should be able to scan for networks using startScan(), then call getScanResults(). The scan results contain signal strength info for each network. For more see http://developer.android.com/reference/android/net/wifi/WifiManager.html
I think for GPRS you can get an instance of ConnectivityManager and ask for info on the mobile data connection:
ConnectivityManager cm = your_context.getSystemService(your_context.CONNECTIVITY_SERVICE)
NetworkInfo nw = cm.getNetworkInfo(TYPE_MOBILE)

This will tell you whether you have a data connection or not. I'm not sure how to get signal strength, but I'm sure you'll figure it out if you read some of the docs:
http://developer.android.com/reference/android/net/ConnectivityManager.html
Comment: No use of what the info u provide.ok

How to find gprs strenght?


Finite difference method, boundary conditions

Question: I'm not gonna show every approximation here since I know many of you are familiar with it, but my start equation is:
$$-u''(x)+u(x)=f(x)$$
$$u(0)=0$$
$$u(1)=1$$
I can approximate this using finite difference method (I'm not really familiar with how to write it nicely), but my problem is the boundary condition, how do you know how the vector containing the boundary condition is going to look like, been struggling with this for a while now.
Thanks in advance for any help!
Comment: I would appreciate even a link at this point, I simply cant find a good example....
Answer: Let $h = 1/(n+1)$. Let $u_{0} = u(0)$, $u_{n+1} = u(1)$, $u_{j} = u(jh)$.
Using the second-order finite-difference scheme
\begin{align*}
u''(x) \approx \frac{u_{j+1} - 2u_{j} + u_{j-1}}{h^2}
\end{align*}
our linear system is
\begin{align*}
-u_{j+1} + 2u_{j} - u_{j-1} + h^2u_{j} = h^{2}f_{j}, j = 1, 2, .. n
\end{align*}
If $j = 1$, then
\begin{align*}
-u_{2} + (2 + h^2)u_{1} = h^{2}f_{1}
\end{align*}
and if $j = n$
\begin{align*}
-1 + 2u_{n} - u_{n-1} + h^2u_{n} = h^{2}f_{n}
\end{align*}
which is equivalent to
\begin{align*}
- u_{n-1} + (2+h^2)u_{n} = h^{2}f_{n} + 1
\end{align*}
Can you write down the matrix now?


IOS Status Bar not in its position

Question: I working with an application which consist of two Targets (Paid and free). The In free version the status bar was misplaced somewhere in the screen (Both in ios7 and ios 6.1). But the Paid version working perfectly. Any ideas? Refer below image
Answer: set your iPhone retina 4 launch image 640*1136
Answer: You have forgotten to add the 4" default-image to your project, the email@example.com, so your application is in 3.5" mode.
Comment: Yes, this is what i missed here.

IOS Status Bar not in its position


Number of solutions of equations mod $p^n$

Question: Using Hensel's lemma, it is easy to prove that if $p$ is a prime with $p\equiv 1\mod 3$ then the equation $x^2-x+1=0$ has at least two solutions $\mod p^n$ for all $n\geq 1$. Are there more than two solutions?. Of course, the anwer is not when $n=1$ but what happens if $n\gt 1$?. I have many more equations to analyze so it would be interesting to find an answer for more general equations.
Thanks in advance.
Answer: It is convenient to note that $x$ is a solution of $x^2-x+1\equiv 0\pmod{p^n}$ if and only if $x\equiv -t\pmod{p^n}$, where $t$ is a solution of $t^2+t+1\equiv 0\pmod{p^n}$.
Since $p$ is an odd prime, there is a primitive root $g$ modulo $p^n$. To show that there are exactly $2$ solutions of $t^2+t+1\equiv 0\pmod{p^n}$, it is enough to show that the congruence $t^3-1\equiv 0\pmod{p^n}$ has exactly $3$ solutions. We look for solutions of the shape $g^k$.
We have that $g^k$ is a solution of the congruence $t^3-1\equiv 0\pmod{p^n}$ if and only if $g^{3k}\equiv 1\pmod{p^n}$.
Note that $\varphi(p^n)=(p-1)p^{n-1}$.  Let $p=1+3m$. If we put $k=mp^{n-1}$, then $g^{3k}\equiv 1\pmod{p^n}$. And in general, $g^{3k}\equiv 1\pmod{p^n}$ if and only if  $\varphi(p^n)$ divides $3k$. For $0\le k\lt \varphi(p^n)$, this happens if and only if $k=0$, $m$, or $2m$.
Comment: @Diego: Thanks for the edit!
Comment: question: why did you prefer $t^3-1$ over $t^2+t+1=(t+\frac{1}{2})^2+\frac{3}{4}$ and the three solutions must be counted with multiplicity for $p=3$ the solution $t=1$ is a double root
Comment: The problem is about primes of the form $3k+1$. As to $t^3-1$, it looks nicer than $(t+1/2)^2+3/4$, and a basic chapter in elementary number theory has to do with order. Also, the same idea would work with longer sums. But it is true that $(2t+1)^2+3$ would work nicely, and then it comes down to  $x^2\equiv a\pmod{p^n}$.


Alterar função javascript/php de form para div

Question: pessoal como eu faço para alterar a função abaixo? eu quero exibir a hora em uma div.

 <TITLE>cronometro</TITLE>

<meta name="" content="">

<form  name="clock"><input name="face" value=""></input>
</form>

Comment: Mas o que está errado, a função ou só não está conseguindo exibir a hora em uma div? O seu html está todo errado tbm, tem duas tags body e a tag input não tem tag de fechamento.
Comment: Bom dia  LeAndrade, apesar dos erros que já foram corrigidos está tudo funcionando normal, eu quero apenas retirar o form e o input para colocar a informação em uma div.
Comment: Mas aí então não é só apagar o form e o input e no lugar inserir a div e do mesmo jeito que chamou a função na tag body, chamar na div criada?
Comment: mas eu preciso passar valores para div(name="clock",  name="face", value=" ") como eu faço?
Answer: Para isso, você precisa alterar basicamente 3 linhas. A primeira é a linha
 document.clock.face.value =

Que deve ser alterada para:
document.getElementById("clock").innerHTML =

Logo em seguida, mudar na parte do HTML as linhas:
<form  name="clock"><input name="face" value=""></input>
</form>

Para:

De forma geral, seu código ficará assim:

 <TITLE>cronometro</TITLE>

<meta name="" content="">

Comment: Obrigado David, a principio deu certo qualquer duvida eu volto aqui.
Comment: Opa. Por nada :) Tranquilo
Comment: Boa tarde David, desculpa incomodar mas eu notei que depois de 30minutos/1hora o relógio começa á atrasa você me dizer o porque?
Comment: A princípio não sei. Mas seria atrasar com relação à qual relógio? O do seu próprio computador? Ou um relógio externo?
Comment: do computador, se você colocar esse código para rodar no wampserver e deixar o navegador aberto com ele rodando você vai ver um atraso no segundos.


Adding user meta values to Wordpress admin emails

Question: When a new user registers on our website, they are required to fill out their company information.  This information is stored in the _usermeta table with the meta_key 'company'.
All I want to do is include this information in the notification email that Wordpress sends to the site administrator.  I have had some luck manipulating pluggables.php (where the default email code is located), but I can't get any meta values to send in the email.
Here is my current code:
<code>function wp_new_user_notification($user_id, $plaintext_pass = '') {
    $user = get_userdata( $user_id );
    $user_meta = get_user_meta( $user_id );
    $company = $user_meta['company'][0];

// The blogname option is escaped with esc_html on the way into the database in sanitize_option
// we want to reverse this for the plain text arena of emails.
$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);

$message  = sprintf(__('New user registration on your site %s:'), $blogname) . "\r\n\r\n";
$message .= sprintf(__('Name: %s'), $user->display_name) . "\r\n\r\n";
$message .= sprintf(__('E-mail: %s'), $user->user_email) . "\r\n\r\n";
$message .= sprintf(__('Company: %s'), $company) . "\r\n";

@wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), $blogname), $message);
</code>
The code outputs:
New user registration on your site mywebsite
Name: firstname lastname
E-mail: firstname.lastname@example.com
Company:
I have included get_user_meta() and get_metadata() but the value is always blank.
Any help is greatly appreciated.
Comment: Have you check that `company` is in there in database for a sp. user or not? It might be that while users are registering the `company` meta is not being inserted into database.
Comment: I checked this... for each id, a meta_key is generated as 'company' and a meta_value is added based on their submission e.g. 'McDonalds'
Comment: ok, now use `die();` before `wp_mail` and print `get_user_meta( $user_id )` and check it is returning `company` or not.
Comment: you might not be pulling the data properly,
Just pull the company key directly ```$company = get_user_meta( $user_id, 'company', true);```
Comment: Thanks for the suggestions... pulling the company key directly had the same result and print get_user_meta( $user_id ) returned an empty value for company :/
Comment: @RaunakGupta here is the print Array ( [nickname] => Array ( [0] => firstname.lastname@example.com ) [first_name] => Array ( [0] => test ) [last_name] => Array ( [0] => people ) [description] => Array ( [0] => ) [rich_editing] => Array ( [0] => true ) [comment_shortcuts] => Array ( [0] => false ) [admin_color] => Array ( [0] => fresh ) [use_ssl] => Array ( [0] => 0 ) [show_admin_bar_front] => Array ( [0] => true ) [wpad_capabilities] => Array ( [0] => a:1:{s:10:"subscriber";b:1;} ) [wpad_user_level] => Array ( [0] => 0 ) )
Comment: @fulltimehatr: You array did't have `company` key as expected. I dont know what might be the issue, But manually added a `company` to admin user through `phpmyadmin` and used `echo get_user_meta( 1, 'company', true);` I got the result. you might be having some permission issue from plugin or a specific user might not have that attribute.
Comment: @RaunakGupta thanks for steering me in that direction. The plugin I use is called profilepress and it adds multiple rows to the meta table after the above array. It seems like it sends the email THEN adds the "custom" values to the table. Odd. I may try digging around the code to see if I can prioritize these extra values.
Comment: @fulltimehatr: you are welcome. cheers :)
Answer: I figured out the issue.  The plugin I use to create new users (profile press) was posting the new user, triggering wp_new_user_notification, THEN adding custom values to the meta table.  I moved the meta table function above wp_new_user_notification and the data is transferring as expected.  Should anyone else run into this issue, here is how to solve it:
In wp-includes/pluggable.php, the following works as expected:
<code>$company = get_user_meta( $user_id, 'company', true );
$message .= sprintf(__('Company: %s'), $company) . "\r\n";
</code>
As for profile press, navigate to wp-content/plugins/profilepress/classes/class-registration-form-auth.php and put:
<code>// register custom profile field
if ( ! is_wp_error($user_id)) {
.
//truncated
.
            do_action('pp_after_custom_field_update', $key, $value, $user_id, 'registration');
        }
    }
</code>
above:
<code>    if (is_int($user_id) && 'enable' == $new_user_notification) {
        wp_new_user_notification($user_id, null, 'admin');
    }
</code>
Hope this helps anyone else who has similar issues. Special thanks to @RaunakGupta for pointing me in the direction and credit to profile press for their code.


Is removing points from a calibration rigorous?

Question: When a calibration is generated from a set of standards run on an analytical instrument, should the standards be remade and reanalyzed if not all of the points fit within 20%-30% (depending on regulations) of the regression or give a coefficient of determination of >= 0.99?
I have heard of points being dropped from the calibration if they do not fit well, but isn't that hacking the numbers to get a good fit?
Comment: Hacking would be a polite term for this practice.
Comment: One should check the performance of the analytical instrument in a case like this, particularly if the same standards were measured reliably in the past.
Answer: I don't think your question can be answered without further information.
20 - 30 % of what? Which calibration points/concentrations? For what analyte and what application (matrix!) do you calibrate?
Assuming that in the past (or in other labs) much better calibration was possible, however, I'd recommend to think about the possible sources of the trouble.

As @EdM points out, your instrument may be out of order.
preparing standards afresh and doing a completely new calbration is obviously the thing to do if your standards are degraded or they somehow got contaminated.
Note that I'd either go for a complete set of freshly prepared calibration standards or at the very least I'd recommend some other (reference) analysis of the standards you want to keep. Particularly in case of degradation, how much can you trust the seemingly OK standards?
Excluding points from your calibration in order to get a "nicer" fit will at the very least lead to severely underestimating the expected variance and thus to far too narrow confidence, prediction and tolerance intervals.
There's one possibility how you may still be allowed to do this: validate the calibration with completely new independent test samples and get the error from this validation experiment. However, that would be far more work than redoing a proper calibration with freshly prepared calibration samples.
Note that a relative error of 1/3 is expected at the LOD (limit of detection), and that the LOQ (limit of quantitation) is often defined as the concentration where the relative error falls below 10 %, so if you are calibrating around the LOD, such variation is actually expected behaviour.
Comment: 20 - 30 % of what?

The predicted value of the model.
Comment: My question is not about troubleshooting.  I've been challenged with the claim that it is sometimes acceptable to drop points from a calibration model, but in college I was taught to always run new standards.
Comment: This is Galen from the future. That was meant to be 20 - 30 % **difference** from the expected value of the model, formulated as $$\text{% Difference} = \frac{|y_i - \hat{y}_i|}{ \hat{y}_i} \cdot 100$$ for the ith calibration standard.
Comment: While choice of analyte and matrix are essential considerations for a chemical analysis in general, it is unclear to me what exact relation you had in mind with respect to the statistical control limits of a calibration.


Java: How to print every output of the console either in the console and in a file?

Question: Evening, I have this need:
Every output of the console should be printed into a file but also still in the console. and the /n should be changed with lineSeparator().
How can I achieve that?
Comment: With "every output of the console" you mean everything you send to `System.out`?
Comment: Try System.getProperty("line.separator")
Comment: @UsagiMiyamoto that's right
Comment: Id write a new class with a static method handling messages
Answer: You can assign a PrintStream to System.out with System.setOut().
Thus you have to implement a PrintStream that outputs its input to the old System.out and a file simultaneously. (Overriding the FilterOutputStream.write() method.)
Answer: You can print the output in output file by using FileOutputStream and PrintStream, You can try below code for better understanding.
import java.io.*;

public class ReadFile {
    public static void main(String[] args) throws FileNotFoundException {
        java.io.File outFile = new java.io.File ("File name" );
        FileOutputStream fos = new FileOutputStream(outFile);
        PrintStream ps = new PrintStream(fos);
        System.setOut(ps);
        for(int i = 0 ; i < 5 ; i++) {
            System.out.println(i);
        }
    }
}

This code prints the output in the text file, If the text file does not exist then it creates a new file and then prints output in the file.


SQL Server instance service doesn't start

Question: After manually stopping SQL Server instance service it can not be started both manually from a SQL Server Configuration Manager and automatically by restarting computer. If trying to do it manually I get a message:
The request failed or the service did not respond in a timely fashion. Consult the event log or other applicable error logs for details.
In event log I can see following:
Event ID 7024. The SQL Server (RBSQL) service terminated with service-specific error 126 (0x7E).
I use SQL Server 2008 on Windows XP Pro
Answer: The problem is solved. It was because the VIA  protocol appeared to be enabled. After disabling it (in SQL Server Configuration Manager there are protocols for this instance) everything is OK.


linux korn shell /../.envfile [a]..[b]..[c] meaning

Question: I get an error message when logging in that is similar to below:

Can someone please help me understanding the numbers in brackets ? In case these are some line numbers in referenced files, how to track down to which file, what line content ?
Answer: The general syntax is:
filename[lineno]: functionname[lineno]: nestedfunction[lineno]: error

For example:
$ cat demo
function bar { invalid; }
function foo { bar; }
foo

$ ksh demo
demo[3]: foo[2]: bar[1]: invalid: not found [No such file or directory]

When you use . to source a file instead of calling a function, you see the same thing but with . as the name. I don't know why it doesn't show the filename instead, but hey:
$ cat foo
. ./bar

$ cat bar
# dummy line
. ./baz

$ cat baz
# dummy line
# dummy line
invalid

$ ksh foo
foo[1]: .[2]: .[3]: invalid: not found [No such file or directory]

You can start with your .envfile, look on line 6, follow the file it sources, look at line 65, follow the file it sources, look at line 737, follow the line it sources, and that should be your file with bad line terminators.
Comment: Thank you for the detailed answer, I will check it out.


How to create a windows scheduler job using asp.net mvc web app from cron expression?

Question: I have a question is there any way to create windows scheduler job using ASP.NET MVC web app from my cron expression (string). I have generated this cron expression using a jQuery plugin. After generating cron expression string I need to schedule a job which has to be executed an .exe file on server for given interval of time (cron expression), It can also be a recursive job or simple job.
For example here I generated a cron expression using jQuery plugin to execute an .exe on Every day at 12:00 PM
0 12 * * *
How to create scheduler job using ASP.NET MVC from the above cron expression?
Answer: If you want to use a Windows Scheduler, you need to do a lot of COM-object-related-stuff. Lucky you are, there is nice and shiny a Quartz.net project. Take a look at this
Comment: to work with Quartz.net, do we need to install Quartz.net on my server box? or just Quartz.net dll reference in web app is enough.
Comment: you've got a lot of options here. You can install Nuget package to your application and start Quartz along side your app. Or you can start Quartz in a seperate application (windows service?) and work with them via .NET Remoting. Or you can deploy a whole cluster of standalone Quartz-apps with load-balance and fail-over capabilities.


python module binaries (pep8.exe) not found in python scripts folder if -t flag used

Question: If any python package is installed to different target directory using below command
pip install pep8 -t c:\external --no-cache-dir

then pep8.exe is missing in the c:\Python27\scripts folder. Where will pep8.exe reside in this case?
If I perform normal installation
pip install pep8

Then I see pep8.exe in C:\Python27\Scripts
OS: Windows 7
Python: 2.7.11
Any Idea where the pip.exe is going, when I use -t flag?
Thank you very much in advance
Answer: I figured it out , below command gets/puts the executable(pep8.exe - binaries/scripts coming as part of installation) into C:\Python27\Scripts
pip install pep8 -t c:\external --no-cache-dir --install-option="--install-scripts=C:\Python27\Scripts"

This is applicable for all modules installations


QlikView Default selection trigger - previous + current year minus current month

Question: I want to create a sheet trigger to select the previous year and the current year but not the current month.
If for example we were in 201604...
Sample data is as follows:
201511

201512

201601

201602

201603

201604

Selection I would want would be:
201511

201512

201601

201602

201603

Answer: In the Trigger expression you can use the YearStart function along with the MAX function to get all of the previous year plus the current years months excluding the current month.
='<' & Max(YearMonth) & '>=' & Num#(Date(YearStart(Max(Date#(YearMonth, 'YYYYMM')), -1), 'YYYYMM'), '##')


Prove that a set of functions has the same cardinality as $\mathbb{N}$

Question: Prove that a set of all functions $f:\mathbb N \rightarrow \mathbb N$, which are constant from a certain point, (i.e. a set $\{f\in\mathbb {N^N} \:| \: \exists l\: \exists n \in \mathbb N, \forall k>n, \: f(k)=l\} $) has the same cardinality as
$\mathbb{N}$.
I have a big problem with this task, because I thought that if $f\in\mathbb {N^N}$, then this set (let's call it $X$) can have the same cardinality as $\mathbb R$, not $\mathbb{N}$. Because if $|\mathbb R|=|\mathbb {N^N}|$, then how it is possible that $|X|=|\mathbb{N}|$?
Comment: If $S \subset T$ then $|S| \le |T|$.  Sometimes $|S| = |T|$ but sometimes $|S| < |T|$.  In this case {constant functions} $\subset$ {all functions} and |{constant functions}| < |{all functions}|....  The actual bijection $j:${constant functions}$\rightarrow \mathbb N$ is deceptively simple. If $f$ is a constant function, let $j:f\rightarrow$ the constant that $f$ maps all numbers to.  i.e.  if $f(n) =c$ is the constant function, then $j(f) = c$.  It's that simple.
Comment: An analoguous situation.  $|\mathbb N| = $ "countable".   $\mathbb J_n = \{1,2,3,......n\} \subset \mathbb N$.  But $|\mathbb J_n| = n \ne $ "countable".
Comment: You are right, but since we take only **a part** of the functions $\mathbb{N}\to\mathbb{N}$, we may get a set $Y$ such that $\left|Y\right|=\left|\mathbb{N}\right|$. For example, had we took only the constant functions (i.e. $Y=\left\{f\in\mathbb{N}^\mathbb{N}\mid f\textrm{ is constant}\right\}$), then $\left|Y\right|=\left|\mathbb{N}\right|$ of course.
Comment: I think this problem has a stronger version.
Answer: Your set $X$ is not $\mathbb{N}^\mathbb{N}$; it's a subset. So, there is no contradiction.
For each $n\in\mathbb N$, let $X_n=\{f\in\mathbb{N}^\mathbb{N}\,|\,m\geqslant n\Longrightarrow f(m)=f(n)\}$. Then $X=\bigcup_{n\in\mathbb N}X_n$ and therefore all you need is to prove is that $|X_n|=|\mathbb{N}|$. That is easy, since $|X_n|$ is equal to the cardinal of the set of all functions from $\{1,2,\ldots,n\}$ to $\mathbb N$, which is equal to the cardinal of $\mathbb N$.
Comment: Because the set of all functions from $\{1,2,\ldots,n\}$ to $\mathbb N$ is the set $\mathbb{N}^n$ and $\bigl|\mathbb{N}^n\bigr|=|\mathbb{N}|$.
Comment: Thank you! Everything is much clearer now, but I still can't understand one thing. $\mathbb {N^N}$ is the set of all functions from $\mathbb N$ to  $\mathbb N$.  $\{1,2,…,n\} \in \mathbb N $, so why the cardinal of the set of all functions from $\{1,2,…,n\}$ to $\mathbb N$ is equal to the cardinal of  $\mathbb N$?


Finding a Vector in 3D while you have the angle between a vector and its y axis?

Question: I am trying to find a vector $\alpha$. I have the angle between the vector $\alpha$ and $\beta$ which is $\beta = \begin{pmatrix}0 \\1 \\0\end{pmatrix}$.
To find the angle between them I use this formula:
$\begin{equation*}
\cos\theta =
\frac{\beta\cdot\alpha}{\left|\beta \right|\left|\alpha \right|}
\end{equation*}$
Both the magnitude of the vector $\beta$ and $\alpha$ is 1, so the formula is simplified to
$\begin{equation*}
\cos\theta =
\beta\cdot\alpha
\end{equation*}$
Lets take the vector $\alpha = \begin{pmatrix}\alpha_x \\ \alpha_y \\ \alpha_z\end{pmatrix}$ and $\beta= \begin{pmatrix}\beta_x \\ \beta_y \\ \beta_z\end{pmatrix}$. I have found the $\alpha_y$ by using this formula
$\begin{equation*}\cos\theta = \alpha_x\beta_x + \alpha_y\beta_y + \alpha_z\beta_z\end{equation*}$
$\begin{equation*}\cos\theta = \alpha_x(0) + \alpha_y(1) + \alpha_z(0)\end{equation*}$
$\begin{equation*}\cos\theta = \alpha_y\end{equation*}$
I know the angle between them is 60 degrees which $\theta = 60^{\circ}$. So
$\begin{equation*}\cos(60)= \alpha_y = \frac{1}{2}\end{equation*}$
I tried to find $\alpha_x$ and $\alpha_z$ by using this formula
$\begin{equation*}\sqrt{\alpha_x^2+\alpha_y^2+\alpha_z^2} = 1\end{equation*}$
$\begin{equation*}\alpha_x^2+\alpha_y^2+\alpha_z^2 = 1\end{equation*}$
$\begin{equation*}\alpha_x^2+(\frac{1}{2})^2+\alpha_z^2 = 1\end{equation*}$
$\begin{equation*}\alpha_x^2+\frac{1}{4}+\alpha_z^2 = 1\end{equation*}$
$\begin{equation*}(\alpha_x+\alpha_z)^2 = 1 - \frac{1}{4}\end{equation*}$
$\begin{equation*}\alpha_x+\alpha_z = \frac{\sqrt{3}}{2}\end{equation*}$
If you simplify it again and again. In the end you are left with an unknown and I cant seem to figure out $\alpha_x$.
can I find the $\alpha_x$ and $\alpha_z$ component or is it impossible to find them?
Comment: Careful: $\alpha_x^2+\alpha_z^2\neq(\alpha_x+\alpha_z)^2$ in general.
Answer: I have found the answer. $\alpha = \begin{pmatrix}0.866 \\ 0.5 \\ 0\end{pmatrix}$. $\theta$ is between the vector $\alpha$ and the y axis. So to calculate the $\alpha_x$ is simply $\sin\theta$ which in turm makes the $\alpha_z = 0$


How to read blank cell column value of excel using OpenXML in C#

Question: Here in my Execl Sheet there are some blank value column cell, so When I use This code then in get Error "Object reference not set to an instance of an object".
foreach (Row row in rows)
{
   DataRow dataRow = dataTable.NewRow();
   for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
   {
        dataRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i));
   }

   dataTable.Rows.Add(dataRow);
}

private static string GetCellValue(SpreadsheetDocument document, Cell cell)
{
    SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;

    string value = cell.CellValue.InnerXml;

    if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
    {
        return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
    }
    else
    {
        return value;
    }
}

Comment: On which line you got the error ?
Comment: string value = cell.CellValue.InnerXml;
Answer: The "CellValue" don't necessarily exist. In your case it is "null", so you have your error.
To read your blank cell :
If you don't want format the result depending what the cell contain, try
private static string GetCellValue(Cell cell)
{
    return cell.InnerText;
}

if you want to format your cell before returning the value of it
private static string GetCellValue(SpreadsheetDocument doc, Cell cell)
{
    // if no dataType, return the value of the innerText of the cell
    if (cell.DataType == null) return cell.InnerText;

    // depending type of the cell
    switch (cell.DataType.Value)
    {
        // string => search for CellValue
        case CellValues.String:
            return cell.CellValue != null ? cell.CellValue.Text : string.Empty;

        // inlineString => search of InlineString
        case CellValues.InlineString:
            return cell.InlineString != null ? cell.InlineString.Text.Text : string.Empty;

        // sharedString => search for the SharedString
        case CellValues.SharedString:
            // is sharedPart exist ?
            if (doc.WorkbookPart.SharedStringTablePart == null) doc.WorkbookPart.SharedStringTablePart = new SharedStringTablePart();
            // is the text exist ?
            foreach (SharedStringItem item in doc.WorkbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>())
            {
                // the text exist, return it from SharedStringTable
                if (item.InnerText == cell.InnerText) return cell.InnerText;
            }
            // no text in sharedStringTable, create it and return it
            doc.WorkbookPart.SharedStringTablePart.SharedStringTable.Append(new SharedStringItem(new DocumentFormat.OpenXml.Spreadsheet.Text(cell.InnerText)));
            doc.WorkbookPart.SharedStringTablePart.SharedStringTable.Save();
            return cell.InnerText;

        // default case : bool / number / date
        // return the value of the cell in plain text
        // you can parse types depending your needs
        default:
            return cell.InnerText;
    }
}

Two usefull documentations:

About cell :
https://msdn.microsoft.com/en-us/library/documentformat.openxml.spreadsheet.cell(v=office.14).aspx
About SharedString :
https://msdn.microsoft.com/en-us/library/office/gg278314.aspx


Como receber informações do firebase em um ion-select?

Question: Olá, estou com dificuldade de recuperar informações já armazenadas em outro cadastros em um ion-select. Em um cadastro anterior o Local já é cadastrado e em um segundo cadastro gostaria de receber em um ion-select uma lista de todos os Locais que já foram cadastrados antes.
Preciso apenas dos nomes dos Locais e que seja possível salvar esse nome. em item.local. Segue código que está salvando manualmente sem resgatar do banco so option.
<ion-item>
      <ion-label>Local</ion-label>
      <ion-select [(ngModel)]="item.local" placeholder="Local">
        <ion-option value="Frente 1">Frente 1</ion-option>
        <ion-option value="Frente 2">Frente 2</ion-option>
        <ion-option value="Frente 3">Frente 3</ion-option>
        <ion-option value="Frente 4">Frente 4</ion-option>
        <ion-option value="Frente 5">Frente 5</ion-option>
      </ion-select>
    </ion-item>

Answer: Essa seria a resposta, para quem estiver em dificuldade como eu estava.
<ion-item>
  <ion-label>Status</ion-label>
      <ion-select  [(ngModel)]="item.status" placeholder="Status">
        <ion-option *ngFor="let status of statusList$ | async" value={{status.name}}>{{status.name}}</ion-option>
      </ion-select>
    </ion-item>>


If $f:R \to R$ such that $(f(x))^7=x-f(x)$ find required area

Question: If $f:R \to R$ be a differentiable function such that $(f(x))^7=x-f(x)$, then find
find the area bounded by curve $y=f(x)$ between the ordinates $x=0$ and $x=\sqrt{3}$ and $x-$axis.
(A) $\frac{f(\sqrt3)}{8}[8 \sqrt{3}-(f(\sqrt3))^7-4 f(\sqrt3)]$
(B)  $\frac{f(\sqrt3)}{8}[8 \sqrt{3}-(f(\sqrt3))^7]$
(C) $\sqrt3 f(\sqrt3)-\frac{93}{8}$
(D) None of these.
Here $(f(x))^7=x-f(x)$
Hence $x=(f(x))^7+f(x)$
which gives $f^{-1} (x)=x^7+x$
i.e. but there is no way to reach $f(x)$ itself. Could someone help me with this?
Answer: HINT
We know that $$\int_{a}^{b} f(x) dx+\int_{f(a)}^{f(b)} f^{-1}(x) dx =bf(b)-af(a)$$
This follows as substituting $f(x)=u$, we get
$$\int_{a}^{b} f(x) dx+\int_{f(a)}^{f(b)} f^{-1}(x) dx = \int_{a}^{b} f(x) + \int _{a}^{b} u f'(u) du=\int_{a}^{b} (xf(x))' dx$$
As $(xf(x))'=f(x)+xf'(x)$ from product rule. So we get $$\int_{0}^{\sqrt{3}}f(x) dx+\int_{0}^{f (\sqrt{3})}x^7+x \; dx=\sqrt{3}f(\sqrt{3})$$
As $f(0)=0$ and the inverse of $f(x)$ is $x^7+x$. Can you take it from here?
Comment: How did you write first statement?
Comment: @Mathgeek edited that in. Do you understand?
Comment: Yes.Got it. Thanks.


How to authentic/authorize a backend API for non browser clients in AWS Cognito service?

Question: I am working on a NodeJS application which exposes some APIs. This APIs can be accessed by different vendors (Without any browser). Now I want to know what is the best way to Authentic/Authorize these vendors using AWS Cognito service?

Should I give a client ID (Username) and API_KEY (Password) to my vendors and Validate it through cognito for every subsequent requests. (As of now it is already implemented from the Database)
[OR]
Should I generate a access and Id token for the vendor with MAX validity and give it to the vendor. (I understand this isn't the best practice)

So what should be the best way to achieve this?
Answer: Define app clients in your user pool, one for each of the "foreign" servers. When you create them Cognito will generate an app client id and a secret (if you check that box...and you should check it). In "App client settings" (AWS Console for Cognito) you tell it the client will use "Client credentials." Finally, define whatever custom scopes you think you can leverage to provide finer control of access. These can be different for each client.
Now the foreign server can authenticate/get-authorization by passing in the app client id and the secret, etc., etc. Usual Cognito stuff.


org.apache.logging.log4j.core.config.ConfigurationException: No name attribute provided for Appender layout

Question: I'm using log4j to log into LogOutput.log. I'm getting below error. Can anyone explain the logic. I'm new to logging
'Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: org.apache.logging.log4j.core.config.ConfigurationException: No name attribute provided for Appender layout
at org.apache.logging.log4j.core.config.properties.PropertiesConfigurationBuilder.createAppender(PropertiesConfigurationBuilder.java:212)
at org.apache.logging.log4j.core.config.properties.PropertiesConfigurationBuilder.build(PropertiesConfigurationBuilder.java:158)
at org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory.getConfiguration(PropertiesConfigurationFactory.java:56)
at org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory.getConfiguration(PropertiesConfigurationFactory.java:35)
at org.apache.logging.log4j.core.config.ConfigurationFactory$Factory.getConfiguration(ConfigurationFactory.java:532)
at org.apache.logging.log4j.core.config.ConfigurationFactory$Factory.getConfiguration(ConfigurationFactory.java:456)
at org.apache.logging.log4j.core.config.ConfigurationFactory.getConfiguration(ConfigurationFactory.java:318)
at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:687)
at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:708)
at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:263)
at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:153)
at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:45)
at org.apache.logging.log4j.LogManager.getContext(LogManager.java:194)
at org.apache.logging.log4j.spi.AbstractLoggerAdapter.getContext(AbstractLoggerAdapter.java:138)
at org.apache.logging.log4j.jcl.LogAdapter.getContext(LogAdapter.java:39)
at org.apache.logging.log4j.spi.AbstractLoggerAdapter.getLogger(AbstractLoggerAdapter.java:48)
at org.apache.logging.log4j.jcl.LogFactoryImpl.getInstance(LogFactoryImpl.java:40)
at org.apache.logging.log4j.jcl.LogFactoryImpl.getInstance(LogFactoryImpl.java:55)
at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:655)
at userinterface.PizzaShoppie.<clinit>(PizzaShoppie.java:17)'

here is my properties file
name=LoggerConfigFile

rootlogger.level=DEBUG
rootlogger.appenderRef.file.ref=LoggerAppender

appender.file.name=LoggerAppender
appender.file.type=FILE
appender.file.fileName=log/LogOutput.log

appender.layout.type=PatternLayout
appender.layout.pattern=%d{dd-mmm-yyyy} %level -%m%n

Answer: TL;DR: replace appender.layout with appender.file.layout.
The purpose of a Log4j 2 configuration file is to build a Configuration object with its tree of subcomponents. Whenever you have a simple JavaBean property like "name" you can use:
<component prefix>.name=My configuration name

For properties that are components you use the syntax:
<component prefix>.<unique identifier>.type=<plugin's name>

to set the property on the component. FileAppender's plugin name is "File", therefore you can write (you use "file" as identifier, but it can be anything, e.g. "1"):
appender.1.type=File

to instantiate it and then you need to configure all JavaBean properties of the FileAppender by prepending the prefix appender.1. to the property name:
appender.1.name=LoggerAppender
appender.1.fileName=log/LogOutput.log
...

The same rules apply to nested components of the appender:
appender.1.layout.type=PatternLayout

and so on recursively.


Cannot resolve constructor ViewModelProvider(... .FragmentActivity, ... .ui.viewmodels.profileViewModelFactory)

Question: I'm getting the following error when I hover over the red squiggly line where I'm passing in a custom ViewModelFactory into my ViewModelProvider:

Cannot resolve constructor ViewModelProvider(androidx.fragment.app.FragmentActivity, myproject.ui.viewmodels.profileViewModelFactory)

The profileViewModelFactory code is here:
public class profileViewModelFactory extends ViewModelProvider.NewInstanceFactory {
    @NonNull
    private final Application m_Application;
    private final profileRepository m_newProfileRepo;

    public profileViewModelFactory(@NonNull Application application){
        m_Application = application;
        m_newProfileRepo = ((myapp) application).getNewProfileRepository();
    }

    @SuppressWarnings("unchecked")
    @Override
    @NonNull
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        @NonNull T result;
        if (modelClass.isAssignableFrom(profileViewModel.class)) {
            result = (T) new profileViewModel(m_Application, m_newProfileRepo);
        } else {
            throw new IllegalArgumentException("Unknown ViewModel class");
        }
        return result;
    }
}

The strange thing is that this works fine. No compilation errors whatsoever. It just bugs me that Android Studio flags it at all. Incidentally, it recommends I cast the second parameter to 'androidx.lifecycle.ViewModelProvider.Factory' which does cause the red squiggle to go away only to be replaced by a yellow highlight which states
"Casting 'factory' to 'ViewModelProvider.Factory' will produce 'ClassCastException' for any non-null value"

Which seems to be moving in the wrong direction. If I remember correctly, the error appeared after I made some changes to the gradle. Here's the androidx part:
...

/* androidx  */
implementation 'androidx.fragment:fragment:1.5.0'
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation 'androidx.appcompat:appcompat:1.4.2'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel:2.5.0'
...

Per my research, I did find this and this on SO which are almost my issue (or maybe they are and I'm just not seeing how).
My guess is that I've got more implementations than I need, but I'm not sure which of those (if any) are causing conflicts. Thanks to any who can shine light on this, and I'm happy to add more detail if necessary.
Comment: Is there a reason you are extending `ViewModelProvider.NewInstanceFactory` instead of just `ViewModelProvider.Factory`? That's not a class you should ever be extending.
Comment: Apparently not? I went through and changed all the 'extends ViewModelProvider.NewInstanceFactory' to 'implements ViewMovdelProvider.Factory' and ALL of the squiggles went away. THANK YOU SO MUCH!!

If you refactor your comment as a solution I'll mark it accordlingly. No idea why I was doing that. Maybe an artifact of being up too late and not paying attentionf?
Answer: Generally, you shouldn't be extending ViewModelProvider.NewInstanceFactory, but directly extending the base class, ViewModelProvider.Factory. In this case, NewInstanceFactory isn't providing anything for you (as you don't call super), so the first thing you should try is changing what class you extend to be ViewModelProvider.Factory.


F5 BIG_IP persistence iRules applied but not affecting selected member

Question: I have a virtual server. I have 2 iRules (see below) assigned to it as resources.
From the server log it looks like that the rules are running and they select the correct member
from the pool after persisting the session (as far as I can tell based on my log messages), but the requests are ultimately directed to somewhere else.
Here's how both rules look like:
when HTTP_RESPONSE {

  set sessionId [HTTP::header X-SessionId]

  if {$sessionId ne ""} {

    persist add uie $sessionId 3600

    log local0.debug "Session persisted: <$sessionId> to <[persist lookup uie $sessionId]>"

  }

}

when HTTP_REQUEST {

  set sessionId [findstr [HTTP::path] "/session/" 9 /]

  if {$sessionId ne ""} {

     persist uie $sessionId

     set persistValue [persist lookup uie $sessionId]

     log local0.debug "Found persistence key <$sessionId> : <$persistValue>"
  }
}

According to the log messages from the rules, the proper balancer members are selected.
Note: the two rules can not conflict, they are looking for different things in the path. Those two things never appear in the same path.
Notes about the server:
* The default load balancing method is RR.
* There is no persistence profile assigned to the virtual server.
I'm wondering if this should be adequate to enable the persistence, or alternatively, do I have to combine the 2 rules and create a persistence profile with them for the virtual server?
Or is there something else that I have missed?
Edit: as it turns out, I have missed something. Keep-alive connections interfere with
the rules, so as this support case suggested, I've modified the rules a bit:
when HTTP_REQUEST {

  set sessionId [findstr [HTTP::path] "/session/" 9 /]

  if {$sessionId ne ""} {
     # added this line:
     LB::detach

     persist uie $sessionId

     set persistValue [persist lookup uie $sessionId]

     log local0.debug "Found persistence key <$sessionId> : <$persistValue>"
  }
}

Answer: So when you're looking at the log entries you're seeing the expected information, but the traffic is still ending up somewhere else? Where is it ending up? Also, why two persistence entries for the same session? That may be confusing the system.
You shouldn't need a persistence profile assigned to the Virtual, the iRule should override that anyway, if you have persistence set up there. What do your log entries look like? Also, have you posted to DevCentral yet? More people with F5 experience may see it there. - http://devcentral.f5.com
Have you tried changing the names of the variables? You're using "sessionID" as the variable name in both cases. Variables within iRules are session based, meaning that for the duration of your session with the system the variables remain pinned in memory. If you have both of those iRules executing you'll be over-writing the same variable name with data for both the request and response, which could make your logic checking to see if the sessionID is empty useless. Meaning, if the sessionID gets set on request, but not response, but the response runs the code checking to see if it's empty...it's not going to fail the way you want it to. Different variable names are a good thing.
Other than that, though, your syntax is correct, and unless that issue is causing the confusion it looks like the issue is not with the iRules themselves but with the way the persistence is interacting with the requests.
Colin
Comment: Turns out that the the rules were working properly, but Apache was misconfigured. Still, it's good to know about the scope of the variables. It could cause rad to reproduce issues later.
Answer: In this situation, on the very first HTTP request, you will never log the correct persistence entry based on the above iRules. The reason for this is that persistence is set in another event later on because the F5 has not yet decided which pool member this request will be load balanced to. Since this decision has not been made, it is impossible to create the persistence entry yet. This means that during the life of the entire HTTP_REQUEST event, you will never be able to retrieve the persistence value. You can only do this AFTER the HTTP_REQUEST event has completed and the next event fires. This is why it was working, even though you were not seeing the expected debug data. Instead, try checking it in LB_SELECTED. You will see the entry has been created in that event.