How to transform numbers with decimal point in numbers smaller tham 1000

Question: How to transform numbers with decimal point in numbers smaller then 1000. For example what i did in this case:
for 1.09649 i multiply by 10000, i subtract 10000 and once again i subtract 900. (1.09649 * 10000 - 10000 - 900). But if is 2.49649 i need to find another solution. Is there a way to do it with some of the Math functions? I need only the value that changes between 2 or more same numbers like 1.09649, 1.09730, 1.09689.
Comment: Um.... what are you *doing*? $1.09649\times 10000-10000 - 900=64.9$ but why is this what you *want*.  What are you trying to achieve?  You can do $2.49649 \times 10000-10000 -900 = 14064.9$ but I assume that is irrelevant to want you are trying to do. But I don't know what you *are* trying to do.  You could do $2.49649\times 10000 - 20000-4000 =964.9$.  Is that closer to what you want?
Comment: What is the purpose of the transformation?
Comment: The numbers, will draw a fine line in a Chart.
Comment: Could you give a few pairs of inputs and outputs?  I can't guess what output you intended for the input $2.49649$?  (For $1.09649$, you seem to have gotten $98749$.)
Comment: @fleablood : $1.09649 \cdot 10000 - 900 = 108749$.
Comment: @EricTowers you didn't subtract 10000. $1.09649\times 10000= 10964.9$ and $10964.9 - 10000 = 964.9$ and $964.9-900 = 64.9$
Comment: @fleablood :   How many zeroes?  Now I *want* commas in these numbers.  Why aren't there commas in these numbers?  The title promised commas...
Comment: To multiply by number length (100000, 8) and to simple divide until i obtain the preferred format?
Comment: Or with PI, cos, sin. Until 360. Converting in hundrets.
Comment: Yes here are some pairs: 1.09358* 10000 - 10000 - 900 = 35.79
1.09290* 10000 - 10000 - 900 = 29
1.09256* 10000 - 10000 - 900 = 25.6
1.09269* 10000 - 10000 - 900 = 26.9
1.09296* 10000 - 10000 - 900 = 29.59
1.09182* 10000 - 10000 - 900 = 18.20
1.09162* 10000 - 10000 - 900 = 16.20.
Comment: Well is seems like you've figured it out.  For those numbers multiplying by 10000 and then subtracting $10900$.  That works.  What is your actual question.
Comment: To do it with $2.49whatever$ we need some idea of what range of numbers you want and what range of output you want and .... you approximate.  But basically you multiply to get a good scale and then subtract to get a good offset.  The question is do you to guestimate to make the math easy.  Or do you want it perfect.
Comment: Yes, i figure it out only for one pair of numbers, i need a formula to suite all, and finding the interval between pairs is very good idea. Thank you for the answer. It sure is the correct answer for mapping the interval between two close together small scale numbers. I need to test it.
Comment: *Why* do you want to do these operations on a list of numbers? Are you trying to find an appropriate way to plot a graph of the numbers so that the relative differences between numbers are accurately shown, even if the percentage differences are very small? Because if you try to plot two numbers like $1.09730$ and $1.09740$ on a scale that starts at zero, nobody will be able to see that they are two different numbers, so you might want to "zoom in" so that only numbers between $1.09$ and $1.10$ are on the graph, or even just numbers between $1.097$ and $1.098.$
Comment: I think you should stop using the words "comma numbers." It is not standard mathematical English and is likely to fail to communicate what you mean. Try describing what you mean in standard terms. If you mean numbers between $0$ and $1,$ say "between $0$ and $1$".
Answer: I think what you are try to do is map the interval between two close together small scale numbers $a,b$ to $c$ and $d$ were $c$ and $d$ are at a more reasonable scale and offset appropriately.
For example:
If you had you want to graph the three numbers $1.09649, 1.09730, 1.09689$ but on a line only about $2000$ pixels wide so that $1.096 \mapsto 0$ and $1.098 \mapsto 2000$ and $1.09649 \mapsto 649$ and $1.09730 \mapsto 730$ and $1.09689\mapsto 689$.
So to do this you need the smallest point on your input.  Call it $a$.  (In this case $a = 1.09649$)  And the largest point in you input.  Call it $b$. (In this case $b = 1.09730$)  Then you need the smallest point in your output. Call it $c$. (In this case lets say $c=0$.) and you need the largest point of your output.  Call it $d$.  (In this case $d = 100$)
Create a scale ratio.  $R = \frac {d-c}{b-a}$.  (In this case $R = \frac {100 - 0}{1.0730- 1.09649} = \frac {100}{0.00081} \approx 123456$  [That's a weird coincidence!].  Then if you have any $x$ between $a$ and $b$ you map it to $x \mapsto (x-a)*R + c$.  In this case $x= 1.09689$ and $y = (1.09689- 1.09649)\cdot 123456 + 0 = (0.00040)\cdot 123456 = 49.3824\approx 49$.
Which intuitively should make sense as $1.09689$ is $\frac {40}{81}\approx 49\%$ of the way  between $1.09649$ and $1.09730$.
.....
Or not so labor intensive, not so stark, not such firm borders, and a little more intuitive and holistic...
If you want the numbers $1.09649, 1.09730, 1.09689$ to go from a little less than $1.09649$, say $1.09640$ to a little more than $1.09730$ so $1.09740$ so that's a difference of $0.00100$ it makes sense to make the scale $100$ and the offset $1.09640$.  So subtract $1.09640$ and multiply by a high enough power of $10$ to turn $0.001$ to $100$ (that's multiplying by $100,000$.)  To get the obvious $1.09649\mapsto 9$ and $1.09730\mapsto 90$ and $1.09689\mapsto 49$.
But that's $a = 1.09640$ and $b = 1.09740$ and $c=0$ and $d= 0$ and $R= \frac {100-0}{1.09740-1.09640} = 100,000$ and $x \mapsto (x-a)*R + c$ as above.
......
Or was your question about how to calculate powers of $10$?
Comment: Even if i find the difference between 1.09730 and 1.09740 is still a comma number. The result i will need to multiply it again with a high number to obtain a even higher number. After i do not know if is 2, 3, or 4 number long. This answer to formula '≈49' is the answer i need between 2 numbers. Because on the chart i need only the y axis to be found out and is between the first number and the following .Then i can multiply it exactly by 10 and so on. But the ratio is important.
Comment: Well, multiply it by as high a power of $10$ as you need.  What is the issue?  .... what do you mean by "comma number"?
Comment: Decimal point not comma number! Sorry about that. I try to get a good ratio out from the fractional part of this decimal numbers.
Comment: Well, .... where are you having trouble.  Just do it.  Find an appropriate scale and scale to that and subtract appropriately.  What range of numbers are you having trouble with?
Comment: I try with : a=1.32520, b=1.32523, c=1.32530, d=1.32527. Where a is the closest to the 0 on x axis of the chart. How to make a good ratio for every number so i can point it on a chart with maximum x=1000 and y=1000?
Comment: I have for example two numbers A=1.32520 and B=1.32523. How to make a good ration number from each decimal numbers so i can draw a chart line within 1000 x 1000, knowing x axis is 144.
Comment: Well the only significant difference at the last digit.  So multiply by $100000$ so ge $132520$ and $132523$.  Subtract $132520$ to get $0$ and $3$ and then multiple by, say $300$ to get $0$ and $900$.
Comment: It works perfectly fine.


Use properties of determinant and show

Question:
Let $n$ be a positive integer and
\begin{align} M =
    \begin{pmatrix}
    n! & (n+1)! & (n+2)! \\
    (n+1)! &(n+2)! & (n+3)! \\
    (n+2)! & (n+3)! & (n+4)! \\
    \end{pmatrix}
\end{align}
Use properties of determinant to show that \begin{align}\left(\frac{|M|}{(n!)^3}- 4\right)\end{align} is divisible by $n$.

I took an $n!$ factor out of the matrix, getting a new matrix $B$ such that $\det A = n^3 \det B$, since $A$ and $B$ are row equivalents. But what is $\det B$ ?
Answer: So, they're looking for the determinant of $M$.  We can make that easier to calculate by factoring a common term of $n!$ out of each row, giving us a new matrix:
$$N=\left[\begin{array}{ccc}
1 & n+1 & (n+1)(n+2)\\
n+1 & (n+1)(n+2) & \small{(n+1)(n+2)(n+3)}\\
(n+1)(n+2) & \small{(n+1)(n+2)(n+3)} & \scriptsize{(n+1)(n+2)(n+3)(n+4)}
\end{array}\right]$$
Now, $|N|=\frac{|M|}{(n!)^3}$, so we just need to find $|N|-4$.  It looks like we're about to dive into horrible polynomial multiplications.  But wait!  We only need to show that $|N|-4$ is divisible by $n$.  That means that if the constant term of the polynomial $|N|$ is 4, we're done.  We can do that by multiplying those terms out and ignoring all but the constant term"
$$\left[\begin{array}{ccc}
1 & ...+1 & ...+2\\
..+1 & ...+2 & ...+6\\
...+2 & ...+6 & ...+24
\end{array}\right]$$
Now the determinant is easy enough to calculate.  Using Sarrus' Rule, the value of this determinant is
$$(1\cdot2\cdot24) + (1\cdot6\cdot2) +(2\cdot1\cdot6)- (2\cdot2\cdot2) - (1\cdot6\cdot6) - (1\cdot1\cdot24) $$ $$ = 48+12+12-8-36-24=4$$.
Therefore, $|N|=An^6+Bn^5+Cn^4+Dn^3+En^2+Fn+4$ for some integer values of $A,B,C,D,E,F$.  We don't need to find those values, though.  The only thing that matters is that every term of $|N|-4$ contains a power of $n$, which is what we were asked to show.
Comment: how the determinant could be 4 i don't understand
Comment: That should be clearer.  The determinant of that last matrix is 4, which shows that the determinant on N is a polynomial of the form $n^6+An^5+...+Fn+4$, which proves the statement that $|N|-4$ is divisible by $n$.
Comment: don't understand yet]
Comment: How far do you get before not understanding?
Comment: I understand how to collect the scaler values of the matrix elements and but I didn't understand how you get the 4 value by them
Answer: After you take the common factor $n!$ out of all columns, take $(n+1)$ and $(n+1)(n+2)$ out of 2nd and 3rd columns, respectively:
$$\frac{|M|}{(n!)^3}=\left|\begin{array}{ccc}
1 & \color{red}{n+1} & \color{blue}{(n+1)(n+2)}\\
n+1 & (\color{red}{n+1})(n+2) & \small{\color{blue}{(n+1)(n+2)}(n+3)}\\
(n+1)(n+2) & \small{(\color{red}{n+1})(n+2)(n+3)} & \scriptsize{\color{blue}{(n+1)(n+2)}(n+3)(n+4)}
\end{array}\right|=\\
\color{red}{(n+1)}\color{blue}{(n+1)(n+2)}\left|\begin{array}{ccc}
1 & 1 & 1\\
n+1 & n+2 & \small{n+3}\\
(n+1)(n+2) & \small{(n+2)(n+3)} & \scriptsize{(n+3)(n+4)}
\end{array}\right|\stackrel{C_3-C_2\to C_3\\ C_2-C_1\to C_2}{=}\\
(n+1)^2(n+2)\left|\begin{array}{ccc}
1 & 0 & 0\\
n+1 & 1 & 1\\
(n+1)(n+2) & 2n & 2n+2
\end{array}\right|\stackrel{C_3-C_2\to C_3}=\\
(n+1)^2(n+2)\left|\begin{array}{ccc}
1 & 0 & 0\\
n+1 & 1 & 0\\
(n+1)(n+2) & 2n & \color{red}2
\end{array}\right|=\color{red}2(n+1)^2(n+2)$$
Hence:
$$\begin{align}\left(\frac{|M|}{(n!)^3}- 4\right)\end{align}=2n^3+8n^2+10n\equiv 0 \pmod{n}.$$
Comment: You are welcome. Thank you all for understanding. Good luck!

Use properties of determinant and show


Real-time processing using Kafka, Storm & HBase

Question: Apologies for my ignorance.
We are building a real-time database that captures records based on members  activity on a website. The application that emits these information is IBM MQ. We are planning to setup Apache Kafka to consume these messages from IBM MQ and store that in HBase for Analytics. Is it possible for Kafka to write this information directly into HBase OR we should a setup a real-time stream engine like Apache Storm in between Kafka & HBase? That is Kafka --> Storm --> HBase.
Appreciate your valuable feedback.
Answer: Kafka is just a publish-subscribe messaging system for real time activity. So it just receives and sends. Main features are messaging in realtime, fault tolerant and large scale data processing.
To perform actual processing, you have to depend on Storm. On one side of Strom, you take kafka output and on the other side, you can have data processing and send the data to hdfs or hbase. Its upto you. The topologies(storm jargom) run forever which is one of the main requirement for real time unlike batch processing
Answer: I dont think you need to use Kafka and Storm to write data to HBase. As per my understanding, you can write the data directly from IBM MQ consumers to HBase. HBase has java api. It also has Thrift. So, other languages like Python, Ruby, etc can also talk to HBase.


Como capturar o valor do atributo corrente com jQuery?

Question: Tenho o seguinte formulário em html:
<form>First name:

    <input type="text" name="nome">

Last name:

    <input type="text" name="sobrenome">
</form>

E o código jQuery:
    $(document).ready(function () {
    $('input').change(function()
    {
        alert($(this).attr('name'));
    });
});

Ao alterar o valor de determinado campo quero dar um alert com o nome do atributo, porém, queria fazer isso sem ter que informar a tag do seletor, ou seja, ao invés de informar o input quero que o mesmo seja obtido automaticamente com base no elemento que estou atualmente alterando. Como faço isso?
Answer: * para todos elementos.
$('*')

Caso queira fazer uma lista de elementos separe por ,:
$('input,select,textarea')

Você pode também usar o filter :
jQuery('*').filter(function(){
    var accept = [
        'input',
        'select',
        'textarea'
    ];
    var tag = jQuery(this).prop('nodeName');
    return jQuery.inArray(tag.toLowerCase(), accept);
});


Prime counts with maximal prime spacing.

Question: I think this question is related to Maier's theorem but I am unsure.
Notation: $\pi(x)$ is the prime-counting function up to $x$. $g_k := p_{k+1} - p_k$.
Define $M_n$ to be the $n$th maximal gap between primes. That is, $M_n = g_i$, where $p_i$ is the smallest prime such that $g_i > g_j$ for all $j < i$. Define $x_n := $smallest $x$ where $m_n := max(\pi(x+M_n)-\pi(x))$ for all $x$ between $p_i$ of $M_{n-1}$ to the $p_i$ of $M_n$ occurs.
In other words, using the spacing between maximal primes as a section, what is the maximum count of primes for each section? And, where is it? Does the count $m_n$ go to infinity? At what rate does it grow? Clearly, $\pi(x+M_n)-\pi(x)$ is greater than 1 up to the maximal prime where is it 1. What happens with $m_n/M_n$?
Comment: https://math.stackexchange.com/questions/2671337/bounding-maximal-gaps-with-ramanujan-primes
Answer: Does the count $m_n$ go to infinity? At what rate does it grow?
Heuristically, yes, $m_n$ goes to infinity; assuming that the Cramer and Shanks conjectures are true for almost all maximal prime gaps, we can expect that $m_n$ goes to infinity at least as fast as $\log x_n$. That's because
(i) we almost always have $M_n\sim\log^2 x_n$ by the Cramer and Shanks conjectures;
(ii) the average count of primes in the interval $[x,x+M_n]$ (for $x$ near $x_n$) is estimated by the ratio
$${M_n\over\mbox{average gap near $x_n$}}\sim {\log^2 x\over\log x}
\sim\log x \sim\log x_n;
$$
(iii) it's intuitively clear that we will almost always see $m_n$ exceeding the average count of primes in $[x,x+M_n]$ (for $x$ near $x_n$). That is,
$$
m_n > \log x_n \qquad\mbox{ for almost all } n.
$$
What happens with $m_n/M_n$?
We can expect that the ratio $m_n/M_n$ is bounded. If the ratio decreases to zero, then the decrease is surely not as fast as $1/\log x_n$. (But I would be very surprised to see a rigorous proof of this.)
Comment: Does the ratio $m_n/M_n$, if bounded, break Maier's theorem? (or at least show that it's mute.)
Comment: With (ii), you have "for almost all n" what is going on with the exceptions? I get that means $m_n \le \log x_n$, but a small count implies something with the gap size.
Comment: Under assumption that $\frac{M_{n+1}}{M_n} \le 2$, what is true? https://math.stackexchange.com/questions/831768/under-assumption-that-fracm-n1m-n-le-2-what-is-true?rq=1
Comment: I think Maier's theorem is compatible with everything in my answer. I do not think the additional assumption of $\frac{M_{n+1}}{M_n} \le 2$ changes anything in the answer. By saying "the ratio $m_n/M_n$ is bounded" I mean that there exists $C$ such that $m_n/M_n<C$.
Comment: In this answer, when I say "for almost all $n$", I actually further expect that the statement also may be plausible even "for all $n$ large enough". (The strengthening "for all $n$ large enough" just does not follow from my heuristic assumptions; e.g. we do not know how the Shanks conjecture might break, if it breaks at all -  so we simply assume that the Shanks conjecture is true for almost all maximal gaps, so $M_n\sim\log^2 x_n$ for almost all $n$.)


Neighborhoods and Metric Spaces in Real Analysis

Question: In my analysis class, we are looking at metric spaces and topologies.  We were asked to prove the following two theorems.  I believe I have the first one completed, but am somewhat confused by the second one; it seems like it should just "follow" from the first one, but I don't know how to rigorously show this:
1)  Prove that in a metric space, a set $N$ is a neighborhood of $a$ iff there exists a real number $\epsilon > 0$ such that the $B_\epsilon(a)\subset N$
2)  Prove that in a metric space, a set $N$ is a neighborhood of $a$ iff there exists a real number $\epsilon > 0$ such that $x \in N$ for any $x \in X$ such that $\rho(x,a)<\epsilon$
For #1, I have this:
Let $\epsilon\in R$ such that $\epsilon>0$ and $B_\epsilon(a)\subset N$ for some set $N$ and some point $a$.  $B_\epsilon(a)$ is an open ball contain $a$ and thus is an open set, i.e. $a\in B_\epsilon(a)$, thus by definition $N$ is a neighborhood of $a$
Now, let $N$ be a neighborhood of $a$. Then there exists an open set $U$ such that $a\in U$ and $U\subset N$.  By a previous theorem (which we proved, namely "a set is open in metric topology iff it is a union of open balls", $U$ must be a union of open balls, and thus $a$ must be contained in one of those balls, call it $B_r(z)$. Now, consider $B_{r-\rho(z-a)}$, a ball centered at $a$ with radius smaller than the distance from $a$ to $z$.  Note that $B_r(z)\subset U$ since it is in the union that forms $U$.  Thus, $B_{r-\rho(z-a)}\subset B_r(z)\subset U \subset N$.  So choose $\epsilon=r-\rho(z-a)$.  The there exists a real number $\epsilon>0$ such that $B_\epsilon(a) \subset N$.
I have no idea if it is correct, and I have no idea how to begin on #2.  The class doesn't have a textbook, and the professor posts notes but they are very blunt with only definitions and theorems (and not examples), and there are also many typos that he doesn't catch.  Any comments on my solution to #1 would be appreciated, and anything you can provide for #2 would be of immense help; we never discussed anything in class about epsilons, nor is there anything in his online notes about it either.
Comment: 2 is just a reformulation of 1. All $x$ with $\rho(x,a) < \epsilon$ is exactly the set $B_\epsilon(a)$.
Answer: The text for the analysis course I took gives the following definition of a neighborhood (or an open neighborhood - also sorry that the definition is a bit long, but this is how it is given in my text authored by a professor of the university, and I didn't want to stray from the exact text):
Definition:  Let $(X,d)$ be a metric space. We say the set $V\subset X$ is open if (and only if) for every $x\in X$ there exists a $\delta>0$ such that $B(x,\delta)\subset V$. A set $E\subset X$ is closed if (and only if) the compliment $E^{c}=X\big\backslash E$ is open. When the ambient space is not clear from context we say $V$ is open in $X$ and $E$ is closed in $X$. Furthermore, if $x\in V$ and $V$ is open, then we say that $V$ is an open neighborhood of $x$ (or sometimes just a neighborhood of $x$).
//Proof: Consider the metric space $(X,d)$ (i.e. from your work $(X,\rho)$). Supposing $N\subset X$ is a neighborhood $x$ directly implies by definition that for every $x\in N$ there exists some open ball $B(x,\delta)\subset N\subset X$ of radius $\delta>0$ around $x\in X$, and hence this direction is trivial.
Conversely, take $N\subset X$ and for $x\in N$ take an open ball $B(x, \delta')\subset N\subset X$. Now, $x\in B(x,\delta')$ trivially; moreover, we also note that $B(x,\delta')\subset N$ is an open set since for every $y\in B(x,\delta')$ there exists a $0<\widetilde{\delta}\leq\delta'$ such that $B(y,\widetilde{\delta})\subset B(x,\delta')\subset N\subset X$. Set $\widetilde{\delta}=\delta'-d(x,y)$, and take $z\in B(y,\widetilde{\delta})$. Then we have that:
$d(x,z)\leq d(x,y)+d(y,z)<d(x,y)+\widetilde{\delta}=d(x,y)+\delta'-d(x,y)=\delta'$.
So $d(x,z)<\delta'$ yielding $z\in B(x,\delta')$ for every $z\in B(y,\widetilde{\delta})$. This proves the that $B(x,\delta')$ is open. I included this since you mentioned you didn't have a textbook, etc. Returning to  the proof, when $x\in N$ we have that there is an open (set) ball $B(x,\delta')\subset N$. Taking the union of these open (sets) balls yields an open set overall, so $N$ must be open. Therefore we conclude that since $x\in N$ and $N$ is open, we have the $N$ is an (open) neighborhood of $x$. Since statement (2) is an equivalent form of the statement we proved here, i.e. (1) holds if, and only if (2) holds, we have that (2) must also be true and we are done.$~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\square$
Should you want to prove (2) independently, repeat the same procedure as the proof above, except recall the definition of an open ball in a metric space:
Definition: Let $(X,d)$ be a metric space, $x\in X$ and $\delta>0$. Then define the open ball, or simply a ball, of radius $\delta$ around $x$ as $B(x,\delta):=\big\{y\in X:d(x,y)<\delta\big\}$.
In your case treat $d(x,y)$ as $\rho(x,a)$, and proceed. Overall they are equivalent statements, so you will get very similar results. I hope this helps, as I tried to do things much more rigorously since you mentioned the lack of materials to prepare with.
Comment: By the way, where I proved that an open ball in a metric space is open, you can skip that part since any $x\in N$ implies there is a $\delta>0$ such that $B(x,\delta)\subset N$, so $N$ must be open in this case. Like I said, I figured to include more since you mentioned you didn't have much to go from. Best of luck to you.


Joining the edges of a disc in a way that prevents mirroring

Question: Imagine an object moving across a square and when it reaches an edge, it is transported to the opposite side of the square.
Now imagine the same thing, but with a disc.  When you reach the edge, you are transported to the opposite side of the disc.  In this case, the object gets flipped.
To prevent this, we could divide perimeter into many segments and transport each one without flipping, but this creates discontinuities at the segment borders.
How can we avoid flipping in a continuous way?
I have a vague idea of a solution involving hyperbolic geometry where the perimeter is divided into small segments, but as you approach those segments they get arbitrarily large.
Sorry if this is not very clear.  If someone has a clearer way of explaining it, that is welcome.  The motivation for this question was thinking about the topology of the universe.
Comment: If we replace the disk with a $2n$-gon, what you're describing sounds similar to the construction of a surface with genus $g$ by gluing (see [here](https://www.youtube.com/watch?v=G1yyfPShgqw) for an animated example of genus 2). This falls under the domain of algebraic topology to my understanding. Surfaces of infinite genus have been considered, but they can be much wilder (see for instance the [Loch Ness monster surface](https://en.wikipedia.org/wiki/Loch_Ness_monster_surface).)
Comment: A disk is homeomorphic to a square, so you could just compose this homeomorphism with the quotient map defined on the square.
Comment: Though I guess this violates the requirement of coming out of the "opposite" point in the sense of being diametrically opposed. Instead it will come out of the point that is the mirror image under a reflection across a diagonal.
Answer: How about we glue a disk to the disk itself! So, the total space would be homeomorphic to $S^2$. Moreover, within the original disk, for each point on the boundary there's a path to the antipode that doesn't flip you around. Seems like the most light-weight no-nonsense solution. I don't think $S^3$ would be an unreasonable guess at the shape of the universe, but if I recall the consensus so far is that our observable universe is pretty flat. That's outside of my comfort zone, though, so that's all I'll say about that.


Calculating the differential of the map $A \mapsto A A^T$, $A \in M(n\times n, \mathbb{R})$

Question: Let $M(n \times n, \mathbb{R})$ denote the set of $n \times n$ matrices over $\mathbb{R}$ and $S(n \times n, \mathbb{R}) \subset M(n \times n, \mathbb{R})$ the subspace of matrices that are symmetric.
Define $f: M(n \times n, \mathbb{R}) \rightarrow S(n \times n, \mathbb{R})$ by $A \mapsto A A^T$. In Hamilton's Mathematical Gauge Theory he says the differential of $f$ at a point $A \in O(n) = f^{-1}(I)$ in the direction $X \in M(n \times n, \mathbb{R})$ is
$$(D_Af)(X) = XA^T + AX^T.$$
I am familiar with the notion of differentials of maps between manifolds, but I cannot see how he obtained the above expression. I have two questions.

How did he compute the differential?
What exactly does he mean by "in the direction of $X$"? If he means identifying the differential with the directional derivative, shouldn't $X$ be a tangent vector? Or is he implicitly identifying $M(n \times n, \mathbb{R})$ with its tangent space at $A$?
Answer: Regarding your 2nd question: the tangent space of the space of matrices $M(n\times n, \mathbb R)$ at a point $A$ is, as you said, identified with $M(n\times n, \mathbb R)$ itself.
Regarding your 1st question: you may view the tangent vectors as velocities of curves $c:\mathbb R\to M(n\times n, \mathbb R)$ starting at $A$, i.e. the tangent vector $X=c'(0)$, where $c(t)\in M(n\times n,\mathbb R)$ and $c(0)=A$. Then we have
$$  D_Af(X)= \frac{d}{dt} |_{t=0} f(c(t))=\frac{d}{dt} |_{t=0} c(t)c(t)^T = c'(0)c(0)^T+c(0)c'(0)^T= XA^T+AX^T.$$
Comment: After all, it's simply Leibniz.
Comment: Yes, if you write down everything carefully, it's a simple application of the Leibniz rule. No mumbo jumbo.


Definition of the multiplication matrix of element of finite field.

Question: I've been reading this article XOR-counts and lightweight multiplication with fixed elements in binary finite fields and I came across the term Multiplication matrix and I've wondered if that's some terminology from finite fields theory I perhaps don't know (English is not my native language and I don't study math in English). It seems really odd that the author mentions the term in an abstract and doesn't define it properly (but then maybe it's just a widely used term).
From what I've understood multiplication matrix is matrix such that: $\forall \alpha \in \mathbb{F}_{2^n} \exists A \in \mathbb{F}_2$ such that $\forall x \in \mathbb{F}_{2^n}: \alpha \cdot x = A \cdot \hat{x}$, where $\hat{x}$ is element $x$ written as an n-dimensional vector over $\mathbb{F}_2$.
Thank you for any help.
Answer: Multiplication by an element of $\mathbb F_{2^n}$ on elements of $\mathbb F_{2^n}$ produces a $\mathbb F_2$ linear transformation on $\mathbb F_{2^n}$. As such, you can pick a basis of $\mathbb F_{2^n}$ (necessarily having $n$ elements) and find a transformation matrix (an element of $M_n(\mathbb F_2)$) for each element.
Then the explanation in the paper is quite clear (p 286, the second page of the pdf):

Our goal in this work is to explore some connections and properties of the direct and sequential XOR-count metrics and then to apply these to get some theoretical results regarding optimal implementations of matrices that represent multiplication with a fixed field element $α ∈ \mathbb F_{2^k}$. Optimal choices of these matrices (called multiplication matrices) can then be used for local optimizations of matrices over $\mathbb F_{2^k}$.

As mentioned in the paper in several places, they are optimizing to minimize the number of XOR operations required to perform multiplication.
Comment: Could you please describe a way to finding such a transformation matrix? I realize that when I pick a basis $B$, the element $\alpha x$ has only one way of being written in this basis. I just can't think of a way to get matrix $A$ from $x$ and $\alpha x$. I can even think of a general example where multiple matrices that fulfill these criteria exist. Does $B^{-1}AB$ change with basis? By my geometrical intuition, it shouldn't, since linear transformation just a rotation of vector space. But I guess that might be the goal of this article: to find in which basis has $[A]_B$ the lowest XOR-count.
Comment: @kytka it is too complicated to write in a comment, and it sounds anyway like you need to struggle through the details yourself.  It is a simple thing, except if you have not really understood how a matrix represents a transformation in terms of a particular basis.  I would advise you to construct the field of four elements, then choose a basis over the field of two elements, then pick an element that is not 0 or 1, and work out what its matrix is.


Where is views exposed form's submit handler located?

Question: When views exposed form is submitted without ajax it redirects to somepage like http://example.com/reports?taxonomy=tid&date=27%20F6%20f2005 etc.
I am curious to know ,in views module,inc file where it's submit handler is located,where is ajax callback?
I tried for some hours but no luck.
I know about hooks like form alter but that's not a concern.
I have no specific requirements,just for drupal learning :)
Answer: All of its functions are handled in programmatic way. You can look all functions are declared in theme.inc file located at module/views/theme/theme.inc location. Its hard to understand that core functions. But if you want to play with these functions then you will have to use the hooks .
NOTE: Never try to change any core file.
Comment: No,I don want to hack ,just for knowledge:)
Answer: You can hook in to the form and see submit handlers and which form elements have ajax callbacks by debugging the form.
kpr() is a function available when you have installed the Devel module.
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  kpr($form);
}

You will need to put the function above in a custom module.
Comment: How can I make that url user friendly after submitting the exposed form inside alter hook you suggested?
Comment: See this answer http://drupal.stackexchange.com/questions/22989/changing-url-of-exposed-filter


EAP-TLS: is it possible eavesdropping when sharing client certificate?

Question: I want to know how to share a network of WPA2 enterprise with EAP-TLS,  authenticating users with  a common certificate. They share the same certificate.
I'm afraid they can monitor each other. Is that possible?
In EAP-TLS, do clients encrypt their packets with their own certificates or other session keys or else? Actually, the packets in WPA2 are all encrypted, but how?
Answer:
I'm afraid they can monitor each other. Is that possible?

yes, it is possible. Clients use their certificate to protect session key. Therefore, if clients share the same certificate with the same private key -- they can intercept and decrypt the session key and, eventually, all encrypted data.

In EAP-TLS, do clients encrypt their packets with their own certificates or other session keys or else?

packets are encrypted by a session key which is shared between client and server. After peers successfully authenticate each other, a session key is generated. Generated session key is encrypted by a peer's public key. That is, when server encrypts something with client's public key, only corresponding private key holder can decrypt it. In your case, all certificate holders will be able to decrypt it.
As the result, sharing the same certificate and private key among clients isn't a very good idea.
Comment: Thanks. It comes very clear. That's why the public Wi-Fi doesn't use EAP-TLS.


Cannot deserialize instance of 'java.util.date' out of START_OBJECT token

Question: Invalid JSON input: Cannot deserialize instance of java.util.Date out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of ``java.util.Date` out of START_OBJECT token
I am trying to set the default date picker to show pacific time in REACT using functional Component. useState()
REACT
const [startDate, setStartDate] = useState(new Date());
return(<TextField
         id="datetime-local-startTime"
         type="datetime-local"
         defaultValue={startDate}
         className={classes.textField}
         onChange={setDefaultStartDate(startDate)}
       />)
const setDefaultStartDate = (date) => {
        date.setHours(date.getHours() - 8);
        setStartDate(date.toISOString().substr(0, 16))
        return date.toISOString().substr(0, 16);
    }

JAVA
@JsonProperty("startDate")
private Date startDate;

@JsonProperty("endDate")
private Date endDate;`

Comment: Please share how you are parsing this and possibly more information. Whatever you've parsing, you have sent a json object but you're looking for a date or something.
Comment: Json object with date field
Comment: React component is materialui component datetime
Comment: Can you send the json that is received by the api?
Comment: It's trying to send json to api...I m getting error msg on start date rather then an object
Answer: What is happening here is that the react date is not a string but a complex object. When you send that object up as part of the request, Jackson is expecting to find a the same class definition on the server side to deserialize into. In other words, react date class != java date class. You either need to define a custom jackson Deserializer for this date on the Java side, or convert the react date into a simple string that can be deserialized by Jackson.


how to find log base 2 of decimal number without calculator

Question: As with calculator things are simple but I don't know how to calculate log base 2 of decimal number without calculator. like $\log_2(0.25)$ etc.
Comment: Try rewriting .25 as 2 to some power.
Comment: This may be a duplicate of the question [How to figure out the log of a number without a calculator](http://math.stackexchange.com/q/135368/253804), which was answered with several practical methods. Of course remember that the $\log_{a}(x)$ can be converted to $\log_{2}(x)$ by dividing by $\log_{a}$(2).
Answer: Logarithms are easier to calculate if you can write your input as a power of the base. In this case, $\log_2(0.25) = \log_2(\frac{1}{4}) = \log_2(2^{-2}) = -2$.
In general, $\log_a(a^k) = k$. So writing the input as a power of your base gives you the easiest way to evaluate a logarithm. If the input and base aren't related by a nice power relationship, you may have to relate them to known values or use a calculator.
Answer: Regarding $\log_a(x)$ if $x \in (0, 1) $ you can just multiply $x$ by $a$. The amount of times you can do so without going over $1$ is the $\lfloor \log_a(x) \rfloor$.
Same with $x > 1$ except you divide by $a$ instead without going below $1$.


Hashing password while registering new user in Symfony

Question: I have a problem registering new users to my User database. I want to hash the password while submitting the form. I am not exactly sure how to do it and I'm new to this. I need help guys. My code:
<code><?php

namespace App\Controller;

use App\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class UserController extends AbstractController
{
    /**
     * @Route("/users", name="signingUP")
     */
    public function new(Request $request)
    {
        $user = new User();

        $form = $this->createFormBuilder($user)
            ->add('userName', TextType::class, array('label' => 'Username'))
            ->add('fullName', TextType::class, array('label' => 'Fullname'))
            ->add('email', EmailType::class, array('label' => 'Email'))
            ->add('password', PasswordType::class, array('label' => 'Password'))
            ->add('save', SubmitType::class, array('label' => 'Submit'))
            ->getForm();

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $user = $form->getData();

            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            $entityManager->flush();

            return $this->render('index.html.twig', array('data' => 'Added to database'));
        }

        return $this->render('users/signUp.html.twig', array('form' => $form->createView()));
    }
}
</code>
It adds everything else just the way I want it but cant do with the password
Comment: It is a bit interesting that the link @yivi provided was for an old non-supported version of Symfony (4.1).  It does indeed show how to correctly hash a password.  But newer versions of the link basically point to an almost empty big picture sort of page which essentially says to figure it out yourself.  The closest actual example in the current docs I could find is in the [fixtures section](https://symfony.com/doc/master/security.html#c-encoding-passwords).  There are of course many almost duplicate Stack Overflow questions which might also be worth searching for.
Comment: https://symfony.com/doc/4.1/doctrine/registration_form.html
Answer: Simple pass UserPasswordEncoderInterface to your controller and encode the password
<code> public function new(Request $request, UserPasswordEncoderInterface $encoder){
        //$user = new User(); <- this is not necessary as long as you set data_class in form to your User class.

        $form = $this->createForm(RegisterType::class); // Move your register form to a RegisterType in Form namespace (less mess in your controllers)

        $form->handleRequest($request);

        if($form->isSubmitted() && $form->isValid()){
            $user = $form->getData();
            $user->setPassword($encoder->encodePassword($user, $user->getPlainPassword);
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            $entityManager->flush();

            return $this->render('index.html.twig', array('data'=>'Added to database'));
        }
        return $this->render('users/signUp.html.twig', array('form'=>$form->createView()));
    }
</code>
Also make sure you have an encoder specified in security.yml, although it should be set to auto already.
<code># config/packages/security.yaml
security:
    # ...

    encoders:
        App\Entity\User: 'auto'
</code>


Eclipse/Java not stopping on exception, not showing stacktrace

Question: For some reason, Eclipse for Java stopped showing the stacktrace on exceptions nor is Eclipse stopping on exceptions while in debug. I installed (not upgrade) the latest Eclipse 2023-03 (4.27.0) and referenced the workspace and projects in the hopes that would solve the issue, but Eclipse is still blissfully moving past exceptions.
I have a breakpoint set for Throwable (caught and uncaught), and I also have the debug option set to  suspend execution on uncaught exceptions. Regardless, the exception is caught with my catch statement without suspending execution, and the printStackTrace command does nothing that I can see. There is no output to the console. The showMessageDialog statement does work and displays my failure during initialization message.
If I comment out the try/catch so that the exception is uncaught, then the program appears to terminate immediately without any messages from either me or the system.
Any thoughts on what is happening here?
Below is my tray/catch, and the exception is somewhere in the initializeEX() statement:
    try {
        initializeEX();   // the error is somewhere in here...
    } catch(Exception e) {
        e.printStackTrace();
        msg = "Failure during console initialization.";
        JOptionPane.showMessageDialog(frame, msg, "Cannot load AssetAllocation", JOptionPane.ERROR_MESSAGE);
    }

Thanks for any input.
Comment: If you want the debugger to stop, you need to set a breakpoint on the line you want execution to pause at. While uncaught exceptions will crash the JVM, caught exceptions by definition do not, because you caught them and dealt with them.
Comment: Have you tried adding the exception.toString() in the error dialog? You also should post the initializeEX() code.
Comment: Print the exception, message and stacktrace to the pane and copy the text to your question.
Comment: You are catching all Exceptions. Is anything throwing Throwable by name? Have you tried setting a breakpoint in your `catch` block?
Comment: daniu, aled, Mike & nitind - thanks for the input. I can't post the code because initializeEX() is a top-level method with many subroutines and thousands of lines of code. Nor can I give you any details on the exception because I haven't found it yet. The catch block around initializeEX is a catch-all fail-safe in the event I didn't gracefully catch something farther down.
Comment: @daniu, thanks for the suggestion and toString does give me the error description. I still need to solve this problem. e.printStackTrace used to work and now it doesn't. I don't know what changed but I need the debuging functionality to show the full stackTrace and to pause execution on exceptions.
Answer: Since you managed to get the exception description in the dialog, you can also get the stash trace there.
Create a ByteArrayOutputStream, then a PrintWriter from it. Then give that to the printException() method.
try {
  initializeEX();
} catch (Exception x) {
  try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      PrintStream errorOut = new PrintStream(byteArrayOutputStream)) {
    x.printStackTrace(errorOut);
    msg = byteArrayOutputStream.toString();
    // joptionpane
 }
}

As for why the stask trace isn't printed as is, I assume the standard error stream is changed along the execution (System.setError(someStream)).
Comment: Any thoughts on why the breakpoints aren't working?


Acessar /index.php como /index (sem o ".php")

Question: Utilizando expressões regulares, consigo verificar páginas index.html como index mas não paginas index.php como index.
Meu .htaccess.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /login.php [L]
RewriteRule ^index$ index.html [NC,L]
</IfModule>

Dentro do meu apache, no endereço /etc/apache2/sites-available, tenho o virtual host padrão e tenho o virtual host esms.com com o seguinte conteúdo:
<VirtualHost *:80>
    ServerAdmin email@example.com
    DocumentRoot "/var/www/html/meus_projetos/E-SMS-DEVEL"
    ServerName www.esms.com
    ServerAlias esms.com
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

AllowOverride All

    <Directory /var/www/html/meus_projetos/E-SMS-DEVEL>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
    </Directory>
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

Baseando nessas informações, gostaria de ajuda para entender o que estou fazendo de errado.
Comment: Bom dia, a resposta resolveu o seu problema?
Answer: Não seria só trocar o .html por .php:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /login.php [L]
RewriteRule ^index$ index.php [NC,L]

Ou pode tentar fazer isto que serviria pra qualquer arquivo php:
RewriteRule ^([a-z0-9]+)$ $1.php [NC,L]

Você pode também tentar usar o mod_negotiation


Fundamental group of two spheres in a cylinder

Question: Hi I'm a little bit stuck on this problem

Let $$S_1 =\{ (x,y,z) \in \mathbb{R}^3: x^2+(y-1)^2+z^2=1\}\\S_2 =\{ (x,y,z) \in \mathbb{R}^3: x^2+(y+1)^2+z^2=1\}$$
consider also
$$C=\{(x,y,z)\in \mathbb{R}^3: x^2+y^2 = 4, z\in [-2,2]\}$$
and union of upper and lower cylinder's basis $$B =\{(x,y,z)\in \mathbb{R}^3: x^2+y^2 \leq 4, z =-2,z= 2\}$$ Calculate the fundamental group $\pi_1(S_1\cup S_2\cup B\cup C, p)$ where $P=(0,2,0)$

I represent everything on the cartesian plane and it's a cylinder of radius $2$ and two radius $1$ spheres touching in the origin and tangent to $C$. I've tried SVK theorem but I could not say anything useful, even though I have a feeling that this group is isomorphic to $\mathbb{Z}$. Here's why I think that (sorry for the poor drawing)

I think that every loop that goes only on the cylinder like $\alpha$ are homotopic to the constant loop, the same holds for all the loops that goes on the spheres and come back to $P$ whitout going on the cylinder. So I think the only loop that is important is $\delta$ the yellow one going on the spheres and cylinder. I honestly don't know if what I'm saying make sense and I still don't know how to calculate this fundamental group. Thanks for the help.
Comment: If the discs are included, then yes, I agree that loops like $\alpha$ are null-homotopic. I also agree that it seems plausible in that case that the group is $\mathbb{Z}$.
Comment: Does the cylinder include the discs on the top and bottom? From the parametric equations you've given, I don't think it does. Therefore, I don't think a loop like $\alpha$ is possible (although it may just be me failing to interpret the drawing properly), and I don't think the answer to whether or not any loops only on the cylinder are necessarily null-homotopic is immediate.
Comment: @legionwhale thank you, I will edit the post the cylinder includes also the two basis. Btw do you think (cylinder basis included) is not so simple to conclude that the loop is null-homotopic?
Comment: @legionwhale Ok and if we substitute the cylinder with a sphere or a square is irrelevant (homotopically speaking)? I don't know If I'm explaining myself clearly
Answer: Your guess that the fundamental group is $\mathbb{Z}$ is correct. Here is a way to see that your space is homotopy equivalent to a wedge product of a circle and three spheres, which shows the fundamental group is $\pi_1(S^1)*\pi_1(S^2)*\pi_1(S^2)*\pi_1(S^2)=\mathbb{Z}*1*1*1=\mathbb{Z}$:

I hope it is clear that the last space is indeed equivalent to a wedge product of a circle and three spheres.
Comment: @TurquoiseTilt $1 \to 2$ makes use of the fact that spaces are homotopy equivalent if they are strong deformation retracts of the same space. Therefore, as you observe, replacing a point with a contractible space has no effect modulo homotopy equivalence.
Comment: @TurquoiseTilt I believe that's correct. The proof I saw that, for instance, the wedge product of $n$ circles has fundamental group the free group on $n$ letters was nothing other than handwaving, so I'm not sure if there is a more rigorous proof, but your reasoning should be sufficient for most purposes, at least.
Comment: So I should remember that every time I have shapes attached I can substitute the attachment point with a contractible space, like a segment in this case. In conclusion the fundamental group of the wedge product is $\mathbb{Z}$ because spheres are tre trivial group and remains the circle, right?
Comment: @legionwhale Thanks, and what about my last comment above do you have any thoughts on that?


Copiando registro da tabela nela mesma via vba

Question: Dá pra copiar um registro de uma tabela e inserir nela mesma?
Eu queria copiar um registro num novo na mesma tabela.
INSERT INTO Produtos ( Produto, Preco )
SELECT Produtos.Produto, Produtos.Preco
FROM Produtos
WHERE (((Produtos.Produto)="AN001"));

Comment: Estou tentando entender o que está acontecendo com essa pergunta em http://meta.br.stackoverflow.com/questions/533/o-que-esta-acontecendo-com-uma-pergunta-ja-resolvida
Comment: Não edites a pergunta para aplicar a resposta... Sugiro que alteres a pergunta de forma a que fique com o código necessário para se notar o erro que descobriste e posteriormente a isso, colocas uma resposta dando conta da solução, marcando a mesma como a resposta correcta, fechando assim este assunto. :)
Comment: @RegisdaSilva Estamos tentando reabrir a pergunta, aí então você poderá postar uma resposta. Se você preferir, pode também simplesmente excluir a pergunta (i.e. se você achar que não tem muita utilidade manter a pergunta no site; mas não estou dizendo que é isso que precisa ser feito - a decisão é só sua!)
Comment: Olá! Por curiosidade, você tentou executar já isto, e qual foi o resultado? alguma mensagem de erro ?
Comment: Esse código retorna algum erro?
Comment: Regis, não edite o título para "Resolvido". Poste a sua solução e marque-a como certa.
Comment: Se você está tendo dificuldades com isso, talvez seja porque está duplicando a *Primary Key*. Geralmente as ferramentas SQL permitem esse tipo de código, mas isso só funcionaria na forma da pergunta se você tiver um código (ID) com *auto incremento*.
Comment: @utluiz eu ia comentar sobre chaves, mas achei melhor esperar uma mudança na pergunta (mais detalhes: funcionou ou não? com qual erro?) para depois dar uma resposta. Tenho quase certeza que o seu comentário é a resposta para a pergunta
Comment: Deverias adicionar uma resposta, em vez de alterar a pergunta.
Comment: Não consigo postar uma resposta para mim mesmo, mas como afirmei. Já foi resolvido, e a resposta correta encontra-se logo na sequencia.
Answer:
Resposta originalmente postada pelo autor da pergunta, na própria pergunta

Foi só um erro de sintaxe, segue o código correto:
sql = "INSERT INTO Produtos ( Produto, Preco )" _
    & " SELECT '" & Me.CodProduto & "', Preco" _
    & " FROM Produtos" _
    & " WHERE Produto='" & Me.ListaProduto & "';"


always have issues with htaccess

Question: I am trying to short out one issue with my htaccess.
<code>   RewriteBase /
   RewriteRule ^(.+)/$ /$1 [R=301,L]
   RewriteRule ^profile/(.*)$ details.php?profile=$1 [L,NC,QSA]
   RewriteRule ^industry/(.*)$ category.php?industry=$1 [L,NC,QSA]

   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^index.php$ /index.php [L,NC]
</code>
it work fine as long as there is profile or industry match.. but now what i want to achieve is when above no rule matches then it should redirect user to home page (www.example.com). what is happening is it redirect me to index.php but the problem is on browser it still shows (www.example.com/skfjsf/sfjsfk) i want to change it to (www.example.com)
Answer: Try:
<code>RewriteRule ^index.php$ /index.php [r=301,nc]

//instead of

RewriteRule ^index.php$ /index.php [L,NC]
</code>
Comment: thank you for answering PolCPP but unfortunetly when i type in browser  something like http://www.example.com/pfdsjfage/dgsd  it redirect to index.php but on browser window still it shows http://www.example.com/pfdsjfage/dgsd  i would like to display it something like http://www.example.com/index.php or http://www.example.com/
Comment: yes i got it...     RewriteRule . /index.php [R=301,L]  thank you
Comment: Ah, dang typos. No problem :) htaccess is annoying

always have issues with htaccess


Find $a,b,c,d,e$ such that $\frac{s}a+1,\frac{s}b+1,\frac{s}c+1,\frac{s}d+1,\frac{s}e+1$ are all perfect squares $ (s=abcde)$

Question: Are there five distinct positive integers $a,b,c,d,e$ such that $\dfrac{s}a+1,\dfrac{s}b+1,\dfrac{s}c+1,\dfrac{s}d+1,\dfrac{s}e+1$ are all perfect squares ? $ (s=abcde)$
If $a=1,b=2,c=12,d=2380,s=abcd=57120,$ then $\dfrac{s}a+1,\dfrac{s}b+1,\dfrac{s}c+1,\dfrac{s}d+1$ are all perfect squares. But the case of  five numbers is more difficult than four numbers.
Comment: I don't know if it helps, but $(3/35,7/3,5,24,35)$ is such a set of rationals.
Comment: There exist much smaller $(a,b,c,d)$:
$(1, 5, 7, 24)$,
$(2, 4, 15, 28)$,
$(4, 7, 8, 30)$, ... But I still can't find any $(a,b,c,d,e)$.
Comment: For what values of $a, b, c, d, e$ have you been looking for counterexamples?
Comment: Does the "perfect square" mnean the square of an integer?
Comment: @Boris Novikov Yes, actually.
Comment: I have changed the formatting of the title so as to
[make it take up less vertical space](https://math.meta.stackexchange.com/a/9686/290189) --
this is a policy to ensure that the scarce space on the main
page is distributed evenly over the questions.
See [here](https://math.meta.stackexchange.com/a/9730)
for more information. Please take this into consideration for future
questions. Thanks in advance.
Answer: Small contribution: if you drop the requirement that $e$ must be distinct from $a,b,c,d$ (but leave the rest the same), then the only tuples that I could find by brute force with $1+abcd\leq (2\times10^4)^2$ and some fairly large limit on $e$ are
$$
\begin{array}{ccc}
\{2,6,12,35,2\},
&\{1,2,12,1190,2\},
&\{2,4,68,105,2\},
\\\{2,10,87,156,2\},
&\{2,22,86,195,2\},
&\{2,23,90,204,2\},
\\\{2,6,247,330,2\},
&\{2,30,99,238,2\},
&\{2,58,129,360,2\},
\\\{2,52,161,396,2\},
&\{2,10,714,893,2\},
&\{2,35,1518,2014,2\},
\\\{2,12,3185,3588,2\}.
\end{array}
$$
Naturally, this doesn't answer your question.
Answer: Denote
$bcde+1=A^2$, $\quad$
$acde+1=B^2$, $\quad$
$abde+1=C^2$, $\quad$
$abce+1=D^2$, $\quad$
$abcd+1=E^2$.
If $a<b<c<d<e$, then $A>B>C>D>E$.
My search was unsuccessful. I found only few "semi-solutions" (where $A,B,C$ are integer, but $D$ or $E$ isn't): here they are:
\begin{array}{|rrrrr|rrrrr|}
\hline
a & b & c & d & e & A & B & C & D & E \\
\hline
1 & 3 & 6 & 14 & 20 &    71 & 41 & 29 & 19 & \color{#CC3300}{(15.90...)} \\
1 & 2 & 12 & 34 & 70 &    239 & 169 & 69 & 41 & \color{#CC3300}{(28.58...)} \\
1 & 2 & 12 & 35 & 68 &    239 & 169 & 69 & \color{#CC3300}{(40.41...)} & 29 \\
2 & 6 & 11 & 14 & 76 &    265 & 153 & 113 & \color{#CC3300}{(100.16...)} & 43 \\
2 & 4 & 87 & 308 & 615 &   8119 & 5741 & 1231 & \color{#CC3300}{(654.24...)} & 463 \\
11 & 34 & 39 & 140 & 464 &   9281 & 5279 & 4929 & \color{#CC3300}{(2601.51...)} & 1429 \\
23 & 82 & 360 & 462 & 494 &  82081 & 43471 & 20747 & \color{#CC3300}{(18314.09...)} & 17711 \\
11 & 28 & 195 & 792 & 4978 &   146719 & 91961 & 34847 & 17291 & \color{#CC3300}{(6896.92...)} \\
4 & 182 & 395 & 957 & 2968 &  451879 & 66991 & 45473 & \color{#CC3300}{(29214.34...)} & 16589 \\
7 & 470 & 912 & 2669 & 154548 &  13296959 & 1622753 & 1164941 & \color{#CC3300}{(680968.56...)} & 89489 \\
2 & 385 & 403 & 1836 & 23240614 & 81366011 & 5864455 & 5731991 & \color{#CC3300}{(2685478.52...)} & 23869
\end{array}
And I have a doubt if solutions exist (at all) ...

Skeleton of search algorithm can be as follow:
Denote $M = cde$.
First, we need to find such triples $(a,b,M)$, that:
$a\cdot M +1 = B^2$,
$b\cdot M +1 = A^2$.
It is more convenient to talk about triples $(a,b,A)$ (where $A$ is the greatest square base).
To avoid brute-forcing, we observe that
for many pairs $(a,b)$ there exist sequence $\{A_n \}$ (and, of course, $\{B_n\}, \{M_n\}$).
And it is not hard to build/construct such sequence (for some reasonable limit), because exists a recurrence.

For example, consider $(a,b)=(1,10)$:
\begin{array}{|c|rrrrrrrrr}
\hline
n &  1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9\\
\hline
A_n & 9 & 41 & 79 & 351 & 1559 & 3001 & 13329 & 59201 & 113959 \\
\hline
B_n & 3 & 13 & 25 & 111 & 493 & 949 & 4215 & 18721 & 36037 \\
\hline
M_n & 8 & 168 & 624 & 12320 & 243048 & 900600 & 17766224 & 350475840 & 1298665368 \\
\hline
\end{array}
We observe, that (here step is $3$):
$$
A_{n+3} = 38 \cdot A_{n} - A_{n-3}, \qquad \qquad (n>3).\tag{1}
$$
Yes, $3001 = 38 \cdot 79 - 1, 13329 = 38 \cdot 351 - 9, \ldots.$
Each pair $(a,b)$ has its own step, and its own multiplier near $A_n$.
A little bit more: we can define $A_0 = - A_{1}, A_{-1}=-A_2, A_{-2} = -A_3, \ldots$. Then formula $(1)$ will be true for any $n\in \mathbb{Z}$.

So, method is:

considering different pairs $(a,b)$, find first terms of sequence $\{A_n \}$
construct other terms (using recurrence, not bruting)
for each triple $(a,b,A_n)$ consider all divisors of $A_n (c<d<e)$, and check them ...


Breaking chocolate problem and Euler characteristic.

Question: There is the following Problem:

Given an $m \times n$ chocolate bar, where you can only break it along the gridlines and only break one piece at the time. What is the minimum amout of steps needed to break it into $1\times1$ pieces?
Answer: You always need $m \times n -1$ Steps.

Now, my gut is telling me that this is related to the Euler characteristic. If that is the case, where can i find more information as to why/how that is the case?
P.S. This is not a homework problem, just a question about the more general principles and ways of seeing it.
Comment: Each piece is contractible, so the chocolate bar $X$ has $\chi(X) = \dim H_0(X, \mathbb{Q}) = \#\{\text{pieces the bar has been broken into}\}$ at each point in the process. But that's really just an overcomplicated way of saying that the piece count increases by $1$ at each step.
Comment: Same problem [here](https://math.stackexchange.com/q/2897007/305862).
Comment: Figure out the answer for a $2 \times3$ piece and then a $3 \times 4$ piece.
Comment: I proved the answer without the Euler char. But my question is specificaly related to it. (This is not a homework problem, just a question about the more general principles.
Comment: do you know the interpretation of Euler Characteristic in terms of homology (esp of simplicial complexes, with $\mathbb F_2$ coefficients)?
Comment: @user8675309 I'll say no. Because i never really took the time to understand them. But i have the required knowledge in order to be able to understand.
Answer: I like your thought, there is indeed a (very simple) Euler characteristic description, although I think it turns out to be a little disappointing because it's really not much different than the "square counting" solution that is linked in the comments.
But here goes anyway.
From the assumption given, each "break" is carried out on a single piece, breaking that piece along a "fault line" which follows the grid. Let's examine how the numbers of faces, edges, and vertices change from "before" the break to "after" the break.
The number of faces is the the same before and after the break (namely $m \times n$).
Before the break, assume that the fault line has $k$ edges, it therefore also has $k+1$ vertices. After the break, each of those $k$ edges and $k+1$ vertices along the fault line has doubled, producing $2k$ edges and $2k+2$ vertices.
The numbers of vertices and edges not along the fault line is the same before and after the break.
The net change in the Euler characteristic is therefore
\begin{align*}
\chi_{\text{after}} - \chi_{\text{before}} &= (\text{vertices after} - \text{vertices before}) - (\text{edges after} - \text{edges before}) \\
  &= ((2k+2)-(k+1)) - (2k - k) \\
  &= 1
\end{align*}
That is to say: after each break, the Euler characteristic has increased by $1$. Since the Euler characteristic started at $1$ and ended at $m \times n$, there are $m \times n - 1$ breaks.
Comment: Cutting along circles does preserve Euler characteristic, as your comment suggests. However, what you cut along matters. Cutting along arcs increases Euler characteristic by $1$, as my argument shows.
Comment: Since this is the best you found, but you were disappointed. May I ask what thought/(direction you mind pointed towards) made my thought interesting?
Comment: It is interesting to me that my intuition was pointing towards some quantities being preserved, whereas you did the exact opposite. I guess my intuition went along the lines of: the number of steps is constant since the Characteristic of the pieces remained unchanged at all times. I am writing as i am thinking, but to illustrate the thought, the number of steps needed to cut an annulus into n-annuluses is invariant.
Comment: Interesting because I like little Euler characteristic arguments!
Comment: Yes, but it is not what I meant with my comment. I meant that the new piece that is created by breaking has the same caracteristic as the piece from which it was created. But it seems that i am kind of moving away from the original question and more towards asking wether or not/under what circumstances you can cover something with stuff of another characteristic.


discrete distribution sampling error

Question: Let's say all people on earth can be divided in five categories depending on their favorite fruit or vegetable (so discrete probability distribution) and we know the true distribution.
For example 2% like apples the most, 30% like bananas the most, 40% like cherries, 20% like dates and 8% like eggplants.
I have surveyed $N$ people and measured that there's $x_a$ of them like apples, $x_b$ like bananas and so on with $x_{c},x_d$ and $x_e$.
How do I compute the probability of obtaining such set of measurements, given that I know the global distribution?
[This is not a textbook question, I just rephrased my real world problem as fruit and veggies, to save on domain-specific terminology.]
Answer: If $N \ll M,$ where $M$ is the total number of people in the world, then you simply use the Multinomial Distribution as a perfectly valid approximation. (The assumption here is that the probability distribution doesn't change as you draw samples. It isn't exact because when you draw a sample, there is one less member of that group in the remaining population, so the probability distribution changes slightly.)
On the other hand, if $N$ and $M$ are of comparable size (which, I know, is extremely unrealistic if we're talking about surveys, but let's pretend it could be for the sake of completion) then you simply want to solve a combinatorics problem. Suppose there are $K$ groups, and $x_j$ is the number of members sampled from group $j$ where $j = 1, \dots, K.$ Also, let $M_j$ be the number of people in the world in group $j$, so that $\sum_{j=1}^K M_j = M,$ where $M$ is the number of people in the world. Then, if our observation is ${\bf x} = \{x_1, x_2, \dots, x_K\},$ with $\sum_j x_j = N,$ the number of possible ways to have gotten such an observation, assuming each individual in the world has an equal chance of being selected, is,
$$
n({\bf x}) = \prod_{j=1}^K {M_j \choose x_j}.
$$
The number of possible choices of any subgroup of $N$ people is simply
$$
{M \choose N}.
$$
Thus the exact probability of observing the outcomes given by $\bf x$ is
$$
P({\bf x}) = \frac{\prod_{j=1}^K {M_j \choose x_j} } {M \choose N}.
$$
This is the multivariate hypergeometric distribution. (Thanks @Glen_b for suggesting I include the name.)
Usually this won't be tractable to calculate for large values of $M$ and $N,$ so approximate factorial calculations (such as the Stirling approximation) should be used. However, suppose we take the original assumption that $N \ll M.$ Let's further assume that this is true for each subgroup of the population, i.e. $x_j \ll M_j \hspace{1mm} \forall j.$ Then,
$$
{M_j \choose x_j} = \frac{M_j!}{x_j! (M_j - x_j)!} \approx \frac{M_j^{x_j}}{x_j!},
$$
and similarly,
$$
{M \choose N} \approx \frac{M^N}{N!}.
$$
So
$$
P({\bf x}) \approx \frac{N!}{\prod_j x_j!} \prod_j \left(\frac{M_j}{M}\right)^{x_j} = \frac{N!}{\prod_j x_j!} \prod_j q_j^{x_j}
$$
where $q_j = M_j/M$ is the probability of selecting a member of group $j.$ Thus we have shown that the exact answer reduces to the approximate answer that I suggested at the beginning, i.e. the Multinomial distribution, when the sample size of each subgroup of the population is much smaller than the true size of each subgroup.
Comment: It might be worth noting the name of the distribution you discuss in the later part (the multivariate hypergeometric).

discrete distribution sampling error


Decomposability of Inf. Entropy applied to corpus statistics

Question: Can you help me understand the additivity property of IE?  I think I may have found a violation but it may be that I'm just misunderstanding the maths. I'm attempting to achieve a meaningful understanding of information entropy and compression by studying the first 9 chapters of MacKay's book, Information Theory Inference & Algorithms. (You can get the free book here. I highly recommend it)
In Chapter 4 Mackay introduces the additivity property of Shannon Information for two independent random variables $x$ and $y$:

$H(x, y) = log_{2}\frac{1}{P(x,y)} = log_{2}\frac{1}{P(x)P(y)} = log_2\frac{1}{P(x)} + log_2\frac{1}{P(y)}$

In general we can write,

$H(X, Y) = H(X) + H(Y)$

This is pretty straightforward since the joint probability of two events is:

$P(x,y) = P(x|y)P(y)$

Where two events are independent if:

$P(x|y) = P(x,y)P(y) = P(x)$

So we write the joint probability as:

$P(x,y) = P(x)P(Y)$

However I found this property did not hold when I tried to work out one of the numerical examples he included in his text.  It also did not hold on an artificial language I randomly generated.
MacKay creates a dictionary of the artificial language, Wenglish, by selecting $2^{15}$ words of 5 character length from the probability distribution of a-z including the space character '-'.
MacKay then claims that since Wenglish uses all of its words with equal probability that the average information content per character is 15 bits/5 chars = 3 bits / char.
Information is highly variable at the first character (low for a, high for z) "however a word is exactly 15 bits so the letters that follow an initial z have lower average information content per character than an initial a."
So I computed the character by character entropy of word examples he gave such as:

zatnt
zxast
odrcr
aztdn

And found that the summation of the individual character entropies did NOT add up to 15 bits.  Does this constitute a violation of the additivity property of entropy or is it that on average it should be 15 and we can only assume additivity when the distributions for characters are uniform?
As requested, here are my calculations:
For word 'zatnt' with following probabilities:

[0.0007 0.0575 0.0706 0.0596 0.0706]

and log2 1/p entropy:

[10.4804    4.1203    3.8242    4.0685    3.8242]

with a sum:
26 ~= 15
Here are the probabilities:

a = .0575
b = .0128
c = .0263
d = .0285
e = .0913
f = .0173
g = .0133
h = .0313
i = .0599
j = .0006
k = .0084
l = .0335
m = .0235
n = .0596
o = .0689
p = .0192
q = .0008
r = .0508
s = .0567
t = .0706
u = .03334
v =.0069
w = .0119
x = .0073
y = .0164
z = .0007
'-' = .1928
Comment: "And found that the summation of the individual character entropies did NOT add up to 15 bits" Could you add your numerical calculations (at least your results)?
Comment: I added an example calculation.  I've also included the probabilities and example words in MacKay's  book.  I thought that it might have been an erratum at first but I tried the same technique on a language I created and did not find that the individual character entropies summed to the entropy of the word.
Answer: There seems to be several problems here.
First, the entropy is, by definition, an average: $H(X) = E[-\log p(X)]$ You don't compute the entropy of a single realization - you can compute, yes, the "information content" as $-\log p(X)$
Second, the "Wenglish" language is defined in somewhat tricky terms, which can lead to confusion: it consists of a dictionary of $2^{15}$ words constructed "at random" according to the probabilities table you copied; then, the source consists of a device which chooses a word at random (with equal probability) from that dictionary. The confusion arises because the word "probability" is used here twice. In what regards to the entropy calculation, only the second is relevant, the dictionary should be assumed as given.
Now: given (fixed) a particular dictionary, (and knowing that words are extracted uniformly) to compute the probability that the first letter is 'a', we should not use the probabilities table, but simply count the ratio of words starting with 'a' over the total in the dictionary ($2^{15}$). True, this should be near $p_a$ in your table. But the succesive letters are not independent: to take the extreme case, if you are given the first four letters, the probability that the fifth is 'a' will not be $p_a$, it will probably be 0 or 1 (given the first four letters we almost always can deduce the fifth). Hence, the conditional entropies of successive letters are lower than the marginals. And this explains that the total entropy is $15$ bits (as it must be for a source that emits $ 2^{15} $equiprobable macro-symbols), which is much less than $5\times H(x_1)$.
In summary, when the dictionary is fixed the symbols are not independent anymore, and hence the additive property does not apply.
Comment: well, you can always write $P(A,B,C,D,E)=P(E|A B C D) P(D | A B C ) P (C | AB) P(B|A) P(A)$
Comment: Perfect! Now could you decompose the entropy of a word based off of the correlations amongst its constituents (i.e. using bigrams/trigrams?).

In other words, is the word entropy decomposable as the 1 to N gram entropy of its constituents where N is the length of the word?  I hope my question makes sense :s
Comment: sorry I mean *information content* not entropy


Convert hosted site to just parked domain

Question: I have a small site that's been a side project for a while and until I have an opportunity to improve it I'm going to take it offline. I'd still like to keep the domain name.
I've seen people buy domain names that get parked. What I haven't been able to find is how do you get a domain name you own and park it? The hosting service I'm using doesn't seem to offer that service so suggestions of services where I could move my domain to would also be helpful.
I'm doing this to save costs with hosting which I don't need ATM.
Answer: You dont need to setup parking or the like, simply ensure you have paid for the domain name and check the expiry date, provided you keep paying for the domain you will keep it.You will not lose your domain because there is not hosting assigned to it.
Hope this helps!
Comment: Let me revise. The place where I have it hosted (siteground.com) doesn't offer an option to simply park it. I expect a parked domain to be cheaper than a hosted one and I don't need the hosting portion ATM. So, I need to move my domain out of where it is to a service that accommodates parked domains but that were registered elsewhere.
Comment: I'm trying to explain that the domain and the hosting are two seperate items. You do not need hosting to have a domain name, nor does it need to be parked to remain valid. Many people buy domain names simply to use names instead of IP's in the big wide world, or even just so the domain can recieve mail.
Long story short, as long as your pay for your DOMAIN it dosnt matter whether it is using a hosts name servers or an A record is pointing at hosting!
Answer: While James is absolutely correct, you don't lose your domain if it's not hosted, you might want to consider an advertising parked domain.
Google AdSense for Domains could give you a little trickle of advertising revenue (or a river depending on traffic :D), and it's fairly easy to set up.
Additionally, the setup is just DNS updates which should be free through the registrar you got your domain through.
Answer: Depending on your registrar you can you their parking feature , or you can park it with a company like Google ads as said before or Sedo.


The operator $T+i Id$

Question: I have the operator  $$T:\mathcal{H}\rightarrow\mathcal{H}$$
the operator $T$ is linear, symmetric and compact, $\mathcal{H}$ is a Hilbert space
my problem is

Prove that ($\,T+i\,$Id) is $\,\bf{surjective}$.

($i$ is a imaginary number and Id is the identity operator)
I proved that $\,\,\,T+i\bf{Id}$  is injective
occupying the above, is there any way to show that $\,\,\,T+i\bf{Id}\,$ is $\,\bf{surjective}$?
So you can give me some hint, thanks!
Comment: 'Epijective' wants to mean '*surjective*', right?
Answer: The spectrum of $T$ is contained in the real line. Hence $-i$ is not in the spectrum This means $T+iI$ is invertible.
Answer: You can show that $(T-\lambda I)$ is invertible for all $\lambda\notin\mathbb{R}$. Using the fact that $\langle Tx,x\rangle$ is real, it is easy to see that
$$
         \Im\langle (T-\lambda I)x,x\rangle = -\Im\lambda \langle x,x\rangle,\;\;\; x\in \mathcal{H}
$$
Therefore,
$$
     |\Im\lambda|\|x\|^2 \le \|(T-\lambda I)x\|\|x\|, \\
      |\Im\lambda|\|x\| \le \|(T-\lambda I)x\|.
$$
So $T-\lambda I$ has trivial null space for $\lambda\notin\mathbb{R}$.

The range of $T-\lambda I$ is closed because, if $(T-\lambda I)x_n\rightarrow y$, then $(T-\lambda I)x_n$ is Cauchy, which then forces $\{x_n\}$ to be Cauchy by the last inequality. Hence, $\{x_n\}$ converges to some $x\in\mathcal{H}$ and the above implies that $(T-\lambda I)x_n\rightarrow (T-\lambda I)x=y$.
The range of $T-\lambda I$ is $\mathcal{H}$ because $z\perp \mathcal{R}(T-\lambda I)$ implies
$$0=\langle (T-\lambda I)x,z\rangle
=\langle x,(T-\overline{\lambda}I)z\rangle \;\;\;\forall x \\
    \implies (T-\overline{\lambda}I)z=0 \\
    \implies z = 0.
$$

Therefore $T-\lambda I$ is surjective for all non-real $\lambda$ because its range is dense and its range is closed. Note: you do not need compactness of $T$ for this argument to work, only boundedness.

The operator $T+i Id$


How to create column-range chart from data of a HTML table?

Question: I want to get a column-range chart that shows columns from min and max columns of a HTML table.
I have already built a bar graph (column graph) from the table but am unable to make it work for the column-range graph.
$(function() {

  $('#container').highcharts({
    data: {
      table: 'datatable'
    },
    chart: {
      type: 'column',
      inverted: true
    },
    title: {
      text: 'Data extracted from a HTML table in the page'
    },
    yAxis: {
      allowDecimals: true,
      title: {
        text: 'Mean difference (d)'
      }
    },
    tooltip: {
      formatter: function() {
        return '' + this.series.name + '
' +
          this.point.y + ' ' + this.point.name.toLowerCase();
      }
    }
  });

});

I expect to get a column-graph instead of a bar graph.
This is the jsFiddle of how I want my output to be.
Comment: The JS fiddle is not showing the output, but you can run it on your PC and see the result. Sorry for the inconvenience.
Comment: I have update the JSfiddle link @Abhi Patel
Comment: Please post the html data too. Which you are setting as datatable
Comment: Is there any way of adding scatter points showing average on each of these line?
Answer: Below you can find a fully working example with columnrange series type and data form HTML table:
Highcharts.chart('container', {
    chart: {
        type: 'columnrange',
        inverted: true
    },
    data: {
        table: 'datatable'
    },
    plotOptions: {
        columnrange: {
            pointWidth: 5,
        }
    }
});

Live demo: https://jsfiddle.net/BlackLabel/oks6xf7d/
API Reference: https://api.highcharts.com/highcharts/data.table
Comment: Thanks a lot. I just did a silly mistake of not including a CDN of HighCharts.


Select statement return if there is a value and if there is no value

Question: Here's my code of the SQL Server stored procedure:
SELECT NOTES as DeletionNote
FROM STCRCHF_LOG
WHERE STHTR_ =  @transferNo

IF ( @@ROWCOUNT = 0)

If there is data found, I just want to return the string of NOTES. Else if it doesn't have data, I just want to return an empty string or null.
Screenshot (executed stored procedure):
If there is data found. At my program on the web server side it gets the data.

If there is no data. In my program on the web server side it causes a NullReferenceException
Comment: Will you be expecting multiple rows for a `@transferNo` ?
Comment: Side note - TransforNo seems to be a number. Why is it a unicode string?
Comment: @Squirrel i do have only one data for each transfer data
Comment: But don't you handle NullReferenceException in web program level. Handling such exception at programming level is always a wise idea.
Answer: If only a single record is possible then:
select coalesce((SELECT NOTES FROM STCRCHF_LOG
WHERE STHTR_ =  @transferNo), '') as DeletionNote

If multiple records are possible then the following will ensure at least one row is returned:
SELECT NOTES as DeletionNote FROM STCRCHF_LOG WHERE STHTR_ =  @transferNo
union all select '' /* or null if preferred */ where not exists (SELECT 1 FROM STCRCHF_LOG WHERE STHTR_ =  @transferNo)

Comment: Good answer, though the alias should be on the outer select.
Comment: The solution you posted for multiple rows is similar to the one I had in mind, with one exception: In case the query gets more complicated, for the second solution I would suggest using a cte or even a table variable to hold the results (in case it's a long running query) instead of repeating the entire query in the `exists`. Still, I would upvote again if I could :-)
Comment: Also, please note that it will only work for a select statement that returns a single value. If the select statement returns more than one row, this will fail with "Subquery returned more than 1 value...".
Comment: @ZoharPeled I do have only one data in each transfer no.  Thanks Guys!! I'l check !
Comment: @ZoharPeled Agreed - I would certainly do that if there was additional complexity. Thanks for your kind words.
Answer: Another way which I like is to use a dummy value and OUTER APPLY like so.
-- sample data
DECLARE @table TABLE (someId INT IDENTITY, Col1 VARCHAR(100));
INSERT @table(Col1) VALUES ('record 1'),('record 2');

DECLARE @id INT = 11;

SELECT f.Col1
FROM   (VALUES(NULL)) AS dummy(x)
OUTER APPLY
(
  SELECT t.Col1
  FROM   @table AS t
  WHERE t.someId = @id
) AS f;

Answer: Check If(DataTable.Rows.Count >0) check at your web programming level to avoid NullReferenceException. Based on the condition you can make the decision what to do with the further logic at web program.
It is always wise idea to handle such exception from programming level. Think of scenario where somebody else make changes in SQL query without knowing the effect of web usages of the code.
Comment: Corret, I've missed that... need more coffee, I guess.
Comment: No worries @Zohar.. Coffee always helps us always go and get it. I wish I could join on Coffee table :)
Comment: What makes you think this is a website? or that it's even used outside sql server?
Comment: @zohar question has web server side. Mostly NullReferenceException always raised where we call sql code outside of the sql server. Also I did not use any where website.

Be it any programming language the check point I suggest is part of the best practices of the programming. I am not perfect and I am trying to pretend at least.


O que é o AntiForgeryToken?

Question: O que é o AntiForgeryToken e para que ele serve em uma aplicação ASP.NET MVC?
Answer: É um método que gera e insere no HTML gerado na view um código para evitar que se falsifique o envio de dados para o servidor.
Quando se usa este método ele insere algo assim:
<input name="__RequestVerificationToken" type="hidden"
    value="saTFWpkKN0BYazFtN6c4YbZAmsEwG0srqlUqqloi/fVgeV2ciIFVmelvzwRZpArs" />

Coloquei no GitHub para referência futura.
Quando o formulário for enviado com este código é possível validar se foi gerado pela sessão atual. O atributo ValidateAntiForgeryToken é usado para validar no controlador.
Ele resolve alguns tipos de ataque como CSRF, mas não todos.
Comment: Sensacional @bigown cada dia mais aprendendo com suas respostas.
Comment: ValidateAntiForgeryToken faz sentido usar em uma Web Api?
Answer: Caso vc precisa passar as informações via AJAX com jQuery pode fazer assim:~
var token = $('input[name="__RequestVerificationToken"]', form).val();

$.ajax({
    url: "/Controller/Action",
    type: "POST",
    data: {
        __RequestVerificationToken: token,
        IdAnuncio: $("#IdAnuncio").val(),
        Quantidade: quantidade,
        ValorCompra: valorCompra.toFixed(2)
    },
    success: function (data, textStatus, xhr) {
    }
});

Answer: No entanto, para ser usado vc deve chamar o método que insere o token na página html. "@Html.AntiForgeryToken()"

O que é o AntiForgeryToken?


Compute the probability of an event that selects red ball only?

Question: I have $n_1$ red balls and $n_2$ blue balls in a box.
Randomly select $k$ balls from the box. What is probability selects red balls only?
My solution is:
Let $X$ be event that select red ball only. $R$ is number of selected red ball. The probability of the event $X$ is
$$P(X)=\sum_{i=1}^{n_1} P(R=i)=\sum_{i=1}^{n_1} \frac{\binom{n_1}{i}}{ \binom{n_1+n_2}{i}}$$
Is my solution correct? Thank all
Comment: The obvious answer is no, it's not correct, because the probability should depend on $k$. (In particular, for $k=1$, the probability is $n_1/(n_1 + n_2)$, but for $k = n_1+1$ the probability is zero!) And your formula doesn't depend in any way on the value of $k$, so it can't possibly be right.
Comment: After the edit, even the question doesn't make sense now. If $P(k)=0.1k^1+0.2k^2+0.7k^{n_1}$ then $P(1)=0.1(1^1)+0.2(1^2)+0.7(1^{n_1})=0.1+0.2+0.7=1$. How do we find that the probability of $k=1$ is $0.1$? And if $k$ is random, how can the answer (which is a probability, therefore not random) just be a multiple of $P(k)$?
Comment: @DavidK: Thank you. I edited my question to adapt with your issue. Now it is more clear
Comment: @user3051460: it is not a wise thing to keep changing a question after it has received answers. This edit, completely changes the question. It should be better posted as a new question.
Comment: $P(k)$ just polynomial to said probability of select $k$. I updated a new question at http://math.stackexchange.com/questions/1961753/how-to-compute-the-probability-of-an-event-that-selects-red-ball-only
Answer: The probability of the event:

selecting $k$ balls, out of a box containing $n_1$ red and $n_2$ blue balls, such that all $k$ of them are red,

is given by ($k\leq n_1$):
$$
P=\frac{\binom{n_1}{k}\binom{n_2}{0}}{\binom{n_1+n_2}{k}}=\frac{\binom{n_1}{k}}{\binom{n_1+n_2}{k}}
$$
this is called the hypergeometric distribution.
Comment: Thank you. If $k$ is various from $1$ to $k_2$, it will be sum. is it right? Do you think my explaination about $X$ and $R$ are correct ?
Comment: Hmm, I do not think I agree with your interpretation of $X$. It describes a different event in a different sample space.
Comment: How can I write a full solution and explain it in mathematical?
Comment: A full solution on the question posed in your first sentence is contained in my post above (study the cited link as well). If you feel you have some extra question related to it, you should better post it as a new question.
Comment: I means I want to define $X$, $R$
Comment: I do not know what you mean by $X$. One thing I can tell you for sure is that it does not have anything to do with your original question. Now if you really want to ask: "what is the question for which the answer provided might be correct?" .... this is not smt I can say ;) and this is the reason I advised you, that it might be better to consider asking a new question.
Comment: Thank you. Because of issue of DavidK, I edited my question more clear. Could you look at it again
Comment: Please look at my comment above. This is not how things work here.
Comment: I updated a new question at http://math.stackexchange.com/questions/1961753/how-to-compute-the-probability-of-an-event-that-selects-red-ball-only
Answer: There are $\binom{n_1}{k} \binom{n_2}{0}$ ways to choose $k$ red balls (first term) and $0$ blue balls (second term). There are $\binom{n_1+n_2}{k}$ ways to choose $k$ balls from the box.
Your solution can't be right since your binomial coefficients are all zero (except for one term which is 1/0 which is undefined).
Comment: Thank you. I was wrong when typing binominal


How can a destination buffer be opaque?

Question: I came across implementation details of serialization functions and it is mentioned that the target memory to which the structure has to be unpacked and stored needed to be an opaque buffer.
Wikipedia says:

"Some languages, such as C, allow the declaration of opaque records (structs), whose size and fields are hidden from the client. The only thing that the client can do with an object of such a type is to take its memory address, to produce an opaque pointer."

According to this  pointer to  any memory address would be opaque since we have no control over the memory address at which the destination buffer would start.
So what is the point of such a classification in C with respect to buffers. I have seen that in C++ objects can be opaque which makes more sense, since we can create objects which can be prevented from changing and data abstraction is in place .
Comment: Simply put, "opaque type" in C works exactly like an abstract base class in C++, except opaque types have no automatic invocation of constructors/destructors. The caller can only declare a pointer to an object of the given type, never allocate it, nor access the members.
Answer: Suppose you had a library header that looks like this:
struct lib_data;

struct lib_data *new_data();
void read_data(struct lib_data *data);
void clean_data(struct lib_data *data);

There is a forward declaration of struct lib_data without specifying its contents. Your app can then do this:
struct lib_data *data = new_data();
read_data(data);
clean_data(data);

Note that you have no knowledge of what struct lib_data looks like or even what its size is. That is what is meant by opaque. But you can hold a pointer to it and pass that around.
In the library's implementation (which you may or may not have access to), the struct has a proper definition and can therefore modify its elements.
For example, the library implementation might look like this:
struct lib_data {
    int data1
    double data2;
}

struct lib_data *new_data()
{
    struct lib_data *temp = malloc(sizeof(struct lib_data);
    temp->data1 = 1;
    temp->data2 = 3.5;
    return temp;
}

void read_data(struct lib_data *data)
{
    ...
}

void clean_data(struct lib_data *data)
{
    free(data);
}

So the library can manipulate the struct, but application that use it cannot.
Comment: Thanks a lot for the pragmatic answer.

How can a destination buffer be opaque?


Telerik RadGrid incorrect data when paging

Question: I have a textbox and a search button and a RadGrid which was already bound data to by OnNeedDataSource event. When I click search button, it will get the new data and I Rebind() that data on search button click event.
But when I change page number on the grid, the datasource was not the datasource I've already Rebind().
Comment: Perhaps post some code will help us identify your problem...
Answer: Here is my sample code.. I don't find any problem on changing page.
You might want to change Rebind to DataBind due to different DataSource.
Rebind most probably will take back the previous DataSource
.aspx
<asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>

<asp:TextBox ID="txt" runat="server" Text=""></asp:TextBox>
<telerik:RadButton ID="btn" runat="server" Text="Search" OnClick="btn_Click">
</telerik:RadButton>

<telerik:RadGrid ID="rg" runat="server" PageSize="5"
    OnNeedDataSource="rg_NeedDataSource" AllowPaging="true"
    AutoGenerateColumns="false">
    <MasterTableView>
        <Columns>
            <telerik:GridBoundColumn DataField="Text" HeaderText="Sample">
            </telerik:GridBoundColumn>
        </Columns>
    </MasterTableView>
    <PagerStyle Mode="NumericPages" />
</telerik:RadGrid>

.cs
protected void Page_Load(object sender, EventArgs e)
{
    // Variable
    DataTable dt = new DataTable();
    dt.Columns.Add("Text");

    for (int i = 0; i < 20; i++)
        dt.Rows.Add("DataSource before search First Item No." + (i + 1));

    // Save to Viewstate
    ViewState["Data"] = dt;

    // Bind
    rg.DataSource = dt;
    rg.DataBind();
}

protected void rg_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
    rg.DataSource = ViewState["Data"] as DataTable;
}

protected void btn_Click(object sender, EventArgs e)
{
    // Variable
    DataTable dt = new DataTable();
    dt.Columns.Add("Text");

    // Loop
    for (int i = 0; i < 20; i++)
        dt.Rows.Add("Datasource Search button item no " + (i + 1));

    // Viewstate the new Datasource
    ViewState["Data"] = dt;

    // Reset Page
    rg.CurrentPageIndex = 0;

    // Bind
    rg.DataSource = dt;
    rg.DataBind();
}


Twitter Bootstrap não carrega nos arquivos jsp

Question: Boa tarde pessoal.
Estou com um problema, minhas páginas jsp não carregam os CSS do bootstrap.
Gostaria de saber se há alguma configuração em algum xml ou em outro lugar que precisa ser feita, ou apenas colocar as pastas do bootstrap dentro do webapp resources e pronto?
Obrigado.
Comment: só colocar o bootstrap dentro do webapp e inserir a tag `` apontando para ele.
Answer: Se você estiver usando apenas jsp não precisa nenhuma configuração, a principio a pasta webapp é a pasta acessível pela web, então só precisa colocar o arquivo la e colocar a tag <link rel="stylesheet" href="caminho/do/arquivo"/>.


Lottery exam question

Question: I am studying a past examination paper however I do not have the answers to this paper so I can't check if I am right or wrong. I have just reached a section on combinatorics and counting and I have come across a few troubling questions.
The lottery rules state that you choose five different numbers in the range 1 to 53 and write them in an order of your choice on an entry form.

Question a) asks : On a lottery day, a machine selects ten balls from a sphere containing 53 balls numbered 1 to 53 and arranges them in a row. How many different outcomes can this process have? (write answer to 2 significant figures in scientific notation)

My answer to this was $53 \choose 10$ which is $1.9 \times 10^{10}$
I used choose (binomial coefficient) because the order doesnt matter and there not repetitions.
part b) to this question however, Im not sure how to calculate:

Part (b) asks : You win prize 1 if the first five balls selected by the machine match the five numbers you chose, and are arranged in the order you wrote them on your entry form. In how many of the outcomes of part (a) do you win prize 1? (You can write your answer in scientific notification and to 2 significant figures)'

I started by calculating the number of permutations you can actually have of choosing 5 lottery numbers which was 53!. My problem from here is that I don't know where else to start calculating and I'm really not sure if I have even started to calculate this in the right way? Please could someone explain to me the best way of doing this in as much detail as they can so that I can learn from this?
Answer: In part (a) the order does matter: this is indicated by the statement that the balls are arranged in a row. If they're in a row, they automatically have an order. Thus, the correct answer is
$$53\cdot52\cdot\ldots\cdot44=\frac{53!}{43!}=\binom{53}{10}\cdot 10!\approx 7.1\times 10^{16}\;.$$
For (b), we'll count the winning outcomes. There is only one winning choice for the first ball. In fact, there's only one winning choice for each of the first five balls. The sixth ball drawn can be any of the remaining $53-5=48$ balls, the seventh can be any of the $47$ balls still left, and so on, so there are
$$1^5\cdot48\cdot47\cdot46\cdot45\cdot44=205,476,480$$
winning outcomes.
Comment: I'm not sure if you understood what part b was asking? part b asks if the 'first 5 balls' match the 5 balls you chose, correct me if I am wrong but you are looking at the last 5 balls and working out the winning outcomes from them?
Comment: @RJB: Yes, I understood (b). In order for the first $5$ balls to match the ones that you chose, they must be precisely those $5$ balls: there is only one first ball that can give you a winning draw, only one second ball, and so on. The last $5$ balls drawn, however, can be any of the remaining $48$ balls in any order. This is exactly the calculation that I made.
Comment: ahh okay I see what you are saying now and yes you are correct, thanks for your help!
Comment: @RJB: You're welcome!
Comment: Hi Brian, I am answering the following question which is part c) this states **"You win Prize 2 if the first five balls selected by the machine match the five numbers you chose, and are arranged in any order (including that for which you win Prize 1). In how many of the outcomes of part (a) do you win Prize 2? (You may write your answer in scientific notation, to 2 significant figures.)"** I tried working this out by gathering that the first choice would have 53 winning outcomes, the second would have 52, third would have 51 and so on until the 5th choice. This gave me **344362200** but this -
Comment: doesnt consider all 10 balls I suppose so it would be incorrect, after doing this with all 10 balls I get the same answer to part a which would be all possible outcomes, please could you explain what I need to do here? It'd be a great help! Thanks!
Comment: @RonB7: In this case the first $5$ cards have to be the $5$ that you chose, but they can appear in any order. There are $5!=120$ possible orders in which they can appear, and all of those will get you Prize $2$. The remaining $5$ cards can be anything at all, so the answer is $5!\cdot48\cdot47\cdot46\cdot45\cdot44$, or $120\cdot205,476,480$.
Comment: Ahhh I see thats great! I know the basic theory behind how to calculate these types of questions is just applying it and breaking the questions down which I find hardest lol, thanks for the help!
Comment: @RonB7: You're welcome! Yes, the basic principles are pretty simple; it's working out how to apply them that can sometimes be quite difficult.

Lottery exam question


httpd error log "Error: Document has not the mandatory ending %EOF"

Question: The company I work for recently outsourced a website rebuild, and along with it came a CMS.
Despite my lack of expertise, I am the nominated server expert. Go Figure.

Anyway, when trying to upload .pdfs to the CMS we cant upload anything over 1Mb.
I have checked the php.ini and the .htaccess files and they are currently:
post_max_size = 15M
upload_max_filesize = 10M

Now to the main point of this question, the error logs show the following:
Error: Document has not the mandatory ending %EOF

However, when I open the PDF in notepad++ it certainly does have %EOF as the very last line.
Currently the server is running PHP 5.5 and CentOS 5.11
So really I'm just hoping someone has experienced this before and has a solution, none of my googling is helping!
Comment: What's the CMS ?
Comment: @Iain Its a custom Content Management System written by the people who made our site.
Comment: With all due respect, you're going to have the best luck contacting the support/developers of the CMS.
Comment: @BrandonXavier They refuse to help because they claim its a server issue. Apparently on their test server it works fine.
Answer: I don't think there is much we can do to help here. The wording of that error message is a little odd but the internet has little information on it.
There are several things I would try

I would ask the developers if that message is one that their CMS generates and try to work with them to solve the issue. If it's not within their software then I'd be looking to track down what does generate it and use that as a starting point.
Your system is, whilst supported, somewhat elderly you really shouldn't be developing for CentOS 5.11 any more without a very good reason. I would get a VM with a more recent version of CentOS (6.7 or 7.1), install the CMS and it's dependencies and then do some testing.


Obvious claim about Kurdyka-Łojasiewicz inequality

Question: Let $H$ be a hilbert space and $f$ a closed, proper, convex function from $H$ to $\mathbb{R}\cup\infty$. We write $[f < \mu]$ to denote the set $\{x\in H: f(x)<\mu\}$, $d$ for the hausdorff distance, and $\partial$ for the subdifferential. Let $r_0>0$ and set,
$$K(0,r_0) = \{\phi\in C^0[0,r_0)\cap C^1(0,r_0), \phi(0)=0, \phi\mbox{ is concave and }\phi'>0\}$$
Then we say the function $f$ satisfies the K-L inequality locally at $\bar{x}\in dom(f)$ if there exists $r_0>0$, $\phi\in K(0,r_0)$, and $\varepsilon>0$ such that
$$\phi'(f(x)-f(\bar{x}))d(0,\partial f(x))\geq 1$$
for all $x\in B(\bar{x},\varepsilon)\cap [f(\bar{x})<f(x)<f(\bar{x})+r_0]$.
The paper I am reading claims that if $\bar{x}$ is not a minimizer of $f$ then the KL inequality is obviously satisfied at $\bar{x}$. I don't see it, can someone explain why it's true/obvious?
Comment: Minor note: did you mean that $f$ is from $H$ to $\mathbb{R} \cup \infty$? Your current statement reads $f: H \to \mathbb{R} \cap \infty$, but $\mathbb{R} \cap \infty$ is the empty set.
Comment: Yes you're correct.
Answer:
Lemma: for convex, closed $f$, if $\bar{x} \in \mathrm{dom}f$ is not critical, there is a $c > 0$ such that $\| x - \bar{x} \| + \| f(x) - f(\bar{x}) \| < c \Rightarrow d(0, \partial f(x)) \geq c. $

Proof: By Lemma 2, which is applicable to critical points of any proper lsc function, after noticing that:

all critical points of convex functions are also minimizers
the convex subdifferential is closed.

Based on that lemma, you can define the "neighbourhood" $B\left(\bar{x}, \frac{c}{2}\right) \cap \left[f(\bar{x}) < f(x) < f(\bar{x}) + \frac{c}{2}\right]$, in which
$d(0, \partial f(x)) \geq c$, and set $\phi(s) = \frac{1}{c} s$ with $\phi'(f(x) - f(\bar{x})) = c^{-1}$.
Comment: This lemma is indeed a huge piece I was missing.