Expressing Tornheim sums in terms of Riemann's Zeta

Question: If
$$T(a,b,c)=\sum_{r\geq1}\sum_{s\geq1} \frac{1}{r^as^b(r+s)^c}$$
How to prove that :
$$T(3,1,2)=-\frac13 \zeta(6)+\frac{\zeta^2(3)}{2}$$
I tried some algebraic manipulations but did not work. Can you please help me ?
Any solution will be appreciated
Answer: You might benefit from reading Basu, A., "On the evaluation of Tornheim sums and allied double sums", doi:10.1007/s11139-011-9302-5.  Table 2, item F would be a starting point.
Answer: The easiest way to do it is to use partial fraction decomposition. Let us choose the variable for the decomposition to be $s$. Then we have:
\begin{equation}
\frac{1}{r^a s^b (s+r)^c} =
\sum\limits_{l_1=1}^b \binom{b+c-1-l_1}{c-1} \frac{(-1)^{b-l_1}}{s^{l_1} r^{b+b+c-l_1}} +
\sum\limits_{l_1-1}^c \binom{b+c-1-l_1}{b-1} \frac{(-1)^b}{(s+r)^{l_1} r^{a+b+c-l_1}}
\end{equation}
Now we sum over $s$ and we get :
\begin{equation}
\sum\limits_{s=1}^\infty \frac{1}{r^a s^b (s+r)^c} =
\sum\limits_{l_1=1}^b \binom{b+c-1-l_1}{c-1} \frac{(-1)^{b-l_1} \zeta(l_1) 1_{l_1 \ge 2}}{ r^{a+b+c-l_1}} +
\sum\limits_{l_1=1}^c \binom{b+c-1-l_1}{b-1} \frac{(-1)^b(\zeta(l_1) 1_{l_1 \ge 2} - H_r^{(l_1)})}{ r^{a+b+c-l_1}}
\end{equation}
I think that this that doesn't require any explanation except that for $l_1=1$ we are getting singular terms. Therefore in that case we simply apply the following identity $H_r^{(1)} = \sum_{s\ge 1}\left( 1/s - 1/(s+r)\right)$. Now we sum over the variable $r$ and we get:
\begin{eqnarray}
&&T(a,b,c)=\sum\limits_{l_1=1}^b \binom{b+c-1-l_1}{c-1} (-1)^{b-l_1} \zeta(l_1) 1_{l_1 \ge 2} \zeta(a+b+c-l_1) +
\sum\limits_{l_1=1}^c \binom{b+c-1-l_1}{b-1} (-1)^b\zeta(l_1) 1_{l_1 \ge 2}  \zeta(a+b+c-l_1) - \\
&&
\sum\limits_{l_1=1}^c \binom{b+c-1-l_1}{b-1} (-1)^b {\bf H}^{(l_1)}_{a+b+c-l_1}(+1)
\end{eqnarray}
where ${\bf H}^{(l)}_n(t) := \sum\limits_{r\ge 1} H_r^{(l)}/r^n t^r$.
Now if we take $(a,b,c)=(3,1,2)$ we get:
\begin{eqnarray}
T(3,1,2)&=& 0 + (-1)^1 \zeta(2) \zeta(4) - \sum\limits_{l_1=1}^2 \binom{2-l_1}{0} (-1)^1 {\bf H}^{(l_1)}_{6-l_1}(+1)\\
&=&(-1)^1 \zeta(2) \zeta(4)+ {\bf H}^{(1)}_5(+1) + {\bf H}^{(2)}_4(+1) \\
&=&(-1)^1 \zeta(2) \zeta(4)+\left(-\frac{1}{2} \zeta(3)^2-1/3 \zeta(2) \zeta(4)+\frac{7}{3} \zeta(6)\right)+\left(+1 \zeta(3)^2 + \frac{4}{3} \zeta(2) \zeta(4)-\frac{8}{3} \zeta(6)\right) \\
&=& \frac{1}{2} \zeta(3)^2 - \frac{1}{3} \zeta(6)
\end{eqnarray}
where in the second line from the bottom we used my answer to Calculating alternating Euler sums of odd powers .


Question about John Lee's proof of Fundamental Theorem for Nonautonomous ODEs by using the result for autonomous ODEs

Question: The following is from John Lee's Introduction to Smooth Manifolds that gives the proof to the Fundamental theorem for nonautonomous ODEs. The proof is given in Theorem D.6 below, and it uses Theorem D.1, which is the Fundamental theorem for autonomous ODEs and extend it to cover the nonautonomous case. However, I cannot see how this proof actually works.  It says in the proof that Theorem D.1 guarantees that there is an interval $J_0 \subset \mathbb{R}$ containing $s_0$ and an open subset $W_0 \subset J \times U$ containing $(s_0,x_0)$, such that for any $(t_0,c)\in W_0$ there exists a unique solution to (D.20) defined for $t\in J_0$, and the solution depends smoothly on $(t,t_0,c)$.
However, if you look at the statement of Theorem D.1, the domain of $V$ is an open subset of $\mathbb{R}^n$, and the open subset $W_0$ is also a subset of $\mathbb{R}^n$, and so I cannot see how Theorem D.1 applies here. I can see that by the first statement of the proof, we only need to solve for $y^1, \dots, y^n$, however, $V^i$ in (D.20), is a function with $n+1$ inputs, or with the domain contained in $\mathbb{R}^n$, so I really cannot see how Theorem D.1 guarantees a solution. I would greatly appreciate some help. understanding this modification.
Answer: The idea is to augment the dimension of $V$. Replace $V = (V^1,\ldots,V^n)$ with $V = (V^0,V^1,\ldots,V^n)$, where
$$
V^0 = V^0(y^0(t),\ldots,y^n(t)) = 1.
$$
Also set $c^0 = y^0(t_0) = t_0$. Then for $i=0,\ldots,n$ we have
$$
\dot{y}^i(t) = V^i(y_0(t),\ldots,y^n(t)),~~~ y^i(t_0) = c^i.
$$
Now we're in the setting of Theorem D.1, with $U\subset\mathbb{R}^n$ replaced by $J\times U \subset\mathbb{R}^{n+1}$, $V:J\times U\to\mathbb{R}^{n+1}$, and $c = (c^0,\ldots,c^n)\in\mathbb{R}^{n+1}$.


How to separate groups using PCA?

Question: I have two groups: A) controls: $25\times2000$, B) patients: $12\times2000$.
Group A has one PC explaining a lot of the variance. (Suggesting a homogenous population?) Group B cannot be explained by the first 2 or 3 (each of the PCs seem to be dominated by single patients).
If I use the group A PC1 as an example of "normal control", is there a way to show how "far" or "close" each of the patients are from this? I.e. How can I establish that some patients are very similar to the controls and some aren't?

I have 25 controls but only 12 patients. Each of them have a spectrogram (time x freq x channels) that is collapsed down to 1 vector.I have tried PCA on just the controls and get a good 1st PC (it's not dominated by any one subject) and looks like the individual data. With patients alone, I do not get this. If I do the PCA on both patients and normals [controls] together, the 1st PC still looks like the normals but it doesn't separate the 2 groups. So it was suggested to me to take the PCA of just normals and then project the patients into this space but how to do that is unclear.
Just want to add - I don't think there are two populations; i.e., controls and patients are not very different (at least on the measure that I am using here). But, some patients are "farther apart" than others from the controls; i.e., some look like normals but others are very far from them.
Comment: Hi, I have 25 controls but only 12 patients. Each of them have a spectrogram (time x freq x channels) that is collapsed down to 1 vector.I have tried PCA on just the controls and get a good 1st PC (its not dominated by any one subject) and looks like the individual data. With patients alone, I do not get this. If I do the PCA on both patients and normals together, the 1st PC still looks like the normals but it does'nt seperate the 2 groups. SO it was suggested to me to take the PCA of just normals and then project the patients into this space but how to do that is unclear.
Comment: Please explain what "$25\times 2000$" means: are these 25 subjects for which you have 2000 attributes or 2000 subjects with 25 attributes?  Either way, the mismatch between (A) and (B) requires some explanation up front. Are any variables common to the two datasets?  If so, how many?  (The rest would appear to be irrelevant.)  Did you do the PCA only on the common variables or on all variables in each dataset?
Comment: Hi, Just want to add - I don't think there are two populations i.e. controls and patients are not very different (atleast on the measure that I am using here). BUT some patients are "farther apart" than others from the controls. i.e. some look like normals but others are very far from them.
Comment: Hi, is this called training on the controls and testing the patients?
Answer:
it was suggested to me to take the PCA of just normals and then project the patients into this space but how to do that is unclear

This is not difficult. Let's say that your control subjects data is combined in one matrix $\mathbf{X}$ with 25 rows and 2000 columns, and your patients' data -- in one matrix $\mathbf{Y}$ with 12 rows and 2000 columns. When you do PCA of your control subjects, you will get up to 24 (number of subjects minus 1) principal axes. Each principle axis is a vector in 2000-dimensional space. If you take the first principal axis $\mathbf{u}$ then you can project your control data onto this axis, obtaining $\mathbf{z_x} = \mathbf{X}\mathbf{u}$. This is the first principal component, it consists of 25 values, one for each subject.
Now if you need to project patients on the same axis, you simply compute $\mathbf{z_y} = \mathbf{Y}\mathbf{u}$. This will be a vector of length 12, the projection you were looking for.
Note that I would rather take two first principal axes and not just one, because then the projection onto this two-dimensional space can be nicely plotted as a scatter-plot. You can plot all your controls as black dots, and all your patients as red dots, this will give you a clear visualization.
Comment: Hi! I think I understand but let me see..
Comment: In matlab[coeff, score, latent, tsquared, explained, mu] = pca(X'); then coeff = 25x25
Comment: Sorry -editing cut me off..BUt Coeff(:,1:2) does not multiply with Y.
Comment: sorry if i'm missing something fundamental
Comment: Try pca(X), not X'.
Comment: But pca wants the variables as columns
Comment: coeff=pca(AN);
score = coeff(:,1:2)'*X';
scoreP = coeff(:,1:2)'*Y';

figure,plot(score(1,:),score(2,:),'m*')
hold on
plot(scoreP(1,:),scoreP(2,:),'r*')
Comment: @susan: "Variables as columns" means that X should have 2000 columns and does *not* need to be transposed. Did you figure it out by now?
Comment: Yes..So does this make sense:  coeff=pca(X); score = coeff(:,1:2)'*X'; scoreP = coeff(:,1:2)'*Y'; figure,plot(score(1,:),score(2,:),'m') hold on plot(scoreP(1,:),scoreP(2,:),'r*')
Comment: @susan: Yes, I think so. Well, you need to have a multiplication sign between `coeff` and `X` in the second line, and also use `'m*'` and `'r*'` instead of `'m'` and `'r'` (you don't need lines). I checked with random X and Y and it works. Does it give you the results you wanted?
Comment: unfortunately no.. meaning the first and second PCs do not seperate the two populations..
Comment: @susan: Well, it is not surprising, it did sound like a rather weird approach from the very beginning (but was maybe still worth a try). It makes more sense to analyze the groups together, i.e. do `pca([X;Y])`, and then do the same scatter-plot. But this is not tailored to separate the groups either. You might want to try to do PCA (or PLS) of the groups together, retain ~5-10 components and do an LDA projection there. But actually, from your description in the original question it sounds like your groups are not linearly separated anyway.
Comment: Hi, I tried pca([X;Y]) and it did'nt help either..Yes, it is probably just the data..

How to separate groups using PCA?


Accessing metaobject referenced by variant metafield

Question: This question was posted as a comment to a different question:
I'm trying to display color swatches in collection. I have metaobject defined which has color and its name. Then I have defined a metafield in variant and created link to metaobject.
Now, I am trying to access hex value of color through variant.metafields.custom.color.value (variant is current variant in for loop and custom is name space and color holds hex value) but instead of color I am getting gid links. @cyberspider789
Answer: Have you tried accessing the metaobject values by looping on them?
{% for metaobject in product.metafields.namespace.values %}
  {{ metaobject.field }}
  {{ metaobject.field.value }}
{% endfor %}

Debug this by logging the values.


Check if a panel page is enabled programmatically?

Question: I need to be able to verify if a panel page (which is just a variant of a ctools page) is enabled or disabled.  How would one do this, programmatically?  If it is disabled, how would one enable it, programmatically?
Comment: I think that thread is exactly what you are looking for: https://www.drupal.org/node/1837948
Answer: You can use
panels_load_display
Then check the disabled flag for page status.
Comment: How do you get the display id?


How do I get the $language object inside a form builder?

Question: I have this necesity to use $language inside MY_MODULE_form($form, &$form_state) function and it seems is not available. I tried to define it as global, but it displays blank.
global $language_content;
dpm($language_content->language);

My simplified structure of MY_MODULE_form() looks like this:
function MYMODULE_form($form, &$form_state) {
global $language_content;
$form['name'] = array(
      '#type' => 'fieldset',
      '#title' => t('Name'),
  );
  $form['back'] = array(
      '#markup' => '
'.t('Back').'
',
  );
  return $form;
}

I found a hardcoded PHP solution:
if(strpos($haystack, 'en')) {
    $back_path = "/project/en/my/home";
    }
  if(strpos($haystack, 'fi')) {
    $back_path = "/project/fi/my/home";
  }
  $form['continue-shopping'] = array(
      '#markup' => '
'.t('Back').'
',
  );

I am looking however to something more elegant.
Answer: Always use l() (or url(), which justs generates the URL) for generating links; then you, don't have to worry about the current language, base path, whatever clean URLs are enabled or not.
l(t('Back'), 'my/home');

That said, global $language should always work.
Comment: Amazing! This is what I was looking for. Thanks a lot, you saved my hardcoding future.
Answer: Using global $language; should always get you the language object.


Performance/Best Practice: If statement in for loop or for loop in if statement

Question: In the interest of writing neat and fast code I ran into a question and with some searching didn't find the answer. What's the best practice for writing code in this situation?

for (let i = 0; i < message.timesheets.length; i++) {
  if (message.timesheets.length > 1) {
    // Run function
  } else {
    // Run other function
  }
};

OR

if (message.timesheets.length > 1) {
  for(let i = 0; i < message.timesheets.length; i++) {
    // Run function
  };
} else {
  for(let i = 0; i < message.timesheets.length; i++) {
    // Run other function
  };
}

My thoughts is that the first option is easier to read but less preformant because it has to evaluate the if each time the for loop loops. The second option only has to run the function contained each time the for loop loops but is harder to read and is longer. The question that arises as both these snippets do the same with is which way of doing it is better? If one is not necessarily better than the other which one is faster?
EDIT: What you guys don't understand is that I didn't copy my entire project into the question. For the sake of the question we assume the message.timesheets array can have values equalling one (1) and more than one (1).
Comment: `if (message.timesheets.length > 1) {` this line is useless
Comment: The if statement determines which version of a notification a user will see depending on how many items need to be communicated ("Timesheet approved: [hours] approved on [date]" vs "13 Timesheets approved: see more..."). It has a use in the project I'm working on. How's it useless?
Comment: OP is correct, it's not useless, because it's checking if the value is greater than 1, not 0.
Comment: @RaceYouAnytime is correct.  So if your timesheet count does not depend on the `for` loop results, you should run the `if` only once, outside the loop.
Answer: I'd go for the second option, since it will perform only one test operation and then enter a loop, while the first one will enter into a loop and it will perform a test operation at every iteration.
It can be seen as:
Loop
  |_Test
       |_ do
  |_Test
       |_ do
  |_Test
       |_ do
  |_Test
       |_ do
End

and:
Test
   |_ Loop
      |_ do
      |_ do
      |_ do
      |_ do
   |_ End

Respectively. I'm not an expert on this, it's just my opinion, it also depends on how the JS interpreter (or compiler) handles this situations, there might be some optimizations that make the first option the best (or worst). If you want to be sure, you can take a look into a JS engine code, like the Google's V8 JS engine
Answer: Since the second for loop (in the second example) only runs for 1 iteration if the conditional is false, you can leave out the second loop.
if (message.timesheets.length > 1) {
  for(let i = 0; i < message.timesheets.length; i++) {
    // Run function
  };
} else if (message.timesheets.length == 1) {
  let i=0;
  // Run other function
}

Thanks to Bergi for pointing out that the else statement should be an else if, in case length is 1.
Comment: 1 or 0 iterations. You still need at least an `if` statement. Otherwise I'd agree.
Comment: Geniuses catching these things like that. Well thought through.
Answer: Re-evaluating the same if condition in the loop over and over is indeed slower. However, this would not matter unless your array way really huge, and instead you should focus on writing clean and readable code instead.
You probably can (and should) simplify to
const run = message.timesheets.length > 1 ? oneFunction : otherFunction;
for (const timesheet of message.timesheets)
  run(timesheet);

which is both dry and fast.
Comment: That's amazingly clean code! I didn't know javascript had a java-esque shorthand if ? operator.
Comment: @MicahFriesen I don't think there's any modern language not having the [conditional operator](https://en.wikipedia.org/wiki/%3F:) (there are however some that don't have `if` statements :P)
Answer: Since your test (the size of the array) is known before having to loop, you don't need to leave it till the last moment. And as bergi points out, use the test to choose the function to call in one single loop.
Basically, this comes down to premature optimisation. This really shouldn't matter. Write your code to be readable first, then in the future, if you have performance problems, investigate why. I bet you this will never be a problem.

Premature optimisation, in programming, is the act of optimising a piece of code before we know that we need to. It's an important problem to spot because it's often a waste of time; there are other tasks to do and what appears to be a problem at the micro level might only be a fraction of the entire system. You can't tell what's important without taking a step back to analyse the whole
Comment: However it's still an educational question to ask imo. Look how much I've learned from asking it. When you've got nothing to do at midnight it's worthwhile.


How to interpret when a variable is not significant in logistic regression while having the highest variable importance in a tree-based model

Question: I'm building a binary classifier with logistic regression and boosting. Just like the case that I described in the title, I am a little bit confuse on how to explain the result of those two models together, and how to answer questions like is this variable a key predictor for predicting?
Answer: Logistic Regression is a type of generalized linear model, and hence is analogous to linear regression. Because of this, the ability to handle a non-linear relationship is limited with Logistic Regression.
On the other hand, tree-based models can capture non-linear relationships very well.
I think the reason why you're seeing a variable that is important for a tree-based model, but not significant for Logistic Regression, is because that variable has a non-linear relationship with the target (dependent) variable.
Answer: In addition to the nonlinear/linear modeling issues raised in another answer and in the page linked in a comment, this type of behavior might be seen with strictly linear relations in a logistic model if there are correlations among predictor variables.
The first split in a tree will tend to be based on the predictor that has the best single-variable relation to your classification. If there are other predictors that are correlated to that predictor and also are related to the classification, a logistic multiple regression model will consider all those predictors together. In that case the best individually predictive variable may well diminish to statistical "insignificance" in the multiple regression. I have observed such behavior in practice.
To see if this might be happening in your case, examine how the predictors work individually in logistic regression. Also, note that in such instances the choice of "best" variable can be highly sample-dependent; you might examine the behaviors of your models on bootstrap samples of your data (which would occur directly if you were using bagging rather than boosting).
Note that for a predictive logistic model you should not necessarily remove "statistically insignificant" predictors, as they may nevertheless contribute usefully provided that you are not overfitting.


Drupal 8: Node "options" does not exist for Node "Drupal\Core\Template\TwigNodeTrans" error after update

Question: after updating Drupal 8 from 8.6.14 to 8.6.15 (twig v1.40.1) I suddenly get this kind of fatal errors:
 Uncaught PHP Exception Twig\Error\SyntaxError: "An exception has been thrown during the compilation of a template ("Node "options" does not exist for Node "Drupal\Core\Template\TwigNodeTrans".")

It happens in my custom theme, but also in core/themes/classy/templates/views/views-mini-pager.html.twig
Do you know how to solve this or what the origin is?
Comment: https://www.drupal.org/project/drupal/issues/3051269
Comment: This is known issue, it happened to me once, I just downgrade to twig 1.37 there is thread of this issue on drupal, but it's not fixed yet.
Answer: According to https://www.drupal.org/project/drupal/issues/3051269 this is now resolved by the drupal team. Whatever caused the error seems to be fixed now in drupal 8.7.0


How to create paragraph of particular type using JSONAPI?

Question: I am able to GET the data using endpoint "site_url/jsonapi/paragraph/text". But I am not able to create a new paragraph of type text. Its always giving me error "403 forbidden". I have tried all drupal permissions also i am using simple oauth and i am using admin token to POST.
Endpont :- site_url/jsonapi/paragraph/text
Request Type :- POST
Post Body :- {

"data": {
    "type": "paragraph--text",
    "attributes": {
        "field_text": {
            "value": "
ദുബായ് ∙ സാമ്പത്തിക അച്ചടക്കമില്ലാത്തവർക്കു കുരുക്കായി ക്രെഡിറ്റ് കാർഡുകൾ. കൃത്യമായി പണം തിരച്ചടയ്ക്കാതെ കുടിശിക പെരുകി കുടുക്കിലാകുന്നവരിൽ മലയാളികളുമേറെ. ബാധ്യത കൂടി ചിലർ വിട്ടുവീഴ്ചയ്ക്കായി ബാങ്കിനെ സമീപിക്കുമ്പോൾ മറ്റു ചിലർ രാജ്യത്തുനിന്നു മുങ്ങും. ഒരു കാർഡിന്റെ ബാധ്യത തീർക്കാൻ മറ്റൊരു ബാങ്കിൽ നിന്നുകൂടി ക്രെഡിറ്റ് കാർഡ് എടുത്ത് രണ്ടും തിരിച്ചടയ്ക്കാത്തവരുമുണ്ട്.
\r\n",
            "format": "basic_html",
            "processed": "
ദുബായ് ∙ സാമ്പത്തിക അച്ചടക്കമില്ലാത്തവർക്കു കുരുക്കായി ക്രെഡിറ്റ് കാർഡുകൾ. കൃത്യമായി പണം തിരച്ചടയ്ക്കാതെ കുടിശിക പെരുകി കുടുക്കിലാകുന്നവരിൽ മലയാളികളുമേറെ. ബാധ്യത കൂടി ചിലർ വിട്ടുവീഴ്ചയ്ക്കായി ബാങ്കിനെ സമീപിക്കുമ്പോൾ മറ്റു ചിലർ രാജ്യത്തുനിന്നു മുങ്ങും. ഒരു കാർഡിന്റെ ബാധ്യത തീർക്കാൻ മറ്റൊരു ബാങ്കിൽ നിന്നുകൂടി ക്രെഡിറ്റ് കാർഡ് എടുത്ത് രണ്ടും തിരിച്ചടയ്ക്കാത്തവരുമുണ്ട്.
"
        }
    },
    "relationships": {
        "paragraph_type": {
            "data": {
                "type": "paragraphs_type--paragraphs_type",
                "id": "6692c53b-f2f3-4a52-a18f-e59d94be3c88"
            }
        }
    }
}
}

This is always giving me 403 forbidden error. Am i doing anything wrong ?
Comment: Are you sure the user you use for authentication have permission to post to that URL? Are you sure that you have entered the correct username/password?
Comment: Yes everything was right. Problem was i was unaware of "Paragraph Type Permissions" module.
Answer: Issue was I didn't enable the "Paragraph Type Permission" module. Install it and go to drupal permissions.


Which property of Jacobi Symbol is used $\left(\frac{x^e}p\right)\left(\frac{x^e}q\right)=\left(\frac xp\right)\left(\frac xq\right)$

Question: While deriving a Jacobi symbol, this derivation is done in a document, but did not explain the property that is used. $p,q$ are prime, $e$ is odd.
Comment: It seems only true if $e$ is an odd number.
Comment: Yes, e is odd.. can you explain how we can deduct like this if e is odd? I am really new in number theory...
Answer: Since $e=2k+1$ for some $k$, then $x^e = x\cdot\left(x^k\right)^2=xu^2$ for $u=x^k$. So $$\left(\frac{x^e}{p}\right)=\left(\frac{xu^2}{p}\right)=\left(\frac{x}{p}\right)\left(\frac{u}{p}\right)^2 = \left(\frac{x}{p}\right)$$
Answer: $$\left(\frac{x^e}{p}\right)=\left(\frac{x^{e-2}}{p}\right)\left(\frac{x^2}{p}\right)=\left(\frac{x^{e-2}}{p}\right)$$
Now repeat until only $x^1$ is left.


Reset scroll in ScrollView

Question: I have a ScrollView (and a LinearLayout within it) set as main content. When the user scrolls the view further down, and then if I replace it's child (LinearLayout) with another LinearLayout, the view remains in the scrolled positioned.
How do I reset the ScrollView back to coordinate 0?
Answer: Why not just use scrollTo(0, 0);?
Link: http://developer.android.com/reference/android/view/View.html#scrollTo(int%2C%20int)
Comment: I noticed that scrollTo(0,0) works better. smoothScrollTo and fullScroll sometimes just don't really go to the top. I don't know why. I think it has something to do with the scrolling animation. scrollTo just 'jumps' to the top and that is exactly what I needed. Thanks!
Comment: This is exactly what fitted in my use case. I wanted to scroll with animation. It works like charm. But I guess someone who wants to scroll with animation should go with scrollview.fullScroll(scrollVIew.FOCUS_TOP)
Answer: If u want to clear the scrollview u can use
removeAllViews();
Answer: Its all in the documentation... http://developer.android.com/reference/android/widget/ScrollView.html search for fullScroll(int)
Answer: When scrollView.scrollTo(0, 0) & scrollView.fullScroll(View.FOCUS_UP) doesn't work, you can accomplish the intended with:
scrollView.post(new Runnable() {
                @Override
                public void run() {
                    scrollView.scrollTo(0, 0);
                }
            });

Answer: yourScrollView.scrollTo(0,0) will do the job just fine.
Answer: Just use
ScrollView hscrollViewMain = (ScrollView)findViewById(R.id.scrollViewMain);
hscrollViewMain.scrollTo(0, 0);

Reset scroll in ScrollView


How to forward DHCP A record registration to another domain

Question: I'm currently at work and we're having some troubles. We want to create a new domain for our area, but the DHCP server is not in our control. The DHCP server lists DNS as testdomain.com, however we want to make a new domain called testdomain1.com. We've been thinking of fowarding the DNS from testdomain.com to testdomain1.com so that way DHCP doesn't have to be changed. Basically
Client requests testdomain1.com
DHCP says DNS is at testdomain.com
testdomain.com tells client to go to testdomain1.com
client registers in AD at testdomain1.com and adds it's A record to DNS at testdomain1.com
Answer: I don't think it's possible with standard software(Though I don't know much about windows server). However maybe it's possible for you to setup all the hosts in testdomain1.com as CNAME to corresponding hosts in testdomain.com.
Alternatively (though much more complicated), maybe you can periodically load the whole zone (you can use nslookup or dig for that once zone transfers is enabled on your DNS server), and make some script to process zone data and insert changed names in testzone1.com (and possibly remove those entries from testzone.com)
Answer: That's... gonna be hard.  Windows Active Directory DNS does not handle forwarders that well. There are a TON of small records that are created in AD that can break with that setup.  I'd really try to get access to that DHCP server before I'd do a forwarder.


Clearing input value after adding content

Question: I have a simple script that adds an 'li' element with input text value to the list after clicking a button, but I also want to clear this input after clicking the button. Here is the HTML:
<form class="form">
<input id="newInput" type="text" placeholder="Dodaj pozycję">
<button id="createNew" type="button">Dodaj</button>
</form>

Moja lista:

<button id="deleteAll" type="button">Wyczyść</button>

And JS:
function addItem(){
    var myList = document.getElementById("list");
    var newListItem = document.createElement("li");
    var itemText = document.getElementById("newInput").value;
    var listText = document.createTextNode(itemText);
    newListItem.appendChild(listText);
    if (itemText === "") {
        alert("Pole nie może być puste");
    } else {
        myList.appendChild(newListItem);
    }
};

function clearText(){
    var itemText = document.getElementById("newInput").value;
    itemText.innerText = "";
};

var addButton = document.getElementById("createNew");
addButton.addEventListener("click", function(){
    addItem();
    clearText();
});

function clearList(){
    var myList = document.getElementById("list");
    myList.innerHTML = "";
};

var deleteButton = document.getElementById("deleteAll");
deleteButton.addEventListener("click", clearList);

Commands are fine, I've tested it in console and inputing first
var itemText = document.getElementById("newInput").value;

And then
itemText.innerText = "";

Works just fine, but I cannot get it to work on click event. What am I doing wrong?
Comment: i assume you mean native Js?
Comment: try itemText = ""
Answer: Your problem was that you were setting your variable to the value of the textbox, rather than the textbox itself:
function clearText(){
    var itemText = document.getElementById("newInput").value;  // <----
    itemText.innerText = "";
};

This meant that the next line was attempting to set the innerText of the value, which doesn't work. Also, to set or get data to or from an input field, you use the value property. Input fields don't have innerHTML or innerText. In fact, innerText is not even a standard. In places where that makes sense, use textContent instead.
It's always better to set variables to reference DOM elements themselves instead of particular properties of the element. That way, you can access the element and get whatever you need, as often as you need to, without having to re-scan the DOM for the element again when a different property value is needed.
Here's the working code:

function addItem(){
    var myList = document.getElementById("list");
    var newListItem = document.createElement("li");
    var itemText = document.getElementById("newInput").value;
    var listText = document.createTextNode(itemText);
    newListItem.appendChild(listText);
    if (itemText === "") {
        alert("Pole nie może być puste");
    } else {
        myList.appendChild(newListItem);
    }
};

function clearText(){
    // Just set your variable to the input element, not its value
    var itemText = document.getElementById("newInput");
    itemText.value = "";  // Form elements have a value property
};

var addButton = document.getElementById("createNew");
addButton.addEventListener("click", function(){
    addItem();
    clearText();
});

function clearList(){
    var myList = document.getElementById("list");
    myList.innerHTML = "";
};

var deleteButton = document.getElementById("deleteAll");
deleteButton.addEventListener("click", clearList);
<form class="form">
<input id="newInput" type="text" placeholder="Dodaj pozycję">
<button id="createNew" type="button">Dodaj</button>
</form>

Moja lista:

<button id="deleteAll" type="button">Wyczyść</button>
Comment: And now it's working great, thanks for clearing that out :)


Master theorem in which k is rational

Question: I've been looking at my algorithms and complexity course's suggested exercises for master theorem and I the only one I can't seem to solve is a case in which k is rational. I managed to prove that master theorem is applicable, but I don't know how to go about using it. The function in question is
<code>T(n) = 3T(n/9) + Θ(n^(7/6))
</code>
Answer: We can apply the Master theorem as normal with $a = 3$, $b = 9$ and $f(n) = n^{7/6}$. Notice that $n^{7/6} = \Omega(n^{\log_b a + \epsilon}) = \Omega(n^{1/2 + \epsilon})$ for some $\epsilon > 0$ (pick one). Checking the regularity condition:
$$
af(n/b) = 3\left(\frac{n}{9}\right)^{7/6} = \frac{3}{9^{7/6}} n^{7/6} \leq kn^{7/6}
$$
for
$$
k = \frac{3}{9^{7/6}} < 1,
$$
so the regularity condition holds. Applying case 3, we arrive at $T(n) = \Theta(n^{7/6})$.
Comment: Great answer, just a quick follow-up question, ϵ can be a fraction, right?
Comment: @JustACuriousMind Yes, $\epsilon$ can be any real number greater than zero.

Master theorem in which k is rational


lua-CoatPersistent, would this work with Corona SDK?

Question: The concept of "lua-CoatPersistent" looks very appealing re higher level usage of a sqlite database in Corona.
Anyone know if this would work under Corona? If you've got it working any tips/learnings re how to get it all setup/working? i.e. any gottcha's that require work arounds?
Link to: "lua-CoatPersistent"
http://fperrad.github.com/lua-CoatPersistent/index.html#documentation
Answer: No. You can't install modules. You can use just pure Lua. But I think it should be possible with Corona Enetrprise.


Confusion about joint probability distribution in Bayesian Inference setup

Question: I am confused by a simple fact but I can't solve my head around it!
It's known that:
$P(y,\theta) = P(y|\theta)*P(\theta)$
and
$P(y,\theta) = P(\theta|y)*P(y)$
Giving us: $P(\theta|y)*P(y) = P(y|\theta)*P(\theta)$ (both valid probability density functions)
But in bayesian inference literature we learn that $P(y|\theta)*P(\theta)$ is not a probability density function because $P(y|\theta)*P(\theta)$ when $P(y|\theta)$ as a likelihood does not sum to 1, needing the $P(y)$ as a denominator to normalize it and give a valid posterior probability density function.
So, my confusion is: is the joint density function NOT a joint PROBABILITY density function in $P(y,\theta) = P(y|\theta)*P(\theta)$ since the right hand side does not sum to 1?
Answer: Both
\begin{equation}
p(\theta|y)\,p(y)
\qquad\text{and}\qquad
p(y|\theta)\,p(\theta)
\end{equation}
are valid joint probability distributions for $(y,\theta)$. Both distributions integrate to 1 with respect to $y$ and $\theta$:
\begin{equation}
\iint p(\theta|y)\,p(y)\,dy\,d\theta = 1
\qquad\text{and}\qquad
\iint p(y|\theta)\,p(\theta) \,dy\,d\theta = 1 .
\end{equation}
But $p(y|\theta)\,p(\theta)$ is not (in general) a valid conditional distribution for $\theta$ because it does not (necessarily) integrate to 1 with respect to $\theta$:
\begin{equation}
\int p(y|\theta)\,p(\theta)\,d\theta = p(y) ,
\end{equation}
where $p(y)$ does not necessarily equal 1.
Addendum
I'm addressing a question in a comment by the OP.
The marginal distribution for $y$ is computed from the joint distribution by integrating out $\theta$:
\begin{equation}
p(y) = \int p(y|\theta)\,p(\theta)\,d\theta .
\end{equation}
For fixed $y$, $p(y)$ is a number, the density at $y$. But the density $p(y)$ is allowed to vary as we vary $y$. In
\begin{equation}
\int p(y)\,dy = 1
\end{equation}
$p(y)$ varies as $y$ varies so as to guarantee the result.
In the conditional distribution
\begin{equation}
p(\theta|y) = \frac{p(y|\theta)\,p(\theta)}{p(y)} ,
\end{equation}
we are holding $y$ fixed and so $p(y)$ is a number. If we chose to fix $y$ at a different value, then we get a different distribution for $\theta$ and a different value for $p(y)$.
(This can be a bit tricky at first and it's good to nail it down before proceeding.)
Comment: Thank you so much for the explanation! It totally makes sense now!
If it's ok, I'd like to add a very beginner's follow up question. (very embarrassing question)

Since () in ∫(|)()=() is a constant (not necessarily equal to 1), if we solve the ∬(|)() in parts, first in respect to , we will end with ∫() and this do not integrate to 1 since it's a constant. But ∬(|)() = 1. Where is the flaw in my thinking??
Comment: Got it!!! Thank you so much again for all the answers! I have researched and thought about it for days before asking it here. Everything now connects for me!
Comment: Glad to hear it.


OOAD - File-Format-Reader class vs Object-Model class: which should depend on which?

Question: Let's consider, as an example, the domain of GPS and Geographical (GIS) entities.
We would model the meaningful geographic entities (points, paths, regions) as classes in any desired programming language, and these classes would be a conceptual, "implementation-free" representation of these entities.
On the other hand, there are a lot of file formats that save these features with more or less the same meaning. In the GPS domain the most common file formats are GPX, KML, ShapeFile, WellKnownText, etc.
Supposing, then, I want to create a GpsFeatureCollection class which would contain a Points property, a Paths property, and so on. Also, I would implement classes like GpsReader, KmlReader, ShapeFileReader (and their respective Writers) and so on.
THE QUESTION IS:
Which is the best practice in OOAD:

Have a GpsFeatureCollection to instantiate a FileFormat(Reader/Writer) class?
Have a GpsFeatureCollection to implement Read/WriteFromFormat methods instead of classes?
Have each file format reader to instantiate an empty GpsFeatureCollection, populate it with data read from file, then pass the populated object as a return value?
Have a mediator class to avoid any dependency between FileFormatClass and ObjectModelClass?
None of the above?
"Well, it depends..."

I am really interested in doing "the right thing". My immediate plans are to use Python, but most probably this would matter for other languages too. This is causing some "analysis paralysis" in my pet project currently...
Answer: Here is my take wherein I pass reader and writer instances to read() and write() methods, this seems to achieve good level of decoupling and yet provides flexibility to pick various readers and writers.
Code uses Java-like syntax
Declare a Reader interface, we will assuming multiple implementation such KMLReader,
ShapeFileReader, etc
interface Reader {
   GpsFeatureCollection read();
}

Declare a Writer interface, we will assuming multiple implementation such KMLWriter, ShapeFileWriter, etc
interface Writer {
   void write(GpsFeatureCollection c);
}

Let's declare GpsFeatureCollection class to have read and write methods which accept respective interfaces as parameter to perform the job.
class GpsFeatureCollection {

    ...

    public static GpsFeatureCollection read(Reader r) {
       return r.read();
    }

    public static void write(Writer w) {
        w.write(this);
    }

}

Some example of usage using different readers and writers.
// Reading data
GpsFeaureCollection data = GpsFeatureCollection.read(new ShapeFileReader("/tmp/shapefile"));

// Writing data
data.write(new KMLWriter("/tmp/kmlfile"));

Comment: Glad that you liked it.  Java-folks don't use prefix "I" for interface, though I don't mind if one uses it as long as it is consistently used.
Comment: This is pure gold! Thank you very much. As an only suggestion, I would name the interfaces IReader and IWriter (but not IGpsFeatureCollectionReader, etc. :P ). Thanks again!
Comment: As a side note (now that I had lunch and my brain is working again), another possible design would be to have, say, a `GpxFormat` class, with `read` and `write` methods to be used by the common interface. Then, the same class could implement a lot of boilerplate/specification-specific code that would most probably be reused by the IO methods, and the `FileFormat` class would be sort of just a file handler passed as arguments to either method.


How Can I restrict a date picker in a date field, to disable a list of specific days from the calendar widget?

Question: I need to let the user choose a day from a datepicker in a date field, but disabling a list of specific days from the calendar picker, so the user can't select a not available day.
(Just for explain my use case. I am using Date field and Form api. My Disabled days are in a field in several nodes, and I can get the list of disabled days easily from a View listing this date field. If it is needed it can be exported too as json, xml, plain text or any other format, to serve as entry in the calendar picker.)
(After the user choose an available Day, I will have to do the same to let him select an available Time from a time picker.
This will be an appointment for a Photography Session.)
Comment: Just to be curious and probably helping others to answer - how many days do you want to exclude? Excluding a lot of days would introduce some ajax requests to the backend to at least cycle between months. What use case are you trying to handle? In all cases you can validate the submitted day on form submit and display an error message.
Comment: I edited my question to detail my use case.
Answer: Using this answer: https://stackoverflow.com/a/15400806/1475662 and a bit of custom coding to add the js and the list of available (or not available) dates to the page.
Comment: This is looking good.


Repetir números ímpares com do while

Question: Oi,
Preciso fazer um código, dentro de um switch, que reproduza todos os números ímpares de 0 a 200, com a estrutura de repetição do while. Procurei no google e só achei com for. Já tentei colocar o "impar0a200%2!=0" dentro do do, mas o problema persiste; fica repetindo todos os números de 0 a 200, incluindo os pares. O Código está assim:
case '3': {    // com problemas!!

    impar0a200%2!=0;

    do
    {
        cout<<"\n Os números a seguir são os ímpares entre 0 e 200:  " <<impar0a200;
        impar0a200++;
    }   while (impar0a200<=200);

    break;
}

Answer: A verificação impar0a200%2 != 0 está correta, basta então utilizar essa condição em um if e sendo verdadeira, exibir o número.
if (impar0a200 % 2 != 0) {
  cout << impar0a200 << endl;
}

Essa condição deve ficar dentro do seu bloco de do/while, exibindo assim todos os números ímpares até o final do loop.

Veja um exemplo utilizando parte de seu código:
#include <iostream>

using namespace std;

int main() {
  char teste = '3';
  int impar0a200 = 0;

  switch (teste) {
    case '3': {
      cout << "\nOs números a seguir são os ímpares entre 0 e 200: " << endl;

      do {
        if (impar0a200 % 2 != 0) {
          cout << impar0a200 << endl;
        }

        impar0a200++;
      } while (impar0a200 <= 200);

      break;
    }
  }

}

Veja online: https://repl.it/repls/PopularCleverPrediction
Comment: Muito grato. Estava faltando colocar o if, este era o principal. Obrigado Daniel Mendes.
Answer: Neste caso específico poderia simplificar para:
case '3': {
    impar0a200 = 1;
    cout<<"\n Os números a seguir são os ímpares entre 0 e 200:  " << endl;
    do
    {
        cout << "\t" << impar0a200;
        impar0a200 += 2;
    } while (impar0a200 <= 200);
    break;
}

Repetir números ímpares com do while


ruby on rails migrations using an existing table

Question: I have this problem. I need to use an existing table on a mysql database. The name of the table is not compatible with RoR conventions and I need to remap the table name and the name of the attributes. I have created a scaffold to visualize on a web page the content of the table but I can't change the mapping. Is there a solution to indicate to RoR the relation between the name of the class and the name  of the table in the database? and a solution to indicate the relation between the attribute of the class and field on the table?
Thanks.
Answer: The table name can be specified using table_name class method.
For the attributes/column, you need to explicitly specify aliases for the attributes using alias_attribute method. For example, if you have name_of_thing column, but want to treat it as name, then you need something like this in your model:
class CreateUtenti < ActiveRecord::Base
  self.table_name = "another_name"
  alias_attribute :name, :name_of_thing
end

Comment: Thanks to you too. In this case rake db:migrate give me this error: rake aborted!
NoMethodError: undefined method `table_name=' for CreateUtenti:Class
Comment: @GiovanniDiClemente does your CreateUtenti class inherits from ActiveRecord::Base?
Comment: what Rails version do you use?
Answer: Yes you can pass table name in model like:
class YourModel < ActiveRecord::Base
  self.table_name = "pass_table_name_here"
end

Comment: Thank for your answer. I have tried but rake db:migrate give me an error: rake aborted!
ArgumentError: wrong number of arguments (given 2, expected 0..1)
Comment: Caused by:
ArgumentError: wrong number of arguments (given 2, expected 0..1)

Tasks: TOP => db:migrate
(See full trace by running task with --trace)
Macintosh:telwebtt giovannidiclemente$ rake db:migrate --trace
** Invoke db:migrate (first_time)
** Invoke db:load_config (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:load_config
** Execute db:migrate
rake aborted!
ArgumentError: wrong number of arguments (given 2, expected 0..1)


How to get a time difference in milliseconds in a cross platform c++ 32-bit system?

Question: I'm developing a c++ app for a cross platform 32 bit embedded system(windows and linux). For one needed functionality I need to calculate a time difference in milliseconds. Firstly the biggest precision that epoch timestamp give for 32bit systems, is that of a second. The majority of relevant answers that I came across are either 64bit related like the use of std::clock or std::chrono like:
std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();

Or system sprecific using
#include <sys/time.h>

or the GetSystemTime function on windows. I also checked the poco related time functions but they are also based on using 64bit variables. Can this be done with an existing standard or external c++ library or should I follow different approach?
Comment: Do you need epoch time in milliseconds or do you need a difference between two time points in milliseconds?
Comment: @RustyX I need a difference between two time points in milliseconds, but I assume if I can get epoch time in milliseconds in different time points will also do the job, unless I'm missing something.
Comment: There is no standard portable way to get epoch time in milliseconds. `chrono::system_clock` often has 1s precision and `chrono::high_resolution_clock` doesn't start at epoch.
Comment: @RustyX  Ok then a simple difference between two time points in milliseconds will be sufficient.
Answer: Here's a C++11 way to get epoch time and time difference in milliseconds (well, std::literals is C++14 but you don't have to use that):
#include <iostream>
#include <chrono>

using namespace std::literals;

int main()
{
    using Clock = std::chrono::system_clock;
    auto point1 = Clock::now();
    int64_t epoch = point1.time_since_epoch() / 1ms;
    std::cout << "Time since epoch: " << epoch << std::endl;
    auto point2 = Clock::now();
    std::cout << "Time difference in milliseconds: " << ((point2 - point1) / 1ms) << std::endl;
    std::cout << "Time difference in nanoseconds: " << ((point2 - point1) / 1ns) << std::endl;
}

system_clock demo
Time since epoch: 1486930917677
Time difference in milliseconds: 0
Time difference in nanoseconds: 102000

For high resolution time point differences the standard has chrono::high_resolution_clock, which may offer higher precision than chrono::system_clock, but the epoch of it often starts at system boot time, not at 1-1-1970.
high_resolution_clock demo
Time since "epoch": 179272927
Time difference in milliseconds: 0
Time difference in nanoseconds: 74980

Keep in mind that high_resolution_clock still has 1 second precision on Visual Studio before 2015. It has 100ns precision in Visual Studio 2015+, and should have at least 1ms precision on other platforms.
PS std::chrono works exactly the same on 32-bit and 64-bit systems.


PHP captura texto de data

Question: Eu tenho uma lista com esses valores:

 Conteúdo

E gostaria de inverter a ordem deles em PHP.
Eu fiz uma função
function inverte_breadcrumb($texto){
 $texto = explode(' - ', $texto);
 $texto = array_reverse($texto);
 $texto = implode(' - ', $texto);

 return $texto;
}

e com o preg_replace pensei em fazer o seguinte:
$novaslinhas = preg_replace("/data-breadcrumb="(.*)"/", 'data-breadcrumb="' . inverte_breadcrumb("$1") . '"', $novaslinhas);

Mas, ele não chama a função.
Alguém sabe o porquê?
Comment: primeiro, você está fazendo uma bagunça delimitando a string com aspas duplas e ao mesmo tempo usando aspas duplas sem escape. Segundo, você tenta aplicar uma função com o valor "$1", ela até será chamada sim, mas é sem efeito (não vai inverter nada, pois "$1" não tem traços. Ponha um `print_r($texto)` dentro da função inverte_breadcrumb que você vai ver que ela será chamada (depois de você consertar as aspas). Espero que nessas alturas do comentário você já tenha percebido que a função "inverte" será chamada antes do replace, ou seja, não vai surtir o efeito que você pretende.
Answer: Não sera possível utilizando a função preg_replace pois a mesma recebe valor do tipo string ou array com strings no parâmetro replacement
Para obter o resultado, utilize a função preg_replace_callback executar um callback.
uso:
preg_replace_callback('expressão', 'callback', 'string');

seu código:
$novaslinhas = preg_replace_callback("/data-breadcrumb=\"(.*)\"/",
                                               'inverte_breadcrumb', $novaslinhas);

note que o nome da função foi informado como uma string, agora mude a primeira linha da função, informando o índice que no caso é 1:
$texto = explode(' - ', $texto[1]);

altere também o retorno, pois deve ser retornado uma string que será substituta:
return 'data-breadcrumb="'. $texto . '"';

Veja funcionando em repl.it
Código completo:
function inverte_breadcrumb($texto){
  $texto = explode(' - ', $texto[1]);
  $texto = array_reverse($texto);
  $texto = implode(' - ', $texto);
  return 'data-breadcrumb="'. $texto . '"';
}

$novaslinhas = preg_replace_callback("/data-breadcrumb=\"(.*)\"/", 'inverte_breadcrumb', $novaslinhas);

Referências:

preg_replace
preg_replace_callback
Comment: Perfeito cara, eu sei que tenho muito o que aprender ainda, mas, valeu pela ajuda!!!

PHP captura texto de data


How can I return DOM content without HTML tags?

Question: I'm using the following function to remove tags and its content from user submitted comments:
function remove_html_element($tag,$content){
    $doc = new DOMDocument();
    $doc->loadHTML($content);
    $xpath = new DOMXPath($doc);
    foreach ($xpath->query('//'.$tag) as $node) {
        $node->parentNode->removeChild($node);
    }
    return $doc->saveHTML();
}

The problem is that the returned content is wrapped in HTML <!DOCTYPE html PUBLIC (...).
How can I return the content without any additional tags?
Comment: i would do that by playing with `strpos/substr` for getting the `` contents and then calling `strip_tags` on it. DOM parsers will lose a lot of time parsing/making arrays which is unneeded.
Answer: If you just want to remove tags from text, DOMDocument is an extraordinarily heavyweight way of doing that. Is there some reason that strip_tags won't suffice?
Comment: No, because then you are just stripping the tags and not the content in between.


Can the split of an AB test be different than 50-50?

Question: I'm running a AB testing at my company, but the split is somehow different than 50-50.
Is my test still correct? Can the split be 55-45, or 60-40, and so on?
When should I be worried?
Sorry if the question is too vague, but I believe it's very straightforward and I haven't seen any similar question.
Answer: There is hardly any problem at performing a A/B test whith unequal sample sizes. But you don't want samples too unbalanced because the precision of the test depends more on the lesser sample size than on the greater (the biggest they are, the better, I bet you already know).
Therefore, an A/B test with sample sizes 50 and 50 is more powerful than the same test with sample sizes 20 and 80.
Answer: @carlo has covered the case where the experimenter specifies an uneven split (e.g. 80/20 split) prior to starting the experiment, why that is fine, and scenarios where it might not be ideal.
However, the wording of the original question might also be suggesting that the OP has specified a 50/50 split prior to starting the experiment, and is seeing something that is not 50/50 during analysis.
If the discrepancy is too extreme (beyond randomness), it is said that a Sample Ratio Mismatch (SRM) has occurred. Many things can cause SRM, though it is usually the first indication that something is wrong with your experiment, and the results may not be trustworthy. See e.g. this article for some examples and existing work on the online A/B test space.
Whether a discrepancy is extreme enough to raise alarm depends on how many samples were involved in the first place. If one intended for a 50/50 split, a 49/51 split might be fine if the experiment involved 100 visitors, but definitely not if the number is 10 million. A common way to test for SRM is to use a chi-squared goodness of fit test. This article suggests multiple ways to implement the test.


jQuery - set div width to sum of it's children

Question: I have following setup:
html:

css
#holder { width: 800px; }

now, i want to make jQuery gallery and will move line of images to the left and right with negative margin-left of inner div.
However, I have to tell s to float to left and set inner div's width to sum of widths of images.
How can I do this some clean and nice way?
thank you
Answer: var sum=0;
$('#holder img').each( function(){ sum += $(this).width(); });
$('#holder > div').width( sum );

//alert(sum);

this should do the trick ..
The float to the images, you can apply it with css
#holder img{float:left;}

Comment: @Adam, yes i wasn't sure if you wanted that .. but being in the same line in the question i added it as bonus :)
Comment: this save me a lot of problems with translation in my blog!


Criar uma tableView com 616 itens

Question: Tenho que criar uma tabela com 616 itens, cada item possuem 5 detalhes.
Exemplo:
item 1 - Aspirina
Risco: Medio
Lactacao: Alto
Gravide: Baixo
item 2 - Dipirona
Risco: Medio
Lactacao: Alto
Gravide: Baixo
...
Na tabela irá aparecer somente o nome do item (Aspirina, Dipirona, ...)
Quando clicado no item da tabela, abre uma detailviewcontroller para mostrar o conteúdo restante.
Qual a melhor forma de se fazer isso?
Se fossem poucos itens ate que eu faria isso na mão mesmo, criando instância de objeto, mas com 616, como faço?
Answer: Vou descrever aqui uma solução que adota a seguinte arquitetura:

Os dados são locais ao dispositivo, inicialmente armazenados em memória não-volátil e estão em formato property list;
Os dados são carregados da memória não-volátil e armazenados em dicionários na memória. Todos os dados são lidos para a memória de uma só vez e não defini uma classe Medicamento específica;
As gradações de risco dos medicamentos são armazenadas como strings

O primeiro passo é criar um arquivo .plist contendo todos os dados a serem apresentados. No menu principal, escolha File > New > File… e então, dentro da categoria iOS, Resource > Property List. Neste exemplo, dei-lhe o nome Medicamentos.plist. Você pode então preencher os dados manualmente. Para esta resposta, eu defini o arquivo como contendo um dicionário com chave "medicamentos", que, por sua vez, é um vetor contendo uma lista de medicamentos. Cada medicamento individual é um dicionário contendo chaves "nome", "risco", "lactacao" e "gravidez". O arquivo poderia começar diretamente como um vetor, mas ter um dicionário facilita a inclusão de outros dados no futuro sem que seja necessário alterar código que se baseia nos dados antigos.

Se você ⌃-clicar o arquivo no navegador de projetos, você pode escolher a opção Open As > Source Code: o Xcode irá exibir-lhe os mesmos dados, desta vez em formato XML:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>medicamentos</key>
    <array>
        <dict>
            <key>nome</key>
            <string>Aspirina</string>
            <key>risco</key>
            <string>Médio</string>
            <key>lactacao</key>
            <string>Alto</string>
            <key>gravidez</key>
            <string>Baixo</string>
        </dict>
        <dict>
            <key>nome</key>
            <string>Dipirona</string>
            <key>risco</key>
            <string>Médio</string>
            <key>lactacao</key>
            <string>Alto</string>
            <key>gravidez</key>
            <string>Baixo</string>
        </dict>
    </array>
</dict>
</plist>

Se esses dados vêm de um banco de dados, você pode escrever um script que os formata da forma acima para evitar ter que digitá-los. Além disso, talvez seja mais fácil editar como XML do que visualmente.
Em seguida, você terá uma representação externa dos dados que fará parte do app bundle gerado pelo Xcode e instalado nos dispositivos.
No view controller mestre, você precisa carregar os dados e armazená-los. Neste exemplo, estou armazenando-os em uma variável de instância chamada _medicamentos:
@interface BAVMasterViewController ()
@property (nonatomic, copy) NSArray *medicamentos;
@end

No método -viewDidLoad, escreva o seguinte:
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSURL *plistURL = [[NSBundle mainBundle] URLForResource:@"Medicamentos" withExtension:@"plist"];
    NSDictionary *plist = [NSDictionary dictionaryWithContentsOfURL:plistURL];
    self.medicamentos = plist[@"medicamentos"];
}

O primeiro passo é obter a URL que descreve o local onde está armazenado o arquivo Medicamentos.plist dentro do app bundle. Feito isso, o método +[NSDictionary dictionaryWithContentsOfURL:] lê os dados no formato plist e cria um dicionário (lembre-se de que definimos que o arquivo .plist é um dicionário) com base no arquivo. O dicionário contém uma única chave chamada "medicamentos", cujo valor é um vetor contendo uma lista de medicamentos. Armazenamos esse vetor na propriedade medicamentos.
Feito isso, basta usar o vetor como os dados do view controller mestre. Cada elemento desse vetor é um dicionário contendo "nome", "risco", "lactacao" e "gravidez". No mestre, exibimos o nome do medicamento:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    NSDictionary *medicamento = self.medicamentos[indexPath.row];
    cell.textLabel.text = medicamento[@"nome"];
    return cell;
}

Resultando em:

Quando o usuário toca um medicamento, seguimos para o view controller detalhe, passando o medicamento escolhido pelo usuário:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        NSDictionary *medicamento = self.medicamentos[indexPath.row];
        [[segue destinationViewController] setMedicamento:medicamento];
    }
}

Note que o view controller detalhe recebe -setMedicamento: para saber qual medicamento exibir. Além disso, contém labels para cada dado exibido:
@interface BAVDetailViewController : UIViewController
@property (strong, nonatomic) NSDictionary *medicamento;
@property (weak, nonatomic) IBOutlet UILabel *riscoGeralLabel;
@property (weak, nonatomic) IBOutlet UILabel *riscoLactacaoLabel;
@property (weak, nonatomic) IBOutlet UILabel *riscoGravidezLabel;
@end

Ao receber um medicamento, ele é armazenado e a view é configurada:
- (void)setMedicamento:(NSDictionary *)medicamento
{
    if (medicamento != _medicamento) {
        _medicamento = medicamento;
        [self configureView];
    }
}

E, na configuração da view, os dados do medicamento são enviados para os labels e o título do detalhe recebe o nome do medicamento:
- (void)configureView
{
    // Update the user interface for the detail item.

    if (self.medicamento) {
        self.title = self.medicamento[@"nome"];
        self.riscoGeralLabel.text = self.medicamento[@"risco"];
        self.riscoLactacaoLabel.text = self.medicamento[@"lactacao"];
        self.riscoGravidezLabel.text = self.medicamento[@"gravidez"];
    }
}

Resultando em:

Esta é uma solução simples. Algumas alternativas para a arquitetura da solução:

Obter os dados de servidores Web, quiçá com cache local no aplicativo;
Usar outro formato de serialização. JSON é popular em serviços Web e nada impede que seja usado localmente. Se os dados forem muitos e tê-los todos em memória (como ocorre com plist e JSON) não é viável, você pode usar Core Data ou SQLite. Da forma como você apresentou — 616 medicamentos —, não precisa preocupar-se com memória;
Em vez de usar strings literais para as chaves do dicionário, usar constantes. Isto evita erros de digitação e torna mais fácil alterar chaves se e quando necessário;
Em vez de usar dicionários para armazenar os dados dentro do processo, convertê-los de dicionários para instâncias de uma classe modelo, e.g. Medicamento, que contém propriedades para cada dado. Desta forma, fica mais claro que dados estão disponíveis e quais os respectivos tipos. O Mantle é um framework do GitHub que pode ajudá-lo na manutenção desse tipo de classes modelos;
Em vez de armazenar as gradações de risco como strings, você pode armazená-las como números (e.g. 1 para Baixo, 2 para Médio e 3 para Alto) e convertê-los para strings apenas ao apresentar os dados. Isto irá reduzir a memória usada pelo processo dado que números são representados mais compactamente do que strings.
Comment: Ola, nao chamaria isso de resposta de um ótimo tutorial, agora deixa eu lhe perguntar, e se eu precisar de adicionar um Search com o NSPredicate para filtrar com os nomes dos medicamentos como funcionaria isso para eu nao perder a referencia na detailviewcontroler, Muito Obrigado
Comment: Perfeito, me ajudou muito ! Eu precisava fazer um exemplo de diretório, com tableview e comecei a partir do seu exemplo. Muito obrigado

Criar uma tableView com 616 itens


Tkinter opens second GUI first

Question: I'm trying to build a login screen for practice and I'm having trouble with it. The general idea is that pressing the Login button closes the current window and opens another in a separate file. However, when I run the main file it opens the GUI window created in the second file. I'm not sure what would be causing it to do this.
import tkinter as tk
import loginEntry

HEIGHT = 200
WIDTH = 500

def login_function():
    root.destroy()
    loginEntry.NewScreen()

def register_function():
    print("Register!")

root = tk.Tk()

root.title("Login Screen")
root.resizable(False, False)

canvas = tk.Canvas(root, height = HEIGHT, width = WIDTH)
canvas.pack()

frame = tk.Frame(root, bg='grey')
frame.place(relx=0.1, rely=0.25, relwidth=0.8, relheight=0.5)

login = tk.Button(frame, text="Login", command=login_function)
login.place(relx=0.05, rely=0.25, relwidth=0.425, relheight=0.5,)

register = tk.Button(frame, text="Register", command=register_function)
register.place(relx=0.525, rely=0.25, relwidth=0.425, relheight=0.5,)

introduction = tk.Label(root, text="Hello and welcome to DogNet, please login below.", font='bold 12')
introduction.place(relx=0.5, anchor='center', rely=0.1)

root.mainloop()

and then the second file
import tkinter as tk

def NewScreen():
    root = tk.Tk()

    canvas = tk.Canvas(root, bg='black')
    canvas.pack()

    root.mainloop()

NewScreen()

Comment: Read [Why are multiple instances of Tk discouraged?](https://stackoverflow.com/questions/48045401/why-are-multiple-instances-of-tk-discouraged)
Answer: This is because, in your second file, you are calling the definition when it is imported.
import tkinter as tk

def NewScreen():
    root = tk.Tk()

    canvas = tk.Canvas(root, bg='black')
    canvas.pack()

    root.mainloop()

NewScreen() #< here you call the definition

This means that the series of events that happen in your program are as follows.

First file starts
Second file is imported
Definition "NewScreen" is called
tkinter mainloop starts which puts your program into a loop and stops the program from going on to any new lines until the loop is closed
Comment: That makes sense! I'm not sure how to stop it from doing this though? Will it always run NewProgram when it's imported?
Comment: It is running NewProgram because you tell it to on the last line of your second file.
Comment: @Bramblethorns We all do it sometimes!

Tkinter opens second GUI first


Remove filter formats help text

Question: In D6 and D7, with a simple form_alter you could unset $element['format'], but now the format help and the format tips are added in a #process method.
How can I remove them?
Comment: Form alter and replace the #process callback with a custom one maybe?
Answer: Apparently you can't hook into the #process phase, but you can still do a #pre_render, from /Drupal/Core/Render/Renderer.php
// If the default values for this element have not been loaded yet, populate
// them.
if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
  $elements += $this->elementInfo->getInfo($elements['#type']);
}

// Make any final changes to the element before it is rendered. This means
// that the $element or the children can be altered or corrected before the
// element is rendered into the final text.
if (isset($elements['#pre_render'])) {
  foreach ($elements['#pre_render'] as $callable) {
    if (is_string($callable) && strpos($callable, '::') === FALSE) {
      $callable = $this->controllerResolver->getControllerFromDefinition($callable);
    }
    $elements = call_user_func($callable, $elements);
  }
}

For example, to hide the element format of the body field of an article:
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['#pre_render'][] = 'mymodule_form_pre_render_body';
}

function mymodule_form_pre_render_body(array $element) {
  foreach (Element::children($element) as $key) {
    if ($key == 'body') {
      foreach (Element::children($element[$key]['widget']) as $widget) {
        $element[$key]['widget'][$widget]['format']['#access'] = FALSE;
      }
    }
  }

  return $element;
}

Remove filter formats help text


prove the sign of $1+2x-e^x$ around 0

Question: I want to prove that the sign of $1+2x-e^x$  around $0$ is negative if $x\to 0^-$ and positive if $x\to 0^+$. If I replace $e^x$ by its equivalent function (the tangent at 0) I conclude that the sign of this expression depends on the sign of $x$ as I have $1+2x - 1-x $.
I need this step to compute the limit of $\frac{1+2x+e^x}{1+2x-e^x}$ when $x\to 0$
Comment: Hint: you should be able to evaluate $\lim_{x\to0} \frac{1+2x-e^x}x$ as a nonzero constant; since $1+2x-e^x = \frac{1+2x-e^x}x \cdot x$, that will tell you the sign of $1+2x-e^x$ on each side of $0$.
Comment: If you can use derivatives, then you know $f(x)=1+2x−e^x$ is increasing at $0$. Combine this fact with $f(0)=0$.
Comment: The derivative of $1+2x-e^x$ at $x=0$ tells you what happens either side of the $x=0$.
Comment: What about the Taylor series of $e^x$ ?
Answer: You should already know from the definition that:
$$
e^x=\lim_{n\to\infty}(1+\frac xn)^n=1+x+\frac{x^2}{2!}+...+\frac{x^k}{k!}+...
$$
Obviously for all $x>0$:   $e^x>1+x$. To consider negative $x$'s we write:
$$
e^x=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}(1-\frac x4)+...+\frac{x^{2m+1}}{(2m+1)!}(1-\frac x{2m+2})+...
$$
Thus for small negative $x$, all the terms starting on the $\frac{x^3}{3!}(1-\frac x4) $ term are negative and we conclude:
$$
e^x<1+x+\frac{x^2}2
$$
for small negative $x$.
From the above we get that $1+2x-e^x>1+2x-(1+x)=x>0$ for small positive $x$ and  $1+2x-e^x<1+2x-(1+x+\dfrac{x^2}{2})=x-\dfrac{x^2}{2}<0 $ for small negative $x$.

prove the sign of $1+2x-e^x$ around 0


Relationship between modules and maximal ideals of a commutative ring

Question: Let  $A$ be an integral domain, $M$ an $A$-module, and $m\in M$. Now for all maximal ideals $\mathfrak{m}$ there exists an $n\notin \mathfrak{m}$ such that $nm=0$. Why does this mean that $m=0$?
Answer: Hint. Show that the ideal generated by $n\notin\mathfrak m$, when $\mathfrak m$ runs over the maximal ideals of $A$, is the whole ring.


duplicate every row multiple times in linux

Question: I have a data file
a b c
d e f
g h i

and want to dublicate every row x times. So if x was chosen as 2 I would like to get:
a b c
a b c
d e f
d e f
g h i
g h i

Is there an easy and fast way to do this with simple linux commands? Otherwise any other ideas how to realize it, e.g. with Python?
Answer: With perl you can do this
perl -ne 'for$i(0..2){print}' your_input_file

and with awk
awk '{for(i=0;i<2;i++)print}' your_input_file

and with sed
sed -n '{p;p;}' your_input_file


IS optimization unnecessary in SVM?

Question: According to here, Now knowing the $a_i$ we can find the weights $w$ for the maximal margin separating hyperplane:
\begin{align*}
w = \sum_{i=1}^{l} a_i y_i x_i
\end{align*}
I cannot understand what this says. I have trouble in how to choose $a_i$. I think we must conduct Newton-method, Pegasos, SMO, or stuff like that.
In addition, I want to implement hard-margin (linear-separable) SVM in Python. So I am seeking for the most simplest(easiest) optimization method.
I am very grateful to you if you make some answers taking this into account.
Answer: You're correct that finding the $a_i$ requires some form of iterative optimization. The thing that doesn't require optimization is converting from the dual variables $a_i$ to the primal variable $w$, which just follows the formula that you wrote.
Comment: It does make sence.Thank you. And as I wrote, I want the most simplest optimization method, then I was wondering if you could give me some ideas?
Comment: If you actually want to use it for something, use an existing library, e.g. scikit-learn's bindings to libsvm. If you want to implement it yourself for learning purposes, stochastic gradient descent is probably simplest.
Comment: SGD is for unconstrain ploblem, isn't it?
Comment: Ah, yeah, you'd have to implement some kind of workaround for the constraints (not sure if you can easily project?). Or you could implement SMO, I don't know how complicated it is (never done it).
Comment: OK. It is difficult for me to implement SMO. But, Thank you.

IS optimization unnecessary in SVM?


How can I specify the load balancer for a CloudWatch alarm?

Question: I am trying to create a Cloud Formation template that includes Cloud Watch alarms based on specific metrics from specific load balancers. My question is how do I specify the load balancer for each alarm? I'm pretty sure you have to specify the ARN somewhere but I'm not sure how to reference the ARN from load balancers in different stacks or where to reference them. I am pretty new to AWS services so any help would be appreciated. Thanks!
<code>"500ErrorAlarmEast": {
        "Type" : "AWS::CloudWatch::Alarm",
        "Properties" : {
            "AlarmName" : "500ErrorAlarm",
            "ComparisonOperator" : "GreaterThanOrEqualToThreshold",
            "EvaluationPeriods" : 1,
            "MetricName" : "HTTPCode_ELB_500_Count",
            "Namespace" :  { "Ref": "AlarmNamespace" },
            "Period" : 300,
            "Statistic" : "Sum",
            "Threshold" : 5,
            "AlarmDescription" : "Unusually high level of internal 500 ALB East errors.",
            "AlarmActions" : [ { "Ref": "SnsTopic" } ],
            "TreatMissingData" : "notBreaching",
            "InsufficientDataActions" : []
        }
    }
</code>
Answer: pass the dimension parameter
"Dimensions": [
{
"Name": "LoadBalancer",
"Value": {
"Ref": "WebAppALBId"
}
}
],


To generate random UUID which is 2 Digit Long

Question: I am Using Boost Random generator to generate Random UUID's.The Random UUID that i generate now is quite Lengthy.Instead i want to generate a UUID which is a 2 Digit like for eg:"Dz"
The Line of Code i am using now is
std::string strAK = to_string( boost::uuids::random_generator()() );
How to Modify this code and Generate a UUID which is 2 digit long.
Comment: there's a reason why a UUID is so long.....
Comment: Taking a step back, what are you going to be doing with this 2 character string?
Comment: Generate something that's two digits long if you must. Just don't call it a UUID, and don't expect to avoid clashes.
Answer: Trivially,
<code>std::string strAK = to_string( boost::uuids::random_generator()() ).substr( 0, 2 );
</code>
but as has already been commented, this isn't going to be universally unique.
Comment: It isn't even likely to be unique over the range this 2 char string could potential represent, depending on the base (i.e 36 for all upper alpha and 0-9). If he truly only needs 2 chars to cover all possibilities, it might be better to use an auto incrementing  counter which would give 100 possible combinations or if he needs more than that convert the decimal number to a different base.
Comment: Thanks Philip...As u rightly said,It would be wrong to call the 2 digit ID as UUID.I need it because i already have a typical UUID and i need the 2 digit ID to link to this inside a map...


On well-definedness of $f : Y \to X/H$ for Hatcher's Algebraic Topology, Exercise 1.3.24(a)

Question: I refer to Exercise 1.3.24(a) of Hatcher's Algebraic Topology:

Given a covering space action of a group $G$ on a path-connected, locally path-connected space $X$, each subgroup $H \subseteq G$ determines a composition of covering spaces $X \to X/H \to X/G$. Show that every path-connected covering space between $X$ and $X/G$ is isomorphic to $X/H$ for
some subgroup $H \subseteq G$.

The common tactic is to define $H \subseteq G$ as the subgroup of deck transformations of the covering map $p : X \to Y$, which induces a second covering map $p' : X \to X/H$, then show that $p$ and $p'$ are isomorphic. Then, define maps $f : Y \to X/H$ and $g : X/H \to Y$ as follows: For $x \in p^{-1}(y)$, define $f(y) = Hx$, and $g(Hx) = p(x)$. We conclude by showing that they are well-defined, continuous, and induces the required isomorphism.
My main issue lies in the well-definedness part. The well-definedness of $g$ is clear, but I struggle to show the same for $f$. Given $x_1,x_2 \in X$ such that $p(x_1) = p(x_2) = y$, we want to show that $Hx_1 = Hx_2$, or equivalently $x_2 = hx_1$ for some $h \in H$. Since $p(x_1) = p(x_2)$, the normality of the covering space $X \to X/G$ ensures the existence of $g \in G$ such that $gx_1 = x_2$.
Now if $g \in H$, then we are done. However, since $p : X \to Y$ may not be normal, I'm not sure how to go about showing this.
Any help is appreciated.
Answer: Showing that $g\in H$ amounts to showing that for all $x\in X, p(gx) = p(x)$. So fix $x\in X$. Since $X$ is path connected, there is a path $\alpha\colon [0,1]\to X$ from $x_1$ to $x$. Let $q$ denote the covering map $X\to X/G$. Then $q\alpha = qg\alpha$ and both $p\alpha$ and $pg\alpha$ are lifts, both starting at $y$. Since $Y\to X/G$ is a covering, uniqueness of lifts implies that $p(x) = p\alpha(1) = pg\alpha(1) =p(gx)$.
Answer: I am also working on this exercise and I met with exactly the same problem. But it turns out to be very simple.
Notations: $p:X\rightarrow Y$, $q:X\rightarrow X/G$, $r:Y\rightarrow X/G$
We want to show that the covering map $p$ is normal. Suppose it's not normal, then $\exists x_1, x_2\in p^{-1}(y)$ s.t. $p_*\pi_1(X,x_1)\neq p_*\pi_1(X,x_2)$. Note that $r_*$ is injective since it's a covering map. So $r_*p_*\pi_1(X,x_1)\neq r_*p_*\pi_1(X,x_2)$. The diagram commutes, so $q_*\pi_1(X,x_1)\neq q_*\pi_1(X,x_2)$, which contradicts with the fact that $q_*$ is a normal covering map.


Trazer somente a primeira ocorrência de uma regex

Question: Como buscar em uma query somente a primeira data?
Por exemplo:

30/09/2018 e 14/10/2018 e 21/10/2018

Gostaria de trazer somente a primeira data. Estou usando assim, [0-9]{2}/[0-9]{2}/[0-9]{4}, porém traz tudo.
Quero só a primeira data. Tem 10 caracteres. Tem algum comando que posso colocar na minha regex que só aceita trazer os 10 primeiros?
Estou usando MySQL:
 WHERE REGEXP '[0-9]{2}/[0-9]{2}/[0-9]{4}'

Comment: https://regex101.com/r/Gqd385/1
Comment: Tem como fazer, mas a resposta depende da linguagem que vc está usando. Clique em [edit] e adicione esaa informação, e o código que vc usou
Comment: @Rod Porque o MySQL [não suporta a sintaxe `\d`](https://dev.mysql.com/doc/refman/8.0/en/regexp.html#regexp-syntax), somente `[0-9]`. Viu como é importante colocar todos os detalhes na pergunta desde o começo? :-)
Comment: só retirar o `/g`. Tire o modificador `g`.
Comment: @hkotsubo editado.
Comment: @ValdeirPsr perfeito, só que no MYSQL não trouxe registros. REGEXP '^(\d{2}\/\d{2}\/\d{4})';  Sabe porque?
Answer: Quando você faz uma query assim:
select campo from tabela where campo REGEXP '[0-9]{2}/[0-9]{2}/[0-9]{4}';

Você está trazendo o campo (no caso, todo o valor 30/09/2018 e 14/10/2018 e 21/10/2018), desde que ele satisfaça a regex (ou seja, desde que ele tenha números no formato indicado). Por isso que a query traz "tudo".
Para extrair somente uma parte do campo, use REGEXP_SUBSTR (disponível a partir do MySQL 8). Supondo que a tabela seja:
create table tabela (
   campo varchar(200)
);

insert into tabela(campo) values('30/09/2018 e 14/10/2018 e 21/10/2018');
insert into tabela(campo) values('blablabla e 14/10/2018 e 21/10/2018');
insert into tabela(campo) values('nao tenho nenhuma data');

Podemos fazer:
select REGEXP_SUBSTR(campo, '[0-9]{2}/[0-9]{2}/[0-9]{4}') from tabela;

E o resultado será:
30/09/2018
14/10/2018
null

O terceiro campo retorna null, pois o valor do campo não corresponde à regex. Você pode alterar a query para só retornar o trecho desejado quando o campo tiver uma data no formato desejado:
select REGEXP_SUBSTR(campo, '[0-9]{2}/[0-9]{2}/[0-9]{4}')
from tabela where campo REGEXP '[0-9]{2}/[0-9]{2}/[0-9]{4}';

Agora o where verifica se o campo possui alguma data, e o REGEXP_SUBSTR extrai somente o trecho desejado. O resultado é:
30/09/2018
14/10/2018

Se quiser a segunda ocorrência, basta passar 2 parâmetros adicionais: a posição inicial e a ocorrência:
--- traz a segunda ocorrencia
select REGEXP_SUBSTR(campo, '[0-9]{2}/[0-9]{2}/[0-9]{4}', 1, 2)
from tabela where campo REGEXP '[0-9]{2}/[0-9]{2}/[0-9]{4}';

No caso, a posição inicial é 1, e a ocorrência é 2 (ou seja, vou pegar a segunda data presente no campo). O resultado é:
14/10/2018
21/10/2018

Veja este exemplo rodando no DB Fiddle.

Mas há um porém: se tiver algo como 112/10/2019, a regex pegará o trecho 12/10/2019. Para evitar estes casos, você pode mudar a regex para:
(^|[^0-9])[0-9]{2}/[0-9]{2}/[0-9]{4}([^0-9]|$)

No início há o trecho (^|[^0-9]): o | significa "ou". Portanto, este trecho significa "início da string" (^) ou "qualquer coisa que não seja número" (o [^ significa que não quero o que vem depois, ou seja, não quero 0-9 - nenhum dígito de zero a 9).
E no final há ([^0-9]|$): qualquer caractere que não seja número ou o final da string ($). Isso garante que não pegará casos como 112/10/2019. Veja aqui a diferença.
Em outras linguagens e engines é possível usar \b em vez de (^|[^0-9]) e ([^0-9]|$), mas o MySQL não suporta isso.

Antes do MySQL 8 não havia REGEXP_SUBSTR, então é um pouco mais complicado. Se a data estiver logo no início da string, dá para usar a solução proposta pelo Luiz Fernando. Mas se a data estiver em qualquer posição da string, acho mais fácil extrair os dados usando alguma linguagem de programação e manipulá-los lá (pois as linguagens geralmente possuem mais recursos de regex que o MySQL, que é bem limitado).

Datas x Regex
Apenas um adendo sobre o uso de regex para verificar datas. A regex [0-9]{2}/[0-9]{2}/[0-9]{4} aceita valores que não são datas válidas, como 99/99/9999 e 00/00/0000, veja aqui um exemplo. Isso porque [0-9] significa "qualquer dígito de 0 a 9".
É possível melhorar um pouco usando algo como:
(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)[0-9]{2}

Isso garante que os dias só podem ser de 01 a 31, os meses de 01 a 12, e os anos de 1900 a 2099.
Mas ainda sim, esta regex aceita datas como 31/04/2019 (sendo que abril só tem 30 dias) e 29/02/2019 (29 de fevereiro em um ano não bissexto), veja. Não ficou claro como os dados são inseridos no seu banco, mas pode ser que ocorra um erro de digitação, ou simplesmente uma data inválida apareça no meio da string.
Até é possível ter uma regex que verifique essas condições. Nesta pergunta do SOen há alguns exemplos, mas eles são tão complicados que começa a não valer a pena. Veja uma delas, só para ter uma ideia:
^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$
Entendeu? Eu também não.
Lembrando que \d não é suportado pelo MySQL, então você deve trocá-los por [0-9]. Mesmo assim, na minha opinião não vale a pena usar essa regex. Ela é um problema para entender e para manter futuramente (boa sorte para quem tiver que alterá-la e adicionar novos casos, por exemplo).
É preciso achar um equilíbrio. Usar a regex gigante acima garante que não serão retornadas datas inválidas, mas é um pesadelo de manutenção. Usando as expressões sugeridas no início desta resposta, você obtém trechos que parecem uma data (pode acertar na maioria dos casos, mas também trará algumas datas inválidas, algo que você deve avaliar se é aceitável). Uma vez extraídos estes trechos, uma validação adicional poderia ser feita posteriormente, de preferência usando alguma API de datas (ou seja, extraia estes dados do banco e faça a validação usando sua linguagem de programação favorita).
Regex é uma ferramenta poderosa, mas não é uma solução mágica que resolve todos os casos.
Comment: foda demais, obrigado.
Answer:
Talvez não seja necessário o regex:

Supondo que temos a seguinte tabela e queremos pegar a primeira data do campo descrição:

Executando o comando abaixo:
select left(descricao , 10) from tb_dados;

Teremos este resultado:

Com regex:

select left(descricao,10) FROM tb_dados where descricao RLIKE('^[0-9]{2}/[0-9]{2}/[0-9]{4}');

Comment: Muito simples e funcional. Obrigado.
Comment: @Rod Apenas lembrando que esta solução só funciona se o campo começa com uma data. Se tiver algum texto antes e a primeira data aparece no meio do texto, aí é melhor usar `REGEXP_SUBSTR`, [como eu sugeri](https://pt.stackoverflow.com/a/360903/112052). Eu preferi deixar uma resposta mais geral porque não tinha ficado claro que em todos os seus casos, a data aparece no início :-)
Comment: Fiz assim: select id_tabela,titulo,data_gabarito,left(data_gabarito,10) as d_gabarito FROM tabela
where data_gabarito RLIKE('^[0-9]{2}/[0-9]{2}/[0-9]{4}')
order by str_to_date(d_gabarito,'%d/%m/%Y') desc;
Comment: @hkotsubo porém surgiu um problema, não é possível manusear o alias d_gabarito pra fazer um refinamento no where. Queria exibir apenas exibir os registros com dois dias anteriores a data d_gabarito.
Comment: resumindo...o campo data_gabarito foi rescrito pelo regex, também foi transformado de string para data na ordenação pra exibir primeiro as antigas. Agora gostaria de pegar essas datas e só exibir as que são próxima de hoje (now). Exemplo: hoje é 07/02/2019 só exibiria registros com datas a partir de 05/02/2019. Complexo não? rs
Comment: @Rod Entendi (eu acho) :-) De qualquer forma, sugiro que nas próximas vezes coloque na pergunta os detalhes que podem influenciar na resposta. Lembre-se que os demais usuários do site não conhecem o seu sistema, e esses detalhes podem te ajudar a ter respostas mais precisas :-)


LineChart add whitespace to top

Question: I'm trying to add whitespace to the top of my chart so I can fit my title etc. into the top without overlapping with the grids, is there a simple way to do this? If I increase the height then the x/y axis scales with it, can I make them smaller?
Answer: LineChart.chart.setExtraTopOffset()
That method took way too long to find.

LineChart add whitespace to top


Sendgrid ~ where to set preheader when sending HTML Dynamic Template via Web Api?

Question: There are two options to build a Dynamic Template: Via the 'Design Editor' or the 'Code Editor'
When choosing the 'Design Editor' the 'DYNAMIC VERSION SETTINGS' have a field for

Version Name
Subject
Preheader

When choosing the 'Code Editor', Preheader is missing.

So how to set the preheader with a self-coded Dynamic Template sending via the Web Api?
const msg = {
        to: '***',
        from: '***',
        templateId: '***',
        dynamic_template_data: {
            subject: 'Subject can be set via dynamic variable',
            preheader: 'But how to set me..?!?',
        },
    }

Answer: My understanding is that a preheader is the first bit of text content in the HTML  of the email. So while that can be placed in the design editor for you, when you have control over the code of an email, you will need to do that yourself.
The important thing is that the preheader text is the first content, so place it right after you open the  tag. You also likely want to hide it, this snippet should achieve that for you:

    But how to set me..?!?

If you want to then set the text for the preheader dynamically in your API call, you can use handlebars.

    {{ preheader }}

And then send the preheader as part of your dynamic_template_data as you showed in your question:
const msg = {
        to: '***',
        from: '***',
        templateId: '***',
        dynamic_template_data: {
            subject: 'Subject can be set via dynamic variable',
            preheader: 'Now I appear in the email',
        },
    }


Conditional rendering with ternary operator in react

Question: I am trying to conditionally render few messages on my page. Following is the simplified code of my actual scenario.

    {
        isCondition1 == true ?
           'Show issue list'
        :
            isConditionA == true?
               'Show message for condition A'
            :
                'Show error message'
    }

    {
        isCondition2 == true?
           'Show team issue list'
        :
            isConditionA == true?
               'Show message for condition A'
            :
               'Show error message'
    }

I want to take out common things from the above and use it in the code.
const msgNoIssues = (
    isConditionA == true?
       'Show message for condition A'
    :
       'Show error message'
);

And use it as follows:

    {
        isCondition1 == true?
           'Show issue list'
        :
           {msgNoIssues}
    }

    {
        isCondition2 == true ?
           'Show team issue list'
        :
           {msgNoIssues}
    }

But it is giving an error message:

Objects are not valid as a React child (found: object with keys
  {msgNoIssues}). If you meant to render a collection of children, use
  an array instead or wrap the object using createFragment(object) from
  the React add-ons.

Can it be achieved without react add-ons? Is there any better way of doing it?
Answer:
When {} is needed in JSX?

We need to use {} to put js expressions inside JSX, so put ternary operator inside {}.

Reason of this error: Objects are not valid as a React child

Meaning of { msgNoIssues } is { msgNoIssues: msgNoIssues } that means you are trying to render an object with key msgNoIssues, that's why it is throwing the error: Objects are not valid as a React child (found: object with keys {msgNoIssues}).
Solution:
Remove {} around the msgNoIssues, write it like this:

    {
        isCondition1 == true ?
            'Show issue list'
        :
            msgNoIssues
    }

    {
        isCondition2 == true ?
            'Show team issue list'
        :
            msgNoIssues
    }

Check this Snippet (meaning of { a }):

let a = 10;

let obj = {a};

console.log('obj = ', obj);

Check the DOC: Embedding Expressions in JSX and Conditional Rendering


How to determine if a div has a specific element with specific class?

Question: How can I determine if my  div.class has a specific child element e.g table? with a specific class? Is there a javascript/Jquery function for this?
In my case, I want to know if there's already a

 inside my

any suggestions, answers, and comments would really be appreciated, Thank you and have a good day!
Answer: you can use
if($('.anotherdiv .mytable').length){
    //exists
}

Answer: Search your div for elements with class name "myTable". If you have other non-table elements with this class and you would only like to find tables, throw a getElementsByTagName inbetween.
var yourDiv = document.getElementsByClassName('anotherdiv');
var yourTable = yourDiv[0].getElementsByClassName('myTable');
alert("Your div has " + yourTable.length + " myTable elements in it!");


If $T$ is a sufficient statistic for $\theta$, is $H(\theta\mid x) = H(\theta\mid T(x))$?

Question: I was trying to prove that sufficient statistics attain equality in the data processing inequality by a slightly different route than I usually see, and came across an odd expression. (I care more about understanding the odd expression than about proving the data processing inequality).
So if we have $\theta \longrightarrow X \longrightarrow T(X)$, the data processing inequality gives us
$$I(\theta;X) \ge I(\theta;T(X))\tag{1}$$
and expanding out into entropies yields $H(\theta) - H(\theta\mid X) \ge H(\theta) - H(\theta\mid T(X))$, which yields $$H(\theta\mid X) \le H(\theta\mid T(X))\tag{2}$$
So $(1)$ attains equality iff $(2)$ does. But how on earth do I even interpret $(2)$? $T(X)$ is generally a non-injective mapping, and so it seems very strange to me that a non-injective mapping (which should strictly decrease discrete entropy) could possibly lead to an equality.
I was trying to manipulate the Neyman-Fisher factorization to try and flip into the form of $(2)$, but to no avail.
Any thoughts?
Thanks!
Answer: Yes, it is true that if $T$ is sufficient, then $$H(\theta | x) = H(\theta|T(x))$$.
From the definition of sufficiency, we have that $$P(x|T(x), \theta) = P(x|T(x))$$.
And now
$$P(\theta | x) = \frac{P(x, \theta)}{P(x)} = \frac{P(x, T(x), \theta)}{P(x, T(x))} = \frac{P(x|T(x), \theta)P(\theta, T(x))}{P(x|T(x))P(T(x))}$$
Now we use the above fact to simplify:
$$\frac{P(x|T(x), \theta)P(\theta, T(x))}{P(x|T(x))P(T(x))} = \frac{P(\theta, T(x))}{P(T(x))} = P(\theta | T(x))$$
Since $H$ is a function of $P$ we obtain the result.


What resources are there to teach Ukrainian refugees music theory?

Question: I have a Ukrainian student in one of my music classes.  We can get past most of the language barriers with Google Translate, but the translation for music theory is a little too complicated sometimes.  Are there any good resources for converting western (US) music theory to the equivalent music theory used in Ukraine?  Thank you!
Comment: Your reputation score is high enough for the chat rooms. I suggest posting this question there. You might also try the [Ukrainian Language SE](https://ukrainian.stackexchange.com/) or chat room.
Comment: What level are they? Is there any reason not to teach them the theory you know the best?
Comment: High school level.  They do not know any English and I'm trying to make it relatable in Ukrainian so I thought it was be easier for me to reach over her side of the fence rather than make her learn a new concept and a new language at the same time.  I'm not sure how theory is taught and quite frankly don't have a lot of spare time to learn it, so if there are resources that already existed I could make assignments from those instead of   trying to create them myself.  I'm not beyond doing that, I just don't have the time.
Comment: That's awesome! Note, the [topics covered here](https://music.stackexchange.com/help/on-topic) don't include resource requests of the "point me toward a book that ___" sort. But seems to me the most important question is: What _are_ the differences in how it's taught? I recommend editing the question to ask that. And I'm guessing the core content is the same, except that Ukrainian (like many languages) [uses solfege syllables](https://music.stackexchange.com/questions/122281/what-letters-are-used-for-guitar-chords-in-ukraine) rather than letters to name pitches.
Comment: Meanwhile, I'm sure there are Ukrainian music theory textbooks; you could simply try to get hold of one (but then *you'd* have to figure out what you were reading!).
Comment: Your objective is laudable, however, asking for resources on this site will render the question closed. Sorry. However, if the student has been brought up using fixed do solfege, you're both going to have to adapt - there's little common ground from that point of view. Unless everything's in key C!
Comment: Try linguee.com instead.
Answer: This doesn't answer directly your question, but I would suggest teaching the theory the way you know it. If it's in English, do it in English.
Don't underestimate your student. After all, music theory, especially on high school level, is not that complicated. There are not so many words to learn. It's the concepts that might be difficult.
Maybe you can try to make sure to play or sing more examples, so that she can easier associate words with sounds. Maybe you can ask her some very basic questions during the classes to make sure she follows. This will be a better use of the time, than trying to translate to a system that you don't know and risking that you're teaching something completely wrong.
I'd suggest asking questions about teaching tips on Academia SE site. Many professors have experience in teaching foreign students, who often come with poor knowledge of the language.
Yes, it might be a bit confusing at the beginning, she may take a while to catch up. Certainly be gentle when grading! But in the end this will benefit her. All theory systems I know, all notation systems, have different flaws. Knowing several of them will only give her better understanding of music. Moreover, it will grant her access to more resources in the future.