Where can I learn more about these two functions obtained from IFF and XOR?

Question: Given a set $X$, write $\mathrm{heaps}(X)$ for the set of all finite heaps (or 'multisets', if you prefer) on $X$.
Under this definition, it is well-known that if a binary operation $*$ on a set $X$ is

commutative
associative
and has an identity

then this operation gives rise to a function $\Phi : \mathrm{heaps}(X) \rightarrow X$ in a natural way.
For example, the operation $+$ on the real numbers gives rise to the function $\sum,$ defined on finite heaps of real numbers. Similarly, $\times$ gives rise to $\prod,$ etc.
In particular, if we write $\uplus$ for the heapic sum, then $\Phi$ can be characterized as the unique function satisfying $$\Phi(H \uplus I) = \Phi(H) * \Phi(I)$$ for all $H,I \in \mathrm{heaps}(X).$
Now let $X =$ the Boolean domain, which we will denote $\mathbb{B}.$
It is a surprising fact that the operators IFF (denoted $\leftrightarrow$) and XOR (denoted $\not\leftrightarrow$) satisfy conditions 1,2 and 3, at least in classical logic. In particular, they're associative, which I don't find at all intuitive.
Anyway, it follows that $\leftrightarrow$ and $\not \leftrightarrow$ each yield a function $\mathrm{heaps}(\mathbb{B}) \rightarrow \mathbb{B}.$
I'm interested in these functions from both a logical, and an algebraic point of view.
Where can I learn more?

Discussion. Lets denote them as follows.

The function obtained from $\leftrightarrow,$ lets denote $\mathrm{ef}.$
The function obtained from $\not\leftrightarrow,$ lets denote $\mathrm{ot}.$

These names are motivated as follows. For $H \in \mathrm{heaps}(\mathbb{B}),$ we have that $\mathrm{ef}(H)$ is true iff an even number of elements of $H$ are false; similarly, $\mathrm{ot}(H)$ is true iff an odd number of elements of $H$ are true.
Anyway, the functions $\mathrm{ef}$ and $\mathrm{ot}$ have some seriously neat properties.
Here's what I've got so far.
Firstly, we can negate pairs without changing anything. $$\mathrm{ef}(H \uplus \{x,y\}) = \mathrm{ef}(H \uplus \{\neg x, \neg y\}),\;\; \mathrm{ot}(H \uplus \{x,y\}) = \mathrm{ot}(H \uplus \{\neg x, \neg y\})$$
Secondly, negation passes straight through uninhibited.
$$\mathrm{ef}(H \uplus \{\neg x\}) = \neg\mathrm{ef}(H \uplus \{ x\}),\;\; \mathrm{ot}(H \uplus \{\neg x\}) = \neg\mathrm{ot}(H \uplus \{ x\})$$
Thirdly, repeated variables annihilate as follows.
$$\mathrm{ef}(H \uplus \{x,x\}) = \mathrm{ef}(H),\;\; \mathrm{ot}(H \uplus \{x,x\}) = \mathrm{ot}(H)$$
Fourthly, $$\mathrm{ef}(\emptyset) = \top,\;\; \mathrm{ot}(\emptyset) = \bot$$
Fifthly, they're equal precisely when the cardinality of $H$ is odd.
$$|H| \;\mathrm{odd} \implies \mathrm{ef}(H) = \mathrm{ot}(H)$$
$$|H| \;\mathrm{even} \implies \mathrm{ef}(H) \neq \mathrm{ot}(H)$$
Sixthly, they interact nicely.
$$\mathrm{ef}(H \uplus \mathrm{ot}(I)) = \mathrm{ot}(\mathrm{ef}(H) \uplus I)$$
Seventhly, we can split into cases as follows.
$$\mathrm{ef}(H \uplus I) = [\mathrm{ef}(H) \wedge \mathrm{ef}(I)] \vee [\neg\mathrm{ot}(H) \wedge \neg\mathrm{ot}(I)]$$
$$\mathrm{ot}(H \uplus I) = [\mathrm{ot}(H) \wedge \neg\mathrm{ef}(I)] \vee [\neg\mathrm{ef}(H) \wedge \mathrm{ot}(I)]$$
Dualising the above expressions:
$$\mathrm{ot}(H \uplus I) = [\mathrm{ot}(H) \vee \mathrm{ot}(I)] \wedge [\neg\mathrm{ef}(H) \vee \neg\mathrm{ef}(I)]$$
$$\mathrm{ef}(H \uplus I) = [\mathrm{ef}(H) \vee \neg\mathrm{ot}(I)] \wedge [\neg\mathrm{ot}(H) \vee \mathrm{ef}(I)]$$
Comment: On what concerns the mentioned 'non-intuitive' _classical_ associativity of $\leftrightarrow$, it might be interesting to notice that the _intuitionistic_ IFF (or its negation) is indeed **not** associative.
Comment: Comment: what you call $\text{heaps}$ (which I wouldn't call by this name because it is already taken; see http://en.wikipedia.org/wiki/Heap_(mathematics) ) is the monad associated to the adjunction between sets and commutative monoids (see http://en.wikipedia.org/wiki/Monad_(category_theory) ). It is a variation of what is in computer science called the list monad.
Comment: @QiaochuYuan, thanks for the info. Those Monad's in particular look very interesting - closure operators have always been pretty much my favourite concept. Regarding terminology, I use "heap" because I find "bag" vulgar, and because "subheap" is preferable to "submultiset." But if anyone knows of better alternative, I'll gladly change.
Answer: Algebraically, XOR is more usually viewed as the addition in $\mathbb Z_2$ (where 0 corresponds to false and 1 to true), which accounts for many of its nice properties -- in particular for the fact that it's associative. In this role it is often notated $\oplus$, so the multiset extension would be $\bigoplus$.
The multiplication in $\mathbb Z_2$ is just $\land$ under the same identification, so algebra and logic align nicely here. (In fact we can recover the entire logical structure from the ring operations since $A\lor B = A \oplus B \oplus (A\land B)$ and $\neg A=1\oplus B$ -- this provides the correspondence between a Boolean algebra and a Boolean ring, which is any ring in which $x^2=x$ for all $x$).
IFF is simply the De Morgan dual of $\oplus$, so it is associative (etc) as well. Alternatively we can write $(A\leftrightarrow B)=A\oplus B\oplus 1$, so by associativity and commutativity,
$$ a_1 \leftrightarrow a_2 \leftrightarrow \cdots \leftrightarrow a_n =
a_1 \oplus a_2 \oplus \cdots \oplus a_n \oplus \underbrace{1\oplus\cdots\oplus1}_{n-1\text{ ones}}$$
where the underbraced part is either $0$ or $1$ according to whether $n$ is odd or even.
The fact that negation "passes through" these operators can be explained by the fact that $\neg A = 1\oplus A$, and the "lifting" of negations out of $\oplus$ is then just associativity. Since $1\oplus 1=0$, an even number of negations cancel each other out.
Comment: Thanks. If there's anywhere good for learning more about $\mathbb{Z}_2$, please indicate tell. The problem is that for $n \geq 3$, the groups in the family $\mathbb{Z}_{n \geq 3}$ lack most of the structure that makes $\mathbb{Z}_2$ interesting; in particular, I don't think there's anything like negation for the groups in $\mathbb{Z}_{n \geq 3}.$
Comment: Also, I really like the way you explained the connection between $\leftrightarrow$ and $\oplus$. I sort of new it already, but the way its written in your answer is just crystal clear.
Comment: @user18921: I'm not aware offhand of any source dedicated to $\mathbb Z_2$. Most of the "interesting" structure you speak about is probably a feature of the ring having characteristic 2 (which means that addition and subtraction are the same operation), or possibly of being a Boolean ring (which implies characteristic 2). You definitely want to study some _ring theory_ here (the group structure is not enough to express all the interesting facts). Most abstract algebra textbooks should give it (though mixed with lots of other suff).
Comment: Cryptography and (in particular) coding theory make heavy use of higher algebra with $\mathbb Z_2$ as the base field, so it is possible that a text in one of these areas would contain a succinct overview of it. I don't have any titles to name, though.


Calculating the variance of a weight-average when the weights also have a variance

Question: Assume there is a series of random variables $X_1$, $X_2$, ..., $X_N$ representing a series of values to be weight-averaged, and a corresponding series of random variables $W_1$, $W_2$, ..., $W_N$ representing the weights themselves.
Let us define the random variable $Z$ to be the result of the weight-average, that is:
$Z = \frac{\sum_i X_i W_i}{\sum_i W_i}$
If we assume that all the random variables are independent, and we know that expected value and variance of all the random variables (other than $Z$), is it possible to calculate the expected value and variance of $Z$ analytically?
My intuition tells me that $E[Z] = \frac{\sum_i E[X_i] E[W_i]}{\sum_i E[W_i]}$, and I have run experiments that suggest this is the case, but I'm unable to prove it.
Is there an analytic solution to calculating $VAR[Z]$ and $E[Z]$?
Comment: Is there any restriction on the distribution of the random variables?  Are they all normally distributed for example?  I'm not sure this will affect the answer but it might be helpful to know.
Comment: It's safe to assume that all the variables are normally distributed about their means.
Answer: If your two random variables $W_i$ and $X_i$ are independent, then from the law of total expectation the expectation of the product of two random variables is the product of their expectations, eg $E[X_i W_i] = E[X_i] E[W_i]$.
As for the Variance, this is defined in terms of the square of the variable, eg:
$$
\text{Var}(Z_i) = E[Z_i^2] - E[Z_i]^2
$$


Connecting points in ggplot2 graph with lines

Question: So as said in the question I want to connect points in ggplot2 graph. The points should be connected one after another in the order they are plotted to the graph, like this :

Sorry for the bad drawing.

basepop <- matrix(c(10,30),nrow = 2)
matrixA <- matrix(c(0.4,-0.325,0.3,1.2),nrow = 2)
matrixA
z <- eigen(matrixA)
z$val
eigenmatrix <- z$vec
eigenmatrix
eigeninverse <- solve(eigenmatrix)
constmatrix <- eigeninverse %*% basepop
constmatrix

popdata = NULL

for(k in 1:100){
  predator <- c(constmatrix[1,1]*z$val[1]^k*z$vec[1,1] + constmatrix[2,1]*z$val[2]^k*z$vec[1,2])
  prey <- c(constmatrix[1,1]*z$val[1]^k*z$vec[2,1] + constmatrix[2,1]*z$val[2]^k*z$vec[2,2])

  popdata = rbind(popdata, data.frame(k,predator,prey))
}
library(ggplot2)
ggplot(popdata, aes(predator, prey, color = k)) +
  geom_point()

ggplot(popdata, aes(k, predator, color = k)) +
  geom_point()

ggplot(popdata, aes(k, prey, color = k)) +
  geom_point()
print(popdata)

This is my code for calculating the pop of a prey and predator system.
Comment: At `geom_line()` at the end!
Answer: From @Duck's comment: just add + geom_line() or + geom_path() to a plot. ("Which to use" depends on your use: geom_line connects by the order on the x-axis, geom_path connects in the order they appear in the data, both have valid uses. In this case they appear to be the same, but keep this in mind if your real data changes.)
ggplot(popdata, aes(predator, prey, color = k)) +
  geom_point() +
  geom_line()

(Similarly for the other plots.)
I should note that order matters.
# left
ggplot(popdata, aes(predator, prey, color = k)) +
  geom_point() +
  geom_line(color="black")
# right
ggplot(popdata, aes(predator, prey, color = k)) +
  geom_line(color="black") +
  geom_point()


Get all row from first table and 1 matching row (column) from another table using JOIN

Question: I have two table related to image gallery, first table stores albums name and second table store album image, i need to show all albums on one page (albums) and related images on the second page (album-photos)
on first page i have to show Album Name & Image but problem is the album table (Albums) doesnt have any Album related image. so i want to take any image from table (AlbumImages) which has all the images related to album.
I tried below JOIN query it pull all teh matching record from both table while i want only any image related to album so that i can show it on the Album Page
  SELECT a.AlbumID,Title,AlbumImageName, Description,AlbumDate,AlbumType FROM Albums a LEFT OUTER JOIN AlbumImages i
  ON a.AlbumID = i.AlbumID
   WHERE AlbumType = 1
  AND  a.IsVisible=1  AND a.IsActive=1
   ORDER BY AlbumDate DESC

Table Structure
Albums (AlbumID,Title,AlbumDate,AlbumType,IsVisible)
AlbumImages(AlbumImageID,AlbumID,AlbumImageName,ImageCaption,ImageOrder,IsVisible)
How can i simple show details from first table and any image one related to album on album page since Albums Table doesn't store any image related to album in Albums table
Answer: You could use ROW_NUMBER with a random/unspecified ordering, and just retain the "first" image record for each album:
WITH cte AS (
    SELECT a.AlbumID, a.Title, i.AlbumImageName, Description, a.AlbumDate, a.AlbumType,
        ROW_NUMBER() OVER (PARTITION BY a.AlbumID ORDER BY (SELECT NULL)) rn
    FROM Albums a
    LEFT JOIN AlbumImages i ON a.AlbumID = i.AlbumID
    WHERE AlbumType = 1 AND a.IsVisible = 1 AND a.IsActive = 1
)

SELECT AlbumID, Title, AlbumImageName, Description, AlbumDate, AlbumType
FROM cte
WHERE rn = 1;

Comment: i am getting error for this CTE `The column 'AlbumID' was specified multiple times for 'cte'.` not sure to where `AlbumID` is specified multiple times..
Comment: @student Thanks for pointing this out.  Try the updated version, where I explicitly list out the columns in the CTE, including `AlbumID` only once.  This should fix the problem.


Qual é a melhor forma de fazer vários pedidos a uma API?

Question: Eu vim colocar esta pergunta mais uma vez achando que seria benéfico a comunidade ter uma forma canónica de fazer vários pedidos http a uma determinada API.
Mais concretamente esta pergunta motivou-me a colocar a minha questão.
Qual é a melhor forma de fazer vários pedidos a uma API? (Tenha em conta em reduzir ao máximo o tempo necessário para obter todas as respostas)
Para ser um pouco mais concreto: Como posso obter as primeiras 10 páginas da api do stackechange, sendo https://api.stackexchange.com/2.2/answers?page=1&pagesize=10&order=desc&sort=activity&site=stackoverflow a primeira página.
Answer: Utilizando Tasks
A ideia é fazer os pedidos assincronamente e adicioná-los a uma lista de tasks com todos os pedidos. Depois espera-se pelas respsotas com Task.WaitAll:
var tasks = new Task<string>[10];
var api = "https://api.stackexchange.com/2.2/answers?page={0}&pagesize=10&site=stackoverflow";
using(var client = new HttpClient()){
    for(int i = 1 ; i < 11; ++i){
        var url = string.Format(api, i);
        tasks[i-1] = client.GetAsync(url)
            .ContinueWith(t => t.Result.Content.ReadAsStringAsync())
            .Unwrap();
    }

    Task.WaitAll(tasks);
    foreach (var resposta in tasks){
        Console.WriteLine(resposta.Result);
    }
}

Na verdade esta outra pergunta questiona esta mesma abordagem.
Uma alternativa (segundo uma medição rápida) mais eficiente do que a de cima e eventualmente mais compreensível pode ser obtida com a utilização da keyword await:
var tasks = new List<Task<HttpResponseMessage>>();
using (var client = new HttpClient())
{
    for (int i = 1; i < paginas; ++i)
    {
        var url = string.Format(api, i);
        tasks.Add(client.GetAsync(url));
    }

    var respostas = await Task.WhenAll(tasks);
    var todas = new List<string>();
    foreach(var resposta in respostas)
    {
        todas.Add(await resposta.Content.ReadAsStringAsync());
    }
    return todas;
}

Mas nunca faça o seguinte código:
var respostas = new List<string>();
using (var client = new HttpClient())
{
    for (int i = 1; i < paginas; ++i)
    {
        var url = string.Format(api, i);
        var resposta = await client.GetAsync(url);
        respostas.Add(await resposta.Content.ReadAsStringAsync());
    }
}
return respostas;

Com este código os pedidos não estão a ser feitos de forma paralela e demoram por isso mais tempo.
Comment: @TobyMosque `await` só seria necessário se eu optásse por usar `Task.WhenAll` em vez de `Task.WaitAll`. Se eu usar `await` dentro do for vou demorar 10x mais tempo a executar o código.
Comment: @TobyMosque Tive a fazer uma experiência e parece que o .Net é mais esperto do que estáva à espera. Em vez de demorar 10x mais ele demora "apenas"  vezes. Eu vou postar uma alternativa em que obtive um tempo de computação ligeiramente menor e que utiliza o `await`.
Comment: Bruno, aconselho que uso as palavras chave async/await
Comment: você pode tentar usar o `Parallel.For(0, 10, async i => { ... return await client...Unwrap() });`
Comment: a minha preocupação é caso a API demore a responder, seja por instabilidade na sua aplicação, na camada de Transporte ou na propria API. neste caso o `await` pode lhe ajudar à manter a escabilidade da sua aplicação ao evitar que recursos fiquem presos sem necessidade.
Comment: @TobyMosque Não sei se o estou a perceber. Esperar por todos os pedidos ao mesmo tempo é melhor do que esperar um por um, a não ser que haja preocupações com memória. Falhas de transporte, ou servidor menos responsivo podem ocorrer quer com 1 pedido quer com n pedidos e nada evita disso.
Comment: apenas apontei o motivo pelo qual eu mencionei o uso de async/await, em todo caso a sua segunda alternativa me parece muito boa.


Specialize a Template Function to Generate a Compile-Time Error

Question: How does one specialize a template function to generate an error at compile-time if a user attempts to call said function with a given template parameter?
I was able to get this behavior for a template class by using the following idiom...
template <typename T>
class MyClass< std::vector<T> >;

The basic signature of the function which I am trying to modify is...
template <typename T>
T bar(const int arg) const {
  ...
}

If I use the same paradigm that I used to disallow certain template classes...
template<>
std::string foo::bar(const int arg) const;

I can generate a linker error, which I suppose is more desirable than a runtime error, but still not really what I'm looking for.
Since I am not able to use C++11, I cannot use static_assert, as described here. Instead, I am trying to use BOOST_STATIC_ASSERT like so...
template<>
std::string foo::bar(const int arg) const {
  BOOST_STATIC_ASSERT(false);
  return "";
}

However, this generates the following compile-time error, even when I am not trying to call an instance of the function with the template parameter I am attempting to disallow...
error: invalid application of 'sizeof' to incomplete type 'boost::STATIC_ASSERTION_FAILURE<false>'

I found this post, but it doesn't really offer any insight that I feel applies to me. Can anyone help?
Comment: Hmm maybe you can use this [link](http://en.cppreference.com/w/cpp/types/type_info)
Comment: An explicit specialization of a function template is like a simple function, so any static assert will always trigger.
Comment: @Sumsar1812, to which link are you referring?
Comment: Is this what you're suggesting...
`BOOST_STATIC_ASSERT(typeid(std::string) != typeid(T));`
That throws compiler errors...
`error: 'typeid' operator cannot appear in a constant-expression`
Comment: What is `foo`? A namespace, a class?
Answer: Use boost::is_same to generate a compile-time boolean value that can then be used with BOOST_STATIC_ASSERT to perform the check.
template <typename T>
T bar(const int)
{
  BOOST_STATIC_ASSERT_MSG((!boost::is_same<T, std::string>::value),
                          "T cannot be std::string");
  return T();
}

bar<int>(10);
bar<std::string>(10);  // fails static assertion

Live demo
Comment: @DanForbes Notice the extra set of parentheses in my example? :) Without those the comma in `is_same` is interpreted as an argument separator by the preprocessor. Also, you need `BOOST_STATIC_ASSERT_MSG` is you want to add a message.
Comment: This throws an (unwanted) compile-time error...
`BOOST_STATIC_ASSERT(!boost::is_same::value, "my message");` produces `error: macro "BOOST_STATIC_ASSERT" passed 3 arguments, but takes just 1` and `error: 'BOOST_STATIC_ASSERT' was not declared in this scope`. Note that I called `BOOST_STATIC_ASSERT(true)` without issue.
Comment: Derp. Accepting this answer as it is simple and provides the exact behavior I am looking for.
Answer: It seems C++ don't allow specialize template member function. So if you want to use same interface, you should use other technology. I'd like to use trait_type to implement this.
template <class T>
struct is_string : false_type {};
template <>
struct is_string<string> : true_type {};

template <typename T>
class MyClass {
 private:
  T bar(const int arg, false_type) const {
    return T();
  }

  std::string bar(const int arg, true_type) const {
    return "123";
  }
 public:
  T bar(const int arg) const {
    return bar(arg, is_string<T>());
  }
};

If you can not use C++11, you must implement false_type and true_type yourself. Or you can use specialize template class.
Comment: Although I appreciate your answer, and it may work, the answer provided by @Praetorian above is much simpler and provides the exact behavior I am looking for.
Comment: I'm pretty sure `std::true_type` and `std::false_type` were in C++03 weren't they?  Or at least in TR1?
Comment: @MooingDuck Only in TR1.
Comment: C++ allows to (fully) specialize a template member function. But the question isn't about it. Your code compiles successfully even with `std::string` passed as a template parameter.


How to calculate sum of squared errors (SSE or SSR) with Stata 12 software?

Question: I have a techincal issue with Stata: I need to calculate the SSE of a regression model, but the automatic output just gives me RMSE; I need SSE of this constrained model because I have to test if this model is better than the completely-free model.
SPSS gives me the SSE value in the regression output, but I don't know how to calculate a constrained linear regression with this model.
Comment: What command are you using? `regress` automatically displays a table with the sums of squares.
Answer: If you are insane enough to literally try to compute the difference of the two sums of squares and relate it to an F distribution, you can certainly do that:
sysuse auto, clear
* (i) run full regression
regress price mpg foreign
* (ii) look into Stata guts
ereturn list
* (iii) take the pieces that you need
scalar ss_model_full = e(mss)
scalar ss_residual_full = e(rss)
scalar dfres_full = e(df_r)
* (iv) run constrained regression
regress price foreign
scalar ss_model_constr = e(mss)
scalar ss_residual_constr = e(rss)
scalar dfres_constr = e(df_r)
* (v) construct the test statistic
scalar F = ( ss_model_full - ss_model_constr) / (ss_residual_full/dfres_full)
display scalar(F)
* (vi) relate it to its reference distribution
scalar p_F = Ftail( dfres_constr - dfres_full, dfres_full, F)
display scalar(p_F)

All the crap starting from (ii) is completely unnecessary and is fully taken care of with
test mpg
* look into the guts
return list

I would even go as far as to say that the reason they've written statistical software is that you won't have to do all the coding, introducing errors (statistical errors, code typos, references to wrong data, etc.) along the way.
Comment: I'm using the interface commands: Linear models > Constrained linear regression
Comment: Wow. Never used Stata interface in 15 years of working with Stata on a daily basis :). So what kind of constraints do you deal with? Constrained regression in Stata is meant to deal with linear constraints of the form $\beta_1 + \beta_2 = 1, \beta_3 = \beta_4 - \beta_5$ and the like. You can test these constraints with `test`, too, following the encompassing unconstrained regression. If your constraints are $\beta_1=0$, then that's equivalent to incuding/excluding variables from regression equation, and that's what I described above.
Comment: My constraint is: beta1 + beta4 - beta2 - beta3=0
Comment: Just `test` it, then.
Comment: I've tested the hypothesis with the test command; bytheway, the alternative hypothesis used is symmetric; I need an asymmetric alternative hypothesis, how can i do?


The interior of a countable set is always empty?

Question: By reading my lectures notes, I stumbled on one justification of a fact that seemed pretty non intuitive for me. It's obvious that $\mathring{\mathbb{Z}} = \emptyset$, but the justification given by my teacher is that simply because $\mathbb{Z}$ is a countable set. So I wonder, what would the proof of this look like?
Answer: If by set you mean "subset of $\Bbb R$" then any non-empty open set
contains a nontrivial open interval $(a,b)$ and that is an uncountable set.
So any set with a non-empty interior is uncountable.


EntityFieldQuery gives error on adding propertyCondition

Question: I have to list down taxonomy term ids which should be greater than a specific tid.
Below is the code I am using:-
<code>$query = new EntityFieldQuery();

$tid = variable_get('last_player_update'); //last index of player update

$query->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition( 'tid',  'value', $tid, '>=')
  ->propertyCondition('vid', 3)
  ->propertyOrderBy('tid', 'ASC')
  ->range(0, 1000);

$result = $query->execute();
</code>
On executing the script I am getting the following error:-
<code>PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '9174 'value') AND (taxonomy_term_data.vid = '3') ORDER BY taxonomy_term_data.ti' at line 1: SELECT taxonomy_term_data.tid AS entity_id, :entity_type AS entity_type, NULL AS revision_id FROM {taxonomy_term_data} taxonomy_term_data WHERE (taxonomy_term_data.tid 9174 :db_condition_placeholder_0) AND (taxonomy_term_data.vid = :db_condition_placeholder_1) ORDER BY taxonomy_term_data.tid ASC LIMIT 1000 OFFSET 0; Array ( [:db_condition_placeholder_0] => value [:db_condition_placeholder_1] => 3 [:entity_type] => taxonomy_term ) in EntityFieldQuery->execute()
</code>
What I am missing in the above code snippet?
Answer: Fields have columns. Properties do not. You want:
<code>$query->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition( 'tid',  $tid, '>=')
  ->propertyCondition('vid', 3)
  ->propertyOrderBy('tid', 'ASC')
  ->range(0, 1000);
</code>


How do you strip HTML from the node summary that appears on taxonomy node listing pages?

Question: I've tried using hook_preprocess_node() inside of a if statement for arg(0) == 'taxonomy', but changes to the node aren't carried through to display.
What is the best way to make the teasers appear in plain text (stripped HTML) when listing in the taxonomy node listing page?
Answer: Within node--taxonomy.tpl.php, you could isolate the field data for your teaser or any field, depending on how you have that template set up, and apply the php strip_tags to that field data.
For example:
$teaser = render($content['body'][0]);
$textteaser = strip_tags($teaser);

This video is a great starting point for learning about the theming templates if that is new: Theming Fields and Nodes with Templates

One other idea is to isolate the div that wraps each teaser (if possible) and use jQuery to transform the content using the relevant CSS selector using .text() method.
Comment: I was really looking for the best place to find the teaser. Thanks.
Comment: I assumed you weren't supposed to put any logic in the tpl files, but I guess this is the only method here.
Comment: I'm sure there is another method. I wish I knew it, this is just the only way i would know how to go about it...


Bars 32-37 in Moonlight sonata first movement

Question: I am having trouble playing and memorizing the broken chords sequence:

Should I try and practice on each triplet individually? because when I try to think on it as a broken chord I often can not play it correctly. Any other tips will be welcomed.
Answer: There are a number of great ways to practice any given pattern. Taking the rhythmic skeleton of your passage, you can apply 3 different Duple-based patterns, each with two 16ths and an 8th. Modifying the rhythm of each triplet thusly helps to develop 3 overlapping schema for each possible way to group 3 notes. Note, it's better to think of these, not as three different rhythm patterns but as three different starting points for a rapid group of 3 notes.
The obvious thing to do next would be to add more notes.

In this case, you'll want to start to overlap, practicing the first triplet plus 2nd downbeat, then the 2nd triplet plus 3rd downbeat, and so on. This would continue on to 5 notes, 6 notes, and finally 7 notes, which would constitute two full triplets plus the following downbeat.
Diads, Triads
There are dozens of other ways to practice, but here is one more valuable way to approach your particular example.
Although the fingerings may not match, it is valuable to "flatten" each beat into a triad.

However, these particular arpeggiations are grouped into diads, so it's most helpful to flatten and organize them in that way.
Does this give you a few ideas to work with in this passage? I mocked these up quickly on my iPad so please forgive the incorrect enharmonic spellings used.
If you like my answer, I hope you'll accept it and up vote it. If you use Flickr at all, I hope you'll favorite one or two of my examples and add me as a contact. I look forward to your feedback!
Comment: wow, thank you for this great and elaborate answer. Your advice about flatting into diads is very helpful:) (I can even use the same fingering)
Comment: thanks for your feedback! I hope you'll connect with me on fb, twitter, or any other services you might use, links to them are on my profile. I like this site as it is helping me to meet and connect with thoughtful musicians like yourself and I hope to stay in touch with them beyond just one question on stack exchange.
Answer: I would advise you to write out the song using numbers instead of the chord letters. Eg using 1 for the chord based on the first note of the key and up to 7 for the last note. I actually recommend using roman numerals as they look better than numbers.
1 = I
2 = II
etc
that way you will much better be able to see what is going on with the chords changes


End-user SSL certificate management workflow

Question: We have an internal website, served from behind HTTPS with client certificates.
Website users are non-technical persons, working remotely. They use Windows (XP, Vista, 7) and OS X (10.5, 10.6, 10.7). They use a variety of browsers, but we can limit the range to modern Chrome, FireFox and Safari (on OS X).
The problem is that it is a huge pain to set up access for a new user or replace a certificate. Since the users are working remotely, they have to install their SSL certificates themselves — with all the usual consequences. Diagnosing and fixing the issues that arise from that can take days.
I'm looking for a good troubleshooting guide for our sysadmin (the questions to ask users, the tools to gather diagnostics etc.) and maybe some advice on how to improve the whole workflow.
Answer: I think you made a strategic mistake in using SSL client certificates.  They're a great idea in theory, but in practice they're just not user-friendly enough to be able to deal with them on a mass-deployment scale.
My only suggestion would be to require users to allow remote access to the machines, and have the sysadmin remote in and do the necessary bits and pieces and test that it's all working.
Comment: What secure alternative would you suggest?
Comment: Questions go in questions, not comments, and that isn't a sufficiently specific question to be able to answer.
Comment: Bah. That's exactly the reason I'm asking that in a comment.
Comment: If a question is too general to be properly answered in the unlimited space of an answer box, how can it be answered in 600 characters?


How do i prove that $| \arg z|<\pi/2$?

Question: Let $|1-z|<1$.
Then how do i prove that $| \arg z| < \pi/2$?
This is geometrically trivial, but i dunno how to prove this precisely
Comment: The geometric proof is completely precise but if you do not want to use geometry, try writing $z$ as $x + iy$. Then the condition you have says that $(x - 1)^{2} + y^{2} < 1.$ This implies that $0 < x < 2$ because otherwise $|(x - 1)| \ge 1$. That implies what you need.
Answer: The set of complex numbers which satisfy $|1- z| < 1$ is the open disk of radius 1 centered at 1. This is contained in the open right half of the complex plane. For complex numbers in the open right half plane, you have
$$\text{Arg}(z) \in \left(-\frac{\pi}{2}, \frac{\pi}{2}\right).$$
Comment: Do you mean the open disc?
Comment: Yes I do. I'll make that edit. Thanks for pointing it out.
Answer: From a purely algebraic point of view, if $z=re^{i \theta}$ and $(1-z)(1- \overline{z})=|1-z|^2<1$, then you get $r<2 \cos(\theta)$. Therefore, $\cos(\theta)>0$ that is $\theta \in (- \pi/2,\pi/2)$.

How do i prove that $| \arg z|<\pi/2$?


Compiling error: cannot find -lGLU and -lGL in kubuntu linux

Question: I have some problems with compiling "hello world" application in kubuntu linux 11.10. This is project file:
// opengltext.pro
SOURCES += \
    main.cpp
QT += opengl

And one cpp file:
    // main.cpp

    #include <QApplication>

    int main( int argc, char *argv[] )
    {
        QApplication app( argc, argv );
        return app.exec();
    }

i have got the following errors:
:-1: error: cannot find -lGLU
:-1: error: cannot find -lGL
:-1: error: collect2: ld returned 1 exit status

I try find in google the solution of this problem. But didn't find.
i try to install:
sudo apt-get install libglw1-mesa-dev

but this error is still taking place
What's the problem?
Answer: You need the following 2 packages:
xlibmesa-gl-dev
xlibmesa-glu-dev

-- edit --
Thanks for correction @ephemient, these were obsolete names, right names are:
libgl1-mesa-dev
libglu1-mesa-dev

Comment: If your system reports that you already have the packages and it still isn't working, try reinstalling them via your package manager. I already the packages installed, but for some reason I was missing the required `libGL.so` files. Reinstalling fixed the problem.
Comment: Thanks pR0Ps - reinstalling worked for me to: aptitude reinstall libgl1-mesa-dev
Answer: In addition to the the answer about installing the right libraries (sudo apt-get install libgl1-mesa-dev libglu1-mesa-dev) you may need to add:
unix:LIBS += -L/usr/lib/x86_64-linux-gnu/mesa/
to your .pro file, I know I needed to. Of course that path may be different if your using 32bit software or other system dependant reasons.


Get current region name in node template Drupal 7

Question: I need to find out what region the node block is appearing in within the node template. I am using node block module to display nodes as blocks but need to know what region the node blocks are appearing in within the node.tpl. In Drupal 6 there was a template preprocess function where you could set a global var to accomplish this but that function is not available in D7.
Thanks for any help.
It won't let me answer my question yet so I will put it here.
If anyone else runs into this and wants to know what region the node is being displayed in within the node template using the node block module or something like it. You can use the template_preprocess_node($vars) function and add the region to the content so that it will be in the content array in the node template like this.
$vars['content']['region']=$vars['elements']['#block']->region;
Comment: Hi Chris, can you post your solution as as a separate answer? This way, it's clear what the solution is and it'd allow people to vote it up as the proper solution.
Answer: If anyone else runs into this and wants to know what region the node is being displayed in within the node template using the node block module or something like it. You can use the template_preprocess_node($vars) function and add the region to the content so that it will be in the content array in the node template like this.
<code>$vars['content']['region'] = $vars['elements']['#block']->region;
</code>
Answer: There is a variable for that: <code>$block->region</code>. This and other variables that are available inside the block template can be found inside the commented-out area (at the top of the template).
Comment: yeah sorry I just realized I asked that wrong I actually need to know the region in my node.tpl and not the block.tpl because I am using node block module. is there a way to pass it from the block tpl to the node tpl?
Comment: Congrats for finding the answer by yourself. +1 for posting it.


Material UI : Form styling

Question: I'm looking for a solution to edit the style of my material ui form.
I would like to change the background and the border.
I try to change directly in CSS :
input { background:#999; }

But it change the background of all the div (https://www.awesomescreenshot.com/showImage?img_id=3537926)
I'm using Redux Form with Material UI : https://redux-form.com/7.4.2/examples/material-ui/
Comment: Possible duplicate of [How do I override compiled classes?](https://stackoverflow.com/questions/51541248/how-do-i-override-compiled-classes)
Answer: The material-ui way - in your jsx file with the form, you can define a theme which includes classNames
import classNames from "classnames";

....

const styles = theme => ({
  form_input: {
    background: "#999"
  },
....

Then, in your form or enclosed div tag, include something like...
className={classes.form_input}

Material UI : Form styling


How do I get the comment ID in a template file?

Question: I want to show the comment title linked to the comment permalink.
This is the content of the comment.html.twig file.

    {% if title %}
      {{ title_prefix }}

{{ title | render | striptags}}

      {{ title_suffix }}
    {% endif %}
    {{ content }}

{{comment.id}} didn't work. How do I get the comment ID?
Comment: Call it as a function `{{ comment.id() }}`
Answer: template_preprocess_comment() sets the following value, which is essentially the string you want to obtain, apart the hash at the beginning.
$variables['attributes']['id'] = 'comment-' . $comment->id();

The template file can use that value with {{ attributes.id }}.

  {% if title %}
    {{ title_prefix }}

{{ title|render|striptags }}

    {{ title_suffix }}
  {% endif %}
  {{ content }}

Reference

Using attributes in templates
Comment: Thank you so much


Decide whether a function has an elementary indefinite integral without determining it!

Question:
Risch, who developed the algorithm in 1968, called it a decision procedure, because it is a method for deciding whether a function has an elementary function as an indefinite integral; and also, if it does, determining it.

Is there a way to only decide whether a function has an elementary function as an indefinite integral without determining it?
Comment: Maybe [Liouville's theorem](http://en.wikipedia.org/wiki/Liouville's_theorem_(differential_algebra)) ?...
Comment: This may just be a matter of taste, and I know this is how it's written on wikipedia, but I find "an indefinite integral" to be an awkward phrasing. I think of "indefinite integral" as something like "set of all antiderivatives (written in odd ways and [sometimes inaccurately](http://golem.ph.utexas.edu/category/2012/03/reader_survey_logx_c.html))". If you just want one function without a +C or whatever, I figure you want "an (elementary) antiderivative".
Answer: For a given integrand, Liouville's theorem and Risch algorithm and its generalizations give equations and conditions that must be fulfilled if the integrand has an elementary antiderivative. Often, the fulfillment or non-fulfillment of these conditions is not known until the solution sets of the equations are known. If the solution sets are known, you already have the antiderivative. The decision problem is therefore usually just as expensive as the problem of determination.
But you can look for classes of functions that have elementary antiderivatives: e.g. the elementary standard functions and polynomials.
And you can look for classes of functions that don't have elementary antiderivatives:
List of Functions Without Antiderivatives
Yadav, D. K.: A Study of Indefinite Nonintegrable Functions. PhD thesis, Vinoba Bhave University, India, 2012
Yadav, D. K.: Six Conjectures in Integral Calculus. 2016
Yadav, D. K.: Six Conjectures on Indefinite Nonintegrable Functions or Nonelementary Functions. 2016


Coefficients in Anova

Question: When considering anova as a linear model where the variables of the model are categorical, I've heard that the coefficient given to a variable is the mean of the response in the group of that variable. Is this always true? Even in glms? If this is true, does this mean that adding new variables should not change the value of the coefficients?
Thanks!
Answer: Not exactly true. If the categorical predictor with its dummies are your only variables in the model, the intercept is the mean of the missing dummy variable and the other coefficients are the gap between respective groups and the intercept.
In GLMs, the same holds but for the models with a non-identity link function (logistic/Poisson/...), the coefficients are not on the same scale as the original response variable. So you would need to calculate prediction for each group and transform using the mean function to see that this is a model for group means. You cannot transform the coefficients directly.
Once you add additional variables to the model, the coefficients begin to represent adjusted differences between groups, so you now have adjusted group means. These group mean differences are adjusted for the other variables in the model. If your categorical variable is unrelated to these other variables, the coefficients should be relatively stable if using GLMs with identity (as with linear regression) or log link (as with Poisson regression); citation below documents this. If your categorical variable is related with other variables and those variables relate to the outcome, the coefficients should swing about.
By "related to other variables", is there a relationship between the group individuals finds themselves and these other variables in the model? For example, if the categorical predictor is age groups, and another variable in the model is wealth, then age groups will have a relationship to wealth and the coefficients for the age groups should change when wealth is included in the model. This is assuming wealth is related to whatever the outcome variable is.

M. H. GAIL, S. WIEAND, S. PIANTADOSI; Biased estimates of treatment effect in randomized experiments with nonlinear regressions and omitted covariates, Biometrika, Volume 71, Issue 3, 1 December 1984, Pages 431–444, https://doi.org/10.1093/biomet/71.3.431

Coefficients in Anova


Jquery animate on mousing over the container

Question: I have the following snippet of code:

        This is the popup bar

        This is a bubble

        See?

js
$(".bubblewrap").mouseenter(function(){
    $(this).find(".bubblebar").animate({top: 0px}, slow);
}).mouseleave(function(){
    $(this).find(".bubblebar").animate({top: 12px}, slow);
});

http://jsfiddle.net/8g52G/
I am trying to make it so on mouse over of any .bubblewrap, it moves the .bubblebar within.  However, it doesn't seem to trigger the event(tested a simple alert).  I must be doing it the wrong way, could someone help me?
Comment: To load jQuery library in a jsFiddle: At top left, under `Frameworks & Extensions`, change `No-Library (pure JS)` to `jQuery 1.8.3` (or whatever version you require
Answer: You forgot to add jQuery in your fiddle, and didn't quote some of the values that should be passed as strings
$(".bubblewrap").mouseenter(function(){
    $(this).find(".bubblebar").animate({top: '0px'}, 'slow');
}).mouseleave(function(){
    $(this).find(".bubblebar").animate({top: '12px'}, 'slow');
});

FIDDLE
as a sidenote you could also do
$(".bubblewrap").on('mouseenter mouseleave', function(e){
    $(this).find(".bubblebar").animate({top: e.type=='mouseenter'?0:12}, 'slow');
});

Comment: Single quotes, oh how the stupid have fallen!  Will tick in 11 minutes!
Comment: @JamesKorden - double quotes would have worked as well
Answer: 3 things :

jQuery isnt loaded in fiddle.
12px should be a string, now it is considered as a var name.
same thing for slow.

Fiddle : http://jsfiddle.net/8g52G/2/


Let $x>0$. Calculate $\lim_{R\rightarrow\infty} \int_{\frac{1}{2}-iR}^{\frac{1}{2}+iR}\frac{x^s}{s}ds$

Question: Let $x>0$. Calculate:
$$\lim_{R\rightarrow\infty} \int_{\frac{1}{2}-iR}^{\frac{1}{2}+iR}\frac{x^s}{s}ds$$
for $x=1$ it is quite simple. Otherwise, I used the following contours:

The left one when $x>1$ and the right one when $0<x<1$. Let us discuss the case $x>1$.
The integral on $\Gamma_1$ is what we want. The integral on $\Gamma_3$ vanishes since:
$$\bigg| \int_{\Gamma_3}f(s)\bigg|\leq \int_{\Gamma_3}|f(s)| \leq 2R \bigg|\frac{x^s}{s}\bigg| \leq 2R \frac{e^{\ln x \Re s}}{\sqrt{2}R}=\sqrt{2}e^
{-R\ln x} \rightarrow 0$$
But I have no idea what to do with $\Gamma_2$ and $\Gamma_4$.
Comment: @user64494: Thanks, but I'm not intersted in the final solution - just how to get to it.
Comment: The Maple command $$int((exp(1))^{k*(1/2+I*y)}/(1/2+I*y), y = -infinity .. infinity, CauchyPrincipalValue) assuming\,k > 0 $$ produces $2\pi$ and $$int((exp(1))^{k*(1/2+I*y)}/(1/2+I*y), y = -infinity .. infinity, CauchyPrincipalValue) assuming\,k <0   $$ produces $-2\pi$. The command $$int(1/(1/2+I*y), y = -infinity .. infinity, CauchyPrincipalValue)  $$ gives $\pi .$
Answer: For the parts $\Gamma_2$ and $\Gamma_4$, you can estimate the integral by estimating the integrand
$$\left\lvert \frac{\exp \bigl((\sigma \pm iR)\log x\bigr)}{\sigma \pm iR} \right\rvert \leqslant \frac{1}{R} e^{\sigma\log x}$$
and then integrating
$$\left\lvert\int_{\Gamma_{2,\,4}} \frac{x^s}{s}\, ds\right\rvert \leqslant \frac{1}{R} \int_{-R}^{1/2} e^{\sigma\log x}\, d\sigma = \frac{1}{R} \frac{x^{1/2} - x^{-R}}{\log x} \leqslant \frac{C(x)}{R}.$$
For the $x < 1$ case, the estimate is similar.


Procurar um elemento na lista

Question:
Faça um programa que gerencie o resultado do vestibular. Para sua felicidade, só existe um curso e o curso tem 10 vagas. O programa deve manter a lista dos 10 classificados. O programa também mantém, em outra lista (de 20 posições), a lista de espera, que contém os
  candidatos aprovados, mas excedentes ao número de vagas (caso algum candidato classificado
  desista, será chamado um da lista de espera). A lista de espera pode ter até 20 candidatos.
O programa deve solicitar o número do candidato e dizer:
(a) se ele foi classificado, ou
(b) se ele está na lista de espera,
  neste caso, indicar em que lugar da fila de espera ele está, ou
(c) se
  ele não foi aprovado.

Exemplo. Sejam os classificados:
20 32 01 14 99 34 21 02 15 07
Seja a lista de espera (valor -1 significa que não há candidato):
08 04 10 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
Exemplos de consultas:
Entrada / Saída
01 "classificado"
04 "número 2 na lista de espera
97 "não aprovado"
O que eu consegui fazer:
numeroCandidato = int(input("Entre com o numero do candidato: "))
classificados = [20,32,1,14,99,34,21,2,15,7]
listaDeEspera = [8, 4, 10]
if numeroCandidato not in classificados:
print("nao aprovado")

Comment: Você pode [edit] sua pergunta e adicionar o código de pelo menos uma das suas tentativas. Assim ficará mais fácil para te orientarmos, sabendo onde você está errando. E esse enunciado está bem confuso de entender. Você o colocou por completo ou omitiu algumas partes? Que informação será a entrada? A nota do candidato? Qual será a condição para definir se o mesmo foi classificado?
Comment: Bom dia! Então, tentei fazer o exercício mas não fiz quase nada... Agora sobre a interpretação: A entrada será o número do candidato, se o número que você entrou estiver na lista de classificados, irá aparecer uma mensagem falando que foi classificado. Se estiver na lista de espera, aparecerá uma mensagem falando a posição do candidato na lista de espera, e se o número não estiver em nenhuma das listas, aparecerá que ele não foi classificado. Teoricamente é assim a funcionalidade.
Comment: Se você fez **quase** nada, você deve ter feito algo. Comece postando esse algo, pelo menos para sabermos se você começou no caminho certo.
Comment: Postei até onde consegui, não consigo sair dali
Answer: Você já chegou bem perto da solução final. Para verificar se o candidato foi aprovado, basta verificar se o seu número consta na lista de classificados:
if numeroCandidato in classificados:
    print("Aprovado")

Para verificar se o candidato está na lista de espera, basta verificar se seu número consta na lista de espera:
elif numeroCandidato in listaDeEspera:
    print("Lista de espera")

Porém, pede-se também para informar em qual posição da lista de espera o candidato se encontra. Para tal, podemos utilizar o método index do objeto listaDeEspera para obter a posição do candidato. Vale lembrar que como os índices de uma lista em Python começam em 0, precisaremos incrementar o valor em um, para que se o candidato estiver na posição 0 da lista, apareca posição 1:
elif numeroCandidato in listaDeEspera:
    posicao = listaDeEspera.index(numeroCandidato) + 1
    print("Número %d na lista de espera." % posicao)

Finalmente, se nenhuma das condições acima for satisfeita, deve aparecer que o candidato não foi aprovado:
else:
    print("Não aprovado")

O código final, então, ficaria:
numeroCandidato = int(input("Entre com o numero do candidato: "))

classificados = [20,32,1,14,99,34,21,2,15,7]
listaDeEspera = [8, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]

if numeroCandidato in classificados:
    print("Aprovado!")
elif numeroCandidato in listaDeEspera:
    posicao = listaDeEspera.index(numeroCandidato) + 1
    print("Número %d na lista de espera." % posicao)
else:
    print("Não aprovado.")

Comment: Então Anderson, copiei o código que você criou e deu um erro quando eu digito algum número que está na lista de espera. Segue o print: http://imgur.com/a/7O9Y2
Comment: Qual será o problema nesse caso? E já aproveitando a pergunta, pra não se estender muito por coisas simples. O professor nos disse para fazer esse exercício usando o "For", tentei fazer e não consegui. Como eu faria usando o "For"? Obrigado desde já!!
Comment: O problema foi na versão do Python, que ainda não existe a implementação do `format`. Irei alterar a resposta. Quanto ao `for`, não vejo como utilizá-lo nesta solução de maneira eficiente.
Comment: Tá certo, estou aguardando. Também não consigo utilizar o "For" nesse programa, por isso me confundi todo.
Comment: @Pigot acredito que agora funcionará. Eu realmente não vejo como utilizar `for` nesta solução.
Comment: Funcionou muito bem. Muito obrigado pela atenção cara, grato mesmo! Sou novo aqui no site, tem alguma forma de agradecer? Tipo aumentando reputação e tal? Valeu.
Comment: No lado esquerdo da resposta, há como você votar positivamente, indicando que a resposta foi útil e um pouco mais abaixo um ícone `v` para você indicar que a resposta resolveu o problema. Pode ler mais sobre [aqui](https://pt.stackoverflow.com/help/someone-answers).

Procurar um elemento na lista


How to iteratively copy each columns in one sheet to different sheets

Question: I am trying to use VBA to realize the following goal:
I have two sheets: "revenue" and "sales tax", and they record the revenue and sales tax of 100 stores from May 1st to May 28th. Now I am trying to create a sheet for  each store recording its revenue and sales tax from May 1st to May 28th.
<code>Sub test1()

    Sheets("Sheet1").Select
    Sheets("Sheet1").Copy Before:=Sheets(17)

    Sheets("revenue").Select
    Range("D154:D168").Select
    Selection.Copy

    Sheets("Sheet1 (2)").Select
    Range("C5").Select
    ActiveSheet.Paste

    Sheets("sales tax").Select
    Range("D138:D152").Select
    Application.CutCopyMode = False
    Selection.Copy

    Sheets("Sheet1 (2)").Select
    Range("F5").Select
    ActiveSheet.Paste

    Sheets("Sheet1 (2)").Select
    Sheets("Sheet1 (2)").Name = " reportF "

End Sub
</code>
Using this code I am only able to establish a file for 1 store each time. What loop syntax should I use to loop through all stores?
Comment: Have you considered the use of sumifs(), countifs() etc and leave the source data in one place?
Comment: We have no idea what your data looks like, or what distinguishes one store from another, so it's difficult for us to make useful suggestions.
Answer: It looks like your data has the store name in column D? This code runs down all cells in column D and copies them into separate sheets depending on the contents
<code>    Sub ExampleCode
    Dim r as range  'declare a pointer variable
    Dim ws as worksheet  'declare a worksheet variable
    set r = Range("d1")  'point to fist cell
    Do   'Start a loop
       If SheetNotExist(r.text) then  'if no sheet of that name
          set ws = worksheets.add(after:=worksheets.count)  'add one
          ws.name = r.text        'and name it as text in r
       End if
       r.copy worksheets(r.text).cells(rows.count,4).end(xlup).offset(1,0)  'copy to next blank cell
       set r = r.offset(1,0) 'shift pointer down one cell
    Loop until r.text = ""  'keep going until r is empty
    End Sub

   Function SheetNotExist(s as string) as boolean  'check if sheet exists
   On error goto nope  'jump on error
   Dim ws as worksheet
   set ws = worksheets(s)  'this will error if sheet doesn't exist
  'so if we get here the sheet does exist
   SheetNotExist = False 'so return false
   Exit Function 'and go back
   nope:  'we only get here if sheet doesn't exist
   SheetNotExist = True 'so return that
   End Function
</code>
Written on my phone - don't have excel so there may be typos - code may not compile therefore,


Haskell: How to organize a group of functions that all take the same arguments

Question: I am writing a program with several functions that take the same arguments. Here is a somewhat contrived example for simplicity:
buildPhotoFileName time word stamp = show word ++ "-" ++ show time ++ show stamp
buildAudioFileName time word = show word ++ "-" ++ show time ++ ".mp3"
buildDirectoryName time word = show word ++ "_" ++ show time

Say I am looping over a resource from IO to get the time and word parameters at runtime. In this loop, I need to join the results of the above functions for further processing so I do this:
let photo = buildPhotoFileName time word stamp
    audio = buildAudioFileName time word
    dir   = buildDirectoryName time word
in ....

This seems like a violation of "Don't Repeat Yourself" principle. If down the road I find I would like to change word to a function taking word, I might make a new binding at the beginning of let expression like so:
let wrd   = processWord word
    photo = buildPhotoFileName time wrd stamp
    audio = buildAudioFileName time wrd
    dir   = buildDirectoryName time wrd
in ....

and would have to change each time I wrote word to wrd, leading to bugs if I remember to change some function calls, but not the others.
In OOP, I would solve this by putting the above functions in a class whose constructor would take time and word as arguments. The instantiated object would essentially be the three functions curried to time and word. If I wanted to then make sure that the functions receive processWord word instead of word as an "argument", I could call processWord in the constructor.
What is a better way to do this that would be more suited to Functional Programming and Haskell?
Answer: Since you say you're ready to create an OO-wrapper-class just for that, I assume you're open to changing your functions. Following is a function producting a tuple of all three results you wanted:
buildFileNames time word stamp =
  ( show word ++ "-" ++ show time ++ show stamp,
    show word ++ "-" ++ show time ++ ".mp3",
    show word ++ "_" ++ show time )

You'll be able to use it like so:
let wrd   = processWord word
    (photo, audio, dir) = buildFileNames time wrd stamp
    in ....

And if you don't need any of the results, you can just skip them like so:
let wrd   = processWord word
    (_, audio, _) = buildFileNames time wrd stamp
    in ....

It's worth noting that you don't have to worry about Haskell wasting resources on computing values you don't use, since it's lazy.
Comment: Very nice. I've never seen this trick before though it's quite obvious in hindsight. A minor note: the three result strings share parts so I think you could insert some `let` -s to share those explicitly.
Comment: @AndrásKovács No need due to compiler performing [common subexpression elimination](http://stackoverflow.com/q/15084162/485115).
Answer: The solution you described from OOP land sounds like a good one in FP land to me. To wit:
data UID = UID
    { _time :: Integer
    , _word :: String
    }

Including or not including the "stamp" in this record is a design decision that we probably don't have enough information to answer here. One can put this data type in its own module, and define a "smart constructor" and "smart accessors":
uid = UID
time = _time
word = _word

Then hide the real constructor and accessors at the module boundary, e.g. export the UID type, uid smart constructor, and time and word smart accessors, but not the UID constructor or _time and _word accessors.
module UID (UID, uid, time, word) where

If we later discover that the smart constructor should do some processing, we can change the definition of uid:
uid t w = UID t (processWord w)

Answer: Building on top of Nikita Vokov's answer, you can use record wild cards for some neat syntax with little repetition:
{-# LANGUAGE RecordWildCards #-}

data FileNames = FileNames { photo :: String, audio :: String, dir :: String }

buildFileNames :: Word -> Time -> Stamp -> FileNames
buildFileNames time word stamp = FileNames
  (show word ++ "-" ++ show time ++ show stamp)
  (show word ++ "-" ++ show time ++ ".mp3")
  (show word ++ "_" ++ show time )

let FileNames {...} = buildFileNames time wrd stamp
in ... photo ... audio ... dir...

Comment: @user1436026 In this example think of `FileNames` as your OOP object and `buildFileNames` as your constructor. The three records `photo`, `audio`, and `dir` are public attributes. They are each calculated once the first time you access them.
Answer: Just to give you another example, if you are passing around the same parameters to multiple functions, you can use the Reader monad instead:
import Control.Monad.Reader

runR = flip runReader

type Params = (String, String, String)

buildPhotoFileName :: Reader Params String
buildPhotoFileName = do
  (time, word, stamp) <- ask
  return $ show word ++ "-" ++ show time ++ show stamp

main = do
  runR (time, word, stamp) $ do
    photo <- buildPhotoFileName
    audio <- buildAudioFileName
    dir <- buildDirectoryName
    processStuff photo audio dir

Comment: Making your function based on Reader takes away many nice properties of functions like currying etc.
Comment: Sure, but you get a lot of nice properties in return.
Answer: To build on David Wagner's solution, and your OO objectives you should move the buildxxx function or functions to a separate module (NameBuilders?) That would give you complete control.
Even with this approach you should also "wrap" the variables with functions inside the module as David suggested.
You would export the variables and the buildxxx constructor (returning a triplet) or constructors (three separate functions).
you could also simplify by
    buildDirectoryName time word = show word ++ "_" ++ show time
    buildPhotoFileName stamp = buildDirectoryName + show stamp
    buildAudioFileName =       buildDirectoryName ++ ".mp3"


NSUserDefaults - Saving and retrieving "High Scores"

Question: I am just learning to program and doing some SWIFT tutorials. I have done as much research as I could but seem to be missing some critical aspect. I have a simple game and when a player dies I want to check their score against the previously saved high. If it's higher it's to save the new score.
On a title screen the highest score is displayed.
Here is the current code I am using;
NSUserDefaults.standardUserDefaults().integerForKey("highscore")

    if score > NSUserDefaults.standardUserDefaults().integerForKey("highscore") {
        NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "highscore")
        NSUserDefaults.standardUserDefaults().synchronize()
    }

    NSUserDefaults.standardUserDefaults().integerForKey("highscore")

The problem I cannot solve is simply how to print the highscore! I tried using;
hiScoreText.text = "Hi Score :  \(highscore)"

but as I guessed that isn't correct. What variable do I use or how do I "read" the highscore that has been saved?
Any advice for a new guy would be greatly appreciated.
Comment: Dont need synchronize() `NSUserDefaults.standardUserDefaults().synchronize()`
Answer: You have to store the result of NSUserDefaults.standardUserDefaults().integerForKey("highscore") inside a variable that you print.
Comment: Thank you so much for your help. Not only was it the solution I needed, but literally within a few minutes of me posting. Your help with this is very much appreciated.
Answer: I guess you forgot to save retrieved highs score to the variable:
let highscore = NSUserDefaults.standardUserDefaults().integerForKey("highscore")

Comment: Thank you greatly. Again, a clear concise answer to my silly oversight... and again all in such a fast response time. Really appreciate your assistance.


Maximum Likelihood estimator from sample distribution $N(0,\sigma^2x_i^2)$

Question: Let independent random variable $Y_1,...,Y_n$ have respective distributions $N(0,\sigma^2x_i^2)$, where $i=1,2,...,n$ are known constants such that $x_i\neq 0$ for all $i=1,2,...,n$. Find the maximum likelihood estimator of $\hat{\sigma}^2$, of the unknown parameter $\sigma^2$.
My attempt:
The likelihood function is $L(\sigma^2)=\prod_{i=1}^n\frac{1}{\sqrt{2\pi\sigma^2x_i^2}}exp(-\frac{y_i}{2\sigma^2x_i^2})=(2\pi\sigma^2)^{-\frac{n}{2}}\prod_{i=1}^n\frac{1}{x_i}\prod_{i=1}^nexp(-\frac{y_i}{2\sigma^2x_i^2})$. Since the $x_i$ are constants, I'll replace $\prod_{i=1}^n\frac{1}{x_i}$ with the constant $K$. Now I'm not exactly sure how I can rewrite the $\prod_{i=1}^nexp(-\frac{y_i}{2\sigma^2x_i^2})$ term in a useful way. I thought of maybe saying $\sum_i\frac{y_i}{2\sigma^2x_i^2}=\frac{\sum_i(\frac{y_i}{x_i})\prod_ix_i}{2\sigma^2\prod_ix_i}=\frac{\sum_i(\frac{y_i}{x_i})}{2\sigma^2}$, so then $L(\sigma^2)=(2\pi\sigma^2)^{-\frac{n}{2}}Kexp(-\frac{\sum_i(\frac{y_i}{x_i})}{2\sigma^2})$. Then I would maximize $ln(L(\sigma^2))=-\frac{n}{2}ln(2\pi\sigma^2)+ln(K)-\frac{\sum_i(\frac{y_i}{x_i})}{2\sigma^2}.$
This doesn't seem right though. Can anyone point out where I might have made a mistake or how I should go about this?
Comment: $\displaystyle \left(\frac{Y_1}{x_1},\frac{Y_2}{x_2}, \cdots, \frac{Y_n}{x_n}\right)$ is a set of $n$ independent $N(0,\sigma^2)$ random variables, and your book probably has a full description of the maximum-likelihood estimator of $\sigma^2$ in terms of the $\frac{Y_i}{x_i}$. So, apply this known solution to the _scaled_ observations $\frac{y_i}{x_i}, 1 \leq i \leq n$.
Answer: I think you miss square of $y_i$ in the likelihood. Then the Likelihood is $\Pi_{i=1}^n\frac{1}{\sqrt{2\pi x_i^2 \sigma^2}}e^{-\frac{y_i^2}{2x_i^2 \sigma^2}}=e^{-\sum_{i=1}^n\frac{y_i^2}{2x_i^2 \sigma^2}} \Pi_{i=1}^n\frac{1}{\sqrt{2\pi x_i^2 \sigma^2}}$. Taking log-likelihood and differentiating w.r.t. $\sigma$, you get $$\sum_{i=1}^n\frac{y_i^2}{\sigma^3 x_i^2}-\frac{n}{\sigma}=0$$.
From this, you get $\sigma^2=\frac{\sum_{i=1}^n\frac{y_i^2}{x_i^2}}{n}$, which seems familiar...
Answer:
the density function $f_i$ of $Y_i \sim \mathcal{N}(0, \sigma^2 x_i^2)$ is
$$
f_i (y_i) = \frac{1}{\sqrt{2 \pi \sigma^2 x_i^2}} \mathrm{exp}\left\{ - \frac{1}{2} \frac{(y_i - 0)^2}{\sigma^2 x_i^2} \right\}$$
e.g. $x_1 = -1$ and $x_2 = \dots = x_n = 1$, so
$$\prod_{i=1}^n \frac{1}{\sqrt{x_i^2}} = \frac{1}{1} \cdot \dots \cdot \frac{1}{1} = 1$$
but
$$\prod_{i=1}^n \frac{1}{x_i} = \frac{1}{-1} \cdot \frac{1}{1} \cdot \dots \cdot \frac{1}{1} = -1$$
I think the log likelihood is the right way

my 2 cents, but maybe I'm wrong.


C++/CLI cli::array, how to access from CS .NET?

Question: I'll preface this with the fact I don't know either language besides tinkering with others' code.  But I'm modifying code to vectorize it and have the C++/CLI portion figured out as this structure:
cli::array<double,2>^% vols
Initialized like this:
vols = gcnew cli::array<double, 2>(2,dealIDs->Length);
So that all compiles fine and I have a 2D array with 2x (Length of dealsID) on the C++ side.  Now on the NET side I'm not sure the correct declaration. What is this the correct .NET CS format to access my 2xN structured C++/CLI array?  Much appreciated.
Comment: It is just a plain `double[,]` on the C# side.  How the IntelliSense popup did not help you fall into that pit of success is very hard to guess when you post this little repro code.
Answer: gcnew cli::array<double, 2>(2,dealIDs->Length);

would be in C# syntax
new double[2, deals.Length]

A List<T> is not an array.
Comment: Thank you @adjan that is what I'm searching for.  Is the proper declaration then in .NET `public double[][] variable` or `public double[,] variable` as @Hans Passant stated?
Comment: `public double[,] identifier`
Comment: I just want to note for those working with a `List` on the NET side the format instead of `.Length` is `.Count`, i.e. `myvariable = new double[2, dealIDs.Count]`


XML Serialization to use empty array instead of NULL

Question: I have a property
<code> [XmlElement]
 public string[] Emails { get; set; }
</code>
which is initialized as string[0] at constructor.
If I XML serialize and deserialize a default instance of this object, the property is NULL.
How can I tell the XML Serializer to use an empty array instead of NULL for this property?
Comment: You can always implement the `{get; set;}` so if `null` is ever set (or attempts to return `null` in the getter) it instead uses an empty array. EDIT: Just be sure if you do the check on the `get` to also store the empty array in the backing field rather than just returning a new instance.
Comment: @ChrisSinclair: I have hundred of such properties, is there a way without manual properties?
Comment: Not that I know of. You can create a separate utility class that will (likely via reflection) find all arrays (and collections?) that are `null` and set them to a new instance of their appropriate empty collection. Have it run through this utility when calling your central deserialization method.
Answer: 5 years later... :)
Replacing Array with List<> did the trick for me.
<code>[XmlElement (IsNullable = false)]
public List<string> Emails {get;set;}
</code>


How do I reverse the values of a Map when one type is a Set of Integers

Question: For example how do I reverse the key and value datatypes from something like this:
TreeMap<Set<Integer>, Integer>

...into this:
TreeMap<Integer, Set<Integer>>

Comment: You must be certain the values are unique.
Comment: So you want to have a datastructre like: TreeMap> as a result?
Comment: In other words make it TreeMap>
Comment: @Robert - Update your question to include what the output is suppose to be
Answer: If you're using Java8, you can do:
TreeMap<Set<Integer>, Integer> map = ....;
Map<Integer, Set<Integer>> result =
       map.entrySet()
          .stream()
          .map(entry -> new AbstractMap.SimpleEntry(entry.getValue(), entry.getKey())
          .collect(Collectors.toMap());

Answer: Iterate over the entry set and put them reversely in a new TreeMap. The following generic method will reverse every map.
public static <K, V> TreeMap<V, K> reverse(TreeMap<K, V> map) {
    TreeMap<V, K> result = new TreeMap<V, K>();

    for (Entry<K, V> e : map.entrySet())
        result.put(e.getValue(), e.getKey());
    return result;
}

Important
If a value is present two times, you will lose the key with the smallest value.
Example:
public static void main(String[] args) {
    TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
    map.put(1, 2);
    map.put(2, 2);
    System.out.println(reverse(map));
}

Output:
{2=2}

The tuple {1,2} is lost since the value 2 was presents multiple times!
Comment: So can I use an iterator on a set of sets of integers? Could I do something like this     Map, Integer> map = new TreeMap, Integer>();

        Set> temp = map.keySet();
        Map> newMap = new TreeMap>();
        Iterator in = temp.iterator();
        while (in.hasNext())
        {
            Set temps = in.next();
            Integer temp2 = map.get(temp);
            newMap.put(temp2, temps);
        }
Comment: I iterated over the entry set of the map. The entry set stores the key/value pairs present in the Map as a tuple.
Answer: Maps are not easilly reversible, And rightly so.
Reversing maps might not work.
In a Map Keys are obviously unique but values have no such constraint.
I don't know what the problem you're facing is, but it sounds as if there is a better design to solve it.
Perhaps you should use a BiMap?
It's essentialy a two way map in which both the "keys" and the "values" are unique. It allows efficient lookup both from the keys and from the values.
Java doesn't have a built in BiMap but google Guava and Apache Commons do.


What's a good way to email sysadmins the first time a failure happens?

Question: I have a cron job which will copy some files and such. From time to time it will start failing due to an inaccessible host. When it starts failing, I'd like to get notified - but I don't want an email every 5 minutes telling me that the problem is ongoing.
I can think of ways to kludge up a solution, but I wonder if this functionality exists somewhere already? Server is OSX, but I only have shell access to it.
Comment: Also, there are several different kinds of failures - I'd like to be notified the first time any of them happens.
Comment: This question is off-topic under current topicality rules.
Answer: Well, a simple solution would be to just touch a "state" file upon first failure and notification. Then the next time the script runs, check for that state file and if it exists, then skip notification. Upon the next successful copy, remove the state file.
Comment: Ended up implementing this. It's simple. Set flag if failure file exists. Delete status file. Do stuff. If failure, compare to flag then send email.
Comment: Yeah, that's reasonable. If failure { if !exists(fail_file) { notify } touch(fail_file) } else {delete(fail_file)} I could have a different file for each failure.
Answer: Something like monit could potentially do what you want.  Have your script write its errors to a file, then setup monit to send out an alert the first time the log becomes non-zero.  The syntax is extremely flexible, so I am sure you could customize a definition to do exactly what you want.
<code># cront
0 0 0 0 0 root script 2>&1 > /var/scripts/myscript_state

#monit config
check file myscriptdata with path /var/scripts/myscript_state
   if changed size then alert
</code>

FILE SIZE TESTING


A question on measure space and measurable function

Question:
Let $(X,\mu)$ be a measure space and $\mu(X)< + \infty$, $\phi$ be a bounded linear functor on  $L^1(\mu)$. Prove that there exists a positive measure $\lambda$ on $X$ such that $\phi(f) = \int_X f d\lambda$ for any $f \in L^1(\mu)$.

This appears like Riesz representation theorem to me. But I don't know how to do it.
Thank you very much.
Comment: This is the abstract version of the Riesz representation theorem.  Check out [this wikibook entry](http://en.wikibooks.org/wiki/Measure_Theory/Riesz%27_representation_theorem) for a proof on $C_c(X)$ (which is dense in $L^1(X,d\mu)$) or for the full picture see Rudin "Real and Complex Analysis" or Lax "Functional Analysis"
Comment: @icurays1 What happens if there is not a topological structure on $X$?
Answer: If $\lambda$ works, then $\lambda(A)=\phi(\chi_A)$ for all $A$ measurable (as the measure is finite, $\chi_A\in L^1(\mu)$).
So we define $\lambda(A):=\phi(\chi_A)\geqslant 0$. It defines a set function, with $\lambda(\emptyset)=0$. $\sigma$-additivity is a consequence of monotone convergence theorem.
Comment: Out of curiosity: How exactly are you suggesting to apply the monotone convergence theorem? Do you mean that the characteristic functions of $F_n$ converge in $L^1$ to the characteristic function of $\bigcup F_n$ or is there a slicker way? Further, a minor point: there seems to be an assumption on positivity of the functional missing in the question.
Comment: I don't know whether there is a slicker way, but yes, that's what I meant. I agree about the assumption of positivity (I assumed it).
Comment: Okay, thanks for the clarification.


Techniques to solve this integral?

Question: $$\int_{-\infty}^{\infty}\frac{\cos x}{4x^2-\pi^2}dx$$
The question is from the Kyoto University exam, and I think it could be solved by the Residue Theorem, but I'm not familiar with it. I also tried Feynman Integral Method but it still doesn't work well.
Comment: What techniques have you been taught in this course?
Comment: @insipidintegrator This problem is from an entrance test so I guess theoretically it can be done any way you want, but I'm more interested in knowing if I can use Feynman Integral to solve it.
Comment: Hi, welcome to Math SE. For what it's worth you can take the real part of $\int_{-\infty}^\infty\frac{e^{ix}dx}{4x^2-\pi^2}$ with a semicircular contour because, although the poles are real, they're also first-order, so the [semi-residue lemma](https://math.stackexchange.com/q/319959) can be used.
Comment: The integrand has removable singularities at $x=\pm\pi/2$.
Answer: You can decompose the integral as follows:
$$\int_{-\infty}^\infty \frac{\cos(x)}{4x^2-\pi^2} \text{d}x = \frac{1}{2\pi}\int_{-\infty}^\infty \frac{\cos(x)}{2x-\pi} \text{d}x - \frac{1}{2\pi}\int_{-\infty}^\infty \frac{\cos(x)}{2x+\pi} \text{d}x$$
Take the change of variable $x\to \tfrac{\pi}{2} - x$ in the first integral and $x\to x - \tfrac{\pi}{2}$ in the second:
$$\int_{-\infty}^\infty \frac{\cos(x)}{4x^2-\pi^2} \text{d}x = -\frac{1}{4\pi}\int_{-\infty}^\infty \frac{\sin(x)}{x} \text{d}x - \frac{1}{4\pi}\int_{-\infty}^\infty \frac{\sin(x)}{x} \text{d}x =  - \frac{1}{2\pi}\int_{-\infty}^\infty \frac{\sin(x)}{x} \text{d}x = -\frac{1}{2}$$
where I used the fact that
$$\int_{-\infty}^\infty \frac{\sin(x)}{x} \text{d}x = \pi$$
as you can check several ways to solve this integral in here: Are there any ways to evaluate $\int^\infty_0\frac{\sin x}{x}dx$ without using double integral?
Answer: Rewriting the integral as $$
I=\int_{-\infty}^{\infty} \frac{\cos x}{4 x^2-\pi^2} d x=\Re\left[\int_{-\infty}^{\infty} \frac{e^{x i}}{4 x^2-\pi^2} d x\right],
$$
then we can evaluate the integral using contour integration along anti-clockwise direction of the path
$$\gamma=\gamma_{1} \cup \gamma_{2} \textrm{ where }  \gamma_{1}(t)=t+i 0(-R \leq t \leq R)  \textrm{ and } \gamma_{2}(t)=R e^{i t}  (0<t<\pi). $$
As $R\rightarrow \infty$, $$
\begin{aligned}
I & = \Re \int_\gamma \frac{e^{z i}}{4 z^2-\pi^2} d z\\&=\Re\left[2 \pi i\left[\operatorname{Res}\left(\frac{e^{z i}}{4 z^2-\pi^2}, \pm \frac{\pi}{2}\right)\right]\right. \\
& =\Re\left[2 \pi i \left(\lim _{z\rightarrow \frac{\pi}{2}}\left(z-\frac{\pi}{2}\right) \frac{e^{z i}}{(2 z+\pi)(2 z-\pi)}+ \lim _{z\rightarrow \frac{-\pi}{2}}\left(z+\frac{\pi}{2}\right) \frac{e^{z i}}{(2 z+\pi)(2 z-\pi)}\right)\right] \\
& =\Re\left[\pi i\left(\frac{e^{\frac{\pi}{2}i} }{4 \pi}+\frac{e^{-\frac{\pi}{2} i}}{-4 \pi}\right)\right] \\
& =-\frac{1}{2}
\end{aligned}
$$
Answer: $$\frac{1}{4x^2-\pi^2}=\frac{1}{(2x-\pi)(2x+\pi)}=\frac 1{4\pi}\left( \frac 1{x-\frac \pi 2}-\frac 1{x+\frac \pi 2}\right)$$
Now, simple changes of variable
$$\int\frac {\cos(x)}{x-\frac \pi 2}\,dx=\text{Si}\left(\frac{\pi }{2}-x\right)$$
$$\int\frac {\cos(x)}{x+\frac \pi 2}\,dx=\text{Si}\left(\frac{\pi }{2}+x\right)$$
$$\int \frac{\cos(x)}{4x^2-\pi^2}\,dx=\frac 1{4\pi}\left(\text{Si}\left(\frac{\pi }{2}-x\right)-\text{Si}\left(\frac{\pi
   }{2}+x\right)\right)$$
$$I=\int_{-t}^{+t} \frac{\cos(x)}{4x^2-\pi^2}\,dx=\frac 1{2\pi}\left(\text{Si}\left(\frac{\pi }{2}-t\right)-\text{Si}\left(\frac{\pi}{2}+t\right)\right)$$
Expanding for large values of $t$
$$I=-\frac{1}{2}+\frac{\sin (t)}{2 t^2}-\frac{\cos (t)}{t^3}+\cdots$$ which is a very good approximation as soon as $t \geq 2\pi$.

Techniques to solve this integral?


Como identificar percentual de uso de memória para executar comando de limpeza de cache?

Question: Sabemos que o comando para limpeza de cache de memória é este:
<code>sync; echo 3 > /proc/sys/vm/drop_caches
</code>
Porém, como fazer um executável com uma condição (if() else()), para que este comando seja executado apenas quando o uso da memória atingir 80% ou mais através do crontab?
Algo parecido com isto:
<code>#!/bin/sh
if (uso da memoria > 80%){
    sync; echo 3 > /proc/sys/vm/drop_caches
}
</code>
Comment: Olá Anderson. Em qual parte você está com dificuldade? Fazer o if em batch script? Extrair o percentual de memória usada? Configurar o job no cron? Se você preparar um mvce demonstrando o problema fica mais fácil de ajudar.
Comment: minha dificuldade está em fazer um if de acordo com o percentual de memória utilizado. não sei por onde começar.
Answer: Resolvi meu problema com o código abaixo:
<code>#!/bin/bash

# total de memória instalada  32991100 (32 GB)

# total em 90% de uso 29691990

MAXIMO="29691990"

MONITOR=$(free | grep Mem)
USADA=$(echo $MONITOR | awk '{ print $3 }')
LIVRE=$(echo $MONITOR | awk '{ print $4 }')

if [ "$USADA" -gt "$MAXIMO" ]
then
    sync; echo 3 > /proc/sys/vm/drop_caches
fi
</code>
A tarefa cron executará a cada 5 minutos e se identificar que o uso de memória está acima de 90%, limpará o cache de memória.
Comment: Talvez você saiba isso, mas não deixa de ser legal ter a informação aqui. Limpar o cache da VM no Linux apenas para liberar memória quase sempre é uma má ideia. O Linux tenta usar sempre o máximo de memória possível para otimizar o desempenho, e quando ele precisa realmente de memória para aplicação, ele tenta limpar as páginas de cache menos "importantes". Quando você força a limpeza de todo o cache, pro Linux não vai fazer tanta diferença em termos de memória livre, mas você perde todo o desempenho que ganharia com arquivos muito acessados direto da memória.
Comment: Mas aí é que tá, por que você é obrigado a fazer isso para limpar o cache? Afinal, se o Linux precisa de memória, ele desaloca o cache do mesmo jeito para conseguir mais memória pra aplicação :)
Comment: Realmente concordo contigo Eitch, isto não é uma boa prática, mas, depende da situação. Tenho um servidor web e sou obrigado a fazer isto, uma vez que não posso reiniciar a máquina quando o cache da memória está cheio. Então esta solução me caiu como uma luva. Além do mais na minha situação a limpeza ocorre a cada 2 dias. Então em caso de desempenho não será muito afetado.
Comment: Passei a fazer isto depois que percebi uma lentidão no servidor e que nenhum aplicativo respondia devido a memória estar com 100% de uso. Talvez então haja outra configuração a fazer, pois seu eu não utilizar desta prática em poucas horas meu servidor "congela".


ManyToOne association on association key not work

Question: I'm using DDD on my project with this contexts (I've anonymise one context by Toto) :

SecurityUser
Toto

My Toto Context have a balance system (currency debits & credits)
In Toto I've a TotoUser table that refers by it's associated key the securityUser as follow :
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
    <entity name="App\Domain\Toto\TotoUser\Entity\TotoUser" table="dol_toto_users">
        <id name="securityUser" association-key="true"/>
        <one-to-one field="securityUser" target-entity="App\Domain\UAC\User\Entity\User">
            <join-columns>
                <join-column name="user_id"/>
            </join-columns>
        </one-to-one>
        <one-to-many field="transactions" target-entity="App\Domain\Toto\TotoUser\Entity\Balance" mapped-by="user">
            <order-by>
                <order-by-field name="date" direction="DESC"/>
            </order-by>
            <cascade>
                <cascade-remove/>
                <cascade-persist/>
            </cascade>
        </one-to-many>
        <field name="currentCurrency" type="float">
            <options>
                <option name="comment">Current amount of currency owned by the user</option>
            </options>
        </field>
    </entity>
</doctrine-mapping>

In this TotoUser table I've a collection of transactions, each transaction is a balance entry (in debit or credit)
My balance table has this mapping
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
    <entity repository-class="App\Api\Template\Repository\BalanceRepository" name="App\Domain\Toto\TotoUser\Entity\Balance" table="dol_balance">
        <id name="id" type="integer" column="id">
            <generator strategy="IDENTITY"/>
        </id>
        <field name="amount" type="decimal" column="amount" precision="15" scale="2" nullable="false"/>
        <field name="date" type="datetime" column="date" precision="0" scale="0" nullable="false"/>
        <many-to-one field="user" target-entity="App\Domain\Toto\TotoUser\Entity\TotoUser" inversed-by="transactions">
            <join-column name="user_id" referenced-column-name="securityUser"/>
        </many-to-one>
        <many-to-one field="type" target-entity="App\Domain\Toto\Template\Entity\Type"/>
    </entity>
</doctrine-mapping>

But this mapping is incorrect, it seems that we can't join column on an associated key in the Owning Side.
My errors are :

Cannot find a field on 'App\Domain\Toto\TotoUser\Entity\TotoUser' that
  is mapped to column 'id'. Either the field does not exist or an
  association exists but it has multiple join columns.

And one doctrine:schema:validate :

[FAIL] The entity-class App\Domain\Toto\TotoUser\Entity\Balance
  mapping is invalid:  * The referenced column name 'id' has to be a
  primary key column on the target entity class
  'App\Domain\Toto\TotoUser\Entity\TotoUser'.

Any ideas on how to solve this ?
EDIT : The solution is simple: just put in referenced-column-name the actual name of your ID in DB...here is user_id
Answer: In your Balance model
referenced-column-name="securityUser"

I assume, that "securityUser" is not your id ... meant here is the real name of the column in the database, usually named "id"
Comment: I already tried "id" and "securityUser" same result, the problem does not seems to be related to this. Error I get by securityUser is as follow :  ``Column name `securityUser` referenced for relation from App\Domain\Toto\TotoUser\Entity\Balance towards App\Domain\Toto\TotoUser\E
  ntity\TotoUser does not exist.``
Comment: Actually you solved my issue with `` real name of the column in the database`` actually my column is named as user_id in database. thanks a lot !


Django: Get model fields recursively (ForeignKeys and it's fields) as strings into a 1 level list

Question: I building a project in Django that needs to list all fields from a given model as options of a html select tag.
I wrote a recursive function that reads the model and returns a list with all fields and subfields. Like this:
def get_fields_true_hierarchy(model, list_fields = []):
    fields_obj = model._meta.fields
    for field_obj in fields_obj:
        if field_obj.rel:
            dict_fields = {field_obj.attname: []}
            list_fields.append(dict_fields)
            get_fields_true_hierarchy(field_obj.rel.to, dict_fields[field_obj.attname])
        else:
            list_fields.append(field_obj.attname)
    return list_fields

It returns an object such as the following:
fiedls = [
    'id',
    'title',
    'number',
    'start_date',
    'finish_date',
    {'status_id':
        ['id',
        'name']
    },
    'postal_code',
    {'requestor_id':
        ['id',
        {'user_id':
            ['id',
            'password',
            'last_login',
            'is_superuser',
            'username',
            'first_name',
            'last_name',
            'email',
            'is_staff',
            'is_active', '
            date_joined']
        },
        'name',
        'phone',
        'email',
        'contact_name',
        'contact_email']
    },
    {'reason_id':
        ['id',
        'description']
    },
    'details',
    {'group_id':
        ['id',
        'description']
    },
    {'subgroup_id':
        ['id',
        'description']
    },
    {'manager_id':
        ['id',
        'password',
        'last_login',
        'is_superuser',
        'username',
        'first_name',
        'last_name',
        'email',
        'is_staff',
        'is_active',
        'date_joined']
    },
    'datetime_subscription',
    'allowed',
    'data_def'
]

However, I need to get a single level list which would look like this:
fiedls = [
    'id',
    'title',
    'number',
    'start_date',
    'finish_date',
    'status_id',
    'status_id.id',
    'status_id.name',
    'postal_code',
    'requestor_id',
    'requestor_id.id',
    'requestor_id.user_id',
    'requestor_id.user_id.id',
    'requestor_id.user_id.password',
    'requestor_id.user_id.last_login',
    'requestor_id.user_id.is_superuser',
    'requestor_id.user_id.username',
    'requestor_id.user_id.first_name',
    'requestor_id.user_id.last_name',
    'requestor_id.user_id.email',
    'requestor_id.user_id.is_staff',
    'requestor_id.user_id.is_active',
    'requestor_id.user_id.date_joined',
    'requestor_id.name',
    'requestor_id.phone',
    'requestor_id.email',
    'requestor_id.contact_name',
    'requestor_id.contact_email',
    'reason_id',
    'reason_id.id',
    'reason_id.description',
    'details',
    'group_id',
    'group_id.id',
    'group_id.description',
    'subgroup_id',
    'subgroup_id.id',
    'subgroup_id.description',
    'manager_id',
    'manager_id.id',
    'manager_id.password',
    'manager_id.last_login',
    'manager_id.is_superuser',
    'manager_id.username',
    'manager_id.first_name',
    'manager_id.last_name',
    'manager_id.email',
    'manager_id.is_staff',
    'manager_id.is_active',
    'manager_id.date_joined',
    'datetime_subscription',
    'allowed',
    'data_def'
]

I couldn't write a recursive function to return such result. Do you have any ideas on how to perform this task?
I'm stuck on this function below. But it does not behave as expected.
PS.: list_fields argument will come from the get_fields_true_hierarchy() function.
def get_fields_fake_hierarchy(list_fields, fake_hierarchy = [], parent_str = "", reset=True):
    for field in list_fields:
        if reset:
            parent_str = ""
        if isinstance(field, dict):
            for key, value in field.iteritems():
                fake_hierarchy.append(key)
                parent_str += "."+key
                get_fields_fake_hierarchy(value, fake_hierarchy, parent_str, reset=False)
        else:
            fake_hierarchy.append("%s.%s"%(parent_str, field))
    fake_hierarchy = [i[1:] if i[0]=='.' else i for i in fake_hierarchy]
    return fake_hierarchy

Comment: A proper programming approach I would use, would be to create a separate Class Foo with all those attributes, fetch the results and create the mock object which in turn you shall use in the views.
The idea is to fetch all the necessary data, parse and create the mock object, if those are expensive operations you can cache the object and re-create it when necessary. If parsing requires effort, create a separate parser function or class, let it construct the object and return it back to the view.
Comment: I don't think that would be possible once this object will have different sizes according to the model the user selects on the interface. It's actually a plugin that reads whatever models the user has on the project, so I couldn't predict it's attributes.
Comment: @Mauricio: Python is highly dynamic so from a technical POV it _is_ actually possible to either add attributes to an instance or even create full classes at runtime. Now whether it's a good idea really depends on your use case - as far as I'm concerned, if all I need is a list of (possibly dotted) names, the "proper programming approach" is to use a list of (possibly dottted) names.
Comment: @brunodesthuilliers. I understand what you mean. Regarding to the need of a flat list, It's necessary cause a need them on a html select tag. The app I'm building is a dynamic report tool that gets the selected model fields into a select tag. After selecting the field the user would select a filter_type (exact, iexact, contains, etc) and a value. Than a have a method called get_results() which builds a dict ({'user__name__exact': 'Mathew'}). With that dict  I do objects.filter(**filter_dict). I need to have a flat list in orde put it in a form, and than use it to build the queryset parameters.
Answer: Use a recursive generator instead, and prefix the names on the fly:
def do_prefix(name, prefix):
    if prefix:
        return "%s.%s" % (prefix, name)
    return name

def get_fields_flat(model):
    return [name for name in iter_fields(model)]

def iter_fields(model, prefix=None):
    fields = model._meta.fields
    for field in fields:
        name = do_prefix(field.attname, prefix)
        yield  name
        if field.rel:
            rel = field.rel.to
            for f in iter_fields(rel, name):
                yield f

Comment: hahaha seriously now, don't judge yourself based on other people's skills, everyone has it's own pace and the only way to gather experience doing your own stuff. You're in the right way, give it some time and you'll be fine :)
Comment: Wow, thank you so much! It really did the trick. Guess I have to work a lot harder to be a real programer.


Appcelerator Titanium Facebook Like Menu

Question: at that moment i'm developing an App where i want to use the Facebook Like Menü from here:
https://github.com/mpociot/titanium-facebook-slide-menu
<code>// ALPHABYTES

// Facebook like menu window
var leftMenu    = Ti.UI.createWindow({
    backgroundColor: 'red',
    top:   0,
    left:  0,
    width: 150,
    zIndex: 1
});
var data = [{title:"Row 1"},{title:"Row 2"},{title:"Row 3"},{title:"Row 4"}];
var tableView   = Ti.UI.createTableView({ data: data });
leftMenu.add(tableView);
leftMenu.open();

// Facebook like menu window
var rightMenu   = Ti.UI.createWindow({
    backgroundColor: 'red',
    top:   0,
    right:  0,
    width: 150,
    zIndex: 1
});
var data = [{title:"Row 1"},{title:"Row 2"},{title:"Row 3"},{title:"Row 4"}];
var tableView   = Ti.UI.createTableView({ data: data });
rightMenu.add(tableView);
rightMenu.open();

// animations
var animateLeft = Ti.UI.createAnimation({
    left: 150,
    curve: Ti.UI.iOS.ANIMATION_CURVE_EASE_OUT,
    duration: 500
});
var animateRight    = Ti.UI.createAnimation({
    left: 0,
    curve: Ti.UI.iOS.ANIMATION_CURVE_EASE_OUT,
    duration: 500
});
var animateNegativeLeft = Ti.UI.createAnimation({
                left: -150,
                curve: Ti.UI.iOS.ANIMATION_CURVE_EASE_OUT,
                duration: 500
});

var win = Titanium.UI.createWindow({
    left: 0,
    zIndex: 10
});
var win1 = Titanium.UI.createWindow({
    backgroundColor: 'white',
    title: 'Facebook menu',
    left: 0,
    zIndex: 10
});
var nav = Titanium.UI.iPhone.createNavigationGroup({
   window: win1,
   left: 0,
   width: Ti.Platform.displayCaps.platformWidth
});
var button = Ti.UI.createButton({
    title: 'm',
    left: 10,
    width: 30,
    height: 30,
    top: 10
});
var button2 = Ti.UI.createButton({
    title: 'm',
    right: 10,
    width: 30,
    height: 30,
    top: 10
});
var touchStartX = 0;
var touchStarted = false;
win1.addEventListener('touchstart',function(e){
    touchStartX = parseInt(e.x,10);
});
win1.addEventListener('touchend',function(e){
    touchStarted = false;
    if( win.left < 0 ){
        if( win.left <= -140 ){
            win.animate(animateNegativeLeft);
            isToggled = true;
        } else {
            win.animate(animateRight);
            isToggled = false;
        }
    } else {
        if( win.left >= 140 ){
            win.animate(animateLeft);
            isToggled = true;
        } else {
            win.animate(animateRight);
            isToggled = false;
        }
    }
});
win1.addEventListener('touchmove',function(e){
    var x       = parseInt(e.globalPoint.x, 10);
    var newLeft = x - touchStartX;
    if( touchStarted ){
        if( newLeft <= 150 && newLeft >= -150)
        win.left    = newLeft;
    }
    // Minimum movement is 30
    if( newLeft > 30 || newLeft < -30 ){
        touchStarted = true;
    }
});
nav.add(button);
nav.add(button2);
win.add(nav);
win.open();

var isToggled = false;
button.addEventListener('click',function(e){
    if( !isToggled ){
        win.animate(animateLeft);
        isToggled = true;
    } else {
        win.animate(animateRight);
        isToggled = false;
    }
});

button2.addEventListener('click',function(e){
    if( !isToggled ){
        win.animate(animateNegativeLeft);
        isToggled = true;
    } else {
        win.animate(animateRight);
        isToggled = false;
    }
});
</code>
I have also implemented the menu and everything works as expected.
Now my Problem is the following:
If i click in the leftMenu on e.g. "Row 1" ("Settings" with me), i want to have my Settings Menu shown in the Main Window. How to do that?
If i create a new Window and open it, i get a complete new window without the facebook menu on the left and the buttons... I don't know how to do?!?! Can someone help?
Thanks,
Sascha
Answer: I hope I did't misunderstand your question, but I would open new windows as views inside of the main window. Here's some code: https://gist.github.com/manumaticx/4961175
Or do you want to change the menu? Then you would do the same to the left menu window!
Answer: <code>var curWin = Titanium.UI.createWindow();

var menuBtn = Titanium.UI.createButton({
    title : "Menu",
    top : 20,
    left : 5,
    zIndex : 999
});

var windowView = Titanium.UI.createView({
    top : 60,
    left : 0,
    right : 0,
    width : '100%',
    height : '100%',
    backgroundColor : "blue",
    zIndex : 1
});
curWin.add(windowView);

curWin.add(menuBtn);

curWin.open();

var menuWindow = Titanium.UI.createView({
    top : 20,
    left : 0,
    width : 150
});

curWin.add(menuWindow);
//// ---- Menu Table
// Menu Titles
var menuTitles = [{
    title : 'Menu 1'
}, {
    title : 'Menu 2'
}, {
    title : 'Menu 3'
}, {
    title : 'Menu 4'
}, {
    title : 'Menu 5'
}, {
    title : 'Menu 6'
}];
// Tableview
var tableView = Titanium.UI.createTableView({
    data : menuTitles
});
menuWindow.add(tableView);
var toggle = false;
menuWindow.hide();
menuBtn.addEventListener('click', function(e) {
    if (toggle) {
        menuWindow.hide();
        toggle = false;
        windowView.left = 0;
        menuBtn.left = 5;
    } else {
        menuWindow.show();
        toggle = true;
        windowView.left = 150;
        menuBtn.left = 160;
    }
});

windowView.addEventListener('click', function(e) {
    if (toggle) {
        menuWindow.hide();
        toggle = false;
        windowView.left = 0;
        menuBtn.left = 5;
    }
});
</code>
Comment: Please add documentation/comments about your solution. If reasonable break it up into smaller code blocks instead of 1 giant scrollable area.
Comment: Code itself is pretty simple , just copy and run . You can learn the rest by just playing around.. :)


Linear Transformation $T:\mathbb{R}^3 \rightarrow \mathbb{R}^3$, $T^3=T$, $T^2 \neq T$, $T^2\neq I$

Question: I need to show that the linear transformation $T:\mathbb{R}^3 \rightarrow \mathbb{R}^3$, $T^3=T$, $T^2 \neq T$, $T^2\neq I$ is such that

(1) $\text{null}\,T=1$ or $2$

(2) $\text{null}\,T=2$ $\Rightarrow$ (using the Characteristic polynomial $\chi_T(x)\,)$ there is a basis for $\mathbb{R}^3$ such that
$$M(T)=
\begin{pmatrix}
0&0&0\\
0&0&0\\
0&0&-1\\
\end{pmatrix}
$$

(1) Since $T^3=T$, we have $T(T^2-I)=0$, which gives $\text{Im}(T^2-I)\subseteq \text{ker}\,T $and since $T^2\neq I$, this says that the kernel of $T^2-I$ is not $\mathbb{R}^3$ and so by rank-nullity $\text{rank}(T^2-I)\geq1$, and so $\text{null}\,T\geq1$.
Also if $\text{null}\,T=3$, then $T=0 \Rightarrow T^2=T$ which is a contradicition.
So $\text{null}\,T=1$ or $2$.
(2) $\text{null}\,T=2$ means $\text{dim}\,E_0=\text{dim ker}\,T=2$.
Suppose $\lambda\neq 0$ is an eigenvalue of $T$. Then $\exists v\neq 0$ such that $T^3v=Tv \iff \lambda^2v=v \iff \lambda=1,-1$.
$\color{red}{This}$ $\color{red}{is}$ $\color{red}{where}$ $\color{red}{I}$ $\color{red}{am}$ $\color{red}{stuck}$
I want to say that $\chi_T(x)=x^2,x^3, x^2(x-1),$ or $x^2(x+1)$ and I can see that if it is $x^2(x+1)$ the basis can be found easily using the fact $\mathbb{R}^3=E_0\oplus E_{-1}$. But I do not know how to rule out the other three possibilities.
Any hints would be great!
Comment: Do you know about the minimal polynomial?
Comment: No I don't think that is something I can use yet
Comment: Note that the characteristic polynomial must have degree $3$; it cannot possibly be equal to $x^2$.
Answer: If the dimension of the nullspace is $2$, then the algebraic multiplicity of the eigenvalue $\lambda=0$ is either $2$ or $3$.
Let $v_1,v_2$ be a basis for the nullspace, and let $v_3$ be any vector not in the nullspace. Then $v_1,v_2,v_3$ form a basis for $\mathbb{R}^3$, and the coordinate matrix of $T$ relative to this basis will be of the form
$$\left(\begin{array}{ccc}
0 & 0& a\\
0 & 0 &b\\
0 & 0 &c
\end{array}\right)$$
for some real numbers $a$, $b$, and $c$. The characteristic polynomial of this matrix is $x^2(x-c)$; I claim that $c\neq 0$.
Indeed, if $c=0$, then $T(v_3)=av_1+bv_2$, so $T^2(v_3) = aT(v_1)+bT(v_2) = a\mathbf{0}+b\mathbf{0}=\mathbf{0}$. That means that $T^2(v_i)=\mathbf{0}$, so $T^2$ is the zero linear transformation. That means $T=T^3$ is also the zero linear transformation, which implies $T=T^2$.
So $c\neq 0$.
Tha means  the algebraic multiplicity of $\lambda=0$ is two, then the characteristic polynomial must be of the form $x^2(x-c)$ for some nonzero $c$; and the algebraic and geometric multiplicities of the eigenvalue $0$ match, so the matrix is diagonalizable.
You've already determined that in this case, you must have $c=1$ or $c=-1$.
If $c=1$, then you can find a basis $v_1,v_2,v_3$ where $T(v_1)=T(v_1)=\mathbf{0}$, and $T(v_3)=v_3$. But then, how do $T$ and $T^2$ compare?
What can you conclude?
Comment: How can we conclude it is diagonalisable?
Comment: @jaycneek: I see what you mean; editing.
Comment: Well and also how can we conclude the polynomial has degree 3?
Comment: @jaycneek: the characteristic polynomial of an $n\times n$ matrix **always** has degree $n$.
Comment: Thank you this is very clear!