Is it justify to use/report OLS model w/o assumptions check cause results are consistent with other types of models?

Question: In one paper I read that the researchers used OLS model (considered well-known, simple and robust to misspecification) but they admitted to have not tested whether its assumptions were met. However, they added that the OLS results were consistent with probit model.
My question is: is this a right way to procede? Can I use and report OLS model results (since they have the advantage of being widely known and easy to interpret also by persons with low statistical literacy) whithout testing its assumptions if its results are consistent with those of other type of models?
Answer: 1) I assume that by "OLS model" you mean (ordinary) least squares regression, which is in fact a method and not a model; people sometimes call the a "model" because it is (in theory) based on a model with certain assumptions. However, I can imagine also other things being meant by "OLS model". Also note that although the OLS regression theory depends on certain model assumptions, this doesn't necessarily mean that it is useless or meaningless if the model assumptions are not met. It still has some kind of interpretation as line/hyperplane/function (depending on what OLS method you are exactly talking about) approximating the data, and even statistical inference may (or may not) be approximately correct, depending on in which way assumptions are violated.
2) The OLS regression is not in fact robust against misspecification. There is a big literature on how particularly outliers will cause trouble.
3) "Is it OK to report...?" That's a weird kind of question. I'd certainly say it is not a good way to find out something valid from the data. This would require some more inspection and maybe testing (surely it is sensible to assess problems with the model assumptions, although this doesn't necessarily have to take the form of a hypothesis test). Whether it is "OK to report" something depends on what you write around it, what audience this is for etc. One could argue it is OK in the sense that it is correct to just say "I applied OLS regression without model checking and the result was this". The reader then knows a rather weakly justified approach was used and can make up their own mind (assuming they're competent enough). However, chances are I wouldn't put too much trust into any subject-matter interpretation or conclusion from this.
Comment: I was thinking about writing something about "validating results of method A by similarity to results of method B", but it's hard to comment on that. Obviously this would assume that method B is fine, but if we knew that, why would we need method A? But then I can see why two methods pointing in the same direction give some more assurance than just one. However from my point of view it depends heavily on the details, what exactly was done and how exactly it was presented, whether I can imagine this to be a sensible thing to say/do.
Comment: Yes, I intend "ordinary least squares regression". It seems that, instead of validate the accuracy of their OLS results by testing the assumptions, they used the results of the other method as a validation. Since they should know how to test OLS assumptions and there is no reason not to test them, I would conclude they were not met! This is surprising because the paper was published in a important journal. Anyway, I found also other cases where (social) researchers report results of different methods to support the robusteness of their outputs, instead of saying the assumptions were met
Comment: You are right and probably what the reseachers did was the right thing to do also for the reviewers, considered the importance of the journal. If you want to take a look you can find [here](https://www.nature.com/articles/s41562-020-0833-x.epdf?author_access_token=nZlPzDV78YgOACoB8eDfCtRgN0jAjWel9jnR3ZoTv0MSqVwVNQWYD-7ScS8YYGbMCO4NJbd3OYEqA1DhbR8gVHnEwrFfNN5vvElr6V4Y7QCZp5QMl4WveRWdZxrNcgakM8jj_ziw-fjDkK5Fe5e_2w%3D%3D) the paper
Comment: Thanks... well, that's probably too much to read for me right now.


How to factor it?

Question: I only know how to factor the usual one, something like x^2+x+1.
Now I have this:
y-xy
And just lost as to how to factor it.
How can I factor it?
Comment: factor out the $y$
Comment: How do you factor $x^2+x+1$?
Answer: As simply as
$$y(1-x)$$
$\phantom{asd}$

How to factor it?


Extracting only modified codes by using git diff

Question: I want the diffrence between two separate branches B1 and B2 to extract the modified codes in B2.
Here, the B1 is more like a parent/Developer branch under which other feature branches(e.g B2,B3,B4,B5) are created, modifications are done and then merged into B1.
The issue i am facing is, whenever i do a git diff --name-status between the B1 and B2, or between commit id's of the same, i get more than what is modified in B2.
The reason is, before B2, other branches(B3,B4) may have been merged into B1 which results in B2 getting behind B1 due to the changes made by the other branches merged into it.
Now, if i do a diff, it not only gives me code names changed in B2, but also B3 and B4.
Is there any way to implement this. I have tried all possible ways that i am aware of.
Comment: Note that when you compare the merge base commit with the tip commit of branch B2, you're seeing what's different in the snapshot at the tip of the branch, vs what's in the common commit shared by branches B1 and B2.
Answer: Try with
git diff --name-status B1...B2 # triple dot
git diff B1...B2

That should work


What range function does to a Python list?

Question: I am not able to figure out what is happening here. Appending reference to range function is kind of creating a recursive list at index 3.
>>> x = range(3)
[0, 1, 2]
>>> x.append(x)
[0, 1, 2, [...]]
>>> x[3][3][3][3][0] = 5
[5, 1, 2, [...]]

Whereas, when I try this:
 >>> x = range(3)
 [0, 1, 2]
 >>> x.append(range(3))
 [0, 1, 2, [0, 1, 2]]

I can easily deduce the reason for the second case but not able to understand what appending reference to range function is doing to the list appended.
Comment: Why is this tagged both Python 2 and 3? `range` behaves differently in 2 and 3.
Comment: Lists are passed by reference in python. This means that in the first scenario, you are appending the pointer to x, not the value of x. Because x now contains a pointer to x, it calls itself recursively at that point.
Comment: @JacobH: saying "lists are passed by reference" makes it seem like lists might behave differently from other objects.  All objects are passed the same way (although people argue about what the right phrase to describe that is.)
Comment: @interjay I mistakenly did that :(
Answer: In python2, ranges are lists.
lists, and most of the things in python are objects with identities.
li = [0,1]
li[1] = li    # [0, [...]]
              # ^----v
id(li)        # 2146307756
id(li[1])     # 2146307756

Since you're putting the list inside itself, you're creating a recursive data structure.
Comment: Please note that this is Python 2-specific. Ranges are entirely different in Python 3, returning a lazily-evaluated `range` object, not a list at all.
Comment: @Karoly thanks for the answer but I am not able to understand why value assignment of 5 is working. Whatever I have learnt is that if I use a[1][0] = 5, then it means assign 5 to 0 index at list of list at index 1.
Comment: if you meant my example: `li[1]` is `li`, so it's simply `li[0]=5`.
Answer: First this is strange, and you probably should not use this in practice. The issue is not specific to range function and has to do with references. When you call x.append(x), you essentially say that x[-1] is x. So when you modify x[0], you also modify x[-1][0], x[-1][-1][0] etc.
To see that this is not range specific, you could use copy.copy:
from copy import copy

x = range(1)
x.append(x)  # here x[1] is reference to x itself (same object)
print(x[0], x[1][0], x[1][1][0])
x[0] = 1
print(x[0], x[1][0], x[1][1][0])  # all values change

#

x = range(1)
x.append(copy(x))  # x[1] is a copy of x at previous state (new object)
print(x[0], x[1][0])  # cannot call x[1][1][0] -> x[1][1] is an int
x[0] = 1
print(x[0], x[1][0])  # only the first value changes

Output:
(0, 0, 0)
(1, 1, 1)
(0, 0)
(1, 0)


hibernate+c3p0+mysql max connections reached due to pools

Question: I have configured c3p0 data source in my application using following code.
<bean id="globalDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="com.mysql.jdbc.Driver" />
    <property name="jdbcUrl" value="${DbUrl}/${DbName}?useOldAliasMetadataBehavior=true&useSSL=false" />
    <property name="user" value="${DbUserId}" />
    <property name="password" value="${Password}" />
    <property name="minPoolSize" value="5" />
    <property name="maxPoolSize" value="100" />
    <property name="idleConnectionTestPeriod" value="14400" />
    <property name="preferredTestQuery" value="select 1" />
 </bean>

i have five different datasources with same configuration. On mysql side i have configured max_connections as 300. After 10 days with this live code mysql process list looks as follows with all sleeping connections:

Database1: 70 connections
Database2: 70 connections
Database3: 70 connections
Database4: 50 connections
Database5: 40 connections

these all connections are in sleep state and mysql have reached to max limit of around 290 to 300 connections. Is there any way to release connections so that number of connections can come to at least min pool size?
for further info about it my application is very old and connections are not closed in many of hibernate transactions because its very hard to find  impact points if i use following line
<property name="hibernate.connection.release_mode">after_transaction</property>

so i can not use above line in my hibernate-cfg.xml and for that reason i am also keeping alive my connections by "idleConnectionTestPeriod" to avoid timeout issue.
Please suggest best possible solution. i am thinking to use "maxIdleTimeExcessConnections" property of c3p0.
Comment: for further information i observed some more points: 1. when some high performance 7 or 8 queries runs parallel connections goes to 300 from normal 290 connections and not able to connect from even mysql CLI and CPU performance was around 100% spike for more than 1 hour.
Comment: Have you tried using the `maxIdleTimetout` value to see whether that helps those sleeping connections?  Basically, the c3p0 driver will not expire and discard any connection by default since it uses `0` for this, but any value above `0` will allow connections to be discarded, allowing the queue to shrink during inactivity periods.
Comment: i tried maxIdleTimetout also and it shrinks queue, but i faced timeout issue due to it.
Answer: The first thing you should do is check for Connection leaks (which seem very likely to be your issue). See e.g. C3P0 Spring Hibernate: Pool maxed out. How to debug?
The best thing to do is to eliminate the Connection leaks. First you should set unreturnedConnectionTimeout and  debugUnreturnedConnectionStackTraces. See also Configuring To Debug and Workaround Broken Client Applications.
If this is an old and crufty thing and you can't or don't want to mess with it, you can workaround the issue by setting an unreturnedConnectionTimeout and turning off debugUnreturnedConnectionStackTraces. Collecting stack traces on every Connection checkout is a drag on performance. But first, to understand the issue, you should set both. If you decide you cannot or don't want to actually fix the problem, but wish to work around it, then unset or set to false debugUnreturnedConnectionStackTraces.


Listing subgroups of a group

Question: I made a program to list all the subgroups of any group and I came up with satisfactory result for $\operatorname{Symmetric Group}[3]$ as
$\left\{\{\text{Cycles}[\{\}]\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 1 & 2 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 1 & 3 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 2 & 3 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{ccc}
 1 & 2 & 3 \\
\end{array}
\right)\right],\text{Cycles}\left[\left(
\begin{array}{ccc}
 1 & 3 & 2 \\
\end{array}
\right)\right]\right\}\right\}$

It excludes the whole set itself though it can be added seperately. But in case of $SymmetricGroup[4]$ I am getting following
$\left\{\{\text{Cycles}[\{\}]\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 1 & 2 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 1 & 3 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 1 & 4 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 2 & 3 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 2 & 4 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 3 & 4 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 1 & 2 \\
 3 & 4 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 1 & 3 \\
 2 & 4 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{cc}
 1 & 4 \\
 2 & 3 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{ccc}
 1 & 2 & 3 \\
\end{array}
\right)\right],\text{Cycles}\left[\left(
\begin{array}{ccc}
 1 & 3 & 2 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{ccc}
 1 & 2 & 4 \\
\end{array}
\right)\right],\text{Cycles}\left[\left(
\begin{array}{ccc}
 1 & 4 & 2 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{ccc}
 1 & 3 & 4 \\
\end{array}
\right)\right],\text{Cycles}\left[\left(
\begin{array}{ccc}
 1 & 4 & 3 \\
\end{array}
\right)\right]\right\},\left\{\text{Cycles}[\{\}],\text{Cycles}\left[\left(
\begin{array}{ccc}
 2 & 3 & 4 \\
\end{array}
\right)\right],\text{Cycles}\left[\left(
\begin{array}{ccc}
 2 & 4 & 3 \\
\end{array}
\right)\right]\right\}\right\}$
The matrix form shows double transposition. Can someone please check for me if I am getting appropriate results? I doubt I am!!
Answer: By using GAP, you can make them all so easier and visible.
<code>  gap> LoadPackage("sonata");;
  gap> s4:=SymmetricGroup(IsPermGroup,4);;
  gap> g:=Subgroups(s4);;
  gap> List([1..Size(g)],k->g[k]);
</code>
Comment: I guess you want `SymmetricGroup`, not `AlternatingGroup`
Comment: @azimut: Yes. That's right. I'll edit it ;-)
Comment: Actually, one liner `AllSubgroups(SymmetricGroup(4));` also suffices, but please see some important hints from [http://www.gap-system.org/Faq/faq.html#7.7](http://www.gap-system.org/Faq/faq.html#7.7) from the GAP F.A.Q.
Comment: Nice work, Babak!
Comment: $\Large\color{blue}{+➀}\color{Violet}{⚛}\color{green}{✓}$@BabakS.
Answer: I have the impression that you only list the cyclic subgroups.
For $S_3$, the full group $S_3$ ist missing as a subgroup (you are mentioning that in your question).
For $S_4$, several subgroups are missing. In total, there should be $30$ of them. $14$ of them are cyclic, which are exactly the ones you listed. To give you a concrete example, the famous Klein Four subgroup
$$\{\operatorname{id},(12)(34),(13)(24),(14)(23)\}$$
is not contained in your list.
Comment: are you aware of the algorithm used to calculate subgroups ?
Comment: In the case of $S_4$, it still can be done by hand if you know some group theoretic basics. In general, the computation of all subgroups is a hard problem.
Comment: http://www.math.colostate.edu/~hulpke/talks/columbustalk.pdf

actually I know that but I found this link and tried though I am not doing what is specified there...it's so brief that I could barely make out anything out of it.

Listing subgroups of a group


Composition of a harmonic function with a holomorphic function is still harmonic

Question:
If $f$ is a harmonic function in a domain $D \subset \mathbb{C}$, and $g$ is a conformal mapping of a domain $D_0$ onto $D$, is $f \circ g$ harmonic in $D_0$?

I noticed this question while reading several pdf of lecture notes, and I'm having trouble figuring it out. Can anyone help?
Thank you so much!
Answer: The answer is yes, and we only need $g$ to be holomorphic. One can prove this by directly computing the Laplacian of $f\circ g$ using the Chain Rule. I'd rather use $z$ and $\bar z$ than $x$ and $y$ for this purpose.
$$\Delta(f\circ g)=\frac{1}{4}(f\circ g)_{z\bar z} = \frac{1}{4}[(f_z\circ g) g']_{\bar z} = \frac{1}{4}(f_{z\bar z}\circ g) \overline{g'} g'= [(\Delta f)\circ g]|g'|^2=0$$
Comment: @user31373 The second derivative step should produce one more term $$f_z(g)g_{z\overline{z}}$.It seems that this term is not always zero.Moreover $\Delta u=4_{z\head{z}}$
Comment: One has to be more careful with the computation of the derivative since $f$ generally is a function of $z,\overline{z}$, so the chain rule should give you more. The result is correct though.
Answer: Let $\phi(u,v)$ be harmonic in $D$. Let $w=f(z)=u(x,y)+iv(x,y)$ be analytic in $D_0$ defining a mapping $D_0\to D$. We have
$$\phi_x=\phi_u u_x+\phi_v v_x$$
$$\phi_y=\phi_u u_y+\phi_v v_y$$
$$\phi_{xx}=\phi_{uu}(u_x)^2+\phi_{uv} u_x v_x +\phi_u u_{xx} +\phi_{vv} (v_x)^2+\phi_{vu} v_x u_x +\phi_v v_{xx}$$
$$\phi_{yy}=\phi_{uu}(u_y)^2+\phi_{uv} u_y v_y +\phi_u u_{yy} +\phi_{vv} (v_y)^2+\phi_{vu} v_y u_y +\phi_v v_{yy}$$
$$\phi_{xx}+\phi_{yy}=[(u_x)^2+(v_x)^2][\phi_{uu}+\phi_{vv}]$$
because
$u_{xx}+v_{yy}=0$, $v_{xx}+v_{yy}=0$, $u_xv_x=-u_yv_y$.
Hence
$\phi_{uu}+\phi_{vv}=0$ implies $\phi_{xx}+\phi_{yy}=0$. We conclude that $\phi(x,y)$ is a harmonic funtion.
Comment: This is not quite what was asked: you have $\phi = \Phi \circ f$ and conclude that if $\phi$ is harmonic and $f$ is analytic then $\Phi$ is harmonic.  The question went the other way: if $\phi$ is harmonic and $g$ is analytic then $\phi \circ g$ is harmonic.
Comment: @RobertIsrael In the original question, $g$ is assumed to be conformal (which I read as biholomorphic), so Valentin's answer is sufficient to answer that. Of course, the assumption of invertibility is extraneous.
Answer: The term "harmonic" will mean "real and harmonic" below. I will use the following:
1) Compositions of holomorphic functions are holomorphic.
2) The real and imaginary parts of a holomorphic function are harmonic.
3) If $D\subset \mathbb C$ is an open disc, and $u$ is harmonic in $D,$ then there exists $v$ harmonic in $D$ such that $u+iv$ is holomorphic in $D.$
1) is just the chain rule. 2) follows from the Cauchy-Riemann equations. If you are unfamiliar with 3), I can add a proof later. I'll assume it for now.
Thm: Suppose $\Omega_1, \Omega_2 \subset \mathbb C$ are open. Assume $u$ is harmonic on $\Omega_2$ and $f: \Omega_1 \to \Omega_2$ is holomorphic. Then $u\circ f$ is harmonic on $\Omega_1.$
Proof: Let $a \in \Omega_1.$ Because harmonicity is a local property, it suffices to show $u\circ f$ is harmonic in a neighborhood of $a.$
Choose an open disc $D$ centered at $f(a)$ contained in $\Omega_2.$ Then by 3) above, there exists a $v$ harmonic in $D$ such that $u+iv$ is holomorphic in $D.$ Let $\omega = f^{-1}(D).$ Then $\omega $ is an open neighborhood of $a$ contained in $\Omega_1,$ and $f:\omega \to D.$ By 1), $(u+iv)\circ f$ is holomorphic in $\omega.$ By 2), the real part of $(u+iv)\circ f$ is harmonic in $\omega.$ But this real part is precisely $u\circ f,$ and we're done.
Answer: Your question can be interpreted in the greater context of "maps preserving harmonic functions".
Definition Let $(M,g)$ and $(N,h)$ be Riemannian manifolds. A mapping $\Phi:M\to N$ is said to be a harmonic morphism if whenever $u:N\to\mathbb{R}$ is a harmonic function (solving $\triangle_h u = 0$ where $\triangle_h$ is the Laplace-Beltrami operator for the Riemannian metric $h$) the composition $u\circ \Phi$ is a harmonic function on $M$.
Theorem A mapping is a harmonic morphism if and only if it is a harmonic map which is weakly horizontally conformal.
(Don't worry too much about the undefined terms in the above theorem.)
Corollary If $M$ and $N$ have the same number of dimensions, then

If dimension is 2, $\Phi$ is a harmonic morphism if and only if $\Phi$ is conformal.
If the dimension is bigger than 2, $\Phi$ is a harmonic morphism if and only if $\Phi$ is a conformal map with a constant coefficient of conformality.

For reference, see this paper of Bent Fuglede's.
Answer: I was wondering the same question and reached here.
Here is how I thought about it:
Let $u$ be harmonic. And let $v$ be its harmonic conjugate. Then $f(z) = u(z) + iv(z)$ is analytic.
If $g$ is another analytic function such that range of $g$ is contained in the domain of $f$ then
$$f(g(z)) = u(f(z)) + iv(g(z))$$
is also analytic with $Re (f(g(z))) = u(f(z))$.


Regex to match a numeric token, but only if not part of another word

Question: Using C# Regex I'm trying to match a token which contains the @ symbol. For instance:

Your salary is @1 for this month.

I can't use a pattern like \b@1\b because \b matches the beginning and ending of a word and @1 is correctly not recognised as a word.
What pattern can I use to match tokens like this i.e @1, @2 etc?
Comment: It's not clear exactly what rules you want applied, but perhaps something along the lines of `(^|\s)@\d\b` is what you are after?  Or perhaps `\W` instead of `\s`?  Again, it's not clear exactly what your intentions are.
Comment: How are your *tokens* delimited? By whitespace? Punctuation? etc
Answer: You can use look-arounds (?<!\w) (=no word character allowed right before) and (?!\w) (=no word character allowed right after).
(?<!\w)@\d+(?!\w)

See regex demo
Note that \d+ matches 1 or more digits.


Proving $\mathbb{F}_p[x]/\langle f(x)\rangle$ with $f(x)$ irreducible of degree $n$ is a field with $p^n$ elements

Question: I am attempting to prove what the title says, that $\mathbb{F}_p[x]/\langle f(x)\rangle$ with $f(x)$ irreducible of degree $n$ is a field with $p^n$ elements.
I have already proven that for any field $K$ and polynomial $f(x)$ in $K[x]$, $K[x]/\langle f(x)\rangle$ is a field if and only if $f(x)$ is irreducible in $K[x]$. So I know that $\mathbb{F}_p[x]/\langle f(x)\rangle$ is a field for sure. Where I'm lost is figuring out how to know for sure that there are $p^n$ elements. It's fairly clear if $n\in\{ 0 ,1\}$, but I don't think induction is going to help.
I know from a proposition in class that since $F_p = \mathbb{Z}/\langle p\rangle$ and $F_p = \mathbb{Z}/\langle p\rangle$ is an integral domain, $F_p[x] = (\mathbb{Z}/\langle p\rangle)[x] = (\mathbb{Z}[x])/(\langle p\rangle[x])$, but I'm not sure whether or not that's helpful information.
Answer: Isn't this enough? If $g\in\mathbb{F}_p[x]/f(x)$, then $\max(\deg g) = \deg(f)-1=n-1$. Thus, all elements in $\mathbb{F}_p[x]/f(x)$ are of the form $\sum_{i=0}^{n-1}a_ix^i$, for $a_i\in\mathbb{F}_p$ for all $1\le i\le n-1$. Since $|\mathbb{F}_p|=p$, and there are $n$ coefficients, there are $p^n$ ways to construct a polynomial in $\mathbb{F}_p[x]/f(x)$, so $|\mathbb{F}_p[x]/f(x)|=p^n$.
Comment: It sounds reasonable when I read it, but then I wonder if there's some way to get a polynomial with degree >= n if n is big enough and f(x) has strange enough coefficients. It seems reasonable to say that there isn't, but I don't know how to be rigorously sure.
Comment: See the comment by Zev Chonoles at http://math.stackexchange.com/questions/83265/prove-that-fx-x21-has-121-elements
Answer: Well, you can always suppose $f$ to be a monic polynomial, $f(x) = x^n + a_{n-1}x^{n-1} + \dots + a_0$. But then, if $\alpha \in \mathbf F_p[x]/(f(x))$ is the image of $x$ in the quotient, the relation $\alpha^n + a_{n-1}\alpha^{n-1} + \dots + a_0$ shows that $\alpha^n, \dots, \alpha, 1$ are linearly dependent over $\mathbf F_p$. Moreover, it is easy to see by induction on $m$ that $\alpha^m$ is a linear combination of $\alpha^{n-1}, \dots, \alpha, 1$ with coefficients in $\mathbf F_p$, for every $m\geq 0$. Since the elements $\alpha^m$ span $\mathbf F_p[x]/(f(x))$ as an $\mathbf F_p$-vector space, it follows that the elements $\{\alpha^{n-1}, \dots, \alpha, 1\}$ also span it. Moreover, $\{\alpha^{n-1}, \dots, \alpha, 1\}$ are linearly independent by the irreducibility of $f$.
Alternatively, use the division algorithm to write any element of $\mathbf F_p[x]$ as $p(x)f(x) + r(x)$, where the degree of $r(x)$ is strictly less than the degree of $f$.
This implies that $\mathbf F_p[x]/(f(x))$ is a vector space of dimension exactly $n$ over $\mathbf F_p$, so it has $p^n$ elements.
Answer: The possible remainders upon division by $f(x)$ (where $\deg(f(x)) = n$) are those polynomials of the form
$$ r(x) = a_0 + a_1x + \dotsb + a_{n-1}x^{n-1}, $$
where $a_i \in \mathbb{F}_p$.  There are $n$ such $a_i$'s, and for each of the $a_i$'s there are $p$ possible choices from $\mathbb{F}_p$.  Thus, there are $p^n$ elements in $\mathbb{F}_p / (f(x))$.


SQL 2008 Install Failure

Question: I have a fresh install of Windows Server 2003 R2 32-bit with all of the latest windows updates. I'm trying to install SQL Server 2008 Standard x86 on it to prepare for Microsoft Team Foundation Server. So far I have been unsuccessful as the installation keeps failing with the error message:

A Severe error occurred on the current command.

This is what I believe to be the relevant section of the Details.txt log file.
<code>2010-10-15 09:51:26 Slp: --SafeSqlCommand: declare @ServerName nvarchar(255) if not

exists (select * from sysservers) begin select @ServerName = Convert(nvarchar(255), SERVERPROPERTY(N'ServerName')) execute sys.sp_addserver @ServerName, local end
2010-10-15 09:51:31 Slp: Sco: SqlException: Message:A severe error occurred on the current command.  The results, if any, should be discarded.
A severe error occurred on the current command.  The results, if any, should be discarded.
LineNumber:0
2010-10-15 09:51:31 SQLEngine: Copying 'D:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Log\ERRORLOG' to 'C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20101015_092804\SQLServer_ERRORLOG_2010-10-15T09.51.31.txt' ...
2010-10-15 09:51:31 Slp: Sco: Attempting to set file full path to 'D:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Log\ERRORLOG'
2010-10-15 09:51:31 Slp: Sco: Attempting to normalize directory path 'D:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Log\ERRORLOG'
2010-10-15 09:51:31 Slp: Sco: Attempting to check if file 'D:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Log\ERRORLOG' exists
2010-10-15 09:51:31 Slp: Sco: Attempting to copy file 'D:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Log\ERRORLOG' to file 'C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20101015_092804\SQLServer_ERRORLOG_2010-10-15T09.51.31.txt'
2010-10-15 09:51:31 Slp: Sco: Attempting to check if file 'D:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Log\ERRORLOG' exists
2010-10-15 09:51:31 Slp: Sco: Attempting to normalize directory path 'C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20101015_092804\SQLServer_ERRORLOG_2010-10-15T09.51.31.txt'
2010-10-15 09:51:31 Slp: Sco: Attempting to set file full path to 'C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20101015_092804\SQLServer_ERRORLOG_2010-10-15T09.51.31.txt'
2010-10-15 09:51:31 Slp: Sco: Attempting to normalize directory path 'C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20101015_092804\SQLServer_ERRORLOG_2010-10-15T09.51.31.txt'
2010-10-15 09:51:31 Slp: Sco: Attempting to check if directory path 'D:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Log\ERRORLOG' is equal to path 'C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20101015_092804\SQLServer_ERRORLOG_2010-10-15T09.51.31.txt'
2010-10-15 09:51:31 Slp: Sco: Attempting to check if directory path 'D:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Log\ERRORLOG' is equal to path 'C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20101015_092804\SQLServer_ERRORLOG_2010-10-15T09.51.31.txt'
2010-10-15 09:51:31 Slp: Sco: Attempting to normalize directory path 'D:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Log\ERRORLOG'
2010-10-15 09:51:31 Slp: Sco: Attempting to normalize directory path 'C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20101015_092804\SQLServer_ERRORLOG_2010-10-15T09.51.31.txt'
2010-10-15 09:51:32 Slp: Sco: Attempting to get security descriptor for file 'D:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Log\ERRORLOG'
2010-10-15 09:51:32 Slp: Sco: Attempting to check if file 'D:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Log\ERRORLOG' exists
2010-10-15 09:51:32 Slp: Sco: Returning security descriptor O:NSG:NSD:AI(A;ID;FA;;;NS)(A;ID;FA;;;SY)(A;ID;FA;;;BA)(A;ID;FA;;;S-1-5-21-3546625195-1536672478-4029743794-1010)(A;ID;0x1201ff;;;S-1-5-21-3546625195-1536672478-4029743794-1011)
2010-10-15 09:51:32 Slp: Sco: Attempting to dispose script
2010-10-15 09:51:32 Slp: Sco: Attempting to disconnect script
2010-10-15 09:51:32 Slp: Current SqlServer Connection closed...
2010-10-15 09:51:32 Slp: Configuration action failed for feature SQL_Engine_Core_Inst during timing ConfigRC and scenario ConfigRC.
2010-10-15 09:51:32 Slp: A severe error occurred on the current command.  The results, if any, should be discarded.
A severe error occurred on the current command.  The results, if any, should be discarded.
2010-10-15 09:51:32 Slp: Configuration action failed for feature SQL_Engine_Core_Inst during timing ConfigRC and scenario ConfigRC.
2010-10-15 09:51:32 Slp: System.Data.SqlClient.SqlException: A severe error occurred on the current command.  The results, if any, should be discarded.
2010-10-15 09:51:32 Slp: A severe error occurred on the current command.  The results, if any, should be discarded.
2010-10-15 09:51:32 Slp:    at Microsoft.SqlServer.Configuration.Sco.SqlScriptExecution.ExecuteScriptStatement(String& scriptStatement)
2010-10-15 09:51:32 Slp:    at Microsoft.SqlServer.Configuration.SqlEngine.SafeSqlCommand.ExecNonQuery(String script)
2010-10-15 09:51:32 Slp:    at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineScriptExecution.RunEngineInstallScripts(SqlServiceInstallScriptParameters scriptParameters)
2010-10-15 09:51:32 Slp:    at Microsoft.SqlServer.Configuration.SqlEngine.SqlDatabaseServiceConfig.Install(SqlServiceInstallScriptParameters scriptParameters)
2010-10-15 09:51:32 Slp:    at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.ConfigSQLServerSystemDatabases(EffectiveProperties properties, Boolean isConfiguringTemplateDBs, Boolean useInstallInputs)
2010-10-15 09:51:32 Slp:    at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.DoCommonDBStartConfig(ConfigActionTiming timing)
2010-10-15 09:51:32 Slp:    at Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.Install(ConfigActionTiming timing, Dictionary`2 actionData, PublicConfigurationBase spcb)
2010-10-15 09:51:32 Slp:    at Microsoft.SqlServer.Configuration.SqlConfigBase.PrivateConfigurationBase.Execute(ConfigActionScenario scenario, ConfigActionTiming timing, Dictionary`2 actionData, PublicConfigurationBase spcbCurrent)
2010-10-15 09:51:32 Slp:    at Microsoft.SqlServer.Configuration.SqlConfigBase.SqlFeatureConfigBase.Execute(ConfigActionScenario scenario, ConfigActionTiming timing, Dictionary`2 actionData, PublicConfigurationBase spcbCurrent)
2010-10-15 09:51:32 Slp:    at Microsoft.SqlServer.Configuration.SqlConfigBase.SlpConfigAction.ExecuteAction(String actionId)
2010-10-15 09:51:32 Slp:    at Microsoft.SqlServer.Configuration.SqlConfigBase.SlpConfigAction.Execute(String actionId, TextWriter errorStream)
2010-10-15 09:51:32 Slp: Exception: System.Data.SqlClient.SqlException.
2010-10-15 09:51:32 Slp: Source: .Net SqlClient Data Provider.
2010-10-15 09:51:32 Slp: Message: A severe error occurred on the current command.  The results, if any, should be discarded.
2010-10-15 09:51:32 Slp: A severe error occurred on the current command.  The results, if any, should be discarded..
2010-10-15 09:51:34 Slp: Sco: Attempting to write hklm registry key SOFTWARE\Microsoft\Microsoft SQL Server to file C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20101015_092804\Registry_SOFTWARE_Microsoft_Microsoft SQL Server.reg_
2010-10-15 09:51:34 Slp: Sco: Attempting to write hklm registry key SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall to file C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20101015_092804\Registry_SOFTWARE_Microsoft_Windows_CurrentVersion_Uninstall.reg_
2010-10-15 09:51:34 Slp: Sco: Attempting to write hklm registry key SOFTWARE\Microsoft\MSSQLServer to file C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\20101015_092804\Registry_SOFTWARE_Microsoft_MSSQLServer.reg_
2010-10-15 09:51:57 Slp: A severe error occurred on the current command.  The results, if any, should be discarded.
A severe error occurred on the current command.  The results, if any, should be discarded.
2010-10-15 09:51:59 Slp: Watson bucket for exception based failure has been created
2010-10-15 09:54:07 Slp: Completed Action: SqlEngineDBStartConfigAction_install_configrc_Cpu32, returned False
2010-10-15 09:54:07 Slp: Sco: Attempting to get instance feature flag UpgradeIncomplete for feature SQL_Engine_Core_Inst, instance MSSQL10.MSSQLSERVER
2010-10-15 09:54:07 Slp: Sco: Attempting to create base registry key HKEY_LOCAL_MACHINE, machine
2010-10-15 09:54:07 Slp: Sco: Attempting to open registry subkey
2010-10-15 09:54:07 Slp: Sco: Attempting to open registry subkey SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.MSSQLSERVER\UpgradeIncompleteState
2010-10-15 09:54:07 Slp: Sco: Attempting to get registry value SQL_Engine_Core_Inst
2010-10-15 09:54:07 Slp: Sco: Attempting to get feature configuration state for feature SQL_Engine_Core_Inst, instance MSSQL10.MSSQLSERVER
2010-10-15 09:54:07 Slp: Sco: Attempting to get instance feature flag ConfigurationState for feature SQL_Engine_Core_Inst, instance MSSQL10.MSSQLSERVER
2010-10-15 09:54:07 Slp: Sco: Attempting to create base registry key HKEY_LOCAL_MACHINE, machine
2010-10-15 09:54:07 Slp: Sco: Attempting to open registry subkey
2010-10-15 09:54:07 Slp: Sco: Attempting to open registry subkey SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.MSSQLSERVER\ConfigurationState
2010-10-15 09:54:07 Slp: Sco: Attempting to get registry value SQL_Engine_Core_Inst
2010-10-15 09:54:07 Slp: Sco: Attempting to get instance feature flag UpgradeIncomplete for feature SQL_Engine_Core_Inst, instance MSSQL10.MSSQLSERVER
2010-10-15 09:54:07 Slp: Sco: Attempting to create base registry key HKEY_LOCAL_MACHINE, machine
2010-10-15 09:54:07 Slp: Sco: Attempting to open registry subkey
2010-10-15 09:54:07 Slp: Sco: Attempting to open registry subkey SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.MSSQLSERVER\UpgradeIncompleteState
2010-10-15 09:54:07 Slp: Sco: Attempting to get registry value SQL_Engine_Core_Inst
2010-10-15 09:54:07 Slp: Sco: Attempting to get feature configuration state for feature SQL_Engine_Core_Inst, instance MSSQL10.MSSQLSERVER
2010-10-15 09:54:07 Slp: Sco: Attempting to get instance feature flag ConfigurationState for feature SQL_Engine_Core_Inst, instance MSSQL10.MSSQLSERVER
2010-10-15 09:54:07 Slp: Sco: Attempting to create base registry key HKEY_LOCAL_MACHINE, machine
2010-10-15 09:54:07 Slp: Sco: Attempting to open registry subkey
2010-10-15 09:54:07 Slp: Sco: Attempting to open registry subkey SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.MSSQLSERVER\ConfigurationState
2010-10-15 09:54:07 Slp: Sco: Attempting to get registry value SQL_Engine_Core_Inst
2010-10-15 09:54:07 Slp: Sco: Attempting to get instance feature flag UpgradeIncomplete for feature SQL_Engine_Core_Inst, instance MSSQL10.MSSQLSERVER
2010-10-15 09:54:07 Slp: Sco: Attempting to create base registry key HKEY_LOCAL_MACHINE, machine
2010-10-15 09:54:07 Slp: Sco: Attempting to open registry subkey
2010-10-15 09:54:07 Slp: Sco: Attempting to open registry subkey SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.MSSQLSERVER\UpgradeIncompleteState
2010-10-15 09:54:07 Slp: Sco: Attempting to get registry value SQL_Engine_Core_Inst
2010-10-15 09:54:07 Slp: Sco: Attempting to get feature configuration state for feature SQL_Engine_Core_Inst, instance MSSQL10.MSSQLSERVER
2010-10-15 09:54:07 Slp: Sco: Attempting to get instance feature flag ConfigurationState for feature SQL_Engine_Core_Inst, instance MSSQL10.MSSQLSERVER
2010-10-15 09:54:07 Slp: Sco: Attempting to create base registry key HKEY_LOCAL_MACHINE, machine
2010-10-15 09:54:07 Slp: Sco: Attempting to open registry subkey
2010-10-15 09:54:07 Slp: Sco: Attempting to open registry subkey SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.MSSQLSERVER\ConfigurationState
2010-10-15 09:54:07 Slp: Sco: Attempting to get registry value SQL_Engine_Core_Inst
2010-10-15 09:54:07 Slp: Error: Action "SqlEngineDBStartConfigAction_install_configrc_Cpu32" failed during execution.
2010-10-15 09:54:07 Slp: Action "AgentScriptConfiguration_install_rc_Cpu32" will return false due to the following conditions:
2010-10-15 09:54:07 Slp: Condition "Feature dependency condition for action: AgentScriptConfiguration_install_rc_Cpu32 The condition tests feature: SQL_Engine_Core_Inst_sql_engine_core_inst_Cpu32. There are 10 dependant features. The feature is tested for results: ValidateResult, Result." did not pass as it returned false and true was expected.
2010-10-15 09:54:07 Slp: Condition is false because the required feature SQL_Engine_Core_Inst_sql_engine_core_inst_Cpu32 failed in result Result
2010-10-15 09:54:07 Slp: Error: Action "AgentScriptConfiguration_install_rc_Cpu32" failed during execution.
2010-10-15 09:54:07 Slp: Action "RS_RunInstallScriptsAction_Cpu32" will return false due to the following conditions:
2010-10-15 09:54:07 Slp: Condition "Feature dependency condition for action: RS_RunInstallScriptsAction_Cpu32 The condition tests feature: SQL_Engine_Core_Inst_sql_engine_core_inst_Cpu32. There are 10 dependant features. The feature is tested for results: ValidateResult, Result." did not pass as it returned false and true was expected.
2010-10-15 09:54:07 Slp: Condition is false because the required feature SQL_Engine_Core_Inst_sql_engine_core_inst_Cpu32 failed in result Result
2010-10-15 09:54:07 Slp: Error: Action "RS_RunInstallScriptsAction_Cpu32" failed during execution.
2010-10-15 09:54:07 Slp: Action "SqlEngineDBStopConfigAction_install_configrc_Cpu32" will return false due to the following conditions:
2010-10-15 09:54:07 Slp: Condition "Feature dependency condition for action: SqlEngineDBStopConfigAction_install_configrc_Cpu32 The condition tests feature: SQL_Engine_Core_Inst_sql_engine_core_inst_Cpu32. There are 10 dependant features. The feature is tested for results: ValidateResult, Result." did not pass as it returned false and true was expected.
2010-10-15 09:54:07 Slp: Condition is false because the required feature SQL_Engine_Core_Inst_sql_engine_core_inst_Cpu32 failed in result Result
2010-10-15 09:54:07 Slp: Error: Action "SqlEngineDBStopConfigAction_install_configrc_Cpu32" failed during execution.
</code>
Any help would be greatly appreciated as this is blocking a bunch of work and I've searched all over to find a solution.
Answer: I still do not know what was causing this issue but I was able to work around it by installing component by component, one at a time, in the following order:

Database Engine
Full Text
Analysis Services
Reporting Services
Client Connectivity
Client Tools

SQL 2008 Install Failure


Continue script execution after try/except exception with Python

Question: Coming from other scripting languages I'm probably missing something fundamental here.
How do I continue on with the rest of the script when an exception is raised?
Example:
errMsg = None
try:
    x = 1
    y = x.non_existent_method()
except ValueError as e:
    errMsg = str(e)

if errMsg:
    print('Error')
else:
    print('All good')

The script just fails. Is there a way to continue with the rest?
Thanks in advance
Comment: You are catching the wrong exception.
Comment: that's embarrassing...it should be Exception and not ValueError. thank you
Answer: It should be Exception and not ValueError:
errMsg = None
try:
    x = 1
    y = x.non_existent_method()
except Exception as e:
    errMsg = str(e)

if errMsg:
    print('Error')
else:
    print('All good')


How to set httpOnly flag true for cookie in Java?

Question: I tried the setHtpOnly(true) option but it doesn't seem to be working as it isn't a method in Cookie. I did see a few solutions using path but I'm not sure about that either.
This is my code.
<code>Cookie cookie = new Cookie (name, entity);
cookie.setPath("/");
httpServletResponse.addCookie(cookie);
</code>
What can I do to set the httpOnly flag as true for the above code?
Answer: What version of Java are you using? Are you seeing a specific error on compilation? This method seems to exist in Java EE since at least 6 and Servlet 3.1:
https://docs.oracle.com/javaee/6/api/javax/servlet/http/Cookie.html#setHttpOnly(boolean)


Writing a vector to csv in c++

Question: I'm trying to write a vector to a .csv final in c++ but the formatting of the .csv file is wrong.
I am currently doing this:
    ofstream myfile(rtn);
    int vsize = returns.size();
    for(int n=0; n<vsize; n++)
     {
     myfile << returns[n] << '\t';
     myfile << "," ;
     }

Which works but it writes the vector like this:
a,b,c,d, (All in one row but different columns)
I need the code to write:
 a
 b
 c
 d

All in one column but on different rows. Does anyone have suggestions on how I would go about doing this?
Thank you!
Comment: The example output you've shown has no commas, where did you want those to be?  The simple answer is put a `\n` in the right spot rather than `\t`.
Comment: Consider replacing ',' with 'std::endl'
Answer: You can implicitly loop through the vector. Replace std::cout with the std::ofstream to output to file.
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>

int main() {

    std::vector<std::string> v;
    v.push_back("a");
    v.push_back("b");
    v.push_back("c");

    std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "\n"));

    return 0;
}

Answer: ofstream myfile(rtn);
int vsize = returns.size();
for (int n=0; n<vsize; n++)
{
    myfile << returns[n] << endl;
}

This writes an endline character after each character is entered into the file. An alternative would be to use '\n' in place of endl but endl is generally favored because it flushes the buffer after the newline character.
Comment: `but endl is generally favored because it flushes the buffer after the newline character.` generally favored by who? You should only manually flush the buffer if you have a reason too, otherwise leave it up to the implementation.

Writing a vector to csv in c++


Tables and their content are shifting aside - why?

Question: I have several tables and their content looks fine in JSFiddle, but on another website opened in the same browser everything - table, content - shifts to the right (screenshot). How can I force the content to look like it does in JSFiddle example above? Everything should be moved back to the left (see the arrows on the screenshot). Thank you!
Here is the original code:

      Some text

              TITLE

              Description

              phone number

Comment: what do you mean by **another website**? Do you copy and paste your code in local text-editor and see in your PC browser and that is different from your **jsfiddle** code?
Comment: Yes, kind of: this code is the email signature, so I plug it into the email service provider's website and what I see differs from what JSFiddle shows.
Answer: If I understood the problem correctly, you want to shift the contents to the left in any situation. But first you should know the reason of this behavior. The reason is CSS relative units. In CSS you can define the unit of your width, height or any other property in two ways:

With relative units like % or vw or ...
With absolute units like px.

The second one is suitable for cases when you want that an element (here the table tag) has a fixed value (for example a fixed width) regardless of the browser (here browser width). When you put your code in jsfiddle, it shows the result in bottom-right part of the browser. So the width for showing the content is limited and because you defined your width relative (width: 99.0328%) to the width of parent element (here the body tag), you see that the elements are dense and space between them are low. If you see that code in a PC browser (that has more width) you get a different result (like the picture you posted). So one solution for that is to put all the table in a
 tag and give an absolute width to that
 tag like the code below:

<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

        Some text

                    TITLE

                    Description

                    phone number

If you want to learn more about CSS units I suggest to read more tutorials like this one.


$g(x) = f(3x + 2)$. If $f ([2, 5])$ = $[10, 20]$, what is $g([0, 1])$?

Question: Suppose we are given functions $f, g : R → R$ satisfying $g(x) = f(3x + 2)$.
(a) If $f ([2, 5])$ = $[10, 20]$, what is $g([0, 1])$?
(b) If $f^{−1}([−10, 10])$ = $[0, 2]$, what is $g^{−1}([−10, 10])$
I know that this is somehow relates to the image and preimage of a function.
I also think that for part (a) you need to find the formula to get If $f ([2, 5])$ = $[10, 20]$, so then afterwards you could apply the function of $g(x)$.
Could someone tell me how I would find the formula for $f(x)$, or point me in the right direction?
Comment: If we define $h(x)=3x+2$, what is $h([0,1])$? As you know that $g(x)=f(h(x))$, you have the answer.
If $f^{-1}([-10,10])=[0,2]$, then knowing that $g^{-1}=(f\circ h)^{-1}=h^{-1}\circ f^{-1}$, you also have the answer.
Comment: So from this we know that for part $(a)$, $g([0,1])  = [10,20]$?
Comment: Exactly, because $h([0,1])=[2,5]$ and $g=f\circ h$.
Comment: For part (b) then could you just say that $g^{-1}([-10,10]) = [0,2]$?
Comment: A priori, no. $g=f\circ h$, so that $g^{-1}=h^{-1}\circ f^{-1}$ and $h^{-1}([0,2])=\left[\frac{-2}{3},0\right]$, so that $g^{-1}([-10,10])=\left[\frac{-2}{3},0\right]$
Answer: $g(0) = f(3*0+2) = f(2)$
$g(1) = f(3*1+2) = f(5)$
so $g([0,1]) = f([2,5]) = [10,20]$
Try to workout the second problem.
hint: $f([0,2]) = [-10,10]$


int captured by value or by reference

Question: Can someone explain the behaviuor of this program:
using System;
namespace lambda
{

    internal class Program
    {

        static Action a;
        static void fun1()
        {
            // this is local
            int x = 3;

            // lambda a : x captured by value or by reference?
            a = () => { ++x ; };

            // call lambda
            a();

            // x now equals 4
            int b = x;

        }

        static void fun2()
        {
            // call lambda: inside lambda x equals 5
            a();

        }

        static void Main(string[] args)
        {
            fun1();
            fun2 ();
        }
    }
}

In particular I don't understand if x of the lambda is a reference to local x, how can i call a inside fun2?
Comment: I would avoid writing code like this since it can really hamper readability. Your example would be easier to read and understand if it took `x` as an parameter and returned the incremented result, and called something descriptive, like `Increment`.
Comment: @JonasH The code is not production one. the goal is to understand how c# works. My question is: how is it possible that local x is captured by reference, as you can infer by the value of x after calling the lambda, and altough permit to call the lambda inside fun2, where x is out of scope
Answer: This code uses 'a' lambda to increment 'a' variable:

In fun1(), the variable 'x' has 'a' value of 3
A lambda 'a' captures 'x' by reference (it modifies the original 'x')
The lambda 'a' is called, incrementing 'x' to 4
In fun2(), 'a' is called again, making 'x' inside the lambda 5
Finally, fun1() and fun2() are called in the Main() method

So, 'x' goes from 3 to 4 in fun1() and then from 4 to 5 in fun2()
In typical scoping rules, x is indeed out of scope in fun2() when it's called in Main(). However, due to the way lambdas capture variables, it retains access to x even outside of its original scope
I hope this helps.
Comment: Problem: when fun2 is called in Main, x should be out of scope. I think that's what is throwing OP off.
Comment: That's right, I'll take another look and try to edit the answer. Thanks for your feedback
Comment: @Fildor, my friend's reply: In typical scoping rules, x is indeed out of scope in fun2() when it's called in Main(). However, due to the way lambdas capture variables, it retains access to x even outside of its original scope
Comment: Exactly. That should be added to your answer.
Answer: The implementation is storing a copy of x, NOT a reference to x. We can see this by disassembling the output to view the generated IL.
Here's the internal class that's generated to handle the closure over x:
 .class nested private sealed auto ansi beforefieldinit
    '<>c__DisplayClass1_0'
      extends [System.Runtime]System.Object
  {
    .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor()
      = (01 00 00 00 )

    .field public int32 x

    .method public hidebysig specialname rtspecialname instance void
      .ctor() cil managed
    {
      .maxstack 8

      IL_0000: ldarg.0      // this
      IL_0001: call         instance void [System.Runtime]System.Object::.ctor()
      IL_0006: nop
      IL_0007: ret

    } // end of method '<>c__DisplayClass1_0'::.ctor

    .method assembly hidebysig instance void
      '<fun1>b__0'() cil managed
    {
      .maxstack 2
      .locals init (
        [0] int32 V_0
      )

      // [20 19 - 20 20]
      IL_0000: nop

      // [20 21 - 20 25]
      IL_0001: ldarg.0      // this
      IL_0002: ldfld        int32 Console1.Program/'<>c__DisplayClass1_0'::x
      IL_0007: ldc.i4.1
      IL_0008: add
      IL_0009: stloc.0      // V_0
      IL_000a: ldarg.0      // this
      IL_000b: ldloc.0      // V_0
      IL_000c: stfld        int32 Console1.Program/'<>c__DisplayClass1_0'::x

      // [20 26 - 20 27]
      IL_0011: ret

    } // end of method '<>c__DisplayClass1_0'::'<fun1>b__0'
  } // end of class '<>c__DisplayClass1_0'

The important thing to notice here is the .field public int32 x member of the generated class, which is being used to store the value of x.
Also note the implementation of the lambda itself, the '<fun1>b__0'() method.
If you inspect the IL you'll see that it loads the x field using ldfld int32 Console1.Program/'<>c__DisplayClass1_0'::x and then adds 1 to it and stores the result back into Console1.Program/'<>c__DisplayClass1_0'::x.
Finally, the IL for the start of fun1() looks a bit like this:
 .method private hidebysig static void
    fun1() cil managed
  {
    .maxstack 2
    .locals init (
      [0] class Console1.Program/'<>c__DisplayClass1_0' 'CS$<>8__locals0',
      [1] int32 b
    )

    IL_0000: newobj       instance void Console1.Program/'<>c__DisplayClass1_0'::.ctor()
    IL_0005: stloc.0      // 'CS$<>8__locals0'

    // [15 5 - 15 6]
    IL_0006: nop

    // [17 9 - 17 19]
    IL_0007: ldloc.0      // 'CS$<>8__locals0'
    IL_0008: ldc.i4.3
    IL_0009: stfld        int32 Console1.Program/'<>c__DisplayClass1_0'::x

At the start of that you can see it creating the Action wrapper class:
    IL_0000: newobj       instance void Console1.Program/'<>c__DisplayClass1_0'::.ctor()
    IL_0005: stloc.0      // 'CS$<>8__locals0'

And then it loads that object and sets the x field to 3:
    IL_0007: ldloc.0      // 'CS$<>8__locals0'
    IL_0008: ldc.i4.3
    IL_0009: stfld        int32 Console1.Program/'<>c__DisplayClass1_0'::x

That's where the x variable is being captured.
For more information, see this Microsoft article and this article on CodeProject

int captured by value or by reference


r ls list.files pattern curly bracket expansion globbing does not work

Question: I need curly bracket expansion in the pattern argument of the R functions base::ls and base::list.files. For example:
# in terminal
ls
# string1  stringX  stringYZ
ls string{1,X}
# string1  stringX

but
# in R
list.files()
# "string1"  "stringX"  "stringYZ"
list.files(pattern="string{1,X}")
# error: invalid 'pattern' regular expression
list.files(pattern="string\\{1,X\\}")
# character(0) # i.e. finds nothing
list.files(pattern=glob2rx("string{1,X}"))
# character(0) # i.e. finds nothing

Same is true for base::ls.
Thanks a lot for help,
Chris
Comment: Try: "string1$|X$" or "string(1|X)$"
Comment: Try: `list.files(pattern="^string(1|X)$")`
Comment: In Bash, `{1,X}` means either `1` or `X`. Thus, you need either `string(1|X)` or (here, since the `1` and `X` are single chars) `string(?:1|X)` or `string[1X]`
Answer: list.files(pattern="^string(1|X)$") works (list.files(pattern="string(1|X)") as well).
Thanks!
Comment: The difference is, that `string(1|X)` will match also e.g. `Astring1` what `ls string{1,X}` and also `^string(1|X)$` will not.
Answer: A result like ls string{1,X} in sh you can get with:
list.files(pattern="^string(1|X)$")

Alternatively, as pointed out already by @wiktor-stribiżew in the comments, you can use:
list.files(pattern="^string[1X]$")

To have a full string match you have to surround the pattern with ^ and $. Thanks to @wiktor-stribiżew for this comment.
Comment: You can mention that globs require a full string match, that is why you use `^` and `$` anchors.
Answer: You may also want to consider using the glob() function from the {bracer} package:
bracer::glob("string{1,X}")

[1] "string1" "stringX"


Android- Want to show graphics for move an Object from one Point A to B

Question: I am new to make animation and graphics in Android. I am trying to create a Quiz type of game. and it is created . Now I am try to show the diff Levels(Level 1,Level 2...) to player. When a Player finish Level 1 , I want to move that Player Avatar to One Level 1 to Level 2 using some Animation(Ex: Like Candy Crush). Player Avatar moves to next level Automatically. Is there any Lib to animate is Avatar moving to  next level.
And is it possible to switch between my Quiz Game Activity and Game Level Screen using Libary.
Answer: It's a pretty general question so I can only suggest getting into Android animation tools. There right tool for the job is probably PropertyAnimator animating View (avatar) position as described here.
Comment: Thanks a lot. one more doubt, actually i have many levels. I cant show all levels within mobile screen. For ex: for user view i am showing first 4 level. for the 5th level, i want to move avatar(view) and background along with it(Which out of user view). i am so confuse with it. can you suggest any idea or some example for it?


The orbits with respect to two groups from the same conjugacy class are isomorphic

Question: On the Wikipedia page for the Symbolic Method of Flajolet and Sedgewick
https://en.m.wikipedia.org/wiki/Symbolic_method_(combinatorics)
under the heading "Classes of combinatorial structures" it states: "The orbits with respect to two groups from the same conjugacy class are isomorphic."
Does anyone know of a proof of this? Perhaps something like:
Definitions/notation:

$G$ is a group.

$X$ is a set.

$\psi: G \times X \rightarrow X$ is a $G$ action on $X$.

$H$ and $H^{\prime}$ are conjugate subgroups of $G$ — that is,
$H^{\prime} = gHg^{-1}$ for some $g \in G$.

$H$ and $H^{\prime}$ act on $X$ by the restrictions of $\psi$ to $H$
and $H^{\prime}$, respectively.

$\text{orb}_{H}(x)$ and $\text{orb}_{H^{\prime}}(x)$ denote the
orbits of $x \in X$ with respect to $H$ and $H^{\prime}$,
respectively.

$\phi$ denotes the isomorphism between $H$ and $H^{\prime}$ defined
by $\phi(h) = ghg^{-1}$.

Now, define the function $f: \text{orb}_H(x) \rightarrow \text{orb}_{H^{\prime}}(\psi(g, x))$ by
\begin{equation*}
f(\psi(h, x)) = \psi(\phi(h), \psi(g, x)).
\end{equation*} Then, $f$ is a well-defined bijection and
\begin{align*}
f(\psi(h, z)) = \psi(\phi(h), f(z)).
\end{align*}
Many thanks.
Comment: Please do not vandalize your question, particularly after getting an answer.
Comment: I assume in the sense of G sets. That is, that there exists a bijection between the orbits which is compatible with the group actions.
Comment: What's the definition of "isomorphic orbits"?
Answer: After defining conjugacy as a group action, it follows from the definition that the orbits  are now the conjugacy classes.


How do I create content of the day/week/month?

Question: I have a (growing) number of articles. I want to display one on the homepage as article of the week, although that week will probably be a day in the beginning and a month later on. I also want a specific editor be able to choose which of those articles will be the chosen one for a given time period. There will only be one chosen article for any given time. What is the best way to do this (preferably without programming)?
I first thought of creating a vocabulary (with a date field and an entity reference to an article field) for this where the editor can simply add days/weeks/months as they come and select from the articles. The bad part here is that the name field is required and I cannot ui wise set it to take the name from the actual date field.
Making it then a custom content type instead would probably work, but seems overkill.
Adding an article of the timeperiod date field to the article content type would also seem to encapsulate all the necessary information, but how do I expose this to the editor?
I want the editor to see a list of the coming say 20 months and assign to each an article on the same page (a single save operation from the editor's point of view). I also want the editor to be able to override that for specific shorter time periods.
I'm using Drupal 7.
Answer: Using the Flag module seems like a no brainer to me to get this to work: introduce a global flag that is allowed to be used by your editors to flag relevant articles. Since Flags are fieldable, you could add extra field(s) to such flags to let the flagging user indicate an appropriate start date and end date.
With the above in place, you've reduced your question to creating an appropriate view (using Views) which shows the flagged article(s) for which their flag fields (start / end dates) have appropriate values as compared to the current date.
This solution is "without programming" (as in your question) ...
Ps: I'm assuming this is about D7.
Comment: That sounds good, I'm going to try that. And I should indeed have mentioned that it is about Drupal 7. I'm going to add that to the question. Thanks
Comment: I don't want to accept and upvote an answer before testing the solution, but do want to acknowledge. I tested it and this works great.


MYSQL - INSERT INTO using WHERE condition of Table 1

Question: after reading all the "INSERT INTO" posts as well as the documentation, I am still unsure whether what I want is feasible or not.
I want to change the UPDATE below into an INSERT INTO, because I have many 100-thousands of them (speed issues):
   UPDATE city c
   SET
    c.g17h = '3196504',
    c.g17q = '2593487',
    c.g17k = '0',
    c.g17w = '0',
    c.g17s = '0'
   WHERE
    p17t = 30 AND p17l = '30';

or
UPDATE city c
SET
 c.g1h = '0',
 c.g1q = '0',
 c.g1k = '0',
 c.g1w = '0',
 c.g1s = '0'
WHERE
 p1t = 1
 AND p1l = '1';

However, my best solutions do not work:
INSERT INTO city (g17h, g17q, g17k, g17w, g17s)
SELECT
 '3196504',
 '2593487',
 '0',
 '0',
 '0'
FROM valuestoretab
WHERE
 p17t = 30
 AND p17l = '30';

This is of course because my WHERE condition can only be satisfied in the first table (city) but not in the second one which is just a table of values, whereas the city table is a data set where each id has particular values for p17t, p17l and so on.
For clarification:
The first table (city) looks like
cityid1, ownerid1, islandid1, p17t, p17l
cityid2, ownerid2, islandid2, p17t, p17l

with different values for each row for p17t and p17l.
So, my questions would be:
1. Is it at all possible to write a INSERT-Query with a WHERE condition for the table that is being inserted into?
2. If no, do I have to stick to my UPDATE or is there another (fast!) solution?
Thanks to the community!
litotes
Comment: What are those row names? Do you have any idea? This seems like an easy way to extend bug debugging by a bunch of time ("*aaah - I used `g17w` instead of `g17q`. Silly me!*").
Comment: No, I mean solely in the future when you can't figure out why something doesn't work. However if you have `p1t, p2t, p3t, p4t` etc., then you should normalize your data instead.
Comment: These row names indicate 5 types of resources per city, e.g. q for quarry that are needed for 1-32 buildings that may be built on 1-17 places in each city (hence the p17t = place, p17l = level of building). Debugging is not a problem here, because the UPDATE queries ran successfully and have been checked for data inconsistencies. Is that what you mean?
Comment: can you give an example of your ValueStoreTab and maybe the relation between City and ValueStoreTab? Also, column names don't have accents , column 'col' != col
Comment: ValueStoreTab looks like: row1: p1t = 1, p1l = 1, g1h = someval, g1q = someotherval; row2: p1t = 1, p1l = 2, g1h = some3val etc.; row3: p2t = 2, p2l = 1, g1h = some4val etc. p1t going up to p17t and p1l going up to p32l but varying. The relation is not specified at the moment, but other than identical combinations of p1t-p17t and p1l-p32l in both tables there are no IDs to connect.
Comment: normalize, normalize, normalize
Comment: I don't get it. You want to replace an update statement with an insert statement? You want the insert statement to actually update records, not insert them? Because you think it's faster? Well, there's `INSERT ... ON DUPLICATE KEY UPDATE`, but that's a different story. And it certainly is not faster. Apart from that, replacing update with insert is not possible. Was someone trying to fool you?
Comment: I have info on building type and building level for each of 17 fields for 1000s of rows, each differing. Each building + level combination is associated with different values for the building materials. I want to fill the building material fields depending on building and level for each row. Since the material fields are empty I thought to use INSERT instead of UPDATE, because it takes my computer full days to calculate all the updates.
Comment: `it takes my computer full days to calculate all the updates` <- There's something wrong with your computer. Again, an insert can not replace an update. If you have rows with `null` values in some columns either delete the rows and insert again or fix your indexes on the fields that identify the row to be updated. I'd prefer the latter.
Comment: I don't seem to get your table structure...
Comment: My computer is absolutely ok, in fact it is rather fast - it is just the sheer number of updates (16000 Queries * 17DBs * 15000 rows per DB). There are no NULL values. The table structure is (cols): building type/building level/material1/material2/etc. with type and level variable per row and the material should be inserted depending on type and level. So, my original question remains (but thanks for the help so far!): Is there an INSERT Syntax with a WHERE condition on the table to be modified??
Answer: To give a quick answer insert with a select statement is possible
Insert INTO MyTable (Val1, Val2)
Select
 SomeValue,
 AnotherValue
From MyOtherTable
Where Date = Getdate()

On the other hand, you can also update many records like in the following example:
Update t1
Set
 t1.Val1 = t2.SomeValue,
 t1.Val2 = t2.AnotherValue
From MyTable t1
Inner join MyOtherTable t2 ON t1.PK = t2.FK
where t2.Date = getdate()

EDIT:
When i read the following query, I presume p17t and p17l are from the valuestoretab.
UPDATE city c
SET
 c.g17h = '3196504',
 c.g17q = '2593487',
 c.g17k = '0',
 c.g17w = '0',
 c.g17s = '0'
WHERE
 p17t = 30 AND p17l = '30';

==> changed this into:
UPDATE c
SET
 c.g17h = '3196504',
 c.g17q = '2593487',
 c.g17k = '0',
 c.g17w = '0',
 c.g17s = '0'
FROM City c, ValueStoreTab v
WHERE
 c.SomeCol = v.SomeCol -- Here, your relation must exist!
 AND v.p17t = 30 AND v.p17l = '30';

Comment: change "col" to actual column name from your table?
Comment: Thanks, but that does not solve the problem, because any WHERE t1.col = t2.col condition results in the error "unknown column name t1.col in WHERE clause".


Adding parameters to $header links

Question: Is there a way we can specify which link to use to sort a drupal table, or atleast, specify some parameters to the header links?
To be more clear, my table uses the following link when I click on the headers to sort the table: http://mysite.com/node?sort=asc&order=Name
What I would like the header link to look like is this: http://mysite.com/node?nid=123&pager_element_id=3&sort=desc&order=Name
Is there any way we can give the parameters to the header links?
Answer: The code that outputs the links for the table header is contained in tablesort_header().
$cell['data'] = l($cell['data'] . $image, $_GET['q'], array('attributes' => array('title' => $title), 'query' => array_merge($ts['query'], array('sort' => $ts['sort'], 'order' => $cell['data'])), 'html' => TRUE));

The function is called from theme_table(), which is the theme function used to render a table.
What you can do is implementing your theme function that is then used to render the table your module is outputting. There isn't any other method, as theme_table() is not getting any parameter that changes the URL for the table header; as such, implementing hook_preprocess_table() would not achieve anything.
To implement a theme function, you need to declare it using hook_theme().
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_table' => array(
      'variables' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL, 'colgroups' => array(), 'sticky' => TRUE, 'empty' => ''),
    ),
  );
}

Once you declared the theme function, you can use it as you used theme_table(), simply replacing any call to theme('table', /* the rest of the arguments */) with theme('mymodule_table', /* the rest of the arguments */). Notice that in hook_theme() the theme function is referred as mymodule_table, but the PHP function is theme_mymodule_table().
The code you need for your theme function is the same used by theme_table(), except that instead of calling tablesort_header() it will call your own function.
foreach ($header as $cell) {
  $cell = tablesort_header($cell, $header, $ts); // Replace it with the call to your function.
  $output .= _theme_table_cell($cell, TRUE);
}

Comment: Could you please clarify, as I don't grasp the idea of implementing it in the theme function.

Adding parameters to $header links


WSDL server HTTP headers

Question: I am sending request to WSDL server, and I have some funny results. In about 9 of 10 cases I got error from server, however in 1 of 10 I got successful response.
Headers from successful response:
HTTP/1.1 200 OK
Date: Thu, 01 Sep 2011 09:34:47 GMT
Content-Type: text/xml; charset=utf-8
x-wily-servlet: Clear appServerIp=x.x.x.x&agentName=esb_online_server4&servletName=HttpTransportServlet&servletResponseTime=4&agentHost=z2esb04.xxx.com&agentProcess=WebLogic
X-Powered-By: Servlet/2.5 JSP/2.1
x-wily-info: Clear guid=24573561C68E76520E3CD0AC3E3A7EC9
Content-Length: 568
Connection: close

From failure:
HTTP/1.1 500 Internal Server Error
Date: Thu, 01 Sep 2011 09:34:45 GMT
Server: WebSphere Application Server/5.0
Content-Type: text/xml; charset=utf-8
Content-Language: en
Connection: close
Content-Length: 521

I am trying to figure our where is the problem, however I am responsible for client side only. Does it mean that there are two different servers that may respond to same request with same URL, and therefore it must be problem somewhere in backend configuration?
Answer: It sure looks like there are multiple separate servers responding to that same URL, thus that same IP address. I suspect some kind of IP sprayer is being used and is distributing between a WebLogic server (which understands the URL) and a WebSphere one (which doesn't).
When you get the 200 response, do you also receive WSDL data content?
Comment: Yep. It seems there is a problem on the backend side - load balancer forwards requests to different servers, and one of them is misconfigured.

WSDL server HTTP headers


Getting started with the Form API and Ajax framework

Question: I'm really struggling to understand how to use Drupal 7's Form API in conjunction with its Ajax framework. I'd like to accomplish the following:
On certain pages, multiple nodes may appear. Each one of these nodes should have a comment form appear right below it. When the user submits a comment, it should be done via Ajax and the resulting comment should then appear under the node in question.
Can someone give me an overview of the steps that are required to do this?
Answer: There is a module for submitting forms with Ajax.

Provides AJAX comments to Drupal sites. Features:

Makes AJAX submits
Allows replies to comments on the actual thread page
AJAX comments deleting
Works with CAPTCHA
Cool jQuery sliding
Comment: They only have a dev version for D7.
Comment: Indeed, but if you download the module and take a look a the code, you can get started on how to implement Ajax into your forms.
Comment: Though it is in dev the ajax_comments module currently does what you are asking for. If you have any issues please file a ticket in the module's issue queue.
Comment: @maxedison Have a look at the [issue queue](http://drupal.org/project/issues/ajax_comments?text=&status=Open&priorities=All&categories=bug&version=7.x&component=All), it doesn't look like there's anything particularly prohibitive in there, I'd just get stuck in and give it a try
Answer: Check out the Examples module.  There is loads of information and examples on how to implement AJAX with Drupal 7 forms :-)


Manually applying OData query options using Breeze and still return InlineCount

Question: I'm using Breeze with a Web API back-end and I am trying to figure out how to properly apply the received OData query options while also trying to return the inlineCount for the given OData query.
The reason I'm trying to do this is because I need to hit another datasource and fill in some associated properties on the entity that I'm returning (all while still allowing for paging and sorting).
Here's an example of what I'm trying to do:
<code>[HttpGet]
public QueryResult Reservations( ODataQueryOptions options ) {
    var set = _contextProvider.Context.Reservations.Where(r => r is ScheduledReservation || r is PoolReservation).Include(i => i.ReservationType)
                                      .Include(i => i.Vehicle)
                                      .Include(i => i.Vehicle.VehicleMake)
                                      .Include(i => i.Vehicle.VehicleModel).AsQueryable();

    var queryable = Breeze.WebApi.QueryHelper.ApplyQuery(set, options, new ODataQuerySettings { EnableConstantParameterization = true, EnsureStableOrdering = true, HandleNullPropagation = HandleNullPropagationOption.Default });

    // Hit other data source here and fill in associated properties on returned entities

    return new QueryResult
    {
        InlineCount = // Would like to get at breeze's execution of this query,
        Results = queryable.Cast<Reservation>()
    };
}
</code>
How do I manually apply the query options to my Queryable while still allowing for Breeze to take care of executing and returning an inlineCount?
The problem with what I'm doing above is three-fold:
1) This is throwing an error saying that Breeze cannot create an EDM model because this action method returns a QueryResult and not something that implements IEnumerable<>.
2) I'm using Breeze's ApplyQuery() method instead of the ApplyTo() off of the ODataQueryOptions object because I am also wanting to sort on nested properties which ApplyTo() does not yet allow.  I'm not sure if I'm over-stepping my bounds by digging into Breeze's functionality and manually calling the ApplyQuery() method.
3) I can see in EF Profiler that the query to retrieve the inlineCount is executing when calling Breeze's ApplyQuery method.  I have found that the ApplyQuery method is setting the inlineCount on the ODataQueryOptions object as a property with a key of MS_InlineCount.  So, it doesn't appear that there is an "easy" way to get at that (rather, it seems hokey for me to go pull it out of the ODataQueryOptions properties array).
The over-arching reason why I'm asking is this whole line of thinking feels awkward.  I want to double-check and make sure I have not missed something that would allow me to easily apply the OData query to my DbSet and still allow for returning the inlineCount (and still allow for proper paging and sorting).
Answer: I eventually stumbled upon the solution to this problem.  The following post is what lead me to the proper solution to take care of the problem I described above.
Breeze WebAPI: How to combine QueryResult with ODataQueryOptions to return inlineCount


Intuition for Well-Founded Relations

Question: On page 11 of Holz's Introduction to Cardinal Arithmetic a well founded relation $R$ is defined as
that for which

$\forall x\in\text{fld}(R)\exists y\left(x\in y\land R^{-1}[y]\subseteq y\right)$, and
$\forall x\subseteq\text{fld}\left(x\neq 0\implies \exists y\in x\forall z\in x\left(\sim z R y\right)\right).$

Is there any more intuitive way of explaining this concept and why it is introduced?
Comment: This book is an introduction to cardinal arithmetic, not set theory. Try, e.g., Hrbacek and Jech, chapter 14.
Comment: The content of your question is outside my scope. Maybe it is not useful for you but at least let me provide the definition that I am familiar with in set-theory. "A relation $R$ on a set $A$ is well-founded if for every non-empty $B\subseteq A$ there is some $x\in B$ that is $R$-minimal in the sense that $yRx$ implies that $y\notin B$." Such a relation can be used for induction and recursion. Also there is a broader version for classes. The axiom of regularity states that $\in$ is well-founded.
Answer: The user drhab has mentioned in the comments that well-foundedness is used for induction. The usual proof that induction is a sound method of mathematical reasoning goes something along these lines:

Say that you are trying to prove $\forall(x\in\mathbb N)(\phi(x))$ for some property $\phi$. Assume towards a contradiction that you have proven $\phi(0)$ and $\forall(x\in\mathbb N)(\phi(x)\implies\phi(x+1))$, but yet $\phi$ is false for some natural number. Consider the set $F$ of natural numbers for which $\phi$ fails, or $\{n\in\mathbb N\mid\lnot\phi(n)\}$. Since we assumed $\phi$ is false for some natural number, it is nonempty, so since the natural numbers are well-ordered, $F$ has a least element, call it $k$. We know $k$ can't be $0$, since you proved $\phi(0)$. So $k$ has to be some natural number greater than $0$. But since $k$ was the least element of $F$, the smaller number $k-1$ can't be in $F$, so $\phi(k-1)$ must be true. But then by the induction that you have proved, $\phi(k-1)\implies\phi(k)$, so $\phi(k)$ is true. But this contradicts that $k$ was an element of $F$.

The use of well-foundedness of $\mathbb N$ is in bold and is needed to pick the least element $k$ out of $F$ and continue the proof.
This also intuitively explains why induction does not work in some scenarios, like if one were to attempt to prove a property holds for all subsets of $\mathbb N$ by "building up the subsets". Specifically, say that someone has proven $\phi(\varnothing)$, and has shown that for $X\subseteq\mathbb N$, $y\in\mathbb N$, if you assume $\phi(X)$ is proven, then you can prove $\phi(X\cup\{y\})$, and then attempts to conclude that $\phi(X)$ holds for all $X\subseteq\mathbb N$. (For example, they show that $\phi(\{\})$ holds, then from that they conclude that $\phi(\{0\})$ holds, then that $\phi(\{0,1\})$ holds, $\phi(\{0,1,4\})$ holds, $\phi(\{0,1,4,9\})$ holds, etc., then they claim that they have just shown $\phi(\textrm{set of square numbers})$ holds by induction.)
Yet this method of induction can give false conclusions. For example, say $\phi(X)$ is "$X$ is finite". You can prove $\varnothing$ is finite, and that if $X$ is finite then $X\cup\{y\}$ has to be still finite, but clearly this attempt of induction must be doing something wrong, as not every subset of $\mathbb N$ is finite! The key thing here is that well-foundedness doesn't hold. There is an infinite decreasing sequence of counterexamples $\ldots\subset\{4,9,16,\ldots\}\subset\{1,4,9,16,\ldots\}\subset\{0,1,4,9,16,\ldots\}$, so you can't take a "smallest" counterexample and use the fact that it's the smallest to derive a contradiction, like we did in the natural number case - in the realm of subsets of $\mathbb N$, there is not always a smallest one out of any given set of them, as $\subset$ is not well-founded on $\mathcal P(\mathbb N)$. In the falling domino metaphor for induction, the problem is that the dominos for some $X$ like $\{0,1,4,9,16,\ldots\}$ are unreachable, there is an infinite backwards sequence of dominos before it that never ends up getting toppled.

About this formulation of well-foundedness, the first condition seems unnecessary, since if I am not mistaken you can always choose $y=\mathrm{fld}(R)$ to get $x\in y$ and $R^{-1}[y]\subseteq y$. (I am assuming $R^{-1}[y]$ is $\{z\in\mathrm{fld}(R)\mid zRy\}$.) The one I am more familiar with is as in drhab's comment, consisting just of condition 2.

Intuition for Well-Founded Relations


Defining the set of pre-images of a product of random variables in terms of the sets of pre-image of the original random variables

Question: Say I have two random variables $X$ and $Y$. Their respective $\sigma$-algebras are $$\sigma(X) = \{ X^{-1}(B) \mid B \in \mathscr{B} \}$$ and $$\sigma(Y) = \{ Y^{-1}(B) \mid B \in \mathscr{B} \}.$$
Their product $XY$ has sigma-algebra: $$\sigma(XY) = \{ (XY)^{-1}(B) \mid B \in \mathscr{B} \}.$$
Is there a way to define $\sigma(XY)$ in terms of $\sigma(X)$ and $\sigma(Y)$ (not necessarily using unions, intersections or complements)?
For instance, we can define $$\sigma(A_1,A_2) = \sigma(\sigma(A_1) \cup \sigma(A_2))$$ instead of $\sigma(A_1,A_2)$ the smallest $\sigma$-algebra containing $A_1$ and $A_2$ and generated by the partition $\{B_1, B_2, B_3, B_4\}$ where \begin{align}B_1 &= A_1 \setminus A_2,\\ B_2 &= A_2 \setminus A_1,\\ B_3 &= A_1 \cap A_2,\\ B_4 &= (A_1 \cup A_2)^{C}.\end{align}
Comment: Answer: No (as two-valued random variables show).
Comment: @Did Thanks. What is it that two-valued random variables show?
Answer: Let $\Omega = \{a,b\}$.
Define $X,Y:\Omega\to\mathbb R$ by
$$X(\omega) = \begin{cases}0,& \omega=a\\ 1,&\omega=b. \end{cases} $$
and
$$Y(\omega) = \begin{cases}1,& \omega=a\\ 0,&\omega=b. \end{cases} $$
Then $\sigma(X)=\sigma(Y) = 2^\Omega$, but $XY$ is identically zero so $\sigma(XY)=\{\varnothing,\Omega\}$.
Comment: I guess you mean to say that it is easy to construct pathological examples and hence 'no'. Thanks Math1000 ^-^
Comment: @Did Clever way of circumventing the lower bound on characters in a comment..


Exchange 2010 unable to send to external email address using a receive connecter

Question: I have set up receive connector on my Exchange 2010 server to receive email from my Nagios box. I have an external email address in my contacts for nagios to convert emails to text. It seems exchange is refusing to relay mail to an external address but it will relay fine if the address is internal. Are there any other places to look for settings besides the hub transport rules? I also have the receive connecter set up for anonymous login. Any ideas?
Comment: What do you mean that it won't relay for an external address?  So you're sending an email from Outlook(?) to firstname.lastname@example.com and it rejects it?
Answer: Assuming you've created your internal receive connector properly (locked down to Nagios IP) you need to run this command:
Get-ReceiveConnector RelayConnector | Add-ADPermission -User "NT AUTHORITY\ANONYMOUS LOGON" -ExtendedRights "ms-Exch-SMTP-Accept-Any-Recipient"
This will enable the specific permission that enables an open relay.  This is disabled by default on all connectors created.


Stone-Cech compactification

Question: Please help me to figure out this problems.
Let X be a metric space and let Y be a compact metric space. Denote by $\Phi: X \rightarrow \beta X$ the standard embedding of X as a dense subset of its Stone-Cech compactification $\beta X$.
With this assumptions, I want to prove that to every continuous map $f: X \rightarrow Y$ there corresponds a continuous map $f^\beta : \beta X \rightarrow Y$ so that $f^\beta \circ \Phi = f$.
I started the prove with f induces a map $H_f: C_b(X)^* \rightarrow C_b(Y)^*$; then I consider the restriction of $H_f$ to $\beta X$. Then I don't know what to do.
Answer:
Show first that if $f:X\to Y$ then there is an induced map $\beta f:\beta X\to\beta Y$ which is continuous.
Then show that if $Y$ is compact, the natural map $Y\to \beta Y$ is an homeomorphism.
Answer: It is true when X is any Tychonoff space and Y is any compact Hausdorff space. For a proof, see General Topology (Revised and completed edition) by R.Engelking, section 3.6.1 (page 173 in the English edition).

Stone-Cech compactification


Send spam mail to a special folder using postfix

Question: I have a postfix server running amavis and SpamAssassin to help filter spam. Messages that are detected as spam look like this when delivered into the user's Maildir:

From tom@tom-mint Fri Mar 15 01:46:20 2013
Return-Path: <tom@tom-mint>
X-Original-To: firstname.lastname@example.com
Delivered-To: firstname.lastname@example.com
X-Virus-Scanned: Debian amavisd-new at my-server.com
X-Spam-Flag: YES
X-Spam-Score: 6.463
X-Spam-Level: ******
X-Spam-Status: Yes, score=6.463 tagged_above=2 required=6.31
    tests=[DRUGS_ERECTILE=2.221, FH_FROMEML_NOTLD=0.18,
    FSL_HELO_NON_FQDN_1=0.001, HELO_NO_DOMAIN=0.001, RCVD_IN_PBL=3.558,
    RDNS_DYNAMIC=0.363, TO_NO_BRKTS_DYNIP=0.139] autolearn=no
Date: Fri, 15 Mar 2013 01:46:19 -0400
To: firstname.lastname@example.com
Subject: ***SPAM*** hello
User-Agent: Heirloom mailx 12.5 6/20/10
Content-Type: text/plain; charset=us-ascii
From: tom@tom-mint (Tom)
Status: RO

buy some viagra!

Note specifically the subject, which is prepended with ***SPAM***, and the X-Spam-Flag: YES header.
What's the best way to configure postfix to store these messages in a special junk folder?
From my research, it seems like I will need to use a different mail delivery tool than postfix to accomplish this, but I am not sure what approach is the best. There seems to be a lot of dated information, and I am wondering whether postfix is capable of placing messages into a folder or not.
The mail directories are all Maildir.
Comment: Looks like it might be necessary to use something like [maildrop](https://en.wikipedia.org/wiki/Maildrop). I am still looking for a way to do this with Postfix's default MDA so I can keep aliases and other postfix features with minimal trouble. I will post my answer when I come up with it.
Answer: Cursory perusal of postfix's local(8) local delivery agent man page shows no hint of this type of capability - as expected. This kind of tasks is usually offloaded to procmail (probably through  the mailbox_command directive) which can handle the task you describe while managing your kitchen sink on the side. The downside of procmail is the config file format, the upside the flexibility and the tons of examples that are easily found. If anything better than procmail has recently emerged, I know not.
For my money, though, even if I found the way to shoehorn the MTA in doing what you want, I would not follow that road, because this kind of mail sorting things have a way of balooning and no MTA (that I know of: perhaps exchange does,who knows) can do a good job in also being a flexible message handler/delivery agent.
This is a procmail recipe that woud do what you want based on the sole header content (where DEFAULT is the delivery directory, often something like $HOME/Mail/):
:0
* ^X-Spam-Flag: YES
$DEFAULT/.Spam/

Edit:
(This assumes maildir mailbox format, as noted in a comment below. Omit final slash if using mbox)
Comment: `$DEFAULT/` is not necessary. Helpful for human readability. Also note, that adding a slash at the end will create a Maildir, if using Mbox then omit the slash (see: https://unix.stackexchange.com/a/132658/241396).
Answer: As Alien Life Form said, this is a job for procmail. That's not a replacement for the mail server's local delivery agent; it's a separate process which will be called after the MDA has done it's work.
Each user that wants to have procmail sort their mail will need to create a file called .forward in their home directory. That file should contain the following:
"|exec /usr/local/bin/procmail || exit 75"

complete with the " sign and all.
ALF has already posted a basic .procmail file that will sort the mail tagged with spam into a separate folder.
Comment: Please note that in some cases procmail lives at /usr/bin/procmail, to figure out where it is on your system run `which procmail`
Answer: What is your mail delivery agent (see main.cf mailbox_command)?  If the MDA is dovecot, it supports the Sieve IETF standard (rfc5228), which can do a lot more than procmail without exposing possible security holes.  DON'T bolt on procmail to postfix/dovecot, sieve is fully integrated.  If you're using Courier, then procmail is an okay solution.  However, you will find the sieve/sievec programs from Pigeonhole to be faster and cleaner.
The following is a simple sieve script to recognize your spam header and put the message in the Trash file.
require "fileinto";

if header :comparator "i;ascii-casemap" :contains "Subject" "**SPAM**"
{
  fileinto "Trash";
  stop;
}


Values of parameters for which a function is differentiable

Question: I am given the piecewise function $G(t)$, which is written below, and I am asked to find all values of the parameters $\alpha$ and $\beta$ for which the function $G$ is differentiable at $t=1$.
$G(t)=\alpha t^{2}+\ln(t)$  if $t\geq 1$
$G(t)=\beta e^{t-1}-2t$ if $t<1$
I am also given the hint:

You may assume that:$$\lim_{x\to0} \frac{e^{x}-1}{x}=1$$
  $$\lim_{x\to 0} \frac{\ln(1+x)}{x}=1$$

I know that the function must be continuous, so $\lim\limits_{t\to 1^+}G(t)=\lim\limits_{t\to 1^-}G(t)$. This leaves me with $\beta-2=\alpha$. I am a bit confused with my next steps. I believe I must use the definition of a derivative in order to set the slopes of each parts of $G(t)$ to be equal to each other. We are not far enough in the course to simply take the derivatives of each part of $G(t)$.
Answer: For the function to be differentiable at $1$, you need
$$\lim_{x\to 0}\frac{G(1+x)-G(1)}{x}$$
to exist.
Note that $G(1) = \alpha$.
Evaluating the limit from the right, we have
$$\begin{align*}
\lim_{x\to 0^+}\frac{G(1+x)-G(1)}{x} &= \lim_{x\to 0^+}\frac{\alpha(1+x)^2+\ln(1+x)-\alpha }{x}\\
&= \lim_{x\to 0^+}\frac{\alpha\bigl((1-x)^2-1\bigr) + \ln(1+x)}{x}\\
&= \lim_{x\to 0^+}\frac{\alpha(x^2-2x)}{x} + \lim_{x\to 0^+}\frac{\ln(1+x)}{x}\\
&=\lim_{x\to 0+}\alpha(x-2) + 1\\
&= 1-2\alpha.
\end{align*}$$
Now try evaluating the limit from the left in a similar manner; the two limits must be equal for the derivative to exist. (If the derivative exists, this automatically guarantees continuity).
Comment: It worked out very well, thank you!
Answer: Your belief is true, the definition of the derivative is in order here:
$
G'(t) = \lim_{h\rightarrow 0}\frac{G(t+h)-G(t)}{h}
$
And in your case, $t=1$, so you need to evaluate $G(1)$ and $G(1+h)$ for the right-end limit and $G(1-h)$ for the left-end limit of $G'(t)$ (just as you did for the continuity part).  When you evaluate
$
\lim_{h\rightarrow 0}\frac{G(t+h)-G(t)}{h}
$
you'll see that the two fractions given in the "you may assume" part will pop up and you can use those assumptions to help you with the limit.
I can clarify more if needed.


How to prevent Hamachi service stop when Remote Desktop disconnects on Windows XP?

Question: I have a Windows XP SP2 machine with Hamachi service running. Usually I connect to it using Remote Desktop, and when I disconnect I can't connect to it again because the Hamachi VPN is down. How to prevent the Hamachi service to stop?
I am sure that Hamachi is configured as an automatic service.
Answer: Apparently the free version of Hamachi requires the GUI to be running in order to operate. When you disconnect your RDP session the free version of Hamachi will disconnect. The workaround appears to be to run the following command instead of disconnecting. (Note: Number 1 below is your session ID. To know what your current session ID, in the console, run query user or open the task manager and go to users and look at your session ID)
tscon 1 /dest:console

This may need to be run as administrator. This will transfer your session back to the local machine. Also note that when the session is transfered back to the local machine it will not be locked and will be available to anyone with physical access to the machine.
Comment: Very interesting. It looks like you are right: "*So, in the hopes of converting more of you into paying customers, we're making a small change to Hamachi: unless a computer is part of a paid network, you need to be logged in and running the Hamachi UI on your desktop in order to allow it to function. If no user is logged on to the computer then – even though the Hamachi service or daemon is active in the background – it will not go online in any networks that it may belong to. We believe this a fair change...*" http://b.logme.in/2012/11/07/changes-to-hamachi-on-november-19th/
Comment: In order for this to work for me, I had to log into the console first by using `mstsc /console /V:servername` to acquire the console login. Then remoting to terminal services on the host and viewing my logins using `query user`. Then I switched to the console using `tscon 0 /dest:console` and was logged off, but the console stayed logged on. See [Single Remote Desktop Session in Server 2003](http://stackoverflow.com/a/328433/1020470).
Answer: If Hamachi is configure to run as a service, then it should not matter whether you just disconnect from the RDP sesssion, or log off, as it should be running in the background.
You should check the services MMC to see that the service is there, and that it is running.
Answer: Just add this in a .bat script:
tscon 1 /dest:console
rundll32.exe user32.dll, LockWorkStation

The first line transfers the remote session to the local desktop and the second line, locks it.
Instead of disconnecting, just run the bat script.
Comment: This is the best answer.
Answer: If you close the remote desktop session without logging off it shouldn't be an issue. If your using the microsoft rdp client just click the "X" at the top bar of the screen.
The only other thing I could think of is maybe the hamachi client is set to auto-disconnect if idle for X minutes. I'm not even sure if hamachi has that option, I've never really looked.
Comment: Have you tried logging to see what exactly is going on?

Go into Hamachi Preferences > System > Enable Diagnostic Log.

Logs are place in %APPDATA%\Hamachi (your Hamachi configuration folder) and are rotated when they reach 8MB.
Comment: I usually use the close(X) button
Comment: Hmmm the Hamachi shouldn't see a difference, the only thing that effectively happens when you close an rdp session that way is the computer locks. I would poke around the settings a bit. I don't have access to a Himachi client where I'm at.
Answer: When I stopped to close the window through the X button, and started to Disconnect, then the  problem not occurred again.
Answer: The batch script is a crude solution. The way I solved the problem is the following.
I went into policy editor>Computer Conf.>Administrative Templates>Windows Components>Remote Desktop Services>Remote Connection Host>Connections>Restrict Desktop Remote services users to a single RDP session> Disabled the rule. After that you can go to the local machine(or use any remote software like TeamViewer) log in with your credentials> and start-up Hamachi> LOCK THE ACCOUNT so it will stay logged on. Now if you log in with RDP and go to task manager>users you will see that you two users logged in. After that, you can log in\log out with RDP how many times you want it will not log off the local session and thus Hamachi will stay on.
Answer: I briefly inspected the action Hamachi is doing. From what I found there, the Hamachi service (named Hamachi2SVC, running hamachi-2.exe) seemed to actively detect the Windows logoffs and ask their server what to do; in OP's case, the server instructs the client to disconnect.
To take around this mechanism, a way is to patch the program not to check for the logoffs. For Hamachi version 18.104.22.168, changing byte 0x10122E 0x85 to 0x31 (instruction test to xor) in C:\Program Files (x86)\LogMeIn Hamachi\x64\hamachi-2.exe works as expected, though not sure about other versions.


Is there a way to conect the input/output of a console application to the output/input of another program

Question: I have an application i cannot edit that reads from the console and writes to it and i want to know how i can read what the program is saying and write back commands to the program.
This is for a minecraft server where i want to read what the players are saying and run commands acoording to what is said. (the server is the application i cannot edit)
I cannot create a modification for the server, because i am using a mod that checks if there are any other modifications done to the files and fails to load if that is the case.
Comment: It's unclear what you asking (at least for me). Do you want to write an application that interacts with the console and in this case what language do you want to use?
Comment: I want to write an application that controls an already existing application. basically, the already existing application has console i/o where it says what is happening.
I want to take what the application is saying and if specific conditions are met, send a string to the input of that application like "save current state" or "stop execution"

the programming language doesn't matter, as long as it can be used to write a program to talk with another program via the console.

basically, i want a program that can mimic human interaction in the console.
Answer:
I wrote a simple app in c# to get started with, to redirect the I/O streams you need to start the application (in this case the server) within your own application.
First we create a new instance of the System.Diagnostics.Process class
var process = new Process();

then we specify the start info
process.StartInfo = new ProcessStartInfo
{
    FileName = Console.ReadLine(), //Reads executable path from console
    RedirectStandardOutput = true,
    RedirectStandardInput = true,
    UseShellExecute = false
};

then we add an event handler, in this example it's just writes the lines with a "> " prefix
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => Console.WriteLine($"> {e.Data}");

and now we can start the process by calling Process#Start()
process.Start();

and finally we can call Process#BeginOutputReadLine() without this the OutputDataReceived event will never trigger
process.BeginOutputReadLine();

To send commands you can use the process' StandardInput stream
process.StandardInput.WriteLine("command");

The fully working code with example output (tested with cmd.exe, but it's must work with MC servers)
Code:
static void Main(string[] args)
{
    Console.Write("Enter executable path: ");
    var process = new Process();
    process.StartInfo = new ProcessStartInfo
    {
        FileName = Console.ReadLine(), //Reads executable path, for example cmd is the input
        RedirectStandardOutput = true,
        RedirectStandardInput = true,
        UseShellExecute = false
    };
    process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => Console.WriteLine($"> {e.Data}");
    process.Start();
    process.BeginOutputReadLine();

    process.StandardInput.WriteLine("echo a");

    //Prevent closing
    Console.ReadKey();
}

Output:

Enter executable path: cmd
> Microsoft Windows [Version 10.0.18362.239]
> (c) 2019 Microsoft Corporation. Minden jog fenntartva.
>
> F:\VisualStudio\StackOverflow\StackOverflow\bin\Debug\netcoreapp2.1>echo a
> a
>


Can Haar Measures Exist On Not Locally Compact Spaces?

Question: In a reading course on measure theory this semester I had the pleasure of preparing a lecture covering the existence-uniqueness of Haar measure on locally compact groups. Since the proofs (as presented in Cohn's book) depend on the local compactness already at the very start, it is obvious that the reasoning and constructions presented don't work for groups that aren't locally compact.
I wonder (for the sake of curiosity, the presentation is already over and this is not homework) if there can exist Haar measures in those cases as well. Does anyone know of any examples of such groups, where existence or uniqueness doesn't hold?
I have tried searching and thinking on my own, but I have trouble coming up with groups that aren't locally compact to begin with…
Answer: If you require that a Haar measure is also a Radon measure, then yes: a topological group carries a Haar measure if and only if it is locally compact.
See 443E in Fremlin's Measure theory Vol. 4 Topological Measure Spaces.
As for examples of groups which are not locally compact, try to show that there is no Haar measure on an infinite-dimensional Banach space.
Comment: In general, how could one do away with local compactness? You need it to ensure that compact sets do not have empty interior. Or is there a way to avoid this problem?