I get error , cannot import from file helper

Question: Please help, I get the error below running jupyter notebook.
import numpy as np
import pandas as pd
from helper import boston_dataframe

np.set_printoptions(precision=3, suppress=True)

Error:
ImportError                               Traceback (most recent call last)
<ipython-input-3-a6117bd64450> in <module>
      1 import numpy as np
      2 import pandas as pd
----> 3 from helper import boston_dataframe
      4
      5

ImportError: cannot import name 'boston_dataframe' from 'helper' (/Users/irina/opt/anaconda3/lib/python3.8/site-packages/helper/__init__.py)

Comment: I suspect that you installed `helper` which is this code: https://github.com/gmr/helper available from pypi under the `helper` project. It does not contain a `boston_dataframe` variable. So the question here is which `helper` are you suppose to use for this notebook? Is there a `helper` code somewhere distributed with this notebook?
Comment: This seems like a relative path. See the below answer. If you want to use it more generally then you will want to include it in a number of ways, such as adding the directory to PYTHONPATH. But having this specific code in the same place will be clear which `helper` library/module you're using.
Comment: there is a helper file that came with the notebook. i have downloaded it. It works for other notebooks but not fr this one
Answer: Since you are not giving the where you get the notebook, I have to guess that you get it from this course Supervised Learning: Regression provided IBM.
In the zip folder in week 1, it provides helper.py.

What you need to do it is to change the directory to where this file is. Change IPython/Jupyter notebook working directory
Alternatively, you can load boston data from sklearn then load it to Pandas Dataframe
Advices for you:

Learn how to use Jupyter notebook
Learn how Python import work
Learn how to provide information in a question so that no one need to guess


$\mathbb{Z}/n\mathbb{Z}$ is not flat

Question: On the flat module Wikipedia page, it's stated that $\mathbb{Z}/n\mathbb{Z}$ is not flat over $\mathbb{Z}$.  But I don't understand their explanation of why.  It is said that

$n:\mathbb{Z}\rightarrow \mathbb{Z}$ is injective, but tensored with $\mathbb{Z}/n\mathbb{Z}$ it is not.

Why does this imply that $\mathbb{Z}/n\mathbb{Z}$ is not flat?  What exact sequence is not preserved by $\oplus_\mathbb{Z}\mathbb{Z}/n\mathbb{Z}$, and why? I apologize if this is an elementary question, but I am new to flatness.  I may need to have it spelled out for me.
Answer: Every monomorphism $f:A \to B$ induces an exact sequence $0 \to A \to B \to \text{coker}(f) \to 0$. As tensoring is right-exact, a module $M$ is flat iff tensoring with $M$ preserves monomorphisms.
Now use that $\Bbb Z \otimes_{\Bbb  Z}\Bbb Z /n \Bbb Z = \Bbb Z/n \Bbb Z$ to see why the map  $x \to nx$ is not injective on the tensors.
Answer: Guessing that $n:\mathbb{Z}\to\mathbb{Z}$ is multiplication by $n$? If so, this is certainly injective, so starts an exact sequence
$$ 0 \to \mathbb{Z} \stackrel{n}{\to} \mathbb{Z} $$
and the kernel of the next map will have to be the image, $n\mathbb{Z}$, so we take the canonical map from $p:\mathbb{Z}\to \mathbb{Z}/n\mathbb{Z}$ (which is surjective) to get
$$ 0\to \mathbb{Z}\stackrel{n}{\to} \mathbb{Z} \stackrel{p}{\to} \mathbb{Z}/n\mathbb{Z}\to 0. $$
If $\mathbb{Z}/n\mathbb{Z}$ were flat, we could tensor and
$$ 0 \to \mathbb{Z}\otimes \mathbb{Z}/n\mathbb{Z} \to \mathbb{Z}\otimes\mathbb{Z}/n\mathbb{Z} \to \mathbb{Z}/n\mathbb{Z}\otimes\mathbb{Z}/n\mathbb{Z}\to 0 $$
would have to be exact as well. But is it?

$\mathbb{Z}/n\mathbb{Z}$ is not flat


Composition of homotopies of morphisms of complexes of abelian groups

Question: Show that if $f_1, f_2$ are homotopy morphisms of complexes of abelian groups $C_n, D_n$, and $g_1, g_2$ are homotopy morphisms of complexes of abelian groups $D_n, E_n$, then $g_1 \circ f_1$ and $g_2 \circ f_2$ are homotopic.
We have that $f_1 - f_2 = \delta^D h_n + h_{n-1} \delta^C$ and $g_1 - g_2 = \delta^E h'_n + h'_{n-1} \delta^D$, and I tried to combine these two expressions in order to find something of the form $g_1f_1 - g_2f_2 = \delta^E h''_n + h''_{n-1} \delta^C$. However, I could never arrive at a precise formula written in this way (additional terms appeared that I didn't know how to eliminate). Can anyone help me with this? Thank you
Comment: Do you mean "if $f_1, f_2$ are *homotopic* morphisms..."?
Comment: yes, sorry i mean that
Answer: For inspiration, consider the analogous situation in topology:
Let $f_1, f_2 : X \to Y$ and $g_1, g_2 : Y \to Z$ be continuous maps between topological spaces such that $f_1 \sim f_2$ and $g_1 \sim g_2$. We want to show that $g_1 \circ f_1 \sim g_2 \circ f_2$.
We start by picking homotopies $H : f_1 \to f_2$ and $H' : g_1 \to g_2$. We want to construct a homotopy $g_1 \circ f_1 \to g_2 \circ f_2$, so in particular we want to construct paths $g_1(f_1(x)) \rightsquigarrow g_2(f_2(x))$ for all $x \in X$. We already have a path $H(x,{-}) : f_1(x) \rightsquigarrow f_2(x)$, and we can apply $g_2$ to this to get a path $g_2(H(x,{-})) : g_2(f_1(x)) \rightsquigarrow g_2(f_2(x))$. We also have a path $H'(f_1(x),{-}) : g_1(f_1(x)) \rightsquigarrow g_2(f_1(x))$, and so concatenating these yields a path
$$H'(f_1(x),{-}) \diamond g_2(H(x,{-})) : g_1(f_1(x)) \rightsquigarrow g_2(f_2(x))!$$
These do indeed produce a homotopy $g_1 \circ f_1 \to g_2 \circ f_2$.

More abstractly: $g_2 \circ H$ is a homotopy $g_2 \circ f_1 \to g_2 \circ f_2$, and $H' \circ (f_1 \times \operatorname{id})$ is a homotopy $g_1 \circ f_1 \to g_2 \circ f_1$, so concatenation yields a homotopy $g_1 \circ f_1 \to g_2 \circ f_2$. To make this argument work, we only needed the following facts:

For any homotopy $H : f_1 \to f_2$ between morphisms $f_1, f_2 : X \to Y$ and any morphism $g : Y \to Z$, there is a homotopy denoted $gH$ from $g \circ f_1$ to $g \circ f_2$.
For any homotopy $H : g_1 \to g_2$ between morphisms $g_1, g_2 : Y \to Z$ and any morphism $f : X \to Y$, there is a homotopy denoted $Hf$ from $g_1 \circ f \to g_2 \circ f$.
For any homotopies $H : f \to g$ and $H' : g \to h$ between morphisms $f,g,h : X \to Y$, there is a homotopy denoted $H \diamond H'$ from $f$ to $h$.

So, try to prove these three things individually for morphisms between chain complexes and chain homotopies, then replicate the same argument! If you trace everything through you will end up with the explicit formula you want.
Comment: Thanks very much, we have that $g_{2n}f_{1n}-g_{2n}f_{2n}=g_{2n} \delta^D h_n+g_{2n}h_{n-1} \delta^C= \delta^Eg_{2(n+1)}h_n+g_{2n}h_{n-1} \delta^C$ and $ g_{1n}f_{1n}-g_{2n}f_{1n}= \delta^Eh'_nf_{1n}+h'_{n-1} \delta^D f_{n1}= \delta^Eh'_nf_{1n}+h'_{n-1}f_{1(n-1)} \delta^C$ so $g_{1n}f_{1n}-g_{2n}f_{2n}= \delta^E(g_{2(n+1)}h_n+h'_nf_{1n})+(g_{2n}h_{n-1}+h'_{n-1}f_{1(n-1)}) \delta^C$


Como enviar formulário sem dar refresh na página?

Question: Eu fiz um código que depois de selecionar o radio button ele envia para uma página mas ele esta dando refresh e não quero isso quero q ele não de refresh na página mas continue enviando e quero também que quando enviar ele apareça um alert estou tentando implementar isto do alert e do refresh e até agora nada. Segue meu codigo abaixo:
jQuery:
$(".radioo").click(function(){
        $("#rating").submit();

           $.alert({
            title: 'Atenção',
            content: 'Todos os campos sao obrigatorios!',
            });
            return;
        });

a parte do formulário esta assim:
<form method="post" action="rating.php" id="rating">

  <input type="radio" id="cm_star-empty" class="radioo" name="fb" value="" checked/>

  <input type="radio" class="radioo" id="cm_star-1" name="fb" value="1"/>

  <input type="radio" class="radioo" id="cm_star-2" name="fb" value="2"/>

  <input type="radio" class="radioo" id="cm_star-3" name="fb" value="3"/>

  <input type="radio" class="radioo" id="cm_star-4" name="fb" value="4"/>

  <input type="radio" class="radioo" id="cm_star-5" name="fb" value="5"/>

</form>

Como fazer as implementações nesse código de ele enviar o form para a página rating sem dar refresh e assim que enviar aparecer uma mensagem do tipo
suas implementações foram salvas com sucesso?
Answer: Usando AJAX:
$(".radioo").click(function() {
  var option = $('input[type="radio"]:checked').val();
  $.ajax({
    type: "POST",
    url: "rating.php",
    data: { poll_option : option },
    success: function(response) {
      alert('Dados enviados.');
    }
  });
});

Adaptado de uma pergunta semelhante no SOEn
Comment: obrigado cara funciono perfeito


Openvino: Problem when trying to load CPU plugin in Qt

Question: After installing and successfully run the OpenVino demos in my PC I start implementing a basic application in Qt with this library. I made the linking as Intel's documentation describes and the application successfully compiled.
<code>auto plugin = PluginDispatcher({L""}).getPluginByDevice("CPU");

auto netBuilder = new CNNNetReader();
netBuilder->ReadNetwork("../TestModel/squeezenet1.1.xml");
netBuilder->ReadWeights("../TestModel/squeezenet1.1.bin");

auto network = netBuilder->getNetwork();
netBuilder->getNetwork().setBatchSize(1);
</code>
The application pops an exception when debugger reach getPluginByDevice call (getSuitablePlugin method from ie_plugin_dispacher.hpp (line 73)).

I am using MSVC2017 64bit with Qt 5.11.1 in a Windows 10 machine. The .pro file library call is:
<code>#OpenVino
INCLUDEPATH += $$PWD/inference_engine/include
LIBS += -L$$PWD/inference_engine/lib/intel64/Release
LIBS += -linference_engine -llibiomp5md
</code>
Is anyone experienced the same or has an idea what's going on?
Thanks in advance,
Thanasis
Comment: In Release mode the Application runs normally though...
Answer: The release libraries were causing the problem. When I switched to the debug ones (inference_engined.lib insted of inference_engine.lib) the application run successfully.
EDIT
I paste the code from .pro file in case someone face the same problem.
<code>#OpenVino
INCLUDEPATH += $$PWD/inference_engine/include

CONFIG(release, debug|release):BuildVar=release
CONFIG(debug, debug|release):BuildVar=debug

equals(BuildVar,debug) {
    message(Debug Mode)
    LIBS += -L$$PWD/inference_engine/lib/intel64/Debug
    LIBS += -linference_engined
}

equals(BuildVar,release) {
    message(Release Mode)
    LIBS += -L$$PWD/inference_engine/lib/intel64/Release
    LIBS += -linference_engine
}
</code>


Building a more realistic random word generator?

Question: I'm seen many examples of using Markov chains for generating random words based on source data, but they often seem a bit overly mechanical and abstract to me. I'm trying to develop a better one.
I believe part of the problem is that they rely entirely on the overall statistical occurrence of pairs, and ignore the tendency of words to start and end in certain ways.  For example, if you use the top 1000 baby names as source data, the letter J is relatively rare overall, yet it's the second most common letter for names to start with.  Or, if you're using Latin source data, word endings like -um and -us would be common endings, but not as common if you consider all pairs the same.
So, I'm basically trying to put together a Markov chain based word generator that takes into account the way words start and end in the source data.
Conceptually, that makes sense to me, yet I can't figure out how to implement this from a software perspective. I'm trying to put together a little PHP tool that allows you to drop in source data (e.g., a list of 1000 words) from which it will then generate a variety of random words with realistic starts, middles, and endings. (As opposed to most Markov-based word generators, which are just based on the statistical occurrence of pairs overall.)
I'd also like to do this with word length determined by the source data, if possible; i.e., the length breakdown of the randomly generated words should be approximately the same as the length breakdown of the source data.
Any ideas would be massively appreciated! Thanks.
Answer: The part about not respecting common beginnings and endings isn't actually true if you consider "space between words" to be a symbol -- common beginnings will have high frequencies following "space between words" and common endings will have high frequencies preceding "space between words". Correct word length also settles out of that more-or-less naturally -- the mean number of letters you output before transitioning to a "space between words" symbol should equal the mean number of letters per word in the training data, although something in the back of my mind is telling me that the distribution might be off.
Comment: Thanks, Hobbs! That's actually the solution I finally came around to. I realized that the beginning and ending of a word could be things in themselves, so I assigned a character to represent them. Things fell nicely into place after that. :-)


Swift: regex function return me empty array

Question: hello guys i have problem with working regex in swift
i'm using this regex pattern https://regexr.com/3u4on and this works fine in this website
but in swift code it won't work?
can you help with this problem
I'm using this code in swift:
func matches(for regex: String, in text: String) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex)

        let results = regex.matches(in: text,
                                    range: NSRange(text.startIndex..., in: text))
        return results.map {
            String(text[Range($0.range, in: text)!])
        }
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

var videoButtonWithAtag = self.matches(for: "]*\\bhref\\s*=\\s*\"[^\"]*mp4.*?", in: html)
print(videoButtonWithAtag) // it's empty

Comment: try `"]*\\bhref\\s*=\\s*\"[^\"]*mp4[\\S\\s]*?"`
Answer: By using .* you are missing matches with line break. You should include them as well. So use [\S\s]* instead.
This should work:
let pattern = "]*\\bhref\\s*=\\s*\"[^\"]*mp4[\\S\\s]*?"


Integer to String conversion methods

Question: What are the alternative methods for converting and integer to a string?
Comment: possible duplicate of [How to convert from int to String?](http://stackoverflow.com/questions/4105331/how-to-convert-from-int-to-string)
Answer: Integer.toString(your_int_value);

or
your_int_value+"";

and, of course, Java Docs should be best friend in this case.
Comment: `your_edit_value + "";` causes the allocation of an extra empty string object, call `Integer.toString(your_int_value)` and concatenates both of them. 3 strings allocations where the first statement requires only one. The first one is faster.
Comment: Implicit conversion to `String` has a big downside. `val1 + val2 + ""` is **very** different from `"" + val1 + val2`
Comment: the seoncd version is awful. Java is not PHP or JavaScript.
Comment: yes, totally agree value+""; is not a good approach. i was just trying to mention different ways of doing that.
Answer: String one = Integer.toString(1);

Answer: String myString = Integer.toString(myInt);

Answer: Here are all the different versions:
a) Convert an Integer to a String
Integer one = Integer.valueOf(1);
String oneAsString = one.toString();

b) Convert an int to a String
int one = 1;
String oneAsString = String.valueOf(one);

c) Convert a String to an Integer
String oneAsString = "1";
Integer one = Integer.valueOf(oneAsString);

d) Convert a String to an int
String oneAsString = "1";
int one = Integer.parseInt(oneAsString);

There is also a page in the Sun Java tutorial called Converting between Numbers and Strings.
Answer: String.valueOf(anyInt);

Answer: There is Integer.toString() or you can use string concatenation where 1st operand is string (even empty): String snr = "" + nr;. This can be useful if you want to add more items to String variable.
Comment: I think both are useful. Example: if you want to convert some number to string in loop then you can use `new_name = old_name + i + ".txt"` or `new_name = old_name + Integer.toString(i) + ".txt"`. In this case I prefer shorter method.
Answer: You can use String.valueOf(thenumber) for conversion. But if you plan to add another word converting is not nessesary. You can have something like this:
String string = "Number: " + 1
This will make the string equal Number: 1.

Integer to String conversion methods


Check if density plots are significantly different (with R)

Question: I have daily data on cars per minute passing certain points. The data covers weekdays of 4 months, July and August, for 2013 and 2014. In August 2014 a toll (treatment) was introduced. I would like to test if there is a statistically significant variation in the volume of cars during this month.
I am unsure on how could I give some statistical ground to my analysis going beyond pure visual comparison of trends.
Here they ask on how to statistically compare groups of multiple density plots. I think my question goes on those lines, but I have many plots within a month, and I need to compare months among themselves to see if there is an effect of the treatment (August 2014). Besides this, there is no R implementation of it.
Any idea on how to assess the effect of the treatment using R?

Edit based on @Hunaphu answer:

Only August '14 is treated, so actually I took into account the July months to control for the year effect. Given the loess trends, 2014 shows lower volumes and that wouldn't be a treatment effect. Likewise, July months seem to have higher volumes so, should I define $X_t$ as:

$X_t = f(t) + f(t)*Treatment + f(t)*July + \sigma G_t$
where the binary variables $Treatment = 0$ for both July'13 and August'13, and $July = 1$ for July'13. Likewise,
$Z_t = f(t+1) + f(t+1)*Treatment + f(t+1)*July + \sigma G_t$
Is this correct? My research question would it be if $Treatment$ is significant, right?

As important as the means is the shape of the curve, so a change in the shape of August'14 with respect to the others will also be an "treatment effect". How to assess for significant changes in shape to complement my visual assessment?
Comment: Plots are just a visual representation of data - to check if the *plots* differ you can just judge it by looking at them. *What* do you want to compare?
Comment: The comparison is: Are the vehicle volumes shown in August 2014 significantly different from those of other months?
I would like to know if there is any statistical analysis that could be done beyond the visual comparison of plots.
Comment: Welcome to this site! In response to your flag, rather than deleting this question and posting a new one, I would suggest to clarify it as much as possible.
Answer: You could form the difference process and study that.
Let $X_t$ be the data from '13 and $Y_t$ the data from '14. Define $Z_t = X_t - Y_t$.
Assume that $X_t = f(t) + \sigma G_t$, where $G_t \sim\mathcal{N}(0, 1)$. Then if $Y_t$ follows the same distribution, you should have $Z_t = 2\sigma H_t$ in distribution, where $H$ also is standard normal.
The assumption that $X$ is defined as a deterministic function plus noise is strong but, in my view, reasonable.
Based on the plot I think that you will find that $Z_t$ does not have mean zero.
Short form:
Define $Z_t$. Estimate the mean of the process. If it is not zero then reject the hypothesis that $f(t)$ is the model for both $X$ and $Y$.
Comment: thanks for your answer, it really gives a mathematical setting to the research question. I have edited the question at the end based on your answer.


Difference between t-test and ANOVA in linear regression

Question: I wonder what differences are between t-test and ANOVA in linear regression?

Is a t-test to test whether any one of the slopes and intercept has
mean zero, while ANOVA to test whether all slopes have mean zero? Is this the only difference between them?
In simple linear regression i.e. where there is only one predictor
variable, there is only one slope to estimate. So are t-test and
ANOVA equivalent, and if yes, how, given that they are using different statistics (t-test is using t-statistic and ANOVA is using F-statistic)?
Comment: Ad 1) In linear regression, I normally understand ANOVA as a measure of goodness of fit of the model, i.e. to decide whether the model (regression line) explains substantial part of total variability. The question, whether it is equivalent to all slopes being zero, is really very interesting. Ad 2) it looks I'm getting almost the same p-values for t-test and regression ANOVA in this case. Really interesting theorem!
Answer: The general linear model lets us write an ANOVA model as a regression model. Let's assume we have two groups with two observations each, i.e., four observations in a vector $y$. Then the original, overparametrized model is $E(y) = X^{\star} \beta^{\star}$, where $X^{\star}$ is the matrix of predictors, i.e., dummy-coded indicator variables:
$$
\left(\begin{array}{c}\mu_{1} \\ \mu_{1} \\ \mu_{2} \\ \mu_{2}\end{array}\right) = \left(\begin{array}{ccc}1 & 1 & 0 \\ 1 & 1 & 0 \\ 1 & 0 & 1 \\ 1 & 0 & 1\end{array}\right) \left(\begin{array}{c}\beta_{0}^{\star} \\ \beta_{1}^{\star} \\ \beta_{2}^{\star}\end{array}\right)
$$
The parameters are not identifiable as $((X^{\star})' X^{\star})^{-1} (X^{\star})' E(y)$ because $X^{\star}$ has rank 2 ($(X^{\star})'X^{\star}$ is not invertible). To change that, we introduce the constraint $\beta_{1}^{\star} = 0$ (treatment contrasts), which gives us the new model $E(y) = X \beta$:
$$
\left(\begin{array}{c}\mu_{1} \\ \mu_{1} \\ \mu_{2} \\ \mu_{2}\end{array}\right) = \left(\begin{array}{cc}1 & 0 \\ 1 & 0 \\ 1 & 1 \\ 1 & 1\end{array}\right) \left(\begin{array}{c}\beta_{0} \\ \beta_{2}\end{array}\right)
$$
So $\mu_{1} = \beta_{0}$, i.e., $\beta_{0}$ takes on the meaning of the expected value from our reference category (group 1). $\mu_{2} = \beta_{0} + \beta_{2}$, i.e., $\beta_{2}$ takes on the meaning of the difference $\mu_{2} - \mu_{1}$ to the reference category. Since with two groups, there is just one parameter associated with the group effect, the ANOVA null hypothesis (all group effect parameters are 0) is the same as the regression weight null hypothesis (the slope parameter is 0).
A $t$-test in the general linear model tests a linear combination $\psi = \sum c_{j} \beta_{j}$ of the parameters against a hypothesized value $\psi_{0}$ under the null hypothesis. Choosing $c = (0, 1)'$, we can thus test the hypothesis that $\beta_{2} = 0$ (the usual test for the slope parameter), i.e. here, $\mu_{2} - \mu_{1} = 0$. The estimator is $\hat{\psi} = \sum c_{j} \hat{\beta}_{j}$, where $\hat{\beta} = (X'X)^{-1} X' y$ are the OLS estimates for the parameters. The general test statistic for such $\psi$ is:
$$
t = \frac{\hat{\psi} - \psi_{0}}{\hat{\sigma} \sqrt{c' (X'X)^{-1} c}}
$$
$\hat{\sigma}^{2} = \|e\|^{2} / (n-\mathrm{Rank}(X))$ is an unbiased estimator for the error variance, where $\|e\|^{2}$ is the sum of the squared residuals. In the case of two groups $\mathrm{Rank}(X) = 2$, $(X'X)^{-1} X' = \left(\begin{smallmatrix}.5 & .5 & 0 & 0 \\-.5 & -.5 & .5 & .5\end{smallmatrix}\right)$, and the estimators thus are $\hat{\beta}_{0} = 0.5 y_{1} + 0.5 y_{2} = M_{1}$ and $\hat{\beta}_{2} = -0.5 y_{1} - 0.5 y_{2} + 0.5 y_{3} + 0.5 y_{4} = M_{2} - M_{1}$. With $c' (X'X)^{-1} c$ being 1 in our case, the test statistic becomes:
$$
t = \frac{M_{2} - M_{1} - 0}{\hat{\sigma}} = \frac{M_{2} - M_{1}}{\sqrt{\|e\|^{2} / (n-2)}}
$$
$t$ is $t$-distributed with $n - \mathrm{Rank}(X)$ df (here $n-2$). When you square $t$, you get $\frac{(M_{2} - M_{1})^{2} / 1}{\|e\|^{2} / (n-2)} = \frac{SS_{b} / df_{b}}{SS_{w} / df_{w}} = F$, the test statistic from the ANOVA $F$-test for two groups ($b$ for between, $w$ for within groups) which follows an $F$-distribution with 1 and $n - \mathrm{Rank}(X)$ df.
With more than two groups, the ANOVA hypothesis (all $\beta_{j}$ are simultaneously 0, with $1 \leq j$) refers to more than one parameter and cannot be expressed as a linear combination $\psi$, so then the tests are not equivalent.
Answer: In 1, ANOVA will usually test factor variables and whether or not between group variance is significant. You'll clearly see the difference if your software allows indicator variables in a regression: for each dummy you'll get a p value saying whether this group scores significantly different from 0, and as a consequence significantly different than the reference group or reference value applicable. Usually, you won't see to what degree the indicator itself is important until you do an ANOVA test.
A F-test is a squared t-test. Therefore, in 2, it's the same.
Comment: Thanks! (1) What do indicator variables mean here? (2) Generally, a t-test is equivalent to ANOVA only when there are only two groups. But in simple linear regression there may be more than two groups, where the number of groups is the number of values the predictor variable takes in the data set.
Comment: (1) Indicator or categorical or factor variable ... all the same. (2) Indeed, but you may want to know how well a set of dummies/categories scores from ANOVA.
Comment: Thanks! (2) So in simple linear regression, how is t-test equivalent to ANOVA, given that there are more than two groups? What does "how well a set of dummies/categories scores from ANOVA" mean, and why do I want to know it?
Comment: In OLS regression, R² (explained variance) will be equal to eta² or MSS / TSS from ANOVA no matter how many groups you define. Next, you might want to know the contribution of a set of dummies (i.e. an indicator variable) to say whether the set itself is relevant and to what extent, which is different from the significance of the difference between one single category with the reference category.


skimr: How to get variables printed in the original order?

Question: By default, the print method for object created with function skim() (in R package skimr) sorts variables alphabetically. How can I get this method to print the variables in the order they appeared in the summarized dataset?
# Default (desired) order of variable names
names(iris)
#> [1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"
#> [5] "Species"

# `skim()` sorts variables alphabetically
skimr::skim_with(numeric = list(hist = NULL))
skimr::skim(iris)
#> / ... the output was truncated manually ... /
#>
#> -- Variable type:numeric ---------------------------------------------
#>      variable missing complete   n mean   sd  p0 p25  p50 p75 p100
#>  Petal.Length       0      150 150 3.76 1.77 1   1.6 4.35 5.1  6.9
#>   Petal.Width       0      150 150 1.2  0.76 0.1 0.3 1.3  1.8  2.5
#>  Sepal.Length       0      150 150 5.84 0.83 4.3 5.1 5.8  6.4  7.9
#>   Sepal.Width       0      150 150 3.06 0.44 2   2.8 3    3.3  4.4

Answer: This happens for reasons that are pretty deep in how the package works, meaning that the short answer to your question is no. However, if you are willing to work with the skim_df object or do skim_to_wide() you can actually accomplish this
so_l <- skimr::skim_to_list(mtcars)$numeric

You can get the list in a nice string
   orig_order<- names(mtcars)
   so_l$ordered_var_name <- factor(so_l$variable, levels = orig_order,
        ordered = TRUE)

ANd then the data will be in the order you want, but the print may or may not work for you.
You may also want to try installing the v2 branch from github.  It really rethinks a lot about how the printing works.


Animate background color to different colors

Question: How can I animate the back ground color of a div from the lightest orange color to the darkest red color, and back (which should make it look like a glow effect)?
I created a jsFiddle but it only changes colors from light grey (static set) to red. This is as far as I got.
I did found a few questions regarding animating colors, but nothing about multiple colors.
Any help is really appreciated.
Answer: Add this CSS to your div.
http://jsfiddle.net/Nillervision/a4ELz/
.test {
    overflow: hidden;
    text-align: center;
    font-family: sans-serif;
    font-size: 40px;
    line-height: 3;
    -webkit-animation: glow linear 1s infinite;
    animation: glow linear 1s infinite;
}
@-webkit-keyframes glow {
    0% { background-color:red; }
    50% { background-color:orange; }
    100% { background-color:red; }

}
@keyframes glow {
    0% { background-color:red; }
    50% { background-color:orange; }
    100% { background-color:red; }
}

If you only want the animation to run once on pageload remove the "infinite" value.
If you want the effect to happen on hover you could use css transitions instead.
Comment: Hi, looks great, but I want it from orange to red. Can i Just change the order of these colors? And if i want some more shades, do i have to add a few more lines like `50% { background-color:orange; }` with different percentage?
Comment: Yes to both questions. You can add as many keyframes as you want and you can animate any color (or any other CSS property for that matter)


ValidationProvider rule for url checks

Question: In  @vue/cli 4.0.5 app I need to add additive URL checks to ValidationProvider rules. My code:
<ValidationProvider
    name="website"
    rules="{ required : true, url: {require_protocol: true} }"
    v-slot="{ errors }"
>

But got this console error:

No such validator '{ required ' exists.

With rules:
    rules="required : true, url: {require_protocol: true}"

Error is:

No such validator 'required ' exists.

Which format is valid?
    "vee-validate": "^3.1.0",
    "vue": "^2.6.10",

MODIFIED BLOCK :
With rules :
:rules="{ required : true, url: {require_protocol: true} }"

I got next error :
vee-validate.esm.js?7bb1:708 Uncaught (in promise) Error: No such validator 'url' exists.

I expected all methods must be accessible, as I have in import part:
...
import {ValidationObserver, ValidationProvider, extend} from 'vee-validate'
import * as rules from 'vee-validate/dist/rules';

Object.keys(rules).forEach(rule => {
    extend(rule, rules[rule]);
});
import {localize} from 'vee-validate';

What is wrong ?
MODIFIED BLOCK #2 :
In vue file
   <ValidationProvider
        name="website"
        :rules="{ required : true }"
        v-slot="{ errors }"
    >

...

import { ValidationObserver, ValidationProvider } from 'vee-validate'
import { required, email } from 'vee-validate/dist/rules' // MY PHP STORM shows this line in gray color as nonused elements

I still got error :
vee-validate.esm.js?7bb1:708 Uncaught (in promise) Error: No such validator 'required' exists.

I found file /node_modules/vee-validate/dist/rules.js with lines :
var required = {
    validate: validate$o,
    params: params$h,
    computesRequired: computesRequired
};

var testEmpty = function (value) {
    return isEmptyArray(value) || includes([false, null, undefined], value) || !String(value).trim().length;
};
var validate$p = function (value, _a) {
    var target = _a.target, values = _a.values;
    var required;
    if (values && values.length) {
        if (!Array.isArray(values) && typeof values === 'string') {
            values = [values];
        }
        // eslint-disable-next-line
        required = values.some(function (val) { return val == String(target).trim(); });
    }
    else {
        required = !testEmpty(target);
    }
    if (!required) {
        return {
            valid: true,
            required: required
        };
    }
    return {
        valid: !testEmpty(value),
        required: required
    };
};
...

I do not see error syntax comparing with samples/provided link
I declared ValidationObserver, ValidationProvider before required declaration.
Where is the error ?
Thanks!
Comment: Have you tried adding `Vue.component('ValidationProvider', ValidationProvider)` and
`Vue.component('ValidationObserver', ValidationObserver)` where you import the rules, and then remove the import of those in the actual file?
Answer: In this example they use a pipe character (|) to separate the string rules:
<ValidationProvider rules="required|confirmed:confirm" v-slot="{ errors }">
...

However, if you want to pass an object as you are now (which may be best because it's more complex than that example) then you need to bind the rules prop:
<ValidationProvider
  v-bind:rules="{ required : true, ... }"
  ...
>

:rules="{ required : true, ... }"

To explain the error you're currently seeing:

No such validator '{ required ' exists.

That's because, without binding the rules prop, you're passing a raw string rather than an object. So it's interpreting { required as the name of a validator, when that clearly is not a valid validator name.
ADDITION
Per this GitHub issue:

Now VeeValidate requires you to import the rules yourself. So you can either >import them rule by rule:
import { required, email } from 'vee-validate/dist/rules';
or you can import all rules once using:
import {
 ValidationProvider,
 ValidationObserver
} from 'vee-validate/dist/vee-validate.full';

Comment: It's probably not a great idea to import every rule if you're not going to use all of them. Instead, why not just `import { required, confirmed, url, ...etc } from 'vee-validate'` for the rules you need?
Comment: Sorry about that. I've updated my answer. You don't import from `vee-validate` (which I had in my last comment).
Comment: Thanks! Please look at MODIFIED BLOCK
Comment: I tried to leave 1 line :     import {ValidationObserver, ValidationProvider, required, confirmed, url} from 'vee-validate'
but got error : Error: No such validator 'required' exists.  Error in syntax ?
Comment: This does not work still! Please look at MODIFIED BLOCK #2

ValidationProvider rule for url checks


Array_Shift function - parameter not by reference

Question: I need to use two arrays - initial one, and the same array without the first element. For example:
public function foobar($a, $b, $c)
{
   $initial_array = get_defined_var();
   var_dump($initial_array); // ok
   $sliced_array = array_shift($initial_array);
   var_dump($sliced_array); // int(1) ???

   //initial array should be 'a' => $a, 'b' => $b, 'c' => $c
   // sliced array should be 'b' => $b, 'c' => $c
}

The problem is that sliced array seems to be some strange value, like int(1)...What's wrong here?
Answer: You can try with array_slice:
$sliced_array = array_slice($initial_array, 1);

Answer: array_shift modifies the original array, and return the shifted element, which is the value of $a = 1 in this case.
Comment: you should explain how to achieve what they want also, else this answer is incomplete
Comment: @SterlingArcher, I think the OP just want to know why it happened
Comment: Yes, but who goes on Main and asks why something is wrong without wanting to know how to fix it?
Answer: array_shift modifies the array it receives by removing its first element (as opposed to returning a copy of the array it receives)
If you want a copy of initial_array with the first element removed, try this
public function foobar($a, $b, $c)
{
   $initial_array = get_defined_var();
   $sliced_array = $initial_array; //copy the array
   array_shift($sliced_array); //remove 1st element
}


How to find value of intersection point of two circles?

Question: Consider the following diagram

Here, we have a small circle of radius $r$ inside a large circle of radius $R$. The center of the small circle is offset to the right of the center of the large circle by some length $d$, such that both circles touch each other at one point.
Draw a line from this intersection point to a vertical from the center of the large circle, and call its length $x$.
How do we find $x$ when

$R=11,\, r=3, \, d=6$?
In general?

I started off with coordinate bashing, with $y=-\sqrt{R^{2}-x^{2}}$ as the equation for the large circle and $y=a-\sqrt{-x^{2}++2dx+r^{2}-d^{2}}$ as the equation for the smaller circle for some value $a$.
Then, I set them equal to one another, $$-\sqrt{R^{2}-x^{2}}=a-\sqrt{-x^{2}+2dx+r^{2}-d^{2}}$$ It quickly got very messy so I plugged in some numbers and got $$-\sqrt{121-x^2}=a-\sqrt{-x^2+12x-27}$$
Squaring twice with some manipulation gives $$-4 a^2 x^2+48 a^2 x-108 a^2=21904-296 a^2+a^4+x \left(24 a^2-3552\right)+144 x^2$$
which seems solvable but got wayyy too messy so I just wolfram alpha'd it to get

Setting both solutions equal to each other gives me $$-a^6+188 a^4-4480 a^2=0 \iff a^2 (a^2-160) (a^2-28)=0$$
giving me 5 solutions $a = 0, \pm 4\sqrt{10}, \pm 2\sqrt7$. Graphically, I see that $-2\sqrt{7}$ is the solution I want, and plugging it back into the monstrous expression of $x$ gives me $33\over4$ as the $x$ value.

Clearly, this method is extremely messy, and I imagine it would be even more messier for the general case. I suspect I am missing a simple geometric solution.
Any help?
Thanks!
Max0815
Comment: Let $T$ be the point where the circles are tangent, $O$ the center of the big circle. Draw a rectangle with diagonal $OT$ and find similar triangles.
Comment: @Lozenges comment for your specific question gives $33\over4$ which is wt you got too
Answer:
From $OP = AT = x$ and $OT = R$ you get $PT=\sqrt{R^2-x^2}$.
From $OQ = d$ and $OM = R-r$ you get $QM = \sqrt{(R-r)^2-d^2}$.
Further consider the similarity of the triangles $OQM$ and $OPT$, leading to
$$\frac{PT}{QM}=\frac{x}{d}\ .$$
Putting in the above (and squaring) then results in
$$d^2 (R^2-x^2) = ((R-r)^2-d^2) x^2$$
or
$$d^2 R^2 - d^2 x^2 = (R-r)^2 x^2 - d^2 x^2$$
which clearly results in
$$x^2 = \frac{d^2 R^2}{(R-r)^2} = \left(\frac{d R}{R-r}\right)^2$$
--- rk
Comment: Using the similar triangles you can write $\frac{x}{d}=\frac{R}{R-r}$. No need for further calculations.
Answer:
Since the little circle just touches the big circle at $D$ it is perpendicular to the tangent at that point. So if you extend the line to the back then you will meet the center $O$(because the line perpendicular to the tangent is the radius).
Let $\angle ODP = \theta$. Then $\angle ODP = \angle COQ = \theta$.
If we consider the triangle $COQ$ we can write $\displaystyle \cos\theta = \frac{OQ}{OC} = \frac{d}{R-r}$. Then we consider the triangle $OPD$ to write $\displaystyle x = OD\cos\theta = \frac{Rd}{R-r}$.
Substituting $R = 11, r = 3, d = 6$ to the above equation gives $x = \frac{33}{4}$.
Comment: @Max0815 It must be ODP not OPD. Changed it now. Thanks!
Comment: Isn't angle OPD a right angle? how is it equal to COQ
Answer: $d+r\le R$, also $r\lt R$
$\displaystyle x=d+r\frac{d}{R-r}$
My reasoning? $x$ is the sum of $d$ and $r$ projected to the x-axis. The ratio of $d$ and $(R-r)$ defines the direction center of the big circle to tangent point of the two circles. The rest is Intercept theorem.
With the given values I get $\displaystyle x=\frac{33}{4}$
Answer: Let center of big circle be $O(0,0)$ and small circle be $o(d,-\sqrt{(R-r)^2-d^2})$. Then the equation of the line $\stackrel{\leftrightarrow}{Oo}$ is $$y=-\frac{\sqrt{(R-r)^2-d^2}}d x$$and it cuts the big circle $$x^2+y^2=R^2$$ at the tangency point $P$ with $x$-coordinate
$$x=\frac{dR}{R-r}.$$


Checkbox in WPF DataGrid header only?

Question: Is there a way to add a checkbox (in addition to text) to a column header in a WPF DataGrid? That is, without using DataGridCheckBoxColumn, which would add checkboxes to all grid cells in that particular column.
Thanks.
Answer: can you try this
<code><my:DataGrid Margin="72,59,6,3" Name="DataGrid1" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" >
          <my:DataGrid.Columns>
            <my:DataGridTextColumn Header="Header1">
                <my:DataGridTextColumn.HeaderTemplate>
                    <DataTemplate>
                        <CheckBox Content="{Binding}"/>
                    </DataTemplate>
                </my:DataGridTextColumn.HeaderTemplate>
            </my:DataGridTextColumn>
        </my:DataGrid.Columns>
    </my:DataGrid>
</code>
Comment: It was my pleasure to help you..happy 2018
Comment: Can you elaborate on how to get the checked state?

Checkbox in WPF DataGrid header only?


Function for increasing percentage each period while compounding

Question: I'm looking for how to do some odd compounding, where the rate also changes each period. I'd like a function of

initial balance
percentage rate that's added the first and every period
and a number of periods after which we want our new balance

The worst loan contract ever? I arrived at this problem via a spreadsheet question over on Web Apps SE talking about scores rather than money. Given that spreadsheet context, I dodged the math and just iteratively pre-calculated every period's percentages. It screamed at me that I should be able to work up a simple algebraic approach for a self-contained function.
For a non-financial example, these are the variables from that question restated for my terms:

a student's total grade this quarter as 0 to 100 points
the penalty percent according to school policy
that student's absences this quarter

But again here, that penalty is to both have a compounding effect on score, but also increase after every application. So say a student had a perfect score, but three absences, and the rule is "8% penalty per absence per absence":

$100$ points to start
$100 - ( \mathbf{0.08} \times 100 ) = 92$ left after $1$ absence
$92 - ( \mathbf{0.16} \times 92 ) = 77.28$ after $2$
$77.28 - ( \mathbf{0.24} \times 77.28 ) = 58.73$ after $3$. Brutal! Don't be absent.

So it's compounding, since the input each iteration is the remaining score after the previous absence, but adapting the everyday compounding formula
$$\text{score}_1=\text{score}_0\times(1-\text{penalty} ) ^{\text{absences}}$$
naturally doesn't account for the changing penalty rate across the above steps 2 to 4. Those increasing penalties could be expressed as $(0.08\times\text{absences})$, but that would always use the total absences, not the required piecemeal increase for each exponentiation. I suppose it can't be exponentiation—the base isn't constant.
Is there a way to achieve this without a series or recursion, just simple algebra? Since this is now "just" a curiosity, if you have an answer please at least briefly explain how it works. Also, I cannot upvote you twice but extra esteem and gratitude to you if it is translatable to a native spreadsheet function.
Answer: b(t) balance after t cycles.
p(t) percent added for the t-th cycle.
pt(t) percent for the t-th cycle.
pt(t) = p(0) + p(1) + p(2) ... + p(t-1)
b(0) = b, p(0) = p.
b(t+1) = b(t) + b(t).pt(t)
b(t) = b + b(0).pt(1) + b(1).pt(1) ... + b(t-1).pt(t-1)
Since p(t) is arbitrary, no simplifications are possible.
Comment: Oh thank goodness. I wrote them up as [somewhat different] functions too and couldn't get to the point you did—where I was convinced it couldn't be simplified. Answer acceptance pending any other answers/comments. Thanks for the clarity.


Solving for $c$ in $a(b + cd) \equiv 0 \mod e$

Question: If I have a modulo operation like this:
$$(a ( b+cd ) ) \equiv 0 \pmod{e},$$
How can I derive $c$ in term of other variables present here. I.e. What function $f$ can be used such that:
$$c = f (a,b,d,e) $$
And what is the implication of a mod operation's result being $0$ in terms of simplifying the equation.
Thank you very much for your time.
Answer: You cannot express $c$ as a function of $a,b,d,e$, notably as $e$ varies there will be values for which no $c$ exists, and others for which it is not unique. However if one restricts to the cases where $a$ and $d$ are invertible modulo $e$, meaning that there exist numbers $i_a,i_d$ with $ai_a\bmod e=1=di_d\bmod e$, then $c$ exists, is unique modulo $e$, and is given by
$$
  c\equiv d^{-1}(-b) \pmod e
$$
where $d^{-1}$ is the more usual notation for the number $i_d$ above. Neither $a$ nor the inverse $i_a$ of $a$ occur in the formula, but if $a$ has no inverse modulo $e$ then there are other values for $c$ than the above.
Answer: EDIT
My original solution to this problem was, in hindsight, radically overcomplicated. I have it below the modified post.
We have $a(b + dx) \equiv 0 \mod e$, or equivalently $ab + adx \equiv 0$, or equivalently $(ad)x \equiv -ab \mod e$. This is a very well understood subset of the problem on solving $ax \equiv b \mod m$. It turns out that there are solutions iff $(ad, e) | (-ab)$, and if there are any solutions than there are exactly $(ad,e)$ of them.
This is the Linear Congruence Theorem. In fact, my previous answer is sort of a skim of the ideas behind the proof, in a sense. And although it gives a clear record of my overcomplicating a problem, I think there is a certain amount of illustrative-ness behind it.

Original answer
So we have $a(b + cd) \equiv 0\mod e$.
If we are lucky, and in partcular that $a,b,c,d,e \neq 0$ and $(a,e) = (b,e) = (c,e) = (d,e) = 1$, i.e. that everything is coprime with $e$, then we have that $c \equiv d^{-1} (-b) \mod e$. In fact, we don't actually require $b$ or $c$ to be coprime to $e$ for this to work, as we just wanted to 'cancel' off the $a$ and be able to write down $d^{-1}$.
Otherwise, the solution may not be well-defined, or rather is a family of solutions. To vastly simplify, suppose we have something like $6(1 + c)\equiv 0 \mod 18$. Then $c \equiv 2, 5, 8, 11, 14, 17$ are all solutions.
The general idea to finding the solutions to problems like $6(1+c) \equiv 0 \mod 18$ involve noting that $(6,18) = 6$, and so by dividing out by $6$ we get $(1+c) \equiv 0 \mod 3$. This is not the same equation, but it tells us that $c \equiv 2 \mod 3$, and a quick check shows that $2,5,8,11,14,17$ are all solutions. What we really looked at were the congruences $(1+c) \equiv 0, 3, 6, 9, 12, 15 \mod 18$, as multiplying all of these by $6$ yield the original congruence. In fact, you might see that there are $6$ of them - and this is not a fluke.
So in your case, with $a(b+cd) \equiv 0 \mod e$, you might first do a 'reduction' to account for $(a,e) > 1$. Afterwards, you can effectively ignore the $a$, but remember that it incorporates $(a,e)$ distinct solutions. You are then left with $cd \equiv -b \mod e$, and this is a classic problem. I link to the Linear Congruence Theorem below for more on this.
Let's do a quick example, illustrating the method and a potential problem. $3(1 + 2c) \equiv 0 \mod 18$. We see that $(3,18) = 3$, so we look at $(1 + 2c) \equiv 0 \mod 6$ or $2c \equiv 4 \mod 6$. But what we really wanted was $1+2c \equiv 0, 1+2c \equiv 6,$ and $1+2c \equiv 12 \mod 18$. So we get that $2c \equiv 5, 11, 17 \mod 18$. We could proceed, but it's easy to see here that none of these have a solution. Working $\mod 18$, the left side is always even and the right sides are always odd.
It turns out that the congruence $ax \equiv b \mod m$ has a solution iff $(a,m)|b$. So if we define $e' := e/(a,e)$, then $a(b + xd) \equiv 0 \mod e$ will have solutions iff $(d,e') | (e'-b)$. In the (non)example abolve, we required $(2,6) = 2 | 1$, which it doesn't. But if you repeat with $3(2 + 2c) \equiv 0 \mod 18$, there will be solutions. (Answer: They are $2, 5, 8, 11, 14, 17$, with a total of $6$ coming from the $3$ from $(3,18) = 3$, each having $2 = (2, 6)$ solutions of their own. Food for thought: is it possible that there are fewer than $(a,e)(d,e') due to some overlap?)
To save this answer from becoming too long, I will recommend sources of study. For further reading, I recommend looking into what wikipedia calls the Linear Congruence Theorem, which talks of the general solvability of equations like $ax \equiv b \mod m$, and the Chinese Remainder Theorem. In addition, almost any introductory book on number theory will cover this sort of reasoning. I am particularly fond of recommending Rosen's Elementary Number Theory and Ireland and Rosen's Classical Introduction to Modern Number Theory, which is harder, and by a different Rosen.


haproxy on pfsense fw to guac

Question: I am having some issues with setting up a publicly accessible guacamole server thru my pfsense, which is running haproxy.
<code>Internet > pfsense
          \ haproxy > guac
</code>

I have my domain DNS thru cloudflare. It is currently proxied - should this matter at all?
I have NAT set up to direct 80 and 443 thru to my haproxy VIP
I have the haproxy frontend for port 80 redirecting to port 443
I have the haproxy frontend for port 443 using subdomain acl's to split traffic (eventually, I am looking to have a normal 'www' site as well)

Networking:

I can access guac locally via IP.
I CAN NOT access guac locally via name - getting 503.
I have "split DNS" set up (i think?) right now - I have one entry for guac pointing to its real IP, then another part of a split dns record that points both www and guac to the haproxy VIP.

The general idea is to have haproxy terminate https to the outside; then speak to guac internally via http (i.e. "ssl offloading(?))

I have two backends set up, one for www and the other for guac.

I am unsure exactly.. where to go to troubleshoot. I was following this guide : https://geekistheway.com/2022/10/17/how-to-host-multiple-domains-using-haproxy-as-reverse-proxy-on-pfsense/
and it seems like either perhaps I am just not exactly.. knowing what to do or something.
Any help with like helping me to clarify the situation or finding logs or .. some other troubleshooting I can do would be very much appreciated.
Comment: Ah I forgot to mention - I'm using letsencrypt via pfsense acme module to get the certificates issued.
Answer: re-edit: I had to change my settings in cloudflare to use strict ssl. everything is working now.
edit: well spoke too soon - it works, internally. still inaccessible from external. Getting a 523 from cloudflare.
It turns out - I had haproxy HTTP checks for the backend that were failing, so haproxy itself was saying it wasn't working.
I changed the url it was using to check and it works now.
for guac specifically, I had to add in /guacamole/ to the checked url.

haproxy on pfsense fw to guac


Twitter bootstrap and max-width for mobile devices?

Question: I would like to set the fixed with for mobile devices on 320px - I would like to want to look my website always the same as on the screen for 320px.
I have tried to set up the fixed width on 320px, like this:
<code>@media (max-width: 320px) {
    body {
        width: 320px;
    }
}
</code>
But this code doesn't work me. Is there any way to do it?
Answer: You could use the meta tag in your html.
<code><meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=320, height=device-height, target-densitydpi=medium-dpi" />
</code>
Comment: some of that isnt necessary, but the first couple of arguments are (user-scalable, initial-scale, maximum-scale, minimum-scale)
Comment: @sevenseacat Once target-densitydpi helped me on android
Comment: Could it be the solution to this issue, if yes how? http://stackoverflow.com/questions/24851785/can-i-explicit-define-minimum-pixel-width-on-which-bootstrap-should-switch-to-re


What is current advice on forwarding email - particularly to gmail

Question: I want to move from my current hosting site to a VPS. I am very comfortable with the website hosting side of things but at the moment my stumbling block is email, something which I have never had to deal with before. Outbound is fine, I have set up postfix with TLS and have SPF, DKIM and DMARC configured and all seems to work fine. However, on my existing site I have 5 email addresses for different domain names that I currently forward, 4 of them to gmail accounts. Volumes are trivial, an average of less than one a day - between all 5!
I have seen advice that says don't forward email because of potential problems with spam and being blacklisted because my server would appear to be the origin of the spam.
To avoid this problem (here) Google says "do not change the envelope sender when forwarding email to Gmail". If I use virtual alias maps in Postfix I am assuming that this would change the envelope sender to be my server? Is there a way of not changing the envelope sender? And if I could do it, wouldn't it then fail SPF checks?
Should I be using postsrsd? Does this change the headers in such a way that it satisfies Gmail whilst not breaking SPF.
I have seen a variety of advice out there but much of it seems dated and often assumes a level of knowledge I don't yet have. I would appreciate any advice, preferably not "don't do it"! Thanks.
Answer: In my personal experience using 3rd parties to forward email, I did find that Gmail marked many emails as spam. It's better to avoid that risk altogether. I've had much better deliverability since I set up a pop3 server for Gmail to fetch mail from. There is a delay since it polls, so for some emails like password resets it's important to be able to access that mailbox directly.
Comment: I have seen this approach recommended elsewhere but I couldn't find out how it worked in practice. I thought that it might only pull the emails in if you accessed gmail directly through the browser and not if you were using a client and imap. However you say that it polls so that makes it a viable option. Thanks.


A problem related to binomial theorem for any index

Question: If $|x|<1$, then in the expansion of $(1+2x+3x^2+4x^3+\cdots)^{1/2}$, the coefficient of $x^n$ is
I tried to do it with the AGP approach but wasn't able to solve it completely because of the exponential power
Comment: And the "AGP approach" is...?
Answer: Note that $1+x+x^2+x^3+...=\frac{1}{1-x}$. Then $1+2x+3x^2+...=\left(\frac{1}{1-x}\right)'=\frac{1}{(1-x)^2}$. Then $(1+2x+3x^2+...)^{1/2}=\frac{1}{1-x}=1+x+x^2+x^3+...$
Answer: Like Calculating $1+\frac13+\frac{1\cdot3}{3\cdot6}+\frac{1\cdot3\cdot5}{3\cdot6\cdot9}+\frac{1\cdot3\cdot5\cdot7}{3\cdot6\cdot9\cdot12}+\dots? $
we can prove for $|x|<1,$ $$S=\sum_{r=0}^\infty rx^{r-1}=(1-x)^{-2}$$
Alternatively $$S=\sum_{r=0}\dfrac{d(x^r)}{dx}=\dfrac{d\left(\sum_{r=0}^\infty x^r\right)}{dx}$$ which is for $|x|<1,$ $$=\dfrac{d(1-x)^{-1}}{dx}=?$$


Which statistical software can do Weibull analysis and draw these particular figures?

Question: Some R packages, Weibull++, and a couple of other programs can perform Weibull analysis (survival analysis by fitting a Weibull distribution). But I need the one that can both do Weibull regression and draw the attached figures (not similar figures, but exactly these figures). I am interested in the particular program that can draw these images, not for example the MASS package of R which can give similar Weibull cdfs.

Simple box plots. This is only added in order to facilitate the identification of the used stats program. Not many stats programs use such layouts for plots. So this might help finding the program used to create the below image.

Weibull cumulative distributions.
Comment: The term 'Weibull analysis' is a little ambiguous. Do you want to estimate lifetime distributions in the presence of censoring by fitting Weibull-type regression models?
Comment: Are you basically asking for software that can draw overlaid line plots on common axes?  (That is what it seems like.)
Comment: Glen, yes I want to do survival analysis using Weibull regression as an alternative to the Cox regression.
Comment: Whuber, no I am curious to know the particular software that has created these very images. There are numerous programs that can draw similar plots. However, I am interested in the visuals of these images, and am seeking the program that has created *these* plots, not programs that can create similar plots in other formats (eg, using other fonts, axis styles, plot properties, etc).
Answer: I presume the first plot is simply a plot of observed lifetimes and the second plot is a fitted Weibull cdf. (You should explicitly define what it is you're drawing.)
R can certainly draw both those figures. Quite easily in fact; it would only require a couple of lines of R commands in each case.
Are these 2-parameter Weibulls you're drawing? What are you parameter estimates?
Here's an example of two Weibull cdfs on the one plot; you can do six as easily as two. The few cosmetic differences (labels, the gap between the border and the axes, the specific form of dashed lines and so on, orientation of tick mark labels, even the fonts and font sizes) are all relatively simple to change.
Comment: Ah, sorry, your question wasn't especially clear, then. I had thought you were looking for any program that *could* do such plots. You should replace "can also draw" with "drew". [Of course any package that could exactly reproduce them *might actually have made them*.] Can you give more clues -- how/where did you encounter them?
Comment: Thanks a lot. Yes, the figure you drew using R is similar to the one I posted. I am interested to draw such figures and have researched the relevant R packages (MASS and Weibulltoolkit). However, in this question of mine, I want to explore and identify the very program that has created exactly these plots.
On a side note, my parameter estimates are the magnitude of force.
Comment: Glen thanks for the additions to your comment. Sure I will edit my post.
I saw those figures in an article (which prefer not to mention in public). They had not stated the program used for statistical analysis, so I wonder how did they do it so nicely (I pretty liked the visuals of these plots but hadn't seen them before). I suspect they are drawn using either SAS or STATA. SAS friends confirmed SAS default generic plots are not like this. So remains Stata. SPSS and other packages I know can't draw these.
Comment: Stata (not STATA) won't support those horrible patterns in box plots, nor by default will it support axis ticks that are both inward and outward facing.


Por que e quando usar XML em vez de JSON?

Question: O JSON tem pelo menos duas vantagens em relação ao XML:

O parsing é mais rápido
Ocupa menos bytes

Ainda assim tem gente que prefere o XML. Existe algum motivo para preferir XML? Ou em que situações ele é mais adequado (e porque)?
Comment: Acho que a pergunta ficaria melhor se fosse usado "Por que e quando"
Comment: Uma dúvida... Esta questão pode ser baseada em opinião?
Answer: A decisão entre se usar XML ou JSON é mais ou menos como escolher entre um banco de dados relacional ou um NoSQL: tudo se resume a decidir sobre um esquema explícito ou implícito.
Um esquema (schema) é uma descrição de um conjunto de dados (i.e. meta-dados). Ele determina o tipo desses dados, seu formato, a relação entre eles, como eles estão estruturados, etc. Se esses dados são para consumo humano, o esquema não importa tanto - já que temos a capacidade de ler e interpretar o conteúdo à nossa frente ainda que o mesmo esteja mal-estruturado e "bagunçado". Mas se os dados são para consumo da máquina (i.e. serão lidos e manipulados por outros programas) então um esquema formal sempre será necessário - esteja ele codificado em meta-dados ou apenas convencionado.
Assim como em um BD relacional você precisa criar as tabelas, definir suas colunas, suas chaves e restrições, etc, um arquivo XML pode conter o mesmo tipo de descrição (na forma de um DTD ou de um Schema) - dizendo que elementos são aceitos, quais atributos e sub-elementos eles podem ter, etc. Dessa forma, é possível automatizar o processo de verificar se um dado XML é ou não válido de acordo com sua especificação. Ou seja, da mesma forma como você não pode atribuir uma coluna que não existe num BD, você não pode criar um elemento que não existe no esquema e o XML ainda ser válido.
Por outro lado, é possível se criar um XML sem esquema - onde todo conteúdo é válido desde que a sintaxe esteja correta. Ficaria portanto de responsabilidade do programador garantir que esse conteúdo fosse gerado e consumido segundo uma regra lógica. Se for o mesmo programador fazendo os dois lados, é fácil, pois ao mudar um ele saberá que tem que mudar o outro (não dá pra consumir o que não existe, ou produzir algo pra ninguém). Mas se for uma equipe grande - ou pior, um conjunto de equipes ou mesmo de organizações distintas - é mais difícil controlar as alterações e garantir que todos os sub-sistemas envolvidos tratem delas corretamente.
Entretanto, se pelas características particulares de uma situação um esquema explícito não é mesmo necessário, por que não ainda usar XML? Nesse caso, as desvantagens do XML tornam ele uma solução menos que ideal - a sintaxe é verbosa (toda tag aberta tem que ser fechada), os arquivos se tornam grandes e portanto difíceis de ler e escrever, e o processamento de XML é mais difícil e lento. Nesse caso, uma solução mais "leve" é preferível - da mesma maneira de um BD schema-less será mais simples de usar e terá melhor desempenho do que um BD relacional tentando tratar de dados arbitrários, sem estrutura.
O JSON se mostrou uma solução adequada para esses casos. Não é a única, nem necessariamente a melhor (na Wikipedia em inglês há um comparativo entre diversos formatos de serialização de dados), mas como muitas vezes o lado "cliente" da comunicação é um browser - e portanto suporta JavaScript nativamente - essa proximidade adicional entre o formato e os literais da própria linguagem trouxe a vantagem adicional de simplificar bastante o código cliente*. Creio que esse foi um fator decisivo para consolidar o JSON como a alternativa "leve" preferida ao XML. E uma vez que ele passou a receber amplo suporte na maioria das plataformas, sua ubiquidade aumentou ainda mais sua vantagem.
* Digo isso em termos históricos: antigamente se usava o próprio eval do JavaScript para se interpretar JSON, mas depois que a ameaça de XSS ficou evidente e bem conhecida, passou-se a usar funções próprias para fazer a conversão JS-JSON.
Comment: É interessante acrescentar que o XML e JSON devem coexistir e evoluir juntos por algum tempo, e talvez adquiram menos importância se tratados em uma camada de abstração mais alta, a do *modelo de dados*. A especificação [XSLT 3.0](http://www.w3.org/TR/xslt-30/) que deve sair este ano propõe recursos de transformação para construir modelos de dados que tratam JSON e XML de forma equivalente, podendo-se validar e pesquisar JSON ou XML usando XPath.
Comment: Também existem iniciativas como [JSON Schema](http://json-schema.org/) e [JSONPath](http://goessner.net/articles/JsonPath/) buscam trazer para o JSON algumas das facilidades populares que existem no mundo XML.
Answer: JSON:
O objeto JSON é por vezes utilizado como "ponte de comunicação", pois ele é leve e rápido, diferente do XML que possui uma estrutura mais aguçada. A maneira que o objeto JSON é manipulado também é uma das facilidades de organização, tornando o código mais limpo e dedicado apenas à estrutura de dados. Veja um exemplo em ActionScript:
var json:Object = {nome: "João", idade: 18, veiculos: ["Twister", "BMW"], parentes: {mae: "Maria", pai: "Joaquim"}};

Isso sem falar que é possível inserir um Array diretamente em um item, assim como outro objeto JSON.
Essa facilidade de manipulação junto com a rapidez/leveza é um dos motivos principais que faz do JSON a ferramenta perfeita para comunicação de dados com servidor.
XML:
Acredito que o XML possa funcionar como um "mini-bd", gravando algumas informações cruciais para desenvolvimento de algum sistema, seja local ou web.
O sistema de gerenciamento de dados é um pouco mais estruturada, onde você pode adicionar parâmetros e valores em um determinado item, como abaixo:
var xml:XML = new XML(
    <root>
        <atualizacao data="06/06/2014"></atualizacao>
        <nome>João</nome>
        <idade>18</idade>
        <veiculos>
            <veiculo>Twister</veiculo>
            <veiculo>BMW</veiculo>
        </veiculos>
        <parentes>
            <pai>Joaquim</pai>
            <mae>Maria<mae>
        <parentes>

    </root>
);

Embora a estrutura de um XML seja organizada e bem compreendida, a interação com a Web pode deixar um pouco mais a desejar, pelo fato de ser um pouco mais complicada de se trabalhar para resgatar todas essas informações, tirando o fato que você não tem como aderir à um objeto Array dentro de um nó, criando diversos nós com nome idêntico.
Como eu resgataria essas duas informações:
trace(json["nome"]); //"João"
trace(xml.nome); //"João"

trace(json["veiculos"]); //[Twister, BMW]

trace(xml.veiculos); //<veiculo>Twister</veiculo><veiculo>BMW</veiculo>
trace(xml.veiculos.veiculo[0]); //Twister
trace(xml.veiculos.veiculo[1]); //BMW

trace(xml.atualizacao.@data); //06/06/2014

Sim, há essas diferenças entre eles que podem influenciar no resultado final do seu sistema.
Comment: `JSON tem uma facilidade incrível de organizar informações` O que faz ele ter essa facilidade? `JSON não é o mais adequado para guardar informações` Por que o XML seria mais adequado?
Comment: Editei a resposta!
Answer: O XML apresenta diversas facilidades e usos que o JSON não suporta.
Você pode ter busca nele através de XPath, XQuery além de poder validar Schema ( saber se está bem formado ) e muitas outras coisas.
Há espaço para as duas tecnologias, sendo o XML mais robusto ( e burocrático ) e o JSON mais leve ( e menos controlável? )
Answer: Depende do contexto, meu caro. Se você está considerando escolher entre um deles para expor resultados de uma API, por exemplo, vai depender do padrão da sua API. Normalmente, API's Restful tendem a utilizar JSON, enquanto web services no padrão WSDL usam o XML.
O XML, por seguir um padrão de marcação, vai lhe permitir mais flexibilidade, enquanto o JSON é um padrão mais simples e direto – e atualmente mais aceito no contexto web, principalmente quando se fala de single-page applications.


why onload=showField() is used?

Question:

In the above element why the attribute onload="showField(); is used. Please help me out . thanks in advance.
Comment: `showField();` is a function. look in the code
Comment: Google maps als does this, to display their maps. When the div is ready they load the map.
Answer: It is used to call the function showField when the page loading is completed
Comment: Indead, a **Javascript** function
Answer: This simply executes a JavaScript function called showField when the onload event is fired (i.e. when the page "loads"). We cannot tell you what that function does, because it has been created by some programmer. Check the source code to find its definition and find out what it does.
Answer: It's nothing but, when the contents of bodytag is loaded on to the browser window, it will see the value of onload attribute and executes it as JS script.
In this case, onload="showField();", the JS method showField() is called.

why onload=showField() is used?


Iframe resizing not working well

Question: I'm using iframes with added support for drag'n'drop resizing but it's not working very well. MouseUp isn't fired most times. What can I do about it?

<!DOCTYPE html>

        <title>MB Docs</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

Answer: When you do dragging, your mouseUp and mouseMove event could occur on any other element.  It could even not occured at all on some browsers if you mouseUp/mouseMove outside its window boundaries.
You could try to put the mouseUp and mouseMove event on the whole document instead of the specific object, and only when you start dragging, then remove those handlers.
ex. (untested)
$('#ifdivider').mousedown(function(e) {

    isDragging = true;
    xOffset = e.pageX;
    console.log('down');

    $(document).one('mouseup', function() {
        isDragging = false;
        $(document).off('mousemove.dragging');
        console.log('up');
    });

    $(document).on('mousemove.dragging', function(e) {
        if (isDragging && e.pageX < 500) {
            $('#ifmenu').css('width',e.pageX - 2);
            console.log('move');
        }
    });
});

Iframe resizing not working well


Selecting k distinct numbers from an array with increasing probability distribution

Question: I have to select k distinct numbers from an array such that probability of a number getting selected is more if it is at the end of the array (probability increases linearly). I'm thinking of assigning probability to each number as
current_position_of_number_in_array/(n*(n+1)/2)
where n is the size of the given array. Then generate a random number between 0 and 1 and selecting the number in array which falls into that range. This will work fine if I have to select non-distinct numbers, but in case I have to select distinct numbers, this won't be efficient if size of k is of the order of n.(assuming I'm using some kind of hash-set to discard repeated numbers)
Are there better algorithms to select k distinct numbers which are of better big-oh complexity ?
Comment: @CarlHeckman No, it's better asked as a math question.
Comment: What sort of complexity are you aiming for? I think the approach you describe should take $O(n^2\log n)$ expected time in the case $k=n$. I could describe one that takes $O(n^2)$, if that helps -- or are you looking for something like $O(n\log n)$?
Comment: Probably. You would probably have better luck asking this at http://programmers.stackexchange.com .
Comment: $k$ being of the order of $n$ isn't a problem. The approach you suggest only becomes inefficient if $k$ approaches $n$.
Comment: @joriki Agreed. Main problem is if k approaches n, then probability of selecting repeated number becomes very high and to ensure that k unique numbers are selected, I might have to repeat this procedure too many times.
Comment: I'm looking for something of the order of O(n log n) or better
Comment: Note that an alternative way to choose a single number with linearly increasing probability is to choose two distinct numbers and use the larger one. (To get the same probabilities as you have, starting with $1$ and not with $0$, you'd have to add a dummy least element that gets the $0$ probability.) Perhaps you can somehow use this in selecting $k$ numbers.
Comment: That sounds interesting. I can probably use something like Floyd's sampling Algorithm to select 2 numbers every time and select the larger one (O(k lg (k) ) complexity ?). Is there any proof that I can look up to ensure that this algorithm will select numbers with linearly increasing probability ?
Comment: It selects numbers with linearly increasing probability because the number $j$ is the larger element of $j$ pairs, and all pairs are selected with equal probability.
Answer: As I pointed out in a comment, you can choose a single number with linearly increasing probability by choosing two distinct numbers and using the larger one. (This gives probability $0$ for the least element, so you need to add a dummy least element to get exactly the probabilities you describe.)
To use this for efficiently selecting $k$ distinct elements with linear probabilities, set up an array originally containing all $n$ numbers. Then in each step, select $i$ uniformly randomly between $1$ and $n$ and $j$ uniformly randomly from the numbers remaining in the array. Repeat this until $j\gt i$. Use $j$ as the next number and remove it from the array (in constant time, by overwriting it with the last element of the array and decrementing the array length).
This should select all $n$ numbers in $O(n\log n)$ time. I don't have a rigorous proof for that off the top of my head, but it seems plausible from a coupon collector's perspective. The direct approach you described would take $O(n^2)$ time to select the $1$ if it's the last number left, and I think it would take $O(n^2\log n)$ overall. By contrast, this approach would take $O(n)$ time to select the $1$ if it's the last number left, and thus should take $O(n\log n)$ time overall.
Comment: Come to think of it, this is actually just rejection sampling for the $j$s picked from the array; there's no added benefit in regarding $i$ as the second element of a pair; it's basically just a random number drawn to decide whether to accept $j$ (which means that you can use this to sample from any distribution without repetition, not just for your linear case).
Comment: I finally ended up using weighted reservoir sampling with uniformly increasing weights. http://utopia.duth.gr/~pefraimi/research/data/2007EncOfAlg.pdf
Comment: @r15habh: That's a beautiful algorithm! Never heard of it. Please write an answer to your question (and accept it) in case someone else has a similar question.
Answer: I finally ended up using weighted reservoir sampling with uniformly increasing weights.
Here is a detailed paper: http://utopia.duth.gr/~pefraimi/research/data/2007EncOfAlg.pdf
Implementation in Java: http://utopia.duth.gr/~pefraimi/projects/WRS/


Dynamically Change Lookback Period

Question: I am trying to dynamically adjust the lookback period of a pandas dataframe to run regressions on different lengths of stock data. As an easy example take an MA cross.
<code>date        Prices  Diff    signal

20150101    8.5     -1.5    FALSE
20150101    11.5    0.3     TRUE
20150102    14.5    4.5     FALSE
20150103    16.67   3.66    FALSE
20150104    18      2       FALSE
20150105    18.5    0.5     FALSE
20150106    18.17   -2.17   TRUE
20150107    17      -3      FALSE
</code>
Diff is the difference between 2 moving averages and signal identifies a cross with true/false. Numbers are arbitrary, just examples. There could be 10, 50, 100, etc rows between each signal.
Now I would like to run a regression on the prices for whatever length exists between signals, so at row 6 I would want prices[-4:], and row 8 I would want prices[-1:].
Could anyone help me out with this problem? Looping backwards in each row until I find the latest signal seems inefficient. Should I simply assign an index value to a variable whenever a signal occurs, and use that variable to define the lookback period? I'm still relatively new to Python and not sure how to go about this.
Any help would be appreciated. Thank you!
Comment: I have actually solved this problem, but the solution is not very elegant. If anyone has an elegant solution, please let me know.
Answer: I have actually solved this problem, but the solution is not very elegant. If anyone has an elegant solution, please let me know.
<code>    if diff[-1] > 0 and diff[-2] < 0:
        signal = True
        over_count += 1
        under_count = 0
    elif diff[-1] < 0 and diff[-2] > 0:
        signal = False
        under_count += 1
        over_count = 0
    elif signal:
        over_count += 1
    elif not signal:
        under_count += 1
</code>

Dynamically Change Lookback Period


How to pause a process and continue the program?

Question: I'd like to know if there is a way to pause a process but continue the program.
I need to create processes like this:

But when I hit P4 it ends, dies and then P2 creates P5. Then P2 Dies and P1 creates P3 and the same thing happens there.
I need to create the whole 'tree' before the processes start to die.
Can't use wait nor waitpid() because it only targets it's son.
Is there a way to Pause P4 and continue from it's father ?
If I can't how could I achieve my goal ?
My currently code:  It's creating in this order:

P1 -> P2 -> P4 -> P4 DIES -> P5 -> P5 DIES -> P2 DIES ->
  P3 -> P6 -> P6 DIES -> P7 -> P7 DIES -> P3 DIES -> P1 DIES

    #include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <time.h>

int main(){
    clock_t t;
    double time_taken;
    t = clock();
    int status;
    pid_t idProcesso, pai;
    printf("P1 created: %d\n", getpid());

    idProcesso = fork();
    switch(idProcesso)
    {
        case -1: exit(1);

        case 0: //P2
            printf("P2 created: %d  -  son of P1: %d\n", getpid(), getppid());
            idProcesso = fork();
            switch(idProcesso)
            {
                case -1: exit(1);

                case 0: //P4
                    printf("P4 created: %d  -  son of P2: %d\n", getpid(), getppid());
                    sleep(1);
                    break;
                default://P2
                    idProcesso = fork();
                    switch(idProcesso)
                    {
                        case -1: exit(1);

                        case 0://P5
                            printf("P5 created: %d  -  son of P2: %d\n", getpid(), getppid());

                            break;
                        default://P2
                            sleep(1);
                            break;
                    }

                    break;
            }
            break;
        default:

            idProcesso = fork();
            switch(idProcesso)
            {
                case -1: exit(1);

                case 0://P3
                    printf("P3 created: %d  -  son of P1: %d\n", getpid(), getppid());
                    idProcesso = fork();
                    switch(idProcesso)
                    {
                        case -1: exit(1);

                        case 0://P6
                            printf("P6 created: %d  -  son of P3: %d\n", getpid(), getppid());
                            sleep(1);
                            break;
                        default://P3
                            idProcesso = fork();
                            switch(idProcesso)
                            {
                                case -1: exit(1);

                                case 0://P7
                                    printf("P7 created: %d  -  son of P3: %d\n", getpid(), getppid());
                                    break;
                                default://P3

                                    break;
                            }
                            sleep(1);
                        break;
                    }
                    break;

                default:
                    sleep(4);
                    break;
            }
            break;
    }

    printf("Process id: %d terminated\n", getpid());
    exit(0);
}

Comment: On recent linux you can re-parent processes: http://stackoverflow.com/questions/6476452/process-re-parenting-controlling-who-is-the-new-parent
Comment: you need to have all 7 processes running at the same time, or building the tree serially, with roots/branches dying off as you go?  p7 should be the last process standing?
Comment: And.. why can't you just use some conventional synchronization mechanisms? Like pipes.
Comment: @MarcB Yes, I need to create all of them just then kill them all. I can only create one side, kill it, then start creating the other side. Don't know how to create the right side and keep left side alive.
Comment: There is no reason for P2 to wait for P4 before creating P5.
Comment: Updated with my currently code. Maybe you guys can help me find my mistakes. Don't know what to try
Comment: Processes are independent of each other. You can "pause" a process with `sleep()` or `pause()`.
Comment: @PaulGriffiths But doesn't the whole program stops ? I was making some tests with prints and that was what I understood.
Comment: @PlayHardGoPro: The process stops, yes, but that's what you are saying you want it to do. You want it to hang around until you've created all the rest of your processes. So this is your desired behavior.
Answer: Processes run independently of each other, so you just need to:

Keep your child processes alive for long enough for all your processes to get created, which is easy enough to do using sleep(), for instance; and
Don't start wait()ing for any of your child processes until you've created them all.

Here's an example:
#define _POSIX_C_SOURCE 200809L

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void)
{
    pid_t pids[8] = {0};
    printf("P1 created (%lu).\n", (unsigned long) getpid());

    for ( size_t i = 1; i < 3; ++i ) {
        pids[i] = fork();

        if ( pids[i] == -1 ) {
            perror("fork() error");
            exit(EXIT_FAILURE);
        }
        else if ( pids[i] == 0 ) {
            printf("P%zu created (%lu).\n", i + 1, (unsigned long) getpid());

            for ( size_t j = 1 + i * 2; j < 3 + i * 2; ++j ) {
                pids[j] = fork();

                if ( pids[j] == -1 ) {
                    perror("fork() error");
                    exit(EXIT_FAILURE);
                }
                else if ( pids[j] == 0 ) {
                    printf("P%zu created (%lu).\n", j + 1,
                            (unsigned long) getpid());
                    sleep(8 - j);
                    printf("P%zu exiting.\n", j + 1);
                    exit(EXIT_SUCCESS);
                }
            }

            for ( size_t j = 2 + i * 2; j >= 1 + i * 2; --j ) {
                if ( waitpid(pids[j], NULL, 0) == -1 ) {
                    perror("waitpid() error");
                    exit(EXIT_FAILURE);
                }
                printf("Waited for P%zu (%lu).\n", j + 1,
                        (unsigned long) pids[j]);
            }

            printf("P%zu exiting.\n", i + 1);
            exit(EXIT_SUCCESS);
        }
    }

    for ( size_t i = 2; i > 0; --i ) {
        if ( waitpid(pids[i], NULL, 0) == -1 ) {
            perror("waitpid() error");
            exit(EXIT_FAILURE);
        }
        printf("Waited for P%zu (%lu).\n", i + 1, (unsigned long) pids[i]);
    }

    printf("P1 exiting.\n");

    return 0;
}

with output:
paul@horus:~/src/sandbox$ ./procs
P1 created (27206).
P2 created (27207).
P3 created (27208).
P4 created (27209).
P5 created (27210).
P6 created (27211).
P7 created (27212).
P7 exiting.
Waited for P7 (27212).
P6 exiting.
Waited for P6 (27211).
P3 exiting.
Waited for P3 (27208).
P5 exiting.
Waited for P5 (27210).
P4 exiting.
Waited for P4 (27209).
P2 exiting.
Waited for P2 (27207).
P1 exiting.
paul@horus:~/src/sandbox$

Note that the order in which processes are run is inherently unpredictable, so each time you run it you could get slightly different results to the above. I have not attempted to make them create or exit in order, except for a half-hearted attempt at sleep() in the four leaf processes, which is otherwise just there to keep them all alive for long enough. You can almost guarantee the execution and termination order with strategic calls to sleep(), or guarantee it using some form of inter-process communication. As a general rule, you shouldn't care about this order, just about whether your actual work gets done in order.
But, it fulfills the criteria of keeping all the processes alive before any of them start to die.
Comment: @PlayHardGoPro: I refer you to this part of my answer: "Note that the order in which processes are run is inherently unpredictable".
Comment: The `for` loops are there because each parent process has to create two children. Practically any time you want to do something more than once, you'll want to use a loop to do it.
Comment: Thanks man. Compiling your code I got this: `P1(3808), P3(3810), P2(3809)` -> Diferent order but we can see it's ok because of the Pids.  But now I have: `P6(3811)  P4(3813) P7(3812) P5(3814)`. As the Pids are in diferent order, doesnt it mean that it is being created in a wrong order ?
Comment: You rock ! Work perfect. But I could not understand the reason for those `for loop`. I updated my code and it's creating fine BUT processes are not dying in the right order. (child before parent). Could you take a quick look ?


load class with Class loader in java by Class forName method

Question: <code>public class ClassLoaderTest {

public static void main(String args[]) {
    try {
        //printing ClassLoader of this class
        System.out.println("ClassLoaderTest.getClass().getClassLoader() : "
                             + ClassLoaderTest.class.getClassLoader());

        //trying to explicitly load this class again using Extension class loader
        Class.forName("test.ClassLoaderTest", true
                        ,  ClassLoaderTest.class.getClassLoader().getParent());
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(ClassLoaderTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}
</code>
}
Class.forName has a second argument as true which indicates it will initialize a class in java.
What does class initialization means?
Comment: [Right there in [the JavaDoc](http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#forName-java.lang.String-boolean-java.lang.ClassLoader-) it says *"initialize - if true the class will be initialized. See Section 12.4 of The Java Language Specification."* So [refer to §12.4 of the JLS](https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4).
Answer: execute static code segment and initialize static filed and some other relevant work, for more information see this.
java class initialize
Answer: Initialization phase of the class loading (loading, linking and initialization) includes executing static initializers and initialization of its static fields in textual order as defined in the class.
When class initialization happen


get specific rows of table given a rule SQL Server 2008

Question: I have a table like:
ID   NAME     VAL
----------------------
1   a1*a1   90052
2   a1*a2   236
3   a1*a3   56
4   a1*a4   6072
5   a1*a5   1004
6   a2*a2   4576
7   a2*a3   724
8   a2*a4   230
9   a2*a5   679
10  a3*a3   5
11  a3*a4   644
12  a3*a5   23423
13  a4*a4   42354
14  a4*a5   10199
15  a5*a5   10279

Given a number given S = 5, I want to query
the rows wth id: 1,6,10,13,15
they are a1*a1,a2*a2,a3*a3,a4*a4 and a5*a5
I would like something like:
INSERT #NEW_TABLE (ID,NAME,Value) (
SELECT ordinal, NAME, VAL FROM myTable where id = 1,6,10,13,15)

to get
  ID   NAME     VAL
    ----------------------
    1   a1*a1   90052
    2   a2*a2   4576
    3   a3*a3   5
    4   a4*a4   42354
    5   a5*a5   10279

Is there a way to do this for any given S, Maybe wth dynamic sql?
I was getting the formula and I got this:
S=5
ID     formula
1      1
6      1+S
10     1+S+ (S-1)
13     1+S+ (S-1) + (S-2)
15     1+S+ (S-1) + (S-2) + (S-3)

Is there a way to do this inside a case or a while loop?
Comment: What does `S` represent in all of this?
Comment: S is a number wich tells the number of different atts, in the example, when `S=5`, we have `a1,a2,a3,a4 and a5.`
Answer: This worked in testing.
You can just inner join on @Tab to limit your results.  You probably also want to add some traps for values below 3, which I haven't done.
The basic process is

Declare your @s value
Insert the first two rows since they will always be the same
In a loop, insert one row at a time with an incrementing difference
Loop exits once it has run @s-2 times

Try:
DECLARE @Tab Table (id INT)

DECLARE @S int = 5,
        @ct int

DECLARE @cur int = (1 + @S)

INSERT INTO @Tab SELECT 1
INSERT INTO @Tab SELECT (1 + @S)

SET @ct = 1

WHILE @ct <= @S - 2
BEGIN

    SET @cur = @cur + (@S - @ct)

    INSERT INTO @Tab SELECT @cur

    SET @ct = @ct + 1

END

SELECT * FROM @Tab
ORDER BY id

To use this in your query, you can do either:
SELECT ordinal, NAME, VAL
FROM myTable
WHERE id IN (SELECT id FROM @Tab)

-- OR

SELECT ordinal, NAME, VAL
FROM myTable t
INNER JOIN @tab t2
    ON t2.id = t.id

Comment: How would inner join look like?


Is the free commutative monoid on $n$ generators essentially the same as a polynomial ring in $n$ variables?

Question: I let $M$ denote the free commutative monoid generated by some elements $x_1,\dots, x_n$. Suppose too that $R$ is a commutative ring. Then I can construct the free algebra of $M$ over $R$, denote it $R[M]$.
Recall that $R[M]$ is then the set of mappings $f\colon M\to R$ such that $f(m)\neq 0$ for only finitely many $m\in M$. Then $+$ and $\cdot$ are given by $(f+g)(m)=f(m)+g(m)$, $(fg)(m)=\sum_{pq=m}f(p)q(p)$, $0(m)=0$, and $1(1)=1$ and $1(m)=0$ if $m\neq 1$. Moreover, $R[M]$ has a subring isomorphic to $R$ by associating $r\in R$ with $r'\in R[M]$ such that $r'(1)=r$ and $r'(m)=0$ otherwise. It also has a submonoid of the multiplicative monoid isomorphic to $M$ by associating $m\in M$ with $m'\in R[M]$ given by $m'(m)=1$ and $m'(n)=0$ otherwise.
Viewing $M$ and $R$ as being in $R[M]$, I know that any element of $R[M]$ can be written as $\sum r_im_i$. So I'm curious, is $R[M]$ isomorphic to $R[x_1,\dots,x_n]$? To me it appears that the elements of the sets look more or less the same, as does the $+$ operation, but I'm not sure if they actually are isomorphic or not. Thanks for any explanation.
Comment: Yes; the polynomial ring in $n$ variables with coefficients in $R$ is isomorphic to the semigroup ring $R[\mathbb{N}^n]$. For example, this is the way in which the polynomial ring is defined in Hungerford.
Comment: @ArturoMagidin Great, that was exactly what I was looking for, thanks.
Answer: As Arturo Magidin said in comments, the monoid ring $R[\mathbb N_0^n]$ and the ring of polynomials in $n$ variables $R[x_1,\dots,x_n]$ are indeed naturally isomorphic. (I write $\mathbb N_0$ to indicate that $0$ is included, as it's not always considered an element of $\mathbb N$.) Wikipedia article Monoid Ring gives this as a primary example.


ddd 'Can't open display' on macos

Question: I'd like to debug a cython program (following this tutorial).
To do so, I need ddd.
So, I run the following command: brew install ddd
but when the command ddd python3 leads to:
Error: Can't open display:

What can I do to have more information on what is the problem and identify where it is coming from ?
Answer: I don't use ddd, but it appears to need X11, i.e. an X Windows server. As Macs no longer come with an X11 server, you'd need to install XQuartz which you can obtain here.
Also, I would imagine you need:
brew install ddd

rather than:
brew uninstall ddd

Comment: It was a typo, I edited the question. I did install XQuartz, but nothing changed
Comment: no. I just checked with a simple `xclock -digital` and I again get
`Error: Can't open display:`
Comment: Well, if `xclock` won't run, your X setup is incorrect. Have you rebooted since installing XQuartz? Have you set DISPLAY or not? Have you tried manually starting X11 from Finder->Applications before starting `xclock`?
Comment: After a reboot, xclock is now working. When trying to excecute the command `ddd python3`, I now have the following error:`ddd python3
Warning: locale not supported by Xlib, locale set to C
Error: Unresolved inheritance operation

Xt error (Unresolved inheritance operation).

Oops!  You have found a bug in DDD.

If you can reproduce this bug, please send a bug report
to , giving a subject like

    DDD 3.3.12 (i386-apple-darwin17.3.0) gets Xt error`
Comment: I'm approaching the limits of my knowledge now. This may help https://stackoverflow.com/a/8161863/2836621
Comment: I tried what you just suggest. Unfortunately, this does not solve the problem. Thanks for your help. I will post the solution to this problem if I manage to find one :)

ddd 'Can't open display' on macos


How to change to default Localization Client language to translate

Question: Localization Client allow me only to translate from English to one of others languages.
It is possible to translate from language x to English too?
Answer: No.
The reason is the way the Drupal translation system is built. Original strings (defined in modules) must be written in English. This means all translation will be from English to X-language.
Comment: Thanks, is there any module for doing that kind of job? Ex. I have a custom template for teaser. For i18n I must do if else statement for some static content in the template, it would be great if I could use t() function for this.
Answer: The Locale module (in core) will detect your t() strings and provide an interface for translations. Handbook page explaining it in summary can be found here: Translating a site interface to different languages (Locale core module).


Barras de gráfico em vermelho quando valor abaixo da média estipulada

Question: Uso este script para gerar gráfico de média de questões, como fazer para que as barras mudem de cor(vermelho por exemplo) quando a media for menor que 8 (por exemplo)

Comment: Já viste esta solução: https://stackoverflow.com/a/40720444/5675325 ?
Comment: Sim, coloca o código como resposta dando uma explicação do que foi feito e marca como resposta certa.
Comment: Vou tentar aplicar, não sei nada de javascript, rsrs
Comment: Resolvi, a dica do @tiagoperes deu certinho, como faço agora? coloco a solução que usei, já peguei o código quase todo pronto.
Answer: Resposta baseada neste link:
https://stackoverflow.com/a/40720444/5675325
google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Asset','Days in Stock'],
    ['4990/473',606],['4990/489',504],['4990/557',159],['4990/559',147],
    ['4990/578',87],['4990/581',63],['4990/582',53],['4990/586',41],
    ['4990/590',25],['4990/592',20],['4990/593',5],
  ]);

  var view = new google.visualization.DataView(data);
  view.setColumns([0, 1,
    // style column
    {
      calc: function (dt, row) {
        if ((dt.getValue(row, 1) >= 0) && (dt.getValue(row, 1) <= 60)) {
          return 'green';
        } else if ((dt.getValue(row, 1) > 60) && (dt.getValue(row, 1) <= 100)) {
          return 'yellow';
        } else {
          return 'red';
        }
      },
      type: 'string',
      role: 'style'
    },
    // annotation column
    {
      calc: 'stringify',
      sourceColumn: 1,
      type: 'string',
      role: 'annotation'
    }
  ]);

  var options = {
    title: '',
    titleTextStyle: {
      fontSize: 16,
      bold: true
    },
    backgroundColor: 'transparent',
    chartArea: {
      left:80,
      top:30,
      bottom:60,
      right:10
    },
    legend: {
      textStyle: {
        fontSize: 11
      }
    },
    vAxis: {
      title: 'Asset',
      textStyle: {
        fontName: 'Arial',
        fontSize: 10
      },
      titleTextStyle: {
        fontSize: 12,
        italic: false,
        bold:true
      }
    },
    hAxis: {
      title: 'Days in Stock',
      gridlines: {
        count: 22
      },
      textStyle: {
        fontName: 'Arial',
        fontSize: 11
      },
      titleTextStyle: {
        fontSize: 12,
        italic: false ,
        bold:true
      }
    },
    pointSize: 3,
    pointShape: 'circle',
    annotations: {
      alwaysOutside: true,
      textStyle: {
        fontName: 'Arial',
        fontSize: 9,
        color: '#000000',
        opacity: 1
      }
    }
  };

  var chartDiv = document.getElementById('chart_div');
  var chart = new google.visualization.BarChart(chartDiv);
  chart.draw(view, options);
}

div


Replace em linha vazia

Question: Tenho uma variável com o seguinte conteúdo:
10
20 30
40 50 60

70 80 90

100

Existem espaços (podendo ter 2 ou mais seguidos) e quebra de linha (também várias na sequência), e quero substituir para ficar desta forma:
10
20
30
40
50
60
70
80
90
100

Cada valor em uma linha, sem linhas vazias e sem espaços.
Tentei pelo conteudo = conteudo.replace(" ", "\n"); mas as linhas vazias ficam.
Tem como substituir tudo de uma só vez ou limpar essas linhas vazias depois de quebrar todos valores ?
Comment: Variável do tipo String?
Comment: @Laerte isso, String !
Comment: Ai você quer transformar numa outra string só que formatada da forma que você postou, certo ou quer uma lista com os valores?
Comment: Na mesma String, já "tratada"
Answer: Pra remover as linhas vazias você pode usar o método replaceAll com a expressão regular \n+
String tratar = "10\n"
        + "20 30\n"
        + "40 50 60\n"
        + "\n"
        + "70 80 90\n"
        + "\n"
        + "\n"
        + "100";

String nova = tratar.replace(" ", "\n").replaceAll("\n+", "\n");

System.out.println(nova);

Exemplo Funcional: https://ideone.com/AQYWsK
Comment: Não seria mais fácil utilizar apenas uma regex para as duas coisas ? Com por exemplo `\s+|\n+`.
Comment: Sim é possível, só uma correção no regex: `\\s+|\n+`

Replace em linha vazia


Display/Print both full content and teaser in node.tpl

Question: I want to display both full content and teaser content at the same time in node.tpl.php Here is an example of what i want to display

Mini Table

Full Table

        TEASER DISPLAY

        FULL CONTENT DISPLAY

I search for it but didn't find the answers. Please Help
Answer: I think this would be worked for you.
for teaser use
$rendered_teaser = render(node_view(node_load($node->nid), 'teaser'));
print $rendered_teaser;

and for full use
$rendered_full = render(node_view(node_load($node->nid), 'full'));
print $rendered_full;


pandas value_counts( ) not in descending order

Question: There is a dataframe,df
Index              Date               Name         Category
 0            2017-08-09              ABC-SAP       1
 1            2017-08-09              CDE-WAS       2
 2            2017-08-10              DEF           3
 3            2017-08-11              DEF           3
 4            2017-08-11              CDE-WAS       2
 5            2017-08-11              CDE-WAS       2

I executed this code:
df2=pd.DataFrame(df, columns= ['Name','Category'])
df2= df['Name'].groupby(df['Category']).value_counts()
print(df2)

Then I get:
 Index             Name
 (1,ABC-SAP)       1
 (2,CDE-WAS)       3
 (3,DEF)           2

The value.counts( ) does not return a descending order on the NAME column. I really want to have it in descending order from highest to lowest count. Any way of doing it?
Comment: What is your pandas version?
Answer: For me it working nice, but you can test alternative solution:
df2 = df['Name'].groupby(df['Category']).value_counts()
print(df2)
Category  Name
Pri       CDE-WAS    3
          DEF        2
          ABC-SAP    1
Name: Name, dtype: int64

df2 = df.groupby('Category')['Name'].value_counts()
print(df2)
Category  Name
Pri       CDE-WAS    3
          DEF        2
          ABC-SAP    1
Name: Name, dtype: int64

EDIT:
For sort all values use sort_values:
df1 = df.groupby('Category')['Name'].value_counts().sort_values(ascending=False)

Comment: Please fix the `df1 = df.groupby('Category')['Name'].value_counts().sort_values(ascending=False)` example. It contains invisible encoded characters. *I cannot edit because the modification is less than 6 characters.*
Comment: Thanks for the response but It didn't work. It seems to be ordered by the alphabetic ordering of the index and not by the count of occurrences. my pandas version is v3.6
Comment: it is python version, what about `print (pd.show_versions())` ?
Comment: pandas: 0.20.3. I have edited the question. The category column has numeric values but I replaced it with the words(Pri) before and it is still giving the unordered result
Comment: OK, are data confidental?
Comment: OK, if use some another data like `df = pd.DataFrame({'Category':[5,5,5,9,1,1,1,5,1,1],
                   'Name':list('aaabbaabba')})
` it failed too?
Comment: I have idea, is possible upgrade pandas?
Comment: [Category  Name
    1         a       3
               b       2
    5         a       3
               b       1
    9         b       1
  Name: Name, dtype: int64
]
Comment: because `value_count` function with groupby count each category.
Comment: what I really expect is to order by the count  from highest to lowest irrespective of the category
Comment: So do you need `df1 = df.groupby('Category')['Name'].value_counts().sort_values(ascending=False)` ?
Comment: Could you help out https://stackoverflow.com/questions/47933691/grouping-by-day-of-the-week-pandas