Does existence of mixed derivative imply continuity?

Question: I would like to does existence of mixed derivative at a point guarantees the function is continuous at that point?
And I would like to ask if ${\frac {\partial ^{2}f}{\partial x^{2}}}$ exist implies the function is continuous at that point. I believe the answer to this question is no because I can construct a function f(x) such that it equals to $x^2$ for $x=0$ and equals 1 otherwise.
But how about the first question?Thanks.
Answer: Tl;dr: The existence of a mixed partial derivative at some point doesn't imply that the function is continuous at said point.  The weaker statement which is related, that is, "the existence of all mixed partial derivatives at some point implies continuity at the point" is also false.

For the following I will be assuming three dimensions (since there isn't much of a difference with higher dimensions).
Let's start with the example you gave, since it seems you already have some intuition built there:
$$
f(x, y) =
\begin{cases}x^2 \quad \mbox{ if $x = 0$}\\
0 \quad \mbox{ otherwise.}
\end{cases}
$$
Since you're looking at $\frac{\partial^2f}{\partial x^2}$, I have a feeling that the function you had in mind was to use $x^2$ when $y=0$ rather than $x=0$ like this:
$$
f(x, y) =
\begin{cases}x^2 \quad \mbox{ if $y = 0$}\\
0 \quad \mbox{ otherwise.}
\end{cases}
$$
The advantage this gives becomes clear when we try to take the partial derivative with respect to $x$.  In particular, we don't cross the boundaries defining the piecewise function when making small changes to $x$.  Since this never happens, $
\frac{\partial f}{\partial x} =
\begin{cases}2x \quad \mbox{ if $y = 0$}\\
0 \quad \mbox{ otherwise.}
\end{cases}
$ and $
\frac{\partial^2 f}{\partial x^2} =
\begin{cases}2 \quad \mbox{ if $y = 0$}\\
0 \quad \mbox{ otherwise.}
\end{cases}
$
Of course, $f$ is not continuous at $(3,0)$, but the second partial derivative with respect to $x$ exists at that point.  So, the existence of second degree (or any degree, for that matter) partial derivatives in one variable do not imply that the function is continuous.

Now back to your first question.  Say we tweak the last example so
$$
f(x, y) =
\begin{cases}2 \quad \mbox{ if $y = 0$}\\
0 \quad \mbox{ otherwise.}
\end{cases}
$$
Now $
\frac{\partial f}{\partial x} =
\begin{cases}0 \quad \mbox{ if $y = 0$}\\
0 \quad \mbox{ otherwise}
\end{cases}
$, so $\frac{\partial f}{\partial x} = 0$ for all $(x, y)$.  If we now take the partial with respect to $y$, the resulting function is still $0$ for all $(x, y)$.  So now we have a function where the mixed derivative $\frac{\partial^2 f}{\partial x \partial y} = 0$ exists for all $(x,y)$ but is not continuous for $y = 0$.

This last result leaves room for other partial derivatives to not exist, namely $\frac{\partial f}{\partial y}$.  By using a more esoteric piecewise function, we can give a counterexample to this as well.

Consider
$$
f(x, y) =
\begin{cases}1 \quad \mbox{ if $x = y \not = 0$}\\
0 \quad \mbox{ otherwise.}
\end{cases}
$$
This function is zero everywhere except along the line $y = x$, except again at the point $(0,0)$.  As a result, $f$ is not continuous at $(0,0)$ since approaching the point through the line $y=x$ gives a different result.  However, no matter how many partial derivatives you take and in whatever order, the mixed partial derivative is defined (and is equal to $0$) at the point $(0,0)$.

The last case I can think of (which is well beyond the scope of the question, but still worth thinking about) is whether the existence of every mixed partial derivative at every point implies continuity for all points.  My instinct tells me that this may be enough to get around the weird pitfalls that surround continuity for multivariable functions, but I'm far from confident.


Probability of not having a path between two certain nodes, in a random graph

Question: Suppose we construct an Erdős–Rényi graph $G(n, p)$.
Fix two nodes $u$ and $v$. What is the probability that there is no path connecting the two nodes?

My take:
I tried to model the problem as $P(\text{no path between } i \text{ and } j) = 1 - P(\text{at least a path between } i \text{ and } j)$.

If $n = 2$: $P(\text{no path between } i \text{ and } j) = 1-p$
If $n = 3$: $P(\text{no path between } i \text{ and } j) = 1 - (p + p^2 - p^3)$
If $n$ is an arbitrary number: I will try to compute the probablity of existence of a path.

Update:  the following is incorrect.
Let $Z_{u \rightarrow v}$ be a boolean variable, denoting the path from $u$ to $v$. $Z_{u \rightarrow v} = 1$ if and only if there is a path from $u$ to $v$. The goal is to find the probabilty of having a path from $u$ to $v$, in other words $\mathbb{P}(Z_{u \rightarrow v})$. Instead of calculating this probability, we use the expected number of path from node $u$ to any other node:
$$
\mathbb{P}(Z_{u \rightarrow v}) = \frac{ \mathbb{E} \left( Z_{u \rightarrow ? \neq u} \right) }{ n - 1 }
$$
Next we calculate $\mathbb{E} \left( Z_{u \rightarrow ?} \right)$. Suppose we start from $u$ and we visit its neighbors. Next we repeat the same procedure for its neighbors (like, say via BFS). Suppose we have seen all neighbors of distance $k$ from $u$. Define $S_k$ to be the size of nodes accessible from $u$ with at most $k$ steps. Suppose there is an ordering on visiting the elements in this procedure, based on which we sort them. Suppose the size of the elements at distance $k$ is $X_1$, size of elements with distance 2 is $X_2$, and so on. Hence
$$
S_i = \sum_{j=0}^i X_j
$$
The distribution on $X_{i+1}$ given the previous observed nodes is binomial $ \text{Bin} \left( n - 1 - S_i, p  \right)$; in other words the probability of observing $X_{i+1} = k$ neighbors with distance $i+1$ from the starting point is ${ n - 1 -S_i \choose k }p^{k}(1-p)^{n - 1 -S_i-k}$. With this the expected number of the newly discovered neighbors at distance $i$ is
$\mathbb{E}_{X_{i+1}|S_i} \left( X_{i+1}|S_i  \right) = (n - 1 - S_i)p$.
Using the law of total expectations:
\begin{align*}
    \mathbb{E}X_i &= \mathbb{E}_{S_i} \left[ \mathbb{E}_{X_i | S_i } \left( X_i | S_i \right)  \right]  \\
                    &= \mathbb{E}_{S_i} \left[  n - 1 - S_i  \right]  p  =  (n-1)p - p \mathbb{E} S_i
\end{align*}
\begin{align*}
\mathbb{E}{S_{i+1}} &=  \mathbb{E}{S_i} +  \mathbb{E}{X_{i+1}} \\
                    &=  (n-1)p -(1-p) \mathbb{E}{S_i} \\
                    &=  (n-1)p \sum_{j= 0}^i (1-p)^j \\
                    &=  (n-1)p \frac{ 1 - (1-p)^{i+1}  }{  1 - (1-p) } \\
                    &=  (n-1) \left( 1 - (1-p)^{i+1}  \right)
\end{align*}
Therefore  $\mathbb{P}(Z_{u \rightarrow v}) =  \frac{n-1}{n-1} \left[  1 - (1-p)^{(n-1)} \right] $ and $P(\text{no path between } i \text{ and } j) = (1-p)^{(n-1)}$
The confusing part is, I am not sure why this formula does not work for the special case of $n=3$, as I calculated above.
Comment: The distribution of $X_{i+1}$ given the previous nodes is $\text{Bin}(n - 1 - S_i, 1 - (1-p)^{X_i})$, since a node counted by $X_{i+1}$ may be reached by any of the nodes counted by $X_i$.
Comment: @MishaLavrov can you expand on this comment a little bit. Not sure I understand it.
Comment: If you've found the nodes at distance $1,2,\dots,i$ from the starting node $u$, then the nodes at distance $i+1$ are those of the $n-1-S_i$ remaining nodes which are adjacent to one of the $X_i$ nodes at distance $i$. For each remaining node, the probability it is *not* adjacent to any of those nodes is $(1-p)^{X_i}$, so the probability that it *is* adjacent to one of them is $1-(1-p)^{X_i}$.
Answer: If you want the exact probability, then we can reduce this to the problem of finding the exact probability that a graph is connected. If $f(n,p)$ is that probability, then the probability that two vertices $u,v$ are disconnected is $$\sum_{i+j+k = n} \binom{n-2}{i-1,j-1,k} f(i,p) f(j,p) (1-p)^{ij + ik + jk}$$ where we just sum over all the possibilities: that the first vertex is in a component of size $i$, the second in a component of size $j$, and there are $k$ vertices left over.
But this is a very unnatural question to ask. Generally, with random graphs, we look for asymptotic answers as $n \to \infty$, because the exact answers are not very nice and not very useful.
Asymptotically, for $p \ge \frac{1+\epsilon}n$, the random graph has a giant component of linear size, and all remaining components are sublinear. So up to lower-order terms, two vertices $u,v$ are connected with about the same probability as that they're both in the giant component. If $p \sim \frac cn$, then $(x + o(1))n$ vertices are in the giant component w.h.p., where $x$ satisfies $1-x= e^{-cx}$, and the probability that $u$ and $v$ are not connected is therefore $(1-x)^2+o(1)$.
In particular, if $p \gg \frac1n$, the probability that $u$ and $v$ are not connected tends to $0$ as $n \to \infty$.
If $p \le \frac1n$, there is no giant component, and the probability that $u$ and $v$ are not connected tends to $1$ as $n \to \infty$.
Answer: This is a partial answer, but I will try to complete the answer over time. Well, turns out the question is not that simple.
Based on this paper you can think about it as a layer-wise exploration of all the nodes (i.e. nodes in each layer are equidistant from the starting node)

The paper models the distribution of the shortest path $P(d_{ij} = k)$, and provides a recursive formulation for the distribution (and its approximation).
Side note that, we know that the mean distance for ER random graphs is:
$$
\langle d\rangle = \sum_i i \times P(d_{ij} = i) = \frac{\log n}{ \log c} + o(1)
$$
although this is not what the question was asking for.
And turns out that the diameter, i.e. the longest possible distance among all possible shortest paths in a given network is almost the same as the average distance.
Answer: With the method of @Misha Lavrov, I wrote a Mathematica code to calculate the answer
p = 0.5;
f[n_] := 1 -
   Sum[f[i]*Binomial[n - 1, i - 1]*(1 - p)^{i*(n - i)}, {i, 1, n - 1}];
Flatten@Table[f[n], {n, 1, 10}]
TheTwoCertainVerticesNotConnected[n_] :=
  Sum[Multinomial[m[[1]] - 1, m[[2]] - 1, m[[3]]]*f[m[[1]]]*
    f[m[[2]]]*(1 - p)^{m[[1]] m[[2]] + m[[2]] m[[3]] +
       m[[3]] m[[1]]}, {m,
    Flatten[Table[FrobeniusSolve[ConstantArray[1, 3], k], {k, n, n}],
     1]}];
Flatten@Table[1 - TheTwoCertainVerticesNotConnected[n], {n, 2, 10}]

TheTwoCertainVerticesNotConnected[n] for n in (2..=10)
$$
\{0.5,0.625,0.75,0.853516,0.923584,0.963058,0.982573,0.991691,0.995962\}
$$


Positive measure

Question: Let $\mu$ positive measure over $(\mathbb{R},\mathcal{B}(\mathbb{R}))$. Prove that if $\mu$ is invariant translations and $\mu([0,1])=1$, then $\mu([0,\frac{1}{n}])\leq\frac{1}{n}$
I know that this measure is the Lebesgue measure, but I can´t prove that  $\mu([0,\frac{1}{n}])\leq\frac{1}{n}$
Answer: Fix $n\geq 1$ and consider the partition $\left\{[\frac{k-1}{n},\frac{k}{n})\right\}_{k=1}^{n}$ of the half-open interval $[0,1)\in \mathcal{B}(\mathbb{R})$
Now since $\mu$ is a positive measure we have that $$\sum_{k=1}^{n}\mu\left([\frac{k-1}{n},\frac{k}{n})\right)= \mu([0,1)) \leq \mu([0,1]) =1 $$
Now since $\mu$ is assumed to be translation invariant, we have that $\mu([0,\frac{1}{n})) = \mu\left([\frac{k-1}{n},\frac{k}{n})\right)$ for all $1<k\leq n$. Hence $$\mu([0,\frac{1}{n})) \leq \frac{1}{n}$$
Now i claim that $\mu(\left\{x\right\})=0$ for any $x \in \mathbb{R}$, since if there would be a singleton with positive measure, then certainly every singleton would have positive measure due to the translation invariance, which contradicts the fact that $\mu([0,1]) =1$ by simply taking any countably infinite collection of singleton subsets of $[0,1]$.
Thus we arrive at $$\mu([0,\frac{1}{n}]) = \mu([0,\frac{1}{n})) + \mu\left(\left\{\frac{1}{n}\right\}\right) = \mu([0,\frac{1}{n})) \leq \frac{1}{n}$$

Positive measure


Home studio for guitar question

Question: I just purchased a focusrite solo 2gen and still can't make a nice recording.  The interface is working but the sound is not terrible as I only use the provided Ableton Live, which means no effects and no amp simulation.
I also have a digitech rp255 pedal and a blackstar ht1r.  But I still didn't figure out how to get the best sound out of all this. Do I need some additional softwares? What do I need if I wanna plug and play (recording with an amp simulation software) ?
Thank you for your advice
Comment: Are you recording via a microphone into the Focusrite or are you connecting your instrument directly to it? What's the specific problem you have with the sound - is it poor quality or just not like a commercial recording?
Comment: Also, you might want to have a look at [this post](http://music.stackexchange.com/questions/23896/how-to-record-my-guitar-on-my-computer?rq=1) and see if it has any tips you might use.
Comment: I plug the guitar directly. The sound is poor. I might purchase a mic later but for now i'd like to record direct
Comment: For electric guitar you'll almost certainly want to reamp -- take a look at the [LePou](http://lepouplugins.blogspot.com/) amp sims. They're free, and very good.
Comment: Or for something a little more "all in one," check out the free versions of [Guitar Rig](https://www.native-instruments.com/en/products/komplete/guitar/guitar-rig-5-player/) and [Amplitude](http://www.ikmultimedia.com/products/amplitubecs/).
Answer: I've recorded my guitar at home using a Focusrite Scarlett 2i4 and Ableton Live with decent results.
I plugged my guitar directly into the input, making sure I've selected the 'Instrument' setting.
Be careful with the gain - don't let it go into the red on your recording.
I don't know exactly what you mean by

the sound is poor

When I record the sound is just what comes out of the instrument - if you want to use an amp plugin there are many free ones available but not knowing what the specific problem is makes it hard to give any specific answers.

Home studio for guitar question


Renaming Columns after concatenating two Series with same Column names

Question: I have two series namely x and y.
x:

Index
Timestamp

0
2022-11-16 13:00:00

1
2022-11-17 13:48:00

y:

Index
Timestamp

0
2022-11-16 19:13:00

1
2022-11-17 16:21:00

I combine these two series into a data frame as follows.
z = pd.concat([x, y], axis=1)

But in the dataframe both the column names appear as "Timestamp". I want to rename it.
When I used the below code it changes both column names at the same time.
mapping = {z.columns[0]: 'Start' }
su = z.rename(columns=mapping)

Preferred output:

start
End

2022-11-16 13:00:00
2022-11-16 19:13:00

2022-11-17 13:48:00
2022-11-17 16:21:00

How can I do this in pandas?
Answer: Example
x = pd.Series({0: '2022-11-16 13:00:00', 1: '2022-11-17 13:48:00'}, name='Timestamp')
y = pd.Series({0: '2022-11-16 19:13:00', 1: '2022-11-17 16:21:00'}, name='Timestamp')

Code
pd.concat([x, y], keys=['start', 'end'], axis=1)

result:
    start               end
0   2022-11-16 13:00:00 2022-11-16 19:13:00
1   2022-11-17 13:48:00 2022-11-17 16:21:00


How can I improve my regex so that it takes into account a maximum of scenarios?

Question: I have an input and a result div. When user types whatever text he wants, I want to display the same text whithout accent. So I found here on stackoverflow many functions, among which this one :
function removeDiacritics (str) {
  var defaultDiacriticsRemovalMap = [
    {'base':'A', 'letters':/[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g},
    {'base':'AA','letters':/[\uA732]/g},
    {'base':'AE','letters':/[\u00C6\u01FC\u01E2]/g},
    {'base':'AO','letters':/[\uA734]/g},
    {'base':'AU','letters':/[\uA736]/g},
    {'base':'AV','letters':/[\uA738\uA73A]/g},
    {'base':'AY','letters':/[\uA73C]/g},
    {'base':'B', 'letters':/[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g},
    {'base':'C', 'letters':/[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g},
    {'base':'D', 'letters':/[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g},
    {'base':'DZ','letters':/[\u01F1\u01C4]/g},
    {'base':'Dz','letters':/[\u01F2\u01C5]/g},
    {'base':'E', 'letters':/[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g},
    {'base':'F', 'letters':/[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g},
    {'base':'G', 'letters':/[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g},
    {'base':'H', 'letters':/[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g},
    {'base':'I', 'letters':/[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g},
    {'base':'J', 'letters':/[\u004A\u24BF\uFF2A\u0134\u0248]/g},
    {'base':'K', 'letters':/[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g},
    {'base':'L', 'letters':/[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g},
    {'base':'LJ','letters':/[\u01C7]/g},
    {'base':'Lj','letters':/[\u01C8]/g},
    {'base':'M', 'letters':/[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g},
    {'base':'N', 'letters':/[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g},
    {'base':'NJ','letters':/[\u01CA]/g},
    {'base':'Nj','letters':/[\u01CB]/g},
    {'base':'O', 'letters':/[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g},
    {'base':'OI','letters':/[\u01A2]/g},
    {'base':'OO','letters':/[\uA74E]/g},
    {'base':'OU','letters':/[\u0222]/g},
    {'base':'P', 'letters':/[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g},
    {'base':'Q', 'letters':/[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g},
    {'base':'R', 'letters':/[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g},
    {'base':'S', 'letters':/[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g},
    {'base':'T', 'letters':/[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g},
    {'base':'TZ','letters':/[\uA728]/g},
    {'base':'U', 'letters':/[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g},
    {'base':'V', 'letters':/[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g},
    {'base':'VY','letters':/[\uA760]/g},
    {'base':'W', 'letters':/[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g},
    {'base':'X', 'letters':/[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g},
    {'base':'Y', 'letters':/[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g},
    {'base':'Z', 'letters':/[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g},
    {'base':'a', 'letters':/[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g},
    {'base':'aa','letters':/[\uA733]/g},
    {'base':'ae','letters':/[\u00E6\u01FD\u01E3]/g},
    {'base':'ao','letters':/[\uA735]/g},
    {'base':'au','letters':/[\uA737]/g},
    {'base':'av','letters':/[\uA739\uA73B]/g},
    {'base':'ay','letters':/[\uA73D]/g},
    {'base':'b', 'letters':/[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g},
    {'base':'c', 'letters':/[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g},
    {'base':'d', 'letters':/[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g},
    {'base':'dz','letters':/[\u01F3\u01C6]/g},
    {'base':'e', 'letters':/[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g},
    {'base':'f', 'letters':/[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g},
    {'base':'g', 'letters':/[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g},
    {'base':'h', 'letters':/[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g},
    {'base':'hv','letters':/[\u0195]/g},
    {'base':'i', 'letters':/[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g},
    {'base':'j', 'letters':/[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g},
    {'base':'k', 'letters':/[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g},
    {'base':'l', 'letters':/[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g},
    {'base':'lj','letters':/[\u01C9]/g},
    {'base':'m', 'letters':/[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g},
    {'base':'n', 'letters':/[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g},
    {'base':'nj','letters':/[\u01CC]/g},
    {'base':'o', 'letters':/[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g},
    {'base':'oi','letters':/[\u01A3]/g},
    {'base':'ou','letters':/[\u0223]/g},
    {'base':'oo','letters':/[\uA74F]/g},
    {'base':'p','letters':/[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g},
    {'base':'q','letters':/[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g},
    {'base':'r','letters':/[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g},
    {'base':'s','letters':/[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g},
    {'base':'t','letters':/[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g},
    {'base':'tz','letters':/[\uA729]/g},
    {'base':'u','letters':/[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g},
    {'base':'v','letters':/[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g},
    {'base':'vy','letters':/[\uA761]/g},
    {'base':'w','letters':/[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g},
    {'base':'x','letters':/[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g},
    {'base':'y','letters':/[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g},
    {'base':'z','letters':/[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g}
  ];

  for(var i=0; i<defaultDiacriticsRemovalMap.length; i++) {
    str = str.replace(defaultDiacriticsRemovalMap[i].letters, defaultDiacriticsRemovalMap[i].base);
  }

  return str;

}

Then I want to replace any blank space, any caracter like ' or " by an hyphen. SO I use this :
replace(/\s+|'+|"+|_/gi, "-")

I also want to remove unwanted caracters, so I add another regex :
replace(/[&|'|\(|\)|<|>|#|$|£|;|:|\/|\\|,|?|.|!|§]/g, '')

My final code will look like this:
$(function() {
  $('#myfile').on('input',function(){
    var renamefile = $("#resultDiv");
    filetitle = $(this).val().toLowerCase().replace(/\s+|'+|"+|_/gi, "-").replace(/[&|'|\(|\)|<|>|#|$|£|;|:|\/|\\|,|?|.|!|§]/g, '');
    renamefile.html(removeDiacritics(filetitle));
  });
  })

Everything works fine.BUT...
Is concatenating "replace()" functions like this correct, from a performance point of view ? is there a way to improve the code?
Now sometimes the user input could be "blabla - blabla"..
with the regex I use, this becomes : "blabla---blabla".. I would like it to be : "blabla-blabla"..
How can I achieve this, knowing that I'm already asking it to replace the blanks with dashes? Something like : if hyphens are surrounded by blank spaces, keep only one hyphen ?
Answer: I don't know about performance, but it seems you'll need another
.replace(/\s+|'+|"+|_/gi, "-")

at the end or maybe a
.replace(/---/gi, "-")

Comment: thank you Gary_w, unfortunatly, this doesn't work..


DevExpress BarManager SaveLayoutToStream

Question: I have a window full of DevExpress controls. The prominent control is a DockLayoutManager containing a TabbedGroup (tabs contain one of: pivot table control or grid control). Surrounding this control are other dockable windows as well as a item menu along the top of the window.
I would like to save the layout of the item menu bar by calling the SaveLayoutToStream on the BarManager object.
This function will complete successfully if and only if the layout of the prominent control is identical to the original layout (i.e. at design-time). If I drag the individuals tabs and dock them within the DockLayoutManager, then I get the following exception:
Exception of type 'DevExpress.Xpf.Core.Serialization.DuplicateSerializationIDException' was thrown.

 at DevExpress.Xpf.Core.Serialization.DuplicateSerializationIDException.Assert(IDXSerializable dxObj1, IDXSerializable dxObj2)
 at DevExpress.Xpf.Core.Serialization.DXSerializer.SerailizationStore.<.ctor>b__4(IDXSerializable dxObj)
 at DevExpress.Xpf.Core.Serialization.DXSerializer.AcceptCore(DependencyObject dObj, Action`1 visit, IEnumerable`1 parentIDs)
 at DevExpress.Xpf.Core.Serialization.DXSerializer.Accept(DependencyObject dObj, AcceptNestedObjects acceptNested, Action`1 visit)
 at DevExpress.Xpf.Core.Serialization.DXSerializer.SerailizationStore..ctor(DependencyObject root, AcceptNestedObjects acceptNested)
 at DevExpress.Xpf.Core.Serialization.DXSerializer.SerializeCore(DependencyObject root, Object path, String appName, DXOptionsLayout options, AcceptNestedObjects acceptNested)
 at DevExpress.Xpf.Bars.BarManager.SaveLayoutToStream(Stream stream)
 at LayoutExtensions.GetLayout(BarManager view) in C:\LayoutHelper.cs:line 136

Answer: We have reviewed the callstack and cannot even imagine what can cause this issue to appear.  Please post a sample project showing this issue to the DevExpress support center.  We will research why the problem appears and fix it.
Answer: See
http://www.devexpress.com/Support/Center/e/E2272.aspx
and
http://www.devexpress.com/Support/Center/p/Q325319.aspx
If you are using objects of the same type in your layout, assign the DXSerializer.SerializationID property for all objects
For example
<Window x:Class="WpfApplication.MainWindow"
        xmlns:core="http://schemas.devexpress.com/winfx/2008/xaml/core"
        xmlns:dxdo="http://schemas.devexpress.com/winfx/2008/xaml/docking"

...
<dxdo:DockLayoutManager Name="FilterGridDockLayoutManager" core:DXSerializer.SerializationID="dock1" >


Proof that the Killing form on a simple Lie algebra is non-degenerate

Question: This is obvious since there is a more general result for semi-simple Lie algebras, but I would like to prove it directly.
So suppose that the Killing form $\kappa$ is degenerate and let $X\in L$ be such that $\kappa(X,Y)=0$ for all $Y \in L$.
I would now like to use $X$ to construct a non-trivial ideal of $L$, thereby showing that it is not simple.
The ideal $\mathrm{span}_{\mathbb{F}}\{[X,Y] : Y \in L\} $ seems promising, but I haven't been able to show that it is non-trivial. I'm not sure if I am on the right track.
UPDATE Dietrich Burde's answer shows that this is in fact not true if for example the field $\mathbb{F}$ has characteristic 3. So in this case I assume I am only considering fields of characteristic 0, and moreover one may assume that $\kappa$ does not vanish identically.
Answer: Suppose that the characteristic is zero. $I=\{X:K(X,.)=0\}$ is an ideal. To see this, note that $K([X,Y],Z)=K(X,[Y,Z])$. If $K(X,.)=0,$ for every $Y,Z$, $K([X,Y],Z)=K(X,[Y,Z])=0$. This implies that $[X,Y]\in I$. Suppose that $I$ is not $\{0\}$. Then, since the Lie algebra ${\cal G}$ is simple, $I={\cal G}$ and $K=0$. This implies that ${\cal G}$ is solvable by the Cartan criterion. Contradiction.
https://en.wikipedia.org/wiki/Cartan%27s_criterion#Cartan.27s_criterion_for_solvability
Comment: Thank you. Our course did not cover solvability, but we were given the extra assumption that $\kappa$ does not vanish identically, so that allows us to exclude the case $I=G$.
Answer: Here is a counterexample. Consider the simple Lie algebra $\mathfrak{sl}(3)/Z(\mathfrak{sl}(3))$ over a field of characteristic $p=3$. Then the Killing form is given by $$
\begin{pmatrix}
12 & -6 & 0 & 0 & 0 & 0 & 0 & 0\cr
-6 & 12 & 0 & 0 & 0 & 0 & 0 & 0\cr
0 & 0 & 0 & 0 & 6 & 0 & 0 & 0 \cr
0 & 0 & 0 & 0 & 0 & 0 & 6 & 0 \cr
0 & 0 & 6 & 0 & 0 & 0 & 0 & 0 \cr
0 & 0 & 0 & 0 & 0 & 0 & 0 & 6 \cr
0 & 0 & 0 & 6 & 0 & 0 & 0 & 0 \cr
0 & 0 & 0 & 0 & 0 & 6 & 0 & 0
\end{pmatrix}
$$
which is identical zero for $3=0$.
Comment: For the exam question, probably, there was an assumption on the field $\mathbb{F}$. What did it say about the field?
Comment: I don't know what to say... this was an exam question: "Prove that, if g is
simple, then $\kappa$ is necessarily non-degenerate. [Here you may assume that $\kappa$ does not vanish identically.]"
Comment: There was no explicit mention of that, but the course only covered Lie algebras over fields of characteristic $0$. Actually, just $\mathbb{R}$ and $\mathbb{C}$.
Comment: I'm new to the subject. Could tell me why (or some hints) that $\mathfrak{sl}(3)/Z$ is simple (in my case s.s. will be enough), and if I'm right, $Z$ is all the scalar matrices, which is one dimensional, so the resulting quotient algebra will be 7 dimensional. But your matrix for the Killing form is 8 by 8. Did I miss something?


how remove the first item on drop down with javascript

Question: here is my code:
<select id="List" name="UserType" onChange ="hide">
       <option value="0" disabled="disabled" selected="selected">Tipo de Usuario</option>
       <option value="1" onclick="hide">Administrador</option>
       <option value="2" onclick="hide">Moderador</option>
       <option value="3" onclick="hide">Usuario Comun</option>
</select>

when i click some value (not zero) in the the drop down, i need remove the first item from this (Tipo de Usuario).  Some code in javascript able to do that?
Comment: Yes, you can do that with Javascript. What did you try?
Comment: list.children[0].remove(); or list.options[0].remove(); or list.removeChild(list.options[0]);
Comment: Dalorzo i saw these post but dont work for me
Answer: you can always use this:
<option disabled selected style="display:none">Tipo de usuaro</option>

Comment: not all browsers respect hiding options via display.
Answer: function hide(){
    var list = document.getElementById("List");
    list.removeChild(list.childNodes[1]);
}

Comment: childNodes includes whitespace, making it dangerous to rely on...
Comment: This will remove the first item even if the selected item is value zero.
Comment: @Gabriel but according to the given html the first item cannot be selected


snort complains on local.rules

Question: I just installed snort-220.127.116.11 on Fedora 20, and am getting error when running:
% snort -c /etc/snort/snort.conf --dump-dynamic-rules=/tmp
Running in Rule Dump mode

        --== Initializing Snort ==--
Initializing Output Plugins!
Initializing Preprocessors!
Initializing Plug-ins!
Parsing Rules file "/etc/snort/snort.conf"
PortVar 'HTTP_PORTS' defined :  [ 80:81 311 383 591 593 901 1220 1414 1741 1830 2301 2381 2809 3037 3128 3702 4343 4848 5250 6988 7000:7001 7144:7145 7510 7777 7779 8000 8008 8014 8028 8080 8085 8088 8090 8118 8123 8180:8181 8243 8280 8300 8800 8888 8899 9000 9060 9080 9090:9091 9443 9999 11371 34443:34444 41080 50002 55555 ]
PortVar 'SHELLCODE_PORTS' defined :  [ 0:79 81:65535 ]
PortVar 'ORACLE_PORTS' defined :  [ 1024:65535 ]
PortVar 'SSH_PORTS' defined :  [ 22 ]
PortVar 'FTP_PORTS' defined :  [ 21 2100 3535 ]
PortVar 'SIP_PORTS' defined :  [ 5060:5061 5600 ]
PortVar 'FILE_DATA_PORTS' defined :  [ 80:81 110 143 311 383 591 593 901 1220 1414 1741 1830 2301 2381 2809 3037 3128 3702 4343 4848 5250 6988 7000:7001 7144:7145 7510 7777 7779 8000 8008 8014 8028 8080 8085 8088 8090 8118 8123 8180:8181 8243 8280 8300 8800 8888 8899 9000 9060 9080 9090:9091 9443 9999 11371 34443:34444 41080 50002 55555 ]
PortVar 'GTP_PORTS' defined :  [ 2123 2152 3386 ]
Detection:
   Search-Method = AC-Full-Q
    Split Any/Any group = enabled
    Search-Method-Optimizations = enabled
    Maximum pattern length = 20
ERROR: /etc/snort//etc/snort/rules/local.rules(0) Unable to open rules file "/etc/snort//etc/snort/rules/local.rules": No such file or directory.

I do have /etc/snort/snort.conf and here is a relevant snippet:
var RULE_PATH /etc/snort/rules
include $RULE_PATH/local.rules

What could be the reason that it's unable to locate the file?
Thanks.
Answer: Did you by any chance tried:
var RULE_PATH rules
include $RULE_PATH/local.rules

Comment: Rules selection depends on the things you want to monitor/detect with snort, so it all depends. You can take a look at pulledpork (http://code.google.com/p/pulledpork/) - and download additional rules. But yes, you can safely comment everything you don't want/need/have on your system.
Comment: But it did solve his problem, didn't it?
Comment: Thanks Jakov, it does help, no complaints about /etc/snort//etc/snort/rules/local.rules  However the other thing is that I don't have these rules in /etc/snort/rules installed, I have only community.rules that I downloaded from snort.org.  Does this mean, I simply need to leave only "include $RULE_PATH/community.rules" and comment out the rest?
Comment: I see, the default snort.conf is "one-size-fits-all" case, so it has to be modified according to my needs. Thanks.

snort complains on local.rules


Changing content of XML

Question: There is an XML file and it consists of various nodes. I need to change one attribute of the nodes and then overwrite everything as a new version. I have found that SO question but Flash IDE cannot understand my XML file at all and throw errors about syntax.
I have calculations during the programme and should be written in specific attribute in XML. Then the updated version of the file replaced with former (overwrite).
My XML file are huge and complex, thus I am unable to put all my codes here. However I can tell you that I get everything from the file and put those in the code like link above.
<?xml version="1.0" encoding="UTF-8"?>
<Something x="0" y="0" width="1437.5" height="1010">

Flash expects a ; after the x="0" and stops expectedly.
What is the proper way to change the attribute of an XML?

Edit:
I am using an array for the XML file by slicing into pieces. Then I add necessary parts and keep like that. But I wonder is there better way of doing it without messing with arrays.
Answer: To change an XML attribute, you can use E4X ( ECMAScript for XML ), like this :
var xml:XML = <objects>
    <object id="mc_01" x="0" y="0" width="1437.5" height="1010" />
    <object id="mc_02" x="300" y="400" width="150" height="100" />
    <object id="mc_03" x="120" y="0" width="50" height="30" />
</objects>;

// select the object with its id (for example), and change its "x" attribute
xml.*.(@id == 'mc_02').@x = 800;

trace(xml);

// gives
//
//  <objects>
//    <object id="mc_01" x="0" y="0" width="1437.5" height="1010"/>
//    <object id="mc_02" x="800" y="400" width="150" height="100"/>
//    <object id="mc_03" x="120" y="0" width="50" height="30"/>
//  </objects>

For more about working with XML in ActionScript 3, take a look here.
Hope that can help.
Comment: @coner If you need that edit for another time, you can save it to your xml file, otherwise, you can just use it for that session.
Comment: Please correct me if I got this wrong. By `xml.*.(@id == 'mc_02').@x = 800;` I don't need rewriting the file, init? What I understand is, on the first read after that line, result will be updated.

Changing content of XML


access_type=online vs offline, how to know which one to use

Question: I have implemented Google oauth2 server flow for web, the first time that user logins using his/her google account I have to use access_type=offline to get a refresh token and save it to database but after that access_type=online will be enough.
I have read that google issues limited number of refresh tokens per client (I think the limit is 25 from what I read while I was searching) so after I got the refresh token I just want to use access_type=online.
But before the user logs in how should I know if I have the account associated refresh token or not.
I don't want to rely on cookies as user may remove cookies, several people use the browser and cookie might not equal to the user I have its acount and ...
Any Ideas how to detect it with google oauth or something like that before showing the login button?
Answer: You can just continue to use access_type=offline. It just won't give you a new refresh token after the first time. This will work until the user revokes access for your client in which case you'll have to get a new one anyway.


Sparse matrix multplication in C

Question: I have 2 sparse matrix files in matrix-market format:
row col val
1   1   3.0
1   2   1.0
2   3   2.0
etc...

Currently, I have split the files into 6 arrays:
row_A[], col_A[], val_A[], row_B[] …

Which contain the row index, column index and value respectively.
I would like to multiply the two matrices easily without having to convert them to dense matrix format first. Is there an algorithm for doing this?
I found this pseudocode on Quora but I'm unsure if its the it's the best implementation, or how it would be implemented in C: https://www.quora.com/What-is-the-C-program-for-the-multiplication-of-two-sparse-matrices
multiply(A,B):
  for r in A.rows:
    for c in A.rows[r]:
      for k in B.rows[c]:
        C[r,k] += A[r,c]*B[c,k]

Thanks.
Answer: There are sparse packages that do the multiplication for you. Have you tried Csparse inside SuiteSparse?
http://faculty.cse.tamu.edu/davis/suitesparse.html
You don't even need to convert the matrix format. However there are ways to feed in triplet format too.
Answer: It is not a good idea to multiply sparse matrices, because the resulting matrix will be dense anyway. You algorithm, apparently, consists of sequential multiplication of sparse matrices by a vector: a matrix is multiplied by a vector, then another matrix is multiplied by the obtained product, and so on. It would be wise to stick to that computational pattern, thus saving CPU time and the amount of RAM (the latter would be large if you intend to obtain and store the product of two sparse matrices).

Sparse matrix multplication in C


Problema em trabalhar com resolução com Bootstrap

Question: Observem a imagem;

Vocês podem perceber que a resolução fica do jeito que eu quero com ela está pequena porém ela estoura quando fica com uma resolução maior.
Como eu poderia corrigir isso?
aqui está o código HTML

Lista de Restaurantes

    <form >

                      Nome
                      Ano
                      Ação

                      {{ restaurant.name }}
                      {{ restaurant.category }}

                        botão

      </form>

Comment: eu estou usando esse site :P       `https://convertio.co/pt/mp4-gif/`  kkkkkk
Comment: Só por curiosidade. Qual foi a ferramenta que você usou para criar o ani gif? (vou deletar este comentário se o autor não responder)
Comment: @LeAndrade acabei de corrigir, eu tirei a classe CSS `col-lg-12`
Comment: @hugocsl me desculpe não ter mencionado, mas eu não sei se você tem acompanhado os comentários mas eu já resolvi o problema. Eu estou usando o `admin-lte`
Comment: Qual Bootstrap?
Comment: Qual versão do Bootstrap está usando? Vc tem algum CSS nessa tabela além do default do Bootstrap? Se tiver inclua na pergunta ok.
Comment: Ah legal então! Tente criar uma resposta para sua própria pergunta. Dessa forma em depois dias se não me engano vc pode marcar sua própria resposta como aceita e ela não fica mais como pendente de resposta no site.
Comment: Muito obrigado @hugocsl
Answer: Olá @wlandyband, a correção mais certa para este tipo de caso é .clearfix para as divisórias ou elementos pais que herdam os .col, como os .col, possui atributo float: left; ele faz que flutue o elemento numa segunda camada e como o elemento que herda o background, creio que no seu caso o .invoice ou .content ele não tinha o atributo clear: both; fazendo que quando você diminuísse a resolução saindo da resolução da class .col-lg ele perdesse então o atributo de flutuação fazendo esse pequeno bug.
Para entender melhor segue link da documentação do clearfix no Bootstrap v4, porém também tem a explicação nas versões anteriores.
Segue também um print visualmente do uso em prática.
Sem .clearfix

Com .clearfix

Outro link que irá ajudar a entender melhor o por que do uso do .clearfix, que é apenas um atributo do css clear: both; para corrigir esse problema.
Exemplo do atributo clear:both;
Answer: Por eu está usando o admin-lte tive que tirar a classe col-lg-12 ficou assim

Lista de Restaurantes

                      Nome
                      Ano
                      Ação

                      {{ restaurant.name }}
                      {{ restaurant.category }}

                        botão


Print something in a tlp file if a field isnt empty

Question: I need to print some html in a node tpl file if a certain field is not empty. The follwing is giving me a white screen:
<?php if (!empty($content['field_hotel_sat_nav'])) {
                        print '
The field is not empty
'
            }
?>

Comment: The white screen would surely be caused by the missing semi-colon at the end of the `print` statement...nothing wrong with the call to `empty()`
Answer: Try this code:
<?php
  if ($content['field_hotel_sat_nav'] != '') {

    //Do something

  }
?>


Problem loading Django fixture: IntegrityError: (1062, "Duplicate entry '4' for key 'user_id'")

Question: I used the following commands to generate 2 fixtures:
./manage.py dumpdata --format=json --indent=4 --natural auth.User > fixtures/user.json
./manage.py dumpdata --format=json --indent=4 --natural --exclude=contenttypes --exclude=auth > fixtures/full.json

I've got the following fixture named user.json:
[
    {
        "pk": 4,
        "model": "auth.user",
        "fields": {
            "username": "foo",
            "first_name": "Se\u00e1n",
            "last_name": "Hayes",
            "is_active": true,
            "is_superuser": true,
            "is_staff": true,
            "last_login": "2010-09-27 21:57:45",
            "groups": [],
            "user_permissions": [],
            "password": "!",
            "email": "firstname.lastname@example.com",
            "date_joined": "2010-09-27 21:57:45"
        }
    }
]

and the following fixture named full.json:
[
    {
        "pk": "72a75887b4a0ce06a61f9183fe1c0e15",
        "model": "sessions.session",
        "fields": {
            "expire_date": "2010-10-11 21:57:45",
            "session_data": "gAJ9cQEoVRJfYXV0aF91c2VyX2JhY2tlbmRxAlUOZmIuYXV0aC5GYkF1dGhxA1UNX2F1dGhfdXNl\ncl9pZHEEigEEdS5hOGZlODU0MmRjYmUwNmEzODIwNjhiYzYyODc2MWQxZA==\n"
        }
    },
    {
        "pk": 1,
        "model": "sites.site",
        "fields": {
            "domain": "example.com",
            "name": "example.com"
        }
    },
    {
        "pk": 2,
        "model": "common.userprofile",
        "fields": {
            "money": 10,
            "energy": 10,
            "experience": 0,
            "stamina": 10,
            "health": 10,
            "user": 4
        }
    },
    {
        "pk": 2,
        "model": "missions.missionprofile",
        "fields": {
            "user": 4,
            "last_area_viewed": null
        }
    },
    {
        "pk": 1,
        "model": "fb.facebookuser",
        "fields": {
            "updated": "2010-09-27 21:57:45",
            "uid": "24411841",
            "created": "2010-09-27 21:57:45",
            "access_token": "foo",
            "url": "http://www.facebook.com/profile.php?id=24411841",
            "user": 4,
            "img_url": null,
            "name": "Se\u00e1n Hayes"
        }
    }
]

Running the following commands (in either order):
./manage.py loaddata user
./manage.py loaddata full

raises the following exception:
Problem installing fixture '/projectpath/fixtures/full.json': Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.6/django/core/management/commands/loaddata.py", line 169, in handle
    obj.save(using=using)
  File "/usr/lib/pymodules/python2.6/django/core/serializers/base.py", line 165, in save
    models.Model.save_base(self.object, using=using, raw=True)
  File "/usr/lib/pymodules/python2.6/django/db/models/base.py", line 528, in save_base
    result = manager._insert(values, return_id=update_pk, using=using)
  File "/usr/lib/pymodules/python2.6/django/db/models/manager.py", line 195, in _insert
    return insert_query(self.model, values, **kwargs)
  File "/usr/lib/pymodules/python2.6/django/db/models/query.py", line 1479, in insert_query
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/usr/lib/pymodules/python2.6/django/db/models/sql/compiler.py", line 783, in execute_sql
    cursor = super(SQLInsertCompiler, self).execute_sql(None)
  File "/usr/lib/pymodules/python2.6/django/db/models/sql/compiler.py", line 727, in execute_sql
    cursor.execute(sql, params)
  File "/usr/lib/pymodules/python2.6/django/db/backends/util.py", line 15, in execute
    return self.cursor.execute(sql, params)
  File "/usr/lib/pymodules/python2.6/django/db/backends/mysql/base.py", line 86, in execute
    return self.cursor.execute(query, args)
  File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 166, in execute
    self.errorhandler(self, exc, value)
  File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py", line 35, in defaulterrorhandler
    raise errorclass, errorvalue
IntegrityError: (1062, "Duplicate entry '4' for key 'user_id'")

Any ideas on what's going on? I'm aware there's a problem with forward references in MySQL, but that shouldn't matter if the User object with id 4 is being installed before the fixtures that contain a foreign key to it, right?
Comment: do you have any signal that creates entry in `common.userprofile` as soon as the user is created ?
Comment: Do you have any ``unique`` settings set on your models ?
Comment: I also tried splitting up full.json into smaller fixtures and installed them one at a time. As soon as a foreign key to User is present, the error is generated.
Comment: Can you post the code for your models here?
Comment: Ashok, yup, that's it. I don't suppose there's anyway to get the fixtures to overwrite the signal generated models.
Comment: @Ashok: Your comment saved me! Thanks.
Answer: As per Ashok's comment, when I had the same problem, it was solved by changing my signal handler to check for whether it is running in "raw" mode which apparently means a fixture is being loaded:
def create_user_profile(sender, instance, created, **kwargs):
    if created and not kwargs.get('raw', False):
        UserProfile.objects.create(user=instance)

See How do I prevent fixtures from conflicting with django post_save signal code?
Answer: Static fixture of Django is an ANTI-PATTERN, that is the reason you are having this kind of problem. I suggest you to use some library that generate these fixtures for you, including the ID naturally.
I suggest you Dynamic Dynamic Fixture


view to view in HMVC Code Igniter

Question: i have some problem with hmvc in codeigniter because im newbie with hmvc.
i have a template bootstrap with ci  , so the problem like i not able to show my view
my view name index.php in directory "theme"  :
<!DOCTYPE html>

    <?php echo $this->load->view('theme/header') ?>

    <?php echo $this->load->view('theme/navbar') ?>

        <?php $this->load->view($content) ?>

<?php echo $this->load->view('theme/footer') ?>

My Controller name dashboard in directory "theme" :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Dashboard extends CI_Controller{

    function __construct()
    {
        parent::__construct();

    }
    function index()
    {
            $data['content'] = 'dashboard';
            return $this->load->view('theme/index', $data);
    }
}

i the error is in  :
<?php echo $this->load->view('theme/navbar') ?>

and
<?php echo $this->load->view('theme/footer') ?>

the error Says :
"A PHP Error was encountered"
"Severity: 4096"
"Message:  Object of class MY_Loader could not be converted to string"
"Filename: theme/index.php"
"Line Number : 8"
Please help
Answer: dont use echo
just $this->load->view('viewfile')
example if your view file is on application/view/theme/footer then it is
$this->load->view('theme/footer')

if you want to convert it to string you can pass a boolean true in Third parameter$this->load->view('theme/footer',array(),true)
Please refer to this codeigniter's view's documentation

view to view in HMVC Code Igniter


Postgresql JDBC connection via eclipse not happening

Question: I am trying to do a simple connection test to a postgresql database, the code is working well  but I am getting the following message:
PostgreSQL 9.0 JDBC4 (build 802)
Found in: jar:file:/C:/thales/Dropbox/study/java/jars/postgresql-9.0-802.jdbc4.jar!/org/postgresql/Driver.class
I am using the jdbc file provided by the address http://jdbc.postgresql.org/download.html
Following, the code:
<code>import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class connector {
  public static void main(String[] argv) {
  System.out.println("Checking if Driver is registered with DriverManager.");

  try {
    Class.forName("org.postgresql.Driver");
  } catch (ClassNotFoundException cnfe) {
    System.out.println("Couldn't find the driver!");
    System.out.println("Let's print a stack trace, and exit.");
    cnfe.printStackTrace();
    System.exit(1);
  }

  System.out.println("Registered the driver ok, so let's make a connection.");

  Connection c = null;

  try {
    // The second and third arguments are the username and password,
    // respectively. They should be whatever is necessary to connect
    // to the database.
    c = DriverManager.getConnection("jdbc:postgresql://localserver/test","ping", "pong");
  } catch (SQLException se) {
    System.out.println("Couldn't connect: print out a stack trace and exit.");
    se.printStackTrace();
    System.exit(1);
  }

  if (c != null)
    System.out.println("Hooray! We connected to the database!");
  else
    System.out.println("We should never get here.");
  }
}
</code>
Comment: Your question is confusing.  You're saying that it's showing that message... but according to the message that you gave us, it's just saying that it found the JDBC driver... which isn't a problem...
Comment: Well, i was expecting any output given by any System.out.println and im not sure what could be wrong.
Comment: Have you tried breakpoints in an IDE?  Perhaps you have a connection to your database that is taking a significant amount of time for some reason etc...
Comment: Not that either, im trying under a local database, even with invalid/valid user,pass,host, i still getting the same result described at the post.
Comment: Show full output of your program's execution, and the command line with which you invoked it (eg `java -classpath .... -jar .....`). This looks like a simple misconfiguration issue.
Answer: thanks for all feedback but i manage to solve the problem reinstallign eclipse (?? )
using the same code, and the same jdbc driver, the code described in the question worked.


Using AM-GM to prove $\lim_{p\to 0}$ of the $p$-mean is equal to the GM.

Question: The problem in question is.

Let $a_1,a_2,...,a_n>0$. Prove that
   $${\lim_{p\to 0} \left(\frac{{a_1}^p+{a_2}^p+\cdots+{a_n}^p}{n}\right)^{1/p}}=(a_1a_2\cdots a_n)^{1/n}$$ i.e. show that as $p$ approches $0$, the $p$-mean approaches the geometric mean.

The direct proof of this is simple and can be done using logorithms. However when I started this problem I had the following idea:
Notice first that by the $AM-GM$ inequality,
$$\frac{a_1^p+\cdots+a_n^p}{n}\geq(a_1a_2\cdots a_n)^{p/n}$$ Thus, $$\left(\frac{a_1^p+\cdots+a_n^p}{n}\right)^{1/p}\geq(a_1a_2...a_n)^{1/n}$$ Equality is achieved in the above iff $a_1^p=a_2^p=\cdots=a_n^p$. But when $p$ approaches $0$, $a_1^p=a_2^p=\cdots=a_n^p=1$. Of course this does not prove the problem in question but I am trying to use this idea to construct a proof but it is much trickier that expected. Any ideas? The most promising idea I had so far was to create a subsequence of the p-mean and prove that it is decreasing and the geometric mean is the infinimum of this subsequence. But that is very hard to do.
So I guess my main question is:
Could we find some special case where if the terms $a_1,a_2,\cdots,a_n$ approached some $x$ in some limit $L$ then, $L(AM)$=$L(GM)$?
Comment: I know a proof by rearrangement!
Comment: @gimusi I did not think of that that sounds very interesting/counterintuitive
Comment: Ah ok! What are you looking for exactly?
Comment: @gismusi thinking of a way to complete the proof I started in the question.
Answer: I have no proof using AM-GM alone.  But this answer may be useful.
We can prove a more general result.  Let $a_1,a_2,\ldots,a_n>0$ and $w_1,w_2,\ldots,w_n> 0$ be such that $w_1+w_2+\ldots+w_n=1$ (in your setting $w_1=w_2=\ldots=w_n=1/n$).  Define the power mean
$$M(p)=\left(w_1a_1^p+w_2a_2^p+\ldots +w_na_n^p\right)^{1/p}$$
for all $p\ne0$.  We want to show that $\lim_{p\to 0}M(p)$ exists and equals the geometric mean $G=a_1^{w_1}a_2^{w_2}\cdots a_n^{w_n}$.
Let $b_i=\ln a_i$.  Then $$a_i^p=\exp(pb_i)=1+pb_i+O(p^2).$$
That is
$$\sum_{i=1}^nw_ia_i^p=1+p\sum_{i=1}^nw_ib_i+O(p^2).$$
Therefore
$$M(p)=\left(\sum_{i=1}^nw_ia_i^p\right)^{1/p}=\left(1+p\sum_{i=1}^nw_ib_i+O(p^2)\right)^{1/p}.$$
Note that $\lim_{h\to 0}(1+ht)^{1/h}=e^t$.  As $p\to 0$, we get
$$M(p)\to \exp\left(\sum_{i=1}^nw_ib_i\right)=\prod_{i=1}^na_i^{w_i}=G.$$
So it makes sense to define $M(0)=G$.  With this definition, $M:\Bbb R\to \Bbb R$ is a non-decreasing function (and it is not strictly increasing iff $a_1=a_2=\ldots=a_n$).  You can also show that $\lim_{p\to\infty}M(p)=\max_{i=1}^na_i$ and $\lim_{p\to-\infty}M(p)=\min_{i=1}^na_i$.
Answer: Let $a_k=\exp(b_k)$. By homogeneity you may assume $\prod a_k=1$, or $\sum b_k=0$, then prove
$$ \lim_{p\to 0^+}\left(\frac{1}{n}\sum_{k=1}^{n}e^{pb_k}\right)^{1/p} = 1. $$
As long as $p\to 0^+$ we have
$$ e^{pb} = 1+ pb + o(p), $$
hence
$$ \frac{1}{n}\sum_{k=1}^{n}e^{pb_k} = 1+\frac{p}{n}\sum_{k=1}^{n}b_k + o(p)=1+o(p) $$
and
$$ \left(\frac{1}{n}\sum_{k=1}^{n}e^{pb_k}\right)^{1/p} = \exp\left[\frac{\log(1+o(p))}{p}\right]=\exp\left[\frac{o(p)}{p}\right]=\exp\left[o(1)\right] $$
converges to $e^0=1$.


What naming conventions should I follow?

Question: I am a Drupal CMS beginner, studying this CMS for several days, also through the Drupal module development pages.
I still have no clue on the proper function names, database table names, and relationship between .module, .info and so on.
How are names mapped and what is the sequence of functions that are called?
Answer: I'm a bit surprised that you haven't found anything on the internet that could answer your questions. Here is an article about coding standards for Drupal.
Anyway, here are several things I always do with naming, functions and directories (that doesn't mean it's the best conventions):

The only directory you should work in is ./sites (please never ever edit something in the other directories).
The contribute modules you download should be placed in ./sites/all/modules/contrib
The custom modules that you develop yourself should be placed in ./sites/all/modules/custom
When you create a custom module, chose a simple and suitable name of it, preceded by the name of your project (better), for example myproject_blog.
The .module and .info files should have the same name as your module's, for example myproject_blog.module and myproject_blog.info. It will automatically make the relationship between them.
All the functions that appear in your .module file should be named by your module's name, for example myproject_blog_revision_publish().
If your custom module needs a table in your database, the name of your module has to show up somewhere, for example $schema['myproject_blog']. If you need more than one table, keep the prefix and add some explicit suffix.
Idem for the custom themes in ./sites/all/themes.

If I forgot something, just ask ;)
Comment: Thanks for the article link.  I think, just like other programmers who get start in developing using Drupal, I am quite frustrated about how all the names are used.  For example the $schema['myproject_blog'], my immediate question would be: where is it placed?  Which function will use this variable or call this function? How is it being used?  I also get mad when I saw this: revisioning_action_revision_trigger() what the heck is this?  Thanks for your response.  It helps.
Comment: Mh I see. In my opinion, you'd better start at the beginning, and read a lot about Drupal, its UI, its contribute modules system, its entities (very important),... And only after, you can start to read about developing your custom module/theme, trying thing more and more complicated (don't bother you with the custom DB tables too soon). You will naturally understand the naming for the "hooks", that are just functions preceded by the word itself "hook" and that you have to replace by the name of your module/theme in which you work, simply ;)
Answer: From the sound of the question you are looking for a simple overview to help you get started. I would suggest that rather than initially tracing the way that the (labyrinthian) drupal core passes requests through functions, you should start with looking at how simple modules and themes connect to it to get an idea of the larger design pattern. Once you have an idea of the concepts and terminology used, the commented code examples are invaluable for this, giving examples of things you can do, and describing how to accomplish it.
Basically, as Djouuuuh points out, you can safely leave drupal core to do its thing. That is why you will work exclusively within the sites directory. Your interaction as a developer is to configure the installation to behave how you you would like (site building), create themes to customise display (theming) and create modules (development) to match very site-specific functionality. Always look to existing, supported modules first, it will save you a lot of time, even if must add to their functionality with your own module.
To understand the naming conventions for files and functions used in modules and themes, you will need to learn about the hook system and then look to the examples and the API(via google) to understand the uses of those hooks. More than likely you will rely heavily on just a few hooks to start with, for example hook_menu, hook_node_load, hook_form_alter (forms are a big subject).
Drupal.org holds extensive documentation about development methods.
Also Jeff Eaton of lullabot looks to have created a good slideshow on the subject of drupal development, which might be worth a click through.
Comment: Thanks for your response.  I sort of understand the hook system (not very much) because I am coming from Wordpress development.  And you are right, I am looking for an easy understanding of this "Drupal" thing.  Your resources are very helpful and thank you very much for your response.


C# Microsoft Bot Framework -Integrate LUIS + QNA +Graph API

Question: I have a Bot(using Microsoft Bot Framework) that has a QNA Service And Microsoft Graph API integrated with LUIS.

The LUIS model acts as a dispatcher to QNA and Graph API.
Based on the LUIS Intent, it gets routed to either the QNA or Graph API.
Corresponding to each QNA question there is an intent configured in LUIS and for each API ,there is an intent too

Problem: I have more than 50 intents inside LUIS.I want to handle all the intents related to QNA with a generic piece of code . I want to Optimise the Code.
Also I want to understand from the Intent itself whether it should go to QNA or Graph API
Question:Is there an efficient way in which I can efficiently route from  LUIS Model to QNA and Graph API
Comment: Can you show the code you are using to do routing?
Comment: @GeethuSuresh are you using v3 or v4 of the bot framework to build your bot?
Comment: @Zeryth Im using v3
Answer: Sounds like you essentially want to create an app that follows the architecture of building a LUIS app with different intents. From within each intent, you could code your bot to call information you have stored in QnAMaker or the MS Graph API.
To get started, you could follow this tutorial: Integrate QnA Maker and LUIS to distribute your knowledge base.
(Note: in this tutorial there is a small documentation bug regarding the endpoint to query QnAMaker
It says in the docs:
var client = new RestClient( qnaServiceHostName + "/qnamaker/knowledgebases/" + knowledgeBaseId + "/generateAnswer");
make sure you DELETE "/qnamaker", as it is accidentally duplicated--it's already included in qnaServiceHostName)
And I don't know what it is specifically you want to accomplish with the Graph API, but there are multiple examples linked in the MS Graph GitHub here and docs on MS Graph overall here, which should help you get started on the right path as well.


Configurar HTTPS em WebApi

Question: Fiz um Web Service utilizando WebApi MVC5, com Visual Studio 2017. Está funcionando, mas como faço para utilizar HTTPS ao invés de HTTP? Alguém tem algum material pra eu pesquisar? Encontrei algumas coisas mas com WCF e não com Web Api.
Answer: Segue link com 2 materiais bem interessantes sobre o assunto:
Working with SSL in Web API
https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/working-with-ssl-in-web-api
e Using SSL in ASP.NET Web API
http://www.codeguru.com/csharp/.net/using-ssl-in-asp.net-web-api.htm
Abs.
Comment: Obrigado @Rodolpho!

Configurar HTTPS em WebApi


Are nodes outside the markov blanket unconditionally independent?

Question: Apologies if my question is deeply flawed, I've been working through a lot of material in the past few weeks and have a few blind spots here and there.
On one level my question is this - given a bayesian network with all directed edges, what is the set of nodes X and Y such that P(Y) = P(Y|X)
My intuition says that this is all Y,X such that Y not in the markov blanket of X.  My rationale is that when performing marginalization, for any given term in the marginalization sum, values have been chosen for every node in the markov blanket, rendering the terms chosen for nodes outside the markov blanket irrelevant.
Am I mistaken?
Much thanks.
Answer: Consider the bayesian network: X -> Y -> Z
$X$ is out of the Markov blanket of $Z$ (which is $\{Y,Z\}$), yet $Z$ (unconditionally) depends on $X$.
On the other hand, d-separation is what you are looking for. From Pearl's Causality book, you can read:

d-separation is a criterion for deciding, from a given a causal graph, whether a set X of variables is independent of another set Y, given a third set Z.

You can use an empty conditionning set to check whether two variables are (unconditionally) independent. The Bayes-Ball algorithm is a practical algorithm based on this criterion for deciding whether or not two variables are independent.


Requisição jquery dando erro

Question: pessoal eu estou com o seguinte problema eu tenho uma pagina onde coloca os comentários tudo certinho ai carrega até 5 comentários até aqui tudo funciona o que ocorre é que nesses 5 comentários tem um botão que você clica e aparece em fadeIn o campo para por resposta até aqui tudo certo, mas quando clico em mostrar mais comentários ele pucha de outra pagina e esses que vem quando é clico em responder não funciona não sei por que.
código fonte:
javascript
$('.resposta').click(function(){
        var id = $(this).children('input').val();
        alert(id);
        $(this).fadeOut("fast");
        $(this).parents('.coment').find('.resp').fadeIn("slow");

        $('form[name="responder"]').submit(function(){
           return false;
        });

        return false;
    });

página php onde já exibe os 5 comentários
<?php
                       /*
                     **********************************************
                     **********************************************
                     ***********Função para exibição dos***********
                     ****************comentarios*******************
                     **********************************************/

                        $comentar = new Read;
                  $comentar ->ExeRead('coment', 'WHERE video = :video ORDER BY id DESC LIMIT 5', "video={$sei[1]}");
                  foreach ($comentar->getResult() as $big):
                      extract($big);
                  $image = new Read;
                  $image ->ExeRead('users', 'WHERE id = :id', "id={$big['user']}");
                  foreach ($image->getResult() as $imx)
                      extract ($imx);
                /*
                     **********************************************
                     **********************************************
                     *********Fim da função de exibição************
                     ***************de comentarios*****************
                     **********************************************/
                  echo "<input type='text' hidden='hidden' value='{$link}' id='link'>";
                  ?>

                                <?php

                    if($foto == "" || $foto == "uploads/"):
                        echo  "";
                    else:
                        echo  "";
                    endif;
                    ?>

Comentado por: <?=$nome?> Em:   <?=$date?> As:  <?=$hora?>

<?=nl2br($comentario)?>

Responder<input type='hidden' value='<?=$big[id] ?>' name='idcoment'>

                           <form method='post'><textarea></textarea>

                               <input class='btn btn-green' type='submit' value='responder' name='responder'>
                           </form>

                        <?php
                    endforeach;

                    endforeach;

                    endforeach;
                    ?>

Mostar mais comentários

pagina onde é puchado o mostrar mais
<?php
include '../_app/Config.inc.php';

// Função do jquery para listar os comentários
if(filter_input(INPUT_POST, 'acao') ==  'comentarios'){

    $video = filter_input(INPUT_POST, 'video');
    $numcom = filter_input(INPUT_POST, 'numcom');

    $readCount = new Read ();
    $readCount ->ExeRead('coment', "WHERE video = :video LIMIT $numcom,4", "video={$video}");

    echo $readCount->getRowCount();

}

// Função do jquery para exibir mais comentários

if(filter_input(INPUT_POST, 'acao') ==  'morecoment'){
    $video = filter_input(INPUT_POST, 'video');
    $numcom = filter_input(INPUT_POST, 'numcom');

    $readCount = new Read ();

    $readCount ->FullRead("SELECT * FROM coment WHERE video = :video ORDER BY id DESC LIMIT $numcom,3", "video={$video}" );

        foreach ($readCount->getResult() as $cat):
        extract($cat);
        $image = new Read;
                  $image ->ExeRead('users', 'WHERE id = :id', "id={$cat['user']}");

                  foreach ($image->getResult() as $imx):
                      extract ($imx);
                  echo "
";
                    if($foto == "" || $foto == "uploads/"):
                        echo  "";
                    else:
                        echo  "";
                    endif;
                       ?>

Comentado por: <?=$nome?> Em:   <?=$date?> As:  <?=$hora?>

<?=nl2br($comentario)?>

Responder<input type='hidden' value='<?=$big[id] ?>' name='idcoment'>

                           <form name='responder' method='post'><textarea></textarea>

                               <input class='btn btn-green' type='button' value='responder' name='responder'>
                           </form>

                        <?php

                   endforeach;
               endforeach;
}

Answer: Quando você executa o jQuery lá no início, ele encontra todas as divs com classe "resposta" e aplica os eventos que você programou na função de resposta, certo?
Só que quando você carrega mais comentários, ele não faz isso de novo, por que ele já fez uma vez (nos primeiros 5 comentários que já estavam na página).
Ou seja: você precisa executar esse script nas novas respostas.
Mas tem um problema
Se você executar esse mesmo seletor, ele vai colocar dois eventos nos primeiros cinco comentários, por que o jQuery usa o setEventListener para registrar o evento de clique. Ou seja, ele vai executar duas vezes e ocupar mais memória à toa, além de que pode dar dor de cabeça mais tarde. Para resolver isso, cria uma função que faça duas coisas: retire os eventos todos dos objetos e depois coloque de novo.
function addEventosRespostas() {
   $('.resposta')
       .off("click")
       .on("click", function(){
         ...
       });
}

Outra coisa
Evite usar .click() por que ele está pra sair do jQuery mais atual (deve ter saído já, tem tempo que ouço isso). O padrão hoje em dia é .on()
Referências
http://api.jquery.com/off/
http://api.jquery.com/on/

Requisição jquery dando erro


Prepare Drupal to be multilingual in the future

Question: I am building a Drupal website with only one language (Italian first) but there might be more languages in the future. This website will use also DrupalGap to create an app.
Editors don't need backend Italian interface.
So these are the scenarios I thought about:
Case one:

Install Drupal with English as default.
I will NOT enable Locale module.
All machine names (Content types, vocabularies, views etc..) will be in English.
Labels will in Italian.
Content and term will be created in Italian.
Views page title and views block title will be in Italian.

After few months the website may be translated in English so, the steps will be:

Enable locale.
Install Italian language.
Install Entity translation i18n etc...
Make entities translatable.
Bulk update all nodes and terms to be Italian as original language.
Revert all Italian labels into English and use string translation to translate it in Italian.

Case two:

Install Drupal with Italian as default
All machine names (Content types, vocabularies, views etc..) will be in English.
Labels will in Italian.
Content and term will be created in Italian.
Views page title and views block title will be in Italian.

After few months the website may be translated in English so, the steps will be:

Install Entity translation i18n etc...
Make entities translatable.
Bulk update all nodes and terms to be Italian as original language.
Translate strings from Italian to English.

In terms of extendability and usability, which approach should I use at the beginning?
Let me know if you have any question.
Thanks in advance.
Answer: I think the best approach is something similar to your first one.

Install Drupal in English as defaults
Configure your environment for multilingual at the beginning.
Enable Italian Language
Set Italian to default language
When you create entities(Users, Content types, Etc..), configure everything at the beginning. Otherwise you might forget things later.
Enable multilingual support only for other pages excepting admin pages @ admin/config/regional/i18n/select (Under "ENABLE FOR SPECIFIC PAGES" set all pages except "admin/*")
Then do everything in Italian for Italian until you need English language stuffs.

Good luck.


Using HashMaps Java

Question: I'm writing a method that allows me to count how many times an element of type String shows up in a LinkedList of type Strings. my code shown below does not work. I keep getting index out of bounds in the line i commented on down below. Can't seem to find the bug
public int findDuplicate (LinkedList<String> e) {
int j = 1;
LinkedList<String> test = e;
while (!test.isEmpty()){
    test = e;
    String value = test.pop();
    //Screws up here when i = 6
    for(int i =0; i<=test.size() && test.get(i)!=null; i++){
        String value3 = test.get(i);
        if(e.get(i).equals(value) && i<=test.size()){
            String value2 = test.get(i);
            j++;
            String Duplicate = e.get(i);
            e.remove(i);
        }
    }
    System.out.println(value + " is listed " + j + " times");

}
return j;
}

using hashmaps.. still doesn't work
public void findDuplicate (LinkedList e) {

    Map<String,Integer> counts = new HashMap<String,Integer>();

    while(!e.isEmpty()){
        String value = e.pop();
        for(int i =0; i<e.size(); i++){
            counts.put(value, i);
        }
    }
    System.out.println(counts.toString());
}

My code should go through the linked list find out how many times an element within the list appears and deletes duplicates from the list at the same time. Then prints the element and the number of times it appears in the list. I posted about this last night but didn't get a response yet. Sorry for the repost.
Answer: You are running off the end of the list.  Change
for(int i =0; i<=test.size() && test.get(i)!=null; i++){

to
for(int i =0; i< test.size() && test.get(i)!=null; i++){

Valid indexes for a List (or an array) are 0 through size() - 1.
Answer: Regarding your hashmap example to count the duplicates:
@Test
public void countOccurrences() {
    LinkedList<String> strings = new LinkedList<String>(){{
        add("Fred");
        add("Fred");
        add("Joe");
        add("Mary");
        add("Mary");
        add("Mary");
    }};

    Map<String,Integer> count = count(strings,new HashMap<String,Integer>());
    System.out.println("count = " + count);
}

private Map<String, Integer> count(List<String> strings, Map<String, Integer> runningCount) {
    if(strings.isEmpty()) {
        return runningCount;
    }
    String current = strings.get(0);
    int startingSize = strings.size();
    while(strings.contains(current)) {
        strings.remove(current);
    }
    runningCount.put(current, startingSize - strings.size());
    return count(strings,runningCount);
}

If you want the original strings list preserved you could do
    Map<String,Integer> count = count(new LinkedList<String>(strings),new HashMap<String,Integer>());
    System.out.println("strings = " + strings);
    System.out.println("count = " + count);

Answer: Check out google's guava collections which has a perfect class for maintaining a map and getting a count:
https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap
Multiset<String> wordsMultiset = HashMultiset.create();
wordsMultiset.addAll(words);
// now we can use wordsMultiset.count(String) to find the count of a word

Answer: This doesn't affect your out of bounds issue, but you are removing elements from your list while still evaluating it. If you remove an element, you should call i-- afterwards, or you skip the next entity (which is re-indexed) for evaluation.
Also of note regarding your code, I see you are trying to make a copy of your list, but standard assignment means test and e both point to the same instance.  You need to use Collections.copy() see this SO thread on how to use the class.
Answer: I hope you realize what the test = e statement is doing. After this statement executes both test and e refer to the same object.
If anyone of them modifies the list, the other sees it as they both are looking at the same object.
If this is not intended you need to clone the list before assigning it to another list reference.

Using HashMaps Java


Weird behaviour in toy RNN (Keras, LSTM)

Question: I'm trying to learn more about RNNs and I'm tackling a toy problem. I'm generating some data that has a pattern, two 1s followed by three 0s which keeps repeating infinitely without any noise. So my master data is something like [1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 ... ]
Then I slide a window of N timesteps over the data and feed this into an LSTM, asking it to predict the next value. I'm treating this as a binary classification problem.
model = tf.keras.models.Sequential([
    tf.keras.layers.LSTM(4, input_shape=(None, 1)),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

model.fit(train_gen, epochs=EPOCHS)

All is well, the model reaches 100% accuracy and near 0 loss pretty quickly. However, unexpected things start happening when I feed in sequences of different lengths (drawn from the same master data).
for i in range(15):
    TEST_WINDOW_SIZE = WINDOW_SIZE + i

    longer_data_gen = TimeseriesGenerator(train_data[:2000], train_data[:2000], TEST_WINDOW_SIZE, batch_size=2000)

    [loss, acc] = model.evaluate(longer_data_gen)
    if acc < 1.0:
        print('For i={} accuracy is {}'.format(i, acc))

The output will be something like
i = 0, acc = 1.0
i = 1, acc = 0.6
i = 2, acc = 0.2
i = 3, acc = 0.2
i = 4, acc = 0.6
i = 5, acc = 1.0
...

So basically the network learned the pattern, but it isn't syncing it to the input, it's off-phase.
Note:

In my experiments, adding dropout=0.15 to the LSTM sometimes fixes the problem,
depending on the run, however the reported accuracy on the training set doesn't get to 100%, despite me getting 100% accuracy on all my variable length test data.

I also tried lowering the number of hidden units in the LSTM but it
doesn't seem to do the job

Sometimes it generalizes even without dropout, but most of the time it doesn't

I kind of get the feeling I'm doing something wrong here, it seems like it's pretty hard to generalize on such a simple problem. Am I approaching this wrong ?
The full code is here.
Answer: It seems LSTM hasn't really learnt the short term pattern, which is the only pattern. If you see carefully, it only needs last 3 inputs to "guess", or in your case "predict" (because you used sigmoid) the next number. For instance
i/p    o/p
11000 - 1
01100 - 0
00110 - 0
00011 - 0
10001 - 1

But your LSTM is relying on values that are even further from last 3 digits to predict the next digit. A simple fix of
TEST_WINDOW_SIZE = WINDOW_SIZE*10 + i

should give you an accuracy of 1, irrespective of value of i
Also, the model is overfit. If you get an accuracy of 0.9<acc<1.0 by 5th iteration, then probably the fix won't be needed
Comment: yes, oversight from me, I thought `training_example_length` = 32. That said, `TEST_WINDOW_SIZE = WINDOW_SIZE*10 + i` still fixes the problem. Therefore your model is overfitting because training acc is 1 and testing isn't. Try with changing batch size and learning rate. Also, use `optimizer=optimizer` instead of `'adam'`
Comment: I don't quite understand. `training_example_length == WINDOW_SIZE`. Unless you mean pattern length ? My pattern length is 5 and WINDOW_SIZE=10. How is WINDOW_SIZE much larger ? In practice, if I know the length of my pattern then what use is an RNN to me? The network should learn the pattern and I feel like I give it enough context for it to be able to.


Definir placeholder com variável PHP

Question: Tenho um Formulário de Cadastro/pesquisa e agora estou adicionando a opção para editar os campos. Para o funcionário não ficar confuso, eu queria definir o placeholder com uma variável PHP, através do echo. É possível fazer isso?

    <?php if ($id != '') { ?>
        <input type="hidden" name="id" value="<?php echo $id; ?>" />ID: <?php echo $id; ?>
    <?php } ?>
    <?php echo $cliente; ?>
    <input type="text" name="cliente" maxlength="50" placeholder="<?php echo $cliente; ?>" value="<?php echo $cliente; ?>"/>

    <input type="text" name="produto" maxlength="25" placeholder="PRODUTO" value="<?php echo $produto; ?>"/>

    <input type="text" name="solicitante" maxlength="50" placeholder="SOLICITANTE" value="<?php echo $solicitante; ?>"/>

    <input type="text" name="status" maxlength="25" placeholder="STATUS" value="<?php echo $status; ?>"/>

    <input type="text" name="incluiu" maxlength="25" placeholder="INCLUIU" value="<?php echo $incluiu; ?>"/>

    <input id="submit" class="button_text" type="submit" name="submit" value="Cadastrar" />

Comment: Thiago a pergunta está pouco clara... Quer fazer isso em PHP para ser aplicado a um elemento HTML? Que tipo de elemento é? um input? Pode juntar um exemplo do código que tem e como quer que seja apresentado ao funcionário
Comment: Você quer setar ou pegar o placeholder?
Comment: Se o que você quer é um jeito de resetar o valor para um valor anterior, o caminho é usar o campo _value_ e o método _reset_ do form, ou um _data-parameter_. (ou até _labels_ mesmo)
Comment: Perdão pela pergunta pouco clara, atualizei a pergunta com meu código, tentei dar echo no placeholder mas ele saiu em branco.
Comment: Earendul, buscar no meu banco.
Comment: Ok, muito obrigado a todas as respostas ;)
Comment: eu entendi, eu perguntei se era possível fazer isso e a resposta foi sim. grato a todos pelas respostas.
Answer: É possível sim:
<input type="text" placehold="<?php  echo 'palavra'; ?>" />

Comment: já tentei dessa forma e resultado vem em branco.
Comment: Provavelmente a variável `$cliente` está vindo em branco. O `value` também está em branco?
Comment: Não, o value está correto.
Answer: Só faz sentido usar isto se a variável for diferente do campo, pois o placeholder só aparece com campo vazio. E do jeito que você está fazendo, o placeholder só vai ser usado vazio mesmo. Provavelmente teria que ser feito algo neste sentido:
<input type="text" name="cliente" maxlength="50" placeholder="<?php echo 'CLIENTE'; ?>"
   value="<?php echo $cliente; ?>"/>

Ou mesmo assim:
$pla_cliente = 'Cliente';
... seu código PHP ...

<input type="text" name="cliente" maxlength="50" placeholder="<?php echo $pla_cliente; ?>"
   value="<?php echo $cliente; ?>"/>

mas sempre usando variáveis diferentes para o placeholder e para o campo.

Se você estiver tentando usar o valor para um reset dos campos, basta usar o reset do próprio form para voltar o valor anterior
Comment: O placeholder é o valor de exibição quando o campo está vazio, nada mais nada menos. Se quiser usar o valor pra um reset do form, ou use o value, ou use um data-parameter customizado.
Comment: Não necessariamente.
Vai que ele quer deixar o placeholder sendo o nome do usuário, pra ficar fácil dele entender caso ele apague ou queira trocar o valor. O problema, é que ele não deixou muito claro o objetivo dele, assim não teria como darmos um exemplo bem feito.
Comment: Eu quero fazer um UPDATE no banco e quero que placeholder seja o valor que eu pretendo mudar.
Comment: @Thiago nao tem problema de onde você vai pegar o placeholder. Só não pode ser o mesmo valor do campo, senão não faz o mínimo sentido.
Comment: Rodrigo Coelho, Exatamente isso.
Comment: Thiago, o placeholder é apenas uma exibição para o usuário identificar o que pode ser digitado no campo. Ele não vai influenciar em nada no POST do formulário.
Comment: Então não é possível eu resgatar o valor anterior?
Comment: Tenho um formulário que foi preenchido por um usuário, eventualmente, é preciso fazer certas alterações nesse formulário, isso já está feito. funciona perfeitamente.
Comment: Oque eu quero fazer agora é o seguinte:
Mostrar o valor no placeholder somente mostrar, ele não vai ter função alguma, só preciso que seja exatamente o mesmo dado que está no meu banco.
Answer: Com JavaScript podes fazer assim:

var placeholder = document.getElementById("entrada").getAttribute("placeholder");
alert(placeholder);
<input type="text" placeholder="teste" id="entrada">
Comment: Ainda assim vem em branco.
Answer: A Alteração que sugiro é a seguinte:
<input type="text" name="cliente" maxlength="50" placeholder="<?php echo $cliente; ?>" value="<?php echo $cliente; ?>"/>

Perceba que você está setando o placeholder e depois substituindo pelo value
no caso remova o value e veŕá que o placeholder está funcionando conrretamente.
<input type="text" name="cliente" maxlength="50" placeholder="<?=
$cliente; ?>"/>

Definir placeholder com variável PHP


Updating combobox model - item listener no longer fires

Question: I have a combo box and I update its model with a new DefaultComboBoxModel by calling setModel. However when I first created the combo box, I registered an ItemListener with it by calling addItemListener. The problem is after I update the model, the ItemListener no longer fires. Do I need to call addItemListener with a new ItemListener on my combo box after each time I update the model?
Comment: `I only want to do it if it is necessary` - you just stated the code doesn't work. Doesn't that tell you that you need to do something? `I don't want to have to recreate a new object each time the model is refreshed if it is not necessary.` - so why are you creating a new model instead of changing the items in the model?  What is different about creating a new model object, but not creating new listeners? Why are you worried about creating a single object. Seems like some kind of micro optimization.
Comment: `Do I need to call addItemListener with a new ItemListener on my combo box after each time I update the model?` - Try it and see what happens, then report the results back here.
Comment: I only want to do it if it is necessary. I don't want to have to recreate a new object each time the model is refreshed if it is not necessary.
Comment: Good point. I jumped the gun a bit with this. The answer below did the trick. Thanks
Answer: Yes. You can use either of these approaches:

Use getListDataListeners() to get the listeners and transfer them to the new model.
Use removeAllElements() and recycle the existing model.


How to correctly vectorise a function using numpy?

Question: I'm new to numpy and I must be doing something stupid here, but all I want is to generate an array of 4-dimention probability distributions. I don't understand why my vectorised function is returning this weird object which claims to be of type np.ndarray but doesn't print like one. Also, it returns error when I call self.inputSpace[:,0].
Here's the entire content of test.py:
import numpy as np

def generateDist(i,j,k):
    return np.squeeze(np.array([i*j,i*(1-j),(1-i)*k,(1-i)*(1-k)]))

generateDist = np.vectorize(generateDist,otypes=[np.ndarray])

class distributionSpace():
    def __init__(self):
        self.grid = 3 # set to 3 for simplicity
        self.inputSpace = np.array([])

    def generateDistribution(self):
        alpha = np.linspace(0.,1.,self.grid)
        beta = np.linspace(0.,1.,self.grid)
        gamma = np.linspace(0.,1.,self.grid)
        i , j , k = np.meshgrid(alpha,beta,gamma)
        i = np.squeeze(i.flatten())
        j = np.squeeze(j.flatten())
        k = np.squeeze(k.flatten())
        self.inputSpace = generateDist(i,j,k)
        print(self.inputSpace)
        return self

if __name__ == '__main__':
    distributionSpace().generateDistribution()

And here's the result I got:
$ python3 test.py
[array([ 0.,  0.,  0.,  1.]) array([ 0. ,  0. ,  0.5,  0.5])
 array([ 0.,  0.,  1.,  0.]) array([ 0. ,  0.5,  0. ,  0.5])
 array([ 0.  ,  0.5 ,  0.25,  0.25]) array([ 0. ,  0.5,  0.5,  0. ])
 array([ 0.,  1.,  0.,  0.]) array([ 0.,  1.,  0.,  0.])
 array([ 0.,  1.,  0.,  0.]) array([ 0.,  0.,  0.,  1.])
 array([ 0. ,  0. ,  0.5,  0.5]) array([ 0.,  0.,  1.,  0.])
 array([ 0.25,  0.25,  0.  ,  0.5 ]) array([ 0.25,  0.25,  0.25,  0.25])
 array([ 0.25,  0.25,  0.5 ,  0.  ]) array([ 0.5,  0.5,  0. ,  0. ])
 array([ 0.5,  0.5,  0. ,  0. ]) array([ 0.5,  0.5,  0. ,  0. ])
 array([ 0.,  0.,  0.,  1.]) array([ 0. ,  0. ,  0.5,  0.5])
 array([ 0.,  0.,  1.,  0.]) array([ 0.5,  0. ,  0. ,  0.5])
 array([ 0.5 ,  0.  ,  0.25,  0.25]) array([ 0.5,  0. ,  0.5,  0. ])
 array([ 1.,  0.,  0.,  0.]) array([ 1.,  0.,  0.,  0.])
 array([ 1.,  0.,  0.,  0.])]

Comment: possible duplicate of [Using Numpy Vectorize on Functions that Return Vectors](http://stackoverflow.com/questions/3379301/using-numpy-vectorize-on-functions-that-return-vectors)
Answer: Found an answer here for people who are searching :
Using Numpy Vectorize on Functions that Return Vectors
tl;dr:
self.inputSpace = np.array(generateDist(i,j,k).tolist())

Comment: it might be worth reading the second answer there too: that `np.vectorize` is just a convenience funciton, so is not really that useful to use here, as you are feeding it a `numpy` array, and expecting one in return. Since `vectorize` will not speed up your code, you might want to just rewrite your function to do what you require without using `vectorize`


Uniform Convergence of a function defined by an integral

Question: I'm stuck with the following problem:
Let K be a real-valued function such that:
$\int_{-\infty}^{\infty} |K(t)|dt < \infty$ and $\int_{-\infty}^{\infty} K(t)dt = 1 $. Let f be a continuous function. Then we define:
$f_{n} (x) = \int_{-\infty}^{\infty} f(x+ t/n)K(t)dt $. I want to prove that the sequence ${f_{n}}$ uniformly converges to f in any interval of the form $[a,b]$. I've thought about integration by parts, but you aren't given any hypothesis on the differentiability of either $K$ nor $f$. Any ideas?
Comment: Just as a side note, K kind of looks like the Dirac Delta. I'm not an expert on the topic, but maybe there are useful results in that context that can help with the problem
Comment: K is not the dirac delta since the dirac delta is not a function in the common sense and even if you look on the dirac delta as a function, it is infinity a point. Hence not real valued.
Comment: Is $f$ assumed to be bounded? What makes the integral defining $f_n$ converge?
Comment: Yes, I forgot to mention it
Answer: Use the fact that $f(x) = \displaystyle \int_{-\infty}^\infty f(x) K(t) \, dt$. It follows that
$$ |f_n(x) - f(x)| \le \int_{-\infty}^\infty |f(x+t/n) - f(x)| |K(t)| \, dt.$$
Can you proceed from here?
Comment: I think so. Given epsilon > 0, since f is continuous you can find a large enough N such that for all n > N, |f(x+t/n) - f(x)| < epsilon . Then the epsilon gets out of the integral sign and the resulting integral is convergent by hipothesis. Thanks a lot!
Comment: It is a little more complicated than that because $f(x+t/n)$ may not be close to $f(x)$ for all $x$, rather just for $t$ inside a bounded interval. When $t$ is large you can use the fact that $|f(x+t/n) - f(x)|$ is bounded.