Is there a Drupal module that implements a (+/-) button with a counter textbox at the side?

Question: Can you implement a (+/-) button with a counter textbox at the side with Drupal like a shown below?

A very simple way of implementing this, like using an existing module, is much welcome. I am also open for answers implementating this using hard coded scripts.
Comment: @GisleHannemyr Oh... wouldn't that be "[implementing a functionality for which only a screenshot or a site URL is provided](http://drupal.stackexchange.com/help/on-topic)" - as in the **not** section?
Comment: Yes. But what do you want? [``](http://www.w3.org/TR/html5/forms.html#number-state-%28type=number%29) is not enough?
Comment: No actually, I wan't to add a button for increment and decrement.
Comment: That's what number input is supposed to be displayed.
Comment: I am also open for any implementation using hard coded scripts, but for a simpler way of implementing it like an existing module is much welcome.
Comment: @GisleHannemyr if OP needs a module, we need more data. How can we know which of these he needs: entity field, form api field, webform field, standalone voting module? Or possibly others with similar look?
Answer: There is already a module that gives you a vote up/down button, just like the one we have here on SE: https://drupal.org/project/vote_up_down.

Allows votes on some drupal entities and provides the base for implementing votes on other entities.

It is still under dev for Drupal 7, but IMHO quite usable.  If you find any problems, it will probably be less work to help the developers fix those, compared to reinventing the wheel.
Answer: In your existing form(or if one does not exist, you need to create it), add a textfield like this, with some associated markup:
$form['counter'] = array(
  '#type' => 'textfield',
  '#title' => t('Counter value'),
  '#default_value' => YOUR DEFAULT VALUE CALCULATED BY REQUIRED LOGIC GOES HERE, MAKE SURE ITS INTEGER,
  '#size' => 30,
  '#maxlength' => 128,
  '#attributes' => array('class' => 'counter-textfield'),
  '#suffix' => '

',
);

Now in JS file, apply this code:
Drupal.behaviors.updown = { attach: function (context, settings) {
      $('.vote-up').click(function() {
        var existing = $('.counter-textfield input').val();
        var new_count = parseInt(existing) + parseInt(1);
        if(new_count < 0) {
          new_count = 0;
        }
        $('.counter-textfield input').val(new_count);
      });

      $('.vote-down').click(function() {
        var existing = $('.counter-textfield input').val();
        var new_count = parseInt(existing) - parseInt(1);
        if(new_count < 0) {
          new_count = 0;
        }
        $('.counter-textfield input').val(new_count);
      });
    }
};

Comment: Does anybody know if there is a module for this too? Thanks.
Comment: I have seen  the Stepper Field Module. https://www.drupal.org/project/field_stepper which I find very helpful. Thank you.


How to use Matrix Profile for dimension reduction and clustering

Question: Matrix Profile (MP) has been used for clustering time-series segments. In the slideshow tutorial featured on the MP website, they use a figure to demonstrate projecting segment similarity onto an M-dimensional space:

How is this projection from 1-dimensional MP onto M-dimensional space accomplished?
Answer: The procedure is described in the paper "Matrix Profile III: The Matrix Profile Allows Visualization of Salient Subsequences in Massive Time Series" by Yeh et al.
At a high level, the steps are:

Acquire time-series subsequence relevance metric from Matrix Profile
Use metric to select a subset of subsequences
Project subset of subsequences into reduced space using some form of dimension reduction. The paper uses MDS, which is roughly equivalent to PCA.

As described in the paper, the selection of subsequences to reduce is the most important part of this process. If one reduces all subsequences, the result becomes nonsensical, as first presented in the paper "Clustering of streaming time series is
meaningless" by Lin et al.


How do I normalize a bimodal distribution?

Question: I'm working with the Iris dataset. One of the variables, PetalWidth, has a clear bimodal distribution.
My understanding is that multivariate regression sssumes normality for each of the input variables.
Can I continue with the variable left alone? Is it necessary to normalize it?
Here's the R code to access the data:
dni3 <- dimnames(iris3)
ii <- data.frame(matrix(aperm(iris3, c(1,3,2)), ncol = 4,
                        dimnames = list(NULL, sub(" L.",".Length",
                                                  sub(" W.",".Width", dni3[[2]])))),
                 Species = gl(3, 50, labels = sub("S", "s", sub("V", "v", dni3[[3]]))))
all.equal(ii, iris) # TRUE

Answer: I assume you mean multiple regression?
Anyway, it doesn't assume normality of the input variables. It assumes the response variable is conditionally distributed Gaussian (normal) but doesn't assume anything about the covariates or predictor variables (that said, transforming the covariates so that it's not just a few extreme values dominating the estimated effect often makes sense.)
Let's assume you are modelling petal width and it is bimodal. We might assume that the width of the petal is in some way connected to some of the petals coming from species A and some from species B. Once we account for the effect of species, the bimodality disappears if it was due to species as we essentially subtract each species mean from the data, which moves the two modes of the distribution together to be approximately 0. We then can say that conditional upon the model the response is distributed Gaussian (or rather we hope we can say this, but this is an assumption we need to check). Or in linear regression, that the residuals, which are the data after we have account for the model, are distributed Gaussian.
For example:
data(iris)
library('ggplot2')
library('cowplot')
theme_set(theme_grey())

mod <- lm(Petal.Width ~ Species, data = iris)
iris <- cbind(iris, Residual = resid(mod))

p1 <- ggplot(iris, aes(x = Petal.Width)) +
  geom_histogram(bins = 10) + labs(title = "Original data")
p2 <- ggplot(iris, aes(x = Residual))+
  geom_histogram(bins = 10) + labs(title = "Residuals")
plot_grid(p1, p2, ncol = 2, align = 'hv', axis = 'lrtb')

Which produces

The residuals aren't really Gaussian, but this is not the right model for a variable constrained at 0 (can't observe zero width or negative width petals). However, the bimodality has gone because it was due to (careful with causality) or related to differences between species.
Comment: does data transformation of the response variable into one that is conditionally distributed Gaussian (normal), in accordance with linear regression's assumptions, lower the amount of out-of-sample mis-estamation the fitted model makes? or will the model perform the same as it would had the original data been used, untransformed? in other words, are we any better off complying with the rules (assumptions) of a learning model, or will estimation error still be present either way regardless?


How to add more information about authors with the Bibliography module?

Question: We are setting up a bibliography for old and very rare resources with Drupal 7 and the Bibliography module. We need to have more information about authors (picture, biography, nationality). We have seen that we could link authors to users but in our case authors don't require to have a real user account (because most of the time authors are dead).
My questions:

How can we add more information to authors?
Is it possible to create some kind of user account without login, password and e-mail ?
Would it be possible to create a specific content type for authors (with fields for picture, biography and nationality) and link it to the biblio author, and in that case how could we do this?
Answer: Create another content type like "BookAuthor" with 1 node for each such Author. Then add fields to this content type for attributes such as picture, biography and nationality.
Assume you have a content type like "Ressources" (or just create one). Add a field in that content type using the Entity reference module for it (probably with multiple values allowed). That way you can add one or more "links" in each Ressources-node to relevant nodes of type BookAuthor.
PS: just to avoid possible surprises, I would not call the content type "Author" (which has a special meaning in Drupal, so better to not confuse Drupal with the same name for your extra content type).
Comment: THanks for your answer. We are trying in that direction : create a author content type with entity reference to biblio author. And add an entity reference to the biblio content type to the author content type.


Is the following property for positive random variables fulfilled in general?

Question: Suppose we have a continuous random variable $X$, defined on the interval $[0, \infty)$, which has density $f(x)$ and a finite expectation and variance.
I am wondering whether the following is true in general:
Take any value $\alpha > 0$, and let
$x_1 := \mathbb{E}(X|X \leq \alpha)$, while
$x_2 := \mathbb{E}(X|X > \alpha)$.
Will a new, discrete random variable $\tilde{X}$, where
$\tilde{X} = x_1$ with probability $F(\alpha)$, and $\tilde{X} = x_2$ with probability $1-F(\alpha)$, always have a lower variance than $X$?
I have checked that this property is true for the uniform distribution. Formally, it is straightforward to see that the property is fulfilled if for all $\alpha > 0$,
$\int_{0}^{\infty} x^2 f(x)dx \geq \frac{\left(\int_0^\alpha x f(x) dx\right)^2}{F(\alpha)} + \frac{\left(\int_\alpha^\infty f(x) dx\right)^2}{1-F(\alpha)}$.
Using Jensen's inequality, a sufficient condition for the above is that
$\left(\int_{0}^{\infty} x f(x)dx\right)^2 \geq \frac{\left(\int_0^\alpha x f(x) dx\right)^2}{F(\alpha)} + \frac{\left(\int_\alpha^\infty f(x) dx\right)^2}{1-F(\alpha)}$.
However, I am not really sure where to go from there. The integral in the LHS can still be split up into the range $0$ to $\alpha$ and $\alpha$ to $\infty$, but doesn't seem to help me much.
Maybe the property is not true in general, after all?
Any input is appreciated. Many thanks in advance!
Answer:
The property does hold, in great generality.

Let $X$ denote any (integrable) real valued random variable and $a$ some real number such that $A=[X\leqslant a]$ and $A^c=[X\gt a]$ both have positive probability. Let $X_a$ denote any random variable such that $X_a=E[X\mid A]$ with probability $P[A]$ and $X_a=E[X\mid A^c]$ with probability $P[A^c]=1-P[A]$. Then $E[X_a]=E[X]$ and
$$
E[X_a^2]=E[X:A]^2P[A]^{-1}+E[X:A^c]^2P[A^c]^{-1}.
$$
For every event $B$, Cauchy-Schwarz inequality applied to $(X\mathbf 1_B)\cdot\mathbf 1_B$ yields
$$
E[X:B]^2=E[(X\mathbf 1_B)\cdot\mathbf 1_B]^2\leqslant E[(X\mathbf 1_B)^2]E[\mathbf 1_B^2]=E[X^2:B]P[B],
$$
hence, for every event $B$ with positive probability,
$$
E[X:B]^2P[B]^{-1}\leqslant E[X^2:B].
$$
Applying this to $B=A$ and to $B=A^c$ and summing the resulting upper bounds yields
$$
E[X_a^2]\leqslant E[X^2:A]+E[X^2:A^c]=E[X^2].
$$
Finally, since $E[X_a]=E[X]$,

$$\mathrm{var}(X_a)\leqslant\mathrm{var}(X).$$

Although the above fully proves the desired result, it may help to put it in a more general context. Let $\mathcal A=\{\varnothing,A,A^c,\Omega\}$ denote the sigma-algebra generated by $A$, then $Y=E[X\mid\mathcal A]$ is an example of a random variable $X_a$, since $Y=E[X\mid A]\mathbf 1_A+E[X\mid A^c]\mathbf 1_{A^c}$. It happens that, for every sigma-algebra $\mathcal G$, $Z=E[X\mid\mathcal G]$ is such that $E[Z]=E[X]$ and $Z^2\leqslant E[X^2\mid\mathcal G]$. Integrating the last inequality (called conditional Cauchy-Schwarz inequality), one gets $E[Z^2]\leqslant E[E[X^2\mid\mathcal G]]=E[X^2]$. Thus, $E[Z]=E[X]$ and $E[Z^2]\leqslant E[X^2]$, which proves the general result that
$$
\mathrm{var}(E[X\mid\mathcal G])\leqslant\mathrm{var}(X).
$$
Comment: No fallacy. The more refined the partition is, the largest the variance is. Extreme low: partition $\{\varnothing,\Omega\}$, then $Z=E[X]$ hence the variance of $Z$ is zero. Extreme high: $\mathcal G=\mathcal F$ (the most refined possible partition), then $Z=X$ hence the variance of $Z$ is the variance of $X$.
Comment: No density needed. If X is integrable but not square integrable the LHS is finite and the RHS is infinite hence the inequality holds. If X is not integrable, none of these conditional expectations make any sense anyway.
Comment: Many thanks for the detailed reply. I'll make sure to go through the steps (starting from Cauchy-Schwarz) carefully.
Comment: Coming to think of it, the property seems a bit strange though. In essence, I believe it implies that one can split up a random variable into smaller and smaller sub-portions, define a new, discrete random variable out of those, and reduce its variance. However, for infinitely many sub-portions, we end up with the original distribution (and hence, original variance) again. Where is the fallacy here?
Comment: I am missing a proper background in probability theory, so my understanding is on a naïve level, but are you essentially saying that splitting up a distribution into $N \geq 1$ subintervals and making a new discrete random variable out of it (which takes on the $N$ different expectations of each subinterval, with corresponding probability), has a variance that is monotonically increasing in $N$ (given that when going from $N$ to $N+1$, we do not change the old "boundaries")?
Comment: Yes. In other words, to refine a partition can only increase the variance. One may think of $X$ itself as corresponding to the *finest* partition of all (and of the constant $E[X]$ as corresponding to the *coarsest* one).
Comment: Great, I think I understand it now. That's a very nice result. I'll accept your answer directly - thanks a lot for helping out!


Time and speed problems:

Question:
Rahim covered 1/3 of his total Journey by bus,1/6 of his total Journey
  by car and the rest of the Journey by train.If the speeds of the
  train,car and bus are 60km/hr,80km/hr and 50km/hr respectively then
  what was the average speed of Rahim during entire Journey?

I have tried:
For time and speed problems for calculating the average speed we need to know the total distance and total time
let x be the distance so 1/3*x,1/6*x and 1/2*x respectively,speed  have given
I am calculating the total time
total time = (1/3*x + 1/6 *x + 1/2*x )/60+80+50 = x/190
for average speed = total distance/total time = x/(x/190) = 190
but answer is 58.5 km/hr , what i am doing wrong , please anyone rectify my mistake
Answer: The average velocity is: $v_{avg}=\dfrac{displacement}{time}$, and we know that the total time is: $\Delta t=\dfrac{\Delta displacement}{velocity_{avg}}$. Say the total distance is $n$ kilometers. So the distances covered by bus, car and train, are $\dfrac{n}{3}, \dfrac{n}{6}$ and $\dfrac{n}{2}$ kilometers, respectively. The overall distance obviously, is $n$. So we just have to calculate the total time which according to the second formula will be:
$\Delta t = \Delta t_{bus} + \Delta t_{car} + \Delta t_{train} = \dfrac{n/3}{50} + \dfrac{n/6}{80} + \dfrac{n/2}{60} = \dfrac{41n}{2400}$
So the average speed (scalar quantity) is:
$\dfrac{n}{\dfrac{41n}{2400}} = \dfrac{2400}{41}$
Which is approximately $58.53$.
Comment: ok thank you i have understand what i am doing mistake

Time and speed problems:


PHP identifying each record separately

Question: I've been working on a survey system that reads the records(questions sorted by "chapters" you'll see what I mean later) out of database and adds a score per record. The questions are stored in an array. so one record can hold for example five questions. let's dive into the code
//echo the question list from the database

$query_questions = mysql_query("SELECT * FROM `vraag`");
while($result = mysql_fetch_array($query_questions))
{
//displaying the questions
echo "

";
echo $result['header']. "
";
echo $result['beschrijving']. "

";
echo $result['onderwerp']. "
";

$aantal = $result['aantal_vragen'];
$id = $result['id'];
echo "<input type='hidden' id='number_of_questions' value=".$aantal." mousedown='calculate_score(this.value,0)'/>";
$array = unserialize($result['vraag']);
//retrieve the content from the array
for($i = 0; $i < $array; $i++)
{
        foreach($array as $value)
        {
            $array = $value;
            echo "<form>
". $array ."	";
            echo "
            1<input type='radio' name='vraag[]' value=1 onclick='calculate_score(".$aantal.",this.value)'/>
            2<input type='radio' name='vraag[]' value=2 onclick='calculate_score(".$aantal.",this.value)'/>
            3<input type='radio' name='vraag[]' value=3 onclick='calculate_score(".$aantal.",this.value)'/>
            4<input type='radio' name='vraag[]' value=4 onclick='calculate_score(".$aantal.",this.value)'/>
            5<input type='radio' name='vraag[]' value=5 onclick='calculate_score(".$aantal.",this.value)'/>
</form>";
        }
    echo "Uw totaal score is: ";
    break;
}
}

what goes wrong is that it uses the last record of the query as the value to calculate with, it ignores the first record and the second and only picks up the last(third) record I want it to assign a score per record so shortly drawn out. The point of the radio elements is to make a point system ranking from 1 to 5 so it looks like: Question 1-2-3-4-5
this is my intention
[record 1]
score
[record 2]
score
[record 3]
score
but currently it works like this
[record 1]
[record 2]
[record 3]
score
I'm not entirely sure about the break command I have but I was testing if it'd fix my issue. For the score label thing I know I should increment the array by one each time it's filled but I don't know the syntax or if it is even possible at all to do so.
I'm new to stack overflow so forgive me any missing tags or anything other that's unreadable or unpleasant on the eyes.
Answer: The outer for loop makes no sense. In the inner loop you are re-assigning $array while iterating over it (don't really know what it does, but it's just plain wrong).
//Drop this code:
//for($i = 0; $i < $array; $i++)
//{
    foreach($array as $value)
    {
        $array = $value;   /* this is WRONG */
        /* ... */
    }
echo "Uw totaal score is: ";
//break;   <--- don't need this either
//}

PHP identifying each record separately


Como fazer consulta personalizada com JPA+Hibernate

Question: Olá,
Gostaria de saber uma forma elegante de fazer uma consulta personalizada usando JPA.
Basicamente eu quero executar a consulta e que ela me retorne uma lista de objeto, mas geralmente vai se tratar de uma consulta com N tabelas e só com os campos que eu precisarei.
Entendo que tenho que fazer o POJO do retorno da query, mas teria algum annotation  ou outra coisa pra me ajudar a fazer esse link entre o retorno da query e o objeto? Não quero ter que passar linha a linha instanciando o objeto e coluna a coluna preenchendo as propriedades dele.
Answer: Você pode usar a palavra chave NEW da JPQL na query, especificando uma classe. Para cada linha retornada, será criada uma instância desta classe. E então você pode passar o tipo desta sua estrutura de dados como parâmetro quando for solicitar a query ao EntityManager.
Esta estrutura de dados (ou "classe") precisa declarar um construtor que receba os valores dos campos na ordem em que eles são selecionados na query.
Então, considerando esta estrutura de dados:
package org.learning;

class ContaAtrasada {
    final int idConta;
    final double valor;
    final int diasEmAtraso;

    ContaAtrasada(int idConta, double valor, int diasEmAtraso) {
        this.idConta = idConta;
        this.valor = valor;
        this.diasEmAtraso = diasEmAtraso;
    }
}

O método que executa a query ficaria mais ou menos assim:
public List<ContaAtrasada> findContasAtrasadas() {
    return em.createQuery("select NEW org.learning.ContaAtrasada(c.idConta, c.valor, " +
            "today - c.dataVencimento as diasEmAtraso) " +
            "from Conta c where c.dataVencimento < today", ContaAtrasada.class)
            .getResultList();
}

Eu explicitei o namespace (package) da classe porque é muito importante informá-lo na sua query JPQL, já que a query pode ser executada em outro contexto onde a sua classe não estará diretamente acessível.
Comment: Exatamente o que eu precisava... vou testar! =)


How to set condition by referring whether specific record exists or not

Question: I have following mst_table and history_record
mst_table
document name
1        Request for Approval
2        Purchase order
3        Payment Slip
・    ・
・    ・

history_record
case date        status
A     2023/3/13   rejected
A     2023/3/14   rejected
A     2023/3/15   approved
B     2023/3/13   rejected
B     2023/3/13   rejected

I would like to get appropriate document date from mst_table referring to case as variable in history_record
When they have approved,I don't need document A Request for Approval.
When case =A was set as variable. my desired result is
document name
2        Purchase order
3        Payment Slip
・    ・
・    ・

when case=B was set, my desired result is like follows
document name
1        Request for Approval
2        Purchase order
3        Payment Slip
・    ・
・    ・

I tried like follows. but
SELECT EXISTS(SELECT * FROM history_record WHERE case = 'A')
Answer: We can use exists logic as follows:
SELECT m.document, m.name
FROM mst_table m
WHERE NOT EXISTS (
    SELECT 1
    FROM history_record h
    WHERE h."case" = m.document AND
          h.status = 'approved'
          -- AND h."case" = 'A'
);

You may restrict the exists clause to a specific document, if you want the exclusion to apply at a document level.
Comment: thank you for answer ! in fact, each key has no relation in my sample. so that I would like to eliminate `document = 1` when some case has `approved` in my `mst_table`. sorry for inconvenience..
Comment: There needs to be a correlation between the two tables, otherwise your question cannot be answered.


What does it mean to solve a math problem analytically?

Question: I'm reading a Calculus book for my own edification and at the beginning the pre-calculus introduction has the problem,
$3x+y=7$
They talk about solving the problem graphically, analytically, and numerically.  The subject is the basic graph, Rene Descartes, etc.
They have numerical which is just a table of values.  I understand that.
Graph I understand.
But for the analytic approach, they have
"To systematically find other solutions, solve the original equation for $y$
$y=7-3x$
I do not understand how they came up with that.  Why not $x$?  Why is this analytic?  What makes this "analytic"?  Why would it even occur to someone that solving for why is the way to go, the thought process.
I can solve the problem.  That's not the issue.  I want to understand why I'm doing it this way.  Thanks.
edit:
"The Graph of an Equation
Consider the equation $3x+y=7$.  The point $(2,1)$ is a solution point of the equation because the equation is satisfied (is true) when $2$ is substituted for $x$ and $1$ is substituted for $y$.  This equation has many other solutions, such as $(1,4)$ and $(0,7)$.  To systematically find other solutions solve the original equation for $y$.
$y = 7 - 3x$  Analytic approach"
I'm sure this is obvious and maybe I don't understand what the word analytic means in this context.
Calculus of a Single Variable, Sixth Edition, 1998, Larson, Hostetler, Edwards
(I got it a thrift store.)
Comment: To use nice fonts, typeset them with LaTeX -- simple `$` before and after -- e.g. `$3x+7$` yields $3x+7$
Comment: It may help to explain what the actual problem was that the text was solving, that was related to the equation $3x+y=7$.
Comment: That's all it has.  I will put the full paragraph.  It's the first page.
Comment: @gt6989b How do I put the "nice" equation font in there?
Answer: "Analytically" comes from the same root as "analysis," which in mathematics loosely means the study of the properties of objects.
In this case, analytically solving an equation means finding a solution simply by exploiting known rules: addition and subtraction, associativity, commutativity, etc.
This differs from a "numerical" solution, where a sequence of numbers are used and compared to see if equality is met. Numerical solutions are very similar to graphical solutions, but do not require a pictoral representation.
Comment: @johnny turning $3x+y = 7$ into $y = 7-3x$ is just application of the field axioms of the reals and the properties of equivalence relations. Basically, what you are doing is subtracting $3x$ from both sides: $3x+y-3x = 7-3x$. Then, noting that addition is commutative, we have $3x+y-3x = y+3x-3x = y$.
Comment: Ok.  I guess I need to get Algebra One :).  I took Calc 2 several years back, but always took for granted the rules I had memorized.  what would I look at to know why I can do y=7-3x?
Comment: I see what you are saying, but my question is even more fundamental.  Where do I read about "field axioms of the reals"?  I can see it work.  I must know more about why it works.  I don't know if that makes sense.  I want to know about the axioms.  Some guy just discovered this one day?  Something else?  Thanks for your time and patience.
Comment: You can read about it in any analysis book, or by reading about the [http://en.wikipedia.org/wiki/Real_numbers#.22The_complete_ordered_field.22](real numbers). In short, the axioms that make it work are rules that have been "made up." However, they are rules that make sense with ordinary life. If you wanted to construct the real numbers, you might start with the natural numbers (1, 2, etc) and then start with some basic operations (addition, multiplication), and then derive properties from there.
Answer: Analytic would mean manipulating the equations involved to express one variable in terms of other variables without using numerical computations.
For example, in your case, the value of $y$ was expressed in terms of $x$ without using any explicit value for $x$.
Comment: Traditionally, $y$ is used to represent the variable we want to know about or predict and $x$ the variable whose value we know. In analytic solutions, we want to express the variable whose value we want to know in terms of the variables whose values we already have.
Comment: Why did they pick y?
Comment: But we don't already know x.  I guess it is just tradition.
Comment: Well, in your case it is a 'made-up' problem. But, in some situations, $x$ represents a value we want to change (say, velocity of a missile) and we want to predict where it will land which is then denoted by $y$. So, then the goal is to obtain $y$ as a function of $x$ and then understand how 'where it will land' changes as we change velocity with which we launch it.
Answer: Analytic in the generic math sense essentially means to solve using Algebra (properties, rules, or theorems, or use trig/functions properties), or in other words without the use of a calculator, graph, or by plugging in values (which is similar to a table of values).
Answer: The equation that you state is not a problem. It is an equation that relates the variables x and y. A "problem" (task) might be to solve for y, or solve for x, or put the equation in some other special form, or find x when y is 13, or some such. Apparently the author of the book had something in mind that he didn't state. Unfortunately that doesn't seem to be uncommon. You questioned it which was the exactly right thing to do.
Answer: I mean whether you use a numerical approach(by comparing values to get close and close to your desired answer), a graphical approach (looking at the graph to approximately reach your answer, or an analytical approach (using algebra). You will always be given some dependent value (commonly acknowledge as x, but not always), to find the independent value in another set (commonly acknowledge as y, but same, it is not always). So in fact, both x and y are arbitrary variables, you can choose c and e instead of x and y and the equation is going to work. What the more precise definition is that: In the analytical approach, you manipulate the equation algebraically to find the value of the independent variable that you desired to look for.
In lower-level algebra and lower-intermediate calculus analytical approach generally gives you the most accurate answer. Especially when you don't have a powerful computer that is able to get a high level of accurate approximation.
However, there are always equations hard to solve. For example, if you doing integration, some equation is just impossible to integrate, or not without hours of work. So you often approximate by using the numeric integration technique instead of doing it the analytical way. Two examples you could search for are Simpson's rule and Trapezoidal rule, which give a pretty nice approximation when you have sufficient 'cut' made and is not so hard to compare for a large amount of 'cuts' on a modern computer. You can always see this is what the general numerical approach does. (^-^)
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://math.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://math.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/1813818)


Naive Bayes model diagnostics -- testing independence between features

Question: One of the main assumptions of the naive Bayes model is that the features are independent. This allows probabilities to be estimated. However, often times it is understood that this assumption doesn't hold in the data. Naive Bayes is, however, still used for applications like text classification because it still provides "good results."
My question is:
1) Is there any way to check how well the assumption holds? I.e., can I test for conditional independence?
2) Is there a way to determine what "good results" are. I.e., are "good results" from a naive Bayes model, vs any other model, based on things like accuracy/how well the model cross validates on training data?
Answer: You don't check the assumption of independence when using Naive Bayes, you don't even expect it to hold. The textbook example of using Naive Bayes is spam detection with text data, we don't use it in such cases because we assume that words in human language appear in random combinations, that are independent, but because the algorithm has proven to work in such setting. Moreover, it would be hard if not impossible for you to find data where features are independent, usually there exists some, non-zero degree of dependence.
Answer: 1) There is no single answer to this question.  A good metric for linear dependence is a correlation matrix.  i.e. cor(x) in R.  If the features are linearly independent, they are uncorrelated, hence the non-diagonal entries of the correlation matrix should be close to zero.  See here for a discussion of why naive bayes does well even when its assumptions are violated.
2) Again, there is no single answer to this question. The most common way to compare machine learning models is to see how well they do on held out data and the most common metric is AUC.
Comment: Correlation measures only pairwise relationships between variables, while in native Bayes we are talking about joint distribution of all the variables. Also correlation measures only linear relationships. So it does not help much.


is('checked') filtering method not working correctly

Question: I am trying to see if a checkbox got checked with is() method, but it is giving an unexpected result. Either way if I check the checkbox or not, the method is returning false.
HTML
<form action="" method="post" id="place_order">
<input type="checkbox" name="tos" class="required check-condition" />
* This field is required

<input type="submit" name="place_order" value="Submit Order" class="order-sb-btn" />
</form>

Jquery
$("#place_order").submit(function () {
    var is_tos_checked = $(".check-condition").is('checked');
    console.log(is_tos_checked);
    if (is_tos_checked) {
        $(".error-tos").hide();
        return true;
    } else {
        $(".error-tos").show();
        return false;
    }
});

Jsfiddle
http://jsfiddle.net/yogc5ypb/1/
Answer: You need to express checked as a pseudo-selector, i.e. prefixed with :
.is(':checked');

Comment: You can also use `var is_tos_checked = $(".check-condition").prop('checked');`
Comment: Well, one returns a boolean while the other returns the property value. The property value, in this case, would be coerced into its boolean form when tested in a condition, but still, if you want a boolean (as the OP does), best to use the method that returns one.
Answer: I usually use .prop('checked')
So in your code you would change your line to:
var is_tos_checked = $(".check-condition").prop('checked');

Answer: If you want to submit form if user checked check box then you can use following method also-
1.write following statement in html file
<form action="" method="post" id="place_order">
<input type="checkbox" name="tos" class="required check-condition" />
* This field is required

<input type="submit" name="place_order" value="Submit Order" class="order-sb-btn" />
</form>

2.Write following statement in js file.
jQuery('.order-sb-btn').click(function(){
    var checkedValue = $('.required:checked').val();
    if(checkedValue == undefined)
    {
        alert('not checked');
        return false;
    }
    else
    {
            alert('checked');
    }

})

By using above code form will be submit if user check the checkbox.
To check example please refer following link-
http://jsfiddle.net/1eygh774/1/


Can you be caught out if the bat slips from your hands?

Question: If the bat slips from the batsman's hands, and the ball touches the bat, and is then caught by a fielder, should the batsman be given out?
Answer: No - the batsman can only be out if he hits the ball with the bat, or a hand holding the bat, whilst in the commission of a stroke. If he is not holding the bat, and the ball strikes the bat, it's not out. See Law 6.8 "The bat"1
Depending on the circumstances, it could be obstructing the field, for instance if he throws the bat at the ball to prevent it striking the stumps for a runout. This would need to be a deliberate act.
1. After the Laws were renumbered in 2017, this is now Law 5.6.
Answer: If a ball hits the bat or the hand holding the bat and is then caught by the opposition within the field of play before the ball bounces, then the batsman is out.
Comment: No - see the law as quoted in TrueDub's answer; if the ball hits a bat which is not held by the batsman, they cannot be caught out.


How to get a list of entity types the Drupal 9 way?

Question: I need to get a list of all entity types.
EntityManager is deprecated. In Drupal 9 EntityTypeRepository should be used, though I don't see any reference to its being used.
How would I use this class in a non-static way to obtain a list of all entity types?
Comment: See [EntityTypeRepositoryInterface::getEntityTypeLabels](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityTypeRepositoryInterface.php/function/EntityTypeRepositoryInterface%3A%3AgetEntityTypeLabels/9.0.x). Statically you can use `\Drupal::service('entity_type.repository')->getEntityTypeLabels()`. Non-statically is standard DI, which depends on the type of class you want to use it in.
Comment: Googling `drupal EntityManager is deprecated` gives you a page full of samples how to accomplish this. Please always do some research first, try out what you find and if somethings left unclear provide a reproducible and detailed question of what went wrong. Many thanks
Comment: Yup. Did research, and look through code. EntityTypeManager does the job when you have an entity in mind... not so much when you want all entity types, which is where my research yielded the class I asked about.
Answer: As the EntityManager docs say:

Deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
  Use \Drupal::entityTypeManager() instead in most cases. If the needed
  method is not on \Drupal\Core\Entity\EntityTypeManagerInterface, see
  the deprecated \Drupal\Core\Entity\EntityManager to find the correct
  interface or service.

<code>$entity_type_manager = \Drupal::service('entity_type.manager');
$entity_definitions = $entity_type_manager->getDefinitions();
// Create a list of entity types.
$entity_types_list = [];
foreach($entity_definitions as $entity_name => $entity_definition) {
  $entity_types_list[$entity_name] = (string) $entity_definition->getLabel();
}
</code>
Comment: You're absolutely right. I forgot that there was an interim step where I read that I should instead be using the method getEntityTypeLabels instead, and it was it, not getDefinitions, that forced me to the other class.
Comment: I asked about the other class because EntityTypeManager seems not have a GetDefinitions (plural) method, which is how I eventually found the EnitityTypeRepository class mentioned.
Comment: It does have the `getDefinitions()` plutal method, so you're wrong about that.


I would like to allow login to a box with no password for a particular user how do I do that?

Question: I would like a userid to allow logging into a box without a password.  I am not sure how to accomplish this as changing the password to nothing is not allowed.
Thanks
Answer: On linux, for example, if you changed /etc/shadow in the following way you would accomplish what you want.
Change this:
user:$1$xxxxxxxxxxxxxxxx:14650:0:99999:7:::

To:
user::14650:0:99999:7:::

For a better answer however, I would recommend looking into ssh keys.


can i mark notification as already read , using the graph api?

Question: I'm using this to get a notification list:
https://graph.facebook.com/me/notifications/?include_read=0

Now I'd like to mark them as read, how do I do this?
Comment: i didnt try any thing , i have no idea where and what to try
Answer: You should issue a POST request to https://graph.facebook.com/%notification_id%?unread=false where %notification_id% is the notification identifier you've received earlier (usually  something like 'notif_XXXXX_YYYYY').
If you want to mark all notifications read, you can perform a batch request.


Async/Await Entity Framework ObjectContext disposed

Question: I'm running into this issue where I get the following error:

A first chance exception of type 'System.ObjectDisposedException' occurred in EntityFramework.dll
Additional information: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

I get that error while trying to access a table using EF 6. I have set the method to async and await the return value, but it still gives me disposed error.
 public async Task<List<Ticket>> GetAllOpenTwoTicketsAsync() {

        using (AssetTrackingEntitiesObj _edmObj = new AssetTrackingEntitiesObj()) {
            _edmObj.FullObjectContext.Connection.Open();
            return await _edmObj.Tickets
              .Where(t => t.TicketStatusType.isOpenTicket)
              .Include(t => t.AssetTickets)
              .Select(t => t).ToListAsync();
        }

    }

here is the method that calls the tickets
 TicketsCollection = new ObservableCollection<Ticket>(await _ticketRepository.GetAllOpenTwoTicketsAsync());

Am I doing that correctly? Every method in my repository uses a using statement, creates its own objectcontext, opens its own connection and then does what ever it needs to, is this the correct manner for multiple async with EF6? Thanks in advance.
Answer:
_edmObj.FullObjectContext.Connection.Open(); isn't needed. The using statement takes care of opening and disposing the context. That's the main reason to use them over opening/closing/disposing resources yourself.
.Select(t => t) is completely unnecessary. Just calling ToListAsync() will do the trick.

The rest of your code looks fine, so it's probably the first statement that is causing the error. Another cause could be that you try to access a navigation property that you didn't include, lazy loading doesn't work when your context is disposed.
Comment: The Selects weren't needed, thanks. I did end up having to use some of EF transactions and turned off lazy loading completely.


Prove that if x and y are real numbers, then max(x,y) + min(x,y) = x+y.

Question: Prove that if x and y are real numbers, then max(x,y) + min(x,y) = x+y. [Hint: Use a proof by cases, with the two cases corresponding to x≥y and x<y, respectively.]
Using hint, I supposed two cases where: x≥y or x<y.
Thus, if x≥y, then max(x,y) = x or y (since x and y might be the same), min(x,y) = y. Therefore, it is equal to 2y or x+y. Since it covers all of the cases, the equality always holds.
If x<y, then max(x,y) = y, min(x,y) = x. Thus, it is equal to x+y.
But the answer is slightly different from my solution. The answer is:
If x≤y, then max(x,y) + min(x,y) = y+x = x+y. If x≥y, then max(x,y)+min(x,y) = x+y. Because there are only two cases, the equality always holds.
You can notice that the answer supposed two different cases, x≤y or x≥y.
But I supposed x≥y or x<y.
I want to know whether these two different answers are both correct or not.
On the other hand, is it correct if I make three cases, where x > y, x = y, and x < y?
When x > y, max(x,y) = x, min(x,y) = y. Thus, x + y.
When x = y, max(x,y) = x or y, min(x,y) = x or y. Thus, 2x or 2y or x + y.
When x < y, max(x,y) = y, min(x,y) = x. Thus, x + y.
Is this answer correct? It seems clearer for me.
Thank you in advance.
Comment: The three ways you report are equally correct. It is a matter of taste. Personally, I would write only: "wlog $x\ge y$, then $\max(x,y)+\min(x,y)=x+y$".
Comment: If $x=y$ then the max equals the min so the result is true. If $x\ne y$ then one of them is the max and the other is the min so max+min is $x+y$.
Comment: They are the same.  Your three way approach works, but the $x=y$ case  can be incorporated into both of the others: when $x \ge  y, \max(x,y) = x, \min(x,y) = y$, thus $x + y$; and when $x \le  y, \max(x,y) = y, \min(x,y) = x$, thus $y + x$.  It does not matter that when $x=y$ you have $\max(x,y) = x =y$ as you can use whichever is more helpful
Answer: Your solution is correct but i suggest to take different case for equity, because this may be confusing.
Actually the solution present in the book and your solution are almost similar. But if you ignore equality in first case and prove the statement, then i believe this is better because discussing "equality" and "greater than" at a time is confusing.
And your 3rd proof is also correct. Just write second case simply as
If $x=y$, then $max\{ x,y \} + min\{x,y\}=x+y$ as desired.
Writing 2x and 2y is unnecessary because you have to prove simply x+y.
Btw all three are correct just need little bit modification according to me.


Averaging specific range of data with loop in excel vba

Question: I have a temperature data taken in every second (1Hz).

I want to reduce this data to minutes combined with averaging every 60 seconds of data. Which will be look like this.

I have tried moving average and other things but it didn't work. Is there any VBA code that i can approach my goal or any spesific function.
My time data range is [A3] - [A88739] and data range is [B3] to [B99739]
I will be waiting for your answers.
Thank you!
Answer: I think easier way would be using a helper column.
This will work only if your time data is always like the one you've posted and if the last 6 chars are .XXXXX where X can be letter or numbers, but leading dot is critical

My formula in column C is =VALUE(SUBSTITUTE(LEFT(A3;LEN(A3)-6);".";"/"))
Then with Pivot Table you can group your data by day,hour and minute, and get the average.
Setup of My Pivot Table:

Field Helper into rows section, and grouped by days, hours and minutes
Field Temp into values section, and choose average instead of sum up
Comment: Thank you so much. I have tried the pivot table but couldn't get the filters as hours,minutes and days. Now it works perfectly i have managed to filter those values just as i want!


What does Spacy use to create vector representations?

Question: What is Spacy's built in method of creating vector representations?
I performed NLP on my corpus, and then used .similarity (cosine similarity) to map out documents that were "similar". However, I am unsure what method spacy uses to create vector representations. To my knowledge, I am thinking that it is probably word2vec skip-gram with negative sampling, however, I would like to be sure!
Comment: https://explosion.ai/blog/how-spacy-works
Answer: Spacy's default English model uses GloVe word embeddings to compute the similarity between two words. You can find more information in the SpaCy documentation.
Comment: Is this still true for the `en_core_web_md` and `en_core_web_lg` models?  Second link above forwards to https://spacy.io/usage/linguistic-features#vectors-similarity which doesn't mention the specific embedding algorithm.
Answer: For versions 3.4.0 and higher of SpaCy's English models (en_core_web_md and en_core_web_lg), the default word vectors are floret vectors pretrained on multiple datasets (Wikipedia, OpenSubtitles, WMT Newscrawl, OSCAR 21.09). The repository with the training details is: https://github.com/explosion/spacy-vectors-builder
Earlier versions of the English model vectors were GloVe vectors trained on the CommonCrawl dataset. In general (e.g. for other languages/versions), this information is listed in the model release notes in the spacy-models repo.


dynamically loaded div content using ajax has further links to different files. How to load the content of these links in the same div

Question: Problem statement:
I have a page (main.jsp) with a header, left panel and content divs. When I click on any link in the left panel I use a javascript ajax call to load the content in the  div. So far so good. Now this newly loaded content is actually page one of three of an input form. So this form1 has a submit button that posts data to a servlet which in turn forwards a jsp as a view. This view is nothing but form2 of three.
Now I want this form2 to also load in the same div. As of now when i click on next the form2 opens a new page rather than opening in the parent page's  div.
I dont want to use frames. How do I achieve this? is there a way to call the ajax function in main.jsp from form1,2,3 etc ?
Thanks
Answer: You can use jquery load function
<code>$("#your_content_div_id").load("external_file.jsp");
</code>
Comment: Hi Miqdad, you are loading a static jsp page. form1 is a different page altogether, it does not have access to the div on the main page


Orthogonal basis but not unitary matrix inverse?

Question: For an orthgonal matrix, which has orthogonal+normalized sets of basis, it is said that $A^T$=$A^-1$. But what about matrix with orthogonal but not normalized set of basis? Does it have some kind of characteristics? Thinking of constants that will pop out after normalization, would it be right to think that inverse of the matrix will be same as transpose for matrix with orthogonal but not normalized basis too? Since $B=cA=>cA^T=cA^-1?$ like we could choose any column or row to multiply c back into matrix that will eventually make $B^T=B^-1$
Comment: If the columns of $A$ are orthogonal, but not normalized, what are the entries of $A^TA$? Try the two dimensional case first.
Answer: If the columns of $\ A\ $ are orthogonal, then
$$
A^TA=\text{diag}\big(a_1^Ta_ 1,a_2^Ta_2,\dots,a_n^Ta_n\big)
$$
where $\ a_i\ $ is its $\ i^\text{th}\ $ column.  If these are all non-zero, then
\begin{align}
\text{diag}\left(\frac{1}{a_1^Ta_ 1},\frac{1}{a_2^Ta_ 2},\right.&\left.\dots,\frac{1}{a_1^Ta_ 1}\right)A^TA=I_{n\times n}\\
&=A^T\text{diag}\left(\frac{1}{a_1^Ta_ 1},\frac{1}{a_2^Ta_ 2},\dots,\frac{1}{a_1^Ta_ 1}\right)
\end{align}
What, therefore, are the inverses of $\ A\ $ and $\ A^T\ $?  Do either of them necessarily have orthogonal columns or orthogonal rows?


Interpretation of non-significant results as "trends"

Question: Recently, two different co-workers have used a kind of argument about differences between conditions that seems incorrect to me. Both of these co-workers use statistics, but they are not statisticians. I am a novice in statistics.
In both cases, I argued that, because there was no significant difference between two conditions in an experiment, it was incorrect to make a general claim about these groups with regard to the manipulation. Note that "making a general claim" means something like writing: "Group A used X more often than group B".
My co-workers retorted with: "even though there is no significant difference, the trend is still there" and "even though there is no significant difference, there is still a difference". To me, both of these sound like an equivocation, i.e., they changed the meaning of "difference" from: "a difference that is likely to be the result of something other than chance" (i.e., statistical significance), to "any non-zero difference in measurement between groups".
Was the response of my co-workers correct? I did not take it up with them because they outrank me.
Comment: I found these articles helpful [Still Not Significant](https://mchankins.wordpress.com/2013/04/21/still-not-significant-2/)  and [Marginally Signficant](https://mchankins.wordpress.com/2013/11/10/marginally-significant/)
Answer: This is a great question; the answer depends a lot on context.
In general I would say you are right: making an unqualified general claim like "group A used X more often than group B" is misleading. It would be better to say something like

in our experiment group A used X more often than group B, but we're very uncertain how this will play out in the general population

or

although group A used X 13% more often than group B in our experiment, our estimate of the difference in the general population is not clear: the plausible values range from group A using X 5% less often than group B to group A using X 21% more often than group B

or

group A used X 13% more often than group B, but the difference was not statistically significant (95% CI -5% to 21%; p=0.75)

On the other hand: your co-workers are right that in this particular experiment, group A used X more often than group B. However, people rarely care about the participants in a particular experiment; they want to know how your results will generalize to a larger population, and in this case the general answer is that you can't say with confidence whether a randomly selected group A will use X more or less often than a randomly selected group B.
If you needed to make a choice today about whether to use treatment A or treatment B to increase the usage of X, in the absence of any other information or differences in costs etc., then choosing A would be your best bet. But if you wanted be comfortable that you were probably making the right choice, you would need more information.
Note that you should not say "there is no difference between group A and group B in their usage of X", or "group A and group B use X the same amount". This is true neither of the participants in your experiment (where A used X 13% more) nor in the general population. In almost all real-world contexts, you know that there must really be some effect (no matter how slight) of A vs. B; you just don't know which direction it goes.
Finally, saying just

The difference between group A and B was not statistically significant (p=0.75)

is technically correct, but badly incomplete; without the estimate (13%) and the confidence intervals (-5% to 21%), your audience has no way of knowing whether how large or small the effect might be; contrary to what some people think, knowing that the $p$-value is large is not the same as knowing that the effect is small.
Comment: +1 I think many people fail to realize that in the absence of statistical evidence, the observed differences may very well be the opposite of what's going on with the population!
Comment: Beautiful response, Ben!  I wonder if your second example statement could be modified for clarity to reflect the gist of the first example statement:  "although group A used X 13% more often than group B IN OUR EXPERIMENT,   *the difference IN USAGE OF X BETWEEN GROUPS IN THE GENERAL POPULATION was not clear*: the plausible range OF THAT DIFFERENCE went from A using X 5% *less* often than group B to A using X 21% more often than group B."
Comment: thanks, partially incorporated (trying to balance brevity/clarity and accuracy ...)
Comment: @Dave: even if the presence of "statistical evidence" (statistically significant p-value?), "the observed differences may very well be the opposite of what's going on with the population"
Comment: @boscovich Sure, I was talking in absolutes when we're doing statistics, but I think of it as an insignificant p-value meaning that you really haven't a clue what's happening with the population. At least with a significant p-value you have reached some established threshold of evidence to suggest that you know something. But definitely it's possible to get a significant p-value when it's misidentified the direction. That error should happen from time to time.
Comment: Thanks for the great response. I agree that the discrepancy between the actual participants and the population is what led to the confusion.
Answer: That's a tough question!
First things first, any threshold you may choose to determine statistical significance is arbitrary. The fact that most people use a $5\%$ $p$-value does not make it more correct than any other. So, in some sense, you should think of statistical significance as a "spectrum" rather than a black-or-white subject.
Let's assume we have a null hypothesis $H_0$ (for example, groups $A$ and $B$ show the same mean for variable $X$, or the population mean for variable $Y$ is below 5). You can think of the null hypothesis as the "no trend" hypothesis. We gather some data to check whether we can disprove $H_0$ (the null hypothesis is never "proved true"). With our sample, we make some statistics and eventually get a $p$-value. Put shortly, the $p$-value is the probability that pure chance would produce results equally (or more) extreme than those we got,  assuming of course $H_0$ to be true (i.e., no trend).
If we get a "low" $p$-value, we say that chance rarely produces results as those, therefore we reject $H_0$ (there's statistically significant evidence that $H_0$ could be false). If we get a "high" $p$-value, then the results are more likely to be a result of luck, rather than actual trend. We don't say $H_0$ is true, but rather, that further studying should take place in order to reject it.
WARNING: A $p$-value of $23\%$ does not mean that there is a $23\%$ chance of there not being any trend, but rather, that chance generates results as those $23\%$ of the time, which sounds similar, but is a completely different thing. For example, if I claim something ridiculous, like "I can predict results of rolling dice an hour before they take place," we make an experiment to check the null hypothesis $H_0:=$"I cannot do such thing" and get a $0.5\%$ $p-$value, you would still have good reason not to believe me, despite the statistical significance.
So, with these ideas in mind, let's go back to your main question. Let's say we want to check if increasing the dose of drug $X$ has an effect on the likelihood of patients that survive a certain disease. We perform an experiment, fit a logistic regression model (taking into account many other variables) and check for significance on the coefficient associated with the "dose" variable (calling that coefficient $\beta$, we'd test a null hypothesis $H_0:$ $\beta=0$ or maybe, $\beta \leq 0$. In English, "the drug has no effect" or "the drug has either no or negative effect."
The results of the experiment throw a positive beta, but the test $\beta=0$ stays at 0.79. Can we say there is a trend? Well, that would really diminish the meaning of "trend". If we accept that kind of thing, basically half of all experiments we make would show "trends," even when testing for the most ridiculous things.
So, in conclusion, I think it is dishonest to claim that our drug makes any difference. What we should say, instead, is that our drug should not be put into production unless further testing is made. Indeed, my say would be that we should still be careful about the claims we make even when statistical significance is reached. Would you take that drug if chance had a $4\%$ of generating those results? This is why research replication and peer-reviewing is critical.
I hope this too-wordy explanation helps you sort your ideas. The summary is that you are absolutely right! We shouldn't fill our reports, whether it's for research, business, or whatever, with wild claims supported by little evidence. If you really think there is a trend, but you didn't reach statistical significance, then repeat the experiment with more data!
Comment: +1 for pointing out that *any* significance threshold is arbitrary (and by implication it is not possible to infer absolute claims about the general population from the results in a sample -- all you get are better probabilities).
Answer: Significant effect just means that you measured an unlikely anomaly (unlikely if the null hypothesis, absence of effect, would be true). And as a consequence it must be doubted with high probability (although this probability is not equal to the p-value and also depends on prior believes).
Depending on the quality of the experiment you could measure the same effect size, but it might not be an anomaly (not an unlikely result if the null hypothesis would be true).
When you observe an effect but it is not significant then indeed it (the effect) can still be there, but it is only not significant (the measurements do not indicate that the null hypothesis should be doubted/rejected with high probability). It means that you should improve your experiment, gather more data, to be more sure.
So instead of the dichotomy effect versus no-effect you should go for the following four categories:

Image from https://en.wikipedia.org/wiki/Equivalence_test explaining the two one sided t-tests procedure (TOST)
You seem to be in category D, the test is inconclusive. Your coworkers might be wrong to say that there is an effect. However, it is equally wrong to say that there is no effect!
Comment: "Significant effect just means that you measured the null hypothesis (absence of effect) must be doubted with high probability." I strongly disagree with this statement. What if I told you I can predict the result of any coin flip, we make an experiment, and out of pure luck we get a 1% $p$-value? Would you say there is a high probability of the null hypothesis being false?
Comment: @David, I completely agree with you that the p-value is more precisely a measure for 'the probability that we make an error *conditional* that the null hypothesis is true' (or the probability to see such extreme results), and it does not express directly 'the probabilty that the null hypothesis is wrong'. However, I feel that the p-value is not meant to be to be used in this 'official' sense. The p-value is used to express doubt in the null hypothesis, to express that the results indicate an *anomaly* and anomalies should make us doubt the null....
Comment: ....in your case, when you show to challenge the null effect (challenge the idea that one can not predict the coins) by providing a rare case (just like the tea tasting lady) then we should indeed have doubt in the null hypothesis. In practice we would need to set an appropriate p-value for this (since indeed one might challenge the null by mere chance), and I would not use the 1% level. The high probability to doubt the null should not be equated, one-to-one, with the p-value (since that probability is more a Bayesian concept).
Comment: I have adapted the text to take away this misinterpretation.
Answer: There is not enough information provided to establish the exact meaning of the word "trend." For example, two normal random variates were generated and seem to overlap as below.

Not knowing any better we do a two tailed t-test to see how they differ and get p = 0.495, not significant. Next, we examine if there is any trend or structure for the difference between them by using a pair-wise t-test and get p = 0.
This is because we didn't ask how the data were generated. Sample
A consisted of 100 realizations of a random standard normal distribution. In this case, the pair-wise correlation between Sample A and Sample B is 1, and for each pair Sample B = Sample A + 0.1. That is, if the samples are not independent, and are correlated, we have to account for that in choosing our statistical testing.
Thus, I would ask what "trend" means by asking "What do you mean by trend?" In general, a "trend" can be very predictive, or not at all predictive depending on the circumstances. Moreover, we need to know what "two different conditions in an experiment" means. For example, these may or may not be random variates. They might for example be two different fit functions for a time series of blood plasma concentrations and we might be comparing two different methods of analyzing a single dataset. A very common mistake would be to look at the correlation between each model and the data, then compare the correlation coefficients as if they were uncorrelated. Comparison of correlated results yields a tendency, but without doing an analysis of correlated correlation coefficinets, which many people have never heard of, we would not be able to test properly for its significance.
In summary, there is not enough information provided about the experiment to render an opinion.
Answer: It sounds like they're arguing p-value vs. the definition of "Trend".
If you plot the data out on a run chart, you may see a trend... a run of plot points that show a trend going up or down over time.
But, when you do the statistics on it.. the p-value suggests it's not significant.
For the p-value to show little significance, but for them to see a trend / run in the series of data ... that would have to be a very slight trend.
So, if that was the case, I would fall back on the p-value.. IE: ok, yes, there's a trend / run in the data.. but it's so slight and insignificant that the statistics suggest it's not worth pursuing further analysis of.
An insignificant trend is something that may be attributable to some kind of bias in the research.. maybe something very minor.. something that may just be a one time occurence in the experiment that happened to create a slight trend.
If I was the manager of the group, I would tell them to stop wasting time and money digging into insignificant trends, and to look for more significant ones.
Answer: It sounds like in this case they have little justification for their claim and are just abusing statistics to reach the conclusion they already had. But there are times when it's ok to not be so strict with p-val cutoffs. This (how to use statistical significance and pval cutoffs) is a debate that has been raging since Fisher, Neyman, and Pearson first laid the foundations of statistical testing.
Let's say you are building a model and you are deciding what variables in include.  You gather a little bit of data to do some preliminary investigation into potential variables.  Now there's this one variable that the business team really is interested in, but your preliminary investigation shows that the variable is not statistically significant.  However, the 'direction' of the variable comports to what the business team expected, and although it didn't meet the threshold for significance, it was close. Perhaps it was suspected to have positive correlation to the outcome and you got a beta coefficient that was positive but the pval was just a bit above the .05 cutoff.
In that case, you might go ahead and include it.  It's sort of an informal bayesian statistics -- there was a strong prior belief that it is a useful variable and the initial investigation into it showed some evidence in that direction (but not statistically significant evidence!) so you give it the benefit of the doubt and keep it in the model.  Perhaps with more data it will be more evident what relationship it has with the outcome of interest.
Another example might be where you are building a new model and you look at the variables that were used in the previous model -- you might continue to include a marginal variable (one that is on the cusp of significance) to maintain some continuity from model to model.
Basically, depending on what you are doing there are reasons to be more and less strict about these sorts of things.
On the other hand, it's also important to keep in mind that statistical significance does not have to imply a practical significance!  Remember that at the heart of all this is sample size.  Collect enough data and the standard error of the estimate will shrink to 0. This will make any sort of difference, no matter how small, 'statistically significant' even if that difference might not amount to anything in the real world.  For example, suppose the probability of a particular coin landing on heads was .500000000000001. This means that theoretically you could design an experiment which concludes that the coin is not fair, but for all intents and purposes the coin could be treated as a fair coin.


How can i add multiple instances of newsletter subscriptions?

Question: I want to display newsletter subscribe in different pages, in different ways. Hence once I have set newsletter : subscribe to home page, it does not apply to other page by default.
How can I can assign it to different pages in different positions?
Answer: Each block can be configured in different ways. You can by default give different paths to show or not show your block. Go to /admin/structure/blocks and click on "configure".
If you need more advanced settings, then have a look at the Context module. This allows you to define all kind of rules and conditions to show a block. Very powerfull.
Comment: Thanks for reply but I am wordering that If I can find some thing like http://stackoverflow.com/questions/2872997/how-can-i-create-multiple-different-blocks-in-one-module-in-drupal-6. for drupal 7 It would be helpful for me but i dont get something like this


Journaled filesystems and power failure

Question: I heard that even a journaled filesystems such as EXT3/EXT4 might corrupted during power failure, e.g. from wikipedia [1]:
In the event of a system crash or power failure,
such file systems are quicker to bring back online and
less likely to become corrupted.

Can anyone provide more detail by giving examples such that when

corruption can occur
corruption is avoided by journaled filesystems

[1] http://en.wikipedia.org/wiki/Journaling_file_system
Comment: When the data is not ideally syncing to disk due to drive cache, raid cache, os cache, depends on how many you have enabled, and how your server software is doing this, you might eventually lost the complete file system, have corrupted, or empty files after a power loss.
Comment: @AndrewSmith, the journal handles all of these properly, with the obvious exception of drives that lie to the OS and claim they have flushed data to disk when they have not.
Comment: @psusi OS can lie, drive can lie and RAID as well. The OS when you enable extra buffering (windows) or disable sync (linux), RAID when you dont have battery and enable write cashing.
Comment: @AndrewSmith, you can have the drive write cache enabled without it lieing to the OS.  It is allowed to cache writes where it doesn't matter, then the journal flushes the cache when needed.  It is the flushing of the cache that the drive must not lie to the OS about.  If by "disable sync" you mean using `eatmydata`, that only lies to the application; the journal still keeps the fs clean.
Answer: Corruption can also occur on most modern disks due to in-disk re-ordering.
Modern disks typically do re-ordering of requests that are used to speed up performance (by re-ordering writes to make the entire list of requests less seeky), this is called Tagged Command Queueing.
It is possible the write to the journal on the disk is delayed because its more efficient from the head position currently to write in a different order to the one the operating system requested as the actual order, meaning blocks can be committed before the journal is.
The way to resolve this is to make the operating system explicitly wait for the journal to have been committed before committing any more writes. This is known as a barrier. Most filesystems do not use this by default and would explicitly need enabling with a mount option.
mount -o barrier=1 /dev/sda /mntpnt

The big downside to barriers is they have a tendency to slow I/O down, sometimes dramatically (around 30%) which is why they arent enabled by default. In addition to this, things become doubleplusungood when you start to add logical layering on top of standard disks like LVM or Raid. LVM (relatively recently) added barrier support for most LV configurations and mdadm seems to have had it for a little while.
Comment: @Gaia Defragmentation occurs when contiguous data at the file layer is non-contiguous on the block layer. The order of your data on disk and the order that you put data to the disk are two different things.
Comment: On ext[34], barriers are only needed if you switch to data=writeback mode.  In the default data=ordered mode, the journal writes are completed before the regular writes are issued.  The drive never sees the latter until after it has finished the former, so it has no chance to reorder them.  Also barriers are enabled by default on ext4.
Comment: Most, yes.  A batch of journal writes may be sent to the disk together, but they must all finish before the fs then turns and issues the batch of real writes.  You can think of data=ordered mode as "fsync the journal before the real writes".
Comment: Is it normal to use the `barrier=1` option?
Comment: Normal for me. EXT4 turns it on too. EXT3 does not.
Comment: "Tagged Command Queueing" sounds a lot like defragmentation.
Comment: But the checksum in ext4 makes the late barrier somewhat redundant, and bariers have no effect on older versions of LVM (around 2.6.33)
Comment: @psusi I dont think that is correct. Most requests to disks are done in batches, and a stream of commands are sent to the disk controller at once, rather than command/wait, command/wait, command/wait (this is the point of fsync()). Else disk latencies would be too slow. And yes, barriers are enabled by default on ext4.
Answer: Most journaled file systems (ext3/4, ntfs) only transactionally protect the meta data. If a power outage occurs, user data could be rendered inconsistent but the meta data is fine.
Zfs and I think xfs protect both meta data and user data using transactions and logs.
Comment: Note: No file system can guarantee user data integrity. The application itself has to do this. ZFS and XFS do ensure atomic user data writes (whatever is requested to be written is, or the previous data will be returned, nothing in between); however if the app uses two writes, it's possible those are split before and after power failure, creating user data corruption even though the file is "consistent".
Comment: No: XFS is a meta-data journalling filesystem, ext4 effectively has modes of operation giving better data guarantees than simlpy meta-data journalling. Running ZFS on  Linux machine is not really the greatest idea ever - at best, the performance sucks. There are other full journalling solutions for Linux - NILFS2 and BTRFS. If you want really good data integrity then BTRFS + BBU controller + RAID is, IMHO, the route to go.
Answer: Barrier is a way to avoid corruption on power outages, but this safety feature comes with a performance hit. Best of both worlds (performance/barrier=off WITH pratically no risk of corruption) costs a little bit more: use devices with non-volatile, battery-backed write caches.
Comment: Barries prevent meta-data corruption, not user data corruption. And the Ext file systems have no way of detecting user data corruption.

Journaled filesystems and power failure


Unable to understand this lemma

Question: The lemma is from the book Discrete Mathematics for computer scientists and mathematicians by Joe L Mott, Abraham Kendal, and Theodore P Baker

Suppose $x$ and $m$ are positive integers and $r$ is the smallest positive integer for which there exist integers $c$ and $d$ such that $r = cx + dm$, then $r = gcd(x, m)$

This lemma doesn't make sense to me. Clearly, if all $x, m, c, d$ are integers then $r$ has to be greater than them, then how can $r$ be their gcd? Even if $c$ and $d$ are negative, what even is the point of doing so? The whole thing seems really bizzare. The proof is even more bizarre though

Proof: Suppose $x = pr + q$, where $0 \le q < r$ then, $q = x - pr = x - p(cx + dm) = (1-pc)x + (-pd)m$

Since $r$ is the smallest positive integer of this form, and $0 \le q < r$, it must be that $q = 0$ which is to say r divides x

I don't understand how they managed to derive $q = 0$ from this. If anyone is able to explain it more clearly, I would really appreciate it.
Comment: Not more clearly, just more words: They showed that $q$ is the sum of an integer multiple of $x$ (namely, $1-pc$ times $x$) and an integer multiple of $m$ (namely, $-pd$ times $m$). If $q$ **were** a positive integer, then it would be an element of the set of positive integers writable as sum of an integer multiple of $x$ and an integer multiple of $m$. By definition, $r$ is the smallest element of that set. Hence we'd need to have $q\ge r$, but certainly $q<r$. - We conclude that $q$ is not a positive integer. Given its possible range, $0\le q<r$, the only remaining possibility is that $q=0$.
Comment: It shows that $q$ is also an integer of the form $cx+dm$, but it is less than $r$.  The only choice left is for $q=0$.
Comment: Since $\,c,d\,$ can be negative integers, $r$ does not need to be greater than $x$ and $m$. For example, if $x=8$ and $m=9$, then there exist $c=8$ and $d=-7$ such that $r=1=cx+dm\,.$
Comment: I guess that [Euclid's algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm) is the point. A good point at that.
Answer: About the lemma: if $c$ and $d$ can be negative, then the lemma is correct.
About the proof: since $q=(1-pc)x+(-pd)m$, $q$ verifies the kind of equation that $r$ verifies: a linear combination of $x$ and $m$ with integer coefficients. But we have supposed that $r$ is the smallest positive integer that verifies this. As $0\le q \lt r$, this implies $q=0$.
Answer: In terms of understanding what the lemma is trying to achieve, think about what the values of $cx + dm$ are - they're linear combinations of $x$ and $m$. If $x$ and $m$ were, say, two denominations of poker chips, then $cx + dm$ represents the values we can generate from having $c$ of the first chip and $d$ of the second.
If $c$ and $d$ were strictly non-negative, then we would be looking at a coin problem (also known as a McNugget problem). However, the lemma does not put this restriction on $c$ and $d$, so in this case it's possible to owe a certain number of each denomination, in order to expand the range of possible values.
So, for example, if $x = 6$ and $m = 9$, then we can achieve the following values (among others):

$c$
$d$
$cx + dm$

$1$
$1$
$15$

$0$
$3$
$27$

$1$
$-2$
$3$

$-3$
$-2$
$-30$

The lemma then states that the smallest positive such value you can achieve is the GCD of $x$ and $m$. So with my example, you can find a linear combination to make $cx + dm = \gcd(6, 9) = 3$ (which I did in the table), but you cannot make $cx + dm = 1$ or $cx + dm = 2$.
The proof comes by applying the division algorithm - we know that for any positive integers $a$ and $b$ we can always write $a = lb + k$ for some non-negative integer $l$ and $k \in \{0, 1, \ldots, b - 1\}$ (i.e. "$a$ divided by $b$ gives $l$, with remainder $k$").
Applying that to the division of $x$ by $r$ gives $x = pr + q$. We rearrange that to get $q = x - pr$, then substitute $r = cx + dm$ to get $q = x - p(cx + dm) = (1 - pc)x + (-pd)m$. This is also a linear combination of $x$ and $m$, but we have assumed that $r$ is the smallest positive such value, and we have constructed $q$ to be in the set $\{0, 1, \ldots, r - 1\}$, and removing the positive values from that set leaves $q = 0$ as the only possibility.
But then that means $x = pr + q = pr$ thus demonstrating that $r$ divides $x$. Similarly you can prove that $r$ divides $m$, making $r$ a common divisor of $x$ and $m$, and the final step is proving that $r$ must be the greatest such common divisor, which you do by taking $c$ to be any common divisor and showing that $c$ must divide $r$.
What's the point? This is an extremely important result known as Bézout's identity, which underpins a huge amount of number theory. In particular, it forms part of the proof of the Chinese remainder theorem, which is fundamental to things like the RSA encryption algorithm.

Unable to understand this lemma


Directional Derivatives With Respect to Negative Vectors

Question: I understand this is probably a silly question but I'm with it struggling nonetheless. Consider the directional derivative of $f(x)=x^2$ at $x=1$ with respect to $u=-1$. I can see that this is equal to $-2$ but I struggle to relate this result with my notion of derivatives as slopes of tangent lines. Could someone explain, in elementary terms, how one should picture this result?
Answer: If you have the direction $u = -1$, you have to look to the left, usually, you look to the right. So you could just flip your function...
And if you sit at $x = 1$, and go to the left, the function goes downwards, so the slope is negative.
Comment: So the slope at the same point is different? It doesn't make sense. The function go downwards but shouldn't the quotient also become negative so they cancel out?


$|f(x)| > A$ for all $x \in E$.

Question: If $f \in L_\infty(X, \mathcal{X}, \mu)$, then $|f(x)| \leq ||f||_\infty$ for almost all $x$. Moreover, if $A < ||f||_\infty$, then there exists a set $E \in \mathcal{X}$ with $\mu(E) > 0$ such that $|f(x)| > A$ for all $x \in E$.
I'm studying for my finals and working some problems in my book.
I stumbled upon this one and I'm having difficulty approaching it.
I was trying to look for a contradiction, but I seem to be going in circles.
Answer: I'll take the definition of $\Vert f\Vert_\infty=\Vert f\Vert$ to be
$$
\Vert f\Vert= \inf\bigl\{ \alpha>0\mid \mu\bigl( \{ x\ \bigl|\ |f(x)|>\alpha\}\bigr)=0\bigr\}.
$$
Note that
$$\tag{1}
   \beta>\Vert f\Vert \quad\Longrightarrow\quad\mu\bigl(\{ x \mid   |f(x)|>\beta\}\bigr)=0.
$$

To show $|f(x)|\le\Vert f\Vert$ for almost all $x$:
Let $M=\bigl\{ x \mid   |f(x)|>\Vert f\Vert\bigr\}$.
For each positive integer $n$, set $M_n=\bigl\{ x \mid   |f(x)|>\Vert f\Vert+{1\over n}\bigr\}$. Then by $(1)$ we have $\mu(M_n)=0$ for all $n$. Note that
$M=\bigcup_{n=1}^\infty M_n$. Now note that, since a countable union of sets of measure zero has measure zero:
$$\mu\bigl(\{x\mid |f(x)|> \Vert f\Vert \bigr)
=\mu\Bigl(\bigcup_{n=1}^\infty M_n\Bigr) =0.
$$
Consequently, $|f(x)|\le \Vert f\Vert $ almost everywhere.

To show that
if $A < ||f||_\infty$, then there exists a set $E \in \mathcal{X}$ with $\mu(E) > 0$ such that $|f(x)| > A$ for all $x \in E$:
Suppose that $A<\Vert f\Vert$. By the definition of $\Vert f\Vert$ as the infimum of all $\alpha>0$ such that $\mu\bigl(\{ x \mid   |f(x)|>\alpha\}\bigr)=0$, it follows that
$\mu\bigl(\{ x \mid   |f(x)|>A\}\bigr)\ne0$. So simply take $E=\{ x\mid |f(x)|>A\}$.
Answer: By definition, for all sets $S$ with $\mu(S) > 0$ you have $|f(s)| \leq \|f\|_\infty$ for almost all $s \in S$.
Assume there is a constant $K$ such that $K < \|f\|_\infty$ and there is a set $S$ such that $\mu(S) = 0$ and $|f(s)| \leq K$ on all of $S$. Then this is a contradiction to the definition of $\|f\|_\infty = \inf \{ K > 0 \mid |f(x)| \leq K \text{ for all } x \text{ except on a set of measure } 0\}$.
Comment: The first line's part of what katari wants to prove, so I suspect the definition of the $\sup$-norm in use is $\|f\|_\infty = \inf{\{M \gt 0\,:\,\mu(\{|f| \gt M\} = 0\}}$, so you should maybe add a word more.

$|f(x)| > A$ for all $x \in E$.


mmap() keeps returning MAP_FAILED whe trying to read or write to a PIO address on cyclone V FPGA

Question: I am trying to write an integer (1114129) from my HPS on Cyclone V Altera FPGA from a PUTTY window to a 32bit PIO on the FPGA side via lightweight axis interface. I am using mmap() and cannot get it to work, have been trying for months.
I have set up the hardware side correctly because I was able to read from another 32bit PIO at the address 0xff205000, this works fine but I can't read or write to the second PIO. I have tried multiple different addresses as well and it doesn't seem to make a difference.
Here is the error I get, which is because of mmap returns MAP_FAILED
open /dev/mem successfully !
npheap_alloc(): Invalid argument
#

As you can see above the file is opened correctly and then it fails on the mmap call.
Below is the c code im using. There are no compiling issues.
If anyone could help or even point me in the right direction i would be really appreciative its driving me insane.
#define MAPPED_SIZE 4

#define DDR_RAM_PHYS 0xff205010

int main(void)

{

        int _fdmem;
        void *map;

        const char memDevice[] = "/dev/mem";
        _fdmem = open( memDevice, O_RDWR | O_SYNC );

        if (_fdmem < 0){
                printf("Failed to open the /dev/mem !\n");
                return 0;
        }
        else{
                printf("open /dev/mem successfully !\n");
        }

        /* mmap() the opened /dev/mem */
        map = mmap(0, MAPPED_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, _fdmem, DDR_RAM_PHYS);

          if (map == MAP_FAILED) { perror("npheap_alloc()"); exit(1); }

        *(unsigned int*)(map+(0xff205010)) = (unsigned short)1114129;
        //int *q = (int *)map;
        //*q = 1114129;

        /* unmap the area & error checking */
        if (munmap(map,MAPPED_SIZE)==-1){
               perror("Error un-mmapping the file");
        }

        /* close the character device */
        close(_fdmem);
}

Answer: 0xff205010 is not a valid mmap offset: it's not page-aligned. Also, adding 0xff205010 to map would not be valid even if it were; map would already refer to that physical address.
Instead, You need to mmap the correct page (0xff205010 & -PAGESIZE) then use (0xff205010 % PAGESIZE) as the offset into the mapping.
Comment: Thank you for your quick response, how do I find out the correct page? And where you say I need to mmap the correct page would that mean changing the DDR_RAM_PHYS from current value to a new defined value? Or do I add the '&' sign after like this map = mmap(0, MAPPED_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, _fdmem, DDR_RAM_PHYS & -pagesize);?
Do you know of any good sources of information I can read regarding this topic?
Comment: @Jacko123: Exactly what you wrote there in the comment. The `&` masks off bits, and since `PAGESIZE` is a power of 2 (typically `0x1000`), `-PAGESIZE` is a mask to remove all the lower bits - assuming unsigned 64-bit type and 4k pages, `-PAGESIZE` is `0xfffffffffffff000`. If `PAGESIZE` is not constant for the arch, you get it via `sysconf(_SC_PAGESIZE)`.


Do minimal hyperbolic surfaces exist? What do they look like?

Question: I understand that it is impossible to embed* the entire hyperbolic plane in $\mathbb{R}^3$. But, can one create a embedding of part of the hyperbolic plane such that the resulting surface is also minimal?
Basically, do there exist surfaces which have $\kappa_1 + \kappa_2 = 0$, but also $\kappa_1 \kappa_2 = const < 0$? What do they look like?
*"Embed" may not be the correct term here, but I hope the idea is clear.
Comment: This may not answer your question, but maybe this link to Hilbert's theorem will be helpful: https://en.wikipedia.org/wiki/Hilbert%27s_theorem_%28differential_geometry%29. I know nothing about this, except for seeing crocheted "models of the hyperbolic plane" with crinkly edges, but this link and the Nash embedding theorem it links to seem to be related to your question. I had always assumed the "crinkled edges" models of the hyperbolic disk in $\mathbb{R}^3$ were at least distance-preserving.
Comment: @EricTressler - My limited understanding of Hilbert's theorem is that those crocheted models would get ever more dense at the edges, until at some point the surface would no longer be twice differentiable. What I think I'm asking essentially, is if any of those models are also minimal surfaces.
Answer: $\newcommand{\Reals}{\mathbf{R}}$There is no minimal surface of constant negative Gaussian curvature in $\Reals^{3}$, even locally.
Up to scaling, the principal curvatures would satisfy
$$
\kappa_{2} = -\kappa_{1},\qquad
-1 = \kappa_{1} \kappa_{2} = -\kappa_{1}^{2},
$$
so the principal curvatures would be constant: $\kappa_{1} = 1 = -\kappa_{2}$ without loss of generality.
If a surface in $\Reals^{3}$ has constant principal curvatures, the Codazzi equations give $\kappa_{1} - \kappa_{2} = 0$ or $\kappa_{1}\kappa_{2} = 0$. (See, for example, O'Neill, Elementary Differential Geometry, Second revised edition, Theorem 2.6, page 272.) This excludes a minimal surface of constant negative Gaussian curvature.
In case it's of interest, a connected surface in $\Reals^{3}$ having constant principal curvatures is part of a plane, cylinder, or sphere. See, for example, O'Neill, Elementary Differential Geometry, Second revised edition, Exercise 5 on page 280.
Comment: Does that mean minimal surfaces cannot be tiled by regular heptagons?
Comment: Worse: It means there _are_ no minimal regular heptagons in $\Reals^{3}$ (if "heptagon" refers to a hyperbolic polygon).
Comment: When asymptotic lines cut orthogonally, all surfaces of constant negative Gauss curvature surfaces possess zero average curvature lines locally, following  Euler relation Is n't that correct?
Comment: If $M$ has constant negative curvature and the asymptotic lines are orthogonal at some point $p$ (so the mean curvature of $M$ vanishes at $p$), I'd believe there exists a curve through $p$ along which the mean curvature vanishes (merely for reasons of continuity). In that sense, yes. But in any case, the mean curvature of $M$ does not vanish identically in an open neighborhood of $p$, so $M$ is not minimal near $p$.
Answer: Individual saddle points, lines or rings can occur only locally, but it cannot occur for entire surfaces due to scalar curvature requirement:
$$ H=0, \kappa_{2} = -\kappa_{1} =1/a ; \, K= \kappa_{1} \kappa_{2} = -1/a^2 $$
To find where they occur let $$ \kappa_{2} = -\kappa_{1}= \tan \psi/a ; \, \kappa_n = 0 \, @ \psi= \pi/4 $$
The necessary condition is therefore that asymptotic lines cut orthogonally.
For example here, at  $ \phi= 3 \pi/2 $ a slope line ring for Beltrami pseudosphere, \phi=0 for hyper_pseudospheres.
We may say that is locally valid :

Every minimal surface when sufficiently extended can contain  a line of constant $K=-1, $ and,
Every K<0 surface has a line of H =0.  $


density distribution and bar plot from x and y data

Question: I have the following data set in a pandas dataframe:
x = df_data.iloc[:,0].values
y = df_data.iloc[:,1].values

The following data is in x and y, respectively:
x = 30, 31, 32, 33, 34, 35, 36
y = 1000, 2000, 3000, 4000, 3000, 2000, 1000

y represents the counts (how often each x value exists).
I now want to make a bar plot with the density distribution line. I'm open to using seaborn or matplotlib, but couldn't find a way to enter x and y data separately and to obtain the bar plot plus the density plot.
I've tried this:
x = [30,31,32,33,34,35,36]
y = [1000, 2000, 3000, 4000, 3000, 2000, 1000]
##
sns.distplot(x, hist=True, kde=True,
    bins=int(150/150), color='darkblue',
    hist_kws={'edgecolor':'black'},
    kde_kws={'linewidth': 4})
plt.show()

but didn't get what I wanted.
I would like to have something like below (just for my data)

(i got this image from: https://towardsdatascience.com/histograms-and-density-plots-in-python-f6bda88f5ac0)
Answer: First off, note that distplot has been depreciated in Seaborn 0.11. The extended and improved versions are now called histplot (histogram with optional kde ), kdeplot (for just a kde) and displot (creates subplots).
The optional weights= parameter sets weights for each of the x values. discrete=True is needed to have a bar for each x value. The cut parameter of the kde controls how far the curve is drawn outside the data points.
import matplotlib.pyplot as plt
import seaborn as sns

x = [30, 31, 32, 33, 34, 35, 36]
y = [1000, 2000, 3000, 4000, 3000, 2000, 1000]

sns.histplot(x=x, weights=y, discrete=True,
             color='darkblue', edgecolor='black',
             kde=True, kde_kws={'cut': 2}, line_kws={'linewidth': 4})
plt.show()

Note that in case the underlying data is continuous, you'd get a much correcter plot by providing the original data.
To change the color of the kde line, an obvious idea would be to use line_kws={'color': 'red'}, but this doesn't work in the current seaborn version (0.11.1).
However, you can draw a histplot and kdeplot separately. In order to have matching y-axes, the histplot needs stat='density' (the default is 'count').
ax = sns.histplot(x=x, weights=y, discrete=True, alpha=0.5,
                  color='darkblue', edgecolor='black', stat='density')
sns.kdeplot(x=x, weights=y, color='crimson', cut=2, linewidth=4, ax=ax)

Another approach is to change the color of the line afterwards, which works independently of the chosen stat=.
ax = sns.histplot(x=x, weights=y, discrete=True,
             color='darkblue', edgecolor='black',
             kde=True, kde_kws={'cut': 2}, line_kws={'linewidth': 4})
ax.lines[0].set_color('crimson')

Here is an example how a histogram for one dataset can be combined with a kde curve of another dataset:
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import seaborn as sns

x = [30, 31, 32, 33, 34, 35, 36]
y = [1000, 2000, 3000, 4000, 3000, 2000, 1000]
x2 = [20, 21, 22, 23, 24, 25, 26]
y2 = [1000, 2000, 3000, 4000, 3000, 2000, 1000]

ax = sns.histplot(x=x2, weights=y2, discrete=True, alpha=0.5,
                  color='darkblue', edgecolor='black', stat='density')
sns.kdeplot(x=x, weights=y, color='crimson', cut=2, linewidth=4, ax=ax)
ax.xaxis.set_major_locator(MultipleLocator(1))
plt.show()

Comment: great. is there a possibility to now change the color of the blue line to red but keep the color of the histogram as blue?
Comment: Thank you! Last question: if I now wanted to plot this red line, for the data above in a figure without the histogram, but instead add the histogram of another set of data to the figure instead i.e.: histogram for x2 = [20, 21, 22, 23, 24, 25, 26] and y2 = [1000, 2000, 3000, 4000, 3000, 2000, 1000], plus red line for x = [30, 31, 32, 33, 34, 35, 36]
y = [1000, 2000, 3000, 4000, 3000, 2000, 1000]. Is this possible?
Comment: You'll need `histplot` without kde but with `stat='density'` and then a separate `kdeplot`.  Note that without `stat='density'` histograms for both datasets would have quite a different scale.


How to wrap the text in ggplot?

Question: For the last week's TidyTuesday challenge, I know I am a bit late to ask this, I am trying to plot the BigTech companies' stock prices in a facetted graph. Nevertheless, some companies names are longer than others and I would like to wrap the text for these particular company names. Here is what I have achieved so far:
library(tidyverse)
library(showtext)
library(patchwork)
library(janitor)
library(glue)
library(ggtext)
library(gghighlight)
library(lubridate)

font_add_google("Archivo", family = "title")
font_add_google("Nunito", family = "subtitle")
font_add_google("Martel", family = "axis")
font_add_google("Spartan", family = "caption")

font_add('fa-reg', 'fonts/Font Awesome 6 Free-Regular-400.otf')
font_add('fa-brands', 'fonts/Font Awesome 6 Brands-Regular-400.otf')
font_add('fa-solid', 'fonts/Font Awesome 6 Free-Solid-900.otf')

showtext_auto()
dat <- tidytuesdayR::tt_load(2023, week = 6)

big_tech_stock_prices <- dat$big_tech_stock_prices
big_tech_company_name <- dat$big_tech_companies

big_tech_stock_prices <- big_tech_stock_prices %>%
  left_join(big_tech_company_name, by = "stock_symbol") %>%
  mutate(company = case_when(company == "International Business Machines Corporation" ~ "IBM",
                             TRUE ~ company))

plot <- ggplot(big_tech_stock_prices, aes(x = date, y = close, group = company)) +
  geom_line() +
  gghighlight(company %in% c("Apple Inc.", "Adobe Inc.", "Amazon.com, Inc.", "Salesforce, Inc.", "Cisco Systems, Inc.",
                             "Alphabet Inc.", "IBM", "Intel Corporation", "Meta Platforms, Inc.", "Microsoft Corporation",
                             "Netflix, Inc.", "NVIDIA Corporation", "Oracle Corporation", "Tesla, Inc."),
              use_direct_label = FALSE,
              unhighlighted_params = list(linewidth = 0.1, colour = alpha("grey20", 0.3))) +
  geom_area(aes(date, close, colour = stock_symbol, fill = stock_symbol), big_tech_stock_prices, alpha = 0.2, size = 0.5) +
  geom_text(
            aes(x = lubridate::ymd("2014-01-01"), y = 500, label = company, color = company), size = 30) +
  facet_wrap(~company) +
  theme_minimal() +
  labs(title = "Stock Market Values for BigTech Companies (2010-2022)",
       subtitle = "The plot demonstrates the stock market value for 14 BigTech companies. Note that the values
displays the closed prices for each days",
       y = "US Dollar - $",
       x = "") +
  theme(legend.position = "none",
        strip.background = element_blank(),
        strip.text = element_blank(),
        axis.title.y = element_markdown(family = "axis", size = 55, linewidth = 0.2),
        axis.title.x = element_markdown(family = "axis", size = 55, linewidth = 0.2),
        axis.text.y = element_markdown(family = "axis", size = 35),
        axis.text.x = element_markdown(family = "axis", hjust = 0.43, size = 35),
        plot.title = element_markdown(family = "title", size = 95, hjust = 0.5, lineheight = 0.15, linewidth = 0.1),
        plot.subtitle = element_markdown(family = "subtitle", size = 75, hjust = 0.5, lineheight = 0.15, linewidth = 0.1),
        plot.caption = element_markdown(family = "title", size = 45, lineheight = 0.15, linewidth = 0.1, hjust = 0.5),
        plot.background = element_rect(fill = "white", color = "white"))

ggsave("deneme.png", height = 6,  width = 7.5, dpi = 720)

which produced this plot

So, as can be seen from the plot, Cisco Systems and Intel have longer lengths compared to Adobe and Apple and therefore I would like to wrap the text. My question is how can I do that?
Comment: Referred to: https://stackoverflow.com/questions/47446259/wrapping-long-geom-text-labels
Comment: one simple option would be to substitute spaces with \n to create breaks. Otherwise related: https://stackoverflow.com/questions/25106508/ggplot2-is-there-an-easy-way-to-wrap-annotation-text?noredirect=1&lq=1
Comment: Another excellent thread links to some good solutions for very similar problems: https://stackoverflow.com/questions/65956833/ggplot2-how-to-dynamically-wrap-resize-rescale-x-axis-labels-so-they-wont-over
Comment: I tried to replace the spaces with the new lines as suggested in this thread, however, it just did not work out because this time, the problem was that the labels were not shown up for some reason I could not understand.
Comment: No worries, I just found out a solution to solve that by modifying the geom_text function.
Answer: You can use str_wrap (via stringr) to force the width of the text stringr.tidyverse.org/reference/str_wrap.html OR...
You can replace the spaces in the company names with new lines prior to plotting as I've done here:
big_tech_stock_prices$company2 <- gsub(' ', ' \n',big_tech_stock_prices$company)

plot <- ggplot(big_tech_stock_prices, aes(x = date, y = close)) +geom_line(aes(x = date, y = close, color=company)) + gghighlight(company %in% c("Apple Inc.", "Adobe Inc.", "Amazon.com, Inc.", "Salesforce, Inc.", "Cisco Systems, Inc.",  "Alphabet Inc.", "IBM", "Intel Corporation", "Meta Platforms, Inc.", "Microsoft Corporation",  "Netflix, Inc.", "NVIDIA Corporation", "Oracle Corporation", "Tesla, Inc."),   use_direct_label = FALSE,   unhighlighted_params = list(linewidth = 0.2, colour = "gray50" , aes(color=company2))) + geom_area(aes(date, close, colour = stock_symbol, fill = stock_symbol), big_tech_stock_prices, alpha = 0.2, size = 0.5) + geom_text(  aes(x = lubridate::ymd("2014-01-01"), y = 400, label = company2, color = company2), size = 4) +  facet_wrap(~company) + theme_minimal()+ labs(title = "Stock Market Values for BigTech Companies (2010-2022)",    subtitle = "The plot demonstrates the stock market value for 14 BigTech companies. Note that the values
displays the closed prices for each days", y = "US Dollar - $", x = "") + theme(legend.position = "none", strip.background = element_blank(),strip.text = element_blank(), axis.title.y = element_markdown(family = "axis", size = 11, linewidth = 0.2),  axis.title.x = element_markdown(family = "axis", size = 11, linewidth = 0.2), axis.text.y = element_markdown(family = "axis", size = 10),axis.text.x = element_markdown(family = "axis", hjust = 0.43, size = 10),  plot.title = element_markdown(family = "title", size = 12, hjust = 0.5, lineheight = 0.15, linewidth = 0.1),   plot.subtitle = element_markdown(family = "subtitle", size = 11, hjust = 0.5, lineheight = 0.15, linewidth = 0.1),  plot.caption = element_markdown(family = "title", size = 11, lineheight = 0.15, linewidth = 0.1, hjust = 0.5),  plot.background = element_rect(fill = "white", color = "white")) + theme(plot.margin=unit(c(1,1,1,1),"cm"))

Comment: When I add the first code to replace spaces with new lines, the labels that were supposed to be shown into the plot as company names do not exist. I could not understand what the problem would be. PS. I wanted to add the screenshot, but it does not allow me to do so. Can you confirm that problem as I already provided the code I have?
Comment: No worries, I just found out a solution to solve that by modifying the geom_text function.
Comment: I had to change your code a bit to get this to work but the main issue was that if you change the "company" column by adding spaces dataframe, you also need to update your other references to that column in your figure (ex/ gghighlight was still referring to c("Apple Inc") with a space rather than a "\n").  So you either need to give the new column a new name for the geom_text ("company2") or use the new format in gghighlight (ex/ "Apple\nInc") which you can extract with
for_plot <- unique(big_tech_stock_prices$company) and then use  gghighlight(company %in% c(for_plot),...

How to wrap the text in ggplot?